From 2da193c5f7b939e458f1f965e641cc4d46be5dfd Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Sun, 6 Sep 2026 00:14:03 +0500 Subject: [PATCH 1/4] fix(protocol,node): scrub secrets out of a crash frame's source context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A crash frame can carry `context` — the source lines around the throwing line — and those lines shipped to the wire verbatim. So a hardcoded credential on or near the throwing line was disclosed in plaintext, while the SAME value held in a local variable arrived as ``, because `captureLocalVariables` scrubs by key name (`local-variables.ts:145`). One value, two answers, decided by which feature happened to see it. WHAT "SCRUB A SOURCE LINE" MEANS — `redactSourceLines` in `@bugsee/protocol`, two passes, BOTH of them reusing definitions that already exist rather than adding one: 1. SENSITIVE ASSIGNMENT. A string, template or numeric LITERAL whose key or identifier satisfies `isSensitiveKey` (or `isSensitiveHeader`, since an object literal in a `fetch` call is where a header name appears as a key) becomes ``. That is the same predicate local-variable capture, body/query scrubbing and span sanitizing use, so the inconsistency closes by construction rather than by a second list that would drift. 2. CREDENTIAL SHAPE. `redactShapes` — this package's existing shape pass, already applied to network values, error messages and stack text. Reused wholesale; no new pattern. DELIBERATELY NOT DONE: entropy thresholds, "long base64/hex run", generic 32-or-40-character alphanumeric rules. The published scanner comparisons agree that entropy-plus-broad-regex has high recall and low precision, and a crash window shows exactly the code that is full of hashes, digests, UUIDs, minified identifiers and asset fingerprints. A false positive here silently destroys the feature — a redacted line tells the reader nothing, and unlike a leak nobody reports it. The cost is stated rather than hidden: a secret that is neither assigned to a sensitively-named identifier nor of a recognised provider shape still ships. WINDOW-SCOPED, and redacted BEFORE the clip. Window-scoped because a wrapped assignment puts the key on one line and its literal on the next, and a per-line rule would read that continuation as a bare string with no key to judge it by. Before the clip because clipping first would cut a long line mid-literal, leaving a prefix with no closing quote to match and no complete shape to recognise — a truncated credential is still a credential. That means the input can be a whole minified bundle line, so the pattern is anchored and has linearity tests. MIRRORED IN THE BACKGROUND WORKER, which REPLACES this window on a sourcemap remap and INVENTS one for a frame that had none — the common path for a web frame. The companion PR scrubs it there too. The two are held together by `source-line-redaction.vectors.json`: the denylists (asserted here to equal `sensitive.ts`) plus 35 whole-window vectors that BOTH test suites run, so an algorithmic divergence turns one of the two CIs red. Also removes a lookahead that could not fire. `(?!=|>)` was written to keep `token => "x"` from reading as an assignment; the mutator loop disproved it — removing it changed no test outcome, because between the operator and the value the pattern allows only whitespace and `>` is neither whitespace nor the start of a literal. The arrow cases stay as the pins that say why it is safe to be absent. The `locals` e2e now hardcodes its secret at the throw site instead of referencing a constant, so the existing "the secret never appears anywhere in the bundle" assertion covers the source window too. Verified non-vacuous: bypassing the redaction fails it on node, bun and deno. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .../instrumentation-tests/app/scenario.ts | 7 +- .../test/local-variables.e2e.ts | 19 ++ packages/node/src/source-context.test.ts | 103 ++++++- packages/node/src/source-context.ts | 19 +- packages/protocol/package.json | 9 +- .../source-line-redaction.vectors.json | 291 ++++++++++++++++++ packages/protocol/src/index.ts | 1 + .../src/source-context-redaction.test.ts | 232 ++++++++++++++ .../protocol/src/source-context-redaction.ts | 145 +++++++++ 9 files changed, 817 insertions(+), 9 deletions(-) create mode 100644 packages/protocol/source-line-redaction.vectors.json create mode 100644 packages/protocol/src/source-context-redaction.test.ts create mode 100644 packages/protocol/src/source-context-redaction.ts diff --git a/packages/instrumentation-tests/app/scenario.ts b/packages/instrumentation-tests/app/scenario.ts index 2a54d2f9..d7d92344 100644 --- a/packages/instrumentation-tests/app/scenario.ts +++ b/packages/instrumentation-tests/app/scenario.ts @@ -119,7 +119,12 @@ export const LOCALS_SECRET = 'sk-live-e2e-MUST-NOT-SHIP'; */ function e2eLocalsThrow(): void { const orderId = LOCALS_ORDER_ID; - const apiKey = LOCALS_SECRET; + // HARDCODED ON PURPOSE, and it must STAY a literal rather than a reference to `LOCALS_SECRET`. + // Source-context capture reads this file off disk at report time and puts the window around the + // `throw` below straight on the wire, so a reference would mean the leak the redaction exists to stop + // is not actually present in the file and the assertion covering it would be vacuous. The e2e checks + // this line is still spelled out — see `local-variables.e2e.ts`. + const apiKey = 'sk-live-e2e-MUST-NOT-SHIP'; const customer = { plan: 'pro' }; if (orderId > 0 && apiKey.length > 0 && customer.plan === 'pro') { throw new Error('e2e locals crash'); diff --git a/packages/instrumentation-tests/test/local-variables.e2e.ts b/packages/instrumentation-tests/test/local-variables.e2e.ts index 7133907e..9c39f27e 100644 --- a/packages/instrumentation-tests/test/local-variables.e2e.ts +++ b/packages/instrumentation-tests/test/local-variables.e2e.ts @@ -5,6 +5,7 @@ // thrown object can be stamped and matched back to the Error the SDK captures, or that any of it survives // bundle assembly, zipping and upload. A real process, the real `node:inspector`, a real uncaught throw, // and the real uploaded artifact. +import { readFileSync } from 'node:fs'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { LOCALS_ORDER_ID, LOCALS_SECRET } from '../app/scenario'; import { type ParsedBundle, parseBundles, readJson } from './bundle'; @@ -131,4 +132,22 @@ describe.each(nodeTarget)('local variables — the captured values ($name)', (ta expect(throwingFrame()?.context?.line).toContain('throw new Error'); expect(stderr).not.toContain('[bugsee onError]'); }); + + it('the scenario really does hardcode the secret near the throw', () => { + // The guard that keeps the assertion below from being vacuous. If someone rewrites the scenario's + // `const apiKey = '…'` back into a reference to LOCALS_SECRET, the source window stops containing + // a credential at all and "no secret in the window" becomes true for the wrong reason. + const scenario = readFileSync(new URL('../app/scenario.ts', import.meta.url), 'utf8'); + expect(scenario).toContain(`const apiKey = '${LOCALS_SECRET}';`); + }); + + it('REDACTS the hardcoded secret in the SOURCE WINDOW, not just in the locals', () => { + // The defect this pair of PRs closes: the window shipped verbatim, so the same value arrived + // redacted as a local and in plaintext two lines above it. + const frame = throwingFrame(); + const window = [...(frame?.context?.pre ?? []), frame?.context?.line ?? '']; + expect(window.join('\n')).toContain('const apiKey ='); + expect(window.join('\n')).toContain(''); + expect(window.join('\n')).not.toContain(LOCALS_SECRET); + }); }); diff --git a/packages/node/src/source-context.test.ts b/packages/node/src/source-context.test.ts index 82b173f1..5aff9041 100644 --- a/packages/node/src/source-context.test.ts +++ b/packages/node/src/source-context.test.ts @@ -1,7 +1,9 @@ -import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import process from 'node:process'; +import { fileURLToPath } from 'node:url'; import { describe, expect, it, vi } from 'vitest'; import { createSourceContextEnricher, isReadablePath, readContext } from './source-context'; @@ -41,6 +43,63 @@ describe('readContext', () => { }); }); +describe('readContext — secrets in the source window', () => { + // The defect this closes: these lines shipped verbatim, so a hardcoded credential ON or NEAR the + // throwing line was disclosed in plaintext — while the same value held in a local variable arrived + // as ``, because local-variable capture scrubs by key name. The rule itself lives in + // `@bugsee/protocol` (`redactSourceLines`), shared with the worker; these pin the WIRING. + const secretSource = [ + 'const before = 1;', + 'const apiKey = "sk-live-SUPERSECRET";', + 'throw new Error("boom");', + "const password = 'hunter2';", + 'const after = 2;', + ].join('\n'); + + it('redacts a secret on the THROWING line', () => { + expect(readContext(`const apiKey = "sk-live-SUPERSECRET";`, 1, 0, 200)?.line).toBe( + 'const apiKey = "";', + ); + }); + + it('redacts secrets in `pre` and `post`, not only on the throwing line', () => { + const context = readContext(secretSource, 3, 2, 200); + expect(context?.pre).toEqual(['const before = 1;', 'const apiKey = "";']); + expect(context?.post).toEqual(["const password = '';", 'const after = 2;']); + }); + + it('leaves ordinary source alone', () => { + expect(readContext(secretSource, 5, 0, 200)?.line).toBe('const after = 2;'); + }); + + it('redacts BEFORE clipping, so a clipped line cannot ship a secret prefix', () => { + // Clipping first would cut the literal in half: no closing quote for the assignment pass to match, + // no complete shape for the shape pass, and a usable prefix of the credential on the wire. + const padding = 'x'.repeat(40); + const line = `const apiKey = "sk-live-${padding}"; // ${padding}`; + const context = readContext(line, 1, 0, 30); + expect(context?.line).toBe('const apiKey = ""; /…'); + expect(context?.line).not.toContain('sk-live'); + }); + + it('keeps the window aligned when a redacted literal spans lines', () => { + // A multi-line template collapsed to one `` would shorten the window and slide every + // later line onto the wrong position — a frame pointing at source it did not throw from. + const source = [ + 'const secret = `a', + 'b', + 'c`;', + 'throw new Error("boom");', + 'const tail = 1;', + ].join('\n'); + const context = readContext(source, 4, 3, 200); + expect(context?.line).toBe('throw new Error("boom");'); + expect(context?.pre).toHaveLength(3); + expect(context?.post).toEqual(['const tail = 1;']); + expect(context?.pre?.join('\n')).not.toContain('b'); + }); +}); + describe('isReadablePath', () => { it.each([ ['/app/src/index.js', true], @@ -205,3 +264,43 @@ describe('createSourceContextEnricher — a working directory that has been dele } }); }); + +describe('the background worker vendors an equivalent copy of the redaction artifact', () => { + // WHY HERE. `packages/protocol` owns `source-line-redaction.vectors.json` and runs its vectors, but + // it compiles with no Node types (`types: []`) and so cannot open a file. This tier can, and it is + // the SDK-side producer of the very windows the worker REPLACES on a remap — so the question "do the + // two repos still agree?" is at home next to `readContext`. + // + // The one hand step left in the loop, so it gets a test rather than a comment. It can only run where + // the worker checkout is present — a developer machine — so it SKIPS elsewhere rather than passing + // silently, and says so. The behavioural half (the vectors) is enforced in BOTH CIs independently, + // which is what stops a stale copy from being a silent divergence rather than merely an old one. + // + // CONTENT, not bytes: `pnpm lint:fix` reformats the canonical JSON (biome collapses the short + // arrays), and a byte comparison duly went red on a re-format that changed no vector. A guard that + // fires on whitespace gets suppressed, and then it is not a guard. + const require_ = createRequire(import.meta.url); + // Through the package's own `exports` map, so a rename that forgets to update it fails HERE rather + // than leaving this test quietly reading a path that no consumer can reach. + const canonical = JSON.parse( + readFileSync(require_.resolve('@bugsee/protocol/source-line-redaction.vectors.json'), 'utf8'), + ); + const workerRepo = + process.env.BUGSEE_WORKER_REPO ?? + join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', 'worker'); + const vendored = join(workerRepo, 'symbolfiles', 'source_line_redaction.vectors.json'); + const present = existsSync(vendored); + + it('the canonical artifact is where this test thinks it is', () => { + // Otherwise a moved or renamed file would make the comparison below vacuously pass. + expect(canonical.vectors.length).toBeGreaterThan(25); + }); + + it.skipIf(!present)('carries the same definitions and vectors as the canonical file', () => { + expect(JSON.parse(readFileSync(vendored, 'utf8'))).toEqual(canonical); + }); + + it.runIf(!present)('is not checkable here — recorded, not silently skipped', () => { + expect(present).toBe(false); + }); +}); diff --git a/packages/node/src/source-context.ts b/packages/node/src/source-context.ts index ac489e1c..84de1e41 100644 --- a/packages/node/src/source-context.ts +++ b/packages/node/src/source-context.ts @@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import process from 'node:process'; import type { FrameContext, StackFrame } from '@bugsee/core'; +import { redactSourceLines } from '@bugsee/protocol'; // Source context: the line that threw, plus a little either side, read from disk at report time. // Node-only by nature — core is runtime-portable and has no filesystem. @@ -68,11 +69,23 @@ export function readContext( if (index < 0 || index >= lines.length) { return undefined; } + const start = Math.max(0, index - contextLines); + // REDACT BEFORE CLIPPING. `redactSourceLines` is the shared rule (`@bugsee/protocol`) that also runs + // in the background worker when it rebuilds this window from a sourcemap — see that module's header + // for what it does and, just as deliberately, what it does not. Clipping first would cut a long line + // mid-literal, leaving a prefix with no closing quote for the assignment pass to match and no + // complete shape for the shape pass: a truncated credential, shipped. + // + // The whole window is passed at once because the rule is window-scoped — a wrapped assignment puts + // the key on one line and the literal on the next — and it returns exactly as many lines as it was + // given, so the positions below stay aligned. + const sourceWindow = redactSourceLines(lines.slice(start, index + 1 + contextLines)); + const at = index - start; const clip = (value: string): string => value.length > maxLineLength ? `${value.slice(0, maxLineLength)}…` : value; - const context: FrameContext = { line: clip(lines[index] as string) }; - const pre = lines.slice(Math.max(0, index - contextLines), index).map(clip); - const post = lines.slice(index + 1, index + 1 + contextLines).map(clip); + const context: FrameContext = { line: clip(sourceWindow[at] as string) }; + const pre = sourceWindow.slice(0, at).map(clip); + const post = sourceWindow.slice(at + 1).map(clip); // Omitted rather than empty at the top or bottom of a file — an empty array on the wire says // "we looked and there was nothing", which is not the same as "there is no line 0". if (pre.length > 0) { diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 778ccd46..e129d7ce 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -12,11 +12,13 @@ "types": "./src/index.ts", "import": "./src/index.ts" }, - "./upload-contract.schema.json": "./upload-contract.schema.json" + "./upload-contract.schema.json": "./upload-contract.schema.json", + "./source-line-redaction.vectors.json": "./source-line-redaction.vectors.json" }, "files": [ "dist", - "upload-contract.schema.json" + "upload-contract.schema.json", + "source-line-redaction.vectors.json" ], "sideEffects": false, "scripts": { @@ -44,7 +46,8 @@ "default": "./dist/index.cjs" } }, - "./upload-contract.schema.json": "./upload-contract.schema.json" + "./upload-contract.schema.json": "./upload-contract.schema.json", + "./source-line-redaction.vectors.json": "./source-line-redaction.vectors.json" } } } diff --git a/packages/protocol/source-line-redaction.vectors.json b/packages/protocol/source-line-redaction.vectors.json new file mode 100644 index 00000000..7092a155 --- /dev/null +++ b/packages/protocol/source-line-redaction.vectors.json @@ -0,0 +1,291 @@ +{ + "$comment": [ + "Shared behavioural corpus for source-context secret redaction. CANONICAL COPY — this file lives in", + "the JavaScript SDK (github.com/bugsee/bugsee-javascript) at packages/protocol/, and is VENDORED", + "byte-for-byte into the background worker (github.com/bugsee/bugsee-background-worker) at", + "symbolfiles/source_line_redaction.vectors.json.", + "", + "WHY IT EXISTS. A crash frame's source window is produced on BOTH sides: the SDK reads it off disk", + "at crash time (packages/node/src/source-context.ts) and the worker REBUILDS it from a sourcemap's", + "sourcesContent on a remap (symbolfiles/sourcemap.py), which is the common path for web frames.", + "Two implementations of one redaction rule drift, and only one of them ever gets fixed. Both test", + "suites run this corpus, so a divergence turns one of the two CIs red instead of shipping a secret.", + "", + "Each vector is a whole source WINDOW (the lines in order), because the rule is window-scoped: a", + "value may sit on the line after its key. `expected` must have the same length as `lines`." + ], + "definitions": { + "$comment": [ + "MIRRORED FROM `packages/protocol/src/sensitive.ts`, and asserted equal to it by", + "`src/source-context-redaction.test.ts` — so this copy cannot drift from the SDK inside this repo.", + "The worker READS these at import time rather than restating them, so it cannot drift either. The", + "only hand step left in the loop is keeping the worker’s vendored copy of this file up to date." + ], + "sensitiveKeySubstrings": [ + "password", + "passwd", + "pass", + "secret", + "client_secret", + "token", + "access_token", + "refresh_token", + "id_token", + "auth_token", + "api_key", + "apikey", + "authorization", + "credit_card", + "creditcard", + "card_number", + "cardnumber", + "cvv", + "cvc", + "cvv2", + "ssn", + "social_security", + "pin", + "private_key", + "privatekey", + "jwt", + "bearer", + "bearer_token", + "auth", + "creds", + "credentials", + "session_token", + "sessionid", + "phpsessid", + "jsessionid", + "connect.sid", + "csrf", + "csrf_token", + "_csrf", + "xsrf_token", + "code_verifier", + "client_assertion", + "signature", + "hmac", + "mfa_token", + "otp", + "totp", + "routing_number", + "account_number", + "iban", + "swift", + "bank_account", + "dob", + "date_of_birth", + "passport", + "passport_number", + "national_id", + "tax_id", + "ein" + ], + "sensitiveHeaders": [ + "authentication", + "authorization", + "cookie", + "proxy-authorization", + "proxy-cookie", + "set-cookie", + "x-amz-credential", + "x-amz-security-token", + "x-amz-signature", + "x-api-key", + "x-auth-token", + "x-clerk-session-token", + "x-csrf-token", + "x-forwarded-authorization", + "x-forwarded-for", + "x-goog-api-key", + "x-goog-iam-authorization-token", + "x-ms-token-aad-access-token", + "x-ms-token-aad-id-token", + "x-ms-token-aad-refresh-token", + "x-okapi-token", + "x-original-authorization", + "x-real-ip", + "x-shopify-access-token", + "x-supabase-auth", + "x-vault-token", + "x-vault-wrap-ttl" + ] + }, + "vectors": [ + { + "name": "const assignment to a sensitive identifier, double quotes", + "lines": ["const apiKey = \"sk-live-abcdef\";"], + "expected": ["const apiKey = \"\";"] + }, + { + "name": "let assignment, single quotes", + "lines": ["let password = 'hunter2';"], + "expected": ["let password = '';"] + }, + { + "name": "var assignment, template literal", + "lines": ["var secret = `s3cr3t`;"], + "expected": ["var secret = ``;"] + }, + { + "name": "re-assignment with no declaration keyword", + "lines": ["apiKey = \"abc\";"], + "expected": ["apiKey = \"\";"] + }, + { + "name": "object literal, unquoted key", + "lines": [" apiKey: 'abc',"], + "expected": [" apiKey: '',"] + }, + { + "name": "object literal, double-quoted key (JSON shape)", + "lines": [" \"password\": \"abc\","], + "expected": [" \"password\": \"\","] + }, + { + "name": "object literal, single-quoted key", + "lines": [" 'token': \"abc\","], + "expected": [" 'token': \"\","] + }, + { + "name": "dotted property assignment", + "lines": ["config.apiKey = \"abc\";"], + "expected": ["config.apiKey = \"\";"] + }, + { + "name": "this-property assignment", + "lines": ["this.password = \"abc\";"], + "expected": ["this.password = \"\";"] + }, + { + "name": "bracket property assignment with a quoted key", + "lines": ["obj[\"password\"] = \"abc\";"], + "expected": ["obj[\"password\"] = \"\";"] + }, + { + "name": "SCREAMING_SNAKE env-style key", + "lines": ["process.env.API_KEY = \"abc\";"], + "expected": ["process.env.API_KEY = \"\";"] + }, + { + "name": "dashed header-style key", + "lines": [" \"x-api-key\": \"abc\","], + "expected": [" \"x-api-key\": \"\","] + }, + { + "name": "default parameter value", + "lines": ["function f(apiKey = \"abc\") {}"], + "expected": ["function f(apiKey = \"\") {}"] + }, + { + "name": "strict-equality comparison against a hardcoded credential", + "lines": ["if (password === \"abc\") {}"], + "expected": ["if (password === \"\") {}"] + }, + { + "name": "loose-equality comparison against a hardcoded credential", + "lines": ["if (token == \"abc\") {}"], + "expected": ["if (token == \"\") {}"] + }, + { + "name": "numeric literal assigned to a sensitive identifier", + "lines": ["const cvv = 123;"], + "expected": ["const cvv = ;"] + }, + { + "name": "negative numeric literal", + "lines": ["const pin = -1234;"], + "expected": ["const pin = ;"] + }, + { + "name": "every sensitive assignment on the line, not only the first", + "lines": ["{ apiKey: \"a\", user: \"u\", password: \"p\" }"], + "expected": ["{ apiKey: \"\", user: \"u\", password: \"\" }"] + }, + { + "name": "escaped quote inside the literal does not end it early", + "lines": ["const password = \"a\\\"b\";"], + "expected": ["const password = \"\";"] + }, + { + "name": "value on the line after its key is still redacted", + "lines": ["const apiKey =", " \"sk-live-abcdef\";"], + "expected": ["const apiKey =", " \"\";"] + }, + { + "name": "multi-line template literal keeps the window's line count", + "lines": ["const secret = `a", "b", "c`;", "after"], + "expected": ["const secret = `", "", "`;", "after"] + }, + { + "name": "non-sensitive identifier keeps its value", + "lines": ["const greeting = \"hello sk-live\";"], + "expected": ["const greeting = \"hello sk-live\";"] + }, + { + "name": "arrow function is not an assignment", + "lines": ["items.map((token) => \"x\")"], + "expected": ["items.map((token) => \"x\")"] + }, + { + "name": "bare single-parameter arrow is not an assignment either", + "lines": ["items.map(token => \"x\")"], + "expected": ["items.map(token => \"x\")"] + }, + { + "name": "non-literal right-hand side is left intact", + "lines": ["const apiKey = readKeyFromVault();"], + "expected": ["const apiKey = readKeyFromVault();"] + }, + { + "name": "ORDINARY identifier containing a sensitive substring is over-redacted (documented cost)", + "lines": ["const author = \"Ada\";"], + "expected": ["const author = \"\";"] + }, + { + "name": "JWT with no sensitive key name", + "lines": ["send({ a: \"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc\" });"], + "expected": ["send({ a: \"\" });"] + }, + { + "name": "AWS access key id with no sensitive key name", + "lines": ["const id = \"AKIAIOSFODNN7EXAMPLE\";"], + "expected": ["const id = \"\";"] + }, + { + "name": "Stripe live secret key with no sensitive key name", + "lines": ["stripe(\"sk_live_4eC39HqLyjWDarjtT1zdp7dc\");"], + "expected": ["stripe(\"\");"] + }, + { + "name": "GitHub token with no sensitive key name", + "lines": ["const t = \"ghp_016C7869B9C1E0B9A1C6D0E5F4A3B2C1D0E9F8\";"], + "expected": ["const t = \"\";"] + }, + { + "name": "long ordinary hex digest is KEPT — there is no entropy heuristic", + "lines": [ + "const sha = \"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\";" + ], + "expected": [ + "const sha = \"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\";" + ] + }, + { + "name": "blank lines survive as blank lines", + "lines": ["", "x", ""], + "expected": ["", "x", ""] + }, + { + "name": "an empty window redacts to an empty window", + "lines": [], + "expected": [] + }, + { + "name": "adjacent lines each keep their own string literal", + "lines": ["const password = \"abc\";", "const other = \"keep\";"], + "expected": ["const password = \"\";", "const other = \"keep\";"] + } + ] +} diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index dcf2d37e..55734462 100644 --- a/packages/protocol/src/index.ts +++ b/packages/protocol/src/index.ts @@ -46,6 +46,7 @@ export { SENSITIVE_KEY_SUBSTRINGS, } from './sensitive'; export { redactShapes, type ShapeRedactionOptions } from './shapes'; +export { redactSourceLines } from './source-context-redaction'; export { bytesToMegabytes } from './units'; export { sanitizeErrorMessage, sanitizeUrl } from './url'; export type { diff --git a/packages/protocol/src/source-context-redaction.test.ts b/packages/protocol/src/source-context-redaction.test.ts new file mode 100644 index 00000000..358cd0f5 --- /dev/null +++ b/packages/protocol/src/source-context-redaction.test.ts @@ -0,0 +1,232 @@ +import { describe, expect, it } from 'vitest'; +import ARTIFACT from '../source-line-redaction.vectors.json'; +import { REDACTED, redactSourceLines, SENSITIVE_HEADERS, SENSITIVE_KEY_SUBSTRINGS } from './index'; +import { expectLinearIn } from './linear-time.test-helper'; + +// The corpus is the CROSS-REPO drift guard. Both this suite and the background worker's +// `test_source_line_redaction.py` run the SAME file, so the two implementations of this rule cannot +// disagree without one of the two CIs going red. See `source-line-redaction.vectors.json`. +// +// IMPORTED, not read off disk: this package compiles with `types: []` and `lib: ["ES2023"]` — no Node, +// no DOM — which is the rule that keeps a runtime-portable tier portable, and a test is not an excuse +// to break it. The one check that genuinely needs a filesystem (does the worker's vendored copy still +// match?) therefore lives in `@bugsee/node`, next to the SDK-side producer of these windows. + +interface Vector { + readonly name: string; + readonly lines: readonly string[]; + readonly expected: readonly string[]; +} + +const DOC = ARTIFACT as { + definitions: { sensitiveKeySubstrings: string[]; sensitiveHeaders: string[] }; + vectors: Vector[]; +}; +const vectors: readonly Vector[] = DOC.vectors; + +describe('the shared artifact cannot drift from this package', () => { + // The artifact carries the denylists so the worker can READ them instead of restating them — which + // only helps if the artifact itself still says what `sensitive.ts` says. These two assertions are the + // in-repo half of the drift guard; the cross-repo half is the vendored-copy check below. + it('carries exactly the key substrings this package defines, in order', () => { + expect(DOC.definitions.sensitiveKeySubstrings).toEqual([...SENSITIVE_KEY_SUBSTRINGS]); + }); + + it('carries exactly the sensitive headers this package defines', () => { + expect(DOC.definitions.sensitiveHeaders).toEqual([...SENSITIVE_HEADERS].sort()); + }); +}); + +describe('redactSourceLines — the shared cross-repo corpus', () => { + it('has vectors at all, so an empty file cannot pass as agreement', () => { + expect(vectors.length).toBeGreaterThan(25); + }); + + it.each(vectors.map((v) => [v.name, v] as const))('%s', (_name, vector) => { + expect(redactSourceLines(vector.lines)).toEqual([...vector.expected]); + }); +}); + +describe('redactSourceLines — assignment to a sensitive identifier', () => { + it.each([ + ['const', `const apiKey = "sk-live-abcdef";`, `const apiKey = "${REDACTED}";`], + ['let', `let password = 'hunter2';`, `let password = '${REDACTED}';`], + ['var, backtick', 'var secret = `s3cr3t`;', `var secret = \`${REDACTED}\`;`], + ['bare re-assign', `apiKey = "abc";`, `apiKey = "${REDACTED}";`], + ['object key, unquoted', `{ apiKey: 'abc' }`, `{ apiKey: '${REDACTED}' }`], + ['object key, quoted', `{ "password": "abc" }`, `{ "password": "${REDACTED}" }`], + ['object key, single-quoted', `{ 'token': "abc" }`, `{ 'token': "${REDACTED}" }`], + ['dotted property', `config.apiKey = "abc";`, `config.apiKey = "${REDACTED}";`], + ['this property', `this.password = "abc";`, `this.password = "${REDACTED}";`], + ['env lookup shape', `process.env.API_KEY = "abc";`, `process.env.API_KEY = "${REDACTED}";`], + ['bracket property', `obj["password"] = "abc";`, `obj["password"] = "${REDACTED}";`], + ['default parameter', `function f(apiKey = "abc") {}`, `function f(apiKey = "${REDACTED}") {}`], + ['strict equality', `if (password === "abc") {}`, `if (password === "${REDACTED}") {}`], + ['loose equality', `if (token == "abc") {}`, `if (token == "${REDACTED}") {}`], + ['dashed key', `{ "x-api-key": "abc" }`, `{ "x-api-key": "${REDACTED}" }`], + ['numeric literal', `const cvv = 123;`, `const cvv = ${REDACTED};`], + ['negative numeric', `const pin = -1234;`, `const pin = ${REDACTED};`], + ['decimal numeric', `const pin = 12.5;`, `const pin = ${REDACTED};`], + ])('redacts %s', (_case, input, expected) => { + expect(redactSourceLines([input])).toEqual([expected]); + }); + + it('redacts EVERY sensitive assignment on one line, not just the first', () => { + expect(redactSourceLines([`{ apiKey: "a", user: "u", password: "p" }`])).toEqual([ + `{ apiKey: "${REDACTED}", user: "u", password: "${REDACTED}" }`, + ]); + }); + + it('keeps the value when the identifier is not sensitive', () => { + expect(redactSourceLines([`const greeting = "hello sk-live";`])).toEqual([ + `const greeting = "hello sk-live";`, + ]); + }); + + it('does not treat an arrow function as an assignment', () => { + // `=>` must not read as `=`, or every one-line arrow returning a constant would be redacted. + // A PARENTHESISED parameter list is not the case that exercises the guard — the `)` between the + // name and the `=>` already blocks the match — so the bare single-parameter form is the one that + // pins it, and the parenthesised form rides along to show the common spelling is safe too. + expect(redactSourceLines([`items.map((token) => "x")`])).toEqual([`items.map((token) => "x")`]); + expect(redactSourceLines([`items.map(token => "x")`])).toEqual([`items.map(token => "x")`]); + expect(redactSourceLines([`const f = password => "x";`])).toEqual([ + `const f = password => "x";`, + ]); + }); + + it('leaves a non-literal right-hand side alone', () => { + // Redacting an identifier or a call discloses nothing and destroys the only useful part of the line. + expect(redactSourceLines([`const apiKey = readKeyFromVault();`])).toEqual([ + `const apiKey = readKeyFromVault();`, + ]); + }); + + it('does not match a sensitive substring glued to a longer run to its LEFT', () => { + // The anchor: `notapass` is one identifier, and `isSensitiveKey` sees the whole of it (which does + // match, by substring) — the point is that the scan starts at the run, not inside it. + expect(redactSourceLines([`const xpasswordx = "abc";`])).toEqual([ + `const xpasswordx = "${REDACTED}";`, + ]); + }); + + it('keeps escaped quotes inside a redacted literal from ending it early', () => { + expect(redactSourceLines([`const password = "a\\"b";`])).toEqual([ + `const password = "${REDACTED}";`, + ]); + }); + + it('over-redacts an ordinary identifier that CONTAINS a sensitive substring', () => { + // Documented cost of the ONE shared definition (`isSensitiveKey`, substring-matched): `author` + // contains `auth`. Narrowing it here would create the second definition CLAUDE.md forbids. + expect(redactSourceLines([`const author = "Ada";`])).toEqual([`const author = "${REDACTED}";`]); + }); +}); + +describe('redactSourceLines — credential shapes with no sensitive key name', () => { + it.each([ + [ + 'JWT', + `fetch(url, { headers: { a: "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc" } })`, + `fetch(url, { headers: { a: "${REDACTED}" } })`, + ], + ['AWS access key id', `const id = "AKIAIOSFODNN7EXAMPLE";`, `const id = "${REDACTED}";`], + ['Stripe live key', `stripe("sk_live_4eC39HqLyjWDarjtT1zdp7dc");`, `stripe("${REDACTED}");`], + [ + 'GitHub token', + `const t = "ghp_016C7869B9C1E0B9A1C6D0E5F4A3B2C1D0E9F8";`, + `const t = "${REDACTED}";`, + ], + ])('redacts a %s anywhere on the line', (_case, input, expected) => { + expect(redactSourceLines([input])).toEqual([expected]); + }); + + it('leaves a long ordinary hex string alone — no entropy heuristic', () => { + // The DELIBERATE limit. See the module header: entropy thresholds mis-fire on hashes, minified + // bundles, UUIDs and asset digests, which is most of the code a crash window ever shows. + const line = `const sha = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";`; + expect(redactSourceLines([line])).toEqual([line]); + }); +}); + +describe('redactSourceLines — window shape', () => { + it('returns exactly as many lines as it was given', () => { + const input = [`a`, `const password = "p";`, `b`]; + expect(redactSourceLines(input)).toHaveLength(3); + }); + + it('returns an empty array for an empty window rather than one empty line', () => { + expect(redactSourceLines([])).toEqual([]); + }); + + it('preserves a blank line rather than collapsing it', () => { + expect(redactSourceLines([``, `x`, ``])).toEqual([``, `x`, ``]); + }); + + it('redacts a value that sits on the line AFTER its key, keeping the line count', () => { + // The window is scanned whole, so a wrapped assignment cannot hide a secret on a continuation line. + expect(redactSourceLines([`const apiKey =`, ` "sk-live-abcdef";`])).toEqual([ + `const apiKey =`, + ` "${REDACTED}";`, + ]); + }); + + it('preserves the line count of a redacted MULTI-LINE template literal', () => { + const out = redactSourceLines(['const secret = `a', 'b', 'c`;', 'after']); + expect(out).toHaveLength(4); + expect(out[3]).toBe('after'); + expect(out.join('\n')).toContain(REDACTED); + expect(out.join('\n')).not.toContain('b'); + }); + + it('does not leak across the window boundary: a lone closing quote stays literal', () => { + expect(redactSourceLines([`const password = "abc";`, `const other = "keep";`])).toEqual([ + `const password = "${REDACTED}";`, + `const other = "keep";`, + ]); + }); + + it('does not mutate the array it was given', () => { + const input = [`const password = "p";`]; + redactSourceLines(input); + expect(input).toEqual([`const password = "p";`]); + }); +}); + +describe('redactSourceLines — cost on hostile input', () => { + // This runs BEFORE the SDK clips a line to 200 characters (a secret past the clip point would be cut + // in half and ship as a prefix otherwise), so the input can be a whole minified bundle line. + it('is linear in the length of one enormous identifier run', () => { + // The shape the anchor exists for: without it every offset inside the run starts a fresh scan. + expectLinearIn( + (n) => [`${'a'.repeat(n)};`], + (window) => { + redactSourceLines(window); + }, + 128_000, + ); + }, 30_000); + + it('is linear in the length of whitespace between a sensitive key and its operator', () => { + // Two adjacent unbounded whitespace runs in the separator would backtrack here. + expectLinearIn( + (n) => [`password${' '.repeat(n)}= x`], + (window) => { + redactSourceLines(window); + }, + 128_000, + ); + }, 30_000); + + it('is linear in the length of an unterminated string literal', () => { + // A quote with no partner makes the unrolled literal scan to end-of-input and fail, at every + // sensitive key before it. + expectLinearIn( + (n) => [`password = "${'x'.repeat(n)}`], + (window) => { + redactSourceLines(window); + }, + 128_000, + ); + }, 30_000); +}); diff --git a/packages/protocol/src/source-context-redaction.ts b/packages/protocol/src/source-context-redaction.ts new file mode 100644 index 00000000..6e95992f --- /dev/null +++ b/packages/protocol/src/source-context-redaction.ts @@ -0,0 +1,145 @@ +import { isSensitiveHeader, isSensitiveKey, REDACTED } from './sensitive'; +import { redactShapes } from './shapes'; + +// Secret redaction for a crash frame's SOURCE CONTEXT — the lines around the throwing line. +// +// THE DEFECT THIS CLOSES. Those lines shipped verbatim, so a hardcoded credential on or near the +// throwing line was disclosed in plaintext — while the SAME value held in a local variable arrived as +// ``, because local-variable capture (packages/node/src/local-variables.ts) scrubs by key +// name. One value, two answers, decided by which feature happened to see it. +// +// WHAT "SCRUB A SOURCE LINE" MEANS HERE — two passes, both reusing definitions that already exist: +// +// 1. SENSITIVE ASSIGNMENT. A string, template or numeric LITERAL whose key/identifier satisfies +// `isSensitiveKey` is replaced by ``. That is the SAME predicate local-variable capture, +// network body/query scrubbing and span sanitizing use, so the inconsistency is closed by +// construction rather than by a second list that would drift (CLAUDE.md: "One definition of +// sensitive field ... shape it, never restate it"). +// +// 2. CREDENTIAL SHAPE. `redactShapes` — the package's existing shape pass (anchored JWT, AWS access +// key ids, Stripe live/webhook keys, GitHub tokens), already applied to network values, error +// messages and stack text. Reused wholesale; NO new pattern is introduced here. +// +// WHAT IS DELIBERATELY NOT DONE: entropy thresholds, "long base64/hex run", generic 32-or-40-character +// alphanumeric rules. Those are where the false positives live, and the code a crash window shows is +// exactly the code full of hashes, digests, UUIDs, minified identifiers and asset fingerprints. The +// published comparisons of secret scanners are consistent about this: entropy-and-broad-regex tools +// have high recall and low precision, and the precise rules are the ones with a provider-specific +// prefix — which is exactly the set `redactShapes` already carries. A false positive here silently +// destroys the feature (a redacted line tells the reader nothing), so the extra recall is not free. +// +// ORDER MATTERS: this runs BEFORE the caller clips a line to `maxLineLength`. Clipping first would cut +// a long line mid-secret, leaving a prefix with no closing quote for pass 1 to match and no complete +// shape for pass 2 — a truncated credential is still a credential. Clipping after means the input can +// be a whole minified bundle line, which is why the pattern below is anchored (see `SENSITIVE_ASSIGNMENT`). +// +// MIRRORED IN THE BACKGROUND WORKER. A remapped frame's window is rebuilt server-side from the +// sourcemap's `sourcesContent` (`symbolfiles/sourcemap.py`), which is the common path for web frames, +// so the same rule has a Python twin. The two are held together by the shared behavioural corpus +// `source-line-redaction.vectors.json`, which BOTH test suites run — see that file's header. + +/** + * One JS string literal, in each of the three quote styles. + * + * Written in Friedl's unrolled form (`[^q\\]*(?:\\[\s\S][^q\\]*)*`) rather than the lazy `(?:\\.|.)*?`: + * the unrolled form has exactly one way to match any input, so there is nothing for the engine to + * backtrack through. `[\s\S]` rather than `.` so an escape immediately before a newline — reachable + * because this scans a whole multi-line window — consumes the newline instead of failing the escape. + */ +const STRING_LITERAL = + '"[^"\\\\]*(?:\\\\[\\s\\S][^"\\\\]*)*"' + + "|'[^'\\\\]*(?:\\\\[\\s\\S][^'\\\\]*)*'" + + '|`[^`\\\\]*(?:\\\\[\\s\\S][^`\\\\]*)*`'; + +/** A numeric literal. `pin`, `cvv` and `ssn` are routinely written unquoted. */ +const NUMERIC_LITERAL = '-?\\d[\\d_]*(?:\\.\\d+)?'; + +/** + * ``, ANCHORED — which is what keeps it linear. + * + * Group 1 is the anchor: a key starts a token, so a run of identifier characters is scanned from its + * START and once only. Without it every offset inside one enormous minified identifier would begin a + * fresh scan to the end of the run, which is the O(n²) `redactShapes` documents for the same reason. + * The anchor is put back through `$1` — the pattern consumes it. + * + * Group 3 (the separator) accepts what a key can be followed by before its value: + * - `"]` / `']` — the tail of `obj["password"]` + * - `"` / `'` — the closing quote of a quoted object key + * - `:` or 1-3 `=`, so `:`, `=`, `==` and `===` all count. + * + * An ARROW FUNCTION is excluded structurally rather than by a lookahead. `(?!=|>)` was written here + * first, on the assumption that `token => "x"` would otherwise read as an assignment; the mutator loop + * disproved it — removing the lookahead changed no test outcome, because between the `=` and the value + * the pattern allows only whitespace, and `>` is not whitespace and cannot begin a literal. The same + * argument covers `====`. A guard that cannot fire is not protection, so it is gone and the arrow cases + * stay in the suite as the pins that say WHY it is safe to be absent. + * + * The `\]` alternative is grouped so it cannot decompose into two adjacent `\s*` — two adjacent + * unbounded whitespace runs are ambiguous, and ambiguity is what backtracking costs. + */ +const SENSITIVE_ASSIGNMENT = new RegExp( + '(^|[^A-Za-z0-9_$-])' + + '([A-Za-z0-9_$-]+)' + + '((?:["\']?\\s*\\])?["\']?\\s*(?::|={1,3})\\s*)' + + `(${STRING_LITERAL}|${NUMERIC_LITERAL})`, + 'g', +); + +/** + * Is this key one whose literal value must not ship? + * + * BOTH shared predicates, because a source line is the one place the two vocabularies meet: an object + * literal in a `fetch` call is where a HEADER name appears as a key (`{ "x-api-key": "…" }`), and + * `isSensitiveKey`'s substring list carries `api_key`/`apikey` but not the hyphenated header spelling. + * Consulting `isSensitiveHeader` as well reuses the second existing definition rather than widening + * the first — which would change what every network body and query string redacts, a separate call. + */ +function isSensitiveName(name: string): boolean { + return isSensitiveKey(name) || isSensitiveHeader(name); +} + +/** + * `` in place of `value`, keeping the quote style AND the number of newlines the value held. + * + * The newline count is load-bearing, not cosmetic: the caller splits the redacted window back into + * lines and zips them against `pre`/`line`/`post` by position. A multi-line template literal collapsed + * to a single `` would shorten the window and slide every following line onto the wrong one + * — a frame that then points at source it did not throw from, which is worse than no context at all. + */ +function redactedLiteral(value: string): string { + let newlines = ''; + for (let i = 0; i < value.length; i += 1) { + if (value[i] === '\n') { + newlines += '\n'; + } + } + const quote = value[0] as string; + return quote === '"' || quote === "'" || quote === '`' + ? `${quote}${REDACTED}${newlines}${quote}` + : `${REDACTED}${newlines}`; +} + +/** + * Redact secrets from a source-context WINDOW, returning exactly as many lines as it was given. + * + * Window-scoped rather than line-scoped on purpose: a wrapped assignment puts the key on one line and + * the literal on the next, and a per-line rule would read the continuation as a bare string with no + * key to judge it by — the single most likely way a formatter hides a secret from a scrubber. + */ +export function redactSourceLines(lines: readonly string[]): string[] { + // `[].join('\n')` is `''` and `''.split('\n')` is `['']`, so an empty window would come back as one + // empty line and give a frame a context it does not have. + if (lines.length === 0) { + return []; + } + const assigned = lines + .join('\n') + .replace( + SENSITIVE_ASSIGNMENT, + (match, anchor: string, key: string, separator: string, value: string) => + isSensitiveName(key) ? `${anchor}${key}${separator}${redactedLiteral(value)}` : match, + ); + // Neither pass can add or remove a newline — `redactShapes`'s patterns contain none and `` + // has none — so the split below is guaranteed to return `lines.length` entries. + return redactShapes(assigned).split('\n'); +} From 31b9965ed0287f8db04da1dab86143bda64cd68b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Sun, 6 Sep 2026 11:12:49 +0500 Subject: [PATCH 2/4] fix(protocol): redact the other half of the comparison forms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review P2 on worker PR #53, and it applies to both implementations because they share one definition. The separator accepted `:`, `=`, `==` and `===` only. So `if (password === "abc")` redacted while `if (password !== "abc")` shipped the literal — half of the comparison forms this pass already claimed to cover. Same for `!=`, and for the logical assignments `||=`, `??=`, `&&=` (`apiKey ||= "sk-live-fallback"`), and for `<=`/`>=`. The wrapped form `if (password !==\n "hunter2")` leaked too, which is the very case the window-scoped scan exists for. Shape detection does not cover a generic password or a hyphenated `sk-live-…`. The separator now takes an optional operator prefix: `!`, `||`, `&&`, `??`, `<`, `>`. Eight vectors added to the shared artifact FIRST, since it is what both CIs run and the only thing that stops the two implementations drifting apart on this again — including the wrapped inequality, and an arrow function as the negative case. Widening cannot let an arrow through, and the reason is structural, not a guard: after the `=` the pattern allows only whitespace before the literal, and `>` is neither. Measured — a mutation adding `=` to the prefix class SURVIVES the suite, and the only input it changes is `a ==== "x"`, which is not valid JavaScript. Recorded in both files as an equivalent mutant so nobody re-adds the lookahead that was already removed here for the same reason. 6 mutations across the two implementations, 4 caught, 2 equivalent as above. `pnpm ci:local` green. (One linearity assertion failed once while the worker's suite ran concurrently and passes 3/3 alone — the known wall-clock flake, not backtracking from the wider pattern.) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .../source-line-redaction.vectors.json | 40 +++++++++++++++++++ .../protocol/src/source-context-redaction.ts | 12 +++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/protocol/source-line-redaction.vectors.json b/packages/protocol/source-line-redaction.vectors.json index 7092a155..1e96ad99 100644 --- a/packages/protocol/source-line-redaction.vectors.json +++ b/packages/protocol/source-line-redaction.vectors.json @@ -286,6 +286,46 @@ "name": "adjacent lines each keep their own string literal", "lines": ["const password = \"abc\";", "const other = \"keep\";"], "expected": ["const password = \"\";", "const other = \"keep\";"] + }, + { + "name": "strict inequality against a sensitive identifier", + "lines": ["if (password !== \"hunter2\") {"], + "expected": ["if (password !== \"\") {"] + }, + { + "name": "loose inequality against a sensitive identifier", + "lines": ["if (apiKey != \"sk-live-abcdef\") {"], + "expected": ["if (apiKey != \"\") {"] + }, + { + "name": "inequality wrapped across the window, which is why the scan is window-scoped", + "lines": ["if (password !==", " \"hunter2\") {"], + "expected": ["if (password !==", " \"\") {"] + }, + { + "name": "logical-or assignment of a fallback secret", + "lines": ["apiKey ||= \"sk-live-fallback\";"], + "expected": ["apiKey ||= \"\";"] + }, + { + "name": "nullish assignment of a fallback secret", + "lines": ["password ??= \"admin\";"], + "expected": ["password ??= \"\";"] + }, + { + "name": "logical-and assignment", + "lines": ["token &&= \"replacement\";"], + "expected": ["token &&= \"\";"] + }, + { + "name": "an arrow function is still not an assignment", + "lines": ["const pick = (password) => \"not-a-secret\";"], + "expected": ["const pick = (password) => \"not-a-secret\";"] + }, + { + "name": "greater-or-equal is a comparison, not an assignment, and still redacts", + "lines": ["if (secret >= \"0\") {"], + "expected": ["if (secret >= \"\") {"] } ] } diff --git a/packages/protocol/src/source-context-redaction.ts b/packages/protocol/src/source-context-redaction.ts index 6e95992f..a57c5043 100644 --- a/packages/protocol/src/source-context-redaction.ts +++ b/packages/protocol/src/source-context-redaction.ts @@ -67,6 +67,16 @@ const NUMERIC_LITERAL = '-?\\d[\\d_]*(?:\\.\\d+)?'; * - `"` / `'` — the closing quote of a quoted object key * - `:` or 1-3 `=`, so `:`, `=`, `==` and `===` all count. * + * The separator carries an optional OPERATOR PREFIX. Without it only `:`, `=`, `==` and `===` matched, + * so `if (password !== "hunter2")` shipped the literal while `===` redacted it — half of the comparison + * forms this pass already claimed to cover. `!`, `||`, `&&`, `??` and `<`/`>` are accepted, which adds + * `!=`/`!==`, the logical assignments (`||=`, `??=`, `&&=`) and `<=`/`>=`. + * + * Widening the prefix cannot let an arrow through, and that is structural too: `token => "x"` fails + * because after the `=` the pattern allows only whitespace before the literal, and `>` is neither. A + * mutation adding `=` to the prefix class SURVIVES the suite for that reason — measured, the only input + * it changes is `a ==== "x"`, which is not valid JavaScript. It is an equivalent mutant, not a gap. + * * An ARROW FUNCTION is excluded structurally rather than by a lookahead. `(?!=|>)` was written here * first, on the assumption that `token => "x"` would otherwise read as an assignment; the mutator loop * disproved it — removing the lookahead changed no test outcome, because between the `=` and the value @@ -80,7 +90,7 @@ const NUMERIC_LITERAL = '-?\\d[\\d_]*(?:\\.\\d+)?'; const SENSITIVE_ASSIGNMENT = new RegExp( '(^|[^A-Za-z0-9_$-])' + '([A-Za-z0-9_$-]+)' + - '((?:["\']?\\s*\\])?["\']?\\s*(?::|={1,3})\\s*)' + + '((?:["\']?\\s*\\])?["\']?\\s*(?::|(?:!|\\|\\||&&|\\?\\?|[<>])?={1,3})\\s*)' + `(${STRING_LITERAL}|${NUMERIC_LITERAL})`, 'g', ); From dfbb265fa5463231a4ffaea43d62814d96391015 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Sun, 6 Sep 2026 11:28:21 +0500 Subject: [PATCH 3/4] fix(protocol): redact a TypeScript-typed initializer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review P2 on worker PR #53, both sides again since the definition is shared. Only whitespace was allowed between a key and its `:`/`=`, and a type annotation is neither. So on the original TypeScript that `sourcesContent` actually carries: const password: string = "hunter2" shipped verbatim function f(apiKey: string = "abc") shipped verbatim private password: string = "admin" shipped verbatim const pin: number = 1234 shipped verbatim and the worst one, which LOOKS like it worked: const apiKey: "prod" = "actual-secret" -> const apiKey: "" = "actual-secret" the `:` alternative bound the literal TYPE and spared the value. The separator is now an ordered alternation — typed assignment, then bare `:`, then a plain operator — because the typed form must be tried FIRST or the colon keeps winning. The type skip is a negated class that cannot cross `=` and is capped at 200 characters: a type cannot contain `=`, so an unbounded run would be safe to match but not safe to SCAN, and this runs globally over what may be a whole minified bundle line. Eleven vectors first, as before. Two of them exist because a mutation survived and turned out NOT to be equivalent: letting the skip cross an `=` still passes every single-assignment case, but on `const password: string = "leaked" == "y"` it redacts `"y"` and leaves the secret — the same "looks like it worked" shape as the finding itself. That is now pinned. One vector of mine was wrong and was corrected against the existing convention rather than the other way round: a numeric literal redacts unquoted (`= `, not `= ""`). Measured after the change: 2k/20k/100k-character lines with no `=` scan in 0.24/2.19/10.98 ms — linear, so the bounded skip did not make it quadratic. 7 mutations, all caught. `pnpm ci:local` green. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .../source-line-redaction.vectors.json | 55 +++++++++++++++++++ .../protocol/src/source-context-redaction.ts | 21 ++++++- 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/packages/protocol/source-line-redaction.vectors.json b/packages/protocol/source-line-redaction.vectors.json index 1e96ad99..fd7d0216 100644 --- a/packages/protocol/source-line-redaction.vectors.json +++ b/packages/protocol/source-line-redaction.vectors.json @@ -326,6 +326,61 @@ "name": "greater-or-equal is a comparison, not an assignment, and still redacts", "lines": ["if (secret >= \"0\") {"], "expected": ["if (secret >= \"\") {"] + }, + { + "name": "typed const initializer", + "lines": ["const password: string = \"hunter2\";"], + "expected": ["const password: string = \"\";"] + }, + { + "name": "typed default parameter", + "lines": ["function f(apiKey: string = \"abc\") {"], + "expected": ["function f(apiKey: string = \"\") {"] + }, + { + "name": "typed class field with a modifier", + "lines": ["private password: string = \"admin\";"], + "expected": ["private password: string = \"\";"] + }, + { + "name": "typed numeric initializer", + "lines": ["const pin: number = 1234;"], + "expected": ["const pin: number = ;"] + }, + { + "name": "a LITERAL type must not be mistaken for the value it annotates", + "lines": ["const apiKey: \"prod\" = \"actual-secret\";"], + "expected": ["const apiKey: \"prod\" = \"\";"] + }, + { + "name": "a generic type between the key and its value", + "lines": ["const secret: Record = \"nope\";"], + "expected": ["const secret: Record = \"\";"] + }, + { + "name": "a typed initializer wrapped across the window", + "lines": ["const password: string =", " \"hunter2\";"], + "expected": ["const password: string =", " \"\";"] + }, + { + "name": "an object key is still an object key, with no assignment after it", + "lines": ["{ apiKey: \"sk-live-abcdef\" }"], + "expected": ["{ apiKey: \"\" }"] + }, + { + "name": "a type annotation on a NON-sensitive name is left entirely alone", + "lines": ["const total: number = 42;"], + "expected": ["const total: number = 42;"] + }, + { + "name": "a typed initializer compared on the same line redacts the VALUE, not the operand", + "lines": ["const password: string = \"leaked\" == \"y\";"], + "expected": ["const password: string = \"\" == \"y\";"] + }, + { + "name": "the type skip must stop at the first =, or it redacts the far operand and spares the secret", + "lines": ["const apiKey: T = \"real-secret\" === \"compare\";"], + "expected": ["const apiKey: T = \"\" === \"compare\";"] } ] } diff --git a/packages/protocol/src/source-context-redaction.ts b/packages/protocol/src/source-context-redaction.ts index a57c5043..96a16acb 100644 --- a/packages/protocol/src/source-context-redaction.ts +++ b/packages/protocol/src/source-context-redaction.ts @@ -87,10 +87,29 @@ const NUMERIC_LITERAL = '-?\\d[\\d_]*(?:\\.\\d+)?'; * The `\]` alternative is grouped so it cannot decompose into two adjacent `\s*` — two adjacent * unbounded whitespace runs are ambiguous, and ambiguity is what backtracking costs. */ +/** + * How much TypeScript may sit between a key and its `=`. + * + * BOUNDED on purpose. A type annotation cannot contain `=`, so an unbounded run would be safe to + * match but not safe to SCAN: this pattern runs globally over a window that may be a whole minified + * bundle line, and an unbounded negated class is what turns that scan quadratic. 200 characters is + * far past any real annotation; past it the line simply does not redact, which the linearity guards + * exist to keep true. + */ +const MAX_TYPE_ANNOTATION = 200; + +/** The assignment and comparison operators a value can follow. See the separator note below. */ +const ASSIGN_OP = '(?:!|\\|\\||&&|\\?\\?|[<>])?={1,3}'; + const SENSITIVE_ASSIGNMENT = new RegExp( '(^|[^A-Za-z0-9_$-])' + '([A-Za-z0-9_$-]+)' + - '((?:["\']?\\s*\\])?["\']?\\s*(?::|(?:!|\\|\\||&&|\\?\\?|[<>])?={1,3})\\s*)' + + '((?:["\']?\\s*\\])?["\']?\\s*' + + // Ordered: a TYPED assignment must be tried before the bare `:`, or the colon binds a literal + // TYPE and spares the value — `const apiKey: "prod" = "actual-secret"` redacted `"prod"` and + // shipped the secret, which reads as success. + `(?::[^=;\\n]{0,${MAX_TYPE_ANNOTATION}}${ASSIGN_OP}|:|${ASSIGN_OP})` + + '\\s*)' + `(${STRING_LITERAL}|${NUMERIC_LITERAL})`, 'g', ); From 6df8c92a9d0a219a32cf28c854a5a8b9366aa7f3 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Sun, 6 Sep 2026 12:57:51 +0500 Subject: [PATCH 4/4] fix(protocol): end a type annotation at the top-level comma MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review P2 on worker PR #53 — a regression I introduced with the type skip, on the same line it was meant to fix. The skip was "anything that is not `=`", which includes commas, so on a parameter list it was wrong in BOTH directions: function login(user: string, password = "changeme") -> shipped the default function connect(password: string, host = "localhost") -> redacted "localhost" The first is the worse one and it is a leak. The match starts at `user`, runs across the comma, and takes `password`'s default as its own literal. `user` is not sensitive, so the match is returned unchanged — but it has CONSUMED the region, and `password = "changeme"` never gets its own look. It redacted correctly before the previous commit. A comma now ends the type, unless it is inside `<…>` where it belongs to the type. The two branches are disjoint — the first cannot match `<`, so a `<` only ever starts the second — which is what keeps the scan linear. The inner class still allows `<` and `>`, so nesting keeps working: only the last `>` before the operator has to line up, and `Array>` does. Seven vectors first. Three went red; the other four are the cases that already worked and had to keep working — nested generics, `Pick`, a renamed destructure default, and a prettier-wrapped signature. 6 mutations, all caught, including restoring the flat comma-eating skip. Measured, since this pattern got more complex rather than less: 2k/20k/100k-character lines of pure whitespace, pure commas and pure `<` all scan linearly (12.24 / 8.53 / 4.44 ms at 100k). Against the previous pattern on the whitespace case the new one is FASTER — 0.21 ms vs 0.27 ms at 128k — which is how I know the one linearity assertion that failed under load was the known wall-clock flake and not this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .../source-line-redaction.vectors.json | 35 +++++++++++++++++++ .../protocol/src/source-context-redaction.ts | 21 ++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/packages/protocol/source-line-redaction.vectors.json b/packages/protocol/source-line-redaction.vectors.json index fd7d0216..cf0d8534 100644 --- a/packages/protocol/source-line-redaction.vectors.json +++ b/packages/protocol/source-line-redaction.vectors.json @@ -381,6 +381,41 @@ "name": "the type skip must stop at the first =, or it redacts the far operand and spares the secret", "lines": ["const apiKey: T = \"real-secret\" === \"compare\";"], "expected": ["const apiKey: T = \"\" === \"compare\";"] + }, + { + "name": "a typed parameter must not swallow a later default on the same line", + "lines": ["function login(user: string, password = \"changeme\") {"], + "expected": ["function login(user: string, password = \"\") {"] + }, + { + "name": "a sensitive typed parameter does not reach across the comma to the next default", + "lines": ["function connect(password: string, host = \"localhost\") {"], + "expected": ["function connect(password: string, host = \"localhost\") {"] + }, + { + "name": "commas INSIDE a generic are part of the type", + "lines": ["const secret: Pick = \"nope\";"], + "expected": ["const secret: Pick = \"\";"] + }, + { + "name": "a nested generic is still one type", + "lines": ["const secret: Array> = \"nope\";"], + "expected": ["const secret: Array> = \"\";"] + }, + { + "name": "a renamed destructure with a default", + "lines": ["const { password: pw = \"changeme\" } = opts;"], + "expected": ["const { password: pw = \"\" } = opts;"] + }, + { + "name": "a prettier-wrapped signature keeps each parameter on its own line", + "lines": ["function login(", " user: string,", " password = \"changeme\",", ") {"], + "expected": ["function login(", " user: string,", " password = \"\",", ") {"] + }, + { + "name": "a typed parameter followed by a non-sensitive one is left alone entirely", + "lines": ["function f(token: string, retries = 3) {"], + "expected": ["function f(token: string, retries = 3) {"] } ] } diff --git a/packages/protocol/src/source-context-redaction.ts b/packages/protocol/src/source-context-redaction.ts index 96a16acb..41dc2c98 100644 --- a/packages/protocol/src/source-context-redaction.ts +++ b/packages/protocol/src/source-context-redaction.ts @@ -101,6 +101,25 @@ const MAX_TYPE_ANNOTATION = 200; /** The assignment and comparison operators a value can follow. See the separator note below. */ const ASSIGN_OP = '(?:!|\\|\\||&&|\\?\\?|[<>])?={1,3}'; +/** + * A TypeScript type annotation, ending at the TOP-LEVEL comma that separates one parameter from the + * next. + * + * A flat "anything but `=`" skip was wrong in both directions on a parameter list. It let a + * NON-sensitive parameter's type run across the comma and match the next parameter's default — + * `function login(user: string, password = "changeme")` matched at `user`, was returned unchanged + * because `user` is not sensitive, and CONSUMED the region, so `password`'s default never got its own + * look. And it did the reverse too: `function connect(password: string, host = "localhost")` reached + * past the comma and redacted `"localhost"`, which is not a secret. + * + * So a comma ends the type — unless it is inside `<…>`, where it belongs to the type + * (`Record`, `Pick`). The two branches are DISJOINT: the first cannot + * match `<`, so a `<` only ever starts the second, which is what keeps this linear. The inner class + * still allows `<`/`>`, so arbitrary nesting works — only the last `>` before the operator has to line + * up, and `Array>` does. + */ +const TYPE_ANNOTATION = `(?:[^=;,\\n<]|<[^=;\\n]{0,150}>){0,${MAX_TYPE_ANNOTATION}}`; + const SENSITIVE_ASSIGNMENT = new RegExp( '(^|[^A-Za-z0-9_$-])' + '([A-Za-z0-9_$-]+)' + @@ -108,7 +127,7 @@ const SENSITIVE_ASSIGNMENT = new RegExp( // Ordered: a TYPED assignment must be tried before the bare `:`, or the colon binds a literal // TYPE and spares the value — `const apiKey: "prod" = "actual-secret"` redacted `"prod"` and // shipped the secret, which reads as success. - `(?::[^=;\\n]{0,${MAX_TYPE_ANNOTATION}}${ASSIGN_OP}|:|${ASSIGN_OP})` + + `(?::${TYPE_ANNOTATION}${ASSIGN_OP}|:|${ASSIGN_OP})` + '\\s*)' + `(${STRING_LITERAL}|${NUMERIC_LITERAL})`, 'g',