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,1113 @@
1
+ import { emptyCoverage, ATTACHMENT_NAME, addCoverage, dedupeRun, sortCoverage, compareTests, BUILT_IN_RULES } from './chunk-6HZSEXCR.js';
2
+ import { getRegistered, resolveConfig, readMode, enabledRuleCount, RULE_IDS, RUN_ID_ENV, SEVERITIES, severityRank, confidenceRank, ruleManifest, sha256 } from './chunk-IHU2HYVH.js';
3
+ import { VERSION } from './chunk-SFWIEETP.js';
4
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
5
+ import { dirname, isAbsolute, resolve, relative, join } from 'path';
6
+
7
+ // src/core/baseline/domain.ts
8
+ function domainMatchesHost(origin, domain) {
9
+ let host;
10
+ try {
11
+ host = new URL(origin).hostname.toLowerCase();
12
+ } catch {
13
+ return false;
14
+ }
15
+ const d = domain.replace(/^\./, "").toLowerCase();
16
+ return host === d || host.endsWith(`.${d}`);
17
+ }
18
+
19
+ // src/core/baseline/evaluate.ts
20
+ var EXPIRY_WARNING_DAYS = 14;
21
+ var DAY = 864e5;
22
+ var days = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / DAY);
23
+ var blocksAsNew = (f, gate) => severityRank(f.severity) >= severityRank(gate.minSeverity) && confidenceRank(f.confidence) >= confidenceRank(gate.minConfidence);
24
+ function classify(findings, baseline, gate, today2, gateOn) {
25
+ return findings.map((f) => {
26
+ const entry = baseline?.findings[f.fingerprint];
27
+ if (entry === void 0)
28
+ return { ...f, classification: "new", blocking: gateOn && blocksAsNew(f, gate) };
29
+ const info = {
30
+ status: entry.status,
31
+ addedAt: entry.addedAt
32
+ };
33
+ if (entry.note !== void 0) info.note = entry.note;
34
+ if (entry.until !== void 0) info.until = entry.until;
35
+ if (entry.status === "false-positive") {
36
+ return { ...f, classification: "false-positive", blocking: false, baseline: info };
37
+ }
38
+ if (entry.until !== void 0) {
39
+ const left = days(today2, entry.until);
40
+ if (left < 0) {
41
+ return {
42
+ ...f,
43
+ classification: "expired",
44
+ blocking: gateOn && gate.failOnExpired,
45
+ baseline: info
46
+ };
47
+ }
48
+ if (left <= EXPIRY_WARNING_DAYS) info.expiresInDays = left;
49
+ }
50
+ return { ...f, classification: entry.status, blocking: false, baseline: info };
51
+ });
52
+ }
53
+ function parseFingerprint(print) {
54
+ const [ruleId = "", scope = "", ...rest] = print.split("|");
55
+ const subject = rest.length > 1 ? rest.slice(0, -1).join("|") : rest[0] ?? "";
56
+ return { ruleId, scope, subject };
57
+ }
58
+ function covered(entrySubject, scope, coverage) {
59
+ switch (scope) {
60
+ case "origin":
61
+ return (coverage.origins[entrySubject]?.documents ?? 0) > 0;
62
+ case "endpoint":
63
+ return (coverage.endpoints[entrySubject] ?? 0) > 0;
64
+ case "asset":
65
+ return coverage.assets.includes(entrySubject);
66
+ case "storage-key": {
67
+ const at = entrySubject.lastIndexOf("@");
68
+ return at > 0 && coverage.storageOrigins.includes(entrySubject.slice(at + 1));
69
+ }
70
+ case "cookie": {
71
+ const at = entrySubject.lastIndexOf("@");
72
+ if (at <= 0) return false;
73
+ const domain = entrySubject.slice(at + 1);
74
+ return Object.entries(coverage.origins).some(
75
+ ([origin, c]) => c.responses > 0 && domainMatchesHost(origin, domain)
76
+ );
77
+ }
78
+ default:
79
+ return false;
80
+ }
81
+ }
82
+ function resolveEntries(baseline, findings, coverage, enabledRules) {
83
+ const seen = new Set(findings.map((f) => f.fingerprint));
84
+ const resolved = [];
85
+ const notCovered = [];
86
+ for (const [fingerprint, entry] of Object.entries(baseline?.findings ?? {}).sort(
87
+ ([a], [b]) => a < b ? -1 : 1
88
+ )) {
89
+ if (seen.has(fingerprint)) continue;
90
+ const ref = { fingerprint, ruleId: entry.ruleId, subject: entry.subject };
91
+ const { scope } = parseFingerprint(fingerprint);
92
+ if (enabledRules.has(entry.ruleId) && covered(entry.subject, scope, coverage))
93
+ resolved.push(ref);
94
+ else notCovered.push(ref);
95
+ }
96
+ return { resolved, notCovered };
97
+ }
98
+ var NAMES = ["OK", "NEW_FINDINGS", "BASELINE_EXPIRED", "TOOL_ERROR", "NO_TRAFFIC"];
99
+ function outcome(input) {
100
+ const newBlocking = input.findings.filter((f) => f.classification === "new" && f.blocking).length;
101
+ const newNonBlocking = input.findings.filter(
102
+ (f) => f.classification === "new" && !f.blocking
103
+ ).length;
104
+ const expired = input.findings.filter((f) => f.classification === "expired").length;
105
+ const expiredBlocking = input.findings.filter(
106
+ (f) => f.classification === "expired" && f.blocking
107
+ ).length;
108
+ let code = 0;
109
+ if (input.diagnostics.some((d) => d.level === "error")) code = 3;
110
+ else if (newBlocking > 0) code = 1;
111
+ else if (expiredBlocking > 0) code = 2;
112
+ else if (input.responses === 0 && input.gate.failOnNoTraffic) code = 4;
113
+ return {
114
+ schemaVersion: 1,
115
+ code,
116
+ name: NAMES[code],
117
+ testsPassed: input.testsPassed,
118
+ newBlocking,
119
+ newNonBlocking,
120
+ expired,
121
+ resolved: input.resolved
122
+ };
123
+ }
124
+ function missingNotes(baseline) {
125
+ const prints = Object.entries(baseline?.findings ?? {}).filter(
126
+ ([, e]) => e.status !== "false-positive" && (e.note === void 0 || e.note.trim() === "")
127
+ ).map(([p]) => p).sort();
128
+ if (prints.length === 0) return [];
129
+ return [
130
+ {
131
+ code: "BASELINE_NOTE_REQUIRED",
132
+ level: "error",
133
+ message: `baseline.requireNote: ${prints.length} accepted entries have no note: ${prints.slice(0, 10).join(", ")}${prints.length > 10 ? ", …" : ""}`
134
+ }
135
+ ];
136
+ }
137
+
138
+ // src/core/baseline/parse.ts
139
+ var STATUSES = ["accepted", "false-positive", "wontfix"];
140
+ var DATE = /^\d{4}-\d{2}-\d{2}$/;
141
+ var ENTRY_KEYS = /* @__PURE__ */ new Set(["ruleId", "subject", "severity", "status", "note", "until", "addedAt"]);
142
+ var error = (message) => ({
143
+ code: "BASELINE_INVALID",
144
+ level: "error",
145
+ message
146
+ });
147
+ function parseBaseline(text, path, knownRules, enabledRules) {
148
+ let data;
149
+ try {
150
+ data = JSON.parse(text);
151
+ } catch (e) {
152
+ return {
153
+ ok: false,
154
+ diagnostics: [
155
+ error(`${path}: not valid JSON (${e instanceof Error ? e.message : String(e)})`)
156
+ ]
157
+ };
158
+ }
159
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
160
+ return { ok: false, diagnostics: [error(`${path}: the top level must be an object`)] };
161
+ }
162
+ const doc = data;
163
+ if (doc.schemaVersion !== 1) {
164
+ return {
165
+ ok: false,
166
+ diagnostics: [
167
+ error(`${path}: schemaVersion must be 1, found ${JSON.stringify(doc.schemaVersion)}`)
168
+ ]
169
+ };
170
+ }
171
+ const findings = doc.findings;
172
+ if (typeof findings !== "object" || findings === null || Array.isArray(findings)) {
173
+ return {
174
+ ok: false,
175
+ diagnostics: [error(`${path}: "findings" must be an object of fingerprint → entry`)]
176
+ };
177
+ }
178
+ const problems = [];
179
+ const notes = [];
180
+ const entries = {};
181
+ for (const [print, raw] of Object.entries(findings)) {
182
+ const at = `${path}: findings[${JSON.stringify(print)}]`;
183
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
184
+ problems.push(error(`${at} must be an object`));
185
+ continue;
186
+ }
187
+ const e = raw;
188
+ const unknown = Object.keys(e).filter((k) => !ENTRY_KEYS.has(k));
189
+ if (unknown.length > 0)
190
+ problems.push(error(`${at}: unknown field ${unknown.map((k) => `"${k}"`).join(", ")}`));
191
+ if (typeof e.ruleId !== "string") {
192
+ problems.push(error(`${at}.ruleId must be a string`));
193
+ continue;
194
+ }
195
+ if (!knownRules.has(e.ruleId)) {
196
+ problems.push(error(`${at}.ruleId: unknown rule "${e.ruleId}"`));
197
+ continue;
198
+ }
199
+ if (typeof e.subject !== "string") problems.push(error(`${at}.subject must be a string`));
200
+ if (typeof e.severity !== "string" || !SEVERITIES.includes(e.severity)) {
201
+ problems.push(error(`${at}.severity must be one of ${SEVERITIES.join(", ")}`));
202
+ }
203
+ if (typeof e.status !== "string" || !STATUSES.includes(e.status)) {
204
+ problems.push(error(`${at}.status must be one of ${STATUSES.join(", ")}`));
205
+ }
206
+ if (e.note !== void 0 && typeof e.note !== "string")
207
+ problems.push(error(`${at}.note must be a string`));
208
+ if (e.until !== void 0 && (typeof e.until !== "string" || !DATE.test(e.until))) {
209
+ problems.push(error(`${at}.until must be a date YYYY-MM-DD`));
210
+ }
211
+ if (typeof e.addedAt !== "string" || !DATE.test(e.addedAt))
212
+ problems.push(error(`${at}.addedAt must be a date YYYY-MM-DD`));
213
+ if (e.status === "wontfix" && (typeof e.note !== "string" || e.note.trim() === "")) {
214
+ problems.push(error(`${at}: a wontfix entry needs a "note" (02-REQ-02)`));
215
+ }
216
+ if (!enabledRules.has(e.ruleId)) {
217
+ notes.push({
218
+ code: "BASELINE_RULE_OFF",
219
+ level: "info",
220
+ message: `${at}: rule ${e.ruleId} is off in the config; the entry is kept but not used`
221
+ });
222
+ }
223
+ if (e.status === "false-positive" && e.until !== void 0) {
224
+ notes.push({
225
+ code: "BASELINE_STALE_STATUS",
226
+ level: "warn",
227
+ message: `${at}: "until" is ignored on a false-positive entry; false positives do not expire`
228
+ });
229
+ }
230
+ entries[print] = e;
231
+ }
232
+ if (problems.length > 0) return { ok: false, diagnostics: problems };
233
+ const file = { schemaVersion: 1, findings: entries };
234
+ if (typeof doc.generatedBy === "string") file.generatedBy = doc.generatedBy;
235
+ return { ok: true, file, diagnostics: notes };
236
+ }
237
+
238
+ // src/core/baseline/write.ts
239
+ function updateBaseline(existing, findings, resolved, options) {
240
+ const entries = {};
241
+ for (const [print, entry] of Object.entries(existing?.findings ?? {}))
242
+ entries[print] = { ...entry };
243
+ const added = [];
244
+ for (const f of findings) {
245
+ const current = entries[f.fingerprint];
246
+ if (current === void 0) {
247
+ entries[f.fingerprint] = {
248
+ ruleId: f.ruleId,
249
+ subject: f.subject,
250
+ severity: f.severity,
251
+ status: "accepted",
252
+ addedAt: options.today
253
+ };
254
+ added.push({
255
+ fingerprint: f.fingerprint,
256
+ ruleId: f.ruleId,
257
+ subject: f.subject,
258
+ severity: f.severity
259
+ });
260
+ } else {
261
+ current.severity = f.severity;
262
+ }
263
+ }
264
+ const removed = [];
265
+ if (options.prune) {
266
+ for (const ref of resolved) {
267
+ const entry = entries[ref.fingerprint];
268
+ if (entry === void 0 || entry.status === "false-positive") continue;
269
+ Reflect.deleteProperty(entries, ref.fingerprint);
270
+ removed.push(ref);
271
+ }
272
+ }
273
+ const total = Object.keys(entries).length;
274
+ return {
275
+ file: { schemaVersion: 1, generatedBy: options.generatedBy, findings: entries },
276
+ diff: {
277
+ added: added.sort((a, b) => a.fingerprint < b.fingerprint ? -1 : 1),
278
+ removed,
279
+ unchanged: total - added.length
280
+ }
281
+ };
282
+ }
283
+ var ORDER = [
284
+ "ruleId",
285
+ "subject",
286
+ "severity",
287
+ "status",
288
+ "note",
289
+ "until",
290
+ "addedAt"
291
+ ];
292
+ function serializeBaseline(file) {
293
+ const findings = {};
294
+ for (const print of Object.keys(file.findings).sort()) {
295
+ const entry = file.findings[print];
296
+ const ordered = {};
297
+ for (const key of ORDER) if (entry[key] !== void 0) ordered[key] = entry[key];
298
+ findings[print] = ordered;
299
+ }
300
+ const doc = { schemaVersion: 1 };
301
+ if (file.generatedBy !== void 0) doc.generatedBy = file.generatedBy;
302
+ doc.findings = findings;
303
+ return `${JSON.stringify(doc, null, 2)}
304
+ `;
305
+ }
306
+
307
+ // src/core/report/console.ts
308
+ var MAX_SUMMARY_LINES = 30;
309
+ function formatBanner(b) {
310
+ const lines = [
311
+ `pw-sec · mode: ${b.mode} · passive only`,
312
+ `scope: ${b.scope.length === 0 ? "(none: set use.baseURL or scope.origins)" : b.scope.join(", ")}`,
313
+ `rules: ${b.enabledRules} enabled (preset ${b.preset}) · gate: ${b.mode === "baseline" ? "off (baseline run)" : `new findings ≥ ${b.minSeverity} (confidence ≥ ${b.minConfidence})`}`,
314
+ `baseline: ${b.baselinePath} (${b.baselineEntries === null ? "not found" : `${b.baselineEntries} entries`})`,
315
+ `report: ${b.reportPath}`
316
+ ];
317
+ for (const n of b.notes) lines.push(`${n.level === "info" ? "note" : n.level}: ${n.message}`);
318
+ return lines;
319
+ }
320
+ var testLabel = (t) => `${t.file}:${t.line} › ${t.titlePath.join(" › ")}`;
321
+ var findingOrder = (a, b) => severityRank(b.severity) - severityRank(a.severity) || confidenceRank(b.confidence) - confidenceRank(a.confidence) || b.tests.length - a.tests.length || (a.fingerprint < b.fingerprint ? -1 : 1);
322
+ var findingLine = (f, mark) => [
323
+ `${mark} ${f.ruleId} ${f.severity}/${f.confidence} ${f.subject}${f.discriminator === void 0 ? "" : ` (${f.discriminator})`}`,
324
+ ` first seen: ${testLabel(f.firstSeen)}`
325
+ ];
326
+ function formatSummary(report, paths) {
327
+ const c = report.coverage;
328
+ const count = (cls, blocking) => report.findings.filter(
329
+ (f) => f.classification === cls && (blocking === void 0 || f.blocking === blocking)
330
+ ).length;
331
+ const head = [
332
+ `pw-sec · ${c.responses} responses in scope${c.apiResponses > 0 ? ` (${c.apiResponses} API)` : ""} · ${Object.keys(c.endpoints).length} endpoints · ${c.documents} documents`,
333
+ ` NEW ${count("new", true)} blocking ${count("new", false)} non-blocking`,
334
+ ` baseline ${count("accepted")} accepted ${count("wontfix")} wontfix ${count("false-positive")} false-positive ${count("expired")} expired`,
335
+ ` resolved ${report.resolved.length}${report.notCovered.length > 0 ? ` not covered ${report.notCovered.length}` : ""}`
336
+ ];
337
+ const tail = [];
338
+ if (report.resolved.length > 0 && report.mode === "scan") {
339
+ tail.push(
340
+ `→ ${report.resolved.length} baseline ${report.resolved.length === 1 ? "entry" : "entries"} resolved — run baseline mode to remove ${report.resolved.length === 1 ? "it" : "them"}`
341
+ );
342
+ }
343
+ const expiring = report.findings.filter(
344
+ (f) => f.baseline?.expiresInDays !== void 0 && f.classification !== "expired"
345
+ );
346
+ for (const f of expiring.slice(0, 3)) {
347
+ tail.push(
348
+ `! ${f.ruleId} ${f.subject}: baseline entry expires in ${f.baseline?.expiresInDays} days`
349
+ );
350
+ }
351
+ for (const d of report.diagnostics.filter((x) => x.level !== "info").slice(0, 3)) {
352
+ tail.push(`${d.level === "error" ? "✘" : "!"} ${d.code}: ${d.message}`);
353
+ }
354
+ if (report.mode === "scan" && count("new", true) > 0) {
355
+ tail.push(
356
+ "→ accept: PW_SEC_MODE=baseline npx playwright test (review the diff before commit)"
357
+ );
358
+ }
359
+ if (paths.html !== null) tail.push(`→ report: ${paths.html}`);
360
+ else if (paths.json !== null) tail.push(`→ report: ${paths.json}`);
361
+ tail.push(
362
+ `${report.outcome.code === 0 ? "✔" : "✘"} pw-sec: ${report.outcome.name} (code ${report.outcome.code})`
363
+ );
364
+ const important = report.findings.filter((f) => f.blocking || f.classification === "expired").sort(findingOrder);
365
+ const budget = MAX_SUMMARY_LINES - head.length - tail.length;
366
+ const body2 = [];
367
+ let shown = 0;
368
+ for (const f of important) {
369
+ if (body2.length + 2 > budget - 1) break;
370
+ body2.push(...findingLine(f, f.classification === "expired" ? "⌛" : "✘"));
371
+ shown += 1;
372
+ }
373
+ if (shown < important.length)
374
+ body2.push(` … and ${important.length - shown} more (see the report)`);
375
+ return [...head, ...body2, ...tail];
376
+ }
377
+ function formatBaselineDiff(path, diff, partial) {
378
+ const lines = [path];
379
+ for (const a of diff.added.slice(0, 20))
380
+ lines.push(` + ${a.ruleId} | ${a.subject} ${a.severity}`);
381
+ if (diff.added.length > 20) lines.push(` + … ${diff.added.length - 20} more`);
382
+ for (const r of diff.removed.slice(0, 20))
383
+ lines.push(` - ${r.ruleId} | ${r.subject} (resolved)`);
384
+ if (diff.removed.length > 20) lines.push(` - … ${diff.removed.length - 20} more`);
385
+ lines.push(` = ${diff.unchanged} unchanged`);
386
+ if (partial) lines.push(" (partial run: resolved entries were kept)");
387
+ lines.push('Review the new entries, add a "note" (and optionally "until"), then commit.');
388
+ return lines;
389
+ }
390
+
391
+ // src/reporter/partial.ts
392
+ var VALUE_OPTIONS = /* @__PURE__ */ new Set([
393
+ "-c",
394
+ "--config",
395
+ "--reporter",
396
+ "-j",
397
+ "--workers",
398
+ "--retries",
399
+ "--timeout",
400
+ "--repeat-each",
401
+ "--max-failures",
402
+ "--output",
403
+ "--trace",
404
+ "--tsconfig",
405
+ "--global-timeout",
406
+ "--browser",
407
+ "--ui-host",
408
+ "--ui-port"
409
+ ]);
410
+ var FILTER_OPTIONS = [
411
+ "-g",
412
+ "--grep",
413
+ "--grep-invert",
414
+ "--shard",
415
+ "--project",
416
+ "--only-changed",
417
+ "--last-failed"
418
+ ];
419
+ function isPartialRun(config, _suite, argv) {
420
+ if (config?.shard != null) return true;
421
+ const start = argv.findIndex((a) => a === "test");
422
+ const args = start < 0 ? [] : argv.slice(start + 1);
423
+ for (let i = 0; i < args.length; i++) {
424
+ const arg = args[i] ?? "";
425
+ const name = arg.split("=")[0] ?? "";
426
+ if (FILTER_OPTIONS.includes(name)) return true;
427
+ if (arg.startsWith("-")) {
428
+ if (VALUE_OPTIONS.has(name) && !arg.includes("=")) i += 1;
429
+ continue;
430
+ }
431
+ return true;
432
+ }
433
+ return false;
434
+ }
435
+
436
+ // src/core/report/html.ts
437
+ function embedJson(value) {
438
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
439
+ }
440
+ var CSS = `:root{--sans:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Inter,Roboto,"Helvetica Neue",Arial,sans-serif;--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace;--bg:#f6f7f9;--surface:#fff;--sunken:#f1f3f6;--line:#e4e7ec;--fg:#101828;--fg-2:#475467;--fg-3:#5d6979;--accent:#4f46e5;--accent-soft:#eef0ff;--ok:#067647;--ok-soft:#e6f6ee;--warn:#a14c05;--warn-soft:#fef4e4;--bad:#b42318;--bad-soft:#fef3f2;--mute:#5d6979;--mute-soft:#eef0f3;--r:8px;--sh:0 1px 2px rgb(16 24 40/5%)}
441
+ @media (prefers-color-scheme:dark){:root{--bg:#0b0d12;--surface:#12151c;--sunken:#0f1218;--line:#262b36;--fg:#eef1f6;--fg-2:#a9b0bf;--fg-3:#8e97a8;--accent:#8b93ff;--accent-soft:#1d2040;--ok:#47cd89;--ok-soft:#0f2a1d;--warn:#fdb022;--warn-soft:#2d2210;--bad:#f97066;--bad-soft:#2d1214;--mute:#8e97a8;--mute-soft:#1a1e27}}
442
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.5 var(--sans)}
443
+ header,main{max-width:1200px;margin:0 auto;padding:16px}h1{font-size:20px;margin:0 0 4px}h2{font-size:16px;margin:24px 0 8px}
444
+ .card{background:var(--surface);border:1px solid var(--line);border-radius:var(--r);box-shadow:var(--sh);padding:12px 16px;margin-bottom:12px}
445
+ .meta{color:var(--fg-2);font-size:13px}.counters{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}
446
+ .counter{border-radius:var(--r);padding:6px 10px;background:var(--sunken)}.counter b{font-size:18px;margin-right:4px}
447
+ .outcome{display:inline-block;border-radius:999px;padding:2px 10px;font-weight:600}.ok{background:var(--ok-soft);color:var(--ok)}.bad{background:var(--bad-soft);color:var(--bad)}.warn{background:var(--warn-soft);color:var(--warn)}.mute{background:var(--mute-soft);color:var(--mute)}
448
+ .filters{display:flex;flex-wrap:wrap;gap:8px;align-items:center}select,input{font:inherit;color:inherit;background:var(--surface);border:1px solid var(--line);border-radius:6px;padding:4px 8px}
449
+ table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--fg-3);font-weight:600;font-size:12px}
450
+ tr.row{cursor:pointer}tr.row:hover{background:var(--sunken)}tr.group td{background:var(--sunken);font-weight:600}
451
+ .pill{border-radius:999px;padding:0 8px;font-size:12px;white-space:nowrap}.sev-critical,.sev-high{background:var(--bad-soft);color:var(--bad)}.sev-medium{background:var(--warn-soft);color:var(--warn)}.sev-low,.sev-info{background:var(--mute-soft);color:var(--mute)}
452
+ code,pre{font-family:var(--mono);font-size:12px}pre{background:var(--sunken);border-radius:6px;padding:8px;overflow:auto;white-space:pre-wrap;word-break:break-all}
453
+ .detail{display:none}.detail.open{display:table-row}.detail td{background:var(--surface)}.first{font-weight:600}
454
+ .box{border-left:4px solid var(--warn);background:var(--warn-soft)}ul{margin:4px 0;padding-left:20px}button{font:inherit;border:1px solid var(--line);background:var(--surface);color:inherit;border-radius:6px;padding:2px 8px;cursor:pointer}`;
455
+ var SCRIPT = `(function(){
456
+ var D=JSON.parse(document.getElementById('pw-sec-data').textContent);var R=D.report;var RULES=D.rules;
457
+ var SEV=['critical','high','medium','low','info'];var CONF=['high','medium','low'];
458
+ function e(t){return String(t==null?'':t).replace(/[&<>"']/g,function(c){return'&#'+c.charCodeAt(0)+';'})}
459
+ function md(t){return e(t).replace(/\`([^\`]+)\`/g,'<code>$1</code>').replace(/\\*\\*([^*]+)\\*\\*/g,'<b>$1</b>').split('\\n').map(function(l){return/^- /.test(l)?'<li>'+l.slice(2)+'</li>':l===''?'<br>':'<div>'+l+'</div>'}).join('').replace(/(<li>.*?<\\/li>)+/g,'<ul>$&</ul>')}
460
+ function el(id){return document.getElementById(id)}
461
+ var o=R.outcome;var cls=o.code===0?'ok':o.code===4?'warn':'bad';
462
+ var cnt=function(c,b){return R.findings.filter(function(f){return f.classification===c&&(b===undefined||f.blocking===b)}).length};
463
+ el('head').innerHTML='<h1>Security scan <span class="outcome '+cls+'">'+e(o.name)+' · code '+o.code+'</span></h1><div class="meta">mode '+e(R.mode)+' · passive only · scope '+e(R.scope.origins.join(', ')||'(none)')+' · playwright-security-scan '+e(R.pkgVersion)+' · Playwright '+e(R.playwrightVersion)+' · '+e(R.startedAt)+' → '+e(R.finishedAt)+'</div><div class="counters">'+[['new, blocking',cnt('new',true),'bad'],['new, non-blocking',cnt('new',false),'warn'],['accepted',cnt('accepted')+cnt('wontfix')+cnt('false-positive'),'mute'],['expired',cnt('expired'),'bad'],['resolved',R.resolved.length,'ok']].map(function(c){return'<span class="counter '+c[2]+'"><b>'+c[1]+'</b>'+c[0]+'</span>'}).join('')+'</div>';
464
+ var origins={};R.findings.forEach(function(f){origins[f.location.origin]=1});
465
+ function opts(id,vals){el(id).innerHTML='<option value="">all</option>'+vals.map(function(v){return'<option>'+e(v)+'</option>'}).join('')}
466
+ opts('f-class',['new','expired','accepted','wontfix','false-positive']);opts('f-sev',SEV);opts('f-conf',CONF);opts('f-group',Object.keys(RULES).map(function(k){return RULES[k].group}).filter(function(v,i,a){return a.indexOf(v)===i}).sort());opts('f-origin',Object.keys(origins).sort());
467
+ var rank={new:0,expired:1};function order(f){return f.blocking?0:f.classification==='expired'?1:f.classification==='new'?2:3}
468
+ function testName(t){return e(t.file)+':'+t.line+' › '+e(t.titlePath.join(' › '))}
469
+ function detail(f){var r=RULES[f.ruleId]||{};var entry={};entry[f.fingerprint]={ruleId:f.ruleId,subject:f.subject,severity:f.severity,status:'accepted',note:'',until:'',addedAt:new Date().toISOString().slice(0,10)};
470
+ return'<div><b>'+e(f.message)+'</b></div><div class="meta">'+e(f.severity)+'/'+e(f.confidence)+' · '+(r.cwe||[]).map(function(c){return'CWE-'+c+' (cwe.mitre.org/data/definitions/'+c+'.html)'}).join(', ')+(r.owasp?' · OWASP '+e(r.owasp):'')+' · sources: '+e(f.sources.join(', '))+' · '+f.occurrences+' occurrences</div>'
471
+ +(f.baseline?'<div class="meta">baseline: '+e(f.baseline.status)+(f.baseline.note?' — '+e(f.baseline.note):'')+(f.baseline.until?' · until '+e(f.baseline.until):'')+(f.baseline.expiresInDays!=null?' · expires in '+f.baseline.expiresInDays+' days':'')+'</div>':'')
472
+ +'<h3>Evidence</h3>'+(f.evidence.length?'<pre>'+f.evidence.map(function(v){return e(v.kind+(v.name?' '+v.name:'')+': '+v.snippet)}).join('\\n')+'</pre>':'<div class="meta">none</div>')
473
+ +'<h3>Tests</h3><ul><li class="first">'+testName(f.firstSeen)+(f.firstSeen.step?' › '+e(f.firstSeen.step):'')+' (first seen)</li>'+(f.tests.length>1?'<li>and '+(f.tests.length-1)+' more tests</li>':'')+'</ul>'
474
+ +'<h3>Why</h3>'+md(r.why||'')+'<h3>Fix</h3>'+md(r.fix||'')+'<h3>False positives</h3>'+md(r.falsePositives||'')
475
+ +'<h3>Accept</h3><div class="meta">Add to security-baseline.json, fill in "note" (and "until" or remove it), commit after review:</div><pre>'+e(JSON.stringify(entry,null,2))+'</pre>'}
476
+ function render(){var c=el('f-class').value,s=el('f-sev').value,cf=el('f-conf').value,g=el('f-group').value,or=el('f-origin').value,t=el('f-test').value.toLowerCase(),by=el('f-by').value;
477
+ var list=R.findings.filter(function(f){var r=RULES[f.ruleId]||{};return(!c||f.classification===c)&&(!s||f.severity===s)&&(!cf||f.confidence===cf)&&(!g||r.group===g)&&(!or||f.location.origin===or)&&(!t||(f.firstSeen.file+' '+f.firstSeen.titlePath.join(' ')).toLowerCase().indexOf(t)>=0)});
478
+ list.sort(function(a,b){return order(a)-order(b)||SEV.indexOf(a.severity)-SEV.indexOf(b.severity)||(a.fingerprint<b.fingerprint?-1:1)});
479
+ var key=function(f){return by==='origin'?f.location.origin:by==='endpoint'?(f.location.endpointKey||f.subject):f.ruleId};var groups={};list.forEach(function(f){(groups[key(f)]=groups[key(f)]||[]).push(f)});
480
+ var h='';Object.keys(groups).sort(function(a,b){return order(groups[a][0])-order(groups[b][0])||(a<b?-1:1)}).forEach(function(k){h+='<tr class="group"><td colspan="7">'+e(k)+(by==='rule'&&RULES[k]?' — '+e(RULES[k].title):'')+' ('+groups[k].length+')</td></tr>';groups[k].forEach(function(f){var i=R.findings.indexOf(f);
481
+ h+='<tr class="row" data-i="'+i+'"><td><span class="pill sev-'+f.severity+'">'+f.severity+'</span></td><td>'+f.confidence+'</td><td>'+e(f.ruleId)+'</td><td>'+e(f.subject)+(f.discriminator?' <span class="meta">('+e(f.discriminator)+')</span>':'')+'</td><td>'+f.occurrences+'</td><td>'+f.tests.length+'</td><td><span class="outcome '+(f.blocking?'bad':f.classification==='new'?'warn':'mute')+'">'+e(f.classification)+(f.blocking?' · blocking':'')+'</span></td></tr><tr class="detail" id="d'+i+'"><td colspan="7">'+detail(f)+'</td></tr>'})});
482
+ el('rows').innerHTML=h||'<tr><td colspan="7" class="meta">No findings match the filters.</td></tr>';el('shown').textContent=list.length+' of '+R.findings.length}
483
+ ['f-class','f-sev','f-conf','f-group','f-origin','f-test','f-by'].forEach(function(id){el(id).addEventListener('input',render)});
484
+ el('rows').addEventListener('click',function(ev){var tr=ev.target.closest('tr.row');if(tr)el('d'+tr.getAttribute('data-i')).classList.toggle('open')});
485
+ render();
486
+ var C=R.coverage;var noInput=Object.keys(RULES).filter(function(k){return RULES[k].enabled&&!C.rulesRun[k]});
487
+ el('coverage').innerHTML='<div>'+C.responses+' responses in scope ('+C.apiResponses+' from API tests), '+C.outOfScope+' out of scope, '+C.documents+' documents; bodies analysed '+C.bodiesAnalyzed+', skipped: '+(Object.keys(C.bodiesSkipped).map(function(k){return e(k)+' '+C.bodiesSkipped[k]}).join(', ')||'none')+'</div>'
488
+ +'<h3>Origins</h3><ul>'+Object.keys(C.origins).map(function(k){return'<li>'+e(k)+' — '+C.origins[k].responses+' responses, '+C.origins[k].documents+' documents</li>'}).join('')+'</ul>'
489
+ +'<h3>Endpoints ('+Object.keys(C.endpoints).length+')</h3><table><tr><th>endpoint</th><th>responses</th></tr>'+Object.keys(C.endpoints).map(function(k){return'<tr><td><code>'+e(k)+'</code></td><td>'+C.endpoints[k]+'</td></tr>'}).join('')+'</table>'
490
+ +'<h3>Tests without traffic in scope ('+R.testsWithoutTraffic.length+')</h3>'+(R.testsWithoutTraffic.length?'<div class="meta">A context created by hand and not passed to security.track() is not scanned.</div><ul>'+R.testsWithoutTraffic.map(function(t){return'<li>'+testName(t)+'</li>'}).join('')+'</ul>':'<div class="meta">none</div>')
491
+ +'<h3>Rules that had nothing to check ('+noInput.length+')</h3><div class="meta">'+(noInput.map(e).join(', ')||'none')+'</div>'
492
+ +(R.resolved.length?'<h3>Resolved baseline entries ('+R.resolved.length+')</h3><ul>'+R.resolved.map(function(r){return'<li><code>'+e(r.fingerprint)+'</code></li>'}).join('')+'</ul><div class="meta">Run PW_SEC_MODE=baseline to remove them.</div>':'')
493
+ +(R.notCovered.length?'<h3>Baseline entries not covered by this run ('+R.notCovered.length+')</h3><ul>'+R.notCovered.map(function(r){return'<li><code>'+e(r.fingerprint)+'</code></li>'}).join('')+'</ul>':'');
494
+ el('diag').innerHTML=R.diagnostics.length?'<ul>'+R.diagnostics.map(function(d){return'<li><span class="outcome '+(d.level==='error'?'bad':d.level==='warn'?'warn':'mute')+'">'+e(d.level)+'</span> <code>'+e(d.code)+'</code> '+e(d.message)+'</li>'}).join('')+'</ul>':'<div class="meta">none</div>';
495
+ })();`;
496
+ function renderHtml(report, rules, enabled) {
497
+ const used = /* @__PURE__ */ new Set([...report.findings.map((f) => f.ruleId), ...enabled]);
498
+ const docs = {};
499
+ for (const rule of rules) {
500
+ if (!used.has(rule.id)) continue;
501
+ const m = ruleManifest(rule.id);
502
+ docs[rule.id] = {
503
+ id: rule.id,
504
+ title: rule.docs.title,
505
+ group: m?.group ?? "browser",
506
+ cwe: m?.cwe ?? [],
507
+ ...m?.owasp === void 0 ? {} : { owasp: m.owasp },
508
+ why: rule.docs.why,
509
+ fix: rule.docs.fix,
510
+ falsePositives: rule.docs.falsePositives,
511
+ enabled: enabled.has(rule.id)
512
+ };
513
+ }
514
+ const data = embedJson({ report, rules: docs });
515
+ return `<!doctype html>
516
+ <html lang="en">
517
+ <head>
518
+ <meta charset="utf-8">
519
+ <meta name="viewport" content="width=device-width, initial-scale=1">
520
+ <title>Security scan · ${report.outcome.name}</title>
521
+ <style>${CSS}</style>
522
+ </head>
523
+ <body>
524
+ <header><div class="card" id="head"></div></header>
525
+ <main>
526
+ <noscript><div class="card">This report needs JavaScript; the same data is in report.json.</div></noscript>
527
+ <div class="card box"><b>What this scan does not cover.</b> It is passive: it only looks at the traffic of your tests. It does not send attacks (no injection or authorization tests), does not see endpoints your tests never call, WebSockets or Server-Sent Events, and does not judge business logic. It does not replace a penetration test. Active checks are planned for later versions (see the README roadmap).</div>
528
+ <h2>Findings <span class="meta" id="shown"></span></h2>
529
+ <div class="card filters">
530
+ <label>classification <select id="f-class"></select></label>
531
+ <label>severity <select id="f-sev"></select></label>
532
+ <label>confidence <select id="f-conf"></select></label>
533
+ <label>rule group <select id="f-group"></select></label>
534
+ <label>origin <select id="f-origin"></select></label>
535
+ <label>test <input id="f-test" placeholder="file or title"></label>
536
+ <label>group by <select id="f-by"><option value="rule">rule</option><option value="origin">origin</option><option value="endpoint">endpoint</option></select></label>
537
+ </div>
538
+ <div class="card"><table><thead><tr><th>severity</th><th>confidence</th><th>rule</th><th>subject</th><th>occurrences</th><th>tests</th><th>classification</th></tr></thead><tbody id="rows"></tbody></table></div>
539
+ <h2>Coverage</h2>
540
+ <div class="card" id="coverage"></div>
541
+ <h2>Diagnostics</h2>
542
+ <div class="card" id="diag"></div>
543
+ </main>
544
+ <script type="application/json" id="pw-sec-data">${data}</script>
545
+ <script>${SCRIPT}</script>
546
+ </body>
547
+ </html>
548
+ `;
549
+ }
550
+
551
+ // src/core/report/junit.ts
552
+ var GROUPS = [
553
+ "header",
554
+ "cookie",
555
+ "cors",
556
+ "transport",
557
+ "data",
558
+ "disclosure",
559
+ "browser"
560
+ ];
561
+ function xml(text) {
562
+ return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f￾￿]/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
563
+ }
564
+ function body(f, rule) {
565
+ const lines = [
566
+ f.message,
567
+ "",
568
+ `Subject: ${f.subject}${f.discriminator === void 0 ? "" : ` (${f.discriminator})`}`,
569
+ `Severity/confidence: ${f.severity}/${f.confidence} · occurrences: ${f.occurrences} · sources: ${f.sources.join(", ")}`,
570
+ `First seen: ${testLabel(f.firstSeen)}`
571
+ ];
572
+ if (f.evidence.length > 0) {
573
+ lines.push("", "Evidence:");
574
+ for (const e of f.evidence)
575
+ lines.push(` ${e.kind}${e.name === void 0 ? "" : ` ${e.name}`}: ${e.snippet}`);
576
+ }
577
+ if (rule !== void 0) lines.push("", "Fix:", rule.docs.fix);
578
+ lines.push(
579
+ "",
580
+ "Accept in security-baseline.json (review first):",
581
+ JSON.stringify(
582
+ {
583
+ [f.fingerprint]: {
584
+ ruleId: f.ruleId,
585
+ subject: f.subject,
586
+ severity: f.severity,
587
+ status: "accepted",
588
+ note: "",
589
+ addedAt: "YYYY-MM-DD"
590
+ }
591
+ },
592
+ null,
593
+ 2
594
+ )
595
+ );
596
+ return lines.join("\n");
597
+ }
598
+ function buildJunit(report, rules, options) {
599
+ const byId = new Map(rules.map((r) => [r.id, r]));
600
+ const suites = [];
601
+ let total = 0;
602
+ let failures = 0;
603
+ let errors = 0;
604
+ let skipped = 0;
605
+ if (report.outcome.code === 3) {
606
+ const text = report.diagnostics.filter((d) => d.level === "error").map((d) => `${d.code}: ${d.message}`).join("\n");
607
+ suites.push(
608
+ ` <testsuite name="pw-sec" tests="1" failures="0" errors="1" skipped="0" time="0">
609
+ <testcase classname="pw-sec" name="pw-sec" time="0">
610
+ <error type="TOOL_ERROR" message="${xml("the scan could not complete")}">${xml(text)}</error>
611
+ </testcase>
612
+ </testsuite>`
613
+ );
614
+ total += 1;
615
+ errors += 1;
616
+ }
617
+ for (const group of GROUPS) {
618
+ const cases = [];
619
+ let f1 = 0;
620
+ let s1 = 0;
621
+ for (const f of report.findings) {
622
+ if ((ruleManifest(f.ruleId)?.group ?? "browser") !== group) continue;
623
+ const accepted = f.classification === "accepted" || f.classification === "wontfix" || f.classification === "false-positive";
624
+ if (accepted && !options.includeAccepted) continue;
625
+ const name = `${f.subject}${f.discriminator === void 0 ? "" : ` (${f.discriminator})`}`;
626
+ const attrs = `classname="${xml(`pw-sec.${group}.${f.ruleId}`)}" name="${xml(name)}" file="${xml(f.firstSeen.file)}" line="${Math.max(1, f.firstSeen.line)}" time="0"`;
627
+ let child;
628
+ if (f.classification === "new" && f.blocking) {
629
+ child = `<failure type="${xml(f.ruleId)}" message="${xml(`${f.severity}/${f.confidence}: ${f.message}`)}">${xml(body(f, byId.get(f.ruleId)))}</failure>`;
630
+ f1 += 1;
631
+ } else if (f.classification === "expired" && options.failOnExpired) {
632
+ child = `<failure type="baseline-expired" message="${xml(`baseline entry expired on ${f.baseline?.until ?? "?"}: ${f.message}`)}">${xml(body(f, byId.get(f.ruleId)))}</failure>`;
633
+ f1 += 1;
634
+ } else if (accepted) {
635
+ child = `<skipped message="${xml(`baseline: ${f.classification}${f.baseline?.note ? `; ${f.baseline.note}` : ""}`)}"/>`;
636
+ s1 += 1;
637
+ } else {
638
+ child = `<system-out>${xml(body(f, byId.get(f.ruleId)))}</system-out>`;
639
+ }
640
+ cases.push(` <testcase ${attrs}>
641
+ ${child}
642
+ </testcase>`);
643
+ }
644
+ if (cases.length === 0) continue;
645
+ total += cases.length;
646
+ failures += f1;
647
+ skipped += s1;
648
+ suites.push(
649
+ ` <testsuite name="${group}" tests="${cases.length}" failures="${f1}" errors="0" skipped="${s1}" time="0">
650
+ ${cases.join("\n")}
651
+ </testsuite>`
652
+ );
653
+ }
654
+ if (total === 0) {
655
+ suites.push(
656
+ ' <testsuite name="pw-sec" tests="1" failures="0" errors="0" skipped="0" time="0">\n <testcase classname="pw-sec" name="no findings" time="0"/>\n </testsuite>'
657
+ );
658
+ total = 1;
659
+ }
660
+ return `<?xml version="1.0" encoding="UTF-8"?>
661
+ <testsuites name="pw-sec" tests="${total}" failures="${failures}" errors="${errors}" skipped="${skipped}" time="0">
662
+ ${suites.join("\n")}
663
+ </testsuites>
664
+ `;
665
+ }
666
+
667
+ // src/core/report/sarif.ts
668
+ var REPO_URL = "https://github.com/Meser6/playwright-security-scan";
669
+ var SECURITY_SEVERITY = {
670
+ critical: "9.5",
671
+ high: "8.0",
672
+ medium: "5.5",
673
+ low: "3.0",
674
+ info: "0.0"
675
+ };
676
+ var LEVEL = {
677
+ critical: "error",
678
+ high: "error",
679
+ medium: "warning",
680
+ low: "note",
681
+ info: "note"
682
+ };
683
+ function ruleHelpMarkdown(rule) {
684
+ return [
685
+ `**Why.** ${rule.docs.why}`,
686
+ "",
687
+ "**Fix.**",
688
+ "",
689
+ rule.docs.fix,
690
+ "",
691
+ `**False positives.** ${rule.docs.falsePositives}`
692
+ ].join("\n");
693
+ }
694
+ function result(f, ruleIndex) {
695
+ const where = f.location.endpointKey !== void 0 && f.location.endpointKey !== f.subject ? ` (${f.location.endpointKey})` : "";
696
+ const out = {
697
+ ruleId: f.ruleId,
698
+ ruleIndex,
699
+ level: LEVEL[f.severity],
700
+ message: { text: `${f.message} Subject: ${f.subject}${where}.` },
701
+ // The test that first saw the finding is the anchor in the repository (09-REQ-07).
702
+ locations: [
703
+ {
704
+ physicalLocation: {
705
+ artifactLocation: { uri: f.firstSeen.file, uriBaseId: "%SRCROOT%" },
706
+ region: { startLine: Math.max(1, f.firstSeen.line) }
707
+ },
708
+ message: { text: `first seen in: ${f.firstSeen.titlePath.join(" › ")}` }
709
+ }
710
+ ],
711
+ // Stable across runs and line moves (09-REQ-08).
712
+ partialFingerprints: { primaryLocationLineHash: sha256(f.fingerprint) },
713
+ properties: {
714
+ fingerprint: f.fingerprint,
715
+ classification: f.classification,
716
+ severity: f.severity,
717
+ confidence: f.confidence,
718
+ subject: f.subject,
719
+ sources: f.sources,
720
+ occurrences: f.occurrences,
721
+ tests: f.tests.length
722
+ }
723
+ };
724
+ if (f.classification !== "new" && f.classification !== "expired") {
725
+ out.suppressions = [
726
+ { kind: "external", justification: f.baseline?.note ?? `baseline: ${f.classification}` }
727
+ ];
728
+ }
729
+ return out;
730
+ }
731
+ function buildSarif(report, rules, options) {
732
+ const index = new Map(rules.map((r, i) => [r.id, i]));
733
+ const results = report.findings.filter(
734
+ (f) => options.includeAccepted || f.classification === "new" || f.classification === "expired"
735
+ ).map((f) => result(f, index.get(f.ruleId) ?? -1)).filter((r) => r.ruleIndex >= 0);
736
+ return {
737
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
738
+ version: "2.1.0",
739
+ runs: [
740
+ {
741
+ tool: {
742
+ driver: {
743
+ name: "playwright-security-scan",
744
+ version: options.version,
745
+ semanticVersion: options.version,
746
+ informationUri: REPO_URL,
747
+ rules: rules.map((r) => ({
748
+ id: r.id,
749
+ name: r.docs.title.replace(
750
+ /[^A-Za-z0-9]+(.)?/g,
751
+ (_m, c) => (c ?? "").toUpperCase()
752
+ ),
753
+ shortDescription: { text: r.docs.title },
754
+ fullDescription: { text: r.docs.why },
755
+ help: {
756
+ text: `${r.docs.why}
757
+
758
+ ${r.docs.fix}
759
+
760
+ ${r.docs.falsePositives}`,
761
+ markdown: ruleHelpMarkdown(r)
762
+ },
763
+ helpUri: `${REPO_URL}/blob/main/docs/rules/${r.id}.md`,
764
+ defaultConfiguration: { level: LEVEL[r.manifest.defaultSeverity] },
765
+ properties: {
766
+ tags: [
767
+ "security",
768
+ ...r.manifest.cwe.map((n) => `CWE-${n}`),
769
+ ...r.manifest.owasp === void 0 ? [] : [`OWASP-${r.manifest.owasp}`]
770
+ ],
771
+ "security-severity": SECURITY_SEVERITY[r.manifest.defaultSeverity],
772
+ precision: r.manifest.defaultConfidence === "high" ? "high" : r.manifest.defaultConfidence === "medium" ? "medium" : "low"
773
+ }
774
+ }))
775
+ }
776
+ },
777
+ automationDetails: { id: `pw-sec/${report.runId}` },
778
+ results,
779
+ properties: { outcome: report.outcome.name, mode: report.mode }
780
+ }
781
+ ]
782
+ };
783
+ }
784
+
785
+ // src/reporter/sarif-junit.ts
786
+ var writeSarif = (report, config, paths) => {
787
+ if (!config.report.sarif) return null;
788
+ const enabled = BUILT_IN_RULES.filter((r) => config.rules[r.id]?.enabled === true);
789
+ const path = join(paths.reportDir, "results.sarif");
790
+ const log = buildSarif(report, enabled, {
791
+ version: VERSION,
792
+ includeAccepted: config.report.sarifIncludeAccepted
793
+ });
794
+ writeFileSync(path, `${JSON.stringify(log, null, 2)}
795
+ `);
796
+ return path;
797
+ };
798
+ var writeJunit = (report, config, paths) => {
799
+ if (!config.report.junit) return null;
800
+ const path = isAbsolute(config.report.junitPath) ? config.report.junitPath : resolve(paths.configDir, config.report.junitPath);
801
+ mkdirSync(dirname(path), { recursive: true });
802
+ writeFileSync(
803
+ path,
804
+ buildJunit(report, BUILT_IN_RULES, {
805
+ includeAccepted: config.report.junitIncludeAccepted,
806
+ failOnExpired: config.gate.failOnExpired
807
+ })
808
+ );
809
+ return path;
810
+ };
811
+ var writeHtml = (report, config, paths) => {
812
+ if (!config.report.html) return null;
813
+ const enabled = new Set(
814
+ Object.entries(config.rules).filter(([, r]) => r.enabled).map(([id]) => id)
815
+ );
816
+ const path = join(paths.reportDir, "report.html");
817
+ writeFileSync(path, renderHtml(report, BUILT_IN_RULES, enabled));
818
+ return path;
819
+ };
820
+ var REPORT_WRITERS = [
821
+ { name: "html", write: writeHtml },
822
+ { name: "sarif", write: writeSarif },
823
+ { name: "junit", write: writeJunit }
824
+ ];
825
+
826
+ // src/reporter/index.ts
827
+ var MAX_TESTS_WITHOUT_TRAFFIC = 50;
828
+ var today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
829
+ var SecurityReporter = class {
830
+ #write;
831
+ #config;
832
+ #suite;
833
+ #startedAt = /* @__PURE__ */ new Date();
834
+ #findings = [];
835
+ #coverage = emptyCoverage();
836
+ #diagnostics = /* @__PURE__ */ new Map();
837
+ #withoutTraffic = /* @__PURE__ */ new Map();
838
+ #withTraffic = /* @__PURE__ */ new Set();
839
+ constructor(options = {}) {
840
+ this.#write = options.write ?? ((line) => process.stdout.write(`${line}
841
+ `));
842
+ }
843
+ printsToStdio() {
844
+ return false;
845
+ }
846
+ #diag(d) {
847
+ const key = `${d.code}\0${d.message}`;
848
+ if (!this.#diagnostics.has(key)) this.#diagnostics.set(key, d);
849
+ }
850
+ #toolError(where, error2) {
851
+ this.#diag({
852
+ code: "REPORTER_ERROR",
853
+ level: "error",
854
+ message: `reporter: ${where} failed: ${error2 instanceof Error ? error2.message : String(error2)}`
855
+ });
856
+ }
857
+ #settings() {
858
+ const state = getRegistered();
859
+ if (state !== void 0) {
860
+ const scope = [
861
+ ...state.config.scope.includeBaseURL ? state.baseOrigins : [],
862
+ ...state.config.scope.origins
863
+ ];
864
+ return { config: state.config, mode: state.mode, scope: [...new Set(scope)].sort() };
865
+ }
866
+ const fallback = resolveConfig(void 0);
867
+ if (!fallback.ok) throw new Error("the default config is invalid");
868
+ const mode = readMode(process.env);
869
+ return {
870
+ config: fallback.config,
871
+ mode: mode.ok && mode.mode !== null ? mode.mode : "scan",
872
+ scope: []
873
+ };
874
+ }
875
+ #configDir() {
876
+ const config = this.#config;
877
+ if (config?.configFile !== void 0) return dirname(config.configFile);
878
+ return config?.rootDir ?? process.cwd();
879
+ }
880
+ #path(path) {
881
+ return isAbsolute(path) ? path : resolve(this.#configDir(), path);
882
+ }
883
+ onBegin(config, suite) {
884
+ this.#config = config;
885
+ this.#suite = suite;
886
+ this.#startedAt = /* @__PURE__ */ new Date();
887
+ try {
888
+ const { config: sec, mode, scope } = this.#settings();
889
+ const notes = [];
890
+ const state = getRegistered();
891
+ if (state === void 0) {
892
+ this.#diag({
893
+ code: "CONFIG_MISSING",
894
+ level: "error",
895
+ message: 'config: the reporter runs but withSecurity() was not applied to the Playwright config; wrap it with withSecurity() from "playwright-security-scan/config"'
896
+ });
897
+ } else {
898
+ for (const w of state.warnings) {
899
+ this.#diag(w);
900
+ if (w.code !== "SCOPE_EMPTY") notes.push(w);
901
+ }
902
+ }
903
+ if ((process.env.PW_PERF_MODE ?? "") !== "") {
904
+ const w = {
905
+ code: "PERF_MODE_ACTIVE",
906
+ level: "warn",
907
+ message: "PW_PERF_MODE is set too: analysing response bodies adds load to the workers and may distort step timings; run the two scans in separate CI jobs"
908
+ };
909
+ this.#diag(w);
910
+ notes.push(w);
911
+ }
912
+ let entries = null;
913
+ const file = this.#path(sec.baseline.path);
914
+ if (existsSync(file)) {
915
+ try {
916
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
917
+ entries = Object.keys(parsed.findings ?? {}).length;
918
+ } catch {
919
+ entries = 0;
920
+ }
921
+ }
922
+ const reportFile = sec.report.html ? "report.html" : "report.json";
923
+ const banner = formatBanner({
924
+ mode,
925
+ scope,
926
+ enabledRules: enabledRuleCount(sec),
927
+ preset: sec.preset,
928
+ minSeverity: sec.gate.minSeverity,
929
+ minConfidence: sec.gate.minConfidence,
930
+ baselinePath: sec.baseline.path,
931
+ baselineEntries: entries,
932
+ reportPath: `${sec.report.dir.replace(/[\\/]+$/, "")}/${reportFile}`,
933
+ notes
934
+ });
935
+ for (const line of banner) this.#write(line);
936
+ } catch (error2) {
937
+ this.#toolError("the start of the run", error2);
938
+ }
939
+ }
940
+ #ref(test) {
941
+ const root = this.#configDir();
942
+ return {
943
+ testId: test.id,
944
+ titlePath: test.titlePath().slice(3),
945
+ file: relative(root, test.location.file).split("\\").join("/"),
946
+ line: test.location.line,
947
+ project: test.parent.project()?.name ?? ""
948
+ };
949
+ }
950
+ onTestEnd(test, result2) {
951
+ try {
952
+ for (const a of result2.attachments) {
953
+ if (a.name !== ATTACHMENT_NAME) continue;
954
+ const text = a.body !== void 0 ? a.body.toString("utf8") : a.path !== void 0 ? readFileSync(a.path, "utf8") : "";
955
+ let doc;
956
+ try {
957
+ doc = JSON.parse(text);
958
+ } catch {
959
+ this.#diag({
960
+ code: "ATTACHMENT_INVALID",
961
+ level: "warn",
962
+ message: `the findings attachment of "${test.title}" could not be read`,
963
+ testId: test.id
964
+ });
965
+ continue;
966
+ }
967
+ this.#findings.push(...doc.findings);
968
+ addCoverage(this.#coverage, doc.coverage);
969
+ for (const d of doc.diagnostics) this.#diag(d);
970
+ if (doc.coverage.responses > 0) {
971
+ this.#withTraffic.add(test.id);
972
+ this.#withoutTraffic.delete(test.id);
973
+ } else if (!this.#withTraffic.has(test.id)) {
974
+ this.#withoutTraffic.set(test.id, this.#ref(test));
975
+ }
976
+ }
977
+ } catch (error2) {
978
+ this.#toolError(`reading the results of "${test.title}"`, error2);
979
+ }
980
+ }
981
+ onEnd(result2) {
982
+ try {
983
+ return Promise.resolve(this.#finish(result2));
984
+ } catch (error2) {
985
+ this.#write(
986
+ `pw-sec: internal error: ${error2 instanceof Error ? error2.message : String(error2)}`
987
+ );
988
+ return Promise.resolve({ status: "failed" });
989
+ }
990
+ }
991
+ #finish(result2) {
992
+ const { config: sec, mode, scope } = this.#settings();
993
+ const enabled = new Set(
994
+ Object.entries(sec.rules).filter(([, r]) => r.enabled).map(([id]) => id)
995
+ );
996
+ const findings = dedupeRun(this.#findings);
997
+ const coverage = sortCoverage(this.#coverage);
998
+ const date = today();
999
+ const baselinePath = this.#path(sec.baseline.path);
1000
+ let baseline;
1001
+ let baselineOk = true;
1002
+ if (existsSync(baselinePath)) {
1003
+ const parsed = parseBaseline(
1004
+ readFileSync(baselinePath, "utf8"),
1005
+ sec.baseline.path,
1006
+ new Set(RULE_IDS),
1007
+ enabled
1008
+ );
1009
+ for (const d of parsed.diagnostics) this.#diag(d);
1010
+ if (parsed.ok) baseline = parsed.file;
1011
+ else baselineOk = false;
1012
+ }
1013
+ if (mode === "scan" && sec.baseline.requireNote) {
1014
+ for (const d of missingNotes(baseline)) this.#diag(d);
1015
+ }
1016
+ const gate = sec.gate;
1017
+ const classified = classify(findings, baseline, gate, date, mode === "scan");
1018
+ const { resolved, notCovered } = resolveEntries(baseline, findings, coverage, enabled);
1019
+ if (coverage.responses === 0) {
1020
+ this.#diag({
1021
+ code: "NO_TRAFFIC",
1022
+ level: gate.failOnNoTraffic ? "warn" : "info",
1023
+ message: scope.length === 0 ? "no response was in scope: set `use.baseURL` or `scope.origins`" : `no response was in scope (${scope.join(", ")}); check scope.origins and that the tests use the fixtures of withSecurityFixtures()`
1024
+ });
1025
+ }
1026
+ let diff;
1027
+ const partial = isPartialRun(this.#config, this.#suite, process.argv);
1028
+ if (mode === "baseline" && partial) {
1029
+ this.#diag({
1030
+ code: "PARTIAL_RUN",
1031
+ level: "warn",
1032
+ message: "baseline: the run is filtered (grep, shard, project, files or only-changed), so resolved entries are kept (04-REQ-03)"
1033
+ });
1034
+ }
1035
+ if (mode === "baseline" && baselineOk) {
1036
+ const update = updateBaseline(baseline, findings, resolved, {
1037
+ today: date,
1038
+ generatedBy: `playwright-security-scan@${VERSION}`,
1039
+ prune: sec.baseline.pruneResolved && !partial
1040
+ });
1041
+ try {
1042
+ mkdirSync(dirname(baselinePath), { recursive: true });
1043
+ writeFileSync(baselinePath, serializeBaseline(update.file));
1044
+ diff = update.diff;
1045
+ } catch (error2) {
1046
+ this.#toolError(`writing ${sec.baseline.path}`, error2);
1047
+ }
1048
+ }
1049
+ const diagnostics = [...this.#diagnostics.values()];
1050
+ const out = outcome({
1051
+ findings: classified,
1052
+ resolved: resolved.length,
1053
+ diagnostics,
1054
+ testsPassed: result2.status === "passed",
1055
+ responses: coverage.responses,
1056
+ gate
1057
+ });
1058
+ const report = {
1059
+ schemaVersion: 1,
1060
+ runId: process.env[RUN_ID_ENV] ?? getRegistered()?.runId ?? "",
1061
+ startedAt: this.#startedAt.toISOString(),
1062
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1063
+ mode,
1064
+ pkgVersion: VERSION,
1065
+ playwrightVersion: this.#config?.version ?? "",
1066
+ scope: { origins: scope },
1067
+ coverage,
1068
+ findings: [...classified].sort((a, b) => a.fingerprint < b.fingerprint ? -1 : 1),
1069
+ resolved,
1070
+ notCovered,
1071
+ testsWithoutTraffic: [...this.#withoutTraffic.values()].sort(compareTests).slice(0, MAX_TESTS_WITHOUT_TRAFFIC),
1072
+ gate: {
1073
+ minSeverity: gate.minSeverity,
1074
+ minConfidence: gate.minConfidence,
1075
+ failed: out.code === 1 || out.code === 2,
1076
+ blocking: classified.filter((f) => f.blocking).map((f) => f.fingerprint)
1077
+ },
1078
+ diagnostics,
1079
+ outcome: out
1080
+ };
1081
+ const dir = this.#path(sec.report.dir);
1082
+ const shown = (path) => relative(process.cwd(), path) || path;
1083
+ const written = { html: null, json: null };
1084
+ try {
1085
+ mkdirSync(dir, { recursive: true });
1086
+ if (sec.report.json) {
1087
+ writeFileSync(join(dir, "report.json"), `${JSON.stringify(report, null, 2)}
1088
+ `);
1089
+ written.json = shown(join(dir, "report.json"));
1090
+ }
1091
+ writeFileSync(join(dir, "outcome.json"), `${JSON.stringify(out, null, 2)}
1092
+ `);
1093
+ for (const writer of REPORT_WRITERS) {
1094
+ const path = writer.write(report, sec, { reportDir: dir, configDir: this.#configDir() });
1095
+ if (writer.name === "html" && path !== null) written.html = shown(path);
1096
+ }
1097
+ } catch (error2) {
1098
+ this.#write(
1099
+ `pw-sec: could not write the reports: ${error2 instanceof Error ? error2.message : String(error2)}`
1100
+ );
1101
+ }
1102
+ if (diff !== void 0) {
1103
+ for (const line of formatBaselineDiff(sec.baseline.path, diff, partial)) this.#write(line);
1104
+ }
1105
+ for (const line of formatSummary(report, written)) this.#write(line);
1106
+ return out.code === 0 ? void 0 : { status: "failed" };
1107
+ }
1108
+ };
1109
+
1110
+ // src/entries/reporter.ts
1111
+ var reporter_default = SecurityReporter;
1112
+
1113
+ export { SecurityReporter, reporter_default as default };