@jamesbrightman/pretty-csp 0.0.0-stage → 0.1.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.
package/dist/cli.cjs ADDED
@@ -0,0 +1,1667 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/cli/index.ts
5
+ var import_promises3 = require("fs/promises");
6
+ var import_node_fs = require("fs");
7
+ var import_node_path3 = require("path");
8
+ var import_node_url = require("url");
9
+ var import_jiti = require("jiti");
10
+
11
+ // src/audit/index.ts
12
+ var sourceFindings = (policy, directive, source, ruleId, severity, message, fix) => {
13
+ const owners = policy.explain().filter((row) => row.directive === directive && row.source === source);
14
+ return owners.length ? owners.map(({ ruleSet }) => ({
15
+ ruleId,
16
+ severity,
17
+ message,
18
+ fix,
19
+ directive,
20
+ source,
21
+ ruleSet
22
+ })) : [{ ruleId, severity, message, fix, directive, source }];
23
+ };
24
+ function audit(policy, options = {}) {
25
+ const object = policy.toObject();
26
+ const findings = [];
27
+ const add = (id, severity, message, fix, directive) => findings.push({
28
+ ruleId: id,
29
+ severity,
30
+ message,
31
+ fix,
32
+ ...directive ? { directive } : {}
33
+ });
34
+ if (!object["script-src"] && !object["default-src"])
35
+ add(
36
+ "missing-script-src",
37
+ "high",
38
+ "Some script execution is unrestricted.",
39
+ "Restrict script-src or default-src.",
40
+ "script-src"
41
+ );
42
+ for (const directive of [
43
+ "script-src",
44
+ "script-src-elem",
45
+ "script-src-attr",
46
+ "default-src"
47
+ ]) {
48
+ const sources = object[directive];
49
+ if (!sources) continue;
50
+ const isFallback = directive === "default-src" && object["script-src"] !== void 0;
51
+ if (isFallback) continue;
52
+ const hasNonceOrHash = sources.some(
53
+ (s) => /^'(nonce-|sha(?:256|384|512)-)/i.test(s)
54
+ );
55
+ for (const source of sources.filter(
56
+ (s) => s.toLowerCase() === "'unsafe-inline'" && !hasNonceOrHash
57
+ ))
58
+ findings.push(
59
+ ...sourceFindings(
60
+ policy,
61
+ directive,
62
+ source,
63
+ "script-unsafe-inline",
64
+ "high",
65
+ "Inline scripts are permitted.",
66
+ "Use nonces or hashes and remove unsafe-inline."
67
+ )
68
+ );
69
+ for (const source of sources.filter(
70
+ (s) => s.toLowerCase() === "'unsafe-eval'"
71
+ ))
72
+ findings.push(
73
+ ...sourceFindings(
74
+ policy,
75
+ directive,
76
+ source,
77
+ "script-unsafe-eval",
78
+ "high",
79
+ "Dynamic JavaScript evaluation is permitted.",
80
+ "Remove unsafe-eval and replace dynamic evaluation."
81
+ )
82
+ );
83
+ if (directive !== "script-src-attr" && sources.some((source) => source.toLowerCase() === "'strict-dynamic'")) {
84
+ for (const source of sources) {
85
+ if (source.toLowerCase() === "'self'" || source === "*" || /^[a-z][a-z0-9+.-]*:$/i.test(source) || /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:\*|[a-z0-9*.-]+)(?::(?:\*|\d+))?(?:\/[^\s]*)?$/i.test(
86
+ source
87
+ )) {
88
+ findings.push(
89
+ ...sourceFindings(
90
+ policy,
91
+ directive,
92
+ source,
93
+ "ignored-by-strict-dynamic",
94
+ "info",
95
+ "Modern browsers ignore this source for scripts under strict-dynamic.",
96
+ "Remove it if legacy browser fallback is not needed."
97
+ )
98
+ );
99
+ }
100
+ }
101
+ }
102
+ for (const source of sources)
103
+ if (["*", "https:", "http:", "data:"].includes(source.toLowerCase()) || /^(?:https?:\/\/)?\*(?::(?:\*|\d+))?(?:\/[^\s]*)?$/i.test(source))
104
+ findings.push(
105
+ ...sourceFindings(
106
+ policy,
107
+ directive,
108
+ source,
109
+ "script-wildcard",
110
+ "high",
111
+ "A broad script source may permit attacker-controlled scripts.",
112
+ "Restrict script sources and prefer nonces or hashes."
113
+ )
114
+ );
115
+ }
116
+ const objects = object["object-src"] ?? object["default-src"];
117
+ if (!objects || objects.length !== 1 || objects[0]?.toLowerCase() !== "'none'")
118
+ add(
119
+ "missing-object-src",
120
+ "high",
121
+ "Object embedding is not explicitly blocked.",
122
+ "Set object-src to 'none'.",
123
+ "object-src"
124
+ );
125
+ const broad = (sources) => !sources || sources.some(
126
+ (source) => source === "*" || /^[a-z][a-z0-9+.-]*:$/i.test(source) || /^(?:https?:\/\/)?\*(?::(?:\*|\d+))?(?:\/[^\s]*)?$/i.test(source)
127
+ );
128
+ if (broad(object["base-uri"]))
129
+ add(
130
+ "missing-base-uri",
131
+ "medium",
132
+ "The document base URL is not sufficiently restricted.",
133
+ "Set base-uri to 'none' or 'self'.",
134
+ "base-uri"
135
+ );
136
+ if (broad(object["frame-ancestors"]))
137
+ add(
138
+ "missing-frame-ancestors",
139
+ "medium",
140
+ "Embedding by other sites is not sufficiently restricted.",
141
+ "Restrict frame-ancestors to trusted origins.",
142
+ "frame-ancestors"
143
+ );
144
+ const knownBypassDomains = [
145
+ "google.com",
146
+ "googleapis.com",
147
+ "googleusercontent.com",
148
+ "gstatic.com"
149
+ ];
150
+ for (const row of policy.explain()) {
151
+ if (["script-src", "script-src-elem", "default-src"].includes(row.directive)) {
152
+ const host = row.source.match(/^(?:https?:\/\/)?(?:\*\.)?([a-z0-9.-]+)/i)?.[1]?.toLowerCase();
153
+ if (host && knownBypassDomains.some(
154
+ (domain) => host === domain || host.endsWith(`.${domain}`)
155
+ )) {
156
+ findings.push({
157
+ ruleId: "bypass-host",
158
+ severity: "medium",
159
+ directive: row.directive,
160
+ source: row.source,
161
+ ruleSet: row.ruleSet,
162
+ message: "This script host may expose JSONP or script gadgets that weaken host allowlists.",
163
+ fix: "Review the host for JSONP endpoints and script gadgets; prefer nonce or hash authorization."
164
+ });
165
+ }
166
+ }
167
+ if (/^http:/i.test(row.source))
168
+ findings.push({
169
+ ruleId: "insecure-scheme",
170
+ severity: "medium",
171
+ directive: row.directive,
172
+ source: row.source,
173
+ ruleSet: row.ruleSet,
174
+ message: "An insecure HTTP source is permitted.",
175
+ fix: "Use HTTPS where possible."
176
+ });
177
+ if (/^(?:https?:\/\/)?\*\.[a-z0-9-]+(?::(?:\*|\d+))?(?:\/|$)/i.test(
178
+ row.source
179
+ ) || /^https?:\/\/\*\.(?:amazonaws\.com|azurewebsites\.net)(?:[/:]|$)/i.test(
180
+ row.source
181
+ ))
182
+ findings.push({
183
+ ruleId: "broad-wildcard",
184
+ severity: "medium",
185
+ directive: row.directive,
186
+ source: row.source,
187
+ ruleSet: row.ruleSet,
188
+ message: "A wildcard covers an unusually broad or shared domain.",
189
+ fix: "List the specific trusted hosts."
190
+ });
191
+ }
192
+ if (!object["report-uri"] && !object["report-to"])
193
+ add(
194
+ "no-reporting",
195
+ "low",
196
+ "No reporting destination is configured.",
197
+ "Configure reporting and its endpoint."
198
+ );
199
+ const today = (options.now ?? /* @__PURE__ */ new Date()).toISOString().slice(0, 10);
200
+ for (const set of policy.config.ruleSets.filter((s) => s.enabled)) {
201
+ if (!set.owner)
202
+ findings.push({
203
+ ruleId: "ruleset-metadata",
204
+ severity: "low",
205
+ ruleSet: set.name,
206
+ message: "Rule set has no owner.",
207
+ fix: "Assign an owner."
208
+ });
209
+ if (set.reviewBy && set.reviewBy < today)
210
+ findings.push({
211
+ ruleId: "ruleset-metadata",
212
+ severity: "low",
213
+ ruleSet: set.name,
214
+ message: "Rule set review date has passed.",
215
+ fix: "Review permissions regularly."
216
+ });
217
+ }
218
+ for (const rule of options.rules ?? []) findings.push(...rule.check(policy));
219
+ for (const suppression of options.suppressions ?? [])
220
+ if (!suppression.reason.trim() || !suppression.ruleId || !suppression.ruleSet)
221
+ throw new Error(
222
+ "Audit suppressions require a rule id, rule set and reason"
223
+ );
224
+ return findings.filter(
225
+ (finding) => !(options.suppressions ?? []).some(
226
+ (s) => s.ruleId === finding.ruleId && s.ruleSet === finding.ruleSet
227
+ )
228
+ );
229
+ }
230
+
231
+ // src/testing/index.ts
232
+ function cspSnapshot(policy) {
233
+ return {
234
+ schemaVersion: 1,
235
+ mode: policy.config.mode,
236
+ directives: policy.toObject(),
237
+ contributors: policy.explain()
238
+ };
239
+ }
240
+
241
+ // src/cli/init.ts
242
+ var import_promises = require("fs/promises");
243
+ var import_node_path = require("path");
244
+
245
+ // src/matching/index.ts
246
+ var friendly = {
247
+ scripts: "script-src",
248
+ connect: "connect-src",
249
+ images: "img-src",
250
+ styles: "style-src",
251
+ fonts: "font-src",
252
+ frames: "frame-src",
253
+ forms: "form-action",
254
+ media: "media-src",
255
+ workers: "worker-src",
256
+ manifest: "manifest-src",
257
+ default: "default-src",
258
+ objects: "object-src",
259
+ baseUri: "base-uri",
260
+ frameAncestors: "frame-ancestors"
261
+ };
262
+ var fallbacks = {
263
+ "script-src-elem": ["script-src-elem", "script-src", "default-src"],
264
+ "script-src-attr": ["script-src-attr", "script-src", "default-src"],
265
+ "style-src-elem": ["style-src-elem", "style-src", "default-src"],
266
+ "style-src-attr": ["style-src-attr", "style-src", "default-src"],
267
+ "worker-src": ["worker-src", "child-src", "script-src", "default-src"],
268
+ "frame-src": ["frame-src", "child-src", "default-src"]
269
+ };
270
+ for (const name of [
271
+ "script-src",
272
+ "style-src",
273
+ "child-src",
274
+ "connect-src",
275
+ "font-src",
276
+ "img-src",
277
+ "manifest-src",
278
+ "media-src",
279
+ "object-src"
280
+ ]) {
281
+ fallbacks[name] = [name, "default-src"];
282
+ }
283
+ for (const name of [
284
+ "default-src",
285
+ "form-action",
286
+ "base-uri",
287
+ "frame-ancestors"
288
+ ])
289
+ fallbacks[name] = [name];
290
+ function decision(status, effectiveDirective, reason, matchedSource) {
291
+ return {
292
+ status,
293
+ allowed: status === "indeterminate" ? null : status === "allowed",
294
+ ...effectiveDirective && { effectiveDirective },
295
+ ...reason && { reason },
296
+ ...matchedSource && { matchedSource }
297
+ };
298
+ }
299
+ function schemeMatches(source, target) {
300
+ source = source.toLowerCase();
301
+ target = target.toLowerCase();
302
+ return source === target || source === "http" && target === "https" || source === "ws" && ["wss", "http", "https"].includes(target) || source === "wss" && target === "https";
303
+ }
304
+ function scheme(url) {
305
+ return url.protocol.slice(0, -1).toLowerCase();
306
+ }
307
+ function defaultPort(s) {
308
+ return { http: "80", https: "443", ws: "80", wss: "443", ftp: "21" }[s];
309
+ }
310
+ function selfMatches(url, origin) {
311
+ if (scheme(url) === "blob") return false;
312
+ if (origin.origin !== "null" && origin.origin === url.origin) return true;
313
+ const os = scheme(origin), us = scheme(url);
314
+ const portsMatch = origin.port === url.port || !origin.port && !url.port;
315
+ return origin.hostname !== "" && origin.hostname === url.hostname && portsMatch && (us === "https" || us === "wss" || os === "http" && (us === "http" || us === "ws"));
316
+ }
317
+ function segmentBytes(segment) {
318
+ const bytes = [];
319
+ for (let i = 0; i < segment.length; ) {
320
+ const encoded = segment.slice(i).match(/^%([0-9a-f]{2})/i);
321
+ if (encoded) {
322
+ bytes.push(parseInt(encoded[1], 16));
323
+ i += 3;
324
+ continue;
325
+ }
326
+ const point = segment.codePointAt(i);
327
+ const character = String.fromCodePoint(point);
328
+ bytes.push(...new TextEncoder().encode(character));
329
+ i += character.length;
330
+ }
331
+ return bytes.join(",");
332
+ }
333
+ function pathMatches(pattern, target) {
334
+ if (!pattern || pattern === "/" && !target) return true;
335
+ const a = pattern.split("/"), b = target.split("/");
336
+ if (a.length > b.length || !pattern.endsWith("/") && a.length !== b.length)
337
+ return false;
338
+ if (pattern.endsWith("/")) a.pop();
339
+ return a.every((part, i) => segmentBytes(part) === segmentBytes(b[i]));
340
+ }
341
+ function sourceMatches(source, url, origin, redirectCount) {
342
+ const lower = source.toLowerCase(), targetScheme = scheme(url);
343
+ if (lower === "'self'")
344
+ return origin ? selfMatches(url, origin) ? "yes" : "no" : "unknown";
345
+ if (source === "*")
346
+ return ["http", "https"].includes(targetScheme) ? "yes" : origin ? scheme(origin) === targetScheme ? "yes" : "no" : "unknown";
347
+ const schemeOnly = source.match(/^([a-z][a-z0-9+.-]*):$/i);
348
+ if (schemeOnly)
349
+ return schemeMatches(schemeOnly[1], targetScheme) ? "yes" : "no";
350
+ const host = source.match(
351
+ /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9.-]+)(?::(\*|[0-9]+))?(\/[^?#]*)?$/i
352
+ );
353
+ if (!host) return "no";
354
+ const [, explicitScheme, patternHost, port, path] = host;
355
+ if (!url.hostname || /^\[/.test(url.hostname) || /^\d+(?:\.\d+){3}$/.test(url.hostname))
356
+ return "no";
357
+ if (!explicitScheme && !origin) return "unknown";
358
+ if (!schemeMatches(explicitScheme ?? scheme(origin), targetScheme))
359
+ return "no";
360
+ const domain = url.hostname.toLowerCase(), pattern = patternHost.toLowerCase();
361
+ if (pattern !== "*" && !(pattern.startsWith("*.") ? domain.endsWith(pattern.slice(1)) : domain === pattern))
362
+ return "no";
363
+ if (port !== "*") {
364
+ const targetPort = url.port || void 0;
365
+ if (port === void 0 ? targetPort !== void 0 : Number(port) !== Number(targetPort ?? defaultPort(targetScheme)))
366
+ return "no";
367
+ }
368
+ if (path && !pathMatches(path, url.pathname)) {
369
+ if (redirectCount === void 0) return "unknown";
370
+ if (redirectCount === 0) return "no";
371
+ }
372
+ return "yes";
373
+ }
374
+ function matchPolicy(directives, directive, input, options = {}) {
375
+ const requested = friendly[directive] ?? directive.toLowerCase();
376
+ const name = requested === "script-src" ? "script-src-elem" : requested === "style-src" ? "style-src-elem" : requested;
377
+ const chain = fallbacks[name];
378
+ if (!chain)
379
+ return decision(
380
+ "indeterminate",
381
+ void 0,
382
+ "Unsupported directive or inline check"
383
+ );
384
+ const effective = chain.find(
385
+ (key) => Object.prototype.hasOwnProperty.call(directives, key)
386
+ );
387
+ if (!effective)
388
+ return decision("allowed", void 0, "No applicable directive");
389
+ if (name.endsWith("-attr"))
390
+ return decision(
391
+ "indeterminate",
392
+ effective,
393
+ "Inline checks require element content and context"
394
+ );
395
+ if (name === "frame-ancestors")
396
+ return decision(
397
+ "indeterminate",
398
+ effective,
399
+ "Frame enforcement depends on the complete ancestor chain"
400
+ );
401
+ if (options.redirectCount !== void 0 && (!Number.isInteger(options.redirectCount) || options.redirectCount < 0))
402
+ throw new TypeError("redirectCount must be a non-negative integer");
403
+ let url, origin;
404
+ try {
405
+ url = new URL(input);
406
+ if (options.origin !== void 0) {
407
+ origin = new URL(options.origin);
408
+ if (origin.origin === "null") throw new Error("opaque");
409
+ }
410
+ } catch {
411
+ throw new TypeError("Expected an absolute URL and a non-opaque origin");
412
+ }
413
+ const sources = directives[effective];
414
+ const script = name === "script-src" || name === "script-src-elem";
415
+ const style = name === "style-src" || name === "style-src-elem";
416
+ const hasNoncePlaceholder = sources.includes("'nonce-{nonce}'");
417
+ const nonceSources = sources.filter(
418
+ (s) => /^'nonce-[a-z0-9+/_=-]+'$/i.test(s)
419
+ );
420
+ const hashes = sources.filter(
421
+ (s) => /^'sha(256|384|512)-[a-z0-9+/_=-]+'$/i.test(s)
422
+ );
423
+ if ((script || style) && options.nonce && (nonceSources.some((s) => s.slice(7, -1) === options.nonce) || hasNoncePlaceholder && options.policyNonce !== void 0 && options.nonce === options.policyNonce))
424
+ return decision("allowed", effective, "Matching request nonce");
425
+ if (script && options.integrity?.length && options.integrity.every(
426
+ (token) => hashes.some((hash) => {
427
+ const [hashAlg, hashDigest] = hash.slice(1, -1).split("-", 2);
428
+ const [tokenAlg, tokenDigest] = token.split("-", 2);
429
+ return hashAlg?.toLowerCase() === tokenAlg?.toLowerCase() && hashDigest !== void 0 && hashDigest === tokenDigest;
430
+ })
431
+ ))
432
+ return decision("allowed", effective, "Matching integrity metadata");
433
+ const missingNonce = (script || style) && (nonceSources.length > 0 && options.nonce === void 0 || hasNoncePlaceholder && (options.nonce === void 0 || options.nonce !== "" && options.policyNonce === void 0));
434
+ const missingIntegrity = script && hashes.length > 0 && options.integrity === void 0;
435
+ if (script && sources.some((s) => s.toLowerCase() === "'strict-dynamic'")) {
436
+ if (options.parserInserted === false)
437
+ return decision(
438
+ "allowed",
439
+ effective,
440
+ "Non-parser-inserted script under strict-dynamic"
441
+ );
442
+ if (options.parserInserted === void 0 || missingNonce || missingIntegrity)
443
+ return decision(
444
+ "indeterminate",
445
+ effective,
446
+ "Script nonce, integrity or parser metadata is missing"
447
+ );
448
+ return decision(
449
+ "blocked",
450
+ effective,
451
+ "Parser-inserted script has no matching nonce or integrity metadata"
452
+ );
453
+ }
454
+ let unknown = false;
455
+ for (const source of sources) {
456
+ const match = sourceMatches(source, url, origin, options.redirectCount);
457
+ if (match === "yes")
458
+ return decision("allowed", effective, void 0, source);
459
+ if (match === "unknown") unknown = true;
460
+ }
461
+ if (unknown || missingNonce || missingIntegrity)
462
+ return decision(
463
+ "indeterminate",
464
+ effective,
465
+ "Origin, redirect count, nonce or integrity metadata is missing"
466
+ );
467
+ return decision("blocked", effective, "No source matched");
468
+ }
469
+
470
+ // src/reports/index.ts
471
+ function record(value) {
472
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
473
+ }
474
+ function field(obj, ...keys) {
475
+ for (const key of keys)
476
+ if (typeof obj[key] === "string" && obj[key]) return obj[key];
477
+ return void 0;
478
+ }
479
+ function parseViolationReports(input) {
480
+ if (typeof input === "string") {
481
+ try {
482
+ input = JSON.parse(input);
483
+ } catch {
484
+ throw new Error("Invalid report JSON");
485
+ }
486
+ }
487
+ const items = Array.isArray(input) ? input : [input];
488
+ return items.map((item, index) => {
489
+ const envelope = record(item);
490
+ if (!envelope) throw new Error(`Unsupported report at index ${index}`);
491
+ const body = (envelope.type === "csp" ? record(envelope.csp) : void 0) ?? record(envelope["csp-report"]) ?? (envelope.type === "csp-violation" ? record(envelope.body) : void 0) ?? envelope;
492
+ const directive = field(
493
+ body,
494
+ "effective-directive",
495
+ "effectiveDirective",
496
+ "effective_directive",
497
+ "violated-directive",
498
+ "violatedDirective",
499
+ "violated_directive"
500
+ );
501
+ const blockedURL = field(
502
+ body,
503
+ "blocked-uri",
504
+ "blockedURL",
505
+ "blockedUri",
506
+ "blocked_uri"
507
+ );
508
+ const documentURL = field(
509
+ body,
510
+ "document-uri",
511
+ "documentURL",
512
+ "documentUri",
513
+ "document_uri"
514
+ );
515
+ if (!directive || !blockedURL)
516
+ throw new Error(`Unsupported or incomplete report at index ${index}`);
517
+ return {
518
+ directive: directive.split(" ")[0],
519
+ blockedURL,
520
+ ...documentURL ? { documentURL } : {}
521
+ };
522
+ });
523
+ }
524
+ function replayReports(directives, reports) {
525
+ return reports.map((report) => {
526
+ let origin;
527
+ try {
528
+ if (report.documentURL) {
529
+ const parsedOrigin = new URL(report.documentURL).origin;
530
+ if (parsedOrigin !== "null") origin = parsedOrigin;
531
+ }
532
+ } catch {
533
+ }
534
+ let blocked;
535
+ try {
536
+ blocked = new URL(report.blockedURL);
537
+ } catch {
538
+ return {
539
+ report,
540
+ result: {
541
+ status: "indeterminate",
542
+ allowed: null,
543
+ reason: "Report does not contain a replayable URL"
544
+ }
545
+ };
546
+ }
547
+ if (!["http:", "https:", "ws:", "wss:"].includes(blocked.protocol)) {
548
+ return {
549
+ report,
550
+ result: {
551
+ status: "indeterminate",
552
+ allowed: null,
553
+ reason: "Report does not contain a replayable network URL"
554
+ }
555
+ };
556
+ }
557
+ const result = matchPolicy(
558
+ directives,
559
+ report.directive,
560
+ report.blockedURL,
561
+ origin ? { origin } : {}
562
+ );
563
+ if (result.status === "allowed" && result.matchedSource && result.matchedSource.replace(/^[a-z]+:\/\//i, "").includes("/")) {
564
+ return {
565
+ report,
566
+ result: {
567
+ status: "indeterminate",
568
+ allowed: null,
569
+ reason: "Report may omit the request path"
570
+ }
571
+ };
572
+ }
573
+ return { report, result };
574
+ });
575
+ }
576
+
577
+ // src/core.ts
578
+ var import_zod2 = require("zod");
579
+
580
+ // src/schemas.ts
581
+ var import_zod = require("zod");
582
+ var resourceDirectives = {
583
+ scripts: "script-src",
584
+ connect: "connect-src",
585
+ images: "img-src",
586
+ styles: "style-src",
587
+ fonts: "font-src",
588
+ frames: "frame-src",
589
+ forms: "form-action",
590
+ media: "media-src",
591
+ workers: "worker-src",
592
+ manifest: "manifest-src"
593
+ };
594
+ var baseDirectives = {
595
+ default: "default-src",
596
+ objects: "object-src",
597
+ baseUri: "base-uri",
598
+ frameAncestors: "frame-ancestors"
599
+ };
600
+ var risky = /* @__PURE__ */ new Set(["'unsafe-inline'", "'unsafe-eval'", "'unsafe-hashes'"]);
601
+ var keywords = /* @__PURE__ */ new Set([
602
+ "'self'",
603
+ "'none'",
604
+ "'strict-dynamic'",
605
+ "'report-sample'",
606
+ "'wasm-unsafe-eval'",
607
+ ...risky
608
+ ]);
609
+ var NONCE_PLACEHOLDER = "'nonce-{nonce}'";
610
+ function isSource(value) {
611
+ if (!value || /[\x00-\x20\x7f;,]/.test(value) || /^[a-z][a-z0-9+.-]*\/\//i.test(value))
612
+ return false;
613
+ if (keywords.has(value.toLowerCase()) || value === NONCE_PLACEHOLDER || value === "*" || /^[a-z][a-z0-9+.-]*:\/\/\*(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(value))
614
+ return true;
615
+ if (/^'(nonce-[A-Za-z0-9+/_-]+={0,2}|sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2})'$/i.test(
616
+ value
617
+ ))
618
+ return true;
619
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:$/.test(value)) return true;
620
+ return /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:\*\.)?(?:[a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(
621
+ value
622
+ );
623
+ }
624
+ var sourceStringSchema = import_zod.z.string().refine(isSource, "Invalid CSP source expression");
625
+ var sourceEntrySchema = import_zod.z.union([
626
+ sourceStringSchema.refine(
627
+ (s) => !risky.has(s.toLowerCase()),
628
+ "Risky keyword requires a reason"
629
+ ),
630
+ import_zod.z.object({ source: sourceStringSchema, reason: import_zod.z.string().trim().min(1) }).strict()
631
+ ]);
632
+ var sourceList = import_zod.z.array(sourceEntrySchema).min(1);
633
+ var sourceListDirectives = /* @__PURE__ */ new Set([
634
+ ...Object.values(resourceDirectives),
635
+ ...Object.values(baseDirectives),
636
+ "script-src-elem",
637
+ "script-src-attr",
638
+ "style-src-elem",
639
+ "style-src-attr",
640
+ "child-src"
641
+ ]);
642
+ var rawDirectives = import_zod.z.record(
643
+ import_zod.z.string().regex(/^[a-z][a-z0-9-]*$/).refine(
644
+ (name) => sourceListDirectives.has(name),
645
+ "Unsupported raw directive; only known source-list directives are supported"
646
+ ),
647
+ sourceList
648
+ );
649
+ var reserved = /* @__PURE__ */ new Set([
650
+ "report-uri",
651
+ "report-to",
652
+ "upgrade-insecure-requests"
653
+ ]);
654
+ var baseOnly = /* @__PURE__ */ new Set([...Object.values(baseDirectives), ...reserved]);
655
+ var ruleShape = Object.fromEntries(
656
+ Object.keys(resourceDirectives).map((key) => [key, sourceList.optional()])
657
+ );
658
+ var rulesSchema = import_zod.z.object({ ...ruleShape, directives: rawDirectives.optional() }).strict().refine(
659
+ (rules) => Object.entries(rules).some(
660
+ ([key, value]) => key === "directives" ? Object.keys(value ?? {}).length > 0 : value !== void 0
661
+ ),
662
+ "At least one resource directive is required"
663
+ ).superRefine((rules, ctx) => {
664
+ for (const directive of Object.keys(rules.directives ?? {})) {
665
+ if (baseOnly.has(directive))
666
+ ctx.addIssue({
667
+ code: "custom",
668
+ path: ["directives", directive],
669
+ message: "Base-only or reserved directive"
670
+ });
671
+ }
672
+ });
673
+ var baseSchema = import_zod.z.object({
674
+ ...ruleShape,
675
+ default: sourceList.optional(),
676
+ objects: sourceList.optional(),
677
+ baseUri: sourceList.optional(),
678
+ frameAncestors: sourceList.optional(),
679
+ upgradeInsecureRequests: import_zod.z.boolean().optional(),
680
+ directives: rawDirectives.optional()
681
+ }).strict().superRefine((base, ctx) => {
682
+ for (const directive of Object.keys(base.directives ?? {})) {
683
+ if (reserved.has(directive))
684
+ ctx.addIssue({
685
+ code: "custom",
686
+ path: ["directives", directive],
687
+ message: "Use the dedicated configuration field for this directive"
688
+ });
689
+ }
690
+ });
691
+ var ruleSetSchema = import_zod.z.object({
692
+ name: import_zod.z.string().trim().min(1),
693
+ purpose: import_zod.z.string().trim().min(1),
694
+ owner: import_zod.z.string().trim().min(1).optional(),
695
+ docs: import_zod.z.url().optional(),
696
+ tags: import_zod.z.array(import_zod.z.string().trim().min(1)).optional(),
697
+ reviewBy: import_zod.z.iso.date().optional(),
698
+ enabled: import_zod.z.boolean().default(true),
699
+ rules: rulesSchema
700
+ }).strict();
701
+ var reportingSchema = import_zod.z.object({
702
+ uri: import_zod.z.url().refine(
703
+ (value) => !/[\x00-\x20\x7f;,]/.test(value),
704
+ "Invalid reporting value"
705
+ ).optional(),
706
+ to: import_zod.z.string().regex(/^[A-Za-z0-9_-]+$/).optional()
707
+ }).strict();
708
+ var policyConfigSchema = import_zod.z.object({
709
+ base: baseSchema.default({}),
710
+ ruleSets: import_zod.z.array(ruleSetSchema).default([]),
711
+ reporting: reportingSchema.optional(),
712
+ mode: import_zod.z.enum(["enforce", "report-only"]).default("enforce")
713
+ }).strict().superRefine((config, ctx) => {
714
+ const names = /* @__PURE__ */ new Set();
715
+ config.ruleSets.forEach((rule, i) => {
716
+ if (names.has(rule.name))
717
+ ctx.addIssue({
718
+ code: "custom",
719
+ path: ["ruleSets", i, "name"],
720
+ message: `Duplicate rule set name: ${rule.name}`
721
+ });
722
+ names.add(rule.name);
723
+ });
724
+ });
725
+
726
+ // src/core.ts
727
+ function freeze(value) {
728
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
729
+ Object.values(value).forEach(freeze);
730
+ Object.freeze(value);
731
+ }
732
+ return value;
733
+ }
734
+ function entryValue(entry) {
735
+ return typeof entry === "string" ? entry : entry.source;
736
+ }
737
+ function entryReason(entry) {
738
+ return typeof entry === "string" ? void 0 : entry.reason;
739
+ }
740
+ var Policy = class _Policy {
741
+ config;
742
+ headerName;
743
+ constructor(input) {
744
+ const result = policyConfigSchema.safeParse(input);
745
+ if (!result.success) {
746
+ throw new import_zod2.z.ZodError(
747
+ result.error.issues.map((issue) => {
748
+ const index = issue.path[0] === "ruleSets" && typeof issue.path[1] === "number" ? issue.path[1] : void 0;
749
+ const name = index === void 0 ? void 0 : input.ruleSets?.[index]?.name;
750
+ return name ? {
751
+ ...issue,
752
+ message: `RuleSet "${name}" - ${issue.path.slice(2).join(".")}: ${issue.message}`
753
+ } : issue;
754
+ })
755
+ );
756
+ }
757
+ const config = result.data;
758
+ this.config = freeze(config);
759
+ this.headerName = config.mode === "enforce" ? "Content-Security-Policy" : "Content-Security-Policy-Report-Only";
760
+ Object.freeze(this);
761
+ }
762
+ /** Sources and their contributing rule sets. Duplicate values retain all contributors. */
763
+ explain() {
764
+ const rows = [];
765
+ const add = (directive, entries, ruleSet) => {
766
+ for (const entry of entries) {
767
+ const reason = entryReason(entry);
768
+ rows.push({
769
+ directive,
770
+ source: entryValue(entry),
771
+ ruleSet,
772
+ ...reason === void 0 ? {} : { reason }
773
+ });
774
+ }
775
+ };
776
+ const collect = (rules, name) => {
777
+ for (const [key, value] of Object.entries(rules)) {
778
+ if (key === "directives" && value) {
779
+ for (const [directive, entries] of Object.entries(
780
+ value
781
+ ))
782
+ add(directive, entries, name);
783
+ } else if (Array.isArray(value)) {
784
+ const directive = resourceDirectives[key] ?? baseDirectives[key];
785
+ if (directive) add(directive, value, name);
786
+ }
787
+ }
788
+ };
789
+ collect(this.config.base, "base");
790
+ for (const set of this.config.ruleSets)
791
+ if (set.enabled) collect(set.rules, set.name);
792
+ return rows.sort(
793
+ (a, b) => a.directive.localeCompare(b.directive, "en") || a.source.localeCompare(b.source, "en") || a.ruleSet.localeCompare(b.ruleSet, "en") || (a.reason ?? "").localeCompare(b.reason ?? "", "en")
794
+ );
795
+ }
796
+ /** Merged sources, deduplicated without changing path syntax. */
797
+ toObject() {
798
+ const map = /* @__PURE__ */ Object.create(null);
799
+ for (const row of this.explain())
800
+ (map[row.directive] ??= /* @__PURE__ */ new Set()).add(row.source);
801
+ if (this.config.base.upgradeInsecureRequests)
802
+ map["upgrade-insecure-requests"] = /* @__PURE__ */ new Set();
803
+ if (this.config.reporting?.uri)
804
+ map["report-uri"] = /* @__PURE__ */ new Set([this.config.reporting.uri]);
805
+ if (this.config.reporting?.to)
806
+ map["report-to"] = /* @__PURE__ */ new Set([this.config.reporting.to]);
807
+ return Object.fromEntries(
808
+ Object.entries(map).sort(([a], [b]) => a.localeCompare(b, "en")).map(([key, values]) => [key, Array.from(values).sort()])
809
+ );
810
+ }
811
+ /** Evaluate a URL with explicit uncertainty when browser context is missing. */
812
+ allows(directive, url, options = {}) {
813
+ const result = matchPolicy(this.toObject(), directive, url, options);
814
+ const contributors = result.matchedSource && result.effectiveDirective ? this.explain().filter(
815
+ (row) => row.directive === result.effectiveDirective && row.source === result.matchedSource
816
+ ) : [];
817
+ return contributors.length ? { ...result, contributors } : result;
818
+ }
819
+ /** Replay supported violation report JSON without inventing missing request context. */
820
+ check(reports) {
821
+ return replayReports(this.toObject(), parseViolationReports(reports));
822
+ }
823
+ /** Render a header value. Pretty output is for display only and is not a valid HTTP header value. */
824
+ toHeader(options = {}) {
825
+ return this.render(this.toObject(), options);
826
+ }
827
+ render(directives, options) {
828
+ const hasNonce = Object.values(directives).some(
829
+ (sources) => sources.includes(NONCE_PLACEHOLDER)
830
+ );
831
+ if (hasNonce && (!options.nonce || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(options.nonce)))
832
+ throw new Error("A valid base64 nonce is required");
833
+ return Object.entries(directives).map(([directive, values]) => {
834
+ const rendered = values.map(
835
+ (value) => value === NONCE_PLACEHOLDER ? `'nonce-${options.nonce}'` : value
836
+ );
837
+ return directive + (rendered.length ? ` ${rendered.join(" ")}` : "");
838
+ }).join(options.pretty ? ";\n" : "; ");
839
+ }
840
+ /** Render a meta policy; report-only is not supported in meta delivery. */
841
+ toMetaContent(options = {}) {
842
+ if (this.config.mode === "report-only")
843
+ throw new Error(
844
+ "Report-only policies cannot be delivered in a meta element"
845
+ );
846
+ const directives = this.toObject();
847
+ delete directives["frame-ancestors"];
848
+ delete directives["report-uri"];
849
+ delete directives["report-to"];
850
+ delete directives.sandbox;
851
+ return this.render(directives, options);
852
+ }
853
+ withRuleSet(ruleSet) {
854
+ return new _Policy({
855
+ ...this.config,
856
+ ruleSets: [...this.config.ruleSets, ruleSet]
857
+ });
858
+ }
859
+ without(name) {
860
+ return new _Policy({
861
+ ...this.config,
862
+ ruleSets: this.config.ruleSets.filter((set) => set.name !== name)
863
+ });
864
+ }
865
+ };
866
+ function definePolicy(input) {
867
+ return new Policy(input);
868
+ }
869
+
870
+ // src/keywords.ts
871
+ var sourceExpressions = {
872
+ self: "'self'",
873
+ none: "'none'",
874
+ nonce: NONCE_PLACEHOLDER,
875
+ strictDynamic: "'strict-dynamic'",
876
+ reportSample: "'report-sample'",
877
+ wasmUnsafeEval: "'wasm-unsafe-eval'"
878
+ };
879
+
880
+ // src/cli/init.ts
881
+ async function initProject(cwd, options = {}) {
882
+ const language = options.language ?? "javascript";
883
+ if (!["javascript", "typescript"].includes(language))
884
+ throw new Error("language must be javascript or typescript");
885
+ const mode = options.mode ?? "report-only";
886
+ if (!["enforce", "report-only"].includes(mode))
887
+ throw new Error("mode must be enforce or report-only");
888
+ const apiOrigins = [...new Set(options.apiOrigins ?? [])];
889
+ for (const origin of apiOrigins) {
890
+ let parsed;
891
+ try {
892
+ parsed = new URL(origin);
893
+ } catch {
894
+ throw new Error(`Invalid API origin: ${origin}`);
895
+ }
896
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.origin !== origin)
897
+ throw new Error(
898
+ `API origins must be HTTP(S) origins without paths, credentials or trailing slash: ${origin}`
899
+ );
900
+ }
901
+ if (options.reportUri) {
902
+ let parsed;
903
+ try {
904
+ parsed = new URL(options.reportUri);
905
+ } catch {
906
+ throw new Error("Invalid reporting URL");
907
+ }
908
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash)
909
+ throw new Error(
910
+ "Reporting URL must be an HTTP(S) URL without credentials or fragment"
911
+ );
912
+ }
913
+ const review = new Date(options.now ?? /* @__PURE__ */ new Date());
914
+ review.setUTCFullYear(review.getUTCFullYear() + 1);
915
+ const reviewBy = review.toISOString().slice(0, 10);
916
+ const policy = definePolicy({
917
+ mode,
918
+ ...options.reportUri ? { reporting: { uri: options.reportUri } } : {},
919
+ base: {
920
+ default: [sourceExpressions.self],
921
+ scripts: [
922
+ sourceExpressions.self,
923
+ sourceExpressions.nonce,
924
+ sourceExpressions.strictDynamic
925
+ ],
926
+ objects: [sourceExpressions.none],
927
+ baseUri: [sourceExpressions.self],
928
+ frameAncestors: [sourceExpressions.none],
929
+ upgradeInsecureRequests: true
930
+ },
931
+ ruleSets: [
932
+ {
933
+ name: "App assets",
934
+ purpose: "Images used by the application",
935
+ owner: "TODO: assign owner",
936
+ reviewBy,
937
+ rules: { images: [sourceExpressions.self, "data:", "blob:"] }
938
+ },
939
+ ...apiOrigins.length ? [
940
+ {
941
+ name: "App API",
942
+ purpose: "Application API connections",
943
+ owner: "TODO: assign owner",
944
+ reviewBy,
945
+ rules: { connect: apiOrigins }
946
+ }
947
+ ] : []
948
+ ]
949
+ });
950
+ const extension = language === "typescript" ? "ts" : "mjs";
951
+ const importExtension = language === "typescript" ? "" : ".mjs";
952
+ const apiImport = apiOrigins.length ? `import { appApi } from './rule-sets/app-api${importExtension}';
953
+ ` : "";
954
+ const reporting = options.reportUri ? ` reporting: { uri: ${JSON.stringify(options.reportUri)} },
955
+ ` : "";
956
+ const apiTest = apiOrigins.length ? ` expect(policy).toAllow('connect', ${JSON.stringify(apiOrigins[0] + "/")}, { origin: 'https://site.example', redirectCount: 0 });
957
+ ` : "";
958
+ const files = {
959
+ [`csp.config.${extension}`]: `export { policy as default } from './csp/policy${importExtension}';
960
+ `,
961
+ [`csp/policy.${extension}`]: `import { definePolicy, sourceExpressions } from '@jamesbrightman/pretty-csp';
962
+ import { appAssets } from './rule-sets/app-assets${importExtension}';
963
+ ${apiImport}
964
+ export const policy = definePolicy({
965
+ mode: ${JSON.stringify(mode)},
966
+ ${reporting} base: { default: [sourceExpressions.self], scripts: [sourceExpressions.self, sourceExpressions.nonce, sourceExpressions.strictDynamic], objects: [sourceExpressions.none], baseUri: [sourceExpressions.self], frameAncestors: [sourceExpressions.none], upgradeInsecureRequests: true },
967
+ ruleSets: [appAssets${apiOrigins.length ? ", appApi" : ""}],
968
+ });
969
+ `,
970
+ [`csp/rule-sets/app-assets.${extension}`]: `import { defineRuleSet, sourceExpressions } from '@jamesbrightman/pretty-csp';
971
+
972
+ export const appAssets = defineRuleSet({ name: 'App assets', purpose: 'Images used by the application', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { images: [sourceExpressions.self, 'data:', 'blob:'] } });
973
+ `,
974
+ [`csp/policy.test.${extension}`]: `import { readFile } from 'node:fs/promises';
975
+ import { expect, test } from 'vitest';
976
+ import { cspMatchers, cspSnapshot } from '@jamesbrightman/pretty-csp/testing';
977
+ import { policy } from './policy${importExtension}';
978
+
979
+ expect.extend(cspMatchers);
980
+ test('blocks untrusted connections and has no high-risk findings', () => {
981
+ ${apiTest} expect(policy).toBlock('connect', 'https://untrusted.example/', { origin: 'https://site.example', redirectCount: 0 });
982
+ expect(policy).toPassAudit({ maxSeverity: 'low' });
983
+ });
984
+ test('matches the reviewed CSP snapshot', async () => {
985
+ const snapshot = JSON.parse(await readFile(new URL('../csp.snapshot.json', import.meta.url), 'utf8'));
986
+ expect(policy).toMatchCspSnapshot(snapshot);
987
+ });
988
+ `,
989
+ "csp.snapshot.json": `${JSON.stringify(cspSnapshot(policy), null, 2)}
990
+ `
991
+ };
992
+ if (apiOrigins.length)
993
+ files[`csp/rule-sets/app-api.${extension}`] = `import { defineRuleSet } from '@jamesbrightman/pretty-csp';
994
+
995
+ export const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API connections', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { connect: ${JSON.stringify(apiOrigins)} } });
996
+ `;
997
+ async function stat(path) {
998
+ try {
999
+ return await (0, import_promises.lstat)(path);
1000
+ } catch (error) {
1001
+ if (error.code === "ENOENT") return void 0;
1002
+ throw error;
1003
+ }
1004
+ }
1005
+ for (const directory of ["csp", "csp/rule-sets"]) {
1006
+ const dir = await stat((0, import_node_path.join)(cwd, directory));
1007
+ if (dir?.isSymbolicLink() || dir && !dir.isDirectory())
1008
+ throw new Error(`${directory} must be a directory and not a symlink`);
1009
+ }
1010
+ for (const file of Object.keys(files)) {
1011
+ const current = await stat((0, import_node_path.join)(cwd, file));
1012
+ if (current?.isSymbolicLink() || current && !current.isFile())
1013
+ throw new Error(`Refusing non-file or symlink: ${file}`);
1014
+ if (current && !options.force)
1015
+ throw new Error(
1016
+ `File already exists: ${file}. Use --force to replace it.`
1017
+ );
1018
+ }
1019
+ if (!options.dryRun) {
1020
+ await (0, import_promises.mkdir)((0, import_node_path.join)(cwd, "csp/rule-sets"), { recursive: true });
1021
+ for (const [file, content] of Object.entries(files))
1022
+ await (0, import_promises.writeFile)((0, import_node_path.join)(cwd, file), content, {
1023
+ encoding: "utf8",
1024
+ flag: options.force ? "w" : "wx"
1025
+ });
1026
+ }
1027
+ return Object.keys(files);
1028
+ }
1029
+
1030
+ // src/cli/import.ts
1031
+ var import_promises2 = require("fs/promises");
1032
+ var import_node_path2 = require("path");
1033
+ var import_tldts = require("tldts");
1034
+ function registrableDomain(source) {
1035
+ const host = /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:\*\.)?([a-z0-9-]+(?:\.[a-z0-9-]+)+)(?=[:/]|$)/i.exec(
1036
+ source
1037
+ )?.[1];
1038
+ if (!host) return void 0;
1039
+ const { domain, isIcann, isPrivate } = (0, import_tldts.parse)(host, {
1040
+ allowPrivateDomains: true
1041
+ });
1042
+ return domain && (isIcann || isPrivate) ? domain.toLowerCase() : void 0;
1043
+ }
1044
+ function importDraftFiles(draft, mode) {
1045
+ const groups = /* @__PURE__ */ new Map();
1046
+ const unassigned = {};
1047
+ for (const [directive, entries] of Object.entries(
1048
+ draft.base?.directives ?? {}
1049
+ )) {
1050
+ rejectCapturedNonces(entries, directive);
1051
+ }
1052
+ for (const ruleSet of draft.ruleSets ?? []) {
1053
+ for (const [directive, entries] of Object.entries(
1054
+ ruleSet.rules.directives ?? {}
1055
+ )) {
1056
+ rejectCapturedNonces(entries, directive);
1057
+ for (const entry of entries) {
1058
+ const domain = registrableDomain(
1059
+ typeof entry === "string" ? entry : entry.source
1060
+ );
1061
+ let directives = unassigned;
1062
+ if (domain) {
1063
+ directives = groups.get(domain) ?? {};
1064
+ groups.set(domain, directives);
1065
+ }
1066
+ (directives[directive] ??= []).push(entry);
1067
+ }
1068
+ }
1069
+ }
1070
+ const files = /* @__PURE__ */ new Map();
1071
+ const imports = [];
1072
+ const names = [];
1073
+ const addRuleSet = (filename, ruleSet) => {
1074
+ const path = `rule-sets/${filename}.mjs`;
1075
+ const name = `ruleSet${names.length + 1}`;
1076
+ files.set(
1077
+ path,
1078
+ `import { defineRuleSet } from '@jamesbrightman/pretty-csp';
1079
+
1080
+ export default defineRuleSet(${JSON.stringify(ruleSet, null, 2)});
1081
+ `
1082
+ );
1083
+ imports.push(`import ${name} from './${path}';`);
1084
+ names.push(name);
1085
+ };
1086
+ const sortedGroups = Array.from(groups).sort(
1087
+ ([first], [second]) => first.localeCompare(second, "en")
1088
+ );
1089
+ for (const [domain, directives] of sortedGroups) {
1090
+ addRuleSet(`domain-${domain}`, {
1091
+ name: domain,
1092
+ purpose: "Imported domain group. Confirm purpose and owner before use.",
1093
+ rules: { directives }
1094
+ });
1095
+ }
1096
+ if (Object.keys(unassigned).length) {
1097
+ addRuleSet("unassigned", {
1098
+ name: "Unassigned sources",
1099
+ purpose: "Imported sources that need manual grouping and review.",
1100
+ rules: { directives: unassigned }
1101
+ });
1102
+ }
1103
+ files.set(
1104
+ "csp.config.mjs",
1105
+ [
1106
+ "import { definePolicy } from '@jamesbrightman/pretty-csp';",
1107
+ ...imports,
1108
+ "",
1109
+ "// Review this draft before using it in an application.",
1110
+ "export default definePolicy({",
1111
+ ` mode: ${JSON.stringify(mode)},`,
1112
+ ` base: ${JSON.stringify(draft.base ?? {}, null, 2).replace(/\n/g, "\n ")},`,
1113
+ ` ruleSets: [${names.join(", ")}],`,
1114
+ "});",
1115
+ ""
1116
+ ].join("\n")
1117
+ );
1118
+ return files;
1119
+ }
1120
+ function rejectCapturedNonces(entries, directive) {
1121
+ if (entries.some(
1122
+ (entry) => /^'nonce-/i.test(typeof entry === "string" ? entry : entry.source)
1123
+ )) {
1124
+ throw new Error(
1125
+ `Directive ${directive} contains a captured nonce. Migrate it separately using a fresh nonce per response.`
1126
+ );
1127
+ }
1128
+ }
1129
+ async function writeImportDraft(output, files) {
1130
+ try {
1131
+ await (0, import_promises2.mkdir)(output);
1132
+ } catch (error) {
1133
+ if (error.code === "EEXIST")
1134
+ throw new Error(
1135
+ `Import output already exists: ${output}. Choose a new directory.`
1136
+ );
1137
+ throw error;
1138
+ }
1139
+ const createdFiles = [];
1140
+ let createdRuleSets = false;
1141
+ try {
1142
+ if (files.size > 1) {
1143
+ await (0, import_promises2.mkdir)((0, import_node_path2.join)(output, "rule-sets"));
1144
+ createdRuleSets = true;
1145
+ }
1146
+ for (const [name, content] of files) {
1147
+ const path = (0, import_node_path2.join)(output, name);
1148
+ const file = await (0, import_promises2.open)(path, "wx");
1149
+ createdFiles.push(path);
1150
+ try {
1151
+ await file.writeFile(content, "utf8");
1152
+ } finally {
1153
+ await file.close();
1154
+ }
1155
+ }
1156
+ } catch (error) {
1157
+ try {
1158
+ for (const path of createdFiles) await (0, import_promises2.unlink)(path);
1159
+ if (createdRuleSets) await (0, import_promises2.rmdir)((0, import_node_path2.join)(output, "rule-sets"));
1160
+ await (0, import_promises2.rmdir)(output);
1161
+ } catch {
1162
+ throw new Error(
1163
+ `Import failed and may have left partial files in ${output}`,
1164
+ { cause: error }
1165
+ );
1166
+ }
1167
+ throw error;
1168
+ }
1169
+ }
1170
+
1171
+ // src/cli/diff.ts
1172
+ var import_node_child_process = require("child_process");
1173
+ var import_node_util = require("util");
1174
+ var import_zod3 = require("zod");
1175
+
1176
+ // src/diff.ts
1177
+ function diffPolicies(before, after) {
1178
+ const key = (row) => JSON.stringify([
1179
+ row.directive,
1180
+ row.source,
1181
+ row.ruleSet,
1182
+ row.reason ?? null
1183
+ ]);
1184
+ const oldRows = new Map(before.explain().map((row) => [key(row), row]));
1185
+ const newRows = new Map(after.explain().map((row) => [key(row), row]));
1186
+ const changes = [];
1187
+ for (const [id, row] of oldRows)
1188
+ if (!newRows.has(id))
1189
+ changes.push({
1190
+ directive: row.directive,
1191
+ source: row.source,
1192
+ ruleSet: row.ruleSet,
1193
+ change: "removed",
1194
+ ...row.reason ? { detail: row.reason } : {}
1195
+ });
1196
+ for (const [id, row] of newRows)
1197
+ if (!oldRows.has(id))
1198
+ changes.push({
1199
+ directive: row.directive,
1200
+ source: row.source,
1201
+ ruleSet: row.ruleSet,
1202
+ change: "added",
1203
+ ...row.reason ? { detail: row.reason } : {}
1204
+ });
1205
+ const beforeObj = before.toObject(), afterObj = after.toObject();
1206
+ for (const directive of /* @__PURE__ */ new Set([
1207
+ ...Object.keys(beforeObj),
1208
+ ...Object.keys(afterObj)
1209
+ ])) {
1210
+ if (JSON.stringify(beforeObj[directive]) !== JSON.stringify(afterObj[directive]) && !changes.some((c) => c.directive === directive))
1211
+ changes.push({
1212
+ directive,
1213
+ source: "",
1214
+ ruleSet: "base",
1215
+ change: "modified",
1216
+ detail: "Directive value changed"
1217
+ });
1218
+ }
1219
+ if (before.config.mode !== after.config.mode)
1220
+ changes.push({
1221
+ directive: "(mode)",
1222
+ source: "",
1223
+ ruleSet: "base",
1224
+ change: "modified",
1225
+ detail: `${before.config.mode} \u2192 ${after.config.mode}`
1226
+ });
1227
+ changes.sort(
1228
+ (a, b) => a.directive.localeCompare(b.directive) || a.source.localeCompare(b.source) || a.ruleSet.localeCompare(b.ruleSet) || a.change.localeCompare(b.change)
1229
+ );
1230
+ const headersChanged = JSON.stringify(beforeObj) !== JSON.stringify(afterObj) || before.config.mode !== after.config.mode;
1231
+ const dangerous = changes.some(
1232
+ (change) => change.change === "added" && !(beforeObj[change.directive] ?? []).includes(change.source) && /^(?:\*|https?:|data:|'unsafe-(?:inline|eval|hashes)')$/.test(
1233
+ change.source
1234
+ )
1235
+ );
1236
+ return {
1237
+ changes,
1238
+ risk: dangerous ? "increased" : headersChanged ? "unknown" : "unchanged"
1239
+ };
1240
+ }
1241
+
1242
+ // src/cli/diff.ts
1243
+ var snapshotSchema = import_zod3.z.object({
1244
+ schemaVersion: import_zod3.z.literal(1),
1245
+ mode: import_zod3.z.enum(["enforce", "report-only"]),
1246
+ directives: import_zod3.z.record(
1247
+ import_zod3.z.string().regex(/^[a-z][a-z0-9-]*$/),
1248
+ import_zod3.z.array(import_zod3.z.string())
1249
+ ),
1250
+ contributors: import_zod3.z.array(
1251
+ import_zod3.z.object({
1252
+ directive: import_zod3.z.string(),
1253
+ source: import_zod3.z.string(),
1254
+ ruleSet: import_zod3.z.string(),
1255
+ reason: import_zod3.z.string().optional()
1256
+ }).strict()
1257
+ )
1258
+ }).strict();
1259
+ async function readGitSnapshot(ref, cwd) {
1260
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._/~^-]*$/.test(ref))
1261
+ throw new Error("Invalid Git ref");
1262
+ const exec = (0, import_node_util.promisify)(import_node_child_process.execFile);
1263
+ try {
1264
+ const { stdout } = await exec(
1265
+ "git",
1266
+ ["show", "--no-ext-diff", "--no-textconv", `${ref}:csp.snapshot.json`],
1267
+ { cwd, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }
1268
+ );
1269
+ return stdout;
1270
+ } catch {
1271
+ throw new Error(
1272
+ "Could not read csp.snapshot.json at the Git ref; commit a version 1 snapshot at the repository root."
1273
+ );
1274
+ }
1275
+ }
1276
+ function diffSnapshot(json, current) {
1277
+ let data;
1278
+ try {
1279
+ data = JSON.parse(json);
1280
+ } catch {
1281
+ throw new Error("Invalid snapshot JSON");
1282
+ }
1283
+ const parsed = snapshotSchema.safeParse(data);
1284
+ if (!parsed.success)
1285
+ throw new Error("Invalid or unsupported CSP snapshot format");
1286
+ const snapshot = parsed.data;
1287
+ for (const row of snapshot.contributors) {
1288
+ if (!snapshot.directives[row.directive]?.includes(row.source))
1289
+ throw new Error("Snapshot contributor does not match a directive source");
1290
+ }
1291
+ for (const [directive, sources] of Object.entries(snapshot.directives)) {
1292
+ if (directive === "report-uri" || directive === "report-to") continue;
1293
+ for (const source of sources) {
1294
+ if (!snapshot.contributors.some(
1295
+ (row) => row.directive === directive && row.source === source
1296
+ ))
1297
+ throw new Error("Snapshot source has no contributor");
1298
+ }
1299
+ }
1300
+ const previous = {
1301
+ config: { mode: snapshot.mode },
1302
+ toObject: () => snapshot.directives,
1303
+ explain: () => snapshot.contributors
1304
+ };
1305
+ return diffPolicies(previous, current);
1306
+ }
1307
+
1308
+ // src/importer/index.ts
1309
+ function importHeader(header) {
1310
+ if (/[\x00-\x08\x0a-\x1f\x7f,]/.test(header))
1311
+ throw new Error(
1312
+ "Header contains a control character or multiple policies; import one policy at a time"
1313
+ );
1314
+ const seen = /* @__PURE__ */ new Set();
1315
+ const warnings = [];
1316
+ const directives = [];
1317
+ for (const segment of header.split(";")) {
1318
+ const trimmed = segment.trim();
1319
+ if (!trimmed) continue;
1320
+ const [rawName, ...values] = trimmed.split(/[ \t]+/);
1321
+ if (!rawName || !/^[a-zA-Z][a-zA-Z0-9-]*$/.test(rawName))
1322
+ throw new Error(`Invalid directive name: ${rawName ?? ""}`);
1323
+ const name = rawName.toLowerCase();
1324
+ const ignored = seen.has(name);
1325
+ if (ignored)
1326
+ warnings.push(`Duplicate ${name} is ignored by CSP; retained for review`);
1327
+ seen.add(name);
1328
+ directives.push({ name, values, ignored });
1329
+ }
1330
+ return { directives, warnings };
1331
+ }
1332
+ function importedPolicyToDraft(policy) {
1333
+ if (policy.directives.some((directive) => directive.ignored))
1334
+ throw new Error(
1335
+ "Duplicate directives require manual review before conversion"
1336
+ );
1337
+ const base = {};
1338
+ const baseRaw = {};
1339
+ const ruleRaw = {};
1340
+ const baseOnly2 = /* @__PURE__ */ new Set([
1341
+ "default-src",
1342
+ "object-src",
1343
+ "base-uri",
1344
+ "frame-ancestors"
1345
+ ]);
1346
+ const supported = /* @__PURE__ */ new Set([
1347
+ "default-src",
1348
+ "object-src",
1349
+ "base-uri",
1350
+ "frame-ancestors",
1351
+ "script-src",
1352
+ "script-src-elem",
1353
+ "script-src-attr",
1354
+ "style-src",
1355
+ "style-src-elem",
1356
+ "style-src-attr",
1357
+ "img-src",
1358
+ "connect-src",
1359
+ "font-src",
1360
+ "frame-src",
1361
+ "child-src",
1362
+ "form-action",
1363
+ "media-src",
1364
+ "worker-src",
1365
+ "manifest-src"
1366
+ ]);
1367
+ const risky2 = /* @__PURE__ */ new Set([
1368
+ "'unsafe-inline'",
1369
+ "'unsafe-eval'",
1370
+ "'unsafe-hashes'"
1371
+ ]);
1372
+ for (const directive of policy.directives) {
1373
+ if (directive.name === "upgrade-insecure-requests") {
1374
+ if (directive.values.length)
1375
+ throw new Error(
1376
+ "upgrade-insecure-requests with values requires manual review"
1377
+ );
1378
+ base.upgradeInsecureRequests = true;
1379
+ continue;
1380
+ }
1381
+ if (!supported.has(directive.name) || directive.values.some(
1382
+ (value) => value.toLowerCase() === "'nonce-{nonce}'"
1383
+ )) {
1384
+ throw new Error(
1385
+ `Directive ${directive.name} contains unsupported syntax; review manually`
1386
+ );
1387
+ }
1388
+ if (directive.values.length === 0 || ["report-uri", "report-to", "sandbox"].includes(directive.name)) {
1389
+ throw new Error(
1390
+ `Directive ${directive.name} requires manual review before conversion`
1391
+ );
1392
+ }
1393
+ const entries = directive.values.map(
1394
+ (source) => risky2.has(source.toLowerCase()) ? { source, reason: "Imported legacy policy; review required" } : source
1395
+ );
1396
+ (baseOnly2.has(directive.name) ? baseRaw : ruleRaw)[directive.name] = entries;
1397
+ }
1398
+ if (Object.keys(baseRaw).length) base.directives = baseRaw;
1399
+ const draft = {
1400
+ base,
1401
+ ruleSets: Object.keys(ruleRaw).length ? [
1402
+ {
1403
+ name: "Imported policy",
1404
+ purpose: "Imported sources awaiting ownership review",
1405
+ rules: { directives: ruleRaw }
1406
+ }
1407
+ ] : []
1408
+ };
1409
+ const result = policyConfigSchema.safeParse(draft);
1410
+ if (!result.success)
1411
+ throw new Error(
1412
+ `Imported policy contains unsupported sources: ${result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`
1413
+ );
1414
+ return draft;
1415
+ }
1416
+
1417
+ // src/cli/index.ts
1418
+ var help = "Usage: pretty-csp <init|print|explain|audit|snapshot|diff|import|check-reports> [--config path] [options]";
1419
+ var importHelp = "Usage: pretty-csp import <header> | --file <header-file> [--output <new-directory> [--dry-run] [--mode <report-only|enforce>]]";
1420
+ var severities = {
1421
+ info: 0,
1422
+ low: 1,
1423
+ medium: 2,
1424
+ high: 3
1425
+ };
1426
+ function argsFor(args) {
1427
+ const [command = "help", ...rest] = args;
1428
+ const options = {};
1429
+ let positional;
1430
+ const flags = /* @__PURE__ */ new Set([
1431
+ "pretty",
1432
+ "update",
1433
+ "help",
1434
+ "yes",
1435
+ "dry-run",
1436
+ "force"
1437
+ ]);
1438
+ const values = /* @__PURE__ */ new Set([
1439
+ "config",
1440
+ "nonce",
1441
+ "directive",
1442
+ "rule-set",
1443
+ "fail-on",
1444
+ "file",
1445
+ "output",
1446
+ "base",
1447
+ "language",
1448
+ "api-origins",
1449
+ "report-uri",
1450
+ "mode"
1451
+ ]);
1452
+ for (let i = 0; i < rest.length; i++) {
1453
+ const arg = rest[i];
1454
+ if (!arg.startsWith("--")) {
1455
+ if (!["import", "check-reports"].includes(command) || positional !== void 0)
1456
+ throw new Error(`Unexpected argument: ${arg}`);
1457
+ positional = arg;
1458
+ continue;
1459
+ }
1460
+ const key = arg.slice(2);
1461
+ if (flags.has(key)) options[key] = true;
1462
+ else if (values.has(key)) {
1463
+ const value = rest[++i];
1464
+ if (!value || value.startsWith("--"))
1465
+ throw new Error(`--${key} requires a value`);
1466
+ options[key] = value;
1467
+ } else throw new Error(`Unknown option --${key}`);
1468
+ }
1469
+ return {
1470
+ command,
1471
+ options,
1472
+ ...positional === void 0 ? {} : { positional }
1473
+ };
1474
+ }
1475
+ function option(options, name) {
1476
+ return typeof options[name] === "string" ? options[name] : void 0;
1477
+ }
1478
+ function isPolicy(value) {
1479
+ return !!value && typeof value === "object" && ["toHeader", "toObject", "explain", "allows"].every(
1480
+ (key) => typeof value[key] === "function"
1481
+ ) && "config" in value;
1482
+ }
1483
+ async function loadConfigFile(path) {
1484
+ if ([".ts", ".mts", ".cts"].includes((0, import_node_path3.extname)(path).toLowerCase())) {
1485
+ const jiti = (0, import_jiti.createJiti)(path, { moduleCache: false, fsCache: false });
1486
+ return await jiti.import(path);
1487
+ }
1488
+ return await import((0, import_node_url.pathToFileURL)(path).href);
1489
+ }
1490
+ async function runCli(args, io, cwd = process.cwd(), loadConfig = loadConfigFile) {
1491
+ try {
1492
+ const { command, options, positional } = argsFor(args);
1493
+ if (command === "help" || options.help) {
1494
+ io.out(command === "import" ? importHelp : help);
1495
+ return 0;
1496
+ }
1497
+ if (![
1498
+ "init",
1499
+ "print",
1500
+ "explain",
1501
+ "audit",
1502
+ "snapshot",
1503
+ "diff",
1504
+ "import",
1505
+ "check-reports"
1506
+ ].includes(command))
1507
+ throw new Error(`Unsupported command: ${command}. ${help}`);
1508
+ if (command === "init") {
1509
+ if (!options.yes)
1510
+ throw new Error(
1511
+ "Use init --yes and optional --language, --api-origins, --report-uri and --mode flags."
1512
+ );
1513
+ const files = await initProject(cwd, {
1514
+ dryRun: Boolean(options["dry-run"]),
1515
+ force: Boolean(options.force),
1516
+ language: option(options, "language"),
1517
+ mode: option(options, "mode"),
1518
+ apiOrigins: option(options, "api-origins")?.split(",").map((origin) => origin.trim()),
1519
+ reportUri: option(options, "report-uri")
1520
+ });
1521
+ io.out(
1522
+ `${options["dry-run"] ? "Would write" : "Wrote"}:
1523
+ ${files.join("\n")}
1524
+ Install @jamesbrightman/pretty-csp and Vitest, then configure your server to set policy.headerName and policy.toHeader({ nonce }) on each response.`
1525
+ );
1526
+ return 0;
1527
+ }
1528
+ if (command === "import") {
1529
+ const headerFile = option(options, "file");
1530
+ const output = option(options, "output");
1531
+ if (!positional && !headerFile || positional && headerFile)
1532
+ throw new Error(
1533
+ "import requires a header string or --file, but not both"
1534
+ );
1535
+ if (!output && (options["dry-run"] || options.mode))
1536
+ throw new Error("--dry-run and --mode require --output for import");
1537
+ if (options.force)
1538
+ throw new Error(
1539
+ "Import requires a new output directory. --force is not supported."
1540
+ );
1541
+ const header = headerFile ? (await (0, import_promises3.readFile)((0, import_node_path3.resolve)(cwd, headerFile), "utf8")).replace(
1542
+ /\r?\n$/,
1543
+ ""
1544
+ ) : positional;
1545
+ const parsed = importHeader(header);
1546
+ const draft = importedPolicyToDraft(parsed);
1547
+ if (output) {
1548
+ const mode = option(options, "mode") ?? "report-only";
1549
+ if (mode !== "enforce" && mode !== "report-only")
1550
+ throw new Error("--mode must be enforce or report-only");
1551
+ const files = importDraftFiles(draft, mode);
1552
+ const destination = (0, import_node_path3.resolve)(cwd, output);
1553
+ if (!options["dry-run"]) await writeImportDraft(destination, files);
1554
+ io.out(
1555
+ `${options["dry-run"] ? "Would write to" : "Wrote to"} ${destination}:
1556
+ ${Array.from(files.keys()).join("\n")}
1557
+ Review the draft and assign owners before use.`
1558
+ );
1559
+ return 0;
1560
+ }
1561
+ io.out(
1562
+ JSON.stringify(
1563
+ {
1564
+ draft,
1565
+ warnings: parsed.warnings,
1566
+ note: "Review the draft before saving; no files were written."
1567
+ },
1568
+ null,
1569
+ 2
1570
+ )
1571
+ );
1572
+ return 0;
1573
+ }
1574
+ const defaultConfig = (0, import_node_fs.existsSync)((0, import_node_path3.resolve)(cwd, "csp.config.ts")) ? "csp.config.ts" : "csp.config.mjs";
1575
+ const path = (0, import_node_path3.resolve)(cwd, option(options, "config") ?? defaultConfig);
1576
+ const module2 = await loadConfig(path);
1577
+ const candidate = module2.default ?? module2.policy;
1578
+ const policy = candidate && typeof candidate === "object" && "policy" in candidate ? candidate.policy : candidate;
1579
+ if (!isPolicy(policy))
1580
+ throw new Error(
1581
+ "Config must export a Policy as default, as policy, or as default.policy"
1582
+ );
1583
+ if (command === "diff") {
1584
+ const ref = option(options, "base");
1585
+ if (!ref)
1586
+ throw new Error(
1587
+ "diff requires --base <git-ref> and a committed csp.snapshot.json at the repository root"
1588
+ );
1589
+ const result = diffSnapshot(await readGitSnapshot(ref, cwd), policy);
1590
+ io.out(JSON.stringify(result, null, 2));
1591
+ return 0;
1592
+ }
1593
+ if (command === "check-reports") {
1594
+ if (!positional) throw new Error("check-reports requires a JSON file");
1595
+ const contents = await (0, import_promises3.readFile)((0, import_node_path3.resolve)(cwd, positional), "utf8");
1596
+ const results = replayReports(
1597
+ policy.toObject(),
1598
+ parseViolationReports(contents)
1599
+ );
1600
+ io.out(JSON.stringify(results, null, 2));
1601
+ return results.some(({ result }) => result.status !== "allowed") ? 1 : 0;
1602
+ }
1603
+ if (command === "print") {
1604
+ io.out(
1605
+ policy.toHeader({
1606
+ ...option(options, "nonce") ? { nonce: option(options, "nonce") } : {},
1607
+ pretty: Boolean(options.pretty)
1608
+ })
1609
+ );
1610
+ return 0;
1611
+ }
1612
+ if (command === "explain") {
1613
+ const directive = option(options, "directive"), ruleSet = option(options, "rule-set");
1614
+ const rows = policy.explain().filter(
1615
+ (row) => (!directive || row.directive === directive) && (!ruleSet || row.ruleSet === ruleSet)
1616
+ );
1617
+ io.out(JSON.stringify(rows, null, 2));
1618
+ return 0;
1619
+ }
1620
+ if (command === "audit") {
1621
+ const threshold = option(options, "fail-on") ?? "high";
1622
+ if (!Object.hasOwn(severities, threshold))
1623
+ throw new Error("--fail-on must be high, medium, low or info");
1624
+ const findings = audit(policy);
1625
+ io.out(JSON.stringify(findings, null, 2));
1626
+ return findings.some(
1627
+ (finding) => severities[finding.severity] >= severities[threshold]
1628
+ ) ? 1 : 0;
1629
+ }
1630
+ const file = (0, import_node_path3.resolve)(cwd, option(options, "file") ?? "csp.snapshot.json");
1631
+ const expected = `${JSON.stringify(cspSnapshot(policy), null, 2)}
1632
+ `;
1633
+ if (options.update) {
1634
+ await (0, import_promises3.writeFile)(file, expected, "utf8");
1635
+ io.out(`Updated ${file}`);
1636
+ return 0;
1637
+ }
1638
+ let actual;
1639
+ try {
1640
+ actual = await (0, import_promises3.readFile)(file, "utf8");
1641
+ } catch {
1642
+ throw new Error(
1643
+ `Snapshot not found: ${file}. Run snapshot --update to create it.`
1644
+ );
1645
+ }
1646
+ if (actual !== expected) {
1647
+ io.error(
1648
+ "CSP snapshot differs. Review the policy and run snapshot --update."
1649
+ );
1650
+ return 1;
1651
+ }
1652
+ io.out("CSP snapshot matches.");
1653
+ return 0;
1654
+ } catch (error) {
1655
+ io.error(error instanceof Error ? error.message : String(error));
1656
+ return 1;
1657
+ }
1658
+ }
1659
+
1660
+ // src/cli/bin.ts
1661
+ void runCli(process.argv.slice(2), {
1662
+ out: (message) => console.log(message),
1663
+ error: (message) => console.error(message)
1664
+ }).then((code) => {
1665
+ process.exitCode = code;
1666
+ });
1667
+ //# sourceMappingURL=cli.cjs.map