# How OmniRoute Prevents Error Message Leakage and PII Exposure: A Technical Deep‑Dive

> Learn how OmniRoute uses error message sanitization and opt-in PII redaction to prevent sensitive data like stack traces and personal info from reaching clients. Enhance your application security.

- Repository: [Diego Rodrigues de Sa e Souza/OmniRoute](https://github.com/diegosouzapw/OmniRoute)
- Tags: deep-dive
- Published: 2026-08-19

---

**OmniRoute layers error-message sanitization and opt‑in PII redaction to guarantee that stack traces, file paths, credentials, and personal data never reach clients.**

OmniRoute implements a **defense‑in‑depth** strategy to prevent sensitive information from leaking through API responses and SSE streams. According to the diegosouzapw/OmniRoute source code, the framework combines deterministic error sanitization utilities with a feature‑flagged PII masking guardrail. This article examines each layer, the specific functions involved, and how to configure them.

## Error‑Message Sanitization Layer

The first line of defense removes debugging artifacts and credential snippets from any error payload returned to clients.

### Core Sanitization Utilities in `open‑sse/utils/error.ts`

The file [`open‑sse/utils/error.ts`](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/open-sse/utils/error.ts) exports three key functions:

- **`sanitizeErrorMessage`** – Truncates payloads, splits on whitespace, and replaces absolute paths (POSIX or Windows) with `<path>`.
- **`redactSensitiveErrorText`** – Strips data‑URL payloads, bearer/basic tokens, and credential keys including `api_key`, `access_token`, `authorization`, `secret`, and `cookie`.
- **`sanitizeUpstreamDetails`** – Recursively cleans JSON from upstream providers, dropping blocked keys (`stack|trace|path|file|cwd|dir|password|secret|token|key|authorization|cookie`) and limiting depth to `MAX_DEPTH = 4` and arrays to `32` items.

These utilities are **pure and deterministic**, making them safe for concurrent use across all routes.

### Building Safe Error Responses with `buildErrorBody`

The `buildErrorBody` function orchestrates the above utilities into an OpenAI‑compatible error object:

```typescript
import { buildErrorBody } from '@/open-sse/utils/error.ts';

// Inside a route handler
try {
  // operation that may throw
} catch (err) {
  const body = buildErrorBody(
    500,
    err instanceof Error ? err.message : String(err),
    (err as any).upstreamBody, // optional raw provider payload
  );
  return new Response(JSON.stringify(body), {
    status: 500,
    headers: { 'Content-Type': 'application/json' },
  });
}

```

The resulting body always contains a sanitized `message` field and, when applicable, a safe `upstream_details` field.

## PII Masking Guardrail

The second layer prevents **personal‑identifiable information (PII)** from being stored or echoed in requests and responses.

### Opt‑In Protection via Feature Flag

PII redaction is controlled by `PII_REDACTION_ENABLED`, which defaults to `false`. The helper `isFeatureFlagEnabled` (from [[`src/shared/utils/featureFlags.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/shared/utils/featureFlags.ts)](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/src/shared/utils/featureFlags.ts)) reads this value from the database, falls back to environment variables, then to the hard‑coded default. This makes the protection **audit‑friendly and operationally safe to enable**.

### Request Sanitization with `PIIMaskerGuardrail`

The [[`src/lib/guardrails/piiMasker.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/lib/guardrails/piiMasker.ts)](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/src/lib/guardrails/piiMasker.ts) module implements `cloneAndMaskRequestPayload`, which:

1. Deep‑copies the request JSON.
2. Walks string fields: `system`, `messages`, `input`, `prompt`.
3. Applies `sanitizeStringValue` from the configurable `inputSanitizer`.
4. Records detections and replaces the payload only on modification.

Usage in the request pipeline:

```typescript
import { PIIMaskerGuardrail } from '@/src/lib/guardrails/piiMasker.ts';

const piiGuard = new PIIMaskerGuardrail({ enabled: true });

const { payload, modified, detections } = await piiGuard.preCall(requestBody, ctx);
if (modified) {
  // Log detection count, proceed with sanitized payload
}

```

### Response Masking with `maskResponsesOutput`

For provider responses, `maskResponsesOutput` traverses `output_text` and `output[].content[].text`, applying `sanitizePII` and `sanitizePIIResponse` from [[`src/lib/piiSanitizer.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/lib/piiSanitizer.ts)](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/src/lib/piiSanitizer.ts). The guardrail returns a `modified` flag so callers can decide whether to overwrite the original response.

## Upstream Provider Sanitization

When integrating with external LLM providers, OmniRoute guards against **provider‑side error leakage** including authentication tokens and internal IDs.

The `sanitizeUpstreamDetails` function—invoked automatically by `buildErrorBody` when an upstream body is present—prunes blocked keys, enforces depth and array limits, and passes each string through `sanitizeErrorMessage`.

```typescript
import { sanitizeUpstreamDetails } from '@/open-sse/utils/error.ts';

const safeDetails = sanitizeUpstreamDetails(rawProviderError);

```

## Security Guarantees and Design Principles

Together, these layers enforce three critical properties:

- **No stack traces or file paths** in client‑visible errors.
- **No credential material** (tokens, keys, cookies) in any response body.
- **No PII echoing** when the redaction guardrail is enabled.

The sanitization functions are **stateless and side‑effect‑free**, ensuring consistent behavior across HTTP routes, SSE streams, and MCP tool endpoints.

## Summary

- **Error sanitization** in `open‑sse/utils/error.ts` removes debugging artifacts and credentials via `sanitizeErrorMessage`, `redactSensitiveErrorText`, and `sanitizeUpstreamDetails`.
- **PII masking** in [`src/lib/guardrails/piiMasker.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/lib/guardrails/piiMasker.ts) is opt‑in via `PII_REDACTION_ENABLED` and covers both request and response pipelines.
- **`buildErrorBody`** produces OpenAI‑compatible error objects that are safe to serialize to clients.
- **Upstream details** are recursively cleaned with depth and array limits to prevent pathological payload attacks.

## Frequently Asked Questions

### What happens if PII_REDACTION_ENABLED is not set?

PII redaction defaults to **disabled** (`false`). The feature flag system checks the database first, then environment variables, then the hard‑coded default. This ensures backward compatibility while allowing operators to enable protection without code changes.

### Can error sanitization be bypassed for debugging?

The sanitization functions are **mandatory** in `buildErrorBody`. There is no toggle to emit raw errors—operators must inspect server‑side logs for debugging. This design prevents accidental misconfiguration in production.

### How does OmniRoute handle Windows versus POSIX paths in errors?

The `sanitizeErrorMessage` function detects both formats using pattern matching and replaces any absolute path with the literal string `<path>`, regardless of platform.

### Is the PII detection configurable?

Yes. The `PIIMaskerGuardrail` accepts a custom `inputSanitizer` function. The default implementation uses `sanitizeStringValue`, but operators can inject alternative detection logic for specific compliance requirements.