@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/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # pretty-csp
2
+
3
+ ## 0.1.0
4
+
5
+ First public release as `@jamesbrightman/pretty-csp`. The installed command is `pretty-csp`.
6
+
7
+ ### Minor Changes
8
+
9
+ - 375b504: Expose `sourceExpressions` and named helpers for risky keywords and hashes in the first public API.
10
+ - Generate reviewable policy and rule-set files from supported CSP headers. Group hosts by registrable domain, preview with `--dry-run`, and use report-only mode by default.
11
+ - e97e9cb: Add an experimental CSP policy core, matching, audit, migration helpers, testing utilities, and CLI.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 James Brightman
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ # pretty-csp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ![pretty-csp — a friendlier look at Content Security Policy](website/static/img/pretty-csp-logo.svg)
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.
6
+
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.
10
+
11
+ ## Example
12
+
13
+ ```ts
14
+ import {
15
+ definePolicy,
16
+ defineRuleSet,
17
+ sourceExpressions,
18
+ } from '@jamesbrightman/pretty-csp';
19
+
20
+ const imageCdn = defineRuleSet({
21
+ name: 'Image CDN',
22
+ purpose: 'Serve product images',
23
+ owner: 'web',
24
+ rules: { images: ['https://cdn.example.com'] },
25
+ });
26
+
27
+ const policy = definePolicy({
28
+ base: {
29
+ default: [sourceExpressions.self],
30
+ images: [sourceExpressions.self],
31
+ objects: [sourceExpressions.none],
32
+ baseUri: [sourceExpressions.self],
33
+ frameAncestors: [sourceExpressions.none],
34
+ },
35
+ ruleSets: [imageCdn],
36
+ mode: 'report-only',
37
+ });
38
+
39
+ console.log(policy.headerName, policy.toHeader());
40
+ console.table(policy.explain());
41
+
42
+ const image = policy.allows('img-src', 'https://cdn.example.com/product.jpg', {
43
+ origin: 'https://shop.example.com',
44
+ redirectCount: 0,
45
+ });
46
+ console.log(image.status); // allowed
47
+ ```
48
+
49
+ 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
+
51
+ ## Documentation
52
+
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).
54
+
55
+ - [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.
57
+ - [Testing policies](https://jamesbrightman.github.io/pretty-csp/docs/testing) includes Node and Vitest examples.
58
+ - [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.
60
+
61
+ Use `pnpm docs:dev` for the local docs site or `pnpm docs:build` for the static output in `website/build`.
62
+
63
+ ## Development
64
+
65
+ The package and repository toolchain support Node.js 20 or newer. Use pnpm 10.17.1.
66
+
67
+ ```sh
68
+ pnpm install --frozen-lockfile
69
+ pnpm format:check
70
+ pnpm lint
71
+ pnpm typecheck
72
+ pnpm test
73
+ pnpm test:coverage
74
+ pnpm build
75
+ ```
76
+
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.
@@ -0,0 +1,224 @@
1
+ // src/audit/index.ts
2
+ var sourceFindings = (policy, directive, source, ruleId, severity, message, fix) => {
3
+ const owners = policy.explain().filter((row) => row.directive === directive && row.source === source);
4
+ return owners.length ? owners.map(({ ruleSet }) => ({
5
+ ruleId,
6
+ severity,
7
+ message,
8
+ fix,
9
+ directive,
10
+ source,
11
+ ruleSet
12
+ })) : [{ ruleId, severity, message, fix, directive, source }];
13
+ };
14
+ function audit(policy, options = {}) {
15
+ const object = policy.toObject();
16
+ const findings = [];
17
+ const add = (id, severity, message, fix, directive) => findings.push({
18
+ ruleId: id,
19
+ severity,
20
+ message,
21
+ fix,
22
+ ...directive ? { directive } : {}
23
+ });
24
+ if (!object["script-src"] && !object["default-src"])
25
+ add(
26
+ "missing-script-src",
27
+ "high",
28
+ "Some script execution is unrestricted.",
29
+ "Restrict script-src or default-src.",
30
+ "script-src"
31
+ );
32
+ for (const directive of [
33
+ "script-src",
34
+ "script-src-elem",
35
+ "script-src-attr",
36
+ "default-src"
37
+ ]) {
38
+ const sources = object[directive];
39
+ if (!sources) continue;
40
+ const isFallback = directive === "default-src" && object["script-src"] !== void 0;
41
+ if (isFallback) continue;
42
+ const hasNonceOrHash = sources.some(
43
+ (s) => /^'(nonce-|sha(?:256|384|512)-)/i.test(s)
44
+ );
45
+ for (const source of sources.filter(
46
+ (s) => s.toLowerCase() === "'unsafe-inline'" && !hasNonceOrHash
47
+ ))
48
+ findings.push(
49
+ ...sourceFindings(
50
+ policy,
51
+ directive,
52
+ source,
53
+ "script-unsafe-inline",
54
+ "high",
55
+ "Inline scripts are permitted.",
56
+ "Use nonces or hashes and remove unsafe-inline."
57
+ )
58
+ );
59
+ for (const source of sources.filter(
60
+ (s) => s.toLowerCase() === "'unsafe-eval'"
61
+ ))
62
+ findings.push(
63
+ ...sourceFindings(
64
+ policy,
65
+ directive,
66
+ source,
67
+ "script-unsafe-eval",
68
+ "high",
69
+ "Dynamic JavaScript evaluation is permitted.",
70
+ "Remove unsafe-eval and replace dynamic evaluation."
71
+ )
72
+ );
73
+ if (directive !== "script-src-attr" && sources.some((source) => source.toLowerCase() === "'strict-dynamic'")) {
74
+ for (const source of sources) {
75
+ 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(
76
+ source
77
+ )) {
78
+ findings.push(
79
+ ...sourceFindings(
80
+ policy,
81
+ directive,
82
+ source,
83
+ "ignored-by-strict-dynamic",
84
+ "info",
85
+ "Modern browsers ignore this source for scripts under strict-dynamic.",
86
+ "Remove it if legacy browser fallback is not needed."
87
+ )
88
+ );
89
+ }
90
+ }
91
+ }
92
+ for (const source of sources)
93
+ if (["*", "https:", "http:", "data:"].includes(source.toLowerCase()) || /^(?:https?:\/\/)?\*(?::(?:\*|\d+))?(?:\/[^\s]*)?$/i.test(source))
94
+ findings.push(
95
+ ...sourceFindings(
96
+ policy,
97
+ directive,
98
+ source,
99
+ "script-wildcard",
100
+ "high",
101
+ "A broad script source may permit attacker-controlled scripts.",
102
+ "Restrict script sources and prefer nonces or hashes."
103
+ )
104
+ );
105
+ }
106
+ const objects = object["object-src"] ?? object["default-src"];
107
+ if (!objects || objects.length !== 1 || objects[0]?.toLowerCase() !== "'none'")
108
+ add(
109
+ "missing-object-src",
110
+ "high",
111
+ "Object embedding is not explicitly blocked.",
112
+ "Set object-src to 'none'.",
113
+ "object-src"
114
+ );
115
+ const broad = (sources) => !sources || sources.some(
116
+ (source) => source === "*" || /^[a-z][a-z0-9+.-]*:$/i.test(source) || /^(?:https?:\/\/)?\*(?::(?:\*|\d+))?(?:\/[^\s]*)?$/i.test(source)
117
+ );
118
+ if (broad(object["base-uri"]))
119
+ add(
120
+ "missing-base-uri",
121
+ "medium",
122
+ "The document base URL is not sufficiently restricted.",
123
+ "Set base-uri to 'none' or 'self'.",
124
+ "base-uri"
125
+ );
126
+ if (broad(object["frame-ancestors"]))
127
+ add(
128
+ "missing-frame-ancestors",
129
+ "medium",
130
+ "Embedding by other sites is not sufficiently restricted.",
131
+ "Restrict frame-ancestors to trusted origins.",
132
+ "frame-ancestors"
133
+ );
134
+ const knownBypassDomains = [
135
+ "google.com",
136
+ "googleapis.com",
137
+ "googleusercontent.com",
138
+ "gstatic.com"
139
+ ];
140
+ for (const row of policy.explain()) {
141
+ if (["script-src", "script-src-elem", "default-src"].includes(row.directive)) {
142
+ const host = row.source.match(/^(?:https?:\/\/)?(?:\*\.)?([a-z0-9.-]+)/i)?.[1]?.toLowerCase();
143
+ if (host && knownBypassDomains.some(
144
+ (domain) => host === domain || host.endsWith(`.${domain}`)
145
+ )) {
146
+ findings.push({
147
+ ruleId: "bypass-host",
148
+ severity: "medium",
149
+ directive: row.directive,
150
+ source: row.source,
151
+ ruleSet: row.ruleSet,
152
+ message: "This script host may expose JSONP or script gadgets that weaken host allowlists.",
153
+ fix: "Review the host for JSONP endpoints and script gadgets; prefer nonce or hash authorization."
154
+ });
155
+ }
156
+ }
157
+ if (/^http:/i.test(row.source))
158
+ findings.push({
159
+ ruleId: "insecure-scheme",
160
+ severity: "medium",
161
+ directive: row.directive,
162
+ source: row.source,
163
+ ruleSet: row.ruleSet,
164
+ message: "An insecure HTTP source is permitted.",
165
+ fix: "Use HTTPS where possible."
166
+ });
167
+ if (/^(?:https?:\/\/)?\*\.[a-z0-9-]+(?::(?:\*|\d+))?(?:\/|$)/i.test(
168
+ row.source
169
+ ) || /^https?:\/\/\*\.(?:amazonaws\.com|azurewebsites\.net)(?:[/:]|$)/i.test(
170
+ row.source
171
+ ))
172
+ findings.push({
173
+ ruleId: "broad-wildcard",
174
+ severity: "medium",
175
+ directive: row.directive,
176
+ source: row.source,
177
+ ruleSet: row.ruleSet,
178
+ message: "A wildcard covers an unusually broad or shared domain.",
179
+ fix: "List the specific trusted hosts."
180
+ });
181
+ }
182
+ if (!object["report-uri"] && !object["report-to"])
183
+ add(
184
+ "no-reporting",
185
+ "low",
186
+ "No reporting destination is configured.",
187
+ "Configure reporting and its endpoint."
188
+ );
189
+ const today = (options.now ?? /* @__PURE__ */ new Date()).toISOString().slice(0, 10);
190
+ for (const set of policy.config.ruleSets.filter((s) => s.enabled)) {
191
+ if (!set.owner)
192
+ findings.push({
193
+ ruleId: "ruleset-metadata",
194
+ severity: "low",
195
+ ruleSet: set.name,
196
+ message: "Rule set has no owner.",
197
+ fix: "Assign an owner."
198
+ });
199
+ if (set.reviewBy && set.reviewBy < today)
200
+ findings.push({
201
+ ruleId: "ruleset-metadata",
202
+ severity: "low",
203
+ ruleSet: set.name,
204
+ message: "Rule set review date has passed.",
205
+ fix: "Review permissions regularly."
206
+ });
207
+ }
208
+ for (const rule of options.rules ?? []) findings.push(...rule.check(policy));
209
+ for (const suppression of options.suppressions ?? [])
210
+ if (!suppression.reason.trim() || !suppression.ruleId || !suppression.ruleSet)
211
+ throw new Error(
212
+ "Audit suppressions require a rule id, rule set and reason"
213
+ );
214
+ return findings.filter(
215
+ (finding) => !(options.suppressions ?? []).some(
216
+ (s) => s.ruleId === finding.ruleId && s.ruleSet === finding.ruleSet
217
+ )
218
+ );
219
+ }
220
+
221
+ export {
222
+ audit
223
+ };
224
+ //# sourceMappingURL=chunk-KWWYRHIP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/audit/index.ts"],"sourcesContent":["import type { Policy } from '../core';\n\nexport type Severity = 'high' | 'medium' | 'low' | 'info';\nexport interface AuditFinding {\n ruleId: string;\n severity: Severity;\n message: string;\n fix: string;\n directive?: string;\n source?: string;\n ruleSet?: string;\n}\nexport interface AuditRule {\n id: string;\n check(policy: Policy): readonly AuditFinding[];\n}\nexport interface AuditSuppression {\n ruleId: string;\n ruleSet: string;\n reason: string;\n}\nexport interface AuditOptions {\n rules?: readonly AuditRule[];\n suppressions?: readonly AuditSuppression[];\n now?: Date;\n}\n\nconst sourceFindings = (\n policy: Policy,\n directive: string,\n source: string,\n ruleId: string,\n severity: Severity,\n message: string,\n fix: string,\n): AuditFinding[] => {\n const owners = policy\n .explain()\n .filter((row) => row.directive === directive && row.source === source);\n return owners.length\n ? owners.map(({ ruleSet }) => ({\n ruleId,\n severity,\n message,\n fix,\n directive,\n source,\n ruleSet,\n }))\n : [{ ruleId, severity, message, fix, directive, source }];\n};\n\n/** Inspect known dangerous policy patterns. Findings are advisory and do not prove a policy safe. */\nexport function audit(\n policy: Policy,\n options: AuditOptions = {},\n): AuditFinding[] {\n const object = policy.toObject();\n const findings: AuditFinding[] = [];\n const add = (\n id: string,\n severity: Severity,\n message: string,\n fix: string,\n directive?: string,\n ) =>\n findings.push({\n ruleId: id,\n severity,\n message,\n fix,\n ...(directive ? { directive } : {}),\n });\n if (!object['script-src'] && !object['default-src'])\n add(\n 'missing-script-src',\n 'high',\n 'Some script execution is unrestricted.',\n 'Restrict script-src or default-src.',\n 'script-src',\n );\n // script-src-elem falls back to script-src, then default-src. Inspect each explicit list.\n for (const directive of [\n 'script-src',\n 'script-src-elem',\n 'script-src-attr',\n 'default-src',\n ]) {\n const sources = object[directive];\n if (!sources) continue;\n const isFallback =\n directive === 'default-src' && object['script-src'] !== undefined;\n if (isFallback) continue;\n const hasNonceOrHash = sources.some((s) =>\n /^'(nonce-|sha(?:256|384|512)-)/i.test(s),\n );\n for (const source of sources.filter(\n (s) => s.toLowerCase() === \"'unsafe-inline'\" && !hasNonceOrHash,\n ))\n findings.push(\n ...sourceFindings(\n policy,\n directive,\n source,\n 'script-unsafe-inline',\n 'high',\n 'Inline scripts are permitted.',\n 'Use nonces or hashes and remove unsafe-inline.',\n ),\n );\n for (const source of sources.filter(\n (s) => s.toLowerCase() === \"'unsafe-eval'\",\n ))\n findings.push(\n ...sourceFindings(\n policy,\n directive,\n source,\n 'script-unsafe-eval',\n 'high',\n 'Dynamic JavaScript evaluation is permitted.',\n 'Remove unsafe-eval and replace dynamic evaluation.',\n ),\n );\n if (\n directive !== 'script-src-attr' &&\n sources.some((source) => source.toLowerCase() === \"'strict-dynamic'\")\n ) {\n for (const source of sources) {\n if (\n source.toLowerCase() === \"'self'\" ||\n source === '*' ||\n /^[a-z][a-z0-9+.-]*:$/i.test(source) ||\n /^(?:[a-z][a-z0-9+.-]*:\\/\\/)?(?:\\*|[a-z0-9*.-]+)(?::(?:\\*|\\d+))?(?:\\/[^\\s]*)?$/i.test(\n source,\n )\n ) {\n findings.push(\n ...sourceFindings(\n policy,\n directive,\n source,\n 'ignored-by-strict-dynamic',\n 'info',\n 'Modern browsers ignore this source for scripts under strict-dynamic.',\n 'Remove it if legacy browser fallback is not needed.',\n ),\n );\n }\n }\n }\n for (const source of sources)\n if (\n ['*', 'https:', 'http:', 'data:'].includes(source.toLowerCase()) ||\n /^(?:https?:\\/\\/)?\\*(?::(?:\\*|\\d+))?(?:\\/[^\\s]*)?$/i.test(source)\n )\n findings.push(\n ...sourceFindings(\n policy,\n directive,\n source,\n 'script-wildcard',\n 'high',\n 'A broad script source may permit attacker-controlled scripts.',\n 'Restrict script sources and prefer nonces or hashes.',\n ),\n );\n }\n const objects = object['object-src'] ?? object['default-src'];\n if (\n !objects ||\n objects.length !== 1 ||\n objects[0]?.toLowerCase() !== \"'none'\"\n )\n add(\n 'missing-object-src',\n 'high',\n 'Object embedding is not explicitly blocked.',\n \"Set object-src to 'none'.\",\n 'object-src',\n );\n const broad = (sources: string[] | undefined) =>\n !sources ||\n sources.some(\n (source) =>\n source === '*' ||\n /^[a-z][a-z0-9+.-]*:$/i.test(source) ||\n /^(?:https?:\\/\\/)?\\*(?::(?:\\*|\\d+))?(?:\\/[^\\s]*)?$/i.test(source),\n );\n if (broad(object['base-uri']))\n add(\n 'missing-base-uri',\n 'medium',\n 'The document base URL is not sufficiently restricted.',\n \"Set base-uri to 'none' or 'self'.\",\n 'base-uri',\n );\n if (broad(object['frame-ancestors']))\n add(\n 'missing-frame-ancestors',\n 'medium',\n 'Embedding by other sites is not sufficiently restricted.',\n 'Restrict frame-ancestors to trusted origins.',\n 'frame-ancestors',\n );\n // Small advisory subset informed by Google CSP Evaluator; maintain and review this data.\n // https://github.com/google/csp-evaluator/tree/master/allowlist_bypasses\n const knownBypassDomains = [\n 'google.com',\n 'googleapis.com',\n 'googleusercontent.com',\n 'gstatic.com',\n ];\n for (const row of policy.explain()) {\n if (\n ['script-src', 'script-src-elem', 'default-src'].includes(row.directive)\n ) {\n const host = row.source\n .match(/^(?:https?:\\/\\/)?(?:\\*\\.)?([a-z0-9.-]+)/i)?.[1]\n ?.toLowerCase();\n if (\n host &&\n knownBypassDomains.some(\n (domain) => host === domain || host.endsWith(`.${domain}`),\n )\n ) {\n findings.push({\n ruleId: 'bypass-host',\n severity: 'medium',\n directive: row.directive,\n source: row.source,\n ruleSet: row.ruleSet,\n message:\n 'This script host may expose JSONP or script gadgets that weaken host allowlists.',\n fix: 'Review the host for JSONP endpoints and script gadgets; prefer nonce or hash authorization.',\n });\n }\n }\n if (/^http:/i.test(row.source))\n findings.push({\n ruleId: 'insecure-scheme',\n severity: 'medium',\n directive: row.directive,\n source: row.source,\n ruleSet: row.ruleSet,\n message: 'An insecure HTTP source is permitted.',\n fix: 'Use HTTPS where possible.',\n });\n if (\n /^(?:https?:\\/\\/)?\\*\\.[a-z0-9-]+(?::(?:\\*|\\d+))?(?:\\/|$)/i.test(\n row.source,\n ) ||\n /^https?:\\/\\/\\*\\.(?:amazonaws\\.com|azurewebsites\\.net)(?:[/:]|$)/i.test(\n row.source,\n )\n )\n findings.push({\n ruleId: 'broad-wildcard',\n severity: 'medium',\n directive: row.directive,\n source: row.source,\n ruleSet: row.ruleSet,\n message: 'A wildcard covers an unusually broad or shared domain.',\n fix: 'List the specific trusted hosts.',\n });\n }\n if (!object['report-uri'] && !object['report-to'])\n add(\n 'no-reporting',\n 'low',\n 'No reporting destination is configured.',\n 'Configure reporting and its endpoint.',\n );\n const today = (options.now ?? new Date()).toISOString().slice(0, 10);\n for (const set of policy.config.ruleSets.filter((s) => s.enabled)) {\n if (!set.owner)\n findings.push({\n ruleId: 'ruleset-metadata',\n severity: 'low',\n ruleSet: set.name,\n message: 'Rule set has no owner.',\n fix: 'Assign an owner.',\n });\n if (set.reviewBy && set.reviewBy < today)\n findings.push({\n ruleId: 'ruleset-metadata',\n severity: 'low',\n ruleSet: set.name,\n message: 'Rule set review date has passed.',\n fix: 'Review permissions regularly.',\n });\n }\n for (const rule of options.rules ?? []) findings.push(...rule.check(policy));\n for (const suppression of options.suppressions ?? [])\n if (\n !suppression.reason.trim() ||\n !suppression.ruleId ||\n !suppression.ruleSet\n )\n throw new Error(\n 'Audit suppressions require a rule id, rule set and reason',\n );\n return findings.filter(\n (finding) =>\n !(options.suppressions ?? []).some(\n (s) => s.ruleId === finding.ruleId && s.ruleSet === finding.ruleSet,\n ),\n );\n}\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AAAA,EACL;AACA,MAAI,CAAC,OAAO,YAAY,KAAK,CAAC,OAAO,WAAW;AAC9C;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACF,QAAM,SAAS,QAAQ,OAAO,oBAAI,KAAK,GAAG,YAAY,EAAE,MAAM,GAAG,EAAE;AACnE,aAAW,OAAO,OAAO,OAAO,SAAS,OAAO,CAAC,MAAM,EAAE,OAAO,GAAG;AACjE,QAAI,CAAC,IAAI;AACP,eAAS,KAAK;AAAA,QACZ,QAAQ;AAAA,QACR,UAAU;AAAA,QACV,SAAS,IAAI;AAAA,QACb,SAAS;AAAA,QACT,KAAK;AAAA,MACP,CAAC;AACH,QAAI,IAAI,YAAY,IAAI,WAAW;AACjC,eAAS,KAAK;AAAA,QACZ,QAAQ;AAAA,QACR,UAAU;AAAA,QACV,SAAS,IAAI;AAAA,QACb,SAAS;AAAA,QACT,KAAK;AAAA,MACP,CAAC;AAAA,EACL;AACA,aAAW,QAAQ,QAAQ,SAAS,CAAC,EAAG,UAAS,KAAK,GAAG,KAAK,MAAM,MAAM,CAAC;AAC3E,aAAW,eAAe,QAAQ,gBAAgB,CAAC;AACjD,QACE,CAAC,YAAY,OAAO,KAAK,KACzB,CAAC,YAAY,UACb,CAAC,YAAY;AAEb,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AACJ,SAAO,SAAS;AAAA,IACd,CAAC,YACC,EAAE,QAAQ,gBAAgB,CAAC,GAAG;AAAA,MAC5B,CAAC,MAAM,EAAE,WAAW,QAAQ,UAAU,EAAE,YAAY,QAAQ;AAAA,IAC9D;AAAA,EACJ;AACF;","names":[]}
@@ -0,0 +1,67 @@
1
+ import {
2
+ audit
3
+ } from "./chunk-KWWYRHIP.js";
4
+
5
+ // src/testing/index.ts
6
+ var cspMatchers = {
7
+ toAllow(policy, directive, url, options) {
8
+ const result = policy.allows(directive, url, options);
9
+ if (result.status === "indeterminate")
10
+ throw new Error(
11
+ `Cannot assert ${directive} ${url}: indeterminate; ${result.reason ?? "decision is indeterminate"}`
12
+ );
13
+ return {
14
+ pass: result.status === "allowed",
15
+ message: () => `Expected ${directive} ${url} ${result.status === "allowed" ? "not " : ""}to be allowed; decision: ${result.status}${result.reason ? ` (${result.reason})` : ""}`
16
+ };
17
+ },
18
+ toBlock(policy, directive, url, options) {
19
+ const result = policy.allows(directive, url, options);
20
+ if (result.status === "indeterminate")
21
+ throw new Error(
22
+ `Cannot assert ${directive} ${url}: indeterminate; ${result.reason ?? "decision is indeterminate"}`
23
+ );
24
+ return {
25
+ pass: result.status === "blocked",
26
+ message: () => `Expected ${directive} ${url} ${result.status === "blocked" ? "not " : ""}to be blocked; decision: ${result.status}${result.reason ? ` (${result.reason})` : ""}`
27
+ };
28
+ },
29
+ toMatchCspSnapshot(policy, expected) {
30
+ const actual = cspSnapshot(policy);
31
+ const pass = this.equals(actual, expected);
32
+ return {
33
+ pass,
34
+ message: () => pass ? "Expected CSP snapshot to differ from the supplied snapshot" : "CSP snapshot differs; review and update the committed snapshot"
35
+ };
36
+ },
37
+ toPassAudit(policy, options = {}) {
38
+ const ranks = {
39
+ info: 0,
40
+ low: 1,
41
+ medium: 2,
42
+ high: 3
43
+ };
44
+ const threshold = ranks[options.maxSeverity ?? "low"];
45
+ const failing = audit(policy).filter(
46
+ (finding) => ranks[finding.severity] > threshold
47
+ );
48
+ return {
49
+ pass: failing.length === 0,
50
+ message: () => failing.length ? `Expected CSP audit to have no findings above ${options.maxSeverity ?? "low"}: ${failing.map((f) => `${f.ruleId} (${f.severity})`).join(", ")}` : "Expected the CSP audit to exceed the permitted severity"
51
+ };
52
+ }
53
+ };
54
+ function cspSnapshot(policy) {
55
+ return {
56
+ schemaVersion: 1,
57
+ mode: policy.config.mode,
58
+ directives: policy.toObject(),
59
+ contributors: policy.explain()
60
+ };
61
+ }
62
+
63
+ export {
64
+ cspMatchers,
65
+ cspSnapshot
66
+ };
67
+ //# sourceMappingURL=chunk-MDUQKU6Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing/index.ts"],"sourcesContent":["import { audit } from '../audit';\nimport type { Severity } from '../audit';\nimport type { Policy } from '../core';\nimport type { MatchOptions } from '../matching';\n\n/** Matchers can be registered with either Jest's or Vitest's `expect.extend`. */\nexport const cspMatchers = {\n toAllow(\n policy: Policy,\n directive: string,\n url: string,\n options?: MatchOptions,\n ) {\n const result = policy.allows(directive, url, options);\n if (result.status === 'indeterminate')\n throw new Error(\n `Cannot assert ${directive} ${url}: indeterminate; ${result.reason ?? 'decision is indeterminate'}`,\n );\n return {\n pass: result.status === 'allowed',\n message: () =>\n `Expected ${directive} ${url} ${result.status === 'allowed' ? 'not ' : ''}to be allowed; decision: ${result.status}${result.reason ? ` (${result.reason})` : ''}`,\n };\n },\n toBlock(\n policy: Policy,\n directive: string,\n url: string,\n options?: MatchOptions,\n ) {\n const result = policy.allows(directive, url, options);\n if (result.status === 'indeterminate')\n throw new Error(\n `Cannot assert ${directive} ${url}: indeterminate; ${result.reason ?? 'decision is indeterminate'}`,\n );\n return {\n pass: result.status === 'blocked',\n message: () =>\n `Expected ${directive} ${url} ${result.status === 'blocked' ? 'not ' : ''}to be blocked; decision: ${result.status}${result.reason ? ` (${result.reason})` : ''}`,\n };\n },\n toMatchCspSnapshot(\n this: { equals(actual: unknown, expected: unknown): boolean },\n policy: Policy,\n expected: ReturnType<typeof cspSnapshot>,\n ) {\n const actual = cspSnapshot(policy);\n const pass = this.equals(actual, expected);\n return {\n pass,\n message: () =>\n pass\n ? 'Expected CSP snapshot to differ from the supplied snapshot'\n : 'CSP snapshot differs; review and update the committed snapshot',\n };\n },\n toPassAudit(policy: Policy, options: { maxSeverity?: Severity } = {}) {\n const ranks: Record<Severity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n };\n const threshold = ranks[options.maxSeverity ?? 'low'];\n const failing = audit(policy).filter(\n (finding) => ranks[finding.severity] > threshold,\n );\n return {\n pass: failing.length === 0,\n message: () =>\n failing.length\n ? `Expected CSP audit to have no findings above ${options.maxSeverity ?? 'low'}: ${failing.map((f) => `${f.ruleId} (${f.severity})`).join(', ')}`\n : 'Expected the CSP audit to exceed the permitted severity',\n };\n },\n};\n\n/** Stable, provenance-aware input for a test runner's built-in snapshot matcher. */\nexport function cspSnapshot(policy: Policy): {\n schemaVersion: 1;\n mode: 'enforce' | 'report-only';\n directives: Record<string, string[]>;\n contributors: ReturnType<Policy['explain']>;\n} {\n return {\n schemaVersion: 1,\n mode: policy.config.mode,\n directives: policy.toObject(),\n contributors: policy.explain(),\n };\n}\n"],"mappings":";;;;;AAMO,IAAM,cAAc;AAAA,EACzB,QACE,QACA,WACA,KACA,SACA;AACA,UAAM,SAAS,OAAO,OAAO,WAAW,KAAK,OAAO;AACpD,QAAI,OAAO,WAAW;AACpB,YAAM,IAAI;AAAA,QACR,iBAAiB,SAAS,IAAI,GAAG,oBAAoB,OAAO,UAAU,2BAA2B;AAAA,MACnG;AACF,WAAO;AAAA,MACL,MAAM,OAAO,WAAW;AAAA,MACxB,SAAS,MACP,YAAY,SAAS,IAAI,GAAG,IAAI,OAAO,WAAW,YAAY,SAAS,EAAE,4BAA4B,OAAO,MAAM,GAAG,OAAO,SAAS,KAAK,OAAO,MAAM,MAAM,EAAE;AAAA,IACnK;AAAA,EACF;AAAA,EACA,QACE,QACA,WACA,KACA,SACA;AACA,UAAM,SAAS,OAAO,OAAO,WAAW,KAAK,OAAO;AACpD,QAAI,OAAO,WAAW;AACpB,YAAM,IAAI;AAAA,QACR,iBAAiB,SAAS,IAAI,GAAG,oBAAoB,OAAO,UAAU,2BAA2B;AAAA,MACnG;AACF,WAAO;AAAA,MACL,MAAM,OAAO,WAAW;AAAA,MACxB,SAAS,MACP,YAAY,SAAS,IAAI,GAAG,IAAI,OAAO,WAAW,YAAY,SAAS,EAAE,4BAA4B,OAAO,MAAM,GAAG,OAAO,SAAS,KAAK,OAAO,MAAM,MAAM,EAAE;AAAA,IACnK;AAAA,EACF;AAAA,EACA,mBA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