Files
OmniRoute/docs/security/ERROR_SANITIZATION.md
Diego Rodrigues de Sa e Souza 5ac4637816 docs: reorganize docs/ + accuracy audit + drop Node 20 (rebased onto current release tip) (#5262)
* docs: move superpowers/research artifacts to isolated _tasks repo + docs tree cleanup

- Move docs/superpowers/{plans,specs} and docs/research/* into the gitignored,
  separately-versioned _tasks/ repo; untrack the two tracked research design docs.
- Add CLAUDE.md "Planning & Research Artifacts" section overriding the superpowers
  default save paths (docs/... -> _tasks/...); align REPOSITORY_MAP and
  DOCUMENTATION_OVERHAUL_PLAN with the new convention.
- Drop 4 now-obsolete /api/discovery/* entries from check-docs-symbols allowlist
  (stale-enforcement) and refresh code/spec path comments to _tasks/...
- Sweeps in concurrent docs-tree restructuring (root-level provider/guide docs,
  compression spec cleanup, .mcp.json.example removal).

* docs: reorganize docs/ tree + fix stale facts across ~26 docs

Phase A — reorganization:
- Move 7 orphan root docs into subfolders (providers/ created; TIERS+USAGE_QUOTA→guides/;
  plugins+PLUGIN_SDK→frameworks/); delete 8 obsolete/redundant docs (SUBMIT_PR superseded
  by CONTRIBUTING; DOCUMENTATION_OVERHAUL_PLAN; INCIDENT_RESPONSE/PERF_BUDGETS/THREAT_MODEL;
  3 ops snapshots). Rebuild README index (was missing ~40 files) + per-folder meta.json nav.
- Clean 14 dangling doc-path references in bin/ ops scripts, scripts/, workflow, tests;
  fix the dockerignore-docs-coverage required-docs path (PROVIDERS→providers/CLAUDE_WEB).

Phase B — content accuracy (verified against code, not the audit summary):
- Functional: ENVIRONMENT flag defaults (INPUT_SANITIZER/MCP_ENFORCE_SCOPES=true,
  COMPRESS_DESCRIPTIONS=false, dynamic heap); MCP-SERVER notion tool names (omniroute_*→
  notion_*) + counts 87→94; coverage gate 75/70→60/60/60/60 (RELEASE_CHECKLIST, COVERAGE_PLAN,
  ERROR_SANITIZATION, CONTRIBUTING); pre-push hook description; regenerate PROVIDER_REFERENCE (237).
- Count drift: providers 237, executors 70, migrations 106, db modules 94, oauth 19,
  strategies 17, MCP 94, flags 38, TS 6.0, open-sse ~900/services 294 across architecture/
  frameworks/ops docs; AUTO-COMBO 9→12 factors w/ correct DEFAULT_WEIGHTS; REASONING +2
  patterns; STEALTH UA defaults; AGENT_PROTOCOLS +cursor-cloud/list-capabilities;
  LANGUAGE_PACKS +id pack.
- Kept Node 20 (runtime guard accepts 20.20.2+; only engines is stricter) and MCP scopes=13
  (mcpScopes.ts) — both were correct in the docs; corrected only the attribution.

* docs: finish content refresh — compression engines, CLI_TOKEN merge, metadata sweep

- Compression: document the additional built-in engines (CCR, headroom, ionizer,
  session-dedup) in COMPRESSION_ENGINES; clarify LLMLingua-2 is the ultra-mode SLM
  backend + cross-ref the extra engines in EXTENDING_COMPRESSION; add the id
  (Indonesian) language pack to LANGUAGE_PACKS.
- AUTO-COMBO: replace the orphan 'How tiers fit' weight table (stale weights) with a
  pointer to the canonical 12-factor DEFAULT_WEIGHTS table.
- Security: merge CLI_TOKEN_AUTH.md (legacy 32-char SHA-256 format) into CLI_TOKEN.md
  as a 'Legacy format — still accepted' section (server accepts both HMAC + legacy),
  delete CLI_TOKEN_AUTH.md, drop it from the index + security nav.
- Metadata: bump stale frontmatter (version/lastUpdated) to 3.8.40/2026-06-28 across the
  doc set audited this pass, and normalize the in-body 'Last updated' header lines to match.

* fix(runtime): drop Node 20 from supported range + align all docs/diagrams/counts

- Node minimum is now 22 (aligned with package.json engines). SUPPORTED_NODE_RANGE in
  src/shared/utils/nodeRuntimeSupport.ts (and the bin/ mirror) drops the 20.x line →
  '>=22.22.2 <23 || >=24.0.0 <27'; getNodeRuntimeSupport now rejects Node 20 as
  unsupported-major. Test updated (TDD): node-runtime-support.test.ts asserts Node 20
  rejected. Docs aligned (TROUBLESHOOTING ×2, TERMUX, RELEASE_CHECKLIST, CODEBASE,
  CLI-TOOLS, README, llm.txt + 42 i18n llm.txt mirrors, skills/cli-serve).
- Diagrams regenerated: mcp-tools-87 -> mcp-tools-94 (34 base + pool 6 = 94) and
  auto-combo-9factor -> auto-combo-12factor (correct DEFAULT_WEIGHTS); SVGs re-rendered
  via mermaid-cli; doc refs + diagrams/README updated; fixed a pre-existing broken
  resilience-3layers image path.
- CLAUDE.md + AGENTS.md aligned to real counts (237 providers, 94 MCP tools / 34 base,
  106 migrations, 94 db modules, 12-factor auto-combo, 17 strategies); README provider
  count 231 -> 237; executor count corrected to 68 (provider executors, excl base/index)
  and OAuth to 18 across architecture docs. check:docs-all now passes (0 strict drift,
  0 broken links); removed dead .mcp.json.example doc link.

* fix(services): update installer Node hint to >=22.22.2 (aligned with dropped Node 20)

* docs: realign counts to current release tip after rebase

The release tip advanced while this work was in flight (Gemini CLI provider/executor
removed by #5246, plus other PRs). Re-counted against the current code and updated:
providers 237->236, executors 68->67, OAuth modules 18->17, open-sse services 294->298;
regenerated PROVIDER_REFERENCE.md (236). check:docs-all passes (0 strict drift).

* docs(changelog) + i18n: record Node 20 drop + fix nodeIncompatibleHint

- CHANGELOG: add [3.8.40] entries for the Node 20.x removal (runtime) and the docs
  reorganization/accuracy audit.
- i18n: nodeIncompatibleHint across all 42 locales no longer lists Node 20.x as
  supported (ASCII + CJK full-width variants), aligned with the dropped Node 20.

* fix(docs): repair CI breakages from the doc moves

- test: cli-plugin-system asserted docs/dev/plugins.md exists; the file moved to
  docs/frameworks/PLUGINS.md — point the test at the new path (Unit fast-path 2/2 fix).
- frontmatter: PLUGINS.md and PLUGIN_SDK.md moved into the fumadocs-indexed
  docs/frameworks/ which requires a 'title' frontmatter; the missing frontmatter
  failed the Next.js MDX build (dast-smoke 'invalid frontmatter'). Added frontmatter
  to both, plus the providers/ docs (consistency; that folder is not indexed).
2026-06-28 22:07:18 -03:00

8.5 KiB

title, version, lastUpdated
title version lastUpdated
Error Message Sanitization 3.8.40 2026-06-28

Error Message Sanitization

Source of truth: open-sse/utils/error.tssanitizeErrorMessage, buildErrorBody, createErrorResult Tests: tests/unit/error-message-sanitization.test.ts Last updated: 2026-06-28 — v3.8.40 Audience: Any engineer touching error responses (HTTP routes, SSE streams, executors, MCP handlers). Status: MANDATORY for every code path that returns an error message to a client.

Why this exists

CodeQL rule js/stack-trace-exposure (CWE-209) flags any code path where an error message originating from a runtime exception reaches an HTTP / SSE response without being sanitized. Stack traces and absolute file paths in production responses give attackers:

  • Internal directory layout (/srv/app/src/lib/...) → reconnaissance for further attacks.
  • Library / framework versions inferred from stack frames → targeted exploit selection.
  • Sensitive runtime values that may be string-interpolated into errors (DB queries, config values).

The sanitizeErrorMessage helper in open-sse/utils/error.ts strips both classes of leakage:

  1. Multi-line stack traces — only the first line (the actual error message) is kept.
  2. Absolute paths (/...*.{ts,js,tsx,jsx,mjs,cjs}[:line[:col]] and C:\...) — replaced with <path>.

The mandatory pattern

1. Building an error response (HTTP / API routes)

Use buildErrorBody() — sanitization is built-in:

import { buildErrorBody } from "@omniroute/open-sse/utils/error.ts";

export async function POST(req: Request) {
  try {
    // ... handler logic ...
  } catch (err) {
    return new Response(JSON.stringify(buildErrorBody(500, String(err))), {
      status: 500,
      headers: { "Content-Type": "application/json" },
    });
  }
}

Or, for the convenience wrappers in the same module:

import {
  errorResponse, // one-shot Response object
  writeStreamError, // SSE writer
  createErrorResult, // { success: false, status, response, ... } shape
  unavailableResponse, // adds Retry-After
  providerCircuitOpenResponse,
  modelCooldownResponse,
} from "@omniroute/open-sse/utils/error.ts";

All of these route through buildErrorBody and therefore through sanitizeErrorMessage. You never need to call sanitizeErrorMessage manually when using these helpers.

2. Custom error envelopes (rare)

When you can't use the helpers above (e.g. the response shape is dictated by an upstream protocol like Connect-RPC), import sanitizeErrorMessage directly:

import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";

const body = JSON.stringify({
  error: {
    message: sanitizeErrorMessage(rawMessage),
    type: "invalid_request_error",
    code: "",
  },
});

This is the only sanctioned way to assemble a custom error body. See open-sse/executors/cursor.ts::buildErrorResponse for the reference implementation.

3. Logging vs. responding

sanitizeErrorMessage should only wrap the value that crosses the network boundary. Internal logs (pino, console) should keep the full message, including stack, so operators can debug. Pattern:

try {
  // ...
} catch (err) {
  log.error({ err }, "handler failed"); // full err with stack — internal log
  return errorResponse(500, getErrorMessage(err)); // sanitized — sent to client
}

4. Forbidden patterns

Never put raw exception output in a Response body:

// BAD: stack trace + file paths reach the client
return new Response(JSON.stringify({ error: { message: err.stack || err.message } }), {
  status: 500,
});

Never roll your own first-line splitter:

// BAD: forgets to strip absolute paths, may drift from the canonical helper
const safe = String(err).split("\n")[0];

Never sanitize in the route and forget the SSE path. Anything that writes to a stream goes through writeStreamError (or its underlying buildErrorBody).

Never include process.cwd(), __filename, __dirname, env-derived paths in error messages — they bypass the path regex and reveal the deployment topology.

Coverage in CI

tests/unit/error-message-sanitization.test.ts enforces:

  • Every route under /api/model-combo-mappings/* returns sanitized bodies on 4xx/5xx.
  • sanitizeErrorMessage strips multi-line stack traces.
  • sanitizeErrorMessage replaces POSIX and Windows absolute paths with <path>.
  • sanitizeErrorMessage handles null/undefined/Error instance inputs safely.
  • buildErrorBody never exposes stack traces in its message field.

When adding a new route or executor, copy the assertion pattern from this file. The coverage gate (npm run test:coverage) enforces ≥60% statements/lines/functions/branches — error paths must be covered.

  • js/stack-trace-exposure CodeQL alerts in .github/security should always be either fixed via these helpers or dismissed with a comment citing this doc.
  • The pino redaction config (src/shared/utils/logRedaction.ts) handles structured log redaction separately. This doc covers only the response-message surface.
  • Upstream-header denylist (src/shared/constants/upstreamHeaders.ts) covers header leakage — keep both files aligned when adding a new exfiltration concern.

Upstream details passthrough

buildErrorBody accepts an optional third argument upstreamDetails (raw parsed body from the upstream provider). When provided, it is sanitized by sanitizeUpstreamDetails before inclusion in the response as upstream_details.

Sanitization rules applied to upstreamDetails:

  1. String leaves: run through sanitizeErrorMessage (strips stacks + absolute paths).
  2. Key blocklist: keys matching /stack|trace|path|file|cwd|dir|password|secret|token|key/i are removed.
  3. Depth cap: nesting beyond 4 levels is replaced with the string "[truncated]".
  4. Arrays are capped at 32 elements.

Only the seven upstream-error createErrorResult call sites in chatCore.ts pass upstreamErrorBody. Internal OmniRoute errors (SSE parse failures, empty content, guardrail blocks) do not include upstream_details.

Do NOT pass raw err.stack, err.message, or any string from a runtime exception to upstreamDetails. Those must still go through errorResponse / buildErrorBody(code, msg) without an upstream body.

Known CodeQL limitation: custom sanitizers not recognized

The CodeQL query js/stack-trace-exposure uses a fixed allowlist of sanitizer patterns (e.g. inline .split("\n")[0], String#replace with specific regex shapes, access to .message on Error). It does not recognize indirection through a custom helper like our sanitizeErrorMessage().

This means callsites that demonstrably sanitize via this module — for example open-sse/utils/error.ts::errorResponse and open-sse/executors/cursor.ts::buildErrorResponse — may continue to raise the alert even though the code is functionally safe. Precedent dismissals: #224, #231 (May 2026), both marked false positive with technical justification.

How to handle a new occurrence:

  1. Confirm the callsite actually routes the message through sanitizeErrorMessage / buildErrorBody / one of the wrappers documented above (read the call chain end-to-end — don't trust a comment).
  2. Confirm tests/unit/error-message-sanitization.test.ts exercises the path (or add coverage).
  3. Dismiss the alert via gh api ... -X PATCH state=dismissed -f 'dismissed_reason=false positive' referencing this doc.
  4. Do not "fix" by inlining .split("\n")[0] everywhere — the helper is the single source of truth; duplicating the pattern weakens the sanitizer (loses path scrubbing, length cap, type coercion) for the appearance of placating the scanner.

Adopting opt-in features like CodeQL's @codeql/javascript-models custom sanitizer config is the long-term fix; it lives outside this doc.

References