Files
OmniRoute/scripts/check/check-error-helper.mjs
Diego Rodrigues de Sa e Souza 68e4d0c599 Release v3.8.19 (#3526)
* chore(release): open v3.8.19 development cycle

* chore(release): sync electron lockfile to 3.8.19

* feat(quality): quality-gate ratchet + anti-hallucination/rule-enforcement guardrails (Phases 0-6) (#3471)

* feat(quality): generic ratchet comparator (multi-metric, regression-only)

* chore(ci): Fase 0 quality-gate fixes — reconcile coverage gate (40->60), tier npm audit, wire orphaned contract gates, re-enable cheap husky pre-commit

* feat(quality): ratchet engine (collector + frozen baseline + CI job) and provider-consistency gate

- collect-metrics.mjs: emits quality-metrics.json (ESLint warnings + coverage when present)
- quality-baseline.json: frozen baseline (eslintWarnings=3482, regression-only)
- ci.yml: quality-gate job (ratchet + step summary + artifact) and check:provider-consistency in lint job
- check-provider-consistency.ts: every REGISTRY id must be a canonical provider (found krutrim half-registered → allowlisted as known pre-existing, blocks any NEW orphan)
- TDD: 9 tests (5 ratchet + 4 provider-consistency)

* feat(quality): Fase 2 anti-hallucination gates — fetch-targets, openapi-routes, deps allowlist

- check-fetch-targets: every dashboard fetch(/api/...) resolves to a real route.ts; found 7 pre-existing dashboard->route mismatches frozen as KNOWN_MISSING for triage
- check-openapi-routes: every openapi.yaml path resolves to a real route; found 1 stale spec entry (agent-bridge agents/{id}/state) frozen as KNOWN_STALE_SPEC
- check-deps: anti-slopsquatting allowlist (105 deps); new deps need explicit human-reviewed entry
- all wired into CI lint/docs jobs; TDD +12 tests (21 total across 5 gates)

* docs(quality): add quality-gates report + implementation plan to repo root

* feat(quality): Fase 3a — file-size ratchet (freeze 91 files >800 LOC, cap 800 for new)

- check-file-size.mjs: frozen files can only shrink; new files must be <= cap (kills the next 12k-line god-component)
- file-size-baseline.json: 91 files frozen at current LOC (largest 12883)
- wired into CI lint job; TDD 5 tests; --update ratchets the baseline down on shrink

* feat(quality): Fase 3b — duplication ratchet (jscpd@4, baseline 5.72%)

- check-duplication.mjs: runs jscpd@4 (pinned; v5 is an incompatible Rust rewrite) over src+open-sse, fails if duplication % rises vs frozen baseline (5.72%, measured: 1358 clones / 22967 dup lines). Targets the executor copy-paste (48/50 override execute() wholesale)
- wired into the parallel quality-gate CI job (off the lint critical path); TDD 4 tests; --update ratchets down
- snapshot now complete: coverage ~82.6%, eslint 3482 (98.5% no-explicit-any), duplication 5.72%, 91 files >800 LOC

* feat(quality): Fase 4a — anti test-masking gate

- check-test-masking.mjs: for each MODIFIED test file in a PR, flags net assert removal + new assert.ok(true) tautologies (base...HEAD diff). Directly enforces CLAUDE.md 'never weaken asserts to go green'
- wired into pr-test-policy CI job (reuses base fetch); no-op outside PR; TDD 5 tests

* feat(quality): Fase 4b — coverage ratchet (conservative floors, CI consumes merged coverage)

- quality-baseline.json: coverage.{statements,lines,functions,branches} floors (80/80/82/73, real ~82.58/82.58/84.23/75.22 with margin; tighten via --update after a green main run)
- check-quality-ratchet.mjs: --allow-missing (local quality:gate skips coverage.* without a coverage run; CI runs strict)
- ci.yml quality-gate job: needs test-coverage + downloads merged coverage-report so the ratchet enforces 'coverage cannot drop'
- TDD +1 test (6 total)

* feat(quality): Fase 6 — 8 new gates (Rule #11/#12, migrations, known-symbols, route-guard, complexity, docs-symbols, db-rules)

Deterministic gates, each freezing pre-existing violations in a documented allowlist (ratchet) so they pass now and block only NEW regressions:
- check-error-helper (Rule #12): 7 executors/handlers forwarding raw err.message frozen
- check-public-creds (Rule #11): 5 literal client_ids (Claude/Codex/Qwen/Kimi/Copilot) frozen
- check-migration-numbering: gaps 026/055 + dup 041 frozen (prevents the git-rm-deleted-migration incident)
- check-known-symbols: 93 executors conformance + 15 combo strategies + 18 translator pairs
- check-route-guard-membership (#15/#17): all 25 spawn-capable routes verified local-only (0 gaps)
- check-complexity: cyclomatic>15 / fn-length>80 ratchet (baseline 1739)
- check-docs-symbols: 30 stale doc /api refs frozen (docs hallucination)
- check-db-rules (#2/#5): 25 unexported db modules + 15 raw-SQL routes frozen
Wired into CI (lint / docs-sync-strict / quality-gate jobs). 115 TDD tests, all green. ESLint ratchet held at 3482.

* docs(quality): Phase 7 plan (security/dead-code/mutation/community tooling) — GATED to 2026-06-16

Stored, not active. 7 suggested gates + all discussed OSS/Community tools (SonarQube Community + osv-scanner + CodeQL + knip + sonarjs + type-coverage + lockfile-lint + Stryker + size-limit + axe-core + semcheck + agent-lsp + Qlty). Activation gate: do not start before 2026-06-16 (use Phases 0-6 in production for 1 week, validate in practice, then evolve).

* docs(quality): Phase 6A critical-audit plan + Phase 7 additions — gated to 2026-06-16 (#3530)

PLANO-QUALITY-GATES-FASE6A.md (12-task audit of Phases 0-6: orphan tests, stale-allowlist enforcement, scope gaps) + Phase 7 additions (gitleaks, actionlint+zizmor, license compliance). Both stored, activation gated to 2026-06-16. Tasks 6A.1/6A.2 were fast-tracked separately (#3536).

* feat(quality): 6A.1+6A.2 — test-discovery gate, 135 orphan tests re-wired, 2 production bug fixes, vitest in CI (#3536)

check-test-discovery gate (TDD; 195 orphans found, 135 re-wired into the node runner, 60 frozen+annotated). Triage fixed 2 real production bugs: missing BYPASS_PREFIX_NOT_ALLOWED zod refine (spawn-capable prefixes accepted into the bypass list, Hard Rules #15/#17) and resetDbInstance not firing stateReset resetters (stale schema memo → 503 instead of 403; also hit backup-restore). New test-vitest CI job: test:vitest blocking (146/146), test:vitest:ui informational (14 pre-existing fails, triage 2026-06-16).

* chore: ignore generated yt-downloader artifact files

Add dated yt-downloader output files to .gitignore to prevent
local automation artifacts from being accidentally committed.

* chore(quality): green-light the quality-gate — conscious file-size + eslintWarnings re-baselines (#3538)

file-size: 9 files frozen at current sizes (v3.8.18-era growth + core.ts +7 from #3536 fix). eslintWarnings 3482→3501: the published v3.8.18 tag already measures 3501 (delta predates the quality-gate job); v3.8.19 cycle is neutral. Reduction + --require-tighten = Phase 6A (2026-06-16).

* fix(check): exclude internal planning docs (docs/superpowers/) from the docs-symbols gate

docs/superpowers/plans/*.md are historical implementation-plan snapshots that
may cite planned/abandoned routes — not claims about the current code. Three
such refs entered during the v3.8.18 cycle, before this gate was on the
pipeline, and would have blocked the v3.8.19 release merge.

* chore(release): v3.8.19 — 2026-06-09

CHANGELOG section for the quality-infrastructure release (7 commits, 1:1
coverage), [3.8.18] label corrected to its real release date, local prompt
artifacts ignored.

* test: hermetic auth context for 2 re-wired suites + real headroom on the breaker reset-timeout flake

CI shards exposed what the dev DATA_DIR was masking locally: detect.test.ts
and managementCliToken.test.ts asserted 401/403/reject outcomes that only
exist when login protection is configured — on a fresh CI DB isAuthRequired()
is false and the policy anonymous-allows. Both now create an isolated
DATA_DIR with requireLogin+password (the established pattern).

observability-fase04: the breaker reset-timeout test ran with a 5ms margin
(resetTimeout 10 / sleep 15) — lazy HALF_OPEN refresh under shard contention
flipped the first OPEN assert. Now 250/300ms.

* test: align bypass-prefix schema test to the restored layer-1 contract + real waitFor headroom

appearance-widget-settings-schema asserted that /api/cli-tools/runtime/ was
ACCEPTED into the bypass list — written against the buggy schema (missing
BYPASS_PREFIX_NOT_ALLOWED refine, restored in #3536) and consecrating the
bug the AC-8 orphan test guards against. Split into accept-safe +
reject-spawn-capable cases. chatcore waitFor ceiling 1500→10000ms (green
runs return immediately; observed 1580ms expiry on 2-core CI runners).

* test(chatcore): fix structurally-broken pending-detail predicate (flatten before find)

pendingRequests.details[connectionId] is Record<modelKey, PendingRequestDetail[]>
— the upstream-timeout test's waitFor tested each ARRAY's .providerRequest
(always undefined), so it could never resolve and expired (failed on 3 CI jobs;
reproduced deterministically isolated, including at the published v3.8.18 tag).
Flatten to the actual details + declare the call_log_pipeline_enabled dependency
explicitly + waitFor ceiling with real CI headroom.

* chore(quality): re-baseline coverage floors to the honest post-re-wire denominator + changelog coverage for the stabilization commits

The 135 re-wired tests import modules that were never loaded before, so the
c8 denominator grew: the old ~82.5% was inflated by never-imported modules
being invisible. CI merged coverage now measures 78.4/78.4/83.84/75.73 —
floors set ~2pt below (76.5/76.5; functions/branches floors already hold).
Tightening via --require-tighten is Phase 6A work (2026-06-16).
2026-06-09 22:57:12 -03:00

289 lines
13 KiB
JavaScript

#!/usr/bin/env node
// scripts/check/check-error-helper.mjs
// Gate Hard Rule #12 (error sanitization): error responses/results built in
// open-sse/executors/ and open-sse/handlers/ MUST route through the helpers in
// open-sse/utils/error.ts (buildErrorBody / errorResponse / sanitizeErrorMessage /
// sanitizeUpstreamDetails / makeExecutorErrorResult / formatProviderError / …) so
// raw err.stack / err.message / upstream body.error.message never reach a client.
//
// The risk: a file that builds its own `new Response(JSON.stringify({ error: {
// message: err.message } }))` (or a result object with `error: <raw msg>`) and does
// NOT import the sanitizer leaks stack traces / absolute paths / upstream internals.
// CodeQL's js/stack-trace-exposure does not understand the custom sanitizer, so this
// static gate is the canonical enforcement. See docs/security/ERROR_SANITIZATION.md.
//
// Conservative by design: a file is flagged ONLY when it both (a) appears to forward
// a RAW error value into a response/result body AND (b) imports nothing from a
// utils/error path. Files that import the helper are trusted (the `body.error.message`
// they reference is the sanitized output of buildErrorBody, not raw upstream).
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
const cwd = process.cwd();
const SCAN_DIRS = [
path.join(cwd, "open-sse/executors"),
path.join(cwd, "open-sse/handlers"),
];
// Pre-existing violators frozen so the gate is green NOW and blocks only NEW leaks.
// Each entry is a real Rule #12 gap (raw err.message forwarded into a response body
// with no utils/error import) and should become a tracked cleanup issue: route the
// message through sanitizeErrorMessage()/buildErrorBody()/makeExecutorErrorResult().
// Do NOT add new entries without a justification — that defeats the gate.
export const KNOWN_MISSING_ERROR_HELPER = new Set([
// adapta-web: local makeErrorResponse() + `Adapta auth failed: ${msg}` where
// msg = err.message — raw auth/upstream error string in the JSON error body,
// no open-sse/utils/error import. Fix: sanitizeErrorMessage(msg) before forwarding.
"open-sse/executors/adapta-web.ts",
// deepseek-web: local errorResponse() shadow that puts `message` raw into the body,
// fed `DeepSeek error: ${msg}` where msg = err.message — bypasses the canonical
// sanitizer. Fix: route through buildErrorBody()/sanitizeErrorMessage().
"open-sse/executors/deepseek-web.ts",
// perplexity-web: `new Response({ error: { message: `Perplexity connection failed:
// ${err.message}` }})` (multi-line envelope) for TLS/connection failures — raw
// err.message in the client error body, no sanitizer import.
"open-sse/executors/perplexity-web.ts",
// qoder: `response: new Response({ error: { message: `Qoder fetch error:
// ${error.message}` }})` — raw error.message in the returned response body,
// no sanitizer import.
"open-sse/executors/qoder.ts",
// veoaifree-web: local errResp(msg) on nonce-fetch failure where msg = err.message —
// raw error string in the response body, no sanitizer import.
"open-sse/executors/veoaifree-web.ts",
// embeddings handler: `return { success: false, status: 502, error: `Embedding
// provider error: ${err.message}` }` — raw err.message in the result error field,
// no sanitizer import. (The saveCallLog `error: err.message` rows are internal and
// correctly NOT what is frozen here.)
"open-sse/handlers/embeddings.ts",
// search handler: `return { …, error: `Search provider …: ${err.message}` }` — raw
// err.message in the result error field, no sanitizer import.
"open-sse/handlers/search.ts",
]);
// Import specifiers that count as "uses the error helper" (path ends in utils/error).
const ERROR_HELPER_IMPORT =
/\bfrom\s*["'](?:\.{1,2}\/)*(?:open-sse\/)?utils\/error(?:\.[tj]s)?["']|@omniroute\/open-sse\/utils\/error/;
// A caught-error identifier whose .message/.stack is RAW (not sanitized): the leading
// token must be exactly `err` / `error` / `e` (optionally `(err as Error)` cast), and
// NOT preceded by a member access — so `event.error.message` (an upstream-event read)
// does not match, only our own caught `err.message` / `error.stack` / `(err as …).msg`.
// The `(?<![.\w])` lookbehind is non-consuming so it works mid-template (e.g. `${err…`).
const RAW_ERR = String.raw`(?:\((?:err|error|e)\s+as\s+[^)]+\)|(?<![.\w])(?:err|error|e))\.(?:message|stack)\b`;
// Lines that are internal sinks (never reach the client) — excluded so the gate does
// not false-positive on logging, DB audit rows, thrown Errors, or rejected promises.
const INTERNAL_SINK =
/\b(?:log\??\.\w+\??\.?\(|console\.\w+\(|saveCallLog\s*\(|reqLogger\.|throw\s+new\s+\w*Error|reject\s*\(|\.error\??\.\(|finish\s*\()/;
// Internal-sink CALL openers — when a raw-error field sits inside one of these calls'
// argument object (e.g. `saveCallLog({ … error: err.message … })`), it is a DB audit
// row / log entry, not a client response. Matched against the line that opens the
// nearest still-unclosed call enclosing the flagged line.
const INTERNAL_SINK_CALL =
/\b(?:saveCallLog|log\??\.\w+|console\.\w+|reqLogger\.\w+)\s*\(\s*\{?\s*$/;
// A line that is constructing a client-facing response/result body.
const RESPONSE_LINE =
/new\s+Response\s*\(|\bresponse\s*:|\berrResp\s*\(|\bmakeErrorResponse\s*\(|\berrorResponse\s*\(/;
function walk(dir, acc = []) {
if (!fs.existsSync(dir)) return acc;
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) walk(p, acc);
else if (/\.tsx?$/.test(e.name) && !/\.test\.tsx?$/.test(e.name)) acc.push(p);
}
return acc;
}
// A raw caught-error value assigned to / interpolated into a `message:`/`error:` field.
const RAW_ERR_FIELD = new RegExp(String.raw`\b(?:message|error)\s*:\s*` + RAW_ERR);
const RAW_ERR_FIELD_INTERP = new RegExp(
String.raw`\b(?:message|error)\s*:\s*[\`"'][^\n]*\$\{[^}]*` + RAW_ERR
);
// A raw caught-error value interpolated anywhere on a line that also builds a Response.
const RAW_ERR_INTERP = new RegExp(String.raw`\$\{[^}]*` + RAW_ERR);
// Upstream `body.error.message` forwarded into a field without a sanitize call.
const RAW_BODY_ERR = /\b(?:message|error)\s*:\s*[^,}\n]*\bbody\.error\.message\b/;
// A response-builder CALL that takes a message argument (client-facing). A tainted
// local variable (assigned from a raw error) passed here is a leak.
const RESPONSE_BUILDER_CALL =
/\b(?:errResp|makeErrorResponse|errorResponse)\s*\(|\bresponse\s*:\s*(?:errResp|makeErrorResponse|errorResponse|new\s+Response)\s*\(/;
// `const|let <id> = <expr containing a raw caught-error>` — a tainted local holding a
// raw, unsanitized error string. Captures the variable name for downstream tracking.
const TAINT_DECL = new RegExp(
String.raw`\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*[^;\n]*` + RAW_ERR
);
/**
* Does this source forward a RAW error value into a CLIENT-FACING response/result body?
*
* Line-anchored + sink-aware so it does not false-positive on logging, DB audit rows
* (saveCallLog), thrown Errors, rejected promises, or parsed upstream-event reads.
*
* A line is a violation when, after skipping internal-sink lines, it either:
* - assigns/interpolates a raw caught-error into a `message:`/`error:` field, or
* - interpolates a raw caught-error AND is itself a Response/result-builder line, or
* - forwards upstream `body.error.message` into a field without sanitizing, or
* - passes a TAINTED local (a var assigned from a raw error, never sanitized) into a
* response-builder call (errResp / makeErrorResponse / errorResponse / new Response).
*/
function forwardsRawError(source) {
const lines = source.split("\n").map((l) => l.replace(/\/\/.*$/, ""));
// Pass 1: collect tainted local variables (raw error, no sanitize on the line).
const tainted = new Set();
for (const line of lines) {
if (INTERNAL_SINK.test(line)) continue;
const m = line.match(TAINT_DECL);
if (m && !/sanitize/i.test(line)) tainted.add(m[1]);
}
const taintedUse =
tainted.size > 0
? new RegExp(String.raw`\b(?:${[...tainted].join("|")})\b`)
: null;
// Pass 2: scan for leak lines.
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line.trim()) continue;
if (INTERNAL_SINK.test(line)) continue; // log / audit / throw / reject
if (TAINT_DECL.test(line)) continue; // the assignment itself is not the leak
const directLeak =
RAW_ERR_FIELD.test(line) ||
RAW_ERR_FIELD_INTERP.test(line) ||
(RAW_ERR_INTERP.test(line) && RESPONSE_LINE.test(line)) ||
// Multi-line OpenAI error envelope: a raw-error interpolation that sits inside
// an enclosing `error: {` / `message:` field of a `new Response(` body.
(RAW_ERR_INTERP.test(line) && enclosedByErrorResponseBody(lines, i)) ||
(RAW_BODY_ERR.test(line) && !/sanitize/i.test(line));
const taintedLeak =
taintedUse !== null && RESPONSE_BUILDER_CALL.test(line) && taintedUse.test(line);
// The raw error reaches a client body unless it lives inside an internal-sink
// call's argument object (saveCallLog / log / console / reqLogger).
if ((directLeak || taintedLeak) && !enclosedByInternalSinkCall(lines, i)) return true;
}
return false;
}
/**
* Walk back from `idx`, tracking net brace/paren depth, to find the line that opens
* the call enclosing `idx`. Returns true if that opener is an internal-sink call.
* Bounded lookback (sink-call argument objects are small) keeps this cheap.
*/
function enclosedByInternalSinkCall(lines, idx) {
let depth = 0;
for (let j = idx; j >= 0 && idx - j < 80; j--) {
const l = lines[j].replace(/\/\/.*$/, "");
for (let k = l.length - 1; k >= 0; k--) {
const ch = l[k];
if (ch === ")" || ch === "}") depth++;
else if (ch === "(" || ch === "{") {
if (depth === 0) {
// Unbalanced opener at this position — the enclosing construct starts here.
return INTERNAL_SINK_CALL.test(l.slice(0, k + 1));
}
depth--;
}
}
}
return false;
}
// Field opener that is part of an OpenAI-style error envelope (`error: {` / `message:`).
const ERROR_FIELD_OPENER = /\b(?:error|message)\s*:\s*[`{]?\s*$/;
/**
* Walk back from `idx` to the nearest enclosing `{`/`(` opener; if it opens an error
* envelope field (`error: {` / `message:`) AND a `new Response(` / `response:` builder
* appears just above it, the raw error reaches a client error body. Conservative: only
* the canonical error-envelope shape qualifies (not `content:` / data fields).
*/
function enclosedByErrorResponseBody(lines, idx) {
let depth = 0;
for (let j = idx; j >= 0 && idx - j < 80; j--) {
const l = lines[j].replace(/\/\/.*$/, "");
for (let k = l.length - 1; k >= 0; k--) {
const ch = l[k];
if (ch === ")" || ch === "}") depth++;
else if (ch === "(" || ch === "{") {
if (depth === 0) {
if (!ERROR_FIELD_OPENER.test(l.slice(0, k + 1))) return false;
// Confirm a Response builder sits in the few lines above the envelope.
const window = lines.slice(Math.max(0, j - 8), j + 1).join("\n");
return /new\s+Response\s*\(|\bresponse\s*:/.test(window);
}
depth--;
}
}
}
return false;
}
export function findErrorHelperViolations(files, allowlist) {
const violations = [];
for (const { path: rel, source } of files) {
if (allowlist.has(rel)) continue;
if (ERROR_HELPER_IMPORT.test(source)) continue; // trusts the helper
if (forwardsRawError(source)) violations.push(rel);
}
return violations;
}
function collectFiles() {
const files = [];
for (const dir of SCAN_DIRS) {
for (const p of walk(dir)) {
files.push({
path: path.relative(cwd, p).replace(/\\/g, "/"),
source: fs.readFileSync(p, "utf8"),
});
}
}
return files;
}
function main() {
const files = collectFiles();
const violations = findErrorHelperViolations(files, KNOWN_MISSING_ERROR_HELPER);
// Surface allowlist drift: entries that no longer match a real file (cleaned up or
// renamed) so the allowlist does not rot. This is a warning, not a failure.
const present = new Set(files.map((f) => f.path));
const stale = [...KNOWN_MISSING_ERROR_HELPER].filter((p) => !present.has(p));
if (stale.length) {
console.warn(
`[check-error-helper] WARN: ${stale.length} allowlist entr${
stale.length === 1 ? "y" : "ies"
} no longer match a file (remove from KNOWN_MISSING_ERROR_HELPER):\n` +
stale.map((p) => " - " + p).join("\n")
);
}
if (violations.length) {
console.error(
`[check-error-helper] ${violations.length} file(s) build an error response/result with a ` +
`raw err.message/err.stack/body.error.message but do NOT import open-sse/utils/error:\n` +
violations.map((v) => " ✗ " + v).join("\n") +
`\n → route the message through buildErrorBody()/sanitizeErrorMessage()/` +
`makeExecutorErrorResult() (see docs/security/ERROR_SANITIZATION.md), or — if it is a ` +
`false positive — add it to KNOWN_MISSING_ERROR_HELPER with a justification.`
);
process.exit(1);
}
console.log(
`[check-error-helper] OK (${files.length} files scanned, ${KNOWN_MISSING_ERROR_HELPER.size} known-missing frozen)`
);
}
if (import.meta.url === pathToFileURL(process.argv[1] || "").href) main();