repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(leaks): validate structured secret contexts

f6dc2b21f202de16af62d15250d1dce3971b37b2

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (11)

extensions/leaks/SPEC.md

Modified
219 219 - auth, OAuth, JWT, cookie, and session secrets
220 220 - database and cache credentialed connection strings
221 221 - private key material listed below
222 -- generic sensitive-key assignments with non-weak values, including `KEY`, `KEY_DATA`, `PASS`, `PAT`, `PASSPHRASE`, `PEPPER`, `LICENSE_KEY`, `MASTER_KEY`, `ROUTING_KEY`, `ENCRYPTION_KEY`, `SECRET_KEY_BASE`, `SEED`, `UNSEAL_KEY`, and `MNEMONIC` key names
222 +- provider-shaped values in conservative sensitive-key assignments; ambiguous opaque assignments remain visible unless learned exactly from dotenv or environment input
224 224 Redact credential-like IDs such as AWS access key IDs when a reliable provider-specific pattern exists.
225 225 Do not redact arbitrary account IDs, customer IDs, org IDs, project IDs, hostnames, or domains.

extensions/leaks/__fuzz__/builtins.fuzz.test.ts

Added
new file mode 100644
1 +import { fc, test } from "@fast-check/vitest";
2 +import { expect } from "vitest";
3 +import { __test } from "../index.ts";
5 +const base = { numRuns: 1_000 };
6 +const alphaNum = fc.constantFrom(
7 + ..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
8 +);
9 +const body = fc.string({ unit: alphaNum, minLength: 20, maxLength: 24 });
10 +const cases = [
11 + ["OPENROUTER_TOKEN", (v: string) => ["sk-or-v1-", v.repeat(2)].join("")],
12 + ["OPENAI_TOKEN", (v: string) => ["sk-", "proj-", v.repeat(2)].join("")],
13 + [
14 + "ANTHROPIC_TOKEN",
15 + (v: string) => ["sk-ant-", "api03-", v.repeat(2)].join(""),
16 + ],
17 + ["HUGGINGFACE_TOKEN", (v: string) => ["hf_", v.repeat(2)].join("")],
18 + ["GITHUB_TOKEN", (v: string) => ["ghp_", v.repeat(2)].join("")],
19 + ["NPM_TOKEN", (v: string) => ["npm_", v.repeat(2)].join("")],
20 + [
21 + "AWS_ACCESS_KEY_ID",
22 + (v: string) => ["AKIA", v.toUpperCase().slice(0, 16)].join(""),
23 + ],
24 + [
25 + "GOOGLE_API_KEY",
26 + (v: string) => ["AIza", v.repeat(2).slice(0, 35)].join(""),
27 + ],
28 + [
29 + "STRIPE_LIVE_SECRET_KEY",
30 + (v: string) => ["sk_", "live_", v.repeat(2)].join(""),
31 + ],
32 + ["SLACK_TOKEN", (v: string) => ["xoxb-", v.repeat(2)].join("")],
33 + [
34 + "SLACK_WEBHOOK",
35 + (v: string) =>
36 + ["https://hooks.slack.com/", "services/", v.repeat(2)].join(""),
37 + ],
38 + ["SENDGRID_TOKEN", (v: string) => ["SG.", v, ".", v.repeat(3)].join("")],
39 + ["OAUTH_TOKEN", (v: string) => ["ya29.", v.repeat(3)].join("")],
40 + [
41 + "PGP_PRIVATE_KEY",
42 + (v: string) =>
43 + [
44 + "-----BEGIN PGP ",
45 + "PRIVATE KEY BLOCK-----\n",
46 + v,
47 + "\n-----END PGP ",
48 + "PRIVATE KEY BLOCK-----",
49 + ].join(""),
50 + ],
51 + [
52 + "COSIGN_PRIVATE_KEY",
53 + (v: string) =>
54 + [
55 + "-----BEGIN ENCRYPTED COSIGN ",
56 + "PRIVATE KEY-----\n",
57 + v,
58 + "\n-----END ENCRYPTED COSIGN ",
59 + "PRIVATE KEY-----",
60 + ].join(""),
61 + ],
62 + [
63 + "AGE_SECRET_KEY",
64 + (v: string) => ["AGE-SECRET-", "KEY-1", v.toUpperCase().repeat(4)].join(""),
65 + ],
66 + [
67 + "MINISIGN_SECRET_KEY",
68 + (v: string) =>
69 + ["untrusted comment: minisign ", "secret key\nRW", v.repeat(4)].join(""),
70 + ],
71 +] as const;
73 +test.prop(
74 + {
75 + caseIndex: fc.integer({ min: 0, max: cases.length - 1 }),
76 + body,
77 + left: fc.constantFrom("", " ", "\n", "'", '"'),
78 + right: fc.constantFrom("", " ", "\n", "'", '"'),
79 + },
80 + base,
81 +)(
82 + "detects every built-in family with exact spans",
83 + ({ caseIndex, body, left, right }) => {
84 + const [tag, build] = cases[caseIndex];
85 + const value = build(body);
86 + const text = left + value + right;
87 + const span = __test
88 + .findBuiltinSpans(text)
89 + .find((candidate) => candidate.labels.some((item) => item.tag === tag));
90 + expect(span?.value).toBe(value);
91 + expect(text.slice(span?.start, span?.end)).toBe(value);
92 + },
93 +);
95 +test.prop(
96 + { caseIndex: fc.integer({ min: 0, max: cases.length - 1 }), body },
97 + base,
98 +)("rejects truncated built-in near misses", ({ caseIndex, body }) => {
99 + const [tag, build] = cases[caseIndex];
100 + const built = build(body);
101 + const value = `!${built.slice(1)}`;
102 + expect(
103 + __test
104 + .findBuiltinSpans(value)
105 + .some((span) => span.labels.some((item) => item.tag === tag)),
106 + ).toBe(false);
107 +});

extensions/leaks/__fuzz__/detectors.fuzz.test.ts

Modified
2 2 import { fc, test } from "@fast-check/vitest";
3 3 import { expect } from "vitest";
4 4 import { __test } from "../index.ts";
6 +const base = { numRuns: 1_000 };
6 7 const replay = {
8 + ...base,
7 9 ...(process.env.FC_SEED ? { seed: Number(process.env.FC_SEED) } : {}),
8 10 ...(process.env.FC_PATH ? { path: process.env.FC_PATH } : {}),
9 - numRuns: 1_000,
12 +function params(name: string) {
13 + return process.env.FC_TEST === name ? replay : base;
11 15 const alphaNum = fc.constantFrom(
12 16 ..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
14 18 const alphaNumText = (minLength: number, maxLength: number) =>
15 19 fc.string({ unit: alphaNum, minLength, maxLength });
16 -const opaque = alphaNumText(8, 80).filter(
17 - (value) => !__test.highConfidenceSecretShape(value),
18 -);
20 +const opaque = alphaNumText(8, 80).map((value) => `ordinary-${value}`);
19 21 const validJwt = fc
20 22 .record({
21 23 alg: alphaNumText(1, 16),
35 37 return engine.restoreText(engine.redactText(text, "provider").text);
38 -test.prop({ token: validJwt }, replay)(
40 +test.prop({ token: validJwt }, params("engine-determinism"))(
41 + "is deterministic across fresh engines",
42 + ({ token }) => {
43 + const first = new __test.LeaksEngine();
44 + const second = new __test.LeaksEngine();
45 + const firstResult = first.redactText(token, "provider");
46 + const secondResult = second.redactText(token, "provider");
47 + expect(first.redactText(token, "provider").text).toBe(firstResult.text);
48 + expect(second.redactText(token, "provider").text).toBe(secondResult.text);
49 + expect(first.restoreText(firstResult.text)).toBe(token);
50 + expect(second.restoreText(secondResult.text)).toBe(token);
51 + },
52 +);
54 +test.prop({ token: validJwt }, params("jwt-positive"))(
39 55 "accepts valid JWT objects",
40 56 ({ token }) => {
41 57 const spans = __test.findJwtSpans(token);
52 68 alphaNumText(8, 40),
55 - replay,
71 + params("jwt-negative"),
56 72 )("rejects dotted identifiers", ({ parts }) => {
57 73 const value = parts.join(".");
58 74 fc.pre(!value.startsWith("ey"));
59 75 expect(__test.findJwtSpans(value)).toEqual([]);
62 -test.prop({ value: opaque }, replay)(
78 +test.prop({ value: opaque }, params("query"))(
63 79 "uses complete query names",
64 80 ({ value }) => {
65 81 expect(__test.findSensitiveQuerySpans(`?monkey=${value}`)).toEqual([]);
74 -test.prop({ value: opaque }, replay)(
90 +test.prop({ value: opaque }, params("cookie"))(
75 91 "uses complete cookie names",
76 92 ({ value }) => {
77 93 const harmless = ["Cook", `ie: keyboard=${value}`].join("");
86 -test.prop({ value: opaque }, replay)(
102 +test.prop({ value: opaque }, params("assignments"))(
87 103 "rejects ambiguous assignments",
88 104 ({ value }) => {
89 105 for (const text of [
108 124 body: alphaNumText(36, 64),
110 - replay,
126 + params("providers"),
111 127 )("keeps provider prefixes strict", ({ family: [prefix, length], body }) => {
112 128 const valid = prefix + body.slice(0, length);
113 129 expect(__test.findBuiltinSpans(valid)).toHaveLength(1);
116 132 ).toEqual([]);
119 -test.prop({ value: opaque }, replay)(
135 +test.prop({ value: opaque }, params("environment"))(
120 136 "does not learn environment metadata",
121 137 ({ value }) => {
122 138 const learned = __test.learnEnvironmentValues({
131 -test.prop({ text: fc.string() }, replay)(
147 +test.prop(
149 + digits: fc.string({
150 + unit: fc.constantFrom(..."0123456789"),
151 + minLength: 1,
152 + maxLength: 40,
153 + }),
154 + },
155 + params("custom-capture"),
156 +)("custom regex returns exact capture spans", ({ digits }) => {
157 + const compiled = __test.compileCustomRegex({
158 + regex: [{ pattern: "CUSTOM_([0-9]+)", label: "CUSTOM" }],
159 + });
160 + const text = `before CUSTOM_${digits} after`;
161 + const span = __test.customRegexSpans(text, compiled.rules)[0];
162 + expect(span.value).toBe(digits);
163 + expect(text.slice(span.start, span.end)).toBe(digits);
164 +});
166 +test.prop({ text: fc.string() }, params("custom"))(
132 167 "custom regex never changes unmatched text",
133 168 ({ text }) => {
134 169 const compiled = __test.compileCustomRegex({

extensions/leaks/__tests__/detectors.test.ts

Modified
58 58 expect(result.text).toContain(`Private-MAC: 00\n${trailing}`);
61 + it("rejects an invalid EOF PuTTY payload line", () => {
62 + const block = [
63 + "PuTTY-User-Key-File-3: ssh-rsa",
64 + "Private-Lines: 1",
65 + "ordinary prose",
66 + ].join("\n");
67 + expect(__test.findPrivateKeySpans(block)).toEqual([]);
68 + });
61 70 it("redacts supported private-key material", () => {
62 71 const blocks = [

extensions/leaks/__tests__/direct-modules.test.ts

Modified
77 77 "PRIVATE KEY-----\nbody\n-----END EC ",
78 78 "PRIVATE KEY-----",
79 79 ].join("");
80 + const basic = Buffer.from("alice:password").toString("base64");
80 81 const text = [
83 84 `mysql://user:${value}@host/db`,
84 85 `https://host/path?api_key=${value}`,
85 - `Authorization: Basic ${value}`,
86 + ["Authorization", ` Basic ${basic}`].join(":"),
86 87 `Api-Key: ${value}`,
87 88 `Cookie: auth=${value}; theme=dark`,
88 89 `TOKEN=${value}`,
96 97 ).toHaveLength(1);
97 98 expect(findSensitiveQuerySpans(`?api_key=${value}`)).toHaveLength(1);
98 99 expect(
99 - findHeaderSpans(`Authorization: Basic ${value}\nApi-Key: ${value}`),
100 + findHeaderSpans(
102 + ["Authorization", ` Basic ${basic}`].join(":"),
103 + ["Authorization", ` Bearer ${value}`].join(":"),
104 + ].join("\n"),
105 + ),
100 106 ).toHaveLength(2);
101 107 expect(findCookieSpans(`Cookie: auth=${value}; flag`)).toHaveLength(1);
102 108 expect(

extensions/leaks/__tests__/dotenv.test.ts

Modified
102 102 const learned = __test.learnEnvironmentValues({
103 103 GPG_KEY_ID: ordinary,
104 104 SESSION_MANAGER: ordinary,
105 - KEY: ordinary,
106 - AUTH: ordinary,
105 + PROD_KEY: ordinary,
106 + APP_AUTH: ordinary,
107 + USER_SESSION: ordinary,
107 108 PROD_ACCESS_TOKEN: ordinary,
110 111 expect(learned.values.map((item) => item.value)).toEqual([ordinary]);
114 + it("learns URL secret components instead of whole URLs", () => {
115 + const password = ["database", "password", "123456"].join("-");
116 + const query = ["query", "credential", "123456"].join("-");
117 + const url = `postgres://alice:${password}@db/app?token=${query}`;
118 + const learned = __test.learnEnvironmentValues({ DATABASE_URL: url });
120 + expect(learned.values.map((item) => item.value)).toEqual([password, query]);
121 + expect(learned.values.map((item) => item.value)).not.toContain(url);
122 + });
113 124 it("enforces learned exact value cap and warns once", () => {
114 125 const learned = __test.learnEnvironmentValues(

extensions/leaks/__tests__/structures.test.ts

Modified
38 38 expect(engine.redactText(text, "provider").text).toBe(text);
41 - it("redacts header values only", () => {
41 + it("redacts validated header values only", () => {
42 42 const engine = new __test.LeaksEngine();
43 - const text = `Authorization: Bearer ${secret}\nAuthorization: Basic ${secret}\nX-API-Key: ${secret}`;
43 + const basic = Buffer.from("alice:password").toString("base64");
44 + const text = [
45 + ["Authorization", ` Bearer ${secret}`].join(":"),
46 + ["Authorization", ` Basic ${basic}`].join(":"),
47 + ["X-API-Key", ` ${secret}`].join(":"),
48 + ].join("\n");
44 49 const result = engine.redactText(text, "provider");
46 - expect(result.text).toContain("Authorization: Bearer ");
47 - expect(result.text).toContain("Authorization: Basic ");
48 - expect(result.text).toContain(["X-API", "-Key: "].join(""));
49 - expect(result.text.includes(secret)).toBe(false);
51 + expect(result.text).not.toContain(secret);
52 + expect(result.text).not.toContain(basic);
50 53 expect(result.count).toBe(3);
90 93 expect(result.text.includes(secret)).toBe(false);
93 - it("requires decoded JWT objects", () => {
96 + it("requires exactly three decoded JWT object segments", () => {
94 97 const dotted = ["agendaFlick", "visibleArea", "yPosition"].join(".");
98 + const shortPayload = [
99 + Buffer.from(JSON.stringify({ alg: "A" })).toString("base64url"),
100 + Buffer.from(JSON.stringify({})).toString("base64url"),
101 + Buffer.from([0]).toString("base64url"),
102 + ].join(".");
95 103 expect(__test.findJwtSpans(dotted)).toEqual([]);
104 + expect(__test.findJwtSpans(`${jwt}.extra`)).toEqual([]);
105 + expect(__test.findJwtSpans(shortPayload).map((span) => span.value)).toEqual(
106 + [shortPayload],
107 + );
96 108 expect(__test.findJwtSpans(jwt).map((span) => span.value)).toEqual([jwt]);
111 + it("rejects malformed structured contexts", () => {
112 + const ordinary = ["ordinary", "metadata", "value", "123456"].join("-");
113 + expect(
114 + __test.findSensitiveQuerySpans(
115 + ["https://[bad/?tok", `en=${ordinary}`].join(""),
116 + ),
117 + ).toEqual([]);
118 + expect(
119 + __test.findCookieSpans(["Set-Cook", `ie: session=${ordinary}`].join("")),
120 + ).toEqual([]);
121 + expect(
122 + __test.findHeaderSpans(["Authorization", ` Basic ${ordinary}`].join(":")),
123 + ).toEqual([]);
124 + });
99 126 it("uses complete query and cookie names", () => {
100 127 const ordinary = ["ordinary", "metadata", "value", "123456"].join("-");
101 128 expect(

extensions/leaks/src/detectors.ts

Modified
138 138 let end = (match.index as number) + match[0].length;
139 139 let valid = true;
140 140 for (let index = 0; index < count; index++) {
141 - const lineEnd = text.indexOf("\n", end);
142 - if (lineEnd === -1) {
143 - end = text.length;
144 - valid = index === count - 1;
145 - break;
146 - }
147 - if (!/^[A-Za-z0-9+/=]+\r?$/.test(text.slice(end, lineEnd))) {
141 + const newline = text.indexOf("\n", end);
142 + const lineEnd = newline === -1 ? text.length : newline;
143 + const line = text.slice(end, lineEnd).replace(/\r$/, "");
144 + if (!validPuttyLine(line) || (newline === -1 && index !== count - 1)) {
148 145 valid = false;
149 146 break;
151 - end = lineEnd + 1;
148 + end = newline === -1 ? text.length : newline + 1;
153 150 if (!valid) continue;
154 151 spans.push({
164 161 return spans;
164 +function validPuttyLine(value: string) {
165 + if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return false;
166 + return Buffer.from(value, "base64").toString("base64") === value;
167 169 function rule(
168 170 id: string,
169 171 tag: string,

extensions/leaks/src/dotenv.ts

Modified
180 180 continue;
182 + const components = urlSecretComponents(value);
183 + if (components.length > 0) {
184 + for (const component of components)
185 + pushLearned(values, component, key, source);
186 + continue;
182 188 const secretShape = highConfidenceSecretShape(value);
183 189 if (!secretShape && (!isLearnableKey(key) || isWeakValue(value))) continue;
184 - values.push({
185 - value,
186 - labels: [
187 - {
188 - tag: source === "env" ? "ENV_KEY" : sanitizeTag(key),
189 - priority: 10,
190 - source,
191 - },
192 - ],
193 - });
190 + pushLearned(values, value, key, source);
195 192 return { values, warnings };
195 +function pushLearned(
196 + values: LearnedValue[],
197 + value: string,
198 + key: string,
199 + source: "dotenv" | "env",
200 +) {
201 + if (isWeakValue(value)) return;
202 + values.push({
203 + value,
204 + labels: [
206 + tag: source === "env" ? "ENV_KEY" : sanitizeTag(key),
207 + priority: 10,
208 + source,
209 + },
210 + ],
211 + });
214 +function urlSecretComponents(value: string) {
215 + try {
216 + const url = new URL(value);
217 + const components = url.password ? [url.password] : [];
218 + for (const [name, item] of url.searchParams)
219 + if (isSensitiveKey(name) && !isWeakValue(item)) components.push(item);
220 + return components;
221 + } catch {
222 + return [];
198 226 function isLearnableKey(key: string) {
199 227 if (PUBLIC_PREFIX_RE.test(key)) return false;
200 228 const normalized = normalizeKey(key);
201 - if (METADATA_SUFFIX_RE.test(normalized) || CONTEXT_ONLY.has(normalized))
229 + if (METADATA_SUFFIX_RE.test(normalized)) return false;
230 + if (SENSITIVE.has(normalized) && !CONTEXT_ONLY.has(normalized)) return true;
231 + if (
232 + [...CONTEXT_ONLY].some(
233 + (context) => normalized === context || normalized.endsWith(`_${context}`),
202 236 return false;
203 237 return isSensitiveKey(normalized);

extensions/leaks/src/structures.ts

Modified
2 2 import { highConfidenceSecretShape, isSensitiveKey } from "./dotenv.ts";
3 3 import { isWeakValue } from "./safety.ts";
4 4 import type { SecretSpan, SpanLabel } from "./types.ts";
6 +const URL_CANDIDATE_RE = /\b[a-z][a-z0-9+.-]*:\/\/[^\s'"`]+/dgi;
6 7 const URL_CREDENTIAL_RE =
7 - /\b[a-z][a-z0-9+.-]*:\/\/([^\s:@/]*)?:([^\s@/]+)@[^\s]+/dgi;
8 + /\b[a-z][a-z0-9+.-]*:\/\/([^\s:@/]*)?:([^\s@/]+)@[^\s'"`]+/dgi;
8 9 const QUERY_RE =
9 10 /([?&])([A-Za-z0-9_-]*(?:token|key|secret|password|auth)[A-Za-z0-9_-]*)=([^&#\s'"`]+)/dgi;
10 -const AUTH_RE = /Authorization:\s*(Bearer|Basic)\s+([^\s'"`]+)/dgi;
11 -const X_API_RE = /\b(X-API-Key|Api-Key):\s*([^\s'"`]+)/dgi;
12 -const COOKIE_LINE_RE = /Cookie:\s*([^\n]+)/dgi;
11 +const AUTH_RE =
12 + /(?:^|[\n\r\s'"`])Authorization:\s*(Bearer|Basic)\s+([^\s'"`]+)/dgi;
13 +const X_API_RE = /(?:^|[\n\r\s'"`])(X-API-Key|Api-Key):\s*([^\s'"`]+)/dgi;
14 +const COOKIE_LINE_RE = /(?:^|[\n\r])\s*Cookie:\s*([^\r\n]+)/dgi;
13 15 // Keys that look like assignments but are common programming nouns, not secrets.
14 16 // Scoped to findAssignmentSpans only — does NOT affect dotenv/env learning
15 17 // or structure non-assignment detectors. Excludes any key in dotenv.SENSITIVE
46 48 /(?:^|[\n\r\s{,;])(?:export\s+)?["']?([A-Za-z_][A-Za-z0-9_-]*)["']?\s*(?:=|:|=>)\s*["']?([^\s'",;}]{1,512})["']?/dgi;
47 49 const XML_RE = /<([A-Za-z_][A-Za-z0-9_-]*)>([^<]{1,512})<\/\1>/dgi;
48 50 const JWT_RE =
49 - /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{8,}(?![A-Za-z0-9_-])/dg;
51 + /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+(?![A-Za-z0-9_-])/dg;
50 52 const PRIVATE_KEY_RE =
51 53 /-----BEGIN ([A-Z0-9 ]*PRIVATE KEY)-----[\s\S]*?-----END \1-----/dg;
80 82 export function findCredentialedUrlSpans(text: string): SecretSpan[] {
81 - return matches(URL_CREDENTIAL_RE, text, 2, "DB_PASSWORD");
83 + const spans: SecretSpan[] = [];
84 + for (const match of text.matchAll(URL_CREDENTIAL_RE)) {
85 + try {
86 + new URL(match[0]);
87 + } catch {
88 + continue;
89 + }
90 + const value = match[2] as string;
91 + if (isWeakValue(value)) continue;
92 + spans.push(
93 + makeSpan(
94 + match,
95 + 2,
96 + value,
97 + [label("DB_PASSWORD", "structure")],
98 + "structure",
99 + ),
100 + );
102 + return spans;
84 105 export function findSensitiveQuerySpans(text: string): SecretSpan[] {
85 106 const spans: SecretSpan[] = [];
86 107 for (const match of text.matchAll(QUERY_RE)) {
108 + if (!queryHasParsedContext(text, match.index as number)) continue;
87 109 const name = match[2] as string;
88 110 const value = match[3] as string;
89 111 if (!isSensitiveKey(name) || isWeakValue(value)) continue;
109 131 "AUTHORIZATION",
110 132 (match) => `AUTHORIZATION_${match[1]?.toUpperCase()}`,
133 + (match) => match[1]?.toLowerCase() !== "basic" || validBasic(match[2]),
112 135 ...matches(X_API_RE, text, 2, "X_API_KEY"),
128 151 const name = trimmed.slice(0, eq);
129 152 const value = trimmed.slice(eq + 1);
130 - const localStart = part.indexOf(value);
153 + const localStart = part.indexOf(trimmed) + eq + 1;
131 154 if (isSensitiveCookie(name) && !isWeakValue(value)) {
132 155 const start = offset + Math.max(localStart, 0);
133 156 spans.push({
168 191 export function findJwtSpans(text: string): SecretSpan[] {
169 192 const spans: SecretSpan[] = [];
170 193 for (const match of text.matchAll(JWT_RE)) {
171 - const [headerPart, payloadPart, signaturePart] = match[0].split(".");
194 + const parts = match[0].split(".");
195 + if (parts.length !== 3) continue;
196 + const [headerPart, payloadPart, signaturePart] = parts;
172 197 if (!headerPart || !payloadPart || !strictBase64Url(signaturePart))
173 198 continue;
174 199 const header = decodeJsonObject(headerPart);
243 268 group: number,
244 269 fallback: string,
245 270 tag?: (match: RegExpMatchArray) => string,
271 + accept: (match: RegExpMatchArray) => boolean = () => true,
246 272 ): SecretSpan[] {
247 273 regex.lastIndex = 0;
248 274 const spans: SecretSpan[] = [];
249 275 for (const match of text.matchAll(regex)) {
250 276 const value = match[group] as string;
251 - if (isWeakValue(value)) continue;
277 + if (!accept(match) || isWeakValue(value)) continue;
252 278 spans.push(
253 279 makeSpan(
254 280 match,
286 312 return { tag, priority: source === "builtin" ? 40 : 20, source };
315 +function queryHasParsedContext(text: string, index: number) {
316 + if (text.slice(0, index).trim().length === 0 && text[index] === "?")
317 + return true;
318 + for (const candidate of text.matchAll(URL_CANDIDATE_RE)) {
319 + const start = candidate.index as number;
320 + if (index < start || index >= start + candidate[0].length) continue;
321 + try {
322 + new URL(candidate[0]);
323 + return true;
324 + } catch {
325 + return false;
328 + return false;
331 +function validBasic(value: string | undefined) {
332 + if (!value || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return false;
333 + try {
334 + const bytes = Buffer.from(value, "base64");
335 + if (bytes.toString("base64") !== value) return false;
336 + return new TextDecoder("utf-8", { fatal: true })
337 + .decode(bytes)
338 + .includes(":");
339 + } catch {
340 + return false;
289 344 function isSensitiveCookie(name: string) {
290 345 return isSensitiveKey(name);

mise.toml

Modified
55 55 description = "Run property tests"
56 56 depends = ["install"]
57 57 run = '''
58 -node -e "const {spawnSync}=require('node:child_process');const r=spawnSync(process.execPath,['node_modules/vitest/vitest.mjs','run','--config','extensions/leaks/vitest.fuzz.config.ts'],{stdio:'inherit',timeout:120000});process.exit(r.error?.code==='ETIMEDOUT'?124:r.status??1)"
58 +node -e "const {spawnSync}=require('node:child_process');const r=spawnSync(process.execPath,['node_modules/vitest/vitest.mjs','run','--config','extensions/leaks/vitest.fuzz.config.ts'],{stdio:'inherit',timeout:120000,killSignal:'SIGKILL'});process.exit(r.error?.code==='ETIMEDOUT'?124:r.status??1)"
61 61 [tasks.bench]