playwright-security-scan 0.0.0 → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2727 @@
1
+ import { ruleManifest, NON_SESSION_COOKIES, sha256, canonicalOrigin, matchingPattern, parseHostPattern, severityRank, confidenceRank } from './chunk-IHU2HYVH.js';
2
+
3
+ // src/core/fingerprint/fingerprint.ts
4
+ var MAX_FINGERPRINT_LENGTH = 512;
5
+ var KEPT_PREFIX = 480;
6
+ function fingerprintOf(input) {
7
+ const parts = [input.ruleId, input.scope, input.subject];
8
+ if (input.discriminator !== void 0 && input.discriminator !== "")
9
+ parts.push(input.discriminator);
10
+ const full = parts.join("|");
11
+ if (full.length <= MAX_FINGERPRINT_LENGTH) return full;
12
+ return `${full.slice(0, KEPT_PREFIX)}…#${sha256(full).slice(0, 8)}`;
13
+ }
14
+
15
+ // src/core/fingerprint/dedup.ts
16
+ var MAX_EVIDENCE = 3;
17
+ var MAX_TESTS = 50;
18
+ var SOURCE_ORDER = ["browser", "api"];
19
+ function toFinding(raw, context, source) {
20
+ const finding2 = {
21
+ ruleId: raw.ruleId,
22
+ severity: raw.severity,
23
+ confidence: raw.confidence,
24
+ scope: raw.scope,
25
+ subject: raw.subject,
26
+ location: { ...raw.location },
27
+ evidence: raw.evidence.slice(0, MAX_EVIDENCE),
28
+ message: raw.message,
29
+ fingerprint: fingerprintOf(raw),
30
+ occurrences: 1,
31
+ firstSeen: context,
32
+ tests: [context.testId],
33
+ sources: [source]
34
+ };
35
+ if (raw.discriminator !== void 0) finding2.discriminator = raw.discriminator;
36
+ return finding2;
37
+ }
38
+ var compareText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
39
+ function compareTests(a, b) {
40
+ return compareText(a.file, b.file) || a.line - b.line || compareText(a.titlePath.join("\0"), b.titlePath.join("\0")) || compareText(a.project, b.project) || compareText(a.testId, b.testId);
41
+ }
42
+ var evidenceKey = (e) => `${e.kind}\0${e.name ?? ""}\0${e.snippet}`;
43
+ function merge(into, next) {
44
+ into.occurrences += next.occurrences;
45
+ if (severityRank(next.severity) > severityRank(into.severity)) into.severity = next.severity;
46
+ if (confidenceRank(next.confidence) > confidenceRank(into.confidence)) {
47
+ into.confidence = next.confidence;
48
+ }
49
+ const seen = new Set(into.evidence.map(evidenceKey));
50
+ for (const e of next.evidence) {
51
+ if (into.evidence.length >= MAX_EVIDENCE) break;
52
+ if (!seen.has(evidenceKey(e))) {
53
+ seen.add(evidenceKey(e));
54
+ into.evidence.push(e);
55
+ }
56
+ }
57
+ for (const test of next.tests) {
58
+ if (into.tests.length >= MAX_TESTS) break;
59
+ if (!into.tests.includes(test)) into.tests.push(test);
60
+ }
61
+ const sources = /* @__PURE__ */ new Set([...into.sources, ...next.sources]);
62
+ into.sources = SOURCE_ORDER.filter((s) => sources.has(s));
63
+ }
64
+ var clone = (f) => ({
65
+ ...f,
66
+ location: { ...f.location },
67
+ evidence: [...f.evidence],
68
+ tests: [...f.tests],
69
+ sources: [...f.sources],
70
+ firstSeen: { ...f.firstSeen, titlePath: [...f.firstSeen.titlePath] }
71
+ });
72
+ function dedupeTest(findings) {
73
+ const byPrint = /* @__PURE__ */ new Map();
74
+ for (const finding2 of findings) {
75
+ const existing = byPrint.get(finding2.fingerprint);
76
+ if (existing === void 0) byPrint.set(finding2.fingerprint, clone(finding2));
77
+ else merge(existing, finding2);
78
+ }
79
+ return [...byPrint.values()].sort((a, b) => compareText(a.fingerprint, b.fingerprint));
80
+ }
81
+ function dedupeRun(findings) {
82
+ const ordered = [...findings].sort(
83
+ (a, b) => compareTests(a.firstSeen, b.firstSeen) || compareText(evidenceKeys(a), evidenceKeys(b))
84
+ );
85
+ return dedupeTest(ordered);
86
+ }
87
+ var evidenceKeys = (f) => f.evidence.map(evidenceKey).join("");
88
+
89
+ // src/core/patterns/entropy.ts
90
+ function entropy(text) {
91
+ if (text.length === 0) return 0;
92
+ const counts = /* @__PURE__ */ new Map();
93
+ for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
94
+ const length = [...text].length;
95
+ let bits = 0;
96
+ for (const count of counts.values()) {
97
+ const p = count / length;
98
+ bits -= p * Math.log2(p);
99
+ }
100
+ return bits;
101
+ }
102
+ var TOKEN_MIN_LENGTH = 16;
103
+ var TOKEN_MIN_ENTROPY = 3.5;
104
+ var JWT = /^eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*$/;
105
+ function looksLikeJwt(value) {
106
+ return JWT.test(value);
107
+ }
108
+ function looksLikeToken(value) {
109
+ if (looksLikeJwt(value)) return true;
110
+ return value.length >= TOKEN_MIN_LENGTH && entropy(value) >= TOKEN_MIN_ENTROPY;
111
+ }
112
+
113
+ // src/core/patterns/jwt.ts
114
+ var JWT_IN_TEXT = /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g;
115
+ var BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
116
+ function base64UrlDecode(input) {
117
+ let bits = 0;
118
+ let value = 0;
119
+ const bytes = [];
120
+ for (const ch of input.replace(/=+$/, "")) {
121
+ const index = BASE64URL.indexOf(ch === "+" ? "-" : ch === "/" ? "_" : ch);
122
+ if (index < 0) return null;
123
+ value = value << 6 | index;
124
+ bits += 6;
125
+ if (bits >= 8) {
126
+ bits -= 8;
127
+ bytes.push(value >> bits & 255);
128
+ }
129
+ }
130
+ try {
131
+ return new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array(bytes));
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+ function parseObject(text) {
137
+ if (text === null) return null;
138
+ try {
139
+ const value = JSON.parse(text);
140
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
141
+ } catch {
142
+ return null;
143
+ }
144
+ }
145
+ function decodeJwt(token) {
146
+ const parts = token.split(".");
147
+ if (parts.length !== 3) return null;
148
+ const header2 = parseObject(base64UrlDecode(parts[0] ?? ""));
149
+ if (header2 === null || typeof header2.alg !== "string") return null;
150
+ return { header: header2, payload: parseObject(base64UrlDecode(parts[1] ?? "")) };
151
+ }
152
+
153
+ // src/core/patterns/secrets.ts
154
+ var SECRET_PATTERNS = [
155
+ {
156
+ name: "aws-access-key",
157
+ title: "AWS access key",
158
+ regex: /\bAKIA[0-9A-Z]{16}\b/g,
159
+ confidence: "high"
160
+ },
161
+ {
162
+ name: "aws-secret-key",
163
+ title: "AWS secret access key",
164
+ regex: /aws(?:.{0,20})?(?:secret|private).{0,20}['"][0-9a-zA-Z/+]{40}['"]/gi,
165
+ confidence: "high"
166
+ },
167
+ {
168
+ name: "github-token",
169
+ title: "GitHub token",
170
+ regex: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/g,
171
+ confidence: "high"
172
+ },
173
+ {
174
+ name: "stripe-secret-key",
175
+ title: "Stripe secret key",
176
+ regex: /\bsk_live_[0-9a-zA-Z]{24,}\b/g,
177
+ confidence: "high"
178
+ },
179
+ {
180
+ name: "slack-token",
181
+ title: "Slack token",
182
+ regex: /\bxox[baprs]-[0-9A-Za-z-]{10,}/g,
183
+ confidence: "high"
184
+ },
185
+ {
186
+ name: "private-key",
187
+ title: "Private key",
188
+ regex: /-----BEGIN (?:RSA |EC |OPENSSH |DSA |)PRIVATE KEY-----/g,
189
+ confidence: "high"
190
+ },
191
+ // Maps and Firebase keys are public by design (06, chapter 4.8).
192
+ {
193
+ name: "google-api-key",
194
+ title: "Google API key",
195
+ regex: /\bAIza[0-9A-Za-z_-]{35}\b/g,
196
+ confidence: "low"
197
+ },
198
+ {
199
+ name: "generic-secret",
200
+ title: "Generic secret assignment",
201
+ regex: /\b(?:secret|client_secret|api_secret)["']?\s*[:=]\s*["'][^"'\s]{8,}["']/gi,
202
+ confidence: "low",
203
+ offByDefault: true
204
+ }
205
+ ];
206
+
207
+ // src/core/fingerprint/redact.ts
208
+ var MAX_SNIPPET = 200;
209
+ var SNIPPET_CONTEXT = 80;
210
+ var SENSITIVE_PARAMS = [
211
+ "token",
212
+ "access_token",
213
+ "id_token",
214
+ "refresh_token",
215
+ "api_key",
216
+ "apikey",
217
+ "password",
218
+ "passwd",
219
+ "secret",
220
+ "session",
221
+ "sessionid",
222
+ "jwt",
223
+ "auth"
224
+ ];
225
+ var SENSITIVE_HEADER = /^(?:cookie|set-cookie|authorization|proxy-authorization|x-api-key|x-auth-token)$/i;
226
+ var SENSITIVE_HEADER_PART = /token|secret|key|auth|session|passw/i;
227
+ function isSensitiveHeader(name) {
228
+ return SENSITIVE_HEADER.test(name) || SENSITIVE_HEADER_PART.test(name);
229
+ }
230
+ var PLACEHOLDER = /\[(?:redacted |jwt [^\]]*|)sha256:[0-9a-f]{6}\]/g;
231
+ var TOKEN_RUN = /[A-Za-z0-9+/_=-]{24,}/g;
232
+ var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
233
+ function escapeRegex(text) {
234
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
235
+ }
236
+ var Redactor = class {
237
+ #salt;
238
+ #params;
239
+ constructor(options) {
240
+ this.#salt = options.salt;
241
+ const names = [.../* @__PURE__ */ new Set([...SENSITIVE_PARAMS, ...options.paramNames ?? []])];
242
+ this.#params = new RegExp(
243
+ `([?&;#]|\\b)(${names.map(escapeRegex).join("|")})=([^&#\\s"'<>;]+)`,
244
+ "gi"
245
+ );
246
+ }
247
+ /** First 6 hex digits of the salted SHA-256 of `value` (07-REQ-15). */
248
+ hash(value) {
249
+ return sha256(`${this.#salt}\0${value}`).slice(0, 6);
250
+ }
251
+ /** `[redacted sha256:xxxxxx]` */
252
+ value(value) {
253
+ return `[redacted sha256:${this.hash(value)}]`;
254
+ }
255
+ /** `eyJ…[jwt alg=HS256 sha256:xxxxxx]` (07-REQ-13). */
256
+ jwt(token) {
257
+ const alg = decodeJwt(token)?.header.alg;
258
+ const algText = typeof alg === "string" ? ` alg=${alg.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 16)}` : "";
259
+ return `eyJ…[jwt${algText} sha256:${this.hash(token)}]`;
260
+ }
261
+ /** The first 4 characters and `…[sha256:xxxxxx]` (07-REQ-13). */
262
+ secret(match) {
263
+ return `${match.slice(0, 4)}…[sha256:${this.hash(match)}]`;
264
+ }
265
+ /** A header value as it may appear in evidence (07-REQ-13). */
266
+ header(name, value) {
267
+ const lower2 = name.toLowerCase();
268
+ if (lower2 === "set-cookie") return this.setCookie(value);
269
+ if (lower2 === "cookie") {
270
+ return value.split(";").map((pair) => {
271
+ const eq = pair.indexOf("=");
272
+ return eq < 0 ? pair.trim() : `${pair.slice(0, eq).trim()}=${this.value(pair.slice(eq + 1).trim())}`;
273
+ }).join("; ");
274
+ }
275
+ if (lower2 === "authorization" || lower2 === "proxy-authorization") {
276
+ const space = value.indexOf(" ");
277
+ const scheme = space > 0 ? value.slice(0, space) : "";
278
+ const credentials = space > 0 ? value.slice(space + 1).trim() : value;
279
+ const redacted = decodeJwt(credentials) !== null ? this.jwt(credentials) : this.value(credentials);
280
+ return scheme === "" ? redacted : `${scheme} ${redacted}`;
281
+ }
282
+ if (isSensitiveHeader(lower2)) return this.value(value);
283
+ return this.text(value);
284
+ }
285
+ /** A Set-Cookie value with its cookie value replaced; attributes are kept (07-REQ-13). */
286
+ setCookie(value) {
287
+ const semi = value.indexOf(";");
288
+ const pair = semi < 0 ? value : value.slice(0, semi);
289
+ const attributes = semi < 0 ? "" : value.slice(semi);
290
+ const eq = pair.indexOf("=");
291
+ const name = eq < 0 ? "" : pair.slice(0, eq).trim();
292
+ const cookieValue = eq < 0 ? pair : pair.slice(eq + 1);
293
+ return this.text(`${name}=${this.value(cookieValue.trim())}${attributes}`);
294
+ }
295
+ /**
296
+ * The final filter for any text (07-REQ-12, 07-REQ-13): JWTs, secret patterns, values of
297
+ * sensitive query parameters, Bearer credentials and long high-entropy strings are redacted;
298
+ * control characters are replaced; the result is at most MAX_SNIPPET characters.
299
+ */
300
+ text(input) {
301
+ const kept = [];
302
+ const clean = input.replace(/\r\n|[\r\n\t]/g, " ").replace(CONTROL, "?");
303
+ let text = clean.replace(PLACEHOLDER, (m2) => {
304
+ kept.push(m2);
305
+ return `${kept.length - 1}`;
306
+ });
307
+ const keep = (m2) => {
308
+ kept.push(m2);
309
+ return `${kept.length - 1}`;
310
+ };
311
+ text = text.replace(JWT_IN_TEXT, (m2) => keep(this.jwt(m2)));
312
+ for (const pattern of SECRET_PATTERNS) {
313
+ text = text.replace(
314
+ new RegExp(pattern.regex.source, pattern.regex.flags),
315
+ (m2) => keep(this.secret(m2))
316
+ );
317
+ }
318
+ text = text.replace(
319
+ /\b(Bearer|Basic)\s+([A-Za-z0-9._~+/=-]{8,})/g,
320
+ (_m, scheme, value) => keep(`${scheme} ${this.value(value)}`)
321
+ );
322
+ text = text.replace(
323
+ this.#params,
324
+ (_m, lead, name, value) => keep(`${lead}${name}=${this.value(value)}`)
325
+ );
326
+ text = text.replace(
327
+ TOKEN_RUN,
328
+ (m2) => /[0-9]/.test(m2) && /[A-Za-z]/.test(m2) && entropy(m2) >= 3.5 ? keep(this.value(m2)) : m2
329
+ );
330
+ text = text.replace(/\u0001(\d+)\u0001/g, (_m, i) => kept[Number(i)] ?? "");
331
+ return truncate(text, MAX_SNIPPET);
332
+ }
333
+ /** A snippet of `text` around [index, index + length) (07-REQ-14), redacted. */
334
+ snippet(text, index, length) {
335
+ const start = Math.max(0, index - SNIPPET_CONTEXT);
336
+ const end = Math.min(text.length, index + length + SNIPPET_CONTEXT);
337
+ const prefix = start > 0 ? "…" : "";
338
+ const suffix = end < text.length ? "…" : "";
339
+ return this.text(`${prefix}${text.slice(start, end)}${suffix}`);
340
+ }
341
+ /** Every evidence snippet and the message through the final filter (07-REQ-12). */
342
+ enforce(finding2) {
343
+ return {
344
+ ...finding2,
345
+ message: this.text(finding2.message),
346
+ evidence: finding2.evidence.map((e) => ({ ...e, snippet: this.text(e.snippet) }))
347
+ };
348
+ }
349
+ };
350
+ function truncate(text, max) {
351
+ if (text.length <= max) return text;
352
+ let cut = max - 1;
353
+ const code = text.charCodeAt(cut - 1);
354
+ if (code >= 55296 && code <= 56319) cut -= 1;
355
+ return `${text.slice(0, cut)}…`;
356
+ }
357
+
358
+ // src/core/fingerprint/names.ts
359
+ var UUID = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;
360
+ var DIGITS = /^[0-9]{6,}$/;
361
+ var HEX = /^(?=.*[0-9])[0-9a-f]{8,}$/i;
362
+ var UPPER_ID = /^(?=.*[0-9])(?=.*[A-Z])[A-Z0-9]{5,}$/;
363
+ var RANDOM = /^(?=.*[0-9])(?=.*[A-Za-z])[A-Za-z0-9]{16,}$/;
364
+ function isDynamic(part) {
365
+ return UUID.test(part) || DIGITS.test(part) || HEX.test(part) || UPPER_ID.test(part) || RANDOM.test(part);
366
+ }
367
+ function normalizeName(name) {
368
+ const uuid = /^(.*[^_\-.:][_\-.:])[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.exec(name);
369
+ if (uuid !== null) return `${uuid[1] ?? ""}*`;
370
+ const match = /^(.*[_\-.:])([^_\-.:]+)$/.exec(name);
371
+ if (match === null) return name;
372
+ const [, prefix = "", suffix = ""] = match;
373
+ if (prefix.replace(/[_\-.:]/g, "") === "") return name;
374
+ return isDynamic(suffix) ? `${prefix}*` : name;
375
+ }
376
+ function normalizeCookieDomain(domain) {
377
+ return domain.replace(/^\./, "").toLowerCase();
378
+ }
379
+ function cookieSubject(name, domain) {
380
+ return `${normalizeName(name)}@${normalizeCookieDomain(domain)}`;
381
+ }
382
+ var BUILD_HASH = /^(?:(?=.*[0-9])[0-9a-f]{8,}|[0-9]{8,}|(?=.*[0-9])(?=.*[A-Za-z])[A-Za-z0-9_]{8,})$/i;
383
+ function normalizeSegment(segment) {
384
+ return segment.split(/([.\-~])/).map((part) => BUILD_HASH.test(part) ? "*" : part).join("");
385
+ }
386
+ function normalizeAssetUrl(text) {
387
+ if (!URL.canParse(text)) return null;
388
+ const url = new URL(text);
389
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
390
+ const path = url.pathname.split("/").map((segment) => normalizeSegment(segment)).join("/");
391
+ return `${url.origin}${path}`;
392
+ }
393
+
394
+ // src/core/rules/types.ts
395
+ function finding(ctx, manifest, fields) {
396
+ return {
397
+ ruleId: manifest.id,
398
+ scope: fields.scope ?? manifest.scope,
399
+ severity: fields.severity ?? ctx.severity,
400
+ confidence: fields.confidence ?? ctx.confidence,
401
+ ...fields
402
+ };
403
+ }
404
+ function header(headers2, name) {
405
+ return headers2.find((h) => h.name === name)?.value;
406
+ }
407
+ function headers(list, name) {
408
+ return list.filter((h) => h.name === name).map((h) => h.value);
409
+ }
410
+ function isJson(contentType) {
411
+ if (contentType === void 0) return false;
412
+ const type = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
413
+ return type === "application/json" || type.endsWith("+json");
414
+ }
415
+ function manifestOf(id) {
416
+ const found = ruleManifest(id);
417
+ if (found === void 0) throw new Error(`no manifest entry for ${id}`);
418
+ return found;
419
+ }
420
+ function transportConfidence(ctx) {
421
+ return ctx.localDev ? "low" : ctx.confidence;
422
+ }
423
+
424
+ // src/core/rules/browser.ts
425
+ var isRecord = (input) => typeof input === "object" && input !== null && "status" in input;
426
+ var isHtmlDoc = (r) => r.resourceType === "document" && r.status >= 200 && r.status < 300 && /html/i.test(header(r.responseHeaders, "content-type") ?? "text/html");
427
+ var CSP_VIOLATION = manifestOf("browser.csp-violation");
428
+ var cspViolation = {
429
+ id: CSP_VIOLATION.id,
430
+ manifest: CSP_VIOLATION,
431
+ appliesTo: { events: ["csp-violation"], sources: ["browser"] },
432
+ check(input, ctx) {
433
+ if (!("kind" in input) || input.kind !== "csp-violation" || input.directive === "") return [];
434
+ return [
435
+ finding(ctx, CSP_VIOLATION, {
436
+ subject: input.documentOrigin,
437
+ discriminator: input.directive,
438
+ location: { origin: input.documentOrigin },
439
+ evidence: [
440
+ {
441
+ kind: "event",
442
+ name: input.directive,
443
+ snippet: `${input.disposition}: ${input.directive} blocked ${ctx.redact.text(input.blockedOrigin)}`
444
+ }
445
+ ],
446
+ message: `The browser reported a CSP violation of ${input.directive} (${input.disposition === "enforce" ? "blocked" : "report-only"}) on ${input.documentOrigin}.`
447
+ })
448
+ ];
449
+ },
450
+ docs: {
451
+ title: CSP_VIOLATION.title,
452
+ why: "A violation means the page tried to load or run something the policy forbids: a broken feature, a policy to adjust, or an injection attempt.",
453
+ fix: [
454
+ "Find the blocked resource or inline script and either allow it explicitly (a nonce or hash, an origin in the right directive) or remove it.",
455
+ "",
456
+ "- nginx: adjust the `add_header Content-Security-Policy` value",
457
+ "- Express: adjust the `helmet.contentSecurityPolicy` directives",
458
+ "- Spring Security: adjust `contentSecurityPolicy(csp -> csp.policyDirectives(…))`"
459
+ ].join("\n"),
460
+ falsePositives: "Browser extensions and the browser's own requests can cause violations; /favicon.ico is ignored."
461
+ }
462
+ };
463
+ var SRI = manifestOf("asset.sri-missing");
464
+ var TAGS = /<(script|link)\b([^>]*)>/gi;
465
+ var attr = (attributes, name) => {
466
+ const m2 = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(
467
+ attributes
468
+ );
469
+ return m2 === null ? void 0 : m2[1] ?? m2[2] ?? m2[3];
470
+ };
471
+ var sriMissing = {
472
+ id: SRI.id,
473
+ manifest: SRI,
474
+ appliesTo: { resourceTypes: ["document"] },
475
+ needsBody: ["document"],
476
+ check(input, ctx) {
477
+ if (!isRecord(input) || !isHtmlDoc(input) || input.body === void 0) return [];
478
+ const out = [];
479
+ const seen = /* @__PURE__ */ new Set();
480
+ for (const m2 of input.body.text.matchAll(TAGS)) {
481
+ const tag = (m2[1] ?? "").toLowerCase();
482
+ const attributes = m2[2] ?? "";
483
+ if (tag === "link" && !/\brel\s*=\s*["']?stylesheet/i.test(attributes)) continue;
484
+ const ref = attr(attributes, tag === "script" ? "src" : "href");
485
+ if (ref === void 0 || attr(attributes, "integrity") !== void 0) continue;
486
+ let url;
487
+ try {
488
+ url = new URL(ref, input.url);
489
+ } catch {
490
+ continue;
491
+ }
492
+ const origin = canonicalOrigin(url.href);
493
+ if (origin === null || ctx.inScope(origin)) continue;
494
+ const subject = normalizeAssetUrl(url.href);
495
+ if (subject === null || seen.has(subject)) continue;
496
+ seen.add(subject);
497
+ out.push(
498
+ finding(ctx, SRI, {
499
+ subject,
500
+ location: { origin: input.origin, endpointKey: input.endpointKey },
501
+ evidence: [
502
+ {
503
+ kind: "body",
504
+ snippet: ctx.redact.text(
505
+ `<${tag} ${tag === "script" ? "src" : "href"}="${url.href}">`
506
+ )
507
+ }
508
+ ],
509
+ message: `${input.endpointKey} loads ${subject} from another origin without Subresource Integrity.`
510
+ })
511
+ );
512
+ }
513
+ return out;
514
+ },
515
+ docs: {
516
+ title: SRI.title,
517
+ why: "A script or stylesheet from a third-party server runs with the rights of your page; if that server or CDN is compromised, so is your page.",
518
+ fix: [
519
+ 'Add `integrity="sha384-…"` and `crossorigin="anonymous"` to third-party `<script>` and `<link rel="stylesheet">` tags, or host the files yourself.',
520
+ "",
521
+ "- nginx: serve third-party files from your own origin (`location /vendor/ { … }`)",
522
+ "- Express: generate the tags with integrity hashes (e.g. `webpack-subresource-integrity`)",
523
+ "- Spring: add `integrity` attributes in the templates (Thymeleaf `th:attr`)"
524
+ ].join("\n"),
525
+ falsePositives: "Scripts that change on every request (analytics loaders) cannot have SRI: accept them with a note."
526
+ }
527
+ };
528
+ var REDIRECT = manifestOf("browser.open-redirect-candidate");
529
+ var openRedirectCandidate = {
530
+ id: REDIRECT.id,
531
+ manifest: REDIRECT,
532
+ appliesTo: {},
533
+ check(input, ctx) {
534
+ if (!isRecord(input) || input.status < 300 || input.status > 399) return [];
535
+ const location = header(input.responseHeaders, "location");
536
+ if (location === void 0) return [];
537
+ let target;
538
+ let request;
539
+ try {
540
+ request = new URL(input.url);
541
+ target = new URL(location, input.url);
542
+ } catch {
543
+ return [];
544
+ }
545
+ if (!/^https?:\/\//i.test(location) && !location.startsWith("//")) return [];
546
+ if (target.host === request.host) return [];
547
+ const names = new Set(
548
+ (ctx.options.paramNames ?? []).map((n) => n.toLowerCase())
549
+ );
550
+ const same = (value) => {
551
+ try {
552
+ return new URL(value, input.url).href === target.href;
553
+ } catch {
554
+ return false;
555
+ }
556
+ };
557
+ const params = [...request.searchParams].filter(([, value]) => value !== "" && same(value));
558
+ const hit = params.find(([name]) => names.has(name.toLowerCase())) ?? params[0];
559
+ if (hit === void 0) return [];
560
+ return [
561
+ finding(ctx, REDIRECT, {
562
+ subject: input.endpointKey,
563
+ discriminator: hit[0],
564
+ location: { origin: input.origin, endpointKey: input.endpointKey, param: hit[0] },
565
+ evidence: [
566
+ {
567
+ kind: "header",
568
+ name: "location",
569
+ snippet: ctx.redact.text(`${input.status} → ${target.origin}${target.pathname}`)
570
+ }
571
+ ],
572
+ message: `${input.endpointKey} redirects to another host taken from the parameter "${hit[0]}".`
573
+ })
574
+ ];
575
+ },
576
+ docs: {
577
+ title: REDIRECT.title,
578
+ why: "A redirect that goes wherever a parameter says lets phishing links start on your trusted domain; confirmation needs an active test (stage E3).",
579
+ fix: [
580
+ "Redirect only to relative paths or to an allow-list of hosts.",
581
+ "",
582
+ "- nginx: do not build `return 302 $arg_next;` from parameters",
583
+ "- Express: `const next = allowed.has(new URL(req.query.next, base).host) ? req.query.next : '/'`",
584
+ "- Spring Security: `DefaultRedirectStrategy` with `setContextRelative(true)` or a validated target"
585
+ ].join("\n"),
586
+ falsePositives: "SSO flows that redirect to registered client URLs on purpose: accept them with a note."
587
+ }
588
+ };
589
+ var REFLECTED = manifestOf("browser.reflected-param");
590
+ var TRIVIAL = /* @__PURE__ */ new Set(["true", "false", "null", "undefined", "none", "asc", "desc", "default"]);
591
+ var reflectedParam = {
592
+ id: REFLECTED.id,
593
+ manifest: REFLECTED,
594
+ appliesTo: { resourceTypes: ["document"] },
595
+ needsBody: ["document"],
596
+ check(input, ctx) {
597
+ if (!isRecord(input) || !isHtmlDoc(input) || input.body === void 0) return [];
598
+ let url;
599
+ try {
600
+ url = new URL(input.url);
601
+ } catch {
602
+ return [];
603
+ }
604
+ const min = typeof ctx.options.minLength === "number" ? ctx.options.minLength : 6;
605
+ const out = [];
606
+ for (const [name, value] of url.searchParams) {
607
+ if (value.length < min || /^\d+$/.test(value) || TRIVIAL.has(value.toLowerCase())) continue;
608
+ const index = input.body.text.indexOf(value);
609
+ if (index < 0 || out.some((f) => f.discriminator === name)) continue;
610
+ out.push(
611
+ finding(ctx, REFLECTED, {
612
+ subject: input.endpointKey,
613
+ discriminator: name,
614
+ location: { origin: input.origin, endpointKey: input.endpointKey, param: name },
615
+ evidence: [
616
+ {
617
+ kind: "body",
618
+ name,
619
+ snippet: ctx.redact.snippet(input.body.text, index, value.length)
620
+ }
621
+ ],
622
+ message: `The value of the parameter "${name}" appears unencoded in the HTML of ${input.endpointKey}.`
623
+ })
624
+ );
625
+ }
626
+ return out;
627
+ },
628
+ docs: {
629
+ title: REFLECTED.title,
630
+ why: "A reflected parameter is where reflected XSS starts; it is only a candidate until an active test (stage E3) confirms it, so it never blocks.",
631
+ fix: [
632
+ "Encode every reflected value for its HTML context (templates with auto-escaping) and keep a strict CSP.",
633
+ "",
634
+ "- nginx: nothing to configure; add a CSP (`add_header Content-Security-Policy \"script-src 'self'\"`)",
635
+ "- Express: render with an auto-escaping template engine; never concatenate `req.query` into HTML",
636
+ "- Spring: Thymeleaf `th:text` (escaped), not `th:utext`"
637
+ ].join("\n"),
638
+ falsePositives: "Safe reflections such as search terms shown escaped (letters and digits look the same encoded). Reported as info with low confidence."
639
+ }
640
+ };
641
+ var BROWSER_RULES = [
642
+ cspViolation,
643
+ sriMissing,
644
+ openRedirectCandidate,
645
+ reflectedParam
646
+ ];
647
+
648
+ // src/core/rules/cookies.ts
649
+ function parseSetCookie(header2) {
650
+ const [pair = "", ...attributes] = header2.split(";");
651
+ const eq = pair.indexOf("=");
652
+ if (eq <= 0) return null;
653
+ const cookie = {
654
+ name: pair.slice(0, eq).trim(),
655
+ value: pair.slice(eq + 1).trim(),
656
+ secure: false,
657
+ httpOnly: false
658
+ };
659
+ for (const attribute of attributes) {
660
+ const i = attribute.indexOf("=");
661
+ const key = (i < 0 ? attribute : attribute.slice(0, i)).trim().toLowerCase();
662
+ const value = i < 0 ? "" : attribute.slice(i + 1).trim();
663
+ if (key === "secure") cookie.secure = true;
664
+ else if (key === "httponly") cookie.httpOnly = true;
665
+ else if (key === "samesite") cookie.sameSite = value;
666
+ else if (key === "max-age" && /^-?\d+$/.test(value)) cookie.maxAge = Number(value);
667
+ else if (key === "expires") cookie.expires = value;
668
+ else if (key === "domain") cookie.domain = value;
669
+ else if (key === "path") cookie.path = value;
670
+ }
671
+ return cookie;
672
+ }
673
+ function isDeletion(cookie, now) {
674
+ if (cookie.value === "" || cookie.value === '""') return true;
675
+ if (cookie.maxAge !== void 0 && cookie.maxAge <= 0) return true;
676
+ if (cookie.expires !== void 0 && now !== void 0) {
677
+ const at = Date.parse(cookie.expires);
678
+ if (Number.isFinite(at) && at <= now) return true;
679
+ }
680
+ return false;
681
+ }
682
+ var NON_SESSION_NAMES = NON_SESSION_COOKIES;
683
+ function matchesName(name, patterns) {
684
+ return patterns.some(
685
+ (p) => p.endsWith("*") ? name.startsWith(p.slice(0, -1)) : name.toLowerCase() === p.toLowerCase()
686
+ );
687
+ }
688
+ var OPAQUE = /^[A-Za-z0-9+/=_%-]+$/;
689
+ function isSessionCookie(name, value, pattern, nonSession = NON_SESSION_NAMES) {
690
+ if (matchesName(name, nonSession)) return false;
691
+ let re;
692
+ try {
693
+ re = new RegExp(pattern, "i");
694
+ } catch {
695
+ re = /(sess|sid|auth|token|jwt)/i;
696
+ }
697
+ if (re.test(name)) return true;
698
+ return looksLikeJwt(value) || OPAQUE.test(value) && looksLikeToken(value);
699
+ }
700
+
701
+ // src/core/rules/cookie.ts
702
+ function fromRecord(r) {
703
+ const date = header(r.responseHeaders, "date");
704
+ const now = date === void 0 ? void 0 : Date.parse(date);
705
+ const out = [];
706
+ for (const raw of headers(r.responseHeaders, "set-cookie")) {
707
+ for (const line of raw.split("\n")) {
708
+ const c = parseSetCookie(line);
709
+ if (c === null || isDeletion(c, Number.isFinite(now) ? now : void 0)) continue;
710
+ let lifetime = c.maxAge;
711
+ if (lifetime === void 0 && c.expires !== void 0 && now !== void 0 && Number.isFinite(now)) {
712
+ const at = Date.parse(c.expires);
713
+ if (Number.isFinite(at)) lifetime = Math.round((at - now) / 1e3);
714
+ }
715
+ out.push({
716
+ name: c.name,
717
+ value: c.value,
718
+ secure: c.secure,
719
+ httpOnly: c.httpOnly,
720
+ sameSite: c.sameSite,
721
+ sameSiteKnown: true,
722
+ lifetime,
723
+ domain: c.domain ?? new URL(r.url).hostname,
724
+ https: r.url.startsWith("https:"),
725
+ origin: r.origin,
726
+ endpointKey: r.endpointKey,
727
+ evidence: (ctx) => ctx.redact.setCookie(line)
728
+ });
729
+ }
730
+ }
731
+ return out;
732
+ }
733
+ function fromJar(event) {
734
+ return event.cookies.filter((c) => c.value !== "" && c.origin !== void 0).map((c) => ({
735
+ name: c.name,
736
+ value: c.value,
737
+ secure: c.secure,
738
+ httpOnly: c.httpOnly,
739
+ sameSite: c.sameSite,
740
+ sameSiteKnown: false,
741
+ lifetime: void 0,
742
+ domain: c.domain,
743
+ https: (c.origin ?? "").startsWith("https:"),
744
+ origin: c.origin ?? "",
745
+ evidence: (ctx) => `${c.name}=${ctx.redact.value(c.value)}${c.secure ? "; Secure" : ""}${c.httpOnly ? "; HttpOnly" : ""}; SameSite=${c.sameSite} (cookie jar)`
746
+ }));
747
+ }
748
+ function cookiesOf(input) {
749
+ if ("status" in input) return fromRecord(input);
750
+ if (input.kind === "cookie-jar") return fromJar(input);
751
+ return [];
752
+ }
753
+ var sessionPattern = (ctx) => typeof ctx.options.sessionNamePattern === "string" ? ctx.options.sessionNamePattern : "sess|sid|auth|token";
754
+ function cookieFinding(ctx, m2, c, message, confidence) {
755
+ const location = { origin: c.origin };
756
+ if (c.endpointKey !== void 0) location.endpointKey = c.endpointKey;
757
+ return finding(ctx, m2, {
758
+ subject: cookieSubject(c.name, c.domain),
759
+ location,
760
+ evidence: [{ kind: "cookie", name: c.name, snippet: c.evidence(ctx) }],
761
+ message,
762
+ ...confidence === void 0 ? {} : { confidence }
763
+ });
764
+ }
765
+ function cookieRule(id, test, docs, headersOnly = false) {
766
+ const m2 = manifestOf(id);
767
+ return {
768
+ id,
769
+ manifest: m2,
770
+ // Headers of every in-scope response; the cookie jar too unless the rule needs attributes
771
+ // the jar cannot give (SameSite missing, lifetime).
772
+ appliesTo: headersOnly ? {} : { events: ["cookie-jar"], records: true },
773
+ check(input, ctx) {
774
+ const out = [];
775
+ for (const c of cookiesOf(input)) {
776
+ if (headersOnly && !c.sameSiteKnown) continue;
777
+ const hit = test(c, ctx);
778
+ if (hit !== null) out.push(cookieFinding(ctx, m2, c, hit.message, hit.confidence));
779
+ }
780
+ return out;
781
+ },
782
+ docs: { title: m2.title, ...docs }
783
+ };
784
+ }
785
+ var isSession = (c, ctx) => isSessionCookie(
786
+ c.name,
787
+ c.value,
788
+ sessionPattern(ctx),
789
+ Array.isArray(ctx.options.nonSessionNames) ? ctx.options.nonSessionNames : void 0
790
+ );
791
+ var cookieFix = (attributes, express, spring) => [
792
+ `Set the cookie with \`${attributes}\`.`,
793
+ "",
794
+ `- nginx (as a proxy): \`proxy_cookie_flags ~ ${attributes.replace(/; /g, " ").toLowerCase()};\``,
795
+ `- Express: \`res.cookie('sid', value, ${express})\` (or the \`cookie\` options of \`express-session\`)`,
796
+ `- Spring Boot: \`${spring}\``
797
+ ].join("\n");
798
+ var EXPRESS_SESSION = "{ secure: true, httpOnly: true, sameSite: 'lax' }";
799
+ var noSecure = cookieRule(
800
+ "cookie.no-secure",
801
+ (c, ctx) => c.https && !c.secure && isSession(c, ctx) ? {
802
+ message: `Session cookie ${c.name} is set over HTTPS without Secure.`,
803
+ confidence: transportConfidence(ctx)
804
+ } : null,
805
+ {
806
+ why: "A cookie without Secure is also sent over plain HTTP, where anyone on the network can read the session and take over the account.",
807
+ fix: cookieFix(
808
+ "Secure; HttpOnly; SameSite=Lax",
809
+ EXPRESS_SESSION,
810
+ "server.servlet.session.cookie.secure=true"
811
+ ),
812
+ falsePositives: "Local development over HTTP is reported with low confidence only."
813
+ }
814
+ );
815
+ var noHttpOnly = cookieRule(
816
+ "cookie.no-httponly",
817
+ (c, ctx) => {
818
+ if (c.httpOnly || !isSession(c, ctx)) return null;
819
+ const exceptions = Array.isArray(ctx.options.httpOnlyExceptions) ? ctx.options.httpOnlyExceptions.map((n) => n.toLowerCase()) : [];
820
+ if (exceptions.includes(c.name.toLowerCase())) return null;
821
+ return { message: `Session cookie ${c.name} is readable by JavaScript (no HttpOnly).` };
822
+ },
823
+ {
824
+ why: "A session cookie without HttpOnly can be read by any script on the page, so a single XSS steals the session.",
825
+ fix: cookieFix(
826
+ "Secure; HttpOnly; SameSite=Lax",
827
+ EXPRESS_SESSION,
828
+ "server.servlet.session.cookie.http-only=true"
829
+ ),
830
+ falsePositives: "CSRF tokens meant to be read by JavaScript (XSRF-TOKEN, csrftoken) are excluded by the option httpOnlyExceptions; add your own names there."
831
+ }
832
+ );
833
+ var sameSiteNone = cookieRule(
834
+ "cookie.samesite-none",
835
+ (c, ctx) => c.sameSite?.toLowerCase() === "none" && isSession(c, ctx) ? {
836
+ message: `Session cookie ${c.name} has SameSite=None and is sent with cross-site requests.`
837
+ } : null,
838
+ {
839
+ why: "SameSite=None sends the session with requests started by other sites, which re-enables CSRF and cross-site leaks.",
840
+ fix: cookieFix(
841
+ "Secure; HttpOnly; SameSite=Lax",
842
+ EXPRESS_SESSION,
843
+ "server.servlet.session.cookie.same-site=lax"
844
+ ),
845
+ falsePositives: "Apps embedded in third-party sites (SSO, widgets) need SameSite=None: accept with a note."
846
+ }
847
+ );
848
+ var sameSiteMissing = cookieRule(
849
+ "cookie.samesite-missing",
850
+ (c) => c.sameSite === void 0 ? { message: `Cookie ${c.name} has no SameSite attribute.` } : null,
851
+ {
852
+ why: "Without SameSite the browser default applies (Lax in current browsers, None in old ones); being explicit avoids surprises.",
853
+ fix: cookieFix(
854
+ "Secure; HttpOnly; SameSite=Lax",
855
+ EXPRESS_SESSION,
856
+ "server.servlet.session.cookie.same-site=lax"
857
+ ),
858
+ falsePositives: "Reported as info: current browsers treat a missing SameSite as Lax."
859
+ },
860
+ true
861
+ );
862
+ var longLivedSession = cookieRule(
863
+ "cookie.long-lived-session",
864
+ (c, ctx) => {
865
+ const days = typeof ctx.options.maxSessionDays === "number" ? ctx.options.maxSessionDays : 30;
866
+ if (c.lifetime === void 0 || c.lifetime <= days * 86400 || !isSession(c, ctx)) return null;
867
+ return {
868
+ message: `Session cookie ${c.name} lives ${Math.round(c.lifetime / 86400)} days (limit ${days}).`
869
+ };
870
+ },
871
+ {
872
+ why: "A long-lived session stays valid on shared or stolen devices long after the user left.",
873
+ fix: cookieFix(
874
+ "Secure; HttpOnly; SameSite=Lax; Max-Age=86400",
875
+ "{ secure: true, httpOnly: true, sameSite: 'lax', maxAge: 86_400_000 }",
876
+ "server.servlet.session.timeout=30m"
877
+ ),
878
+ falsePositives: '"Remember me" cookies are long-lived by design: accept them with a note. The limit is the option maxSessionDays.'
879
+ },
880
+ true
881
+ );
882
+ var nonSessionInsecure = cookieRule(
883
+ "cookie.non-session-insecure",
884
+ (c, ctx) => c.https && !c.secure && !isSession(c, ctx) ? { message: `Cookie ${c.name} is set over HTTPS without Secure.` } : null,
885
+ {
886
+ why: "Cookies without Secure also travel over plain HTTP; even non-session cookies can carry preferences or tracking data.",
887
+ fix: cookieFix(
888
+ "Secure; SameSite=Lax",
889
+ "{ secure: true, sameSite: 'lax' }",
890
+ "cookie.setSecure(true)"
891
+ ),
892
+ falsePositives: "Reported as info."
893
+ }
894
+ );
895
+ var COOKIE_RULES = [
896
+ noSecure,
897
+ noHttpOnly,
898
+ sameSiteNone,
899
+ sameSiteMissing,
900
+ longLivedSession,
901
+ nonSessionInsecure
902
+ ];
903
+
904
+ // src/core/rules/cors.ts
905
+ function corsOf(input) {
906
+ if (typeof input !== "object" || input === null || !("status" in input)) return null;
907
+ const r = input;
908
+ const origin = header(r.requestHeaders, "origin");
909
+ if (origin === void 0 && r.method !== "OPTIONS") return null;
910
+ const acao = header(r.responseHeaders, "access-control-allow-origin");
911
+ if (acao === void 0) return null;
912
+ const acac = header(r.responseHeaders, "access-control-allow-credentials");
913
+ return {
914
+ record: r,
915
+ origin,
916
+ acao: acao.trim(),
917
+ credentials: acac?.trim().toLowerCase() === "true"
918
+ };
919
+ }
920
+ function corsFinding(ctx, m2, r, c, message) {
921
+ return finding(ctx, m2, {
922
+ subject: r.endpointKey,
923
+ location: {
924
+ origin: r.origin,
925
+ endpointKey: r.endpointKey,
926
+ header: "access-control-allow-origin"
927
+ },
928
+ evidence: [
929
+ {
930
+ kind: "header",
931
+ name: "access-control-allow-origin",
932
+ snippet: `${c.acao}${c.credentials ? " + access-control-allow-credentials: true" : ""}${c.origin === void 0 ? "" : ` (request origin ${c.origin})`}`
933
+ }
934
+ ],
935
+ message
936
+ });
937
+ }
938
+ var CORS_FIX = [
939
+ "Allow only the origins of your own frontends, from a fixed list, and send credentials only to them.",
940
+ "",
941
+ '- nginx: `map $http_origin $cors { "https://app.example.com" $http_origin; default ""; }` and `add_header Access-Control-Allow-Origin $cors;`',
942
+ "- Express: `app.use(cors({ origin: ['https://app.example.com'], credentials: true }))`",
943
+ '- Spring: `config.setAllowedOrigins(List.of("https://app.example.com")); config.setAllowCredentials(true);`'
944
+ ].join("\n");
945
+ function corsRule(id, test, docs) {
946
+ const m2 = manifestOf(id);
947
+ return {
948
+ id,
949
+ manifest: m2,
950
+ appliesTo: {},
951
+ check(input, ctx) {
952
+ const c = corsOf(input);
953
+ if (c === null) return [];
954
+ const message = test(c, c.record, ctx);
955
+ return message === null ? [] : [corsFinding(ctx, m2, c.record, c, message)];
956
+ },
957
+ docs: { title: m2.title, fix: CORS_FIX, ...docs }
958
+ };
959
+ }
960
+ var wildcardCredentials = corsRule(
961
+ "cors.wildcard-credentials",
962
+ (c, r) => c.acao === "*" && c.credentials ? `${r.endpointKey} allows any origin together with credentials.` : null,
963
+ {
964
+ why: "Access-Control-Allow-Origin: * with credentials shows a CORS setup that trusts every site; browsers reject the pair, but the configuration usually reflects origins elsewhere.",
965
+ falsePositives: "None known."
966
+ }
967
+ );
968
+ var reflectedOriginCredentials = corsRule(
969
+ "cors.reflected-origin-credentials",
970
+ (c, r, ctx) => c.origin !== void 0 && c.acao === c.origin && c.credentials && !ctx.inScope(c.origin) ? `${r.endpointKey} echoes the foreign origin ${c.origin} and allows credentials.` : null,
971
+ {
972
+ why: "A server that echoes any Origin with credentials lets every website read the responses of a logged-in user (account data, CSRF tokens).",
973
+ falsePositives: "Partner frontends on other origins that are allowed on purpose: add them to scope.origins or accept the finding. Passively only origins the tests used are seen; confidence is medium."
974
+ }
975
+ );
976
+ var nullOrigin = corsRule(
977
+ "cors.null-origin",
978
+ (c, r) => c.acao === "null" ? `${r.endpointKey} allows the null origin.` : null,
979
+ {
980
+ why: "The null origin is used by sandboxed iframes, data: URLs and local files, which any attacker can create; allowing it is as open as a wildcard.",
981
+ falsePositives: "None known."
982
+ }
983
+ );
984
+ var wildcardSensitive = corsRule(
985
+ "cors.wildcard-sensitive",
986
+ (c, r, ctx) => {
987
+ if (c.acao !== "*") return null;
988
+ const auth = header(r.requestHeaders, "authorization") !== void 0;
989
+ const pattern = typeof ctx.options.sessionNamePattern === "string" ? ctx.options.sessionNamePattern : "sess|sid";
990
+ const cookie = (header(r.requestHeaders, "cookie") ?? "").split(";").some((pair) => {
991
+ const [name = "", value = ""] = pair.trim().split("=");
992
+ return name !== "" && isSessionCookie(name, value, pattern);
993
+ });
994
+ return auth || cookie ? `${r.endpointKey} allows any origin although the request carried credentials.` : null;
995
+ },
996
+ {
997
+ why: "An authenticated endpoint readable from any origin may expose user data if the credentials are also sent automatically or are guessable.",
998
+ falsePositives: "Public APIs that authenticate with an API key on purpose. Reported with low confidence."
999
+ }
1000
+ );
1001
+ var CORS_RULES = [
1002
+ wildcardCredentials,
1003
+ reflectedOriginCredentials,
1004
+ nullOrigin,
1005
+ wildcardSensitive
1006
+ ];
1007
+
1008
+ // src/core/rules/data.ts
1009
+ var m = (id) => {
1010
+ const found = ruleManifest(id);
1011
+ if (found === void 0) throw new Error(`no manifest entry for ${id}`);
1012
+ return found;
1013
+ };
1014
+ var lower = (a, b) => {
1015
+ const order = ["low", "medium", "high"];
1016
+ return order.indexOf(a) < order.indexOf(b) ? a : b;
1017
+ };
1018
+ var STATIC = /* @__PURE__ */ new Set(["script", "stylesheet"]);
1019
+ var SECRET = m("data.secret-in-asset");
1020
+ var secretInAsset = {
1021
+ id: SECRET.id,
1022
+ manifest: SECRET,
1023
+ appliesTo: { resourceTypes: ["document", "script", "xhr", "fetch", "api"] },
1024
+ needsBody: ["document", "script", "xhr", "fetch", "api"],
1025
+ check(input, ctx) {
1026
+ if (!("status" in input) || input.body === void 0) return [];
1027
+ const ignore = new Set(ctx.options.ignore ?? []);
1028
+ const custom = (ctx.options.patterns ?? []).map((p) => ({
1029
+ name: p.name,
1030
+ title: p.name,
1031
+ regex: new RegExp(p.regex, `${(p.flags ?? "").replace(/g/g, "")}g`),
1032
+ confidence: "high"
1033
+ }));
1034
+ const isStatic = STATIC.has(input.resourceType);
1035
+ const subject = isStatic ? normalizeAssetUrl(input.url) ?? input.endpointKey : input.endpointKey;
1036
+ const text = input.body.text;
1037
+ const out = [];
1038
+ for (const pattern of [...SECRET_PATTERNS, ...custom]) {
1039
+ if (ignore.has(pattern.name)) continue;
1040
+ const regex = new RegExp(pattern.regex.source, pattern.regex.flags);
1041
+ const match = regex.exec(text);
1042
+ if (match === null) continue;
1043
+ out.push(
1044
+ finding(ctx, SECRET, {
1045
+ scope: isStatic ? "asset" : "endpoint",
1046
+ subject,
1047
+ discriminator: pattern.name,
1048
+ confidence: lower(ctx.confidence, pattern.confidence),
1049
+ location: { origin: input.origin, endpointKey: input.endpointKey },
1050
+ evidence: [
1051
+ { kind: "body", snippet: ctx.redact.snippet(text, match.index, match[0].length) }
1052
+ ],
1053
+ message: `${pattern.title} found in ${isStatic ? subject : input.endpointKey}.`
1054
+ })
1055
+ );
1056
+ }
1057
+ return out;
1058
+ },
1059
+ docs: {
1060
+ title: SECRET.title,
1061
+ why: "Anything sent to the browser or returned by the API is public. A secret key in a bundle or a response can be copied by anyone who opens the page.",
1062
+ fix: [
1063
+ "Remove the secret from client code and responses, rotate it, and call the third-party API from the server.",
1064
+ "",
1065
+ "- nginx: never inject secrets into served files (`sub_filter`, templated configs).",
1066
+ "- Express: keep secrets in server-only environment variables; do not expose them through `DefinePlugin`/`import.meta.env` with a public prefix.",
1067
+ "- Spring: keep secrets in server-side properties; never serialize them in DTOs."
1068
+ ].join("\n"),
1069
+ falsePositives: "Publishable keys (Google Maps/Firebase `AIza…`) are public by design and reported with low confidence. Test fixtures and documentation examples may match; accept them as false-positive in the baseline."
1070
+ }
1071
+ };
1072
+ var STORAGE = m("data.token-in-storage");
1073
+ var STORAGE_KEY = /(token|jwt|auth|session)/i;
1074
+ var tokenInStorage = {
1075
+ id: STORAGE.id,
1076
+ manifest: STORAGE,
1077
+ appliesTo: { events: ["storage"], sources: ["browser"] },
1078
+ check(input, ctx) {
1079
+ if (!("kind" in input) || input.kind !== "storage") return [];
1080
+ const out = [];
1081
+ for (const { key, value } of input.entries) {
1082
+ const jwt = looksLikeJwt(value);
1083
+ if (!jwt && !(STORAGE_KEY.test(key) && looksLikeToken(value))) continue;
1084
+ const name = normalizeName(key);
1085
+ out.push(
1086
+ finding(ctx, STORAGE, {
1087
+ subject: `${name}@${input.origin}`,
1088
+ discriminator: input.area,
1089
+ location: { origin: input.origin },
1090
+ evidence: [
1091
+ {
1092
+ kind: "storage",
1093
+ name,
1094
+ snippet: jwt ? ctx.redact.jwt(value) : ctx.redact.value(value)
1095
+ }
1096
+ ],
1097
+ message: `${input.area === "local" ? "localStorage" : "sessionStorage"} key "${name}" holds a ${jwt ? "JWT" : "token-like value"}.`
1098
+ })
1099
+ );
1100
+ }
1101
+ return out;
1102
+ },
1103
+ docs: {
1104
+ title: STORAGE.title,
1105
+ why: "Web Storage is readable by every script on the page, so one XSS is enough to steal the token. HttpOnly cookies are not readable by scripts.",
1106
+ fix: [
1107
+ "Keep session tokens in a cookie with `HttpOnly; Secure; SameSite=Lax` and drop them from Web Storage.",
1108
+ "",
1109
+ "- nginx: proxy the auth endpoint and set the cookie there (`proxy_cookie_flags ~ httponly secure samesite=lax;`).",
1110
+ "- Express: `res.cookie('session', token, { httpOnly: true, secure: true, sameSite: 'lax' })`.",
1111
+ "- Spring Security: use the session cookie (`server.servlet.session.cookie.http-only=true`) instead of returning the token to the SPA."
1112
+ ].join("\n"),
1113
+ falsePositives: "Short-lived tokens of a Backend-for-Frontend, or values that only look random (cache keys, ids). Accept them in the baseline with a note."
1114
+ }
1115
+ };
1116
+
1117
+ // src/core/rules/data-tokens.ts
1118
+ var isRecord2 = (input) => typeof input === "object" && input !== null && "status" in input;
1119
+ var TOKEN_IN_URL = manifestOf("data.token-in-url");
1120
+ var tokenInUrl = {
1121
+ id: TOKEN_IN_URL.id,
1122
+ manifest: TOKEN_IN_URL,
1123
+ appliesTo: {},
1124
+ check(input, ctx) {
1125
+ if (!isRecord2(input)) return [];
1126
+ let url;
1127
+ try {
1128
+ url = new URL(input.url);
1129
+ } catch {
1130
+ return [];
1131
+ }
1132
+ const names = new Set(
1133
+ (ctx.options.paramNames ?? []).map((n) => n.toLowerCase())
1134
+ );
1135
+ const out = [];
1136
+ const seen = /* @__PURE__ */ new Set();
1137
+ for (const [name, value] of url.searchParams) {
1138
+ if (value === "" || seen.has(name)) continue;
1139
+ const jwt = looksLikeJwt(value);
1140
+ if (!names.has(name.toLowerCase()) && !jwt) continue;
1141
+ seen.add(name);
1142
+ out.push(
1143
+ finding(ctx, TOKEN_IN_URL, {
1144
+ subject: input.endpointKey,
1145
+ discriminator: name,
1146
+ location: { origin: input.origin, endpointKey: input.endpointKey, param: name },
1147
+ evidence: [
1148
+ {
1149
+ kind: "url",
1150
+ name,
1151
+ snippet: `${name}=${jwt ? ctx.redact.jwt(value) : ctx.redact.value(value)}`
1152
+ }
1153
+ ],
1154
+ message: `${input.endpointKey} carries ${jwt ? "a JWT" : "a secret value"} in the query parameter "${name}".`
1155
+ })
1156
+ );
1157
+ }
1158
+ return out;
1159
+ },
1160
+ docs: {
1161
+ title: TOKEN_IN_URL.title,
1162
+ why: "URLs end up in browser history, server and proxy logs and the Referer header of linked sites, so a token in the query leaks far beyond the request.",
1163
+ fix: [
1164
+ "Send tokens in a header (`Authorization`) or a request body, never in the query string; for links (password reset, magic login) use short-lived one-time codes.",
1165
+ "",
1166
+ "- nginx: do not log the query of such endpoints (`log_format` without `$args`) while fixing the client",
1167
+ "- Express: read the token from `req.get('authorization')`, not `req.query`",
1168
+ "- Spring Security: `BearerTokenResolver` without `setAllowUriQueryParameter(true)`"
1169
+ ].join("\n"),
1170
+ falsePositives: "OAuth authorization codes (`code`) are expected and not on the default list; one-time codes in email links can be accepted with a note. The names are the option paramNames."
1171
+ }
1172
+ };
1173
+ function jwtsOf(r) {
1174
+ const out = [];
1175
+ const auth = header(r.requestHeaders, "authorization");
1176
+ const bearer = auth === void 0 ? void 0 : /^\s*bearer\s+(\S+)/i.exec(auth)?.[1];
1177
+ if (bearer !== void 0 && looksLikeJwt(bearer))
1178
+ out.push({ token: bearer, where: "authorization", context: "" });
1179
+ for (const line of headers(r.responseHeaders, "set-cookie")) {
1180
+ const pair = line.split(";")[0] ?? "";
1181
+ const value = pair.slice(pair.indexOf("=") + 1).trim();
1182
+ if (looksLikeJwt(value))
1183
+ out.push({ token: value, where: "set-cookie", context: pair.slice(0, pair.indexOf("=")) });
1184
+ }
1185
+ for (const pair of (header(r.requestHeaders, "cookie") ?? "").split(";")) {
1186
+ const value = pair.slice(pair.indexOf("=") + 1).trim();
1187
+ if (looksLikeJwt(value))
1188
+ out.push({ token: value, where: "cookie", context: pair.slice(0, pair.indexOf("=")) });
1189
+ }
1190
+ if (r.body !== void 0) {
1191
+ for (const m2 of r.body.text.matchAll(JWT_IN_TEXT)) {
1192
+ out.push({
1193
+ token: m2[0],
1194
+ where: "body",
1195
+ context: r.body.text.slice(Math.max(0, m2.index - 40), m2.index)
1196
+ });
1197
+ }
1198
+ }
1199
+ return out;
1200
+ }
1201
+ function jwtFinding(ctx, m2, r, jwt, message, discriminator) {
1202
+ const sent = jwt.where === "authorization" || jwt.where === "cookie";
1203
+ return finding(ctx, m2, {
1204
+ scope: sent ? "origin" : "endpoint",
1205
+ subject: sent ? r.origin : r.endpointKey,
1206
+ discriminator: discriminator ?? (sent ? `request-${jwt.where}` : void 0),
1207
+ location: { origin: r.origin, endpointKey: r.endpointKey },
1208
+ evidence: [
1209
+ {
1210
+ kind: jwt.where === "body" ? "body" : jwt.where === "authorization" ? "header" : "cookie",
1211
+ name: jwt.where,
1212
+ snippet: ctx.redact.jwt(jwt.token)
1213
+ }
1214
+ ],
1215
+ message
1216
+ });
1217
+ }
1218
+ function jwtRule(id, test, docs) {
1219
+ const m2 = manifestOf(id);
1220
+ return {
1221
+ id,
1222
+ manifest: m2,
1223
+ appliesTo: { resourceTypes: ["document", "xhr", "fetch", "api", "other"] },
1224
+ needsBody: ["document", "xhr", "fetch", "api"],
1225
+ check(input, ctx) {
1226
+ if (!isRecord2(input)) return [];
1227
+ const out = [];
1228
+ const seen = /* @__PURE__ */ new Set();
1229
+ for (const jwt of jwtsOf(input)) {
1230
+ const decoded = decodeJwt(jwt.token);
1231
+ if (decoded === null) continue;
1232
+ const hit = test(decoded, jwt, ctx);
1233
+ if (hit === null) continue;
1234
+ const key = `${jwt.where}\0${hit.discriminator ?? ""}`;
1235
+ if (seen.has(key)) continue;
1236
+ seen.add(key);
1237
+ out.push(jwtFinding(ctx, m2, input, jwt, hit.message, hit.discriminator));
1238
+ }
1239
+ return out;
1240
+ },
1241
+ docs: { title: m2.title, ...docs }
1242
+ };
1243
+ }
1244
+ var JWT_FIX = (what, express, spring) => [
1245
+ what,
1246
+ "",
1247
+ "- nginx (auth_jwt / OpenResty): reject tokens that fail the check before they reach the app",
1248
+ `- Express: ${express}`,
1249
+ `- Spring Security: ${spring}`
1250
+ ].join("\n");
1251
+ var jwtAlgNone = jwtRule(
1252
+ "data.jwt-alg-none",
1253
+ (d, jwt) => String(d.header.alg).toLowerCase() === "none" ? {
1254
+ message: `An unsigned JWT (alg "none") is ${jwt.where === "body" || jwt.where === "set-cookie" ? "issued" : "sent"} here.`
1255
+ } : null,
1256
+ {
1257
+ why: 'A token with alg "none" has no signature: anyone can change its claims (user id, roles) and, if the server accepts it, become any user.',
1258
+ fix: JWT_FIX(
1259
+ "Sign every token and accept only the algorithms you issue.",
1260
+ "`jwt.verify(token, key, { algorithms: ['RS256'] })` (jsonwebtoken)",
1261
+ "`NimbusJwtDecoder.withPublicKey(key).signatureAlgorithm(SignatureAlgorithm.RS256).build()`"
1262
+ ),
1263
+ falsePositives: "None known."
1264
+ }
1265
+ );
1266
+ var jwtNoExp = jwtRule(
1267
+ "data.jwt-no-exp",
1268
+ (d) => d.payload !== null && d.payload.exp === void 0 ? { message: "A JWT without an expiry (exp) is used here." } : null,
1269
+ {
1270
+ why: "A token without exp is valid forever: a leaked token cannot expire and logout does not end the session.",
1271
+ fix: JWT_FIX(
1272
+ "Issue every access token with a short exp and check it.",
1273
+ "`jwt.sign(claims, key, { expiresIn: '15m' })`",
1274
+ "`JwtClaimsSet.builder().expiresAt(now.plus(15, MINUTES))`"
1275
+ ),
1276
+ falsePositives: "Tokens of third parties you cannot change: accept them with a note."
1277
+ }
1278
+ );
1279
+ var jwtLongLived = jwtRule(
1280
+ "data.jwt-long-lived",
1281
+ (d, jwt, ctx) => {
1282
+ const p = d.payload;
1283
+ if (p === null || typeof p.exp !== "number" || typeof p.iat !== "number") return null;
1284
+ const refresh = /refresh/i.test(jwt.context) || /refresh/i.test(String(p.typ ?? "")) || /refresh/i.test(String(p.token_type ?? ""));
1285
+ if (refresh) return null;
1286
+ const hours = typeof ctx.options.maxJwtHours === "number" ? ctx.options.maxJwtHours : 24;
1287
+ const lifetime = (p.exp - p.iat) / 3600;
1288
+ return lifetime > hours ? { message: `A JWT valid for ${Math.round(lifetime)} hours (limit ${hours}) is used here.` } : null;
1289
+ },
1290
+ {
1291
+ why: "A long-lived access token gives an attacker who steals it a long window; access tokens should be short-lived and renewed with a refresh token.",
1292
+ fix: JWT_FIX(
1293
+ "Keep access tokens short (minutes) and renew them with a refresh token kept in an HttpOnly cookie.",
1294
+ "`jwt.sign(claims, key, { expiresIn: '15m' })`",
1295
+ "`JwtClaimsSet.builder().expiresAt(now.plus(15, MINUTES))`"
1296
+ ),
1297
+ falsePositives: "Refresh tokens are skipped when their name or claims say so. The limit is the option maxJwtHours."
1298
+ }
1299
+ );
1300
+ var SENSITIVE_CLAIM = /(pass(word)?|pwd|secret|ssn|pesel|card|cvv|iban)/i;
1301
+ var jwtSensitiveClaims = jwtRule(
1302
+ "data.jwt-sensitive-claims",
1303
+ (d) => {
1304
+ const key = Object.keys(d.payload ?? {}).find((k) => SENSITIVE_CLAIM.test(k));
1305
+ return key === void 0 ? null : { message: `A JWT carries the claim "${key}".`, discriminator: key };
1306
+ },
1307
+ {
1308
+ why: "JWT payloads are only base64-encoded, not encrypted: anyone who sees the token reads every claim.",
1309
+ fix: JWT_FIX(
1310
+ "Keep secrets and personal data out of token claims; put an opaque id in the token and look the data up on the server.",
1311
+ "`jwt.sign({ sub: user.id }, key)` without sensitive fields",
1312
+ "`JwtClaimsSet.builder().subject(userId)` without sensitive claims"
1313
+ ),
1314
+ falsePositives: 'Claims whose names only look sensitive (e.g. "card_type"): accept them as false-positive.'
1315
+ }
1316
+ );
1317
+ var PASSWORD = manifestOf("data.password-in-response");
1318
+ var PASSWORD_KEYS = /* @__PURE__ */ new Set(["password", "passwordhash", "password_hash", "hash", "salt"]);
1319
+ var HASH = /^(?:\$(?:2[abxy]?|argon2(?:id|i|d)|scrypt|pbkdf2[^$]*|[156])\$\S{8,}|[0-9a-f]{32,}|[A-Za-z0-9+/]{24,}={0,2})$/i;
1320
+ function secretLike(value) {
1321
+ if (HASH.test(value)) return true;
1322
+ return value.length >= 6 && !/\s/.test(value) && /[^\p{L}]/u.test(value);
1323
+ }
1324
+ function findPasswordKeys(value, depth = 0, found = /* @__PURE__ */ new Set()) {
1325
+ if (depth > 10 || value === null || typeof value !== "object") return found;
1326
+ if (Array.isArray(value)) {
1327
+ for (const item of value.slice(0, 200)) findPasswordKeys(item, depth + 1, found);
1328
+ return found;
1329
+ }
1330
+ for (const [key, v] of Object.entries(value)) {
1331
+ if (PASSWORD_KEYS.has(key.toLowerCase()) && typeof v === "string" && secretLike(v))
1332
+ found.add(key);
1333
+ findPasswordKeys(v, depth + 1, found);
1334
+ }
1335
+ return found;
1336
+ }
1337
+ var passwordInResponse = {
1338
+ id: PASSWORD.id,
1339
+ manifest: PASSWORD,
1340
+ appliesTo: { resourceTypes: ["xhr", "fetch", "api", "document", "other"] },
1341
+ needsBody: ["xhr", "fetch", "api", "document"],
1342
+ check(input, ctx) {
1343
+ if (!isRecord2(input) || input.body === void 0 || !isJson(input.body.contentType)) return [];
1344
+ let parsed;
1345
+ try {
1346
+ parsed = JSON.parse(input.body.text);
1347
+ } catch {
1348
+ return [];
1349
+ }
1350
+ return [...findPasswordKeys(parsed)].sort().map(
1351
+ (key) => finding(ctx, PASSWORD, {
1352
+ subject: input.endpointKey,
1353
+ discriminator: key,
1354
+ location: { origin: input.origin, endpointKey: input.endpointKey },
1355
+ evidence: [{ kind: "body", name: key, snippet: `"${key}": ${ctx.redact.value(key)}` }],
1356
+ message: `${input.endpointKey} returns the field "${key}" with a value.`
1357
+ })
1358
+ );
1359
+ },
1360
+ docs: {
1361
+ title: PASSWORD.title,
1362
+ why: "Password hashes and salts in API responses can be cracked offline; they should never leave the server.",
1363
+ fix: [
1364
+ "Exclude credential fields from the response model (a DTO or serializer allow-list).",
1365
+ "",
1366
+ "- nginx: nothing to configure; fix the application",
1367
+ "- Express: `const { password, passwordHash, ...safe } = user; res.json(safe)` or a schema serializer",
1368
+ "- Spring: `@JsonIgnore` on the field or a response DTO without it"
1369
+ ].join("\n"),
1370
+ falsePositives: '"hash" or "salt" fields that are not credentials (content hashes, cache keys): accept them as false-positive.'
1371
+ }
1372
+ };
1373
+ var TOKEN_RULES = [
1374
+ tokenInUrl,
1375
+ jwtAlgNone,
1376
+ jwtNoExp,
1377
+ jwtLongLived,
1378
+ jwtSensitiveClaims,
1379
+ passwordInResponse
1380
+ ];
1381
+
1382
+ // src/core/rules/disclosure.ts
1383
+ var isRecord3 = (input) => typeof input === "object" && input !== null && "status" in input;
1384
+ var BODY_TYPES = ["document", "xhr", "fetch", "api", "other"];
1385
+ function bodyMatch(ctx, m2, r, patterns, message, withDiscriminator) {
1386
+ if (r.body === void 0) return [];
1387
+ for (const p of patterns) {
1388
+ const match = p.re.exec(r.body.text);
1389
+ if (match === null) continue;
1390
+ return [
1391
+ finding(ctx, m2, {
1392
+ subject: r.endpointKey,
1393
+ ...withDiscriminator ? { discriminator: p.name } : {},
1394
+ location: { origin: r.origin, endpointKey: r.endpointKey },
1395
+ evidence: [
1396
+ { kind: "body", snippet: ctx.redact.snippet(r.body.text, match.index, match[0].length) }
1397
+ ],
1398
+ message: message(p.name)
1399
+ })
1400
+ ];
1401
+ }
1402
+ return [];
1403
+ }
1404
+ var ERRORS_FIX = (what, express, spring) => [
1405
+ what,
1406
+ "",
1407
+ "- nginx: `proxy_intercept_errors on;` with generic `error_page 500 502 503 504 /50x.html;`",
1408
+ `- Express: ${express}`,
1409
+ `- Spring Boot: ${spring}`
1410
+ ].join("\n");
1411
+ var STACK = manifestOf("disclosure.stack-trace");
1412
+ var STACK_PATTERNS = [
1413
+ { name: "java", re: /\bat [a-z][\w$]*\.[\w.$]+\([\w$]+\.java:\d+\)/ },
1414
+ { name: "dotnet", re: /\bat [\w.`<>]+(?:\([^)]*\))? in .+:line \d+/ },
1415
+ { name: "python", re: /Traceback \(most recent call last\)/ },
1416
+ { name: "php", re: /(?:Fatal error|Warning): .+ on line \d+/ },
1417
+ { name: "node", re: /\bat .+ \((?:\/|[A-Za-z]:\\).+node_modules[\\/].+:\d+:\d+\)/ },
1418
+ { name: "ruby", re: /\.rb:\d+:in `/ }
1419
+ ];
1420
+ var stackTrace = {
1421
+ id: STACK.id,
1422
+ manifest: STACK,
1423
+ appliesTo: { resourceTypes: BODY_TYPES },
1424
+ needsBody: BODY_TYPES,
1425
+ check(input, ctx) {
1426
+ if (!isRecord3(input)) return [];
1427
+ return bodyMatch(
1428
+ ctx,
1429
+ STACK,
1430
+ input,
1431
+ STACK_PATTERNS,
1432
+ (n) => `${input.endpointKey} returns a ${n} stack trace.`,
1433
+ true
1434
+ );
1435
+ },
1436
+ docs: {
1437
+ title: STACK.title,
1438
+ why: "Stack traces show file paths, library versions and code structure, which helps an attacker pick an exploit; they also signal unhandled errors.",
1439
+ fix: ERRORS_FIX(
1440
+ "Return a generic error body to clients and log the details on the server.",
1441
+ "an error handler `app.use((err, req, res, next) => { log(err); res.status(500).json({ error: 'Internal error' }); })` and `NODE_ENV=production`",
1442
+ "`server.error.include-stacktrace=never`"
1443
+ ),
1444
+ falsePositives: "Developer documentation pages that show sample traces: accept them as false-positive."
1445
+ }
1446
+ };
1447
+ var SQL = manifestOf("disclosure.sql-error");
1448
+ var SQL_PATTERNS = [
1449
+ /SQLSTATE\[/,
1450
+ /\bORA-\d{5}\b/,
1451
+ /You have an error in your SQL syntax/,
1452
+ /syntax error at or near/,
1453
+ /unterminated quoted string/i,
1454
+ /\bSqlException\b/,
1455
+ /\bSQLITE_ERROR\b/
1456
+ ].map((re) => ({ name: "sql", re }));
1457
+ var sqlError = {
1458
+ id: SQL.id,
1459
+ manifest: SQL,
1460
+ appliesTo: { resourceTypes: BODY_TYPES },
1461
+ needsBody: BODY_TYPES,
1462
+ check(input, ctx) {
1463
+ if (!isRecord3(input)) return [];
1464
+ return bodyMatch(
1465
+ ctx,
1466
+ SQL,
1467
+ input,
1468
+ SQL_PATTERNS,
1469
+ () => `${input.endpointKey} returns a database error message.`,
1470
+ false
1471
+ );
1472
+ },
1473
+ docs: {
1474
+ title: SQL.title,
1475
+ why: "A database error in a response shows that input reached a query unescaped (a likely SQL injection) and leaks the schema.",
1476
+ fix: ERRORS_FIX(
1477
+ "Use parameterized queries everywhere and return generic errors.",
1478
+ "parameterized queries (`db.query('SELECT … WHERE id = $1', [id])`) and a generic error handler",
1479
+ "Spring Data / `JdbcTemplate` with `?` parameters and `server.error.include-message=never`"
1480
+ ),
1481
+ falsePositives: "Pages that document SQL errors. Confirm SQL injection with an active test (stage E3)."
1482
+ }
1483
+ };
1484
+ var VERSION = manifestOf("disclosure.server-version");
1485
+ var VERSION_HEADERS = [
1486
+ "server",
1487
+ "x-powered-by",
1488
+ "x-aspnet-version",
1489
+ "x-aspnetmvc-version",
1490
+ "x-generator"
1491
+ ];
1492
+ var serverVersion = {
1493
+ id: VERSION.id,
1494
+ manifest: VERSION,
1495
+ appliesTo: {},
1496
+ check(input, ctx) {
1497
+ if (!isRecord3(input)) return [];
1498
+ const out = [];
1499
+ for (const name of VERSION_HEADERS) {
1500
+ const value = header(input.responseHeaders, name);
1501
+ if (value === void 0 || !/\d+\.\d+/.test(value)) continue;
1502
+ out.push(
1503
+ finding(ctx, VERSION, {
1504
+ subject: input.origin,
1505
+ discriminator: name,
1506
+ location: { origin: input.origin, endpointKey: input.endpointKey, header: name },
1507
+ evidence: [{ kind: "header", name, snippet: ctx.redact.text(value) }],
1508
+ message: `${input.origin} discloses its software version in ${name}.`
1509
+ })
1510
+ );
1511
+ }
1512
+ return out;
1513
+ },
1514
+ docs: {
1515
+ title: VERSION.title,
1516
+ why: "Exact versions let an attacker look up known vulnerabilities of the server or framework without probing.",
1517
+ fix: [
1518
+ "Hide versions in response headers.",
1519
+ "",
1520
+ "- nginx: `server_tokens off;` (and `more_clear_headers Server;` with headers-more)",
1521
+ "- Express: `app.disable('x-powered-by')` (or `helmet()`)",
1522
+ "- Spring Boot: `server.server-header=` (empty) and no `X-Application-Context`"
1523
+ ].join("\n"),
1524
+ falsePositives: "None known; reported with low severity."
1525
+ }
1526
+ };
1527
+ var DEBUG = manifestOf("disclosure.debug-mode");
1528
+ var DEBUG_PATTERNS = [
1529
+ {
1530
+ name: "werkzeug",
1531
+ re: /Werkzeug Debugger|The debugger caught an exception in your WSGI application/
1532
+ },
1533
+ {
1534
+ name: "django",
1535
+ re: /You're seeing this error because you have <code>DEBUG = True<\/code>|DEBUG = True/
1536
+ },
1537
+ { name: "laravel", re: /Whoops! There was an error\.|window\.ignite|ignition-/ },
1538
+ { name: "symfony", re: /\bsf-toolbar\b|sfwdt[a-f0-9]{6}/ },
1539
+ { name: "rails", re: /Action Controller: Exception caught/ }
1540
+ ];
1541
+ var debugMode = {
1542
+ id: DEBUG.id,
1543
+ manifest: DEBUG,
1544
+ appliesTo: { resourceTypes: BODY_TYPES },
1545
+ needsBody: BODY_TYPES,
1546
+ check(input, ctx) {
1547
+ if (!isRecord3(input)) return [];
1548
+ return bodyMatch(
1549
+ ctx,
1550
+ DEBUG,
1551
+ input,
1552
+ DEBUG_PATTERNS,
1553
+ (n) => `${input.endpointKey} shows the ${n} debug page.`,
1554
+ true
1555
+ );
1556
+ },
1557
+ docs: {
1558
+ title: DEBUG.title,
1559
+ why: "Debug pages expose source code, settings and sometimes an interactive console (Werkzeug) that runs code on the server.",
1560
+ fix: [
1561
+ "Turn debug mode off outside development.",
1562
+ "",
1563
+ "- nginx: nothing to configure; set the framework to production mode",
1564
+ "- Express: `NODE_ENV=production`; remove `errorhandler` in production",
1565
+ "- Spring Boot: no `spring-boot-devtools` in production, `server.error.include-stacktrace=never`"
1566
+ ].join("\n"),
1567
+ falsePositives: "Development environments scanned on purpose: scan the deployed environment instead."
1568
+ }
1569
+ };
1570
+ var PRIVATE_IP = manifestOf("disclosure.private-ip");
1571
+ var IP = /(?<![\d.])(10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3})(?![\d.])/;
1572
+ var isPrivateHost = (origin) => {
1573
+ try {
1574
+ return IP.test(new URL(origin).hostname);
1575
+ } catch {
1576
+ return false;
1577
+ }
1578
+ };
1579
+ var privateIp = {
1580
+ id: PRIVATE_IP.id,
1581
+ manifest: PRIVATE_IP,
1582
+ appliesTo: { resourceTypes: ["document", "xhr", "fetch", "api", "other"] },
1583
+ needsBody: ["document", "xhr", "fetch", "api"],
1584
+ check(input, ctx) {
1585
+ if (!isRecord3(input) || isPrivateHost(input.origin)) return [];
1586
+ for (const h of input.responseHeaders) {
1587
+ const m3 = IP.exec(h.value);
1588
+ if (m3 !== null) {
1589
+ return [
1590
+ finding(ctx, PRIVATE_IP, {
1591
+ subject: input.endpointKey,
1592
+ location: { origin: input.origin, endpointKey: input.endpointKey, header: h.name },
1593
+ evidence: [{ kind: "header", name: h.name, snippet: ctx.redact.text(m3[0]) }],
1594
+ message: `${input.endpointKey} discloses a private IP address in ${h.name}.`
1595
+ })
1596
+ ];
1597
+ }
1598
+ }
1599
+ if (input.body === void 0) return [];
1600
+ const m2 = IP.exec(input.body.text);
1601
+ if (m2 === null) return [];
1602
+ return [
1603
+ finding(ctx, PRIVATE_IP, {
1604
+ subject: input.endpointKey,
1605
+ location: { origin: input.origin, endpointKey: input.endpointKey },
1606
+ evidence: [
1607
+ { kind: "body", snippet: ctx.redact.snippet(input.body.text, m2.index, m2[0].length) }
1608
+ ],
1609
+ message: `${input.endpointKey} discloses a private IP address.`
1610
+ })
1611
+ ];
1612
+ },
1613
+ docs: {
1614
+ title: PRIVATE_IP.title,
1615
+ why: "Internal addresses map the network behind the application and help attacks such as SSRF.",
1616
+ fix: [
1617
+ "Remove internal addresses from responses and headers (load balancer, upstream and debug fields).",
1618
+ "",
1619
+ "- nginx: `proxy_hide_header X-Backend-Server;` and similar upstream headers",
1620
+ '- Express: do not return infrastructure fields; `app.set("trust proxy", …)` instead of echoing addresses',
1621
+ "- Spring Boot: exclude infrastructure fields from DTOs; `server.forward-headers-strategy=framework`"
1622
+ ].join("\n"),
1623
+ falsePositives: "Version strings that look like addresses, and apps served from a private address (skipped)."
1624
+ }
1625
+ };
1626
+ var LISTING = manifestOf("disclosure.directory-listing");
1627
+ var directoryListing = {
1628
+ id: LISTING.id,
1629
+ manifest: LISTING,
1630
+ appliesTo: { resourceTypes: BODY_TYPES },
1631
+ needsBody: BODY_TYPES,
1632
+ check(input, ctx) {
1633
+ if (!isRecord3(input) || input.status < 200 || input.status >= 300) return [];
1634
+ return bodyMatch(
1635
+ ctx,
1636
+ LISTING,
1637
+ input,
1638
+ [{ name: "listing", re: /<title>\s*Index of \/|Directory listing for /i }],
1639
+ () => `${input.endpointKey} shows a directory listing.`,
1640
+ false
1641
+ );
1642
+ },
1643
+ docs: {
1644
+ title: LISTING.title,
1645
+ why: "A directory listing exposes every file of a folder, including backups and files that were never linked.",
1646
+ fix: [
1647
+ "Turn directory listings off.",
1648
+ "",
1649
+ "- nginx: `autoindex off;`",
1650
+ "- Express: no `serve-index`; `express.static(dir, { index: false })` without a listing middleware",
1651
+ "- Spring Boot: no `ResourceHttpRequestHandler` listings; `spring.web.resources.add-mappings` only for public assets"
1652
+ ].join("\n"),
1653
+ falsePositives: "Public download folders meant to be browsed: accept them with a note."
1654
+ }
1655
+ };
1656
+ var SOURCE_MAP = manifestOf("disclosure.source-map");
1657
+ var sourceMap = {
1658
+ id: SOURCE_MAP.id,
1659
+ manifest: SOURCE_MAP,
1660
+ appliesTo: { resourceTypes: ["script"] },
1661
+ needsBody: ["script"],
1662
+ check(input, ctx) {
1663
+ if (!isRecord3(input) || input.status < 200 || input.status >= 300) return [];
1664
+ const fromHeader = header(input.responseHeaders, "sourcemap") ?? header(input.responseHeaders, "x-sourcemap");
1665
+ const comment = input.body === void 0 ? null : /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/m.exec(input.body.text);
1666
+ if (fromHeader === void 0 && comment === null) return [];
1667
+ const subject = normalizeAssetUrl(input.url) ?? input.endpointKey;
1668
+ const target = fromHeader ?? comment?.[1] ?? "";
1669
+ return [
1670
+ finding(ctx, SOURCE_MAP, {
1671
+ subject,
1672
+ location: { origin: input.origin, endpointKey: input.endpointKey },
1673
+ evidence: [
1674
+ {
1675
+ kind: fromHeader === void 0 ? "body" : "header",
1676
+ snippet: ctx.redact.text(
1677
+ `sourceMappingURL=${target.startsWith("data:") ? "data:…" : target}`
1678
+ )
1679
+ }
1680
+ ],
1681
+ message: `${subject} references a source map.`
1682
+ })
1683
+ ];
1684
+ },
1685
+ docs: {
1686
+ title: SOURCE_MAP.title,
1687
+ why: "Source maps publish the original source code, comments included; the package does not download the map (passive only).",
1688
+ fix: [
1689
+ "Do not deploy source maps to production, or serve them only to authenticated developers.",
1690
+ "",
1691
+ "- nginx: `location ~* \\.map$ { deny all; }`",
1692
+ '- Express: build without `devtool: "source-map"`, or `app.use(/\\.map$/, (req, res) => res.sendStatus(404))`',
1693
+ "- Spring Boot: exclude `*.map` from `spring.web.resources.static-locations`"
1694
+ ].join("\n"),
1695
+ falsePositives: "Open-source frontends that publish their code anyway. Reported as info."
1696
+ }
1697
+ };
1698
+ var SERVER_ERROR = manifestOf("disclosure.server-error");
1699
+ var serverError = {
1700
+ id: SERVER_ERROR.id,
1701
+ manifest: SERVER_ERROR,
1702
+ appliesTo: {},
1703
+ check(input, ctx) {
1704
+ if (!isRecord3(input) || input.status < 500 || input.status > 599) return [];
1705
+ return [
1706
+ finding(ctx, SERVER_ERROR, {
1707
+ subject: input.endpointKey,
1708
+ discriminator: String(input.status),
1709
+ location: { origin: input.origin, endpointKey: input.endpointKey },
1710
+ evidence: [{ kind: "event", name: "status", snippet: String(input.status) }],
1711
+ message: `${input.endpointKey} answered ${input.status} during the tests.`
1712
+ })
1713
+ ];
1714
+ },
1715
+ docs: {
1716
+ title: SERVER_ERROR.title,
1717
+ why: "Unhandled server errors often reveal fragile input handling; they are also functional bugs.",
1718
+ fix: ERRORS_FIX(
1719
+ "Handle the error case and return a 4xx for invalid input.",
1720
+ "validate input and return `res.status(400)` for bad requests",
1721
+ "`@ControllerAdvice` with `@ExceptionHandler` returning 4xx for client errors"
1722
+ ),
1723
+ falsePositives: "Tests that provoke 5xx on purpose. Reported as info."
1724
+ }
1725
+ };
1726
+ var DISCLOSURE_RULES = [
1727
+ stackTrace,
1728
+ sqlError,
1729
+ serverVersion,
1730
+ debugMode,
1731
+ privateIp,
1732
+ directoryListing,
1733
+ sourceMap,
1734
+ serverError
1735
+ ];
1736
+
1737
+ // src/core/rules/csp.ts
1738
+ function parseCsp(value) {
1739
+ return value.split(",").map((policy) => {
1740
+ const map = /* @__PURE__ */ new Map();
1741
+ for (const part of policy.split(";")) {
1742
+ const tokens = part.trim().split(/\s+/).filter(Boolean);
1743
+ const [name, ...sources] = tokens;
1744
+ if (name === void 0) continue;
1745
+ const key = name.toLowerCase();
1746
+ if (!map.has(key))
1747
+ map.set(
1748
+ key,
1749
+ sources.map((s) => /^'(nonce|sha\d+)-/i.test(s) ? s : s.toLowerCase())
1750
+ );
1751
+ }
1752
+ return map;
1753
+ }).filter((p) => p.size > 0);
1754
+ }
1755
+ function policies(values) {
1756
+ return values.flatMap(parseCsp);
1757
+ }
1758
+ function scriptSources(policy) {
1759
+ return policy.get("script-src") ?? policy.get("default-src");
1760
+ }
1761
+ function metaCsp(html) {
1762
+ if (html === void 0) return [];
1763
+ const head = html.slice(0, 4096);
1764
+ const out = [];
1765
+ const re = /<meta\s[^>]*http-equiv\s*=\s*["']?content-security-policy["']?[^>]*>/gi;
1766
+ for (const tag of head.match(re) ?? []) {
1767
+ const content = /content\s*=\s*("([^"]*)"|'([^']*)')/i.exec(tag);
1768
+ const value = content?.[2] ?? content?.[3];
1769
+ if (value !== void 0) out.push(value);
1770
+ }
1771
+ return out;
1772
+ }
1773
+ function unsafeScriptTokens(policy) {
1774
+ const sources = scriptSources(policy);
1775
+ if (sources === void 0) return [];
1776
+ const hasNonceOrHash = sources.some((s) => /^'(nonce|sha256|sha384|sha512)-/i.test(s));
1777
+ const strictDynamic = sources.includes("'strict-dynamic'");
1778
+ const out = [];
1779
+ for (const s of sources) {
1780
+ if (s === "'unsafe-inline'" && !hasNonceOrHash) out.push(s);
1781
+ else if (s === "'unsafe-eval'") out.push(s);
1782
+ else if (!strictDynamic && (s === "*" || s === "http:" || s === "https:" || s === "data:"))
1783
+ out.push(s);
1784
+ }
1785
+ return [...new Set(out)];
1786
+ }
1787
+
1788
+ // src/core/rules/fix-snippets.ts
1789
+ function headerFix(name, value, springLine) {
1790
+ return [
1791
+ `Send \`${name}: ${value}\` on every response.`,
1792
+ "",
1793
+ `- nginx: \`add_header ${name} "${value}" always;\``,
1794
+ `- Express: \`app.use((req, res, next) => { res.setHeader('${name}', '${value}'); next(); });\` or the matching \`helmet\` middleware`,
1795
+ `- Spring Security: \`${springLine}\``
1796
+ ].join("\n");
1797
+ }
1798
+
1799
+ // src/core/rules/header.ts
1800
+ var is2xx = (r) => r.status >= 200 && r.status < 300;
1801
+ var isRecord4 = (input) => typeof input === "object" && input !== null && "status" in input;
1802
+ function isDocument(input) {
1803
+ if (!isRecord4(input) || input.resourceType !== "document" || !is2xx(input)) return false;
1804
+ const type = header(input.responseHeaders, "content-type");
1805
+ return type === void 0 || /html/i.test(type);
1806
+ }
1807
+ var DOC_TYPES = ["document"];
1808
+ function originFinding(ctx, m2, r, name, snippet, message, extra = {}) {
1809
+ return finding(ctx, m2, {
1810
+ subject: r.origin,
1811
+ location: { origin: r.origin, endpointKey: r.endpointKey, header: name },
1812
+ evidence: [{ kind: "header", name, snippet }],
1813
+ message,
1814
+ ...extra
1815
+ });
1816
+ }
1817
+ function enforcedCsp(r) {
1818
+ const fromHeaders = headers(r.responseHeaders, "content-security-policy");
1819
+ return fromHeaders.length > 0 ? fromHeaders : metaCsp(r.body?.text);
1820
+ }
1821
+ var CSP_MISSING = manifestOf("header.csp-missing");
1822
+ var cspMissing = {
1823
+ id: CSP_MISSING.id,
1824
+ manifest: CSP_MISSING,
1825
+ appliesTo: { resourceTypes: DOC_TYPES },
1826
+ needsBody: DOC_TYPES,
1827
+ check(input, ctx) {
1828
+ if (!isDocument(input)) return [];
1829
+ if (enforcedCsp(input).length > 0) return [];
1830
+ if (headers(input.responseHeaders, "content-security-policy-report-only").length > 0) return [];
1831
+ return [
1832
+ originFinding(
1833
+ ctx,
1834
+ CSP_MISSING,
1835
+ input,
1836
+ "content-security-policy",
1837
+ "(missing)",
1838
+ `${input.endpointKey} has no Content-Security-Policy.`
1839
+ )
1840
+ ];
1841
+ },
1842
+ docs: {
1843
+ title: CSP_MISSING.title,
1844
+ why: "Without a Content-Security-Policy any injected script runs: one XSS bug gives full control of the page and the session.",
1845
+ fix: headerFix(
1846
+ "Content-Security-Policy",
1847
+ "default-src 'self'; script-src 'self' 'nonce-{random}'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'",
1848
+ `http.headers(h -> h.contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'; object-src 'none'")))`
1849
+ ),
1850
+ falsePositives: "Pages that only redirect or download files. Start with Content-Security-Policy-Report-Only if the policy may break the page."
1851
+ }
1852
+ };
1853
+ var CSP_UNSAFE = manifestOf("header.csp-unsafe");
1854
+ var cspUnsafe = {
1855
+ id: CSP_UNSAFE.id,
1856
+ manifest: CSP_UNSAFE,
1857
+ appliesTo: { resourceTypes: DOC_TYPES },
1858
+ needsBody: DOC_TYPES,
1859
+ check(input, ctx) {
1860
+ if (!isDocument(input)) return [];
1861
+ const list = policies(enforcedCsp(input)).filter((p) => scriptSources(p) !== void 0);
1862
+ if (list.length === 0) return [];
1863
+ const perPolicy = list.map(unsafeScriptTokens);
1864
+ const tokens = (perPolicy[0] ?? []).filter((t) => perPolicy.every((p) => p.includes(t)));
1865
+ return tokens.map(
1866
+ (token) => originFinding(
1867
+ ctx,
1868
+ CSP_UNSAFE,
1869
+ input,
1870
+ "content-security-policy",
1871
+ `script-src … ${token}`,
1872
+ `The Content-Security-Policy of ${input.endpointKey} allows ${token} for scripts.`,
1873
+ { discriminator: token.replace(/'/g, "") }
1874
+ )
1875
+ );
1876
+ },
1877
+ docs: {
1878
+ title: CSP_UNSAFE.title,
1879
+ why: "'unsafe-inline', 'unsafe-eval', wildcards and whole schemes in script-src let injected scripts run, so the policy no longer stops XSS.",
1880
+ fix: headerFix(
1881
+ "Content-Security-Policy",
1882
+ "script-src 'self' 'nonce-{random}' 'strict-dynamic'; object-src 'none'; base-uri 'self'",
1883
+ `http.headers(h -> h.contentSecurityPolicy(csp -> csp.policyDirectives("script-src 'self' 'nonce-{nonce}'")))`
1884
+ ),
1885
+ falsePositives: "Legacy apps with inline handlers may need 'unsafe-inline' for a while: accept with an expiry date (until) and a ticket."
1886
+ }
1887
+ };
1888
+ var CSP_DIRECTIVES = manifestOf("header.csp-missing-directives");
1889
+ var cspMissingDirectives = {
1890
+ id: CSP_DIRECTIVES.id,
1891
+ manifest: CSP_DIRECTIVES,
1892
+ appliesTo: { resourceTypes: DOC_TYPES },
1893
+ needsBody: DOC_TYPES,
1894
+ check(input, ctx) {
1895
+ if (!isDocument(input)) return [];
1896
+ const list = policies(enforcedCsp(input));
1897
+ if (list.length === 0) return [];
1898
+ const out = [];
1899
+ const objectRestricted = list.some((p) => {
1900
+ const def = p.get("default-src");
1901
+ return p.has("object-src") || def?.length === 1 && def[0] === "'none'";
1902
+ });
1903
+ if (!objectRestricted) {
1904
+ out.push(
1905
+ originFinding(
1906
+ ctx,
1907
+ CSP_DIRECTIVES,
1908
+ input,
1909
+ "content-security-policy",
1910
+ "object-src (missing)",
1911
+ `The Content-Security-Policy of ${input.endpointKey} has no object-src.`,
1912
+ { discriminator: "object-src" }
1913
+ )
1914
+ );
1915
+ }
1916
+ if (!list.some((p) => p.has("base-uri"))) {
1917
+ out.push(
1918
+ originFinding(
1919
+ ctx,
1920
+ CSP_DIRECTIVES,
1921
+ input,
1922
+ "content-security-policy",
1923
+ "base-uri (missing)",
1924
+ `The Content-Security-Policy of ${input.endpointKey} has no base-uri.`,
1925
+ { discriminator: "base-uri" }
1926
+ )
1927
+ );
1928
+ }
1929
+ return out;
1930
+ },
1931
+ docs: {
1932
+ title: CSP_DIRECTIVES.title,
1933
+ why: "default-src does not cover base-uri, and plugins (object-src) can run code: without them an attacker can change the base URL of relative scripts or load a plugin.",
1934
+ fix: headerFix(
1935
+ "Content-Security-Policy",
1936
+ "…; object-src 'none'; base-uri 'self'",
1937
+ `http.headers(h -> h.contentSecurityPolicy(csp -> csp.policyDirectives("…; object-src 'none'; base-uri 'self'")))`
1938
+ ),
1939
+ falsePositives: "None known; object-src is not needed when default-src is 'none'."
1940
+ }
1941
+ };
1942
+ var CSP_RO = manifestOf("header.csp-report-only");
1943
+ var cspReportOnly = {
1944
+ id: CSP_RO.id,
1945
+ manifest: CSP_RO,
1946
+ appliesTo: { resourceTypes: DOC_TYPES },
1947
+ needsBody: DOC_TYPES,
1948
+ check(input, ctx) {
1949
+ if (!isDocument(input)) return [];
1950
+ if (enforcedCsp(input).length > 0) return [];
1951
+ const ro = header(input.responseHeaders, "content-security-policy-report-only");
1952
+ if (ro === void 0) return [];
1953
+ return [
1954
+ originFinding(
1955
+ ctx,
1956
+ CSP_RO,
1957
+ input,
1958
+ "content-security-policy-report-only",
1959
+ ctx.redact.text(ro).slice(0, 120),
1960
+ `${input.endpointKey} has a report-only Content-Security-Policy and no enforced one.`
1961
+ )
1962
+ ];
1963
+ },
1964
+ docs: {
1965
+ title: CSP_RO.title,
1966
+ why: "A report-only policy reports violations but blocks nothing; it is a step towards an enforced policy, not a protection.",
1967
+ fix: headerFix(
1968
+ "Content-Security-Policy",
1969
+ "<the report-only policy, once it reports no violations>",
1970
+ 'http.headers(h -> h.contentSecurityPolicy(csp -> csp.policyDirectives("…"))) // without .reportOnly()'
1971
+ ),
1972
+ falsePositives: "Expected while a new policy is being tuned: accept with an until date."
1973
+ }
1974
+ };
1975
+ var CLICK = manifestOf("header.clickjacking");
1976
+ var clickjacking = {
1977
+ id: CLICK.id,
1978
+ manifest: CLICK,
1979
+ appliesTo: { resourceTypes: DOC_TYPES },
1980
+ check(input, ctx) {
1981
+ if (!isDocument(input)) return [];
1982
+ const csp = policies(headers(input.responseHeaders, "content-security-policy"));
1983
+ if (csp.some((p) => p.has("frame-ancestors"))) return [];
1984
+ const xfo = header(input.responseHeaders, "x-frame-options")?.trim().toUpperCase();
1985
+ if (xfo === "DENY" || xfo === "SAMEORIGIN") return [];
1986
+ return [
1987
+ originFinding(
1988
+ ctx,
1989
+ CLICK,
1990
+ input,
1991
+ "x-frame-options",
1992
+ xfo === void 0 ? "(missing)" : ctx.redact.text(xfo),
1993
+ `${input.endpointKey} can be framed by any site (no frame-ancestors, no X-Frame-Options).`
1994
+ )
1995
+ ];
1996
+ },
1997
+ docs: {
1998
+ title: CLICK.title,
1999
+ why: "A page that any site can put in an iframe can be overlaid with a decoy, so users click buttons they cannot see (clickjacking).",
2000
+ fix: headerFix(
2001
+ "Content-Security-Policy",
2002
+ "frame-ancestors 'none'",
2003
+ "http.headers(h -> h.frameOptions(f -> f.deny()))"
2004
+ ),
2005
+ falsePositives: "Pages meant to be embedded by partners (widgets): allow those origins in frame-ancestors, or accept the finding in the baseline."
2006
+ }
2007
+ };
2008
+ var HSTS_MISSING = manifestOf("header.hsts-missing");
2009
+ var hstsApplies = (r) => r.url.startsWith("https:") && is2xx(r) && (r.resourceType === "document" || r.source === "api" && isJson(header(r.responseHeaders, "content-type")));
2010
+ var hstsMissing = {
2011
+ id: HSTS_MISSING.id,
2012
+ manifest: HSTS_MISSING,
2013
+ appliesTo: { resourceTypes: ["document", "api"] },
2014
+ check(input, ctx) {
2015
+ if (!isRecord4(input) || !hstsApplies(input)) return [];
2016
+ if (header(input.responseHeaders, "strict-transport-security") !== void 0) return [];
2017
+ return [
2018
+ originFinding(
2019
+ ctx,
2020
+ HSTS_MISSING,
2021
+ input,
2022
+ "strict-transport-security",
2023
+ "(missing)",
2024
+ `${input.origin} does not send Strict-Transport-Security.`,
2025
+ // HSTS concerns browsers; API responses and local origins are advisory (15, 05-REQ-06).
2026
+ { confidence: input.source === "api" ? "low" : transportConfidence(ctx) }
2027
+ )
2028
+ ];
2029
+ },
2030
+ docs: {
2031
+ title: HSTS_MISSING.title,
2032
+ why: "Without HSTS the first request of a visit can go over plain HTTP, where an attacker on the network can downgrade the connection and steal the session.",
2033
+ fix: headerFix(
2034
+ "Strict-Transport-Security",
2035
+ "max-age=31536000; includeSubDomains",
2036
+ "http.headers(h -> h.httpStrictTransportSecurity(hsts -> hsts.maxAgeInSeconds(31536000).includeSubDomains(true)))"
2037
+ ),
2038
+ falsePositives: "Local and test environments without a real certificate; accept them or scan the deployed environment."
2039
+ }
2040
+ };
2041
+ var HSTS_WEAK = manifestOf("header.hsts-weak");
2042
+ var hstsWeak = {
2043
+ id: HSTS_WEAK.id,
2044
+ manifest: HSTS_WEAK,
2045
+ appliesTo: { resourceTypes: ["document", "api"] },
2046
+ check(input, ctx) {
2047
+ if (!isRecord4(input) || !hstsApplies(input)) return [];
2048
+ const value = header(input.responseHeaders, "strict-transport-security");
2049
+ if (value === void 0) return [];
2050
+ const maxAge = /max-age\s*=\s*"?(\d+)"?/i.exec(value);
2051
+ const min = typeof ctx.options.minMaxAge === "number" ? ctx.options.minMaxAge : 15552e3;
2052
+ if (maxAge !== null && Number(maxAge[1]) >= min) return [];
2053
+ return [
2054
+ originFinding(
2055
+ ctx,
2056
+ HSTS_WEAK,
2057
+ input,
2058
+ "strict-transport-security",
2059
+ ctx.redact.text(value),
2060
+ `Strict-Transport-Security of ${input.origin} has max-age below ${min} seconds.`,
2061
+ { confidence: input.source === "api" ? "low" : transportConfidence(ctx) }
2062
+ )
2063
+ ];
2064
+ },
2065
+ docs: {
2066
+ title: HSTS_WEAK.title,
2067
+ why: "A short max-age lets the protection expire between visits, so the downgrade attack of a missing HSTS is possible again.",
2068
+ fix: headerFix(
2069
+ "Strict-Transport-Security",
2070
+ "max-age=31536000; includeSubDomains",
2071
+ "http.headers(h -> h.httpStrictTransportSecurity(hsts -> hsts.maxAgeInSeconds(31536000)))"
2072
+ ),
2073
+ falsePositives: "A short max-age during an HSTS rollout: accept with an until date. The threshold is the option minMaxAge."
2074
+ }
2075
+ };
2076
+ var XCTO = manifestOf("header.xcto-missing");
2077
+ var xctoMissing = {
2078
+ id: XCTO.id,
2079
+ manifest: XCTO,
2080
+ appliesTo: { resourceTypes: ["document", "script", "stylesheet", "xhr", "fetch", "api"] },
2081
+ check(input, ctx) {
2082
+ if (!isRecord4(input) || !is2xx(input)) return [];
2083
+ const type = header(input.responseHeaders, "content-type");
2084
+ const relevant = ["document", "script", "stylesheet"].includes(input.resourceType) || isJson(type);
2085
+ if (!relevant) return [];
2086
+ const value = header(input.responseHeaders, "x-content-type-options");
2087
+ if (value !== void 0 && value.trim().toLowerCase() === "nosniff") return [];
2088
+ return [
2089
+ originFinding(
2090
+ ctx,
2091
+ XCTO,
2092
+ input,
2093
+ "x-content-type-options",
2094
+ value === void 0 ? "(missing)" : ctx.redact.text(value),
2095
+ `${input.endpointKey} (${input.resourceType}) has no "X-Content-Type-Options: nosniff".`
2096
+ )
2097
+ ];
2098
+ },
2099
+ docs: {
2100
+ title: XCTO.title,
2101
+ why: "Without nosniff a browser may guess the type of a response and run text or JSON as a script or style (MIME sniffing), which helps XSS and data leaks.",
2102
+ fix: headerFix(
2103
+ "X-Content-Type-Options",
2104
+ "nosniff",
2105
+ "http.headers(h -> h.contentTypeOptions(withDefaults()))"
2106
+ ),
2107
+ falsePositives: "None known for HTML, scripts, styles and JSON. Accept it for legacy endpoints you cannot change."
2108
+ }
2109
+ };
2110
+ var REFERRER = manifestOf("header.referrer-policy-unsafe");
2111
+ var referrerPolicyUnsafe = {
2112
+ id: REFERRER.id,
2113
+ manifest: REFERRER,
2114
+ appliesTo: { resourceTypes: DOC_TYPES },
2115
+ check(input, ctx) {
2116
+ if (!isDocument(input)) return [];
2117
+ const value = header(input.responseHeaders, "referrer-policy");
2118
+ if (value === void 0) {
2119
+ return [
2120
+ originFinding(
2121
+ ctx,
2122
+ REFERRER,
2123
+ input,
2124
+ "referrer-policy",
2125
+ "(missing)",
2126
+ `${input.endpointKey} has no Referrer-Policy; the browser default applies.`,
2127
+ { severity: "info", discriminator: "missing" }
2128
+ )
2129
+ ];
2130
+ }
2131
+ const effective = value.split(",").map((v) => v.trim().toLowerCase()).filter(Boolean).at(-1) ?? "";
2132
+ if (effective !== "unsafe-url" && effective !== "no-referrer-when-downgrade") return [];
2133
+ return [
2134
+ originFinding(
2135
+ ctx,
2136
+ REFERRER,
2137
+ input,
2138
+ "referrer-policy",
2139
+ effective,
2140
+ `Referrer-Policy ${effective} of ${input.endpointKey} sends full URLs (with query parameters) to other sites.`,
2141
+ { discriminator: effective }
2142
+ )
2143
+ ];
2144
+ },
2145
+ docs: {
2146
+ title: REFERRER.title,
2147
+ why: "unsafe-url and no-referrer-when-downgrade send the full URL, including tokens or personal data in the query, to every linked or embedded site.",
2148
+ fix: headerFix(
2149
+ "Referrer-Policy",
2150
+ "strict-origin-when-cross-origin",
2151
+ "http.headers(h -> h.referrerPolicy(r -> r.policy(ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)))"
2152
+ ),
2153
+ falsePositives: "A missing header is reported as info only: current browsers use a safe default."
2154
+ }
2155
+ };
2156
+ var CT = manifestOf("header.content-type-missing");
2157
+ var contentTypeMissing = {
2158
+ id: CT.id,
2159
+ manifest: CT,
2160
+ appliesTo: { resourceTypes: ["document", "script", "stylesheet", "xhr", "fetch", "api"] },
2161
+ check(input, ctx) {
2162
+ if (!isRecord4(input) || !is2xx(input) || input.status === 204) return [];
2163
+ if (header(input.responseHeaders, "content-type") !== void 0) return [];
2164
+ const length = header(input.responseHeaders, "content-length");
2165
+ const hasBody = (length !== void 0 ? Number(length) > 0 : header(input.responseHeaders, "transfer-encoding") !== void 0) || (input.body?.text.length ?? 0) > 0;
2166
+ if (!hasBody) return [];
2167
+ return [
2168
+ finding(ctx, CT, {
2169
+ subject: input.endpointKey,
2170
+ location: { origin: input.origin, endpointKey: input.endpointKey, header: "content-type" },
2171
+ evidence: [{ kind: "header", name: "content-type", snippet: "(missing)" }],
2172
+ message: `${input.endpointKey} returns a body without Content-Type.`
2173
+ })
2174
+ ];
2175
+ },
2176
+ docs: {
2177
+ title: CT.title,
2178
+ why: "Without Content-Type the browser guesses the type of the response, and a guessed HTML or script type can turn data into executable content.",
2179
+ fix: [
2180
+ "Send the right Content-Type (e.g. `application/json; charset=utf-8`) with every response that has a body.",
2181
+ "",
2182
+ "- nginx: `default_type application/octet-stream;` and correct `types` for static files",
2183
+ "- Express: `res.type('application/json')` or `res.json(...)` instead of `res.end(...)`",
2184
+ "- Spring: `@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)`"
2185
+ ].join("\n"),
2186
+ falsePositives: "Empty bodies are not reported. Binary downloads should still declare a type."
2187
+ }
2188
+ };
2189
+ function docHeaderRule(id, name, display, value, spring, why) {
2190
+ const m2 = manifestOf(id);
2191
+ return {
2192
+ id,
2193
+ manifest: m2,
2194
+ appliesTo: { resourceTypes: DOC_TYPES },
2195
+ check(input, ctx) {
2196
+ if (!isDocument(input) || header(input.responseHeaders, name) !== void 0) return [];
2197
+ return [
2198
+ originFinding(ctx, m2, input, name, "(missing)", `${input.endpointKey} has no ${display}.`)
2199
+ ];
2200
+ },
2201
+ docs: {
2202
+ title: m2.title,
2203
+ why,
2204
+ fix: headerFix(display, value, spring),
2205
+ falsePositives: "Reported only in the strict preset; it hardens the page but its absence is not a vulnerability by itself."
2206
+ }
2207
+ };
2208
+ }
2209
+ var permissionsPolicyMissing = docHeaderRule(
2210
+ "header.permissions-policy-missing",
2211
+ "permissions-policy",
2212
+ "Permissions-Policy",
2213
+ "camera=(), microphone=(), geolocation=()",
2214
+ 'http.headers(h -> h.permissionsPolicy(p -> p.policy("camera=(), microphone=()")))',
2215
+ "Permissions-Policy limits powerful browser features (camera, microphone, location) that injected or third-party code could otherwise use."
2216
+ );
2217
+ var coopMissing = docHeaderRule(
2218
+ "header.coop-missing",
2219
+ "cross-origin-opener-policy",
2220
+ "Cross-Origin-Opener-Policy",
2221
+ "same-origin",
2222
+ "http.headers(h -> h.crossOriginOpenerPolicy(c -> c.policy(SAME_ORIGIN)))",
2223
+ "Without Cross-Origin-Opener-Policy a page opened by another site keeps a reference to it (window.opener), which enables cross-window attacks and leaks."
2224
+ );
2225
+ var HEADER_RULES = [
2226
+ cspMissing,
2227
+ cspUnsafe,
2228
+ cspMissingDirectives,
2229
+ cspReportOnly,
2230
+ clickjacking,
2231
+ hstsMissing,
2232
+ hstsWeak,
2233
+ xctoMissing,
2234
+ referrerPolicyUnsafe,
2235
+ contentTypeMissing,
2236
+ permissionsPolicyMissing,
2237
+ coopMissing
2238
+ ];
2239
+
2240
+ // src/core/rules/transport.ts
2241
+ var isRecord5 = (input) => typeof input === "object" && input !== null && "status" in input;
2242
+ var isHtmlDoc2 = (r) => r.resourceType === "document" && r.status >= 200 && r.status < 300 && /html/i.test(header(r.responseHeaders, "content-type") ?? "text/html");
2243
+ var TLS_FIX = [
2244
+ "Serve the application only over HTTPS and redirect HTTP to HTTPS.",
2245
+ "",
2246
+ "- nginx: `server { listen 80; return 301 https://$host$request_uri; }`",
2247
+ "- Express: behind a proxy, `app.use((req, res, next) => req.secure ? next() : res.redirect(301, 'https://' + req.headers.host + req.url))`",
2248
+ "- Spring Security: `http.requiresChannel(c -> c.anyRequest().requiresSecure())`"
2249
+ ].join("\n");
2250
+ var CLEARTEXT = manifestOf("transport.cleartext");
2251
+ var cleartext = {
2252
+ id: CLEARTEXT.id,
2253
+ manifest: CLEARTEXT,
2254
+ appliesTo: {},
2255
+ check(input, ctx) {
2256
+ if (!isRecord5(input) || !input.url.startsWith("http:")) return [];
2257
+ return [
2258
+ finding(ctx, CLEARTEXT, {
2259
+ subject: input.origin,
2260
+ confidence: transportConfidence(ctx),
2261
+ location: { origin: input.origin, endpointKey: input.endpointKey },
2262
+ evidence: [{ kind: "url", snippet: ctx.redact.text(`${input.method} ${input.origin}`) }],
2263
+ message: `${input.origin} is served over plain HTTP.`
2264
+ })
2265
+ ];
2266
+ },
2267
+ docs: {
2268
+ title: CLEARTEXT.title,
2269
+ why: "Plain HTTP can be read and changed by anyone on the network: sessions, passwords and personal data are exposed.",
2270
+ fix: TLS_FIX,
2271
+ falsePositives: "Local development (localhost) is reported with low confidence."
2272
+ }
2273
+ };
2274
+ var MIXED = manifestOf("transport.mixed-content");
2275
+ var MIXED_TAG = /<(script|img|iframe|link|audio|video|source|embed|object)\b[^>]*?\s(?:src|href|data)\s*=\s*["']?(http:\/\/[^"'\s>]+)/gi;
2276
+ var mixedContent = {
2277
+ id: MIXED.id,
2278
+ manifest: MIXED,
2279
+ appliesTo: { outOfScope: true },
2280
+ needsBody: ["document"],
2281
+ check(input, ctx) {
2282
+ if (!isRecord5(input)) return [];
2283
+ const out = [];
2284
+ const report = (url, page, origin, evidence) => {
2285
+ const subject = normalizeAssetUrl(url);
2286
+ if (subject === null) return;
2287
+ out.push(
2288
+ finding(ctx, MIXED, {
2289
+ subject,
2290
+ location: { origin },
2291
+ evidence: [{ kind: "url", snippet: ctx.redact.text(evidence) }],
2292
+ message: `The HTTPS page ${page} loads ${subject} over HTTP.`
2293
+ })
2294
+ );
2295
+ };
2296
+ if (input.url.startsWith("http:") && input.resourceType !== "document" && input.frameUrl?.startsWith("https:") === true) {
2297
+ const frameOrigin = canonicalOrigin(input.frameUrl);
2298
+ if (frameOrigin !== null && ctx.inScope(frameOrigin))
2299
+ report(input.url, frameOrigin, frameOrigin, `${input.resourceType} ${input.url}`);
2300
+ }
2301
+ if (input.url.startsWith("https:") && isHtmlDoc2(input) && ctx.inScope(input.origin) && input.body !== void 0) {
2302
+ for (const m2 of input.body.text.matchAll(MIXED_TAG)) {
2303
+ report(
2304
+ m2[2] ?? "",
2305
+ input.endpointKey,
2306
+ input.origin,
2307
+ `<${(m2[1] ?? "").toLowerCase()} … ${m2[2] ?? ""}>`
2308
+ );
2309
+ }
2310
+ }
2311
+ return out;
2312
+ },
2313
+ docs: {
2314
+ title: MIXED.title,
2315
+ why: "An HTTP resource on an HTTPS page can be read or replaced on the network; a replaced script takes over the page.",
2316
+ fix: [
2317
+ "Load every resource over HTTPS (or with a relative URL) and add `upgrade-insecure-requests` to the CSP.",
2318
+ "",
2319
+ '- nginx: `add_header Content-Security-Policy "upgrade-insecure-requests" always;`',
2320
+ "- Express: `helmet.contentSecurityPolicy({ directives: { upgradeInsecureRequests: [] } })`",
2321
+ '- Spring Security: `http.headers(h -> h.contentSecurityPolicy(c -> c.policyDirectives("upgrade-insecure-requests")))`'
2322
+ ].join("\n"),
2323
+ falsePositives: 'Links (<a href="http://…">) are not mixed content and are not reported.'
2324
+ }
2325
+ };
2326
+ var FORM = manifestOf("transport.form-to-http");
2327
+ var FORM_ACTION = /<form\b[^>]*?\saction\s*=\s*["']?(http:\/\/[^"'\s>]+)/gi;
2328
+ var formToHttp = {
2329
+ id: FORM.id,
2330
+ manifest: FORM,
2331
+ appliesTo: { resourceTypes: ["document"] },
2332
+ needsBody: ["document"],
2333
+ check(input, ctx) {
2334
+ if (!isRecord5(input) || !input.url.startsWith("https:") || !isHtmlDoc2(input) || input.body === void 0)
2335
+ return [];
2336
+ const actions = [...input.body.text.matchAll(FORM_ACTION)].map((m2) => m2[1] ?? "");
2337
+ if (actions.length === 0) return [];
2338
+ return [
2339
+ finding(ctx, FORM, {
2340
+ subject: input.endpointKey,
2341
+ location: { origin: input.origin, endpointKey: input.endpointKey },
2342
+ evidence: actions.slice(0, 3).map((a) => ({
2343
+ kind: "body",
2344
+ snippet: ctx.redact.text(`<form action="${a}">`)
2345
+ })),
2346
+ message: `The HTTPS page ${input.endpointKey} has a form that submits over HTTP.`
2347
+ })
2348
+ ];
2349
+ },
2350
+ docs: {
2351
+ title: FORM.title,
2352
+ why: "A form on an HTTPS page that posts to HTTP sends what the user typed (often passwords) in clear text.",
2353
+ fix: [
2354
+ "Use HTTPS (or a relative URL) in every form action and add `form-action 'self'` to the CSP.",
2355
+ "",
2356
+ "- nginx: `add_header Content-Security-Policy \"form-action 'self'\" always;`",
2357
+ "- Express: `helmet.contentSecurityPolicy({ directives: { formAction: [\"'self'\"] } })`",
2358
+ "- Spring Security: `http.headers(h -> h.contentSecurityPolicy(c -> c.policyDirectives(\"form-action 'self'\")))`"
2359
+ ].join("\n"),
2360
+ falsePositives: "None known."
2361
+ }
2362
+ };
2363
+ var WEAK_TLS = manifestOf("transport.weak-tls");
2364
+ var WEAK = /^(?:ssl|tls ?v?1(?:\.[01])?)$/i;
2365
+ var weakTls = {
2366
+ id: WEAK_TLS.id,
2367
+ manifest: WEAK_TLS,
2368
+ appliesTo: { resourceTypes: ["document"] },
2369
+ check(input, ctx) {
2370
+ if (!isRecord5(input)) return [];
2371
+ const protocol = input.tls?.protocol?.trim();
2372
+ if (protocol === void 0 || !(WEAK.test(protocol) || /^ssl/i.test(protocol))) return [];
2373
+ return [
2374
+ finding(ctx, WEAK_TLS, {
2375
+ subject: input.origin,
2376
+ location: { origin: input.origin, endpointKey: input.endpointKey },
2377
+ evidence: [{ kind: "event", name: "tls", snippet: protocol }],
2378
+ message: `${input.origin} negotiated ${protocol}.`
2379
+ })
2380
+ ];
2381
+ },
2382
+ docs: {
2383
+ title: WEAK_TLS.title,
2384
+ why: "TLS 1.0, TLS 1.1 and SSL have known weaknesses and are deprecated (RFC 8996).",
2385
+ fix: [
2386
+ "Allow only TLS 1.2 and TLS 1.3.",
2387
+ "",
2388
+ "- nginx: `ssl_protocols TLSv1.2 TLSv1.3;`",
2389
+ "- Express (Node https): `https.createServer({ minVersion: 'TLSv1.2', ... })`",
2390
+ "- Spring Boot: `server.ssl.enabled-protocols=TLSv1.2,TLSv1.3`"
2391
+ ].join("\n"),
2392
+ falsePositives: "None known."
2393
+ }
2394
+ };
2395
+ var TRANSPORT_RULES = [
2396
+ cleartext,
2397
+ mixedContent,
2398
+ formToHttp,
2399
+ weakTls
2400
+ ];
2401
+
2402
+ // src/core/rules/index.ts
2403
+ var BUILT_IN_RULES = [
2404
+ ...HEADER_RULES,
2405
+ ...COOKIE_RULES,
2406
+ ...CORS_RULES,
2407
+ ...TRANSPORT_RULES,
2408
+ ...TOKEN_RULES,
2409
+ secretInAsset,
2410
+ tokenInStorage,
2411
+ ...DISCLOSURE_RULES,
2412
+ ...BROWSER_RULES
2413
+ ];
2414
+
2415
+ // src/collector/scope.ts
2416
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
2417
+ function compile(list) {
2418
+ const exact = /* @__PURE__ */ new Set();
2419
+ const patterns = [];
2420
+ for (const item of list) {
2421
+ if (item.includes("*")) {
2422
+ const parsed = parseHostPattern(item, "");
2423
+ if (typeof parsed !== "string") patterns.push(parsed);
2424
+ } else {
2425
+ const origin = canonicalOrigin(item);
2426
+ if (origin !== null) exact.add(origin);
2427
+ }
2428
+ }
2429
+ return { exact, patterns };
2430
+ }
2431
+ var Scope = class {
2432
+ #include;
2433
+ #exclude;
2434
+ #memo = /* @__PURE__ */ new Map();
2435
+ /** Origins and patterns of the scope, for the report. */
2436
+ listed;
2437
+ constructor(settings) {
2438
+ const include = [...settings.includeBaseURL ? settings.baseOrigins : [], ...settings.origins];
2439
+ this.#include = compile(include);
2440
+ this.#exclude = compile(settings.exclude);
2441
+ this.listed = [...new Set(include)].sort();
2442
+ }
2443
+ #matches(list, origin) {
2444
+ if (list.exact.has(origin)) return true;
2445
+ if (list.patterns.length === 0) return false;
2446
+ return matchingPattern(list.patterns, new URL(origin)) !== null;
2447
+ }
2448
+ /** `origin` is a canonical origin (scheme://host[:port]). */
2449
+ has(origin) {
2450
+ const known = this.#memo.get(origin);
2451
+ if (known !== void 0) return known;
2452
+ let result = false;
2453
+ if (canonicalOrigin(origin) === origin) {
2454
+ result = this.#matches(this.#include, origin) && !this.#matches(this.#exclude, origin);
2455
+ }
2456
+ this.#memo.set(origin, result);
2457
+ return result;
2458
+ }
2459
+ };
2460
+ function isLocalOrigin(origin) {
2461
+ try {
2462
+ return LOCAL_HOSTS.has(new URL(origin).hostname);
2463
+ } catch {
2464
+ return false;
2465
+ }
2466
+ }
2467
+ function domainMatches(host, domain) {
2468
+ const d = domain.replace(/^\./, "").toLowerCase();
2469
+ const h = host.toLowerCase();
2470
+ return h === d || h.endsWith(`.${d}`);
2471
+ }
2472
+
2473
+ // src/core/coverage.ts
2474
+ function emptyCoverage() {
2475
+ return {
2476
+ responses: 0,
2477
+ apiResponses: 0,
2478
+ outOfScope: 0,
2479
+ documents: 0,
2480
+ bodiesAnalyzed: 0,
2481
+ bodiesSkipped: {},
2482
+ endpoints: {},
2483
+ origins: {},
2484
+ assets: [],
2485
+ storageOrigins: [],
2486
+ rulesRun: {}
2487
+ };
2488
+ }
2489
+ function addCounts(into, from) {
2490
+ for (const [key, value] of Object.entries(from)) into[key] = (into[key] ?? 0) + value;
2491
+ }
2492
+ function sortKeys(record) {
2493
+ return Object.fromEntries(
2494
+ Object.keys(record).sort().map((k) => [k, record[k]])
2495
+ );
2496
+ }
2497
+ function addCoverage(into, from) {
2498
+ into.responses += from.responses;
2499
+ into.apiResponses += from.apiResponses;
2500
+ into.outOfScope += from.outOfScope;
2501
+ into.documents += from.documents;
2502
+ into.bodiesAnalyzed += from.bodiesAnalyzed;
2503
+ addCounts(into.bodiesSkipped, from.bodiesSkipped);
2504
+ addCounts(into.endpoints, from.endpoints);
2505
+ addCounts(into.rulesRun, from.rulesRun);
2506
+ for (const [origin, counts] of Object.entries(from.origins)) {
2507
+ const current = into.origins[origin] ??= { responses: 0, documents: 0 };
2508
+ current.responses += counts.responses;
2509
+ current.documents += counts.documents;
2510
+ }
2511
+ into.assets = [.../* @__PURE__ */ new Set([...into.assets, ...from.assets])];
2512
+ into.storageOrigins = [.../* @__PURE__ */ new Set([...into.storageOrigins, ...from.storageOrigins])];
2513
+ }
2514
+ function sortCoverage(coverage) {
2515
+ return {
2516
+ ...coverage,
2517
+ bodiesSkipped: sortKeys(coverage.bodiesSkipped),
2518
+ endpoints: sortKeys(coverage.endpoints),
2519
+ rulesRun: sortKeys(coverage.rulesRun),
2520
+ origins: sortKeys(coverage.origins),
2521
+ assets: [...coverage.assets].sort(),
2522
+ storageOrigins: [...coverage.storageOrigins].sort()
2523
+ };
2524
+ }
2525
+
2526
+ // src/collector/test-collector.ts
2527
+ var ATTACHMENT_NAME = "pw-sec-findings";
2528
+ var MAX_ATTACHMENT_BYTES = 256 * 1024;
2529
+ var MAX_CACHE_ENTRIES = 2e3;
2530
+ var AnalysisCache = class {
2531
+ #findings = /* @__PURE__ */ new Map();
2532
+ #hashes = /* @__PURE__ */ new Map();
2533
+ findings(key) {
2534
+ return this.#findings.get(key);
2535
+ }
2536
+ setFindings(key, value) {
2537
+ if (this.#findings.size >= MAX_CACHE_ENTRIES) this.#findings.clear();
2538
+ this.#findings.set(key, value);
2539
+ }
2540
+ hash(key) {
2541
+ return this.#hashes.get(key);
2542
+ }
2543
+ setHash(key, sha) {
2544
+ if (this.#hashes.size >= MAX_CACHE_ENTRIES) this.#hashes.clear();
2545
+ this.#hashes.set(key, sha);
2546
+ }
2547
+ };
2548
+ var TestCollector = class {
2549
+ options;
2550
+ coverage = emptyCoverage();
2551
+ #findings = [];
2552
+ #diagnostics = /* @__PURE__ */ new Map();
2553
+ /** Rules switched off for this test after an exception (05-REQ-15). */
2554
+ #failed = /* @__PURE__ */ new Set();
2555
+ #perRule = /* @__PURE__ */ new Map();
2556
+ #enabled;
2557
+ /** Resource types some enabled rule reads the body of (05-REQ-10). */
2558
+ bodyTypes;
2559
+ constructor(options) {
2560
+ this.options = options;
2561
+ this.#enabled = options.rules.filter((r) => options.config.rules[r.id]?.enabled === true);
2562
+ this.bodyTypes = new Set(this.#enabled.flatMap((r) => r.needsBody ?? []));
2563
+ }
2564
+ get test() {
2565
+ return this.options.test;
2566
+ }
2567
+ diagnostic(code, level, message) {
2568
+ const key = `${code}\0${message}`;
2569
+ if (!this.#diagnostics.has(key)) {
2570
+ this.#diagnostics.set(key, { code, level, message, testId: this.options.test.testId });
2571
+ }
2572
+ }
2573
+ skipBody(reason) {
2574
+ this.coverage.bodiesSkipped[reason] = (this.coverage.bodiesSkipped[reason] ?? 0) + 1;
2575
+ }
2576
+ outOfScope() {
2577
+ this.coverage.outOfScope += 1;
2578
+ }
2579
+ #context(rule, origin, isHttps) {
2580
+ const resolved = this.options.config.rules[rule.id];
2581
+ const scope = this.options.scope;
2582
+ return {
2583
+ options: resolved?.options ?? {},
2584
+ severity: resolved?.severity ?? rule.manifest.defaultSeverity,
2585
+ confidence: resolved?.confidence ?? rule.manifest.defaultConfidence,
2586
+ localDev: isLocalOrigin(origin),
2587
+ isHttps,
2588
+ inScope: (o) => scope.has(o),
2589
+ redact: this.options.redactor
2590
+ };
2591
+ }
2592
+ /** Runs one rule with error isolation (05-REQ-15, P-08) and redaction (05-REQ-16). */
2593
+ #run(rule, input, ctx) {
2594
+ this.coverage.rulesRun[rule.id] = (this.coverage.rulesRun[rule.id] ?? 0) + 1;
2595
+ try {
2596
+ return rule.check(input, ctx).map((raw) => this.options.redactor.enforce(raw));
2597
+ } catch (error) {
2598
+ this.#failed.add(rule.id);
2599
+ this.diagnostic(
2600
+ "RULE_ERROR",
2601
+ "warn",
2602
+ `rule ${rule.id} threw and is off for the rest of this test: ${error instanceof Error ? error.message : String(error)}`
2603
+ );
2604
+ return [];
2605
+ }
2606
+ }
2607
+ #add(raws, source) {
2608
+ const limit = this.options.config.limits.maxFindingsPerRule;
2609
+ for (const raw of raws) {
2610
+ const count = this.#perRule.get(raw.ruleId) ?? 0;
2611
+ if (count >= limit) {
2612
+ this.diagnostic(
2613
+ "RULE_FINDINGS_LIMIT",
2614
+ "warn",
2615
+ `rule ${raw.ruleId} reached limits.maxFindingsPerRule (${limit}) in this test; further findings were dropped`
2616
+ );
2617
+ continue;
2618
+ }
2619
+ this.#perRule.set(raw.ruleId, count + 1);
2620
+ this.#findings.push(toFinding(raw, this.options.test, source));
2621
+ }
2622
+ }
2623
+ /** Counts a record in scope (02, chapter 6). */
2624
+ #count(record) {
2625
+ const c = this.coverage;
2626
+ c.responses += 1;
2627
+ if (record.source === "api") c.apiResponses += 1;
2628
+ const isDocument2 = record.resourceType === "document";
2629
+ if (isDocument2) c.documents += 1;
2630
+ const origin = c.origins[record.origin] ??= { responses: 0, documents: 0 };
2631
+ origin.responses += 1;
2632
+ if (isDocument2) origin.documents += 1;
2633
+ c.endpoints[record.endpointKey] = (c.endpoints[record.endpointKey] ?? 0) + 1;
2634
+ if (record.resourceType === "script" || record.resourceType === "stylesheet") {
2635
+ const asset = normalizeAssetUrl(record.url);
2636
+ if (asset !== null && !c.assets.includes(asset)) c.assets.push(asset);
2637
+ }
2638
+ }
2639
+ /**
2640
+ * Analyses an in-scope record (05-REQ-15). `cachedSha` is set when the body of a static asset
2641
+ * was not read because the worker already analysed it (05-REQ-14).
2642
+ */
2643
+ analyzeRecord(record, cachedSha) {
2644
+ this.#count(record);
2645
+ const isHttps = record.url.startsWith("https:");
2646
+ for (const rule of this.#enabled) {
2647
+ if (this.#failed.has(rule.id) || !applies(rule, record)) continue;
2648
+ const ctx = this.#context(rule, record.origin, isHttps);
2649
+ const readsBody = rule.needsBody?.includes(record.resourceType) === true;
2650
+ const sha = record.body?.sha256 ?? cachedSha;
2651
+ const cacheable = readsBody && sha !== void 0 && (record.resourceType === "script" || record.resourceType === "stylesheet");
2652
+ const key = `${rule.id}\0${record.url}\0${sha ?? ""}`;
2653
+ if (cacheable && record.body === void 0) {
2654
+ this.#add(this.options.cache.findings(key) ?? [], record.source);
2655
+ continue;
2656
+ }
2657
+ const raws = this.#run(rule, record, ctx);
2658
+ if (cacheable) this.options.cache.setFindings(key, raws);
2659
+ this.#add(raws, record.source);
2660
+ }
2661
+ }
2662
+ /** Analyses an out-of-scope record with the rules that ask for it (05-REQ-05). */
2663
+ analyzeOutOfScope(record) {
2664
+ for (const rule of this.#enabled) {
2665
+ if (this.#failed.has(rule.id) || rule.appliesTo.outOfScope !== true) continue;
2666
+ if (!applies(rule, record)) continue;
2667
+ const ctx = this.#context(rule, record.origin, record.url.startsWith("https:"));
2668
+ this.#add(this.#run(rule, record, ctx), record.source);
2669
+ }
2670
+ }
2671
+ /** Analyses a browser event (05, chapters 7 and 8). */
2672
+ analyzeEvent(event) {
2673
+ if (event.kind === "storage" && !this.coverage.storageOrigins.includes(event.origin)) {
2674
+ this.coverage.storageOrigins.push(event.origin);
2675
+ }
2676
+ const origin = event.kind === "storage" ? event.origin : event.kind === "csp-violation" ? event.documentOrigin : "";
2677
+ for (const rule of this.#enabled) {
2678
+ if (this.#failed.has(rule.id)) continue;
2679
+ if (rule.appliesTo.events?.includes(event.kind) !== true) continue;
2680
+ const ctx = this.#context(rule, origin, origin.startsWith("https:"));
2681
+ this.#add(this.#run(rule, event, ctx), "browser");
2682
+ }
2683
+ }
2684
+ /** Adds coverage of work done elsewhere (e.g. the API wrapper). */
2685
+ addCoverage(coverage) {
2686
+ addCoverage(this.coverage, coverage);
2687
+ }
2688
+ findings() {
2689
+ return dedupeTest(this.#findings);
2690
+ }
2691
+ diagnostics() {
2692
+ return [...this.#diagnostics.values()];
2693
+ }
2694
+ /** The attachment (02-REQ-05): at most 256 KB, else one evidence item per finding. */
2695
+ attachment() {
2696
+ const coverage = this.coverage;
2697
+ coverage.assets.sort();
2698
+ coverage.storageOrigins.sort();
2699
+ const doc = {
2700
+ schemaVersion: 1,
2701
+ findings: this.findings(),
2702
+ coverage,
2703
+ diagnostics: this.diagnostics()
2704
+ };
2705
+ let body = JSON.stringify(doc);
2706
+ if (Buffer.byteLength(body) > MAX_ATTACHMENT_BYTES) {
2707
+ doc.findings = doc.findings.map((f) => ({ ...f, evidence: f.evidence.slice(0, 1) }));
2708
+ doc.diagnostics.push({
2709
+ code: "ATTACHMENT_TRUNCATED",
2710
+ level: "warn",
2711
+ message: "the findings of this test exceeded 256 KB; evidence was cut to one item per finding",
2712
+ testId: this.options.test.testId
2713
+ });
2714
+ body = JSON.stringify(doc);
2715
+ }
2716
+ return body;
2717
+ }
2718
+ };
2719
+ function applies(rule, record) {
2720
+ const to = rule.appliesTo;
2721
+ if (to.events !== void 0 && to.events.length > 0 && to.records !== true) return false;
2722
+ if (to.sources !== void 0 && !to.sources.includes(record.source)) return false;
2723
+ if (!rule.manifest.sources.includes(record.source)) return false;
2724
+ return to.resourceTypes === void 0 || to.resourceTypes.includes(record.resourceType);
2725
+ }
2726
+
2727
+ export { ATTACHMENT_NAME, AnalysisCache, BUILT_IN_RULES, Redactor, Scope, TestCollector, addCoverage, compareTests, dedupeRun, domainMatches, emptyCoverage, sortCoverage };