pi-ext bugabingas pi extensions
owned by bugabinga
README Source History Refs Reviews Compare Notes Search Review guide fix(leaks): reject nondurable session ghosts
170e180a5d030eff89cd6efcc9b51cf4b8bf9b75
Oliver Jan Krylow <oliver@bugabinga.net > · 17 Jul 2026
unsigned
Browse files Compare with HEAD
Changed files (18) Diff layout Auto Unified Split
extensions/leaks/__fuzz__/builtins.fuzz.test.ts Modified +38 / −29 text lines
101 101 ["AGE_SECRET_KEY" , ageKey], ["AGE_SECRET_KEY" , ageKey],103 103 "MINISIGN_SECRET_KEY" , "MINISIGN_SECRET_KEY" ,106 - " untrusted comment: minisign encrypted secret key\n", 107 - Buffer .from (v.repeat (4 )).toString ("base64" ),105 + const record = Buffer .alloc (158 , v.charCodeAt (0 ));106 + record.write ("EdScB2" , 0 , "ascii" );107 + return ` untrusted comment: minisign encrypted secret key\n${ record . toString ( "base64 " ) } ` ; 110 110 ] as const ;] as const ;112 - prop ("builtins-positive" , {113 - caseIndex: fc.integer ({ min: 0 , max: cases.length - 1 }),115 - left: fc.constantFrom ("" , "\n" ),116 - right: fc.constantFrom ("" , "\n" ),118 - "detects every built-in family with exact spans" ,119 - ({ caseIndex, body, left, right }) => {120 - const [tag, build] = cases[caseIndex];112 + for (const [index, [tag, build]] of cases.entries ()) {114 + `builtin-${index}-positive` ,117 + left: fc.constantFrom ("" , "\n" ),118 + right: fc.constantFrom ("" , "\n" ),121 + )(`${tag} accepts valid values with exact spans` , ({ body, left, right }) => {121 122 const value = build (body); const value = build (body);122 123 const text = left + value + right; const text = left + value + right;123 124 const span = __test const span = __test125 126 .find ((candidate) => candidate.labels.some ((item) => item.tag === tag)); .find ((candidate) => candidate.labels.some ((item) => item.tag === tag));126 127 expect (span?.value ).toBe (value); expect (span?.value ).toBe (value);127 128 expect (text.slice (span?.start , span?.end)).toBe (value); expect (text.slice (span?.start , span?.end)).toBe (value);131 - prop ("builtins-negative" , {132 - caseIndex: fc.integer ({ min: 0 , max: cases.length - 1 }),134 - })("rejects one-field-invalid built-in near misses" , ({ caseIndex, body }) => {135 - const [tag, build] = cases[caseIndex];136 - const built = build (body);137 - const value = `!${built. slice (1)}` ;140 - .findBuiltinSpans (value)141 - .some ((span) => span.labels.some ((item) => item.tag === tag)),132 + `builtin-${index}-negative` ,135 + )(`${tag} rejects one-field-invalid values` , ({ body }) => {136 + const built = build (body);137 + let value = `!${built. slice (1)}` ;138 + if (tag === "AGE_SECRET_KEY" )139 + value = `${built. slice (0, - 1)}${built. endsWith ("q") ? "p" : "q"}` ;140 + if (tag === "MINISIGN_SECRET_KEY" ) {141 + const [comment, encoded] = built.split ("\n" );142 + const record = Buffer .from (encoded, "base64" );143 + record.write ("XX" , 2 , "ascii" );144 + value = `${comment}\n${record. toString ("base64")}` ;148 + .findBuiltinSpans (value)149 + .some ((span) => span.labels.some ((item) => item.tag === tag)),extensions/leaks/__tests__/__snapshots__/demo-corpus.test.ts.snap Modified +3 / −13 text lines
778 778 "fixtureClass": "crypto", "fixtureClass": "crypto",780 - "MINISIGN_SECRET_KEY",782 - "redactionCount": 1,780 + "redactionCount": 0,783 781 "relativePath": "crypto/minisign.key", "relativePath": "crypto/minisign.key",784 782 "restoredExactly": true, "restoredExactly": true,789 - "MINISIGN_SECRET_KEY",796 786 "fixtureClass": "databases", "fixtureClass": "databases",extensions/leaks/__tests__/corpus.test.ts Modified +6 / −6 text lines
12 12 return result.stdout return result.stdout13 13 .split ("\0" ) .split ("\0" )14 14 .filter (Boolean ) .filter (Boolean )15 - .filter ((file) => / ^ (?:extensions | scripts)\// .test (file))16 - .filter ((file) => ! /(?: ^| \/)(?:README | CHANGELOG | SPEC)\.md $ / .test (file))16 + /\.(?:ts | js | mjs | qml | json | jsonc | kdl | toml | ya ? ml | sh | nu) $ / .test (file),19 - ! /(?:\/__tests__\/ | \/__fixtures__\/ | \/__e2e__\/ | \/static\/)/ .test (file ) , 22 - /\.(?:ts | js | mjs | qml | md | json | jsonc | kdl | toml | ya ? ml | sh | nu) $ / .test (file),20 + ! /(?: ^ test \/| ^ docs \/ | \/ __tests__\/| \/__fixtures__\/ | \/__e2e__\/ | \/static\/)/ .test (extensions/leaks/__tests__/detectors.test.ts Modified +9 / −9 text lines
38 38 return `AGE-SECRET-KEY-1${[ ... data, ... tail]. map ((item) => charset[item]). join ("")}` ; return `AGE-SECRET-KEY-1${[ ... data, ... tail]. map ((item) => charset[item]). join ("")}` ;
41 + function validMinisignSecret () {42 + const record = Buffer .alloc (158 , 7 );43 + record.write ("EdScB2" , 0 , "ascii" );44 + return `untrusted comment: minisign encrypted secret key\n${record. toString ("base64")}` ;41 47 function expectRedacts (text: string , label: string ) {function expectRedacts (text: string , label: string ) {42 48 const engine = new __test.LeaksEngine (); const engine = new __test.LeaksEngine ();43 49 const result = engine.redactText (text, "provider" ); const result = engine.redactText (text, "provider" );112 118 `-----BEGIN ${cosignLabel}-----\nbody\n-----END ${cosignLabel}-----` , `-----BEGIN ${cosignLabel}-----\nbody\n-----END ${cosignLabel}-----` ,113 119 "PuTTY-User-Key-File-3: ssh-rsa\nPrivate-Lines: 1\nbody" , "PuTTY-User-Key-File-3: ssh-rsa\nPrivate-Lines: 1\nbody" ,114 120 validAgeKey (), validAgeKey (),116 - "untrusted comment: minisign encrypted secret key\n" ,117 - Buffer .from ("minisign fixture bytes" .repeat (4 )).toString ("base64" ),121 + validMinisignSecret (),121 124 for (const block of blocks) expectRedacts (block, block.slice (0 , 16 )); for (const block of blocks) expectRedacts (block, block.slice (0 , 16 ));124 127 it ("validates age checksums and minisign payload encoding" , () => { it ("validates age checksums and minisign payload encoding" , () => {125 128 const validAge = validAgeKey (); const validAge = validAgeKey ();126 129 const invalidAge = `${validAge. slice (0, - 1)}q` ; const invalidAge = `${validAge. slice (0, - 1)}q` ;127 - const validMinisign = [ 128 - "untrusted comment: minisign encrypted secret key\n" ,129 - Buffer .from ("minisign fixture bytes" .repeat (4 )).toString ("base64" ),130 + const validMinisign = validMinisignSecret ( ) ; 131 131 const invalidMinisign = `${validMinisign}!` ; const invalidMinisign = `${validMinisign}!` ;133 - expect (__test.findBuiltinSpans (validAge)).toHaveLength (1 );133 + expect (__test.findBuiltinSpans (validAge. toUpperCase ( ))) .toHaveLength (1 );134 134 expect (__test.findBuiltinSpans (invalidAge)).toEqual ([]); expect (__test.findBuiltinSpans (invalidAge)).toEqual ([]);135 135 expect (__test.findBuiltinSpans (validMinisign)).toHaveLength (1 ); expect (__test.findBuiltinSpans (validMinisign)).toHaveLength (1 );136 136 expect (__test.findBuiltinSpans (invalidMinisign)).toEqual ([]); expect (__test.findBuiltinSpans (invalidMinisign)).toEqual ([]);extensions/leaks/__tests__/dotenv.test.ts Modified +2 / −0 text lines
114 114 it ("sensitive key matching ignores case, separators, and numeric suffixes" , () => { it ("sensitive key matching ignores case, separators, and numeric suffixes" , () => {115 115 expect (__test.isSensitiveKey ("client-secret_1" )).toBe (true ); expect (__test.isSensitiveKey ("client-secret_1" )).toBe (true );116 116 expect (__test.isSensitiveKey ("CLIENT_SECRET_2" )).toBe (true ); expect (__test.isSensitiveKey ("CLIENT_SECRET_2" )).toBe (true );
117 + expect (__test.isSensitiveKey ("prod-token-backup" )).toBe (true );118 + expect (__test.isSensitiveKey ("my_token_value" )).toBe (true );117 119 expect (__test.isSensitiveKey ("lineage" )).toBe (false ); expect (__test.isSensitiveKey ("lineage" )).toBe (false );extensions/leaks/__tests__/fuzz-runner.test.ts Modified +8 / −0 text lines
17 17 expect (result.stdout).toMatch (/Tests\s + 1 passed/ ); expect (result.stdout).toMatch (/Tests\s + 1 passed/ );
20 + it ("rejects unknown property selectors" , () => {21 + const result = spawnSync (process .execPath , ["scripts/run_leaks_fuzz.mjs" ], {23 + env: { ... process .env , FC_TEST: "missing-property" },25 + expect (result.status ).toBe (2 );20 28 it ("force-kills timed out children with exit 124" , () => { it ("force-kills timed out children with exit 124" , () => {21 29 const result = spawnSync (process .execPath , ["scripts/run_leaks_fuzz.mjs" ], { const result = spawnSync (process .execPath , ["scripts/run_leaks_fuzz.mjs" ], {22 30 cwd: process .cwd (), cwd: process .cwd (),extensions/leaks/__tests__/lifecycle.test.ts Modified +5 / −0 text lines
50 50 expect (result.issue).toEqual ({ path: "${0}[0]" , label: "TOKEN" }); expect (result.issue).toEqual ({ path: "${0}[0]" , label: "TOKEN" });
52 + engine.hydrateToolInput (53 + "__LEAK_V1_TOKEN_1234567890abcdef1234567890abcdef__" ,53 58 it ("hydrates and inspects property names without prototype mutation" , () => { it ("hydrates and inspects property names without prototype mutation" , () => {extensions/leaks/__tests__/pi-direct.test.ts Modified +110 / −19 text lines
1 - import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs" ;1 + import { appendFileSync , mkdirSync, mkdtempSync, writeFileSync } from "node:fs" ;2 2 import { tmpdir } from "node:os" ;import { tmpdir } from "node:os" ;3 3 import path from "node:path" ;import path from "node:path" ;4 4 import { describe, expect, it, vi } from "vitest" ;import { describe, expect, it, vi } from "vitest" ;10 10 return mkdtempSync (path.join (tmpdir (), "leaks-pi-direct-" )); return mkdtempSync (path.join (tmpdir (), "leaks-pi-direct-" ));13 - function fakePi (appendEntry : ( ) => void = ( ) => { } ) { 14 + appendEntry : (customType?: string , data?: unknown ) => void = () => {},14 16 const handlers = new Map <string , Handler >(); const handlers = new Map <string , Handler >();15 17 const commands = new Map <string , { handler: Handler }>(); const commands = new Map <string , { handler: Handler }>();236 - it ("keeps persistence failures tainted across reload and clear" , async () => {238 - const runtime = fakePi (() => {240 - if (appends === 2 ) throw new Error ("disk full" );242 - leaks (runtime.pi as never );238 + it ("rejects failed-append ghosts after a fresh runtime reload" , async () => {243 239 const view = ui (); const view = ui ();
240 + const sessionFile = path.join (view.ctx.cwd, "session.jsonl" );241 + writeFileSync (sessionFile, "" );242 + const branch: Array <Record <string , unknown >> = [];244 + const append = (customType?: string , data?: unknown ) => {247 + id: `entry-${appends}` ,253 + if (appends === 2 ) throw new Error ("disk full" );254 + appendFileSync (sessionFile, `${ JSON . stringify (entry)}\n` );259 + getBranch : () => branch,260 + getSessionFile : () => sessionFile,244 263 const secret = "ghp_" + "T" .repeat (36 ); const secret = "ghp_" + "T" .repeat (36 );245 - await runtime .handlers.get ("session_start" )?.({}, view . ctx);246 - const failed = await runtime .handlers.get ("before_provider_request" )?.(265 + const first = fakePi (append);266 + leaks (first.pi as never );267 + await first .handlers.get ("session_start" )?.({}, ctx);268 + const failed = await first .handlers.get ("before_provider_request" )?.(247 269 { payload: { text: secret } }, { payload: { text: secret } },250 272 expect (JSON .stringify (failed)).toContain (secret); expect (JSON .stringify (failed)).toContain (secret);252 - await runtime.commands.get ("leaks" )?.handler ("reload" , view.ctx);253 - const afterReload = await runtime .handlers.get (" before_provider_request " ) ?. ( 254 - { payload: { text: secret } },274 + const reloaded = fakePi (append);275 + leaks (reloaded.pi as never );276 + await reloaded.handlers.get ("session_start" )?.({}, ctx);277 + const afterReload = await reloaded .handlers.get (278 + "before_provider_request" ,279 + ) ?. ( { payload: { text: secret } }, ctx ) ; 257 280 expect (JSON .stringify (afterReload)).toContain (secret); expect (JSON .stringify (afterReload)).toContain (secret);259 - await runtime .commands.get ("leaks" )?.handler ("clear" , view . ctx);281 + await reloaded .commands.get ("leaks" )?.handler ("clear" , ctx);260 282 expect (view.notices.at (- 1 )).toContain ("clear failed" ); expect (view.notices.at (- 1 )).toContain ("clear failed" );350 372 expectLocalRestored (messageEnd, secret, placeholder); expectLocalRestored (messageEnd, secret, placeholder);
375 + it ("preserves own __proto__ keys during in-place hydration" , async () => {376 + const runtime = fakePi ();377 + leaks (runtime.pi as never );380 + path.join (view.ctx.cwd, ".pi" , "settings.json" ),382 + leaks: { regex: [{ pattern: "(__proto__)" , label: "KEY" }] },385 + await runtime.handlers.get ("session_start" )?.({}, view.ctx);386 + const provider = await runtime.handlers.get ("before_provider_request" )?.(387 + { payload: { text: "__proto__" } },391 + JSON .stringify (provider).match (LEAK_PLACEHOLDER_RE)?.[0 ];392 + const input = Object .create (null ) as Record <string , unknown >;393 + Object .defineProperty (input, placeholder as string , {397 + const event = { toolName: "custom" , input };398 + await runtime.handlers.get ("tool_call" )?.(event , view.ctx);399 + expect (Object .hasOwn (input, "__proto__" )).toBe (true );400 + expect (Object .getPrototypeOf (input)).toBeNull ();403 + it ("preserves literal placeholders across every maintenance hook" , async () => {404 + const runtime = fakePi ();405 + leaks (runtime.pi as never );407 + const secret = "ghp_" + "M" .repeat (36 );408 + const provider = await runtime.handlers.get ("before_provider_request" )?.(409 + { payload: { text: secret } },413 + JSON .stringify (provider).match (LEAK_PLACEHOLDER_RE)?.[0 ];414 + expect (placeholder).toBeDefined ();415 + const target = path.resolve (import .meta .dirname, "../README.md" );422 + arguments: { path: target, content: placeholder },426 + await runtime.handlers.get ("message_update" )?.({ message }, view.ctx);427 + expect (message.content [0 ].arguments .content ).toBe (placeholder);428 + for (const hook of [430 + "tool_execution_start" ,431 + "tool_execution_update" ,435 + input: { path: `@${target}` , content: placeholder },436 + args: { path: `@${target}` , content: placeholder },438 + await runtime.handlers.get (hook)?.(event , view.ctx);439 + expect (event .input .content ).toBe (placeholder);440 + expect (event .args.content ).toBe (placeholder);353 444 it ("blocks unresolved placeholders in every tool input path" , async () => { it ("blocks unresolved placeholders in every tool input path" , async () => {354 445 const runtime = fakePi (); const runtime = fakePi ();355 446 leaks (runtime.pi as never ); leaks (runtime.pi as never );extensions/leaks/__tests__/placeholders.test.ts Modified +28 / −0 text lines
182 182 expect (orphan.stats ().persistenceEnabled).toBe (false ); expect (orphan.stats ().persistenceEnabled).toBe (false );184 184 store.create (secretB, [label ("SECOND" , 10 , "dotenv" )]); store.create (secretB, [label ("SECOND" , 10 , "dotenv" )]);
185 + const duplicate = new __test.PlaceholderStore ({ cap: 1 });186 + duplicate.configure ([entries[0 ], entries[1 ], entries[1 ]], () => {});187 + expect (duplicate.stats ()).toMatchObject ({189 + persistenceEnabled: true ,185 192 const capped = new __test.PlaceholderStore ({ cap: 1 }); const capped = new __test.PlaceholderStore ({ cap: 1 });186 193 capped.configure (entries, () => {}); capped.configure (entries, () => {});187 194 expect (capped.stats ()).toMatchObject ({ expect (capped.stats ()).toMatchObject ({200 207 expect (conflict.stats ().persistenceEnabled).toBe (false ); expect (conflict.stats ().persistenceEnabled).toBe (false );
210 + it ("lets a later valid generation shadow unsupported history" , () => {211 + const { entries, store } = persistentStore ();212 + const placeholder = store.create (secretA, [213 + label ("TOKEN" , 10 , "dotenv" ),215 + const resumed = new __test.PlaceholderStore ();220 + customType: "leaks-generation-v2" ,221 + data: { version: 2 },227 + expect (resumed.stats ().persistenceEnabled).toBe (true );228 + expect (resumed.restore (placeholder)).toBe (secretA);203 231 it ("rejects noncanonical persisted encodings and malformed bounds" , () => { it ("rejects noncanonical persisted encodings and malformed bounds" , () => {204 232 const { entries, store } = persistentStore (); const { entries, store } = persistentStore ();205 233 store.create (secretA, [label ("TOKEN" , 10 , "dotenv" )]); store.create (secretA, [label ("TOKEN" , 10 , "dotenv" )]);extensions/leaks/__tests__/structures.test.ts Modified +11 / −0 text lines
161 + it ("keeps prose punctuation outside URL query spans" , () => {162 + const value = "ordinary-query-value-123456" ;163 + const url = new URL ("/path" , "https://example.test" );164 + url.searchParams.set ("token" , value);165 + const text = `See (${url}).` ;166 + const spans = __test.findSensitiveQuerySpans (text);167 + expect (spans.map ((span) => span.value )).toEqual ([value]);168 + const redacted = new __test.LeaksEngine ().redactText (text).text ;169 + expect (redacted).toMatch (/__LEAK_V1_[A-Z0-9_] + _[a-f0-9] {32} __\)\. $ / );161 172 it ("uses complete query and cookie names" , () => { it ("uses complete query and cookie names" , () => {162 173 const ordinary = "ordinary-metadata-value-123456" ; const ordinary = "ordinary-metadata-value-123456" ;163 174 expect (__test.findSensitiveQuerySpans (`?monkey=${ordinary}` )).toEqual ([]); expect (__test.findSensitiveQuerySpans (`?monkey=${ordinary}` )).toEqual ([]);extensions/leaks/__tests__/unit.test.ts Modified +28 / −0 text lines
103 103 expect (restored.count).toBe (2 ); expect (restored.count).toBe (2 );
106 + it ("reports property-name redactions" , () => {107 + const sensitiveKey = "property-name-secret-123456" ;108 + const engine = new __test.LeaksEngine ({111 + text === sensitiveKey117 + labels: [{ tag: "PROPERTY" , priority: 1 , source: "custom" }],126 + const result = engine.redactDeep ({ [sensitiveKey]: "value" });127 + expect (result.count).toBe (1 );128 + expect (result.redactions[0 ]).toMatchObject ({130 + labels: ["PROPERTY" ],106 134 it ("fails open when a detector throws" , () => { it ("fails open when a detector throws" , () => {107 135 const engine = new __test.LeaksEngine ({ const engine = new __test.LeaksEngine ({108 136 detectors: [ detectors: [extensions/leaks/src/detectors.ts Modified +8 / −4 text lines
87 87 "age-secret" , "age-secret" ,88 88 "AGE_SECRET_KEY" , "AGE_SECRET_KEY" ,89 89 "private-key" , "private-key" ,90 - / \b AGE-SECRET-KEY-1[023456789acdefghjklmnpqrstuvwxyz] {58}\b / dg ,90 + / \b AGE-SECRET-KEY-1[023456789acdefghjklmnpqrstuvwxyz] {58}\b / dgi ,92 92 "private-key" , "private-key" ,102 102 "private-key" , "private-key" ,104 - (match) => validBase64 (match[1 ]),104 + (match) => validMinisignSecret (match[1 ]),196 196 return checksum === 1 ; return checksum === 1 ;199 - function validBase64 (value: string ) {199 + function validMinisignSecret (value: string ) {200 200 if (! / ^ [A-Za-z0-9+/] + = {0,2}$ / .test (value)) return false ; if (! / ^ [A-Za-z0-9+/] + = {0,2}$ / .test (value)) return false ;201 - return Buffer .from (value, "base64" ).toString ("base64" ) === value;201 + const bytes = Buffer .from (value, "base64" );202 + if (bytes.toString ("base64" ) !== value || bytes.length !== 158 ) return false ;203 + if (bytes.subarray (0 , 6 ).toString ("ascii" ) !== "EdScB2" ) return false ;204 + const limits = bytes.subarray (38 , 54 );205 + return limits.some ((byte) => byte !== 0 );204 208 function validPuttyLine (value: string ) {function validPuttyLine (value: string ) {extensions/leaks/src/dotenv.ts Modified +23 / −20 text lines
141 141 export function isSensitiveKey (key: string ): boolean {export function isSensitiveKey (key: string ): boolean {142 - const normalized = normalizeKey (key.replace (PUBLIC_PREFIX_RE, "" ));143 - if (SENSITIVE.has (normalized)) return true ;144 - return [... SENSITIVE].some (146 - normalized.endsWith (`_${sensitive}` ) || 147 - normalized.startsWith (`${sensitive}_` ),142 + const tokens = normalizeKey (key.replace (PUBLIC_PREFIX_RE, "" )). split ( " _ " ) ;143 + return [... SENSITIVE].some (( sensitive ) => { 144 + const expected = sensitive.split ("_" );145 + return tokens.some ((_, start) => 146 + expected.every ((token, offset) => tokens[start + offset] === token),151 151 export function highConfidenceSecretShape (value: string ): boolean {export function highConfidenceSecretShape (value: string ): boolean {185 185 const values: LearnedValue [] = []; const values: LearnedValue [] = [];186 186 const warnings: WarningRecord [] = []; const warnings: WarningRecord [] = [];187 187 let warned = false ; let warned = false ;188 - for (const [key, value] of Object .entries (pairs)) {189 - if (values.length >= cap) {192 - code: "learned.cap" ,194 - "learned value cap reached; further dotenv/env values ignored" ,195 - severity: "warning" ,188 + const atCap = () => {189 + if (values.length < cap) return false ;192 + code: "learned.cap" ,193 + message: "learned value cap reached; further dotenv/env values ignored" ,194 + severity: "warning" ,
200 + for (const [key, value] of Object .entries (pairs)) {201 + if (atCap ()) continue ;201 202 const components = urlSecretComponents (value); const components = urlSecretComponents (value);202 203 if (components.length > 0 ) { if (components.length > 0 ) {203 - for (const component of components)204 + for (const component of components) { 204 206 pushLearned (values, component, key, source); pushLearned (values, component, key, source);205 208 continue ; continue ;207 210 const secretShape = highConfidenceSecretShape (value); const secretShape = highConfidenceSecretShape (value);extensions/leaks/src/engine.ts Modified +15 / −5 text lines
400 400 const copy: Record <string , unknown > = {}; const copy: Record <string , unknown > = {};401 401 seen.set (value, copy); seen.set (value, copy);402 402 for (const [index, [key, item]] of Object .entries (source).entries ()) { for (const [index, [key, item]] of Object .entries (source).entries ()) {403 - const keyResult = restore404 - ? this.restoreText (key)405 - : this.redactText (key, origin).text ;403 + const keyPath = `${ childPath (trace, index)}.key` ;404 + let keyResult = this.restoreText (key);406 + const result = this.redactText (key, origin);407 + keyResult = result.text ;408 + count += result.count;409 + for (const redaction of result.redactions)410 + redactions.push ({ ... redaction, path: keyPath });411 + for (const ambiguity of result.ambiguities)412 + ambiguities.push ({ ... ambiguity, path: keyPath });406 414 Object .defineProperty (copy, keyResult, { Object .defineProperty (copy, keyResult, {407 415 value: visit (item, depth + 1 , childPath (trace, index)), value: visit (item, depth + 1 , childPath (trace, index)),408 416 enumerable: true , enumerable: true ,436 444 function placeholderLabel (placeholder: string ) {function placeholderLabel (placeholder: string ) {437 - const match = / ^ __LEAK_(?:V1_) ? ([A-Z0-9_] + )/ .exec (placeholder);438 - return match ?.[1 ]?. replace ( / _ + $ / , " " ) ?? "UNKNOWN" ;445 + const current = / ^ __LEAK_V1_(. + )_[a-f0-9] {32} __ $ / .exec (placeholder);446 + if (current) return current[1 ];447 + const legacy = / ^ __LEAK_(. + )_[a-f0-9] {12} (?:_\d + ) ? __ $ / .exec (placeholder);448 + return legacy ?.[1 ] ?? "UNKNOWN" ;441 451 function childPath (parent: string , index: number ) {function childPath (parent: string , index: number ) {extensions/leaks/src/pi.ts Modified +105 / −46 text lines
1 + import { readFileSync } from "node:fs" ;1 2 import path from "node:path" ;import path from "node:path" ;3 4 type ExtensionAPI, type ExtensionAPI,18 19 engine.reload (ctx.cwd, readSettings (ctx.cwd), process .env ); engine.reload (ctx.cwd, readSettings (ctx.cwd), process .env );19 20 notifyInMemorySession (ctx, reportedWarnings); notifyInMemorySession (ctx, reportedWarnings);20 21 flushWarnings (engine, ctx, reportedWarnings); flushWarnings (engine, ctx, reportedWarnings);24 - `leaks ${engine. stats ().persistenceEnabled ? "on" : "degraded"} | last 0` ,26 + `leaks ${engine. stats ().persistenceEnabled ? "on" : "degraded"} | last 0` ,28 33 pi.on ("session_tree" , async (_event, ctx) => { pi.on ("session_tree" , async (_event, ctx) => {45 50 return result.value ; return result.value ;48 - pi.on ("message_update" , async (event) => {53 + pi.on ("message_update" , async (event, ctx ) => {54 + if (containsLeaksSourceMutation (event .message, ctx.cwd)) return ;49 55 restoreEventProperty ( restoreEventProperty (51 57 event as unknown as Record <string , unknown >, event as unknown as Record <string , unknown >,68 74 return { block: true , reason }; return { block: true , reason };71 - pi.on ("tool_execution_start" , async (event) => {77 + pi.on ("tool_execution_start" , async (event, ctx ) => {78 + if (isLeaksSourceMutation (event , ctx.cwd)) return ;72 79 restoreEventProperty ( restoreEventProperty (74 81 event as unknown as Record <string , unknown >, event as unknown as Record <string , unknown >,79 - pi.on ("tool_execution_update" , async (event) => {86 + pi.on ("tool_execution_update" , async (event, ctx ) => {87 + if (isLeaksSourceMutation (event , ctx.cwd)) return ;80 88 restoreEventProperty ( restoreEventProperty (82 90 event as unknown as Record <string , unknown >, event as unknown as Record <string , unknown >,90 98 event as unknown as Record <string , unknown >, event as unknown as Record <string , unknown >,100 + if (! isLeaksPathEvent (event , ctx.cwd)) {106 116 return patch; return patch;109 119 pi.on ("message_end" , async (event, ctx) => { pi.on ("message_end" , async (event, ctx) => {110 120 const restored = engine.restoreDeep (event .message).value ; const restored = engine.restoreDeep (event .message).value ;115 - "assistant message" ,121 + if (! containsLeaksSourceMutation (restored, ctx.cwd))126 + "assistant message" ,118 129 return { message: restored }; return { message: restored };243 254 if (! isPlainObject (target) || ! isPlainObject (source)) return ; if (! isPlainObject (target) || ! isPlainObject (source)) return ;244 - for (const key of Object .keys (target)) delete target[key];245 - Object .assign (target, source);255 + for (const key of Reflect .ownKeys (target))256 + Reflect .deleteProperty (target, key);257 + Object .defineProperties (target, Object .getOwnPropertyDescriptors (source));248 260 const LEAKS_EXTENSION_ROOT = path.resolve (import .meta .dirname, ".." );const LEAKS_EXTENSION_ROOT = path.resolve (import .meta .dirname, ".." );250 262 function isLeaksSourceMutation (event: unknown , cwd: string ) {function isLeaksSourceMutation (event: unknown , cwd: string ) {251 - if (! isPlainObject (event ) || ! isPlainObject (event .input )) return false ;252 - if (event .toolName !== "write" && event .toolName !== "edit" ) return false ;253 - if (typeof event .input .path !== "string" ) return false ;254 - const target = path.resolve (cwd, event .input .path);263 + if (! isPlainObject (event )) return false ;264 + const toolName = event .toolName ?? event .name ;265 + if (toolName !== "write" && toolName !== "edit" ) return false ;266 + return isLeaksPathEvent (event , cwd);269 + function isLeaksPathEvent (event: unknown , cwd: string ) {270 + if (! isPlainObject (event )) return false ;271 + const input = event .input ?? event .args ?? event .arguments ;272 + if (! isPlainObject (input) || typeof input.path !== "string" ) return false ;273 + const target = path.resolve (cwd, input.path.replace (/ ^ @/ , "" ));255 274 const relative = path.relative (LEAKS_EXTENSION_ROOT, target); const relative = path.relative (LEAKS_EXTENSION_ROOT, target);257 276 relative === "" || relative === "" ||
281 + function containsLeaksSourceMutation (value: unknown , cwd: string ): boolean {282 + if (isLeaksSourceMutation (value, cwd)) return true ;283 + if (Array .isArray (value))284 + return value.some ((item) => containsLeaksSourceMutation (item, cwd));285 + if (! isPlainObject (value)) return false ;286 + return Object .values (value).some ((item) => 287 + containsLeaksSourceMutation (item, cwd),262 291 function warnUnknownLocal (function warnUnknownLocal (263 292 engine: LeaksEngine , engine: LeaksEngine ,264 293 value: unknown , value: unknown ,290 319 ctx : ExtensionContext, ctx : ExtensionContext,291 320 state : { tainted : boolean }, state : { tainted : boolean },293 - const entries = (ctx.sessionManager?.getBranch () ?? [])294 - .filter ((entry) => entry.type === "custom" )322 + const branch = ctx.sessionManager?.getBranch () ?? [];323 + const durableIds = persistedEntryIds (ctx);324 + const leaksEntries = branch.flatMap ((entry) => 325 + entry.type === "custom" && entry.customType.startsWith ("leaks-" )329 + if (durableIds && leaksEntries.some ((entry) => ! durableIds.has (entry.id )))330 + state.tainted = true ;331 + const entries = leaksEntries332 + .filter ((entry) => ! durableIds || durableIds.has (entry.id ))295 333 .map ((entry) => ({ .map ((entry) => ({296 334 type: "custom" as const , type: "custom" as const ,297 335 customType: entry.customType, customType: entry.customType,308 346 if (state.tainted) engine.taintPersistence (); if (state.tainted) engine.taintPersistence ();
349 + function persistedEntryIds (ctx: ExtensionContext ) {350 + const file = ctx.sessionManager?.getSessionFile ();351 + if (! file) return undefined ;354 + readFileSync (file, "utf8" )357 + .map ((line) => JSON .parse (line) as { id?: unknown })358 + .flatMap ((entry) => (typeof entry.id === "string" ? [entry.id ] : [])),361 + return new Set <string >();311 365 function notifyInMemorySession (ctx: ExtensionContext , reported: Set <string >) {function notifyInMemorySession (ctx: ExtensionContext , reported: Set <string >) {312 366 if (ctx.sessionManager?.getSessionFile () !== undefined ) return ; if (ctx.sessionManager?.getSessionFile () !== undefined ) return ;313 367 const key = "session.in-memory" ; const key = "session.in-memory" ;392 446 counts.set (label, (counts.get (label) ?? 0 ) + 1 ); counts.set (label, (counts.get (label) ?? 0 ) + 1 );393 447 grouped.set (path, counts); grouped.set (path, counts);396 - `leaks redacted ${result.count} provider value(s)` ,397 - ... [... grouped.entries ()].map (398 - ([path, labels]) => `• ${path} — ${ formatNoticeLabels (labels)}` ,449 + const rows = [... grouped.entries ()]451 + .map (([path, labels]) => `• ${path} — ${ formatNoticeLabels (labels)}` );452 + if (grouped.size > rows.length )453 + rows.push (`• ${grouped. size - rows. length } more path(s)` );454 + return [`leaks redacted ${result.count} provider value(s)` , ... rows].join (403 459 function noticeLabel (raw: string ) {function noticeLabel (raw: string ) {409 465 function formatNoticeLabels (labels: Map <string , number >) {function formatNoticeLabels (labels: Map <string , number >) {410 - return [... labels.entries ()]411 - .map (([label, count]) => (count > 1 ? `${label} ×${count}` : label))466 + const visible = [... labels.entries ()]468 + .map (([label, count]) => (count > 1 ? `${label} ×${count}` : label)); 469 + if (labels.size > visible.length )470 + visible.push (`${labels. size - visible. length } more` );471 + return visible.join (", " );415 474 function formatStatus (engine: LeaksEngine ) {function formatStatus (engine: LeaksEngine ) {extensions/leaks/src/placeholders.ts Modified +14 / −6 text lines
82 82 this.append = append; this.append = append;83 83 this.reset (); this.reset ();84 84 let generationIndex = - 1 ; let generationIndex = - 1 ;85 - for (let index = 0 ; index < entries.length ; index++ ) { 86 - const entry = entries[index];87 - if (entry.customType === GENERATION_TYPE) generationIndex = index;88 - else if (entry.customType.startsWith ("leaks-generation-" ))89 - this.disable ("unsupported leaks generation version" );85 + for (let index = 0 ; index < entries.length ; index++ )86 + if (entries[index].customType === GENERATION_TYPE)87 + generationIndex = index;91 88 if (generationIndex < 0 ) { if (generationIndex < 0 ) {
90 + entries.some ((entry) => 91 + entry.customType.startsWith ("leaks-generation-" ),94 + this.disable ("unsupported leaks generation version" );93 96 entries.some ((entry) => entry.customType.startsWith ("leaks-mapping-" )) entries.some ((entry) => entry.customType.startsWith ("leaks-mapping-" ))95 98 this.disable ("mapping record has no generation" ); this.disable ("mapping record has no generation" );104 107 this.activate (generation); this.activate (generation);105 108 for (const entry of entries.slice (generationIndex + 1 )) { for (const entry of entries.slice (generationIndex + 1 )) {
109 + if (entry.customType.startsWith ("leaks-generation-" )) {110 + this.disable ("unsupported leaks generation version" );107 114 entry.customType.startsWith ("leaks-mapping-" ) && entry.customType.startsWith ("leaks-mapping-" ) && 108 115 entry.customType !== MAPPING_TYPE entry.customType !== MAPPING_TYPE124 131 const existing = this.placeholderToSecret.get (record.placeholder); const existing = this.placeholderToSecret.get (record.placeholder);125 132 const reverse = this.secretToPlaceholder.get (value); const reverse = this.secretToPlaceholder.get (value);
133 + if (existing === value && reverse === record.placeholder) continue ;127 135 (existing !== undefined && existing !== value) || (existing !== undefined && existing !== value) || 128 136 (reverse !== undefined && reverse !== record.placeholder) (reverse !== undefined && reverse !== record.placeholder)extensions/leaks/src/structures.ts Modified +10 / −5 text lines
130 130 export function findSensitiveQuerySpans (text: string ): SecretSpan [] {export function findSensitiveQuerySpans (text: string ): SecretSpan [] {131 131 const spans: SecretSpan [] = []; const spans: SecretSpan [] = [];132 132 for (const candidate of text.matchAll (URL_CANDIDATE_RE)) { for (const candidate of text.matchAll (URL_CANDIDATE_RE)) {
133 + const rawCandidate = trimUrlCandidate (candidate[0 ]);134 - new URL (candidate[0 ]);135 + new URL (rawCandidate);135 136 } catch { } catch {136 137 continue ; continue ;138 - const question = candidate [ 0 ] .indexOf ("?" );139 + const question = rawCandidate .indexOf ("?" );139 140 if (question < 0 ) continue ; if (question < 0 ) continue ;140 - const fragment = candidate [ 0 ] .indexOf ("#" , question);141 - const end = fragment < 0 ? candidate [ 0 ] .length : fragment;141 + const fragment = rawCandidate .indexOf ("#" , question);142 + const end = fragment < 0 ? rawCandidate .length : fragment;142 143 spans.push ( spans.push (143 144 ... parsedQuerySpans ( ... parsedQuerySpans (144 - candidate [ 0 ] .slice (question + 1 , end),145 + rawCandidate .slice (question + 1 , end),145 146 (candidate.index as number ) + question + 1 , (candidate.index as number ) + question + 1 ,354 355 return { tag, priority: source === "builtin" ? 40 : 20 , source }; return { tag, priority: source === "builtin" ? 40 : 20 , source };
358 + function trimUrlCandidate (candidate: string ) {359 + return candidate.replace (/[\])},.;!?] +$ / , "" );357 362 function candidateHasSensitiveQueryName (candidate: string ) {function candidateHasSensitiveQueryName (candidate: string ) {358 363 const question = candidate.indexOf ("?" ); const question = candidate.indexOf ("?" );359 364 if (question < 0 ) return false ; if (question < 0 ) return false ;scripts/run_leaks_fuzz.mjs Modified +27 / −0 text lines
14 14 if (process.argv[1] === fileURLToPath(import.meta.url)) {if (process.argv[1] === fileURLToPath(import.meta.url)) {
15 + const propertyIds = new Set([20 + "engine-determinism",24 + "lifecycle-corruption",25 + "lifecycle-failures",26 + "lifecycle-hydration",33 + process.env.FC_TEST &&34 + !propertyIds.has(process.env.FC_TEST) &&35 + !/^builtin-(?:[0-9]|1[0-6])-(?:positive|negative)$/.test(39 + console.error(`unknown FC_TEST: ${process.env.FC_TEST}`);15 42 const testing = process.env.LEAKS_FUZZ_TEST_HANG === "1"; const testing = process.env.LEAKS_FUZZ_TEST_HANG === "1";16 43 const requested = Number(process.env.LEAKS_FUZZ_TIMEOUT_MS ?? 120_000); const requested = Number(process.env.LEAKS_FUZZ_TIMEOUT_MS ?? 120_000);17 44 const timeout = testing const timeout = testing