@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.js ADDED
@@ -0,0 +1,637 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ definePolicy,
4
+ diffPolicies,
5
+ importHeader,
6
+ importedPolicyToDraft,
7
+ parseViolationReports,
8
+ replayReports,
9
+ sourceExpressions
10
+ } from "./chunk-TE3J7Y25.js";
11
+ import {
12
+ cspSnapshot
13
+ } from "./chunk-MDUQKU6Y.js";
14
+ import {
15
+ audit
16
+ } from "./chunk-KWWYRHIP.js";
17
+
18
+ // src/cli/index.ts
19
+ import { readFile, writeFile as writeFile2 } from "fs/promises";
20
+ import { existsSync } from "fs";
21
+ import { resolve, extname } from "path";
22
+ import { pathToFileURL } from "url";
23
+ import { createJiti } from "jiti";
24
+
25
+ // src/cli/init.ts
26
+ import { lstat, mkdir, writeFile } from "fs/promises";
27
+ import { join } from "path";
28
+ async function initProject(cwd, options = {}) {
29
+ const language = options.language ?? "javascript";
30
+ if (!["javascript", "typescript"].includes(language))
31
+ throw new Error("language must be javascript or typescript");
32
+ const mode = options.mode ?? "report-only";
33
+ if (!["enforce", "report-only"].includes(mode))
34
+ throw new Error("mode must be enforce or report-only");
35
+ const apiOrigins = [...new Set(options.apiOrigins ?? [])];
36
+ for (const origin of apiOrigins) {
37
+ let parsed;
38
+ try {
39
+ parsed = new URL(origin);
40
+ } catch {
41
+ throw new Error(`Invalid API origin: ${origin}`);
42
+ }
43
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.origin !== origin)
44
+ throw new Error(
45
+ `API origins must be HTTP(S) origins without paths, credentials or trailing slash: ${origin}`
46
+ );
47
+ }
48
+ if (options.reportUri) {
49
+ let parsed;
50
+ try {
51
+ parsed = new URL(options.reportUri);
52
+ } catch {
53
+ throw new Error("Invalid reporting URL");
54
+ }
55
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash)
56
+ throw new Error(
57
+ "Reporting URL must be an HTTP(S) URL without credentials or fragment"
58
+ );
59
+ }
60
+ const review = new Date(options.now ?? /* @__PURE__ */ new Date());
61
+ review.setUTCFullYear(review.getUTCFullYear() + 1);
62
+ const reviewBy = review.toISOString().slice(0, 10);
63
+ const policy = definePolicy({
64
+ mode,
65
+ ...options.reportUri ? { reporting: { uri: options.reportUri } } : {},
66
+ base: {
67
+ default: [sourceExpressions.self],
68
+ scripts: [
69
+ sourceExpressions.self,
70
+ sourceExpressions.nonce,
71
+ sourceExpressions.strictDynamic
72
+ ],
73
+ objects: [sourceExpressions.none],
74
+ baseUri: [sourceExpressions.self],
75
+ frameAncestors: [sourceExpressions.none],
76
+ upgradeInsecureRequests: true
77
+ },
78
+ ruleSets: [
79
+ {
80
+ name: "App assets",
81
+ purpose: "Images used by the application",
82
+ owner: "TODO: assign owner",
83
+ reviewBy,
84
+ rules: { images: [sourceExpressions.self, "data:", "blob:"] }
85
+ },
86
+ ...apiOrigins.length ? [
87
+ {
88
+ name: "App API",
89
+ purpose: "Application API connections",
90
+ owner: "TODO: assign owner",
91
+ reviewBy,
92
+ rules: { connect: apiOrigins }
93
+ }
94
+ ] : []
95
+ ]
96
+ });
97
+ const extension = language === "typescript" ? "ts" : "mjs";
98
+ const importExtension = language === "typescript" ? "" : ".mjs";
99
+ const apiImport = apiOrigins.length ? `import { appApi } from './rule-sets/app-api${importExtension}';
100
+ ` : "";
101
+ const reporting = options.reportUri ? ` reporting: { uri: ${JSON.stringify(options.reportUri)} },
102
+ ` : "";
103
+ const apiTest = apiOrigins.length ? ` expect(policy).toAllow('connect', ${JSON.stringify(apiOrigins[0] + "/")}, { origin: 'https://site.example', redirectCount: 0 });
104
+ ` : "";
105
+ const files = {
106
+ [`csp.config.${extension}`]: `export { policy as default } from './csp/policy${importExtension}';
107
+ `,
108
+ [`csp/policy.${extension}`]: `import { definePolicy, sourceExpressions } from '@jamesbrightman/pretty-csp';
109
+ import { appAssets } from './rule-sets/app-assets${importExtension}';
110
+ ${apiImport}
111
+ export const policy = definePolicy({
112
+ mode: ${JSON.stringify(mode)},
113
+ ${reporting} base: { default: [sourceExpressions.self], scripts: [sourceExpressions.self, sourceExpressions.nonce, sourceExpressions.strictDynamic], objects: [sourceExpressions.none], baseUri: [sourceExpressions.self], frameAncestors: [sourceExpressions.none], upgradeInsecureRequests: true },
114
+ ruleSets: [appAssets${apiOrigins.length ? ", appApi" : ""}],
115
+ });
116
+ `,
117
+ [`csp/rule-sets/app-assets.${extension}`]: `import { defineRuleSet, sourceExpressions } from '@jamesbrightman/pretty-csp';
118
+
119
+ 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:'] } });
120
+ `,
121
+ [`csp/policy.test.${extension}`]: `import { readFile } from 'node:fs/promises';
122
+ import { expect, test } from 'vitest';
123
+ import { cspMatchers, cspSnapshot } from '@jamesbrightman/pretty-csp/testing';
124
+ import { policy } from './policy${importExtension}';
125
+
126
+ expect.extend(cspMatchers);
127
+ test('blocks untrusted connections and has no high-risk findings', () => {
128
+ ${apiTest} expect(policy).toBlock('connect', 'https://untrusted.example/', { origin: 'https://site.example', redirectCount: 0 });
129
+ expect(policy).toPassAudit({ maxSeverity: 'low' });
130
+ });
131
+ test('matches the reviewed CSP snapshot', async () => {
132
+ const snapshot = JSON.parse(await readFile(new URL('../csp.snapshot.json', import.meta.url), 'utf8'));
133
+ expect(policy).toMatchCspSnapshot(snapshot);
134
+ });
135
+ `,
136
+ "csp.snapshot.json": `${JSON.stringify(cspSnapshot(policy), null, 2)}
137
+ `
138
+ };
139
+ if (apiOrigins.length)
140
+ files[`csp/rule-sets/app-api.${extension}`] = `import { defineRuleSet } from '@jamesbrightman/pretty-csp';
141
+
142
+ export const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API connections', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { connect: ${JSON.stringify(apiOrigins)} } });
143
+ `;
144
+ async function stat(path) {
145
+ try {
146
+ return await lstat(path);
147
+ } catch (error) {
148
+ if (error.code === "ENOENT") return void 0;
149
+ throw error;
150
+ }
151
+ }
152
+ for (const directory of ["csp", "csp/rule-sets"]) {
153
+ const dir = await stat(join(cwd, directory));
154
+ if (dir?.isSymbolicLink() || dir && !dir.isDirectory())
155
+ throw new Error(`${directory} must be a directory and not a symlink`);
156
+ }
157
+ for (const file of Object.keys(files)) {
158
+ const current = await stat(join(cwd, file));
159
+ if (current?.isSymbolicLink() || current && !current.isFile())
160
+ throw new Error(`Refusing non-file or symlink: ${file}`);
161
+ if (current && !options.force)
162
+ throw new Error(
163
+ `File already exists: ${file}. Use --force to replace it.`
164
+ );
165
+ }
166
+ if (!options.dryRun) {
167
+ await mkdir(join(cwd, "csp/rule-sets"), { recursive: true });
168
+ for (const [file, content] of Object.entries(files))
169
+ await writeFile(join(cwd, file), content, {
170
+ encoding: "utf8",
171
+ flag: options.force ? "w" : "wx"
172
+ });
173
+ }
174
+ return Object.keys(files);
175
+ }
176
+
177
+ // src/cli/import.ts
178
+ import { mkdir as mkdir2, open, rmdir, unlink } from "fs/promises";
179
+ import { join as join2 } from "path";
180
+ import { parse } from "tldts";
181
+ function registrableDomain(source) {
182
+ const host = /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:\*\.)?([a-z0-9-]+(?:\.[a-z0-9-]+)+)(?=[:/]|$)/i.exec(
183
+ source
184
+ )?.[1];
185
+ if (!host) return void 0;
186
+ const { domain, isIcann, isPrivate } = parse(host, {
187
+ allowPrivateDomains: true
188
+ });
189
+ return domain && (isIcann || isPrivate) ? domain.toLowerCase() : void 0;
190
+ }
191
+ function importDraftFiles(draft, mode) {
192
+ const groups = /* @__PURE__ */ new Map();
193
+ const unassigned = {};
194
+ for (const [directive, entries] of Object.entries(
195
+ draft.base?.directives ?? {}
196
+ )) {
197
+ rejectCapturedNonces(entries, directive);
198
+ }
199
+ for (const ruleSet of draft.ruleSets ?? []) {
200
+ for (const [directive, entries] of Object.entries(
201
+ ruleSet.rules.directives ?? {}
202
+ )) {
203
+ rejectCapturedNonces(entries, directive);
204
+ for (const entry of entries) {
205
+ const domain = registrableDomain(
206
+ typeof entry === "string" ? entry : entry.source
207
+ );
208
+ let directives = unassigned;
209
+ if (domain) {
210
+ directives = groups.get(domain) ?? {};
211
+ groups.set(domain, directives);
212
+ }
213
+ (directives[directive] ??= []).push(entry);
214
+ }
215
+ }
216
+ }
217
+ const files = /* @__PURE__ */ new Map();
218
+ const imports = [];
219
+ const names = [];
220
+ const addRuleSet = (filename, ruleSet) => {
221
+ const path = `rule-sets/${filename}.mjs`;
222
+ const name = `ruleSet${names.length + 1}`;
223
+ files.set(
224
+ path,
225
+ `import { defineRuleSet } from '@jamesbrightman/pretty-csp';
226
+
227
+ export default defineRuleSet(${JSON.stringify(ruleSet, null, 2)});
228
+ `
229
+ );
230
+ imports.push(`import ${name} from './${path}';`);
231
+ names.push(name);
232
+ };
233
+ const sortedGroups = Array.from(groups).sort(
234
+ ([first], [second]) => first.localeCompare(second, "en")
235
+ );
236
+ for (const [domain, directives] of sortedGroups) {
237
+ addRuleSet(`domain-${domain}`, {
238
+ name: domain,
239
+ purpose: "Imported domain group. Confirm purpose and owner before use.",
240
+ rules: { directives }
241
+ });
242
+ }
243
+ if (Object.keys(unassigned).length) {
244
+ addRuleSet("unassigned", {
245
+ name: "Unassigned sources",
246
+ purpose: "Imported sources that need manual grouping and review.",
247
+ rules: { directives: unassigned }
248
+ });
249
+ }
250
+ files.set(
251
+ "csp.config.mjs",
252
+ [
253
+ "import { definePolicy } from '@jamesbrightman/pretty-csp';",
254
+ ...imports,
255
+ "",
256
+ "// Review this draft before using it in an application.",
257
+ "export default definePolicy({",
258
+ ` mode: ${JSON.stringify(mode)},`,
259
+ ` base: ${JSON.stringify(draft.base ?? {}, null, 2).replace(/\n/g, "\n ")},`,
260
+ ` ruleSets: [${names.join(", ")}],`,
261
+ "});",
262
+ ""
263
+ ].join("\n")
264
+ );
265
+ return files;
266
+ }
267
+ function rejectCapturedNonces(entries, directive) {
268
+ if (entries.some(
269
+ (entry) => /^'nonce-/i.test(typeof entry === "string" ? entry : entry.source)
270
+ )) {
271
+ throw new Error(
272
+ `Directive ${directive} contains a captured nonce. Migrate it separately using a fresh nonce per response.`
273
+ );
274
+ }
275
+ }
276
+ async function writeImportDraft(output, files) {
277
+ try {
278
+ await mkdir2(output);
279
+ } catch (error) {
280
+ if (error.code === "EEXIST")
281
+ throw new Error(
282
+ `Import output already exists: ${output}. Choose a new directory.`
283
+ );
284
+ throw error;
285
+ }
286
+ const createdFiles = [];
287
+ let createdRuleSets = false;
288
+ try {
289
+ if (files.size > 1) {
290
+ await mkdir2(join2(output, "rule-sets"));
291
+ createdRuleSets = true;
292
+ }
293
+ for (const [name, content] of files) {
294
+ const path = join2(output, name);
295
+ const file = await open(path, "wx");
296
+ createdFiles.push(path);
297
+ try {
298
+ await file.writeFile(content, "utf8");
299
+ } finally {
300
+ await file.close();
301
+ }
302
+ }
303
+ } catch (error) {
304
+ try {
305
+ for (const path of createdFiles) await unlink(path);
306
+ if (createdRuleSets) await rmdir(join2(output, "rule-sets"));
307
+ await rmdir(output);
308
+ } catch {
309
+ throw new Error(
310
+ `Import failed and may have left partial files in ${output}`,
311
+ { cause: error }
312
+ );
313
+ }
314
+ throw error;
315
+ }
316
+ }
317
+
318
+ // src/cli/diff.ts
319
+ import { execFile } from "child_process";
320
+ import { promisify } from "util";
321
+ import { z } from "zod";
322
+ var snapshotSchema = z.object({
323
+ schemaVersion: z.literal(1),
324
+ mode: z.enum(["enforce", "report-only"]),
325
+ directives: z.record(
326
+ z.string().regex(/^[a-z][a-z0-9-]*$/),
327
+ z.array(z.string())
328
+ ),
329
+ contributors: z.array(
330
+ z.object({
331
+ directive: z.string(),
332
+ source: z.string(),
333
+ ruleSet: z.string(),
334
+ reason: z.string().optional()
335
+ }).strict()
336
+ )
337
+ }).strict();
338
+ async function readGitSnapshot(ref, cwd) {
339
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._/~^-]*$/.test(ref))
340
+ throw new Error("Invalid Git ref");
341
+ const exec = promisify(execFile);
342
+ try {
343
+ const { stdout } = await exec(
344
+ "git",
345
+ ["show", "--no-ext-diff", "--no-textconv", `${ref}:csp.snapshot.json`],
346
+ { cwd, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }
347
+ );
348
+ return stdout;
349
+ } catch {
350
+ throw new Error(
351
+ "Could not read csp.snapshot.json at the Git ref; commit a version 1 snapshot at the repository root."
352
+ );
353
+ }
354
+ }
355
+ function diffSnapshot(json, current) {
356
+ let data;
357
+ try {
358
+ data = JSON.parse(json);
359
+ } catch {
360
+ throw new Error("Invalid snapshot JSON");
361
+ }
362
+ const parsed = snapshotSchema.safeParse(data);
363
+ if (!parsed.success)
364
+ throw new Error("Invalid or unsupported CSP snapshot format");
365
+ const snapshot = parsed.data;
366
+ for (const row of snapshot.contributors) {
367
+ if (!snapshot.directives[row.directive]?.includes(row.source))
368
+ throw new Error("Snapshot contributor does not match a directive source");
369
+ }
370
+ for (const [directive, sources] of Object.entries(snapshot.directives)) {
371
+ if (directive === "report-uri" || directive === "report-to") continue;
372
+ for (const source of sources) {
373
+ if (!snapshot.contributors.some(
374
+ (row) => row.directive === directive && row.source === source
375
+ ))
376
+ throw new Error("Snapshot source has no contributor");
377
+ }
378
+ }
379
+ const previous = {
380
+ config: { mode: snapshot.mode },
381
+ toObject: () => snapshot.directives,
382
+ explain: () => snapshot.contributors
383
+ };
384
+ return diffPolicies(previous, current);
385
+ }
386
+
387
+ // src/cli/index.ts
388
+ var help = "Usage: pretty-csp <init|print|explain|audit|snapshot|diff|import|check-reports> [--config path] [options]";
389
+ var importHelp = "Usage: pretty-csp import <header> | --file <header-file> [--output <new-directory> [--dry-run] [--mode <report-only|enforce>]]";
390
+ var severities = {
391
+ info: 0,
392
+ low: 1,
393
+ medium: 2,
394
+ high: 3
395
+ };
396
+ function argsFor(args) {
397
+ const [command = "help", ...rest] = args;
398
+ const options = {};
399
+ let positional;
400
+ const flags = /* @__PURE__ */ new Set([
401
+ "pretty",
402
+ "update",
403
+ "help",
404
+ "yes",
405
+ "dry-run",
406
+ "force"
407
+ ]);
408
+ const values = /* @__PURE__ */ new Set([
409
+ "config",
410
+ "nonce",
411
+ "directive",
412
+ "rule-set",
413
+ "fail-on",
414
+ "file",
415
+ "output",
416
+ "base",
417
+ "language",
418
+ "api-origins",
419
+ "report-uri",
420
+ "mode"
421
+ ]);
422
+ for (let i = 0; i < rest.length; i++) {
423
+ const arg = rest[i];
424
+ if (!arg.startsWith("--")) {
425
+ if (!["import", "check-reports"].includes(command) || positional !== void 0)
426
+ throw new Error(`Unexpected argument: ${arg}`);
427
+ positional = arg;
428
+ continue;
429
+ }
430
+ const key = arg.slice(2);
431
+ if (flags.has(key)) options[key] = true;
432
+ else if (values.has(key)) {
433
+ const value = rest[++i];
434
+ if (!value || value.startsWith("--"))
435
+ throw new Error(`--${key} requires a value`);
436
+ options[key] = value;
437
+ } else throw new Error(`Unknown option --${key}`);
438
+ }
439
+ return {
440
+ command,
441
+ options,
442
+ ...positional === void 0 ? {} : { positional }
443
+ };
444
+ }
445
+ function option(options, name) {
446
+ return typeof options[name] === "string" ? options[name] : void 0;
447
+ }
448
+ function isPolicy(value) {
449
+ return !!value && typeof value === "object" && ["toHeader", "toObject", "explain", "allows"].every(
450
+ (key) => typeof value[key] === "function"
451
+ ) && "config" in value;
452
+ }
453
+ async function loadConfigFile(path) {
454
+ if ([".ts", ".mts", ".cts"].includes(extname(path).toLowerCase())) {
455
+ const jiti = createJiti(path, { moduleCache: false, fsCache: false });
456
+ return await jiti.import(path);
457
+ }
458
+ return await import(pathToFileURL(path).href);
459
+ }
460
+ async function runCli(args, io, cwd = process.cwd(), loadConfig = loadConfigFile) {
461
+ try {
462
+ const { command, options, positional } = argsFor(args);
463
+ if (command === "help" || options.help) {
464
+ io.out(command === "import" ? importHelp : help);
465
+ return 0;
466
+ }
467
+ if (![
468
+ "init",
469
+ "print",
470
+ "explain",
471
+ "audit",
472
+ "snapshot",
473
+ "diff",
474
+ "import",
475
+ "check-reports"
476
+ ].includes(command))
477
+ throw new Error(`Unsupported command: ${command}. ${help}`);
478
+ if (command === "init") {
479
+ if (!options.yes)
480
+ throw new Error(
481
+ "Use init --yes and optional --language, --api-origins, --report-uri and --mode flags."
482
+ );
483
+ const files = await initProject(cwd, {
484
+ dryRun: Boolean(options["dry-run"]),
485
+ force: Boolean(options.force),
486
+ language: option(options, "language"),
487
+ mode: option(options, "mode"),
488
+ apiOrigins: option(options, "api-origins")?.split(",").map((origin) => origin.trim()),
489
+ reportUri: option(options, "report-uri")
490
+ });
491
+ io.out(
492
+ `${options["dry-run"] ? "Would write" : "Wrote"}:
493
+ ${files.join("\n")}
494
+ Install @jamesbrightman/pretty-csp and Vitest, then configure your server to set policy.headerName and policy.toHeader({ nonce }) on each response.`
495
+ );
496
+ return 0;
497
+ }
498
+ if (command === "import") {
499
+ const headerFile = option(options, "file");
500
+ const output = option(options, "output");
501
+ if (!positional && !headerFile || positional && headerFile)
502
+ throw new Error(
503
+ "import requires a header string or --file, but not both"
504
+ );
505
+ if (!output && (options["dry-run"] || options.mode))
506
+ throw new Error("--dry-run and --mode require --output for import");
507
+ if (options.force)
508
+ throw new Error(
509
+ "Import requires a new output directory. --force is not supported."
510
+ );
511
+ const header = headerFile ? (await readFile(resolve(cwd, headerFile), "utf8")).replace(
512
+ /\r?\n$/,
513
+ ""
514
+ ) : positional;
515
+ const parsed = importHeader(header);
516
+ const draft = importedPolicyToDraft(parsed);
517
+ if (output) {
518
+ const mode = option(options, "mode") ?? "report-only";
519
+ if (mode !== "enforce" && mode !== "report-only")
520
+ throw new Error("--mode must be enforce or report-only");
521
+ const files = importDraftFiles(draft, mode);
522
+ const destination = resolve(cwd, output);
523
+ if (!options["dry-run"]) await writeImportDraft(destination, files);
524
+ io.out(
525
+ `${options["dry-run"] ? "Would write to" : "Wrote to"} ${destination}:
526
+ ${Array.from(files.keys()).join("\n")}
527
+ Review the draft and assign owners before use.`
528
+ );
529
+ return 0;
530
+ }
531
+ io.out(
532
+ JSON.stringify(
533
+ {
534
+ draft,
535
+ warnings: parsed.warnings,
536
+ note: "Review the draft before saving; no files were written."
537
+ },
538
+ null,
539
+ 2
540
+ )
541
+ );
542
+ return 0;
543
+ }
544
+ const defaultConfig = existsSync(resolve(cwd, "csp.config.ts")) ? "csp.config.ts" : "csp.config.mjs";
545
+ const path = resolve(cwd, option(options, "config") ?? defaultConfig);
546
+ const module = await loadConfig(path);
547
+ const candidate = module.default ?? module.policy;
548
+ const policy = candidate && typeof candidate === "object" && "policy" in candidate ? candidate.policy : candidate;
549
+ if (!isPolicy(policy))
550
+ throw new Error(
551
+ "Config must export a Policy as default, as policy, or as default.policy"
552
+ );
553
+ if (command === "diff") {
554
+ const ref = option(options, "base");
555
+ if (!ref)
556
+ throw new Error(
557
+ "diff requires --base <git-ref> and a committed csp.snapshot.json at the repository root"
558
+ );
559
+ const result = diffSnapshot(await readGitSnapshot(ref, cwd), policy);
560
+ io.out(JSON.stringify(result, null, 2));
561
+ return 0;
562
+ }
563
+ if (command === "check-reports") {
564
+ if (!positional) throw new Error("check-reports requires a JSON file");
565
+ const contents = await readFile(resolve(cwd, positional), "utf8");
566
+ const results = replayReports(
567
+ policy.toObject(),
568
+ parseViolationReports(contents)
569
+ );
570
+ io.out(JSON.stringify(results, null, 2));
571
+ return results.some(({ result }) => result.status !== "allowed") ? 1 : 0;
572
+ }
573
+ if (command === "print") {
574
+ io.out(
575
+ policy.toHeader({
576
+ ...option(options, "nonce") ? { nonce: option(options, "nonce") } : {},
577
+ pretty: Boolean(options.pretty)
578
+ })
579
+ );
580
+ return 0;
581
+ }
582
+ if (command === "explain") {
583
+ const directive = option(options, "directive"), ruleSet = option(options, "rule-set");
584
+ const rows = policy.explain().filter(
585
+ (row) => (!directive || row.directive === directive) && (!ruleSet || row.ruleSet === ruleSet)
586
+ );
587
+ io.out(JSON.stringify(rows, null, 2));
588
+ return 0;
589
+ }
590
+ if (command === "audit") {
591
+ const threshold = option(options, "fail-on") ?? "high";
592
+ if (!Object.hasOwn(severities, threshold))
593
+ throw new Error("--fail-on must be high, medium, low or info");
594
+ const findings = audit(policy);
595
+ io.out(JSON.stringify(findings, null, 2));
596
+ return findings.some(
597
+ (finding) => severities[finding.severity] >= severities[threshold]
598
+ ) ? 1 : 0;
599
+ }
600
+ const file = resolve(cwd, option(options, "file") ?? "csp.snapshot.json");
601
+ const expected = `${JSON.stringify(cspSnapshot(policy), null, 2)}
602
+ `;
603
+ if (options.update) {
604
+ await writeFile2(file, expected, "utf8");
605
+ io.out(`Updated ${file}`);
606
+ return 0;
607
+ }
608
+ let actual;
609
+ try {
610
+ actual = await readFile(file, "utf8");
611
+ } catch {
612
+ throw new Error(
613
+ `Snapshot not found: ${file}. Run snapshot --update to create it.`
614
+ );
615
+ }
616
+ if (actual !== expected) {
617
+ io.error(
618
+ "CSP snapshot differs. Review the policy and run snapshot --update."
619
+ );
620
+ return 1;
621
+ }
622
+ io.out("CSP snapshot matches.");
623
+ return 0;
624
+ } catch (error) {
625
+ io.error(error instanceof Error ? error.message : String(error));
626
+ return 1;
627
+ }
628
+ }
629
+
630
+ // src/cli/bin.ts
631
+ void runCli(process.argv.slice(2), {
632
+ out: (message) => console.log(message),
633
+ error: (message) => console.error(message)
634
+ }).then((code) => {
635
+ process.exitCode = code;
636
+ });
637
+ //# sourceMappingURL=cli.js.map