playwright-security-scan 0.0.0-stage → 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,1554 @@
1
+ // src/core/config/errors.ts
2
+ var PACKAGE_NAME = "playwright-security-scan";
3
+ var ConfigError = class extends Error {
4
+ issues;
5
+ constructor(issues) {
6
+ const count = `${issues.length} ${issues.length === 1 ? "problem" : "problems"}`;
7
+ super(
8
+ [
9
+ `${PACKAGE_NAME}: invalid configuration (${count})`,
10
+ ...issues.flatMap((issue) => [
11
+ ` - ${issue.message}`,
12
+ ...issue.hint === void 0 ? [] : [` ${issue.hint}`]
13
+ ])
14
+ ].join("\n")
15
+ );
16
+ this.name = "ConfigError";
17
+ this.issues = issues;
18
+ }
19
+ };
20
+
21
+ // src/core/config/defaults.ts
22
+ var DEFAULT_BODY_CONTENT_TYPES = [
23
+ "text/html",
24
+ "application/json",
25
+ "*+json",
26
+ "text/javascript",
27
+ "application/javascript",
28
+ "text/plain",
29
+ "application/xml",
30
+ "text/xml"
31
+ ];
32
+ var DEFAULTS = {
33
+ scope: { origins: [], includeBaseURL: true, exclude: [], projects: "all", api: true },
34
+ preset: "recommended",
35
+ limits: {
36
+ maxBodyBytes: 1048576,
37
+ bodyContentTypes: [...DEFAULT_BODY_CONTENT_TYPES],
38
+ maxFindingsPerRule: 200
39
+ },
40
+ browser: { cspEvents: true, storageScan: true },
41
+ gate: {
42
+ minSeverity: "medium",
43
+ minConfidence: "medium",
44
+ failOnExpired: true,
45
+ failOnNoTraffic: true
46
+ },
47
+ baseline: { path: "security-baseline.json", pruneResolved: true, requireNote: false },
48
+ report: {
49
+ dir: "reports/pw-sec",
50
+ html: true,
51
+ json: true,
52
+ sarif: true,
53
+ junit: true,
54
+ junitPath: "reports/pw-sec/junit.xml",
55
+ junitIncludeAccepted: true,
56
+ sarifIncludeAccepted: false
57
+ }
58
+ };
59
+
60
+ // src/core/manifest/rules.ts
61
+ var BOTH = ["browser", "api"];
62
+ var BROWSER = ["browser"];
63
+ var SESSION_NAME_PATTERN = "(sess|sid|auth|token|jwt|login|remember|connect\\.sid|PHPSESSID|JSESSIONID|ASP\\.NET_SessionId|laravel_session)";
64
+ var NON_SESSION_COOKIES = [
65
+ "_ga",
66
+ "_ga_*",
67
+ "_gid",
68
+ "_gat*",
69
+ "_gcl_*",
70
+ "__utm*",
71
+ "_fbp",
72
+ "_fbc",
73
+ "_hj*",
74
+ "_clck",
75
+ "_clsk",
76
+ "ajs_*",
77
+ "mp_*",
78
+ "cf_clearance",
79
+ "__cf_bm",
80
+ "__cfruid",
81
+ "_cfuvid",
82
+ "OptanonConsent",
83
+ "OptanonAlertBoxClosed",
84
+ "CookieConsent",
85
+ "cookieconsent_status"
86
+ ];
87
+ var cookieOptions = {
88
+ sessionNamePattern: SESSION_NAME_PATTERN,
89
+ nonSessionNames: NON_SESSION_COOKIES
90
+ };
91
+ var TOKEN_PARAM_NAMES = [
92
+ "token",
93
+ "access_token",
94
+ "id_token",
95
+ "refresh_token",
96
+ "api_key",
97
+ "apikey",
98
+ "password",
99
+ "passwd",
100
+ "secret",
101
+ "session",
102
+ "sessionid",
103
+ "jwt",
104
+ "auth"
105
+ ];
106
+ var REDIRECT_PARAM_NAMES = [
107
+ "next",
108
+ "url",
109
+ "redirect",
110
+ "redirect_uri",
111
+ "redirect_url",
112
+ "redirectUrl",
113
+ "return",
114
+ "returnUrl",
115
+ "return_url",
116
+ "returnTo",
117
+ "return_to",
118
+ "continue",
119
+ "dest",
120
+ "destination",
121
+ "goto",
122
+ "target"
123
+ ];
124
+ var rule = (id, group, title, defaultSeverity, defaultConfidence, scope, cwe, owasp, sources, options = {}, strictOnly = false) => ({
125
+ id,
126
+ group,
127
+ title,
128
+ defaultSeverity,
129
+ defaultConfidence,
130
+ scope,
131
+ cwe,
132
+ ...owasp === void 0 ? {} : { owasp },
133
+ sources,
134
+ options,
135
+ ...strictOnly ? { strictOnly } : {}
136
+ });
137
+ var RULE_MANIFEST = [
138
+ // 4.1 header.*
139
+ rule(
140
+ "header.csp-missing",
141
+ "header",
142
+ "Content-Security-Policy missing",
143
+ "medium",
144
+ "high",
145
+ "origin",
146
+ [693],
147
+ "A02:2025",
148
+ BROWSER
149
+ ),
150
+ rule(
151
+ "header.csp-unsafe",
152
+ "header",
153
+ "Unsafe Content-Security-Policy",
154
+ "medium",
155
+ "high",
156
+ "origin",
157
+ [693],
158
+ "A02:2025",
159
+ BROWSER
160
+ ),
161
+ rule(
162
+ "header.csp-missing-directives",
163
+ "header",
164
+ "CSP without object-src or base-uri",
165
+ "low",
166
+ "high",
167
+ "origin",
168
+ [693],
169
+ "A02:2025",
170
+ BROWSER
171
+ ),
172
+ rule(
173
+ "header.csp-report-only",
174
+ "header",
175
+ "CSP in report-only mode only",
176
+ "info",
177
+ "high",
178
+ "origin",
179
+ [693],
180
+ void 0,
181
+ BROWSER
182
+ ),
183
+ rule(
184
+ "header.clickjacking",
185
+ "header",
186
+ "No clickjacking protection",
187
+ "medium",
188
+ "medium",
189
+ "origin",
190
+ [1021],
191
+ "A02:2025",
192
+ BROWSER
193
+ ),
194
+ rule(
195
+ "header.hsts-missing",
196
+ "header",
197
+ "Strict-Transport-Security missing",
198
+ "low",
199
+ "high",
200
+ "origin",
201
+ [319],
202
+ "A04:2025",
203
+ BOTH
204
+ ),
205
+ rule(
206
+ "header.hsts-weak",
207
+ "header",
208
+ "Strict-Transport-Security max-age too short",
209
+ "low",
210
+ "high",
211
+ "origin",
212
+ [319],
213
+ "A04:2025",
214
+ BOTH,
215
+ { minMaxAge: 15552e3 }
216
+ ),
217
+ rule(
218
+ "header.xcto-missing",
219
+ "header",
220
+ "X-Content-Type-Options: nosniff missing",
221
+ "low",
222
+ "high",
223
+ "origin",
224
+ [693],
225
+ "A02:2025",
226
+ BOTH
227
+ ),
228
+ rule(
229
+ "header.referrer-policy-unsafe",
230
+ "header",
231
+ "Unsafe Referrer-Policy",
232
+ "low",
233
+ "high",
234
+ "origin",
235
+ [200],
236
+ void 0,
237
+ BROWSER
238
+ ),
239
+ rule(
240
+ "header.content-type-missing",
241
+ "header",
242
+ "Content-Type missing",
243
+ "low",
244
+ "high",
245
+ "endpoint",
246
+ [16],
247
+ "A02:2025",
248
+ BOTH
249
+ ),
250
+ rule(
251
+ "header.permissions-policy-missing",
252
+ "header",
253
+ "Permissions-Policy missing",
254
+ "info",
255
+ "high",
256
+ "origin",
257
+ [693],
258
+ void 0,
259
+ BROWSER,
260
+ {},
261
+ true
262
+ ),
263
+ rule(
264
+ "header.coop-missing",
265
+ "header",
266
+ "Cross-Origin-Opener-Policy missing",
267
+ "info",
268
+ "high",
269
+ "origin",
270
+ [693],
271
+ void 0,
272
+ BROWSER,
273
+ {},
274
+ true
275
+ ),
276
+ // 4.2 cookie.*
277
+ rule(
278
+ "cookie.no-secure",
279
+ "cookie",
280
+ "Session cookie without Secure",
281
+ "medium",
282
+ "high",
283
+ "cookie",
284
+ [614],
285
+ "A04:2025",
286
+ BOTH,
287
+ cookieOptions
288
+ ),
289
+ rule(
290
+ "cookie.no-httponly",
291
+ "cookie",
292
+ "Session cookie without HttpOnly",
293
+ "medium",
294
+ "high",
295
+ "cookie",
296
+ [1004],
297
+ "A02:2025",
298
+ BOTH,
299
+ {
300
+ ...cookieOptions,
301
+ httpOnlyExceptions: ["XSRF-TOKEN", "csrftoken", "csrf_token", "_csrf", "CSRF-TOKEN"]
302
+ }
303
+ ),
304
+ rule(
305
+ "cookie.samesite-none",
306
+ "cookie",
307
+ "Session cookie with SameSite=None",
308
+ "low",
309
+ "medium",
310
+ "cookie",
311
+ [1275],
312
+ "A01:2025",
313
+ BOTH,
314
+ cookieOptions
315
+ ),
316
+ rule(
317
+ "cookie.samesite-missing",
318
+ "cookie",
319
+ "Cookie without SameSite",
320
+ "info",
321
+ "high",
322
+ "cookie",
323
+ [1275],
324
+ void 0,
325
+ BOTH
326
+ ),
327
+ rule(
328
+ "cookie.long-lived-session",
329
+ "cookie",
330
+ "Long-lived session cookie",
331
+ "low",
332
+ "medium",
333
+ "cookie",
334
+ [613],
335
+ "A07:2025",
336
+ BOTH,
337
+ {
338
+ ...cookieOptions,
339
+ maxSessionDays: 30
340
+ }
341
+ ),
342
+ rule(
343
+ "cookie.non-session-insecure",
344
+ "cookie",
345
+ "Cookie without Secure",
346
+ "info",
347
+ "medium",
348
+ "cookie",
349
+ [614],
350
+ void 0,
351
+ BOTH,
352
+ cookieOptions
353
+ ),
354
+ // 4.3 cors.*
355
+ rule(
356
+ "cors.wildcard-credentials",
357
+ "cors",
358
+ "CORS wildcard with credentials",
359
+ "high",
360
+ "high",
361
+ "endpoint",
362
+ [942],
363
+ "A01:2025",
364
+ BOTH
365
+ ),
366
+ rule(
367
+ "cors.reflected-origin-credentials",
368
+ "cors",
369
+ "CORS reflects a foreign origin with credentials",
370
+ "high",
371
+ "medium",
372
+ "endpoint",
373
+ [942],
374
+ "A01:2025",
375
+ BOTH
376
+ ),
377
+ rule(
378
+ "cors.null-origin",
379
+ "cors",
380
+ "CORS allows the null origin",
381
+ "medium",
382
+ "high",
383
+ "endpoint",
384
+ [942],
385
+ "A01:2025",
386
+ BOTH
387
+ ),
388
+ rule(
389
+ "cors.wildcard-sensitive",
390
+ "cors",
391
+ "CORS wildcard on an authenticated endpoint",
392
+ "low",
393
+ "low",
394
+ "endpoint",
395
+ [942],
396
+ void 0,
397
+ BOTH,
398
+ cookieOptions
399
+ ),
400
+ // 4.4 transport.*
401
+ rule(
402
+ "transport.cleartext",
403
+ "transport",
404
+ "Application served over HTTP",
405
+ "medium",
406
+ "high",
407
+ "origin",
408
+ [319],
409
+ "A04:2025",
410
+ BOTH
411
+ ),
412
+ rule(
413
+ "transport.mixed-content",
414
+ "transport",
415
+ "Mixed content",
416
+ "medium",
417
+ "high",
418
+ "asset",
419
+ [311],
420
+ "A04:2025",
421
+ BROWSER
422
+ ),
423
+ rule(
424
+ "transport.form-to-http",
425
+ "transport",
426
+ "Form submits over HTTP",
427
+ "medium",
428
+ "high",
429
+ "endpoint",
430
+ [319],
431
+ "A04:2025",
432
+ BROWSER
433
+ ),
434
+ rule(
435
+ "transport.weak-tls",
436
+ "transport",
437
+ "Outdated TLS version",
438
+ "medium",
439
+ "high",
440
+ "origin",
441
+ [326],
442
+ "A04:2025",
443
+ BROWSER
444
+ ),
445
+ // 4.5 data.*
446
+ rule(
447
+ "data.token-in-url",
448
+ "data",
449
+ "Token in URL",
450
+ "medium",
451
+ "high",
452
+ "endpoint",
453
+ [598],
454
+ "A04:2025",
455
+ BOTH,
456
+ { paramNames: TOKEN_PARAM_NAMES }
457
+ ),
458
+ rule(
459
+ "data.jwt-alg-none",
460
+ "data",
461
+ "JWT with alg none",
462
+ "critical",
463
+ "high",
464
+ "endpoint",
465
+ [347],
466
+ "A04:2025",
467
+ BOTH
468
+ ),
469
+ rule(
470
+ "data.jwt-no-exp",
471
+ "data",
472
+ "JWT without expiry",
473
+ "medium",
474
+ "high",
475
+ "endpoint",
476
+ [613],
477
+ "A07:2025",
478
+ BOTH
479
+ ),
480
+ rule(
481
+ "data.jwt-long-lived",
482
+ "data",
483
+ "Long-lived JWT",
484
+ "low",
485
+ "high",
486
+ "endpoint",
487
+ [613],
488
+ "A07:2025",
489
+ BOTH,
490
+ { maxJwtHours: 24 }
491
+ ),
492
+ rule(
493
+ "data.jwt-sensitive-claims",
494
+ "data",
495
+ "Sensitive data in JWT claims",
496
+ "medium",
497
+ "medium",
498
+ "endpoint",
499
+ [312],
500
+ "A04:2025",
501
+ BOTH
502
+ ),
503
+ rule(
504
+ "data.password-in-response",
505
+ "data",
506
+ "Password or hash in a response",
507
+ "high",
508
+ "medium",
509
+ "endpoint",
510
+ [200],
511
+ "A01:2025",
512
+ BOTH
513
+ ),
514
+ rule(
515
+ "data.secret-in-asset",
516
+ "data",
517
+ "Secret in a script, page or response",
518
+ "high",
519
+ "high",
520
+ "asset",
521
+ [798],
522
+ "A04:2025",
523
+ BOTH,
524
+ {
525
+ patterns: [],
526
+ ignore: ["generic-secret"]
527
+ }
528
+ ),
529
+ rule(
530
+ "data.token-in-storage",
531
+ "data",
532
+ "Token in Web Storage",
533
+ "low",
534
+ "medium",
535
+ "storage-key",
536
+ [922],
537
+ "A04:2025",
538
+ BROWSER
539
+ ),
540
+ // 4.6 disclosure.*
541
+ rule(
542
+ "disclosure.stack-trace",
543
+ "disclosure",
544
+ "Stack trace in a response",
545
+ "medium",
546
+ "high",
547
+ "endpoint",
548
+ [209],
549
+ "A10:2025",
550
+ BOTH
551
+ ),
552
+ rule(
553
+ "disclosure.sql-error",
554
+ "disclosure",
555
+ "SQL error in a response",
556
+ "high",
557
+ "medium",
558
+ "endpoint",
559
+ [209, 89],
560
+ "A05:2025",
561
+ BOTH
562
+ ),
563
+ rule(
564
+ "disclosure.server-version",
565
+ "disclosure",
566
+ "Server version disclosed",
567
+ "low",
568
+ "high",
569
+ "origin",
570
+ [200],
571
+ "A02:2025",
572
+ BOTH
573
+ ),
574
+ rule(
575
+ "disclosure.debug-mode",
576
+ "disclosure",
577
+ "Debug page exposed",
578
+ "medium",
579
+ "medium",
580
+ "endpoint",
581
+ [489],
582
+ "A02:2025",
583
+ BOTH
584
+ ),
585
+ rule(
586
+ "disclosure.private-ip",
587
+ "disclosure",
588
+ "Private IP address disclosed",
589
+ "low",
590
+ "medium",
591
+ "endpoint",
592
+ [200],
593
+ void 0,
594
+ BOTH
595
+ ),
596
+ rule(
597
+ "disclosure.directory-listing",
598
+ "disclosure",
599
+ "Directory listing",
600
+ "low",
601
+ "high",
602
+ "endpoint",
603
+ [548],
604
+ "A02:2025",
605
+ BOTH
606
+ ),
607
+ rule(
608
+ "disclosure.source-map",
609
+ "disclosure",
610
+ "Source map exposed",
611
+ "info",
612
+ "high",
613
+ "asset",
614
+ [540],
615
+ void 0,
616
+ BROWSER
617
+ ),
618
+ rule(
619
+ "disclosure.server-error",
620
+ "disclosure",
621
+ "Server error during tests",
622
+ "info",
623
+ "high",
624
+ "endpoint",
625
+ [755],
626
+ "A10:2025",
627
+ BOTH
628
+ ),
629
+ // 4.7 browser.*, asset.*
630
+ rule(
631
+ "browser.csp-violation",
632
+ "browser",
633
+ "CSP violation in the browser",
634
+ "info",
635
+ "high",
636
+ "origin",
637
+ [693],
638
+ void 0,
639
+ BROWSER
640
+ ),
641
+ rule(
642
+ "asset.sri-missing",
643
+ "browser",
644
+ "Third-party script or style without SRI",
645
+ "low",
646
+ "high",
647
+ "asset",
648
+ [353],
649
+ "A08:2025",
650
+ BROWSER
651
+ ),
652
+ rule(
653
+ "browser.open-redirect-candidate",
654
+ "browser",
655
+ "Open redirect candidate",
656
+ "medium",
657
+ "medium",
658
+ "endpoint",
659
+ [601],
660
+ "A01:2025",
661
+ BOTH,
662
+ {
663
+ paramNames: REDIRECT_PARAM_NAMES
664
+ }
665
+ ),
666
+ rule(
667
+ "browser.reflected-param",
668
+ "browser",
669
+ "Query parameter reflected in HTML",
670
+ "info",
671
+ "low",
672
+ "endpoint",
673
+ [79],
674
+ "A05:2025",
675
+ BROWSER,
676
+ {
677
+ minLength: 6
678
+ }
679
+ )
680
+ ];
681
+ var RULE_IDS = RULE_MANIFEST.map((r) => r.id);
682
+ var BY_ID = new Map(RULE_MANIFEST.map((r) => [r.id, r]));
683
+ function ruleManifest(id) {
684
+ return BY_ID.get(id);
685
+ }
686
+
687
+ // src/core/normalize/constants.ts
688
+ var MAX_KEY_LENGTH = 2e3;
689
+
690
+ // src/core/normalize/config.ts
691
+ var NORMALIZATION_DEFAULTS = Object.freeze({
692
+ origins: {},
693
+ idPatterns: {
694
+ number: true,
695
+ uuid: true,
696
+ hex: true,
697
+ token: true,
698
+ mixed: true,
699
+ prefixed: true,
700
+ email: true
701
+ },
702
+ extraIdPatterns: [],
703
+ query: "names",
704
+ keepQueryValues: [],
705
+ dropQueryParams: []
706
+ });
707
+ function compilePattern(pattern) {
708
+ if (typeof pattern === "string") return pattern;
709
+ if (pattern instanceof RegExp)
710
+ return new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""));
711
+ return new RegExp(pattern.regex, (pattern.flags ?? "").replace(/[gy]/g, ""));
712
+ }
713
+ function resolveNormalization(input = {}) {
714
+ const config = {
715
+ origins: { ...input.origins ?? {} },
716
+ idPatterns: { ...NORMALIZATION_DEFAULTS.idPatterns, ...input.idPatterns ?? {} },
717
+ extraIdPatterns: (input.extraIdPatterns ?? []).map(compilePattern),
718
+ query: input.query ?? "names",
719
+ keepQueryValues: [...input.keepQueryValues ?? []],
720
+ dropQueryParams: [...input.dropQueryParams ?? []]
721
+ };
722
+ if (input.keyBuilder !== void 0) config.keyBuilder = input.keyBuilder;
723
+ return config;
724
+ }
725
+
726
+ // src/core/hash/index.ts
727
+ var FIXED_HASH_SEED = 0;
728
+ function hash53(input, seed) {
729
+ let h1 = 3735928559 ^ seed;
730
+ let h2 = 1103547991 ^ seed;
731
+ for (let i = 0; i < input.length; i++) {
732
+ const ch = input.charCodeAt(i);
733
+ h1 = Math.imul(h1 ^ ch, 2654435761);
734
+ h2 = Math.imul(h2 ^ ch, 1597334677);
735
+ }
736
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
737
+ h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
738
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
739
+ h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
740
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
741
+ }
742
+ function hashHex(input) {
743
+ return hash53(input, FIXED_HASH_SEED).toString(16).padStart(14, "0");
744
+ }
745
+ var K = new Uint32Array([
746
+ 1116352408,
747
+ 1899447441,
748
+ 3049323471,
749
+ 3921009573,
750
+ 961987163,
751
+ 1508970993,
752
+ 2453635748,
753
+ 2870763221,
754
+ 3624381080,
755
+ 310598401,
756
+ 607225278,
757
+ 1426881987,
758
+ 1925078388,
759
+ 2162078206,
760
+ 2614888103,
761
+ 3248222580,
762
+ 3835390401,
763
+ 4022224774,
764
+ 264347078,
765
+ 604807628,
766
+ 770255983,
767
+ 1249150122,
768
+ 1555081692,
769
+ 1996064986,
770
+ 2554220882,
771
+ 2821834349,
772
+ 2952996808,
773
+ 3210313671,
774
+ 3336571891,
775
+ 3584528711,
776
+ 113926993,
777
+ 338241895,
778
+ 666307205,
779
+ 773529912,
780
+ 1294757372,
781
+ 1396182291,
782
+ 1695183700,
783
+ 1986661051,
784
+ 2177026350,
785
+ 2456956037,
786
+ 2730485921,
787
+ 2820302411,
788
+ 3259730800,
789
+ 3345764771,
790
+ 3516065817,
791
+ 3600352804,
792
+ 4094571909,
793
+ 275423344,
794
+ 430227734,
795
+ 506948616,
796
+ 659060556,
797
+ 883997877,
798
+ 958139571,
799
+ 1322822218,
800
+ 1537002063,
801
+ 1747873779,
802
+ 1955562222,
803
+ 2024104815,
804
+ 2227730452,
805
+ 2361852424,
806
+ 2428436474,
807
+ 2756734187,
808
+ 3204031479,
809
+ 3329325298
810
+ ]);
811
+ var rotr = (x, n) => x >>> n | x << 32 - n;
812
+ function sha256Bytes(bytes) {
813
+ const bitLength = bytes.length * 8;
814
+ const padded = new Uint8Array(bytes.length + 9 + 63 >> 6 << 6);
815
+ padded.set(bytes);
816
+ padded[bytes.length] = 128;
817
+ const view = new DataView(padded.buffer);
818
+ view.setUint32(padded.length - 8, Math.floor(bitLength / 4294967296));
819
+ view.setUint32(padded.length - 4, bitLength >>> 0);
820
+ const h = new Uint32Array([
821
+ 1779033703,
822
+ 3144134277,
823
+ 1013904242,
824
+ 2773480762,
825
+ 1359893119,
826
+ 2600822924,
827
+ 528734635,
828
+ 1541459225
829
+ ]);
830
+ const w = new Uint32Array(64);
831
+ for (let offset = 0; offset < padded.length; offset += 64) {
832
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);
833
+ for (let i = 16; i < 64; i++) {
834
+ const a2 = w[i - 15];
835
+ const b2 = w[i - 2];
836
+ const s0 = rotr(a2, 7) ^ rotr(a2, 18) ^ a2 >>> 3;
837
+ const s1 = rotr(b2, 17) ^ rotr(b2, 19) ^ b2 >>> 10;
838
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
839
+ }
840
+ let [a, b, c, d, e, f, g, hh] = h;
841
+ for (let i = 0; i < 64; i++) {
842
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
843
+ const ch = e & f ^ ~e & g;
844
+ const t1 = hh + s1 + ch + K[i] + w[i] >>> 0;
845
+ const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
846
+ const maj = a & b ^ a & c ^ b & c;
847
+ const t2 = s0 + maj >>> 0;
848
+ hh = g;
849
+ g = f;
850
+ f = e;
851
+ e = d + t1 >>> 0;
852
+ d = c;
853
+ c = b;
854
+ b = a;
855
+ a = t1 + t2 >>> 0;
856
+ }
857
+ h[0] = h[0] + a >>> 0;
858
+ h[1] = h[1] + b >>> 0;
859
+ h[2] = h[2] + c >>> 0;
860
+ h[3] = h[3] + d >>> 0;
861
+ h[4] = h[4] + e >>> 0;
862
+ h[5] = h[5] + f >>> 0;
863
+ h[6] = h[6] + g >>> 0;
864
+ h[7] = h[7] + hh >>> 0;
865
+ }
866
+ return [...h].map((x) => x.toString(16).padStart(8, "0")).join("");
867
+ }
868
+ var encoder = new TextEncoder();
869
+ function sha256(text) {
870
+ return sha256Bytes(encoder.encode(text));
871
+ }
872
+
873
+ // src/core/normalize/host-patterns.ts
874
+ var FORM = /^([A-Za-z]+):\/\/([^/?#@:]+)(?::([0-9]+))?\/?$/u;
875
+ var LABEL = /^[a-z0-9*-]+$/u;
876
+ var DEFAULT_PORT = { http: "80", https: "443" };
877
+ function isHostPattern(key) {
878
+ return key.includes("*");
879
+ }
880
+ function parseHostPattern(text, label) {
881
+ const match = FORM.exec(text);
882
+ if (match === null) {
883
+ return "a host pattern must have the form <scheme>://<host>[:<port>], without a path, query, fragment or credentials";
884
+ }
885
+ const scheme = (match[1] ?? "").toLowerCase();
886
+ if (scheme !== "http" && scheme !== "https")
887
+ return "the scheme of a host pattern must be http or https";
888
+ const host = (match[2] ?? "").toLowerCase();
889
+ const labels = host.split(".");
890
+ if (labels.length < 2) return "a host pattern needs at least two host labels, e.g. *.example.com";
891
+ for (const part of labels) {
892
+ if (part === "" || !LABEL.test(part)) {
893
+ return 'host labels may contain only letters, digits, "-" and "*" (international names in their xn-- form)';
894
+ }
895
+ if (part.split("*").length > 2) return 'a host label may contain at most one "*"';
896
+ }
897
+ if ((labels.at(-1) ?? "").includes("*"))
898
+ return 'the last host label (the top-level domain) cannot contain "*"';
899
+ if (labels.every((part) => part.includes("*"))) {
900
+ return 'at least one host label must be without "*", or the pattern would match every host';
901
+ }
902
+ let port = match[3] ?? "";
903
+ if (port !== "") {
904
+ const n = Number(port);
905
+ if (!Number.isInteger(n) || n < 1 || n > 65535)
906
+ return "the port must be a number from 1 to 65535";
907
+ port = String(n);
908
+ if (port === DEFAULT_PORT[scheme]) port = "";
909
+ }
910
+ return {
911
+ scheme,
912
+ labels,
913
+ port,
914
+ canonical: `${scheme}://${host}${port === "" ? "" : `:${port}`}`,
915
+ label
916
+ };
917
+ }
918
+ function labelMatches(pattern, label) {
919
+ const star = pattern.indexOf("*");
920
+ if (star < 0) return pattern === label;
921
+ const before = pattern.slice(0, star);
922
+ const after = pattern.slice(star + 1);
923
+ return label.length > before.length + after.length && label.startsWith(before) && label.endsWith(after);
924
+ }
925
+ function patternMatches(pattern, url) {
926
+ if (url.protocol !== `${pattern.scheme}:`) return false;
927
+ if (url.port !== pattern.port) return false;
928
+ if (url.hostname.startsWith("[")) return false;
929
+ const labels = url.hostname.toLowerCase().split(".");
930
+ if (labels.length !== pattern.labels.length) return false;
931
+ return pattern.labels.every((part, i) => labelMatches(part, labels[i] ?? ""));
932
+ }
933
+ function literal(pattern) {
934
+ return pattern.labels.join(".").replaceAll("*", "").length;
935
+ }
936
+ function stars(pattern) {
937
+ return pattern.labels.filter((part) => part.includes("*")).length;
938
+ }
939
+ function sortPatterns(patterns) {
940
+ return [...patterns].sort(
941
+ (a, b) => literal(b) - literal(a) || stars(a) - stars(b) || (a.canonical < b.canonical ? -1 : a.canonical > b.canonical ? 1 : 0)
942
+ );
943
+ }
944
+ function compileHostPatterns(origins) {
945
+ const out = [];
946
+ for (const [key, label] of Object.entries(origins)) {
947
+ if (!isHostPattern(key)) continue;
948
+ const parsed = parseHostPattern(key, label);
949
+ if (typeof parsed !== "string") out.push(parsed);
950
+ }
951
+ return sortPatterns(out);
952
+ }
953
+ function matchingPattern(patterns, url) {
954
+ return patterns.find((p) => patternMatches(p, url)) ?? null;
955
+ }
956
+
957
+ // src/core/normalize/patterns.ts
958
+ var ID_PATTERNS = {
959
+ number: /^[0-9]+$/,
960
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
961
+ hex: /^[0-9a-f]{16,}$/i,
962
+ token: /^(?=[^0-9]*[0-9])(?:[A-Za-z0-9~=]{24,}|(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])[A-Za-z0-9_.~=-]{24,})$/,
963
+ mixed: /^(?=[^0-9]*[0-9])(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])[A-Za-z0-9_-]{16,}$/,
964
+ prefixed: /^(?:[A-Z]{2,5}-[0-9]{3,}|[a-z]{1,8}_(?:[0-9]{2,32}|(?=[A-Za-z]*[0-9])[A-Za-z0-9]{8,32}))$/,
965
+ email: /^[^@\s/]+@[^@\s/]+\.[^@\s/]+$/
966
+ };
967
+ function compileIdMatcher(keys) {
968
+ const email = keys.idPatterns.email ? ID_PATTERNS.email : void 0;
969
+ const ids = [];
970
+ for (const name of ["number", "uuid", "hex", "token", "mixed", "prefixed"]) {
971
+ if (keys.idPatterns[name]) {
972
+ const re = ID_PATTERNS[name];
973
+ ids.push((text) => re.test(text));
974
+ }
975
+ }
976
+ for (const pattern of keys.extraIdPatterns) {
977
+ if (typeof pattern === "string") {
978
+ ids.push((text) => text === pattern);
979
+ } else {
980
+ const re = new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""));
981
+ ids.push((text) => re.test(text));
982
+ }
983
+ }
984
+ return (text) => {
985
+ if (email?.test(text) === true) return ":email";
986
+ return ids.some((test) => test(text)) ? ":id" : null;
987
+ };
988
+ }
989
+
990
+ // src/core/normalize/key-builder.ts
991
+ var HINT_EXTEND = "Use keys.extraIdPatterns or keys.keyBuilder for ids in other formats.";
992
+ function parseHttpUrl(text) {
993
+ if (!URL.canParse(text)) return null;
994
+ const url = new URL(text);
995
+ return url.protocol === "http:" || url.protocol === "https:" ? url : null;
996
+ }
997
+ function canonicalOrigin(text) {
998
+ return parseHttpUrl(text)?.origin ?? null;
999
+ }
1000
+ function canonicalOrigins(origins) {
1001
+ const set = /* @__PURE__ */ new Set();
1002
+ for (const origin of origins) {
1003
+ const canonical = canonicalOrigin(origin);
1004
+ if (canonical !== null) set.add(canonical);
1005
+ }
1006
+ return [...set].sort();
1007
+ }
1008
+ var SEGMENT_ESCAPE = /[%/?#& \u0000-\u001f\u007f-\u009f]/g;
1009
+ var NAME_ESCAPE = /[%&=# \u0000-\u001f\u007f-\u009f]/g;
1010
+ var VALUE_ESCAPE = /[%&=#, \u0000-\u001f\u007f-\u009f]/g;
1011
+ var escape = (text, chars) => text.replace(chars, encodeURIComponent);
1012
+ function normalizePath(pathname, matchId) {
1013
+ const segments = [];
1014
+ for (const raw of pathname.split("/")) {
1015
+ const segment = raw.split(";", 1)[0] ?? "";
1016
+ if (segment === "") continue;
1017
+ let decoded;
1018
+ try {
1019
+ decoded = decodeURIComponent(segment);
1020
+ } catch {
1021
+ segments.push(segment);
1022
+ continue;
1023
+ }
1024
+ segments.push(matchId(decoded) ?? escape(decoded, SEGMENT_ESCAPE));
1025
+ }
1026
+ return `/${segments.join("/")}`;
1027
+ }
1028
+ function normalizeQuery(params, keys, matchId) {
1029
+ const drop = new Set(keys.dropQueryParams);
1030
+ const keep = new Set(keys.keepQueryValues);
1031
+ const names = /* @__PURE__ */ new Map();
1032
+ for (const [rawName, value] of params) {
1033
+ const name = rawName.replace(/\[[0-9]+\]/g, "[]");
1034
+ if (name === "" || drop.has(name) || matchId(name) !== null) continue;
1035
+ const encoded = escape(name, NAME_ESCAPE);
1036
+ if (!keep.has(name)) {
1037
+ if (!names.has(encoded)) names.set(encoded, null);
1038
+ continue;
1039
+ }
1040
+ const values = names.get(encoded) ?? /* @__PURE__ */ new Set();
1041
+ values.add(matchId(value) ?? escape(value, VALUE_ESCAPE));
1042
+ names.set(encoded, values);
1043
+ }
1044
+ return [...names.keys()].sort().map((name) => {
1045
+ const values = names.get(name);
1046
+ return values ? `${name}=${[...values].sort().join(",")}` : name;
1047
+ }).join("&");
1048
+ }
1049
+ function truncateKey(key) {
1050
+ if (key.length <= MAX_KEY_LENGTH) return key;
1051
+ const suffix = `…~${hashHex(key)}`;
1052
+ let cut = MAX_KEY_LENGTH - suffix.length;
1053
+ const before = key.charCodeAt(cut - 1);
1054
+ const after = key.charCodeAt(cut);
1055
+ if (before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343) cut -= 1;
1056
+ return key.slice(0, cut) + suffix;
1057
+ }
1058
+ function originLabels(origins, baseOrigins) {
1059
+ const exact = /* @__PURE__ */ new Map();
1060
+ for (const [origin, label] of Object.entries(origins)) {
1061
+ if (isHostPattern(origin)) continue;
1062
+ const canonical = canonicalOrigin(origin);
1063
+ if (canonical !== null) exact.set(canonical, label);
1064
+ }
1065
+ const patterns = compileHostPatterns(origins);
1066
+ const base = new Set(canonicalOrigins(baseOrigins));
1067
+ const memo = /* @__PURE__ */ new Map();
1068
+ return (url) => {
1069
+ const known = memo.get(url.origin);
1070
+ if (known !== void 0) return known;
1071
+ const label = exact.get(url.origin) ?? matchingPattern(patterns, url)?.label ?? (base.has(url.origin) ? "" : null);
1072
+ memo.set(url.origin, label);
1073
+ return label;
1074
+ };
1075
+ }
1076
+ function createKeyBuilder(cfg, ctx) {
1077
+ const matchId = compileIdMatcher(cfg);
1078
+ const labelOf = originLabels(cfg.origins, ctx.baseOrigins);
1079
+ const keyBuilder = cfg.keyBuilder;
1080
+ return (sample) => {
1081
+ const method = sample.method.toUpperCase();
1082
+ const url = parseHttpUrl(sample.url);
1083
+ const issues = [];
1084
+ let key;
1085
+ if (keyBuilder !== void 0) {
1086
+ let built;
1087
+ try {
1088
+ built = keyBuilder({ method, url: sample.url, resourceType: sample.resourceType });
1089
+ } catch (error) {
1090
+ issues.push({
1091
+ code: "NORMALIZE_KEY_BUILDER_THREW",
1092
+ message: `keys.keyBuilder threw an exception: ${error instanceof Error ? error.message : String(error)}. The built-in normalization was used instead.`,
1093
+ hint: "Fix the keyBuilder function; it must not throw."
1094
+ });
1095
+ built = void 0;
1096
+ }
1097
+ if (typeof built === "string" && built.trim() !== "") {
1098
+ key = built;
1099
+ } else if (built !== void 0) {
1100
+ issues.push({
1101
+ code: "NORMALIZE_KEY_BUILDER_INVALID",
1102
+ message: "keys.keyBuilder returned a value that is neither a non-empty string nor undefined. The built-in normalization was used instead.",
1103
+ hint: "Return the whole key as a non-empty string, or undefined for the built-in normalization."
1104
+ });
1105
+ }
1106
+ }
1107
+ if (key === void 0) {
1108
+ if (url === null) {
1109
+ issues.push({
1110
+ code: "NORMALIZE_UNSUPPORTED_URL",
1111
+ message: "A request URL could not be parsed or does not use http/https; the sample was skipped."
1112
+ });
1113
+ return { ok: false, issues };
1114
+ }
1115
+ const label = labelOf(url) ?? url.host;
1116
+ const query = cfg.query === "names" ? normalizeQuery(url.searchParams, cfg, matchId) : "";
1117
+ key = `${method} ${label}${normalizePath(url.pathname, matchId)}${query === "" ? "" : `?${query}`}`;
1118
+ }
1119
+ const truncated = truncateKey(key);
1120
+ if (truncated !== key) {
1121
+ issues.push({
1122
+ code: "NORMALIZE_KEY_TRUNCATED",
1123
+ message: `An endpoint key longer than ${MAX_KEY_LENGTH} characters was truncated and suffixed with its hash.`,
1124
+ hint: HINT_EXTEND
1125
+ });
1126
+ }
1127
+ return {
1128
+ ok: true,
1129
+ key: truncated,
1130
+ origin: url?.origin ?? null,
1131
+ label: url === null ? null : labelOf(url) ?? url.host,
1132
+ issues
1133
+ };
1134
+ };
1135
+ }
1136
+
1137
+ // src/core/types/index.ts
1138
+ var SEVERITIES = ["info", "low", "medium", "high", "critical"];
1139
+ var CONFIDENCES = ["low", "medium", "high"];
1140
+ var severityRank = (s) => SEVERITIES.indexOf(s);
1141
+ var confidenceRank = (c) => CONFIDENCES.indexOf(c);
1142
+
1143
+ // src/core/config/validate.ts
1144
+ var PRESETS = ["recommended", "strict", "minimal"];
1145
+ var MAX_SUGGESTION_DISTANCE = 3;
1146
+ function editDistance(a, b) {
1147
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
1148
+ for (let i = 1; i <= a.length; i++) {
1149
+ let previous = row[0] ?? 0;
1150
+ row[0] = i;
1151
+ for (let j = 1; j <= b.length; j++) {
1152
+ const current = row[j] ?? 0;
1153
+ row[j] = Math.min(
1154
+ (row[j] ?? 0) + 1,
1155
+ (row[j - 1] ?? 0) + 1,
1156
+ previous + (a[i - 1] === b[j - 1] ? 0 : 1)
1157
+ );
1158
+ previous = current;
1159
+ }
1160
+ }
1161
+ return row[b.length] ?? 0;
1162
+ }
1163
+ function closest(name, candidates) {
1164
+ let best;
1165
+ for (const candidate of candidates) {
1166
+ const distance = editDistance(name.toLowerCase(), candidate.toLowerCase());
1167
+ if (distance <= MAX_SUGGESTION_DISTANCE && (best === void 0 || distance < best.distance)) {
1168
+ best = { name: candidate, distance };
1169
+ }
1170
+ }
1171
+ return best?.name;
1172
+ }
1173
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1174
+ var show = (v) => {
1175
+ if (v instanceof RegExp) return String(v);
1176
+ if (typeof v === "function") return "a function";
1177
+ try {
1178
+ return JSON.stringify(v) ?? String(v);
1179
+ } catch {
1180
+ return String(v);
1181
+ }
1182
+ };
1183
+ var Collector = class {
1184
+ issues = [];
1185
+ add(code, path, message, hint) {
1186
+ this.issues.push({
1187
+ code,
1188
+ path,
1189
+ message: `${path === "" ? "config" : path}: ${message}`,
1190
+ ...hint === void 0 ? {} : { hint }
1191
+ });
1192
+ }
1193
+ unknown(path, key, known) {
1194
+ const suggestion = closest(key, known);
1195
+ const full = path === "" ? key : `${path}.${key}`;
1196
+ this.add(
1197
+ "CONFIG_UNKNOWN_OPTION",
1198
+ full,
1199
+ suggestion === void 0 ? "unknown option" : `unknown option. Did you mean "${suggestion}"?`,
1200
+ `Allowed here: ${known.join(", ")}.`
1201
+ );
1202
+ }
1203
+ type(path, value, expected) {
1204
+ this.add("CONFIG_INVALID_TYPE", path, `expected ${expected}, got ${show(value)}`);
1205
+ }
1206
+ oneOf(path, value, allowed) {
1207
+ this.add(
1208
+ "CONFIG_INVALID_VALUE",
1209
+ path,
1210
+ `invalid value ${show(value)}`,
1211
+ `Allowed values: ${allowed.map((a) => show(a)).join(", ")}.`
1212
+ );
1213
+ }
1214
+ };
1215
+ var bool = (c, p, v) => {
1216
+ if (typeof v !== "boolean") c.type(p, v, "true or false");
1217
+ };
1218
+ var positiveInt = (c, p, v) => {
1219
+ if (typeof v !== "number" || !Number.isInteger(v) || v <= 0) c.type(p, v, "a positive integer");
1220
+ };
1221
+ var nonEmptyString = (c, p, v) => {
1222
+ if (typeof v !== "string" || v.trim() === "") c.type(p, v, "a non-empty string");
1223
+ };
1224
+ var stringList = (c, p, v) => {
1225
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string" || x === "")) {
1226
+ c.type(p, v, "an array of non-empty strings");
1227
+ }
1228
+ };
1229
+ var enumOf = (allowed) => (c, p, v) => {
1230
+ if (typeof v !== "string" || !allowed.includes(v)) c.oneOf(p, v, allowed);
1231
+ };
1232
+ var originList = (c, p, v) => {
1233
+ if (!Array.isArray(v)) {
1234
+ c.type(p, v, "an array of origins");
1235
+ return;
1236
+ }
1237
+ v.forEach((item, i) => {
1238
+ const path = `${p}[${i}]`;
1239
+ if (typeof item !== "string") {
1240
+ c.type(path, item, 'an origin such as "https://api.example.com"');
1241
+ return;
1242
+ }
1243
+ const valid = item.includes("*") ? typeof parseHostPattern(item, "") !== "string" : canonicalOrigin(item) !== null;
1244
+ if (!valid) {
1245
+ c.add(
1246
+ "CONFIG_INVALID_VALUE",
1247
+ path,
1248
+ `${show(item)} is not an origin`,
1249
+ 'Use scheme://host[:port], e.g. "https://api.example.com" or "https://*.example.com".'
1250
+ );
1251
+ }
1252
+ });
1253
+ };
1254
+ function section(c, path, value, fields) {
1255
+ if (value === void 0) return;
1256
+ if (!isRecord(value)) {
1257
+ c.type(path, value, "an object");
1258
+ return;
1259
+ }
1260
+ const known = Object.keys(fields);
1261
+ for (const [key, v] of Object.entries(value)) {
1262
+ const check = fields[key];
1263
+ if (check === void 0) c.unknown(path, key, known);
1264
+ else if (v !== void 0) check(c, `${path}.${key}`, v);
1265
+ }
1266
+ }
1267
+ var sameKind = (a, b) => Array.isArray(a) ? Array.isArray(b) : typeof a === typeof b && !Array.isArray(b);
1268
+ function ruleSetting(c, path, id, value) {
1269
+ if (value === "off" || value === "on") return;
1270
+ if (!isRecord(value)) {
1271
+ c.type(path, value, '"off", "on" or { severity?, confidence?, options? }');
1272
+ return;
1273
+ }
1274
+ section(c, path, value, {
1275
+ severity: enumOf(SEVERITIES),
1276
+ confidence: enumOf(CONFIDENCES),
1277
+ options: (cc, p, options) => {
1278
+ if (!isRecord(options)) {
1279
+ cc.type(p, options, "an object");
1280
+ return;
1281
+ }
1282
+ const defaults = ruleManifest(id)?.options ?? {};
1283
+ const known = Object.keys(defaults);
1284
+ for (const [key, v] of Object.entries(options)) {
1285
+ if (!(key in defaults)) {
1286
+ if (known.length === 0) {
1287
+ cc.add("CONFIG_UNKNOWN_OPTION", `${p}.${key}`, `rule ${id} has no options`);
1288
+ } else cc.unknown(p, key, known);
1289
+ } else if (!sameKind(defaults[key], v)) {
1290
+ const expected = Array.isArray(defaults[key]) ? "an array" : `a ${typeof defaults[key]}`;
1291
+ cc.type(`${p}.${key}`, v, expected);
1292
+ }
1293
+ }
1294
+ }
1295
+ });
1296
+ }
1297
+ function rules(c, value) {
1298
+ if (value === void 0) return;
1299
+ if (!isRecord(value)) {
1300
+ c.type("rules", value, "an object");
1301
+ return;
1302
+ }
1303
+ for (const [key, v] of Object.entries(value)) {
1304
+ if (key === "preset") {
1305
+ enumOf(PRESETS)(c, "rules.preset", v);
1306
+ continue;
1307
+ }
1308
+ if (!RULE_IDS.includes(key)) {
1309
+ const suggestion = closest(key, RULE_IDS);
1310
+ c.add(
1311
+ "CONFIG_UNKNOWN_RULE",
1312
+ `rules.${key}`,
1313
+ suggestion === void 0 ? "unknown rule id" : `unknown rule id. Did you mean "${suggestion}"?`,
1314
+ "Rule ids are listed in the README (rules table) and in docs/rules/."
1315
+ );
1316
+ continue;
1317
+ }
1318
+ if (v !== void 0) ruleSetting(c, `rules.${key}`, key, v);
1319
+ }
1320
+ }
1321
+ function normalization(c, value) {
1322
+ section(c, "normalization", value, {
1323
+ origins: (cc, p, v) => {
1324
+ if (!isRecord(v) || Object.values(v).some((x) => typeof x !== "string")) {
1325
+ cc.type(p, v, "an object of origin → label");
1326
+ }
1327
+ },
1328
+ idPatterns: (cc, p, v) => section(cc, p, v, {
1329
+ number: bool,
1330
+ uuid: bool,
1331
+ hex: bool,
1332
+ token: bool,
1333
+ mixed: bool,
1334
+ prefixed: bool,
1335
+ email: bool
1336
+ }),
1337
+ extraIdPatterns: (cc, p, v) => {
1338
+ if (!Array.isArray(v)) {
1339
+ cc.type(p, v, "an array of strings and regexes");
1340
+ return;
1341
+ }
1342
+ v.forEach((item, i) => {
1343
+ if (typeof item === "string" || item instanceof RegExp) return;
1344
+ if (isRecord(item) && typeof item.regex === "string") {
1345
+ try {
1346
+ new RegExp(item.regex, typeof item.flags === "string" ? item.flags : "");
1347
+ } catch (error) {
1348
+ cc.add("CONFIG_INVALID_REGEX", `${p}[${i}]`, String(error));
1349
+ }
1350
+ return;
1351
+ }
1352
+ cc.type(`${p}[${i}]`, item, "a string, a RegExp or { regex, flags }");
1353
+ });
1354
+ },
1355
+ query: enumOf(["names", "ignore"]),
1356
+ keepQueryValues: stringList,
1357
+ dropQueryParams: stringList,
1358
+ keyBuilder: (cc, p, v) => {
1359
+ if (typeof v !== "function") cc.type(p, v, "a function");
1360
+ }
1361
+ });
1362
+ }
1363
+ function validateConfig(input) {
1364
+ const c = new Collector();
1365
+ if (input === void 0) return [];
1366
+ if (!isRecord(input)) {
1367
+ c.type("", input, "an object (the default export of pw-sec.config.ts)");
1368
+ return c.issues;
1369
+ }
1370
+ const top = {
1371
+ scope: (cc, p, v) => section(cc, p, v, {
1372
+ origins: originList,
1373
+ includeBaseURL: bool,
1374
+ exclude: originList,
1375
+ projects: (c3, p3, v3) => {
1376
+ if (v3 !== "all") stringList(c3, p3, v3);
1377
+ },
1378
+ api: bool
1379
+ }),
1380
+ rules: (cc, _p, v) => rules(cc, v),
1381
+ limits: (cc, p, v) => section(cc, p, v, {
1382
+ maxBodyBytes: positiveInt,
1383
+ bodyContentTypes: stringList,
1384
+ maxFindingsPerRule: positiveInt
1385
+ }),
1386
+ browser: (cc, p, v) => section(cc, p, v, { cspEvents: bool, storageScan: bool }),
1387
+ gate: (cc, p, v) => section(cc, p, v, {
1388
+ minSeverity: enumOf(SEVERITIES),
1389
+ minConfidence: enumOf(CONFIDENCES),
1390
+ failOnExpired: bool,
1391
+ failOnNoTraffic: bool
1392
+ }),
1393
+ baseline: (cc, p, v) => section(cc, p, v, { path: nonEmptyString, pruneResolved: bool, requireNote: bool }),
1394
+ report: (cc, p, v) => section(cc, p, v, {
1395
+ dir: nonEmptyString,
1396
+ html: bool,
1397
+ json: bool,
1398
+ sarif: bool,
1399
+ junit: bool,
1400
+ junitPath: nonEmptyString,
1401
+ junitIncludeAccepted: bool,
1402
+ sarifIncludeAccepted: bool
1403
+ }),
1404
+ normalization: (cc, _p, v) => normalization(cc, v)
1405
+ };
1406
+ section(c, "", input, top);
1407
+ for (const issue of c.issues) {
1408
+ if (issue.path.startsWith(".")) {
1409
+ issue.path = issue.path.slice(1);
1410
+ issue.message = issue.message.replace(/^\./, "");
1411
+ }
1412
+ }
1413
+ return c.issues;
1414
+ }
1415
+
1416
+ // src/core/config/resolve.ts
1417
+ function presetRule(rule2, preset) {
1418
+ let severity = rule2.defaultSeverity;
1419
+ const confidence = rule2.defaultConfidence;
1420
+ let enabled = !rule2.strictOnly;
1421
+ if (preset === "minimal") enabled = enabled && confidence === "high";
1422
+ if (preset === "strict") {
1423
+ enabled = true;
1424
+ if (severity === "info") severity = "low";
1425
+ else if (severity === "low" && confidence === "high") severity = "medium";
1426
+ }
1427
+ return { enabled, severity, confidence, options: structuredClone(rule2.options) };
1428
+ }
1429
+ function applySetting(base, setting) {
1430
+ if (setting === "off") return { ...base, enabled: false };
1431
+ if (setting === "on") return { ...base, enabled: true };
1432
+ return {
1433
+ enabled: true,
1434
+ severity: setting.severity ?? base.severity,
1435
+ confidence: setting.confidence ?? base.confidence,
1436
+ options: { ...base.options, ...setting.options ?? {} }
1437
+ };
1438
+ }
1439
+ function resolveConfig(input) {
1440
+ const issues = validateConfig(input);
1441
+ if (issues.length > 0) return { ok: false, issues };
1442
+ const i = input ?? {};
1443
+ const preset = i.rules?.preset ?? DEFAULTS.preset;
1444
+ const rules2 = {};
1445
+ for (const rule2 of RULE_MANIFEST) {
1446
+ const setting = i.rules?.[rule2.id];
1447
+ const base = presetRule(rule2, preset);
1448
+ rules2[rule2.id] = setting === void 0 ? base : applySetting(base, setting);
1449
+ }
1450
+ const reportDir = i.report?.dir ?? DEFAULTS.report.dir;
1451
+ return {
1452
+ ok: true,
1453
+ config: {
1454
+ scope: { ...DEFAULTS.scope, ...i.scope },
1455
+ preset,
1456
+ rules: rules2,
1457
+ limits: { ...DEFAULTS.limits, ...i.limits },
1458
+ browser: { ...DEFAULTS.browser, ...i.browser },
1459
+ gate: { ...DEFAULTS.gate, ...i.gate },
1460
+ baseline: { ...DEFAULTS.baseline, ...i.baseline },
1461
+ report: {
1462
+ ...DEFAULTS.report,
1463
+ ...i.report,
1464
+ junitPath: i.report?.junitPath ?? `${reportDir.replace(/[\\/]+$/, "")}/junit.xml`
1465
+ },
1466
+ normalization: resolveNormalization(i.normalization)
1467
+ }
1468
+ };
1469
+ }
1470
+ function enabledRuleCount(config) {
1471
+ return Object.values(config.rules).filter((r) => r.enabled).length;
1472
+ }
1473
+
1474
+ // src/mode/index.ts
1475
+ var MODE_ENV = "PW_SEC_MODE";
1476
+ var CONFIG_ENV = "PW_SEC_CONFIG";
1477
+ var RUN_ID_ENV = "PW_SEC_RUN_ID";
1478
+ var SALT_ENV = "PW_SEC_RUN_SALT";
1479
+ var MODES = ["scan", "baseline"];
1480
+ function readMode(env) {
1481
+ const raw = (env[MODE_ENV] ?? "").trim();
1482
+ if (raw === "") return { ok: true, mode: null };
1483
+ const value = raw.toLowerCase();
1484
+ if (MODES.includes(value)) return { ok: true, mode: value };
1485
+ if (value === "active") {
1486
+ return {
1487
+ ok: false,
1488
+ issues: [
1489
+ {
1490
+ code: "MODE_NOT_AVAILABLE",
1491
+ path: MODE_ENV,
1492
+ message: `${MODE_ENV}=active: the active scan is not available in this version; the package is passive only`,
1493
+ hint: `Use ${MODE_ENV}=scan or ${MODE_ENV}=baseline.`
1494
+ }
1495
+ ]
1496
+ };
1497
+ }
1498
+ return {
1499
+ ok: false,
1500
+ issues: [
1501
+ {
1502
+ code: "MODE_INVALID",
1503
+ path: MODE_ENV,
1504
+ message: `${MODE_ENV}=${JSON.stringify(raw)} is not a mode`,
1505
+ hint: `Allowed values: ${MODES.join(", ")} (or unset to disable the scan).`
1506
+ }
1507
+ ]
1508
+ };
1509
+ }
1510
+ function scanModeOn(env = process.env) {
1511
+ const mode = readMode(env);
1512
+ return mode.ok && mode.mode !== null;
1513
+ }
1514
+
1515
+ // src/registry/index.ts
1516
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("playwright-security-scan.registry");
1517
+ function slot() {
1518
+ const global = globalThis;
1519
+ let current = global[REGISTRY_KEY];
1520
+ if (current === void 0) {
1521
+ current = {
1522
+ state: void 0,
1523
+ wrappedTests: /* @__PURE__ */ new WeakSet(),
1524
+ trackedContexts: /* @__PURE__ */ new Set(),
1525
+ activeCollector: void 0,
1526
+ wrappedRequestContexts: /* @__PURE__ */ new WeakSet()
1527
+ };
1528
+ global[REGISTRY_KEY] = current;
1529
+ }
1530
+ return current;
1531
+ }
1532
+ function setRegistered(state) {
1533
+ slot().state = state;
1534
+ }
1535
+ function getRegistered() {
1536
+ return slot().state;
1537
+ }
1538
+ function wrappedTests() {
1539
+ return slot().wrappedTests;
1540
+ }
1541
+ function trackedContexts() {
1542
+ return slot().trackedContexts;
1543
+ }
1544
+ function wrappedRequestContexts() {
1545
+ return slot().wrappedRequestContexts;
1546
+ }
1547
+ function activeCollector() {
1548
+ return slot().activeCollector;
1549
+ }
1550
+ function setActiveCollector(collector) {
1551
+ slot().activeCollector = collector;
1552
+ }
1553
+
1554
+ export { CONFIG_ENV, ConfigError, NON_SESSION_COOKIES, RULE_IDS, RUN_ID_ENV, SALT_ENV, SEVERITIES, activeCollector, canonicalOrigin, confidenceRank, createKeyBuilder, enabledRuleCount, getRegistered, matchingPattern, parseHostPattern, readMode, resolveConfig, ruleManifest, scanModeOn, setActiveCollector, setRegistered, severityRank, sha256, trackedContexts, wrappedRequestContexts, wrappedTests };