@jamesbrightman/pretty-csp 0.1.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # pretty-csp
2
2
 
3
+ ## 0.2.0
4
+
5
+ Create readable policies in TypeScript, extend them with reusable rule sets, and test the requests they allow. This release simplifies the API around those workflows and includes breaking changes from 0.1.0.
6
+
7
+ ### Added and improved
8
+
9
+ - Add several rule sets in one call: `policy.withRuleSet([imageCdn, appApi])`. Single rule sets, readonly arrays, and array spreads are supported. The entire update is validated together, and invalid or duplicate rule sets leave the original policy unchanged.
10
+ - Use TypeScript throughout CLI starters and integration examples. The playground accepts type annotations, type-only imports, assertions, and `satisfies` expressions in policy declarations.
11
+ - Export `CspAssertions` from the testing entry point and generate `csp/vitest.d.ts` so starter tests type-check with custom matchers.
12
+ - Try policy creation, extension, and request tests in the interactive playground, with editable policy code and a formatted response-header preview.
13
+ - Expand the documentation with API examples, optional file layouts, and Node, Express, Next.js, and vanilla React integrations. Policies can live anywhere in an application and be kept in one file or split into rule-set modules.
14
+
15
+ ### Fixed
16
+
17
+ - Make `pretty-csp --help` print usage and exit successfully, matching the documented command.
18
+
19
+ ### Breaking changes
20
+
21
+ - Replace `sourceExpressions` and `NONCE_PLACEHOLDER` with named uppercase keyword exports.
22
+ - Remove delivery mode: the `mode` option, `init --mode`, and `policy.headerName`. Set the `Content-Security-Policy` response header explicitly with `policy.toHeader()`.
23
+ - Change policy snapshots to schema version 2 without a delivery-mode field.
24
+ - Generate TypeScript starter files only and remove `init --language`. The default CLI configuration is `csp.config.ts`.
25
+ - Remove header import: `pretty-csp import`, `importHeader`, `serializeImportedPolicy`, and `importedPolicyToDraft`. Create policies with `definePolicy()` and `defineRuleSet()`.
26
+ - Remove policy comparison: `pretty-csp diff`, `diffPolicies`, `PolicyDiff`, and `PolicyChange`. Review policy changes with snapshots and version control.
27
+ - Remove violation-report replay: `pretty-csp check-reports`, `policy.check()`, `parseViolationReports`, `replayReports`, `ViolationReport`, and `ReplayResult`. Test explicit requests with `policy.allows()` or the testing matchers.
28
+ - Remove `policy.toMetaContent()`. Deliver the policy through the response header.
29
+
30
+ ### Upgrade from 0.1.0
31
+
32
+ Replace source-expression imports using this mapping:
33
+
34
+ | Previous expression | Named export |
35
+ | ---------------------------------------------- | ------------------ |
36
+ | `sourceExpressions.self` | `SELF` |
37
+ | `sourceExpressions.none` | `NONE` |
38
+ | `sourceExpressions.nonce`, `NONCE_PLACEHOLDER` | `NONCE` |
39
+ | `sourceExpressions.strictDynamic` | `STRICT_DYNAMIC` |
40
+ | `sourceExpressions.reportSample` | `REPORT_SAMPLE` |
41
+ | `sourceExpressions.wasmUnsafeEval` | `WASM_UNSAFE_EVAL` |
42
+
43
+ Remove `mode` from existing configurations; it is rejected as an unknown property. Set the header directly:
44
+
45
+ ```ts
46
+ response.setHeader('Content-Security-Policy', policy.toHeader());
47
+ ```
48
+
49
+ If the policy contains `NONCE`, generate a fresh nonce per response and pass it to both `policy.toHeader({ nonce })` and the intended script elements. Reporting endpoint configuration remains supported for enforced policies.
50
+
51
+ For existing `.mjs` starters, rename policy and config files to `.ts` and use extensionless local imports, or select an existing config explicitly with `--config path/to/policy.ts`. Review and regenerate committed snapshots with `pretty-csp snapshot --update` or your test runner's snapshot update command.
52
+
3
53
  ## 0.1.0
4
54
 
5
55
  First public release as `@jamesbrightman/pretty-csp`. The installed command is `pretty-csp`.
package/README.md CHANGED
@@ -1,62 +1,96 @@
1
1
  # pretty-csp
2
2
 
3
- ![pretty-csp — a friendlier look at Content Security Policy](website/static/img/pretty-csp-logo.svg)
3
+ ![pretty-csp: CSP as code](website/static/img/pretty-csp-logo.svg)
4
4
 
5
- Build Content Security Policies in TypeScript or JavaScript. Group permissions by feature, generate the response header, and review which sources each rule set adds.
5
+ `pretty-csp` is CSP as code for TypeScript applications. Keep your policy alongside application code, compose permissions from named rule sets, and test the requests you expect to allow or block. Generate the response header from that definition.
6
6
 
7
7
  - **Readable.** Give each rule set a name, purpose, and owner. Use `policy.explain()` to trace a source to every rule set that contributed it.
8
- - **Extendable.** Add or remove reusable rule sets as features change. Write custom audit rules for your team's conventions.
9
- - **Testable.** Assert which requests should pass, check advisory audit findings, and review policy diffs and snapshots in CI.
8
+ - **Extendable.** Add reusable rule sets one at a time or together with `policy.withRuleSet([imageCdn, appApi])`. Remove them as features change, and write custom audit rules for your team's conventions.
9
+ - **Testable.** Assert which requests should pass, check advisory audit findings, and review policy snapshots in CI.
10
10
 
11
- ## Example
11
+ ## Define and compose a policy
12
+
13
+ Save this as `src/security/policy.ts`, or choose a location that suits your application. Commit it to version control with the feature code that needs these permissions.
12
14
 
13
15
  ```ts
14
16
  import {
15
17
  definePolicy,
16
18
  defineRuleSet,
17
- sourceExpressions,
19
+ SELF,
20
+ NONE,
18
21
  } from '@jamesbrightman/pretty-csp';
19
22
 
20
- const imageCdn = defineRuleSet({
23
+ export const imageCdn = defineRuleSet({
21
24
  name: 'Image CDN',
22
25
  purpose: 'Serve product images',
23
26
  owner: 'web',
24
27
  rules: { images: ['https://cdn.example.com'] },
25
28
  });
26
29
 
27
- const policy = definePolicy({
30
+ const basePolicy = definePolicy({
28
31
  base: {
29
- default: [sourceExpressions.self],
30
- images: [sourceExpressions.self],
31
- objects: [sourceExpressions.none],
32
- baseUri: [sourceExpressions.self],
33
- frameAncestors: [sourceExpressions.none],
32
+ default: [SELF],
33
+ images: [SELF],
34
+ objects: [NONE],
35
+ baseUri: [SELF],
36
+ frameAncestors: [NONE],
34
37
  },
35
- ruleSets: [imageCdn],
36
- mode: 'report-only',
37
38
  });
38
39
 
39
- console.log(policy.headerName, policy.toHeader());
40
- console.table(policy.explain());
40
+ export const policy = basePolicy.withRuleSet(imageCdn);
41
+ ```
42
+
43
+ Use `basePolicy.withRuleSet([imageCdn, appApi])` to compose several rule sets in one call. Each rule set records the feature's permissions and purpose; `policy.explain()` shows which rule set contributed each source.
44
+
45
+ ## Test the permissions you intend
41
46
 
42
- const image = policy.allows('img-src', 'https://cdn.example.com/product.jpg', {
43
- origin: 'https://shop.example.com',
44
- redirectCount: 0,
47
+ Import the same policy definition into your tests. Save this beside it as `src/security/policy.test.ts` and run it with `npx tsx --test src/security/policy.test.ts` after adding `tsx` as a dev dependency.
48
+
49
+ ```ts
50
+ import assert from 'node:assert/strict';
51
+ import { test } from 'node:test';
52
+ import { policy } from './policy';
53
+
54
+ const context = { origin: 'https://shop.example.com', redirectCount: 0 };
55
+
56
+ test('permits catalog images and blocks an unrelated origin', () => {
57
+ assert.equal(
58
+ policy.allows('img-src', 'https://cdn.example.com/product.jpg', context)
59
+ .status,
60
+ 'allowed',
61
+ );
62
+ assert.equal(
63
+ policy.allows('img-src', 'https://other.example.com/product.jpg', context)
64
+ .status,
65
+ 'blocked',
66
+ );
45
67
  });
46
- console.log(image.status); // allowed
47
68
  ```
48
69
 
70
+ Run policy tests with your application tests in CI. Review a feature's rule-set changes, request assertions, and policy snapshots together in the same pull request.
71
+
72
+ ## Generate the response header
73
+
74
+ Your server imports the policy and generates the header value when building a response:
75
+
76
+ ```ts
77
+ response.setHeader('Content-Security-Policy', policy.toHeader());
78
+ ```
79
+
80
+ The TypeScript definition is the source of truth. The header string is its generated output. See the [integration examples](https://jamesbrightman.github.io/pretty-csp/docs/integrations) for server and static-host setups.
81
+
49
82
  Your server sets the header, renders per-response nonces when needed, and configures reporting. Request checks can return `indeterminate` when context is missing. Verify your rollout in the browsers you support.
50
83
 
51
84
  ## Documentation
52
85
 
53
- To use a published release, install it with `npm install @jamesbrightman/pretty-csp`. To build from source and run a complete example, follow the [Getting started guide](https://jamesbrightman.github.io/pretty-csp/docs/getting-started).
86
+ Install the package with `npm install @jamesbrightman/pretty-csp`, then follow the [Getting started guide](https://jamesbrightman.github.io/pretty-csp/docs/getting-started) to create your first policy.
54
87
 
55
88
  - [Concepts](https://jamesbrightman.github.io/pretty-csp/docs/concepts) explains how rule sets merge and how to review a contribution.
56
- - [API reference](https://jamesbrightman.github.io/pretty-csp/docs/api) covers policy creation, rendering, audit, diff, report replay, and import.
89
+ - [Files and project structure](https://jamesbrightman.github.io/pretty-csp/docs/files) explains the one-file setup, optional rule-set modules, and every file created by `init`.
90
+ - [API reference](https://jamesbrightman.github.io/pretty-csp/docs/api) covers policy creation, extension, header generation, request checks, and audits.
57
91
  - [Testing policies](https://jamesbrightman.github.io/pretty-csp/docs/testing) includes Node and Vitest examples.
58
92
  - [Integrations](https://jamesbrightman.github.io/pretty-csp/docs/integrations) shows how to set the header and render a nonce.
59
- - [CLI](https://jamesbrightman.github.io/pretty-csp/docs/cli) covers snapshots and importing an existing header into grouped draft files.
93
+ - [CLI](https://jamesbrightman.github.io/pretty-csp/docs/cli) covers starter policies, header output, explanations, audits, and snapshots.
60
94
 
61
95
  Use `pnpm docs:dev` for the local docs site or `pnpm docs:build` for the static output in `website/build`.
62
96
 
@@ -64,6 +98,8 @@ Use `pnpm docs:dev` for the local docs site or `pnpm docs:build` for the static
64
98
 
65
99
  The package and repository toolchain support Node.js 20 or newer. Use pnpm 10.17.1.
66
100
 
101
+ All new commits and PR titles use Conventional Commits. See [CONTRIBUTING.md](CONTRIBUTING.md) for the format and local hook setup.
102
+
67
103
  ```sh
68
104
  pnpm install --frozen-lockfile
69
105
  pnpm format:check
@@ -74,4 +110,4 @@ pnpm test:coverage
74
110
  pnpm build
75
111
  ```
76
112
 
77
- The API is experimental. See the [release guide](https://github.com/JamesBrightman/pretty-csp/blob/main/RELEASE.md) and [delivery plan](https://github.com/JamesBrightman/pretty-csp/blob/main/PLAN.md) for publishing and browser compatibility work.
113
+ The [maintainer release guide](https://github.com/JamesBrightman/pretty-csp/blob/main/RELEASE.md) covers package verification and publishing.
@@ -1,3 +1,29 @@
1
+ // src/keywords.ts
2
+ var SELF = "'self'";
3
+ var NONE = "'none'";
4
+ var NONCE = "'nonce-{nonce}'";
5
+ var STRICT_DYNAMIC = "'strict-dynamic'";
6
+ var REPORT_SAMPLE = "'report-sample'";
7
+ var WASM_UNSAFE_EVAL = "'wasm-unsafe-eval'";
8
+ function generateNonce() {
9
+ const bytes = new Uint8Array(16);
10
+ globalThis.crypto.getRandomValues(bytes);
11
+ return btoa(String.fromCharCode(...bytes));
12
+ }
13
+ var unsafeInline = ({ reason }) => ({
14
+ source: "'unsafe-inline'",
15
+ reason
16
+ });
17
+ var unsafeEval = ({ reason }) => ({
18
+ source: "'unsafe-eval'",
19
+ reason
20
+ });
21
+ var unsafeHashes = ({ reason }) => ({
22
+ source: "'unsafe-hashes'",
23
+ reason
24
+ });
25
+ var cspHash = (algorithm, digest) => `'${algorithm}-${digest}'`;
26
+
1
27
  // src/schemas.ts
2
28
  import { z } from "zod";
3
29
  var resourceDirectives = {
@@ -27,11 +53,10 @@ var keywords = /* @__PURE__ */ new Set([
27
53
  "'wasm-unsafe-eval'",
28
54
  ...risky
29
55
  ]);
30
- var NONCE_PLACEHOLDER = "'nonce-{nonce}'";
31
56
  function isSource(value) {
32
57
  if (!value || /[\x00-\x20\x7f;,]/.test(value) || /^[a-z][a-z0-9+.-]*\/\//i.test(value))
33
58
  return false;
34
- if (keywords.has(value.toLowerCase()) || value === NONCE_PLACEHOLDER || value === "*" || /^[a-z][a-z0-9+.-]*:\/\/\*(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(value))
59
+ if (keywords.has(value.toLowerCase()) || value === NONCE || value === "*" || /^[a-z][a-z0-9+.-]*:\/\/\*(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(value))
35
60
  return true;
36
61
  if (/^'(nonce-[A-Za-z0-9+/_-]+={0,2}|sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2})'$/i.test(
37
62
  value
@@ -129,8 +154,7 @@ var reportingSchema = z.object({
129
154
  var policyConfigSchema = z.object({
130
155
  base: baseSchema.default({}),
131
156
  ruleSets: z.array(ruleSetSchema).default([]),
132
- reporting: reportingSchema.optional(),
133
- mode: z.enum(["enforce", "report-only"]).default("enforce")
157
+ reporting: reportingSchema.optional()
134
158
  }).strict().superRefine((config, ctx) => {
135
159
  const names = /* @__PURE__ */ new Set();
136
160
  config.ruleSets.forEach((rule, i) => {
@@ -144,34 +168,6 @@ var policyConfigSchema = z.object({
144
168
  });
145
169
  });
146
170
 
147
- // src/keywords.ts
148
- var sourceExpressions = {
149
- self: "'self'",
150
- none: "'none'",
151
- nonce: NONCE_PLACEHOLDER,
152
- strictDynamic: "'strict-dynamic'",
153
- reportSample: "'report-sample'",
154
- wasmUnsafeEval: "'wasm-unsafe-eval'"
155
- };
156
- function generateNonce() {
157
- const bytes = new Uint8Array(16);
158
- globalThis.crypto.getRandomValues(bytes);
159
- return btoa(String.fromCharCode(...bytes));
160
- }
161
- var unsafeInline = ({ reason }) => ({
162
- source: "'unsafe-inline'",
163
- reason
164
- });
165
- var unsafeEval = ({ reason }) => ({
166
- source: "'unsafe-eval'",
167
- reason
168
- });
169
- var unsafeHashes = ({ reason }) => ({
170
- source: "'unsafe-hashes'",
171
- reason
172
- });
173
- var cspHash = (algorithm, digest) => `'${algorithm}-${digest}'`;
174
-
175
171
  // src/matching/index.ts
176
172
  var friendly = {
177
173
  scripts: "script-src",
@@ -397,113 +393,6 @@ function matchPolicy(directives, directive, input, options = {}) {
397
393
  return decision("blocked", effective, "No source matched");
398
394
  }
399
395
 
400
- // src/reports/index.ts
401
- function record(value) {
402
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
403
- }
404
- function field(obj, ...keys) {
405
- for (const key of keys)
406
- if (typeof obj[key] === "string" && obj[key]) return obj[key];
407
- return void 0;
408
- }
409
- function parseViolationReports(input) {
410
- if (typeof input === "string") {
411
- try {
412
- input = JSON.parse(input);
413
- } catch {
414
- throw new Error("Invalid report JSON");
415
- }
416
- }
417
- const items = Array.isArray(input) ? input : [input];
418
- return items.map((item, index) => {
419
- const envelope = record(item);
420
- if (!envelope) throw new Error(`Unsupported report at index ${index}`);
421
- const body = (envelope.type === "csp" ? record(envelope.csp) : void 0) ?? record(envelope["csp-report"]) ?? (envelope.type === "csp-violation" ? record(envelope.body) : void 0) ?? envelope;
422
- const directive = field(
423
- body,
424
- "effective-directive",
425
- "effectiveDirective",
426
- "effective_directive",
427
- "violated-directive",
428
- "violatedDirective",
429
- "violated_directive"
430
- );
431
- const blockedURL = field(
432
- body,
433
- "blocked-uri",
434
- "blockedURL",
435
- "blockedUri",
436
- "blocked_uri"
437
- );
438
- const documentURL = field(
439
- body,
440
- "document-uri",
441
- "documentURL",
442
- "documentUri",
443
- "document_uri"
444
- );
445
- if (!directive || !blockedURL)
446
- throw new Error(`Unsupported or incomplete report at index ${index}`);
447
- return {
448
- directive: directive.split(" ")[0],
449
- blockedURL,
450
- ...documentURL ? { documentURL } : {}
451
- };
452
- });
453
- }
454
- function replayReports(directives, reports) {
455
- return reports.map((report) => {
456
- let origin;
457
- try {
458
- if (report.documentURL) {
459
- const parsedOrigin = new URL(report.documentURL).origin;
460
- if (parsedOrigin !== "null") origin = parsedOrigin;
461
- }
462
- } catch {
463
- }
464
- let blocked;
465
- try {
466
- blocked = new URL(report.blockedURL);
467
- } catch {
468
- return {
469
- report,
470
- result: {
471
- status: "indeterminate",
472
- allowed: null,
473
- reason: "Report does not contain a replayable URL"
474
- }
475
- };
476
- }
477
- if (!["http:", "https:", "ws:", "wss:"].includes(blocked.protocol)) {
478
- return {
479
- report,
480
- result: {
481
- status: "indeterminate",
482
- allowed: null,
483
- reason: "Report does not contain a replayable network URL"
484
- }
485
- };
486
- }
487
- const result = matchPolicy(
488
- directives,
489
- report.directive,
490
- report.blockedURL,
491
- origin ? { origin } : {}
492
- );
493
- if (result.status === "allowed" && result.matchedSource && result.matchedSource.replace(/^[a-z]+:\/\//i, "").includes("/")) {
494
- return {
495
- report,
496
- result: {
497
- status: "indeterminate",
498
- allowed: null,
499
- reason: "Report may omit the request path"
500
- }
501
- };
502
- }
503
- return { report, result };
504
- });
505
- }
506
-
507
396
  // src/core.ts
508
397
  import { z as z2 } from "zod";
509
398
  function freeze(value) {
@@ -535,7 +424,6 @@ function entryReason(entry) {
535
424
  }
536
425
  var Policy = class _Policy {
537
426
  config;
538
- headerName;
539
427
  constructor(input) {
540
428
  const result = policyConfigSchema.safeParse(input);
541
429
  if (!result.success) {
@@ -552,7 +440,6 @@ var Policy = class _Policy {
552
440
  }
553
441
  const config = result.data;
554
442
  this.config = freeze(config);
555
- this.headerName = config.mode === "enforce" ? "Content-Security-Policy" : "Content-Security-Policy-Report-Only";
556
443
  Object.freeze(this);
557
444
  }
558
445
  /** Sources and their contributing rule sets. Duplicate values retain all contributors. */
@@ -612,44 +499,26 @@ var Policy = class _Policy {
612
499
  ) : [];
613
500
  return contributors.length ? { ...result, contributors } : result;
614
501
  }
615
- /** Replay supported violation report JSON without inventing missing request context. */
616
- check(reports) {
617
- return replayReports(this.toObject(), parseViolationReports(reports));
618
- }
619
502
  /** Render a header value. Pretty output is for display only and is not a valid HTTP header value. */
620
503
  toHeader(options = {}) {
621
- return this.render(this.toObject(), options);
622
- }
623
- render(directives, options) {
504
+ const directives = this.toObject();
624
505
  const hasNonce = Object.values(directives).some(
625
- (sources) => sources.includes(NONCE_PLACEHOLDER)
506
+ (sources) => sources.includes(NONCE)
626
507
  );
627
508
  if (hasNonce && (!options.nonce || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(options.nonce)))
628
509
  throw new Error("A valid base64 nonce is required");
629
510
  return Object.entries(directives).map(([directive, values]) => {
630
511
  const rendered = values.map(
631
- (value) => value === NONCE_PLACEHOLDER ? `'nonce-${options.nonce}'` : value
512
+ (value) => value === NONCE ? `'nonce-${options.nonce}'` : value
632
513
  );
633
514
  return directive + (rendered.length ? ` ${rendered.join(" ")}` : "");
634
515
  }).join(options.pretty ? ";\n" : "; ");
635
516
  }
636
- /** Render a meta policy; report-only is not supported in meta delivery. */
637
- toMetaContent(options = {}) {
638
- if (this.config.mode === "report-only")
639
- throw new Error(
640
- "Report-only policies cannot be delivered in a meta element"
641
- );
642
- const directives = this.toObject();
643
- delete directives["frame-ancestors"];
644
- delete directives["report-uri"];
645
- delete directives["report-to"];
646
- delete directives.sandbox;
647
- return this.render(directives, options);
648
- }
649
- withRuleSet(ruleSet) {
517
+ withRuleSet(ruleSets) {
518
+ const additions = Array.isArray(ruleSets) ? ruleSets : [ruleSets];
650
519
  return new _Policy({
651
520
  ...this.config,
652
- ruleSets: [...this.config.ruleSets, ruleSet]
521
+ ruleSets: [...this.config.ruleSets, ...additions]
653
522
  });
654
523
  }
655
524
  without(name) {
@@ -663,213 +532,28 @@ function definePolicy(input) {
663
532
  return new Policy(input);
664
533
  }
665
534
 
666
- // src/diff.ts
667
- function diffPolicies(before, after) {
668
- const key = (row) => JSON.stringify([
669
- row.directive,
670
- row.source,
671
- row.ruleSet,
672
- row.reason ?? null
673
- ]);
674
- const oldRows = new Map(before.explain().map((row) => [key(row), row]));
675
- const newRows = new Map(after.explain().map((row) => [key(row), row]));
676
- const changes = [];
677
- for (const [id, row] of oldRows)
678
- if (!newRows.has(id))
679
- changes.push({
680
- directive: row.directive,
681
- source: row.source,
682
- ruleSet: row.ruleSet,
683
- change: "removed",
684
- ...row.reason ? { detail: row.reason } : {}
685
- });
686
- for (const [id, row] of newRows)
687
- if (!oldRows.has(id))
688
- changes.push({
689
- directive: row.directive,
690
- source: row.source,
691
- ruleSet: row.ruleSet,
692
- change: "added",
693
- ...row.reason ? { detail: row.reason } : {}
694
- });
695
- const beforeObj = before.toObject(), afterObj = after.toObject();
696
- for (const directive of /* @__PURE__ */ new Set([
697
- ...Object.keys(beforeObj),
698
- ...Object.keys(afterObj)
699
- ])) {
700
- if (JSON.stringify(beforeObj[directive]) !== JSON.stringify(afterObj[directive]) && !changes.some((c) => c.directive === directive))
701
- changes.push({
702
- directive,
703
- source: "",
704
- ruleSet: "base",
705
- change: "modified",
706
- detail: "Directive value changed"
707
- });
708
- }
709
- if (before.config.mode !== after.config.mode)
710
- changes.push({
711
- directive: "(mode)",
712
- source: "",
713
- ruleSet: "base",
714
- change: "modified",
715
- detail: `${before.config.mode} \u2192 ${after.config.mode}`
716
- });
717
- changes.sort(
718
- (a, b) => a.directive.localeCompare(b.directive) || a.source.localeCompare(b.source) || a.ruleSet.localeCompare(b.ruleSet) || a.change.localeCompare(b.change)
719
- );
720
- const headersChanged = JSON.stringify(beforeObj) !== JSON.stringify(afterObj) || before.config.mode !== after.config.mode;
721
- const dangerous = changes.some(
722
- (change) => change.change === "added" && !(beforeObj[change.directive] ?? []).includes(change.source) && /^(?:\*|https?:|data:|'unsafe-(?:inline|eval|hashes)')$/.test(
723
- change.source
724
- )
725
- );
726
- return {
727
- changes,
728
- risk: dangerous ? "increased" : headersChanged ? "unknown" : "unchanged"
729
- };
730
- }
731
-
732
- // src/importer/index.ts
733
- function importHeader(header) {
734
- if (/[\x00-\x08\x0a-\x1f\x7f,]/.test(header))
735
- throw new Error(
736
- "Header contains a control character or multiple policies; import one policy at a time"
737
- );
738
- const seen = /* @__PURE__ */ new Set();
739
- const warnings = [];
740
- const directives = [];
741
- for (const segment of header.split(";")) {
742
- const trimmed = segment.trim();
743
- if (!trimmed) continue;
744
- const [rawName, ...values] = trimmed.split(/[ \t]+/);
745
- if (!rawName || !/^[a-zA-Z][a-zA-Z0-9-]*$/.test(rawName))
746
- throw new Error(`Invalid directive name: ${rawName ?? ""}`);
747
- const name = rawName.toLowerCase();
748
- const ignored = seen.has(name);
749
- if (ignored)
750
- warnings.push(`Duplicate ${name} is ignored by CSP; retained for review`);
751
- seen.add(name);
752
- directives.push({ name, values, ignored });
753
- }
754
- return { directives, warnings };
755
- }
756
- function serializeImportedPolicy(policy) {
757
- return policy.directives.map(({ name, values }) => {
758
- if (!/^[a-z][a-z0-9-]*$/.test(name) || values.some((value) => !value || /[\x00-\x20\x7f;,]/.test(value))) {
759
- throw new Error("Invalid imported directive or value");
760
- }
761
- return [name, ...values].join(" ");
762
- }).join("; ");
763
- }
764
- function importedPolicyToDraft(policy) {
765
- if (policy.directives.some((directive) => directive.ignored))
766
- throw new Error(
767
- "Duplicate directives require manual review before conversion"
768
- );
769
- const base = {};
770
- const baseRaw = {};
771
- const ruleRaw = {};
772
- const baseOnly2 = /* @__PURE__ */ new Set([
773
- "default-src",
774
- "object-src",
775
- "base-uri",
776
- "frame-ancestors"
777
- ]);
778
- const supported = /* @__PURE__ */ new Set([
779
- "default-src",
780
- "object-src",
781
- "base-uri",
782
- "frame-ancestors",
783
- "script-src",
784
- "script-src-elem",
785
- "script-src-attr",
786
- "style-src",
787
- "style-src-elem",
788
- "style-src-attr",
789
- "img-src",
790
- "connect-src",
791
- "font-src",
792
- "frame-src",
793
- "child-src",
794
- "form-action",
795
- "media-src",
796
- "worker-src",
797
- "manifest-src"
798
- ]);
799
- const risky2 = /* @__PURE__ */ new Set([
800
- "'unsafe-inline'",
801
- "'unsafe-eval'",
802
- "'unsafe-hashes'"
803
- ]);
804
- for (const directive of policy.directives) {
805
- if (directive.name === "upgrade-insecure-requests") {
806
- if (directive.values.length)
807
- throw new Error(
808
- "upgrade-insecure-requests with values requires manual review"
809
- );
810
- base.upgradeInsecureRequests = true;
811
- continue;
812
- }
813
- if (!supported.has(directive.name) || directive.values.some(
814
- (value) => value.toLowerCase() === "'nonce-{nonce}'"
815
- )) {
816
- throw new Error(
817
- `Directive ${directive.name} contains unsupported syntax; review manually`
818
- );
819
- }
820
- if (directive.values.length === 0 || ["report-uri", "report-to", "sandbox"].includes(directive.name)) {
821
- throw new Error(
822
- `Directive ${directive.name} requires manual review before conversion`
823
- );
824
- }
825
- const entries = directive.values.map(
826
- (source) => risky2.has(source.toLowerCase()) ? { source, reason: "Imported legacy policy; review required" } : source
827
- );
828
- (baseOnly2.has(directive.name) ? baseRaw : ruleRaw)[directive.name] = entries;
829
- }
830
- if (Object.keys(baseRaw).length) base.directives = baseRaw;
831
- const draft = {
832
- base,
833
- ruleSets: Object.keys(ruleRaw).length ? [
834
- {
835
- name: "Imported policy",
836
- purpose: "Imported sources awaiting ownership review",
837
- rules: { directives: ruleRaw }
838
- }
839
- ] : []
840
- };
841
- const result = policyConfigSchema.safeParse(draft);
842
- if (!result.success)
843
- throw new Error(
844
- `Imported policy contains unsupported sources: ${result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`
845
- );
846
- return draft;
847
- }
848
-
849
535
  export {
536
+ SELF,
537
+ NONE,
538
+ NONCE,
539
+ STRICT_DYNAMIC,
540
+ REPORT_SAMPLE,
541
+ WASM_UNSAFE_EVAL,
542
+ generateNonce,
543
+ unsafeInline,
544
+ unsafeEval,
545
+ unsafeHashes,
546
+ cspHash,
850
547
  resourceDirectives,
851
548
  baseDirectives,
852
- NONCE_PLACEHOLDER,
853
549
  sourceEntrySchema,
854
550
  rulesSchema,
855
551
  baseSchema,
856
552
  ruleSetSchema,
857
553
  policyConfigSchema,
858
- sourceExpressions,
859
- generateNonce,
860
- unsafeInline,
861
- unsafeEval,
862
- unsafeHashes,
863
- cspHash,
864
554
  matchPolicy,
865
- parseViolationReports,
866
- replayReports,
867
555
  defineRuleSet,
868
556
  Policy,
869
- definePolicy,
870
- diffPolicies,
871
- importHeader,
872
- serializeImportedPolicy,
873
- importedPolicyToDraft
557
+ definePolicy
874
558
  };
875
- //# sourceMappingURL=chunk-TE3J7Y25.js.map
559
+ //# sourceMappingURL=chunk-JAXLODN4.js.map