@jamesbrightman/pretty-csp 0.0.0-stage → 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 +61 -0
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/dist/chunk-JAXLODN4.js +559 -0
- package/dist/chunk-JAXLODN4.js.map +1 -0
- package/dist/chunk-KWWYRHIP.js +224 -0
- package/dist/chunk-KWWYRHIP.js.map +1 -0
- package/dist/chunk-YMAXUCI4.js +66 -0
- package/dist/chunk-YMAXUCI4.js.map +1 -0
- package/dist/cli.cjs +1049 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +328 -0
- package/dist/cli.js.map +1 -0
- package/dist/index-CvwFjLiu.d.cts +426 -0
- package/dist/index-CvwFjLiu.d.ts +426 -0
- package/dist/index.cjs +830 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +42 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +53 -0
- package/dist/index.js.map +1 -0
- package/dist/testing.cjs +309 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +38 -0
- package/dist/testing.d.ts +38 -0
- package/dist/testing.js +10 -0
- package/dist/testing.js.map +1 -0
- package/package.json +102 -4
- package/website/static/img/how-it-works.svg +34 -0
- package/website/static/img/pretty-csp-icon.svg +6 -0
- package/website/static/img/pretty-csp-logo.svg +12 -0
|
@@ -0,0 +1,559 @@
|
|
|
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
|
+
|
|
27
|
+
// src/schemas.ts
|
|
28
|
+
import { z } from "zod";
|
|
29
|
+
var resourceDirectives = {
|
|
30
|
+
scripts: "script-src",
|
|
31
|
+
connect: "connect-src",
|
|
32
|
+
images: "img-src",
|
|
33
|
+
styles: "style-src",
|
|
34
|
+
fonts: "font-src",
|
|
35
|
+
frames: "frame-src",
|
|
36
|
+
forms: "form-action",
|
|
37
|
+
media: "media-src",
|
|
38
|
+
workers: "worker-src",
|
|
39
|
+
manifest: "manifest-src"
|
|
40
|
+
};
|
|
41
|
+
var baseDirectives = {
|
|
42
|
+
default: "default-src",
|
|
43
|
+
objects: "object-src",
|
|
44
|
+
baseUri: "base-uri",
|
|
45
|
+
frameAncestors: "frame-ancestors"
|
|
46
|
+
};
|
|
47
|
+
var risky = /* @__PURE__ */ new Set(["'unsafe-inline'", "'unsafe-eval'", "'unsafe-hashes'"]);
|
|
48
|
+
var keywords = /* @__PURE__ */ new Set([
|
|
49
|
+
"'self'",
|
|
50
|
+
"'none'",
|
|
51
|
+
"'strict-dynamic'",
|
|
52
|
+
"'report-sample'",
|
|
53
|
+
"'wasm-unsafe-eval'",
|
|
54
|
+
...risky
|
|
55
|
+
]);
|
|
56
|
+
function isSource(value) {
|
|
57
|
+
if (!value || /[\x00-\x20\x7f;,]/.test(value) || /^[a-z][a-z0-9+.-]*\/\//i.test(value))
|
|
58
|
+
return false;
|
|
59
|
+
if (keywords.has(value.toLowerCase()) || value === NONCE || value === "*" || /^[a-z][a-z0-9+.-]*:\/\/\*(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(value))
|
|
60
|
+
return true;
|
|
61
|
+
if (/^'(nonce-[A-Za-z0-9+/_-]+={0,2}|sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2})'$/i.test(
|
|
62
|
+
value
|
|
63
|
+
))
|
|
64
|
+
return true;
|
|
65
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:$/.test(value)) return true;
|
|
66
|
+
return /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:\*\.)?(?:[a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(
|
|
67
|
+
value
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
var sourceStringSchema = z.string().refine(isSource, "Invalid CSP source expression");
|
|
71
|
+
var sourceEntrySchema = z.union([
|
|
72
|
+
sourceStringSchema.refine(
|
|
73
|
+
(s) => !risky.has(s.toLowerCase()),
|
|
74
|
+
"Risky keyword requires a reason"
|
|
75
|
+
),
|
|
76
|
+
z.object({ source: sourceStringSchema, reason: z.string().trim().min(1) }).strict()
|
|
77
|
+
]);
|
|
78
|
+
var sourceList = z.array(sourceEntrySchema).min(1);
|
|
79
|
+
var sourceListDirectives = /* @__PURE__ */ new Set([
|
|
80
|
+
...Object.values(resourceDirectives),
|
|
81
|
+
...Object.values(baseDirectives),
|
|
82
|
+
"script-src-elem",
|
|
83
|
+
"script-src-attr",
|
|
84
|
+
"style-src-elem",
|
|
85
|
+
"style-src-attr",
|
|
86
|
+
"child-src"
|
|
87
|
+
]);
|
|
88
|
+
var rawDirectives = z.record(
|
|
89
|
+
z.string().regex(/^[a-z][a-z0-9-]*$/).refine(
|
|
90
|
+
(name) => sourceListDirectives.has(name),
|
|
91
|
+
"Unsupported raw directive; only known source-list directives are supported"
|
|
92
|
+
),
|
|
93
|
+
sourceList
|
|
94
|
+
);
|
|
95
|
+
var reserved = /* @__PURE__ */ new Set([
|
|
96
|
+
"report-uri",
|
|
97
|
+
"report-to",
|
|
98
|
+
"upgrade-insecure-requests"
|
|
99
|
+
]);
|
|
100
|
+
var baseOnly = /* @__PURE__ */ new Set([...Object.values(baseDirectives), ...reserved]);
|
|
101
|
+
var ruleShape = Object.fromEntries(
|
|
102
|
+
Object.keys(resourceDirectives).map((key) => [key, sourceList.optional()])
|
|
103
|
+
);
|
|
104
|
+
var rulesSchema = z.object({ ...ruleShape, directives: rawDirectives.optional() }).strict().refine(
|
|
105
|
+
(rules) => Object.entries(rules).some(
|
|
106
|
+
([key, value]) => key === "directives" ? Object.keys(value ?? {}).length > 0 : value !== void 0
|
|
107
|
+
),
|
|
108
|
+
"At least one resource directive is required"
|
|
109
|
+
).superRefine((rules, ctx) => {
|
|
110
|
+
for (const directive of Object.keys(rules.directives ?? {})) {
|
|
111
|
+
if (baseOnly.has(directive))
|
|
112
|
+
ctx.addIssue({
|
|
113
|
+
code: "custom",
|
|
114
|
+
path: ["directives", directive],
|
|
115
|
+
message: "Base-only or reserved directive"
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
var baseSchema = z.object({
|
|
120
|
+
...ruleShape,
|
|
121
|
+
default: sourceList.optional(),
|
|
122
|
+
objects: sourceList.optional(),
|
|
123
|
+
baseUri: sourceList.optional(),
|
|
124
|
+
frameAncestors: sourceList.optional(),
|
|
125
|
+
upgradeInsecureRequests: z.boolean().optional(),
|
|
126
|
+
directives: rawDirectives.optional()
|
|
127
|
+
}).strict().superRefine((base, ctx) => {
|
|
128
|
+
for (const directive of Object.keys(base.directives ?? {})) {
|
|
129
|
+
if (reserved.has(directive))
|
|
130
|
+
ctx.addIssue({
|
|
131
|
+
code: "custom",
|
|
132
|
+
path: ["directives", directive],
|
|
133
|
+
message: "Use the dedicated configuration field for this directive"
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
var ruleSetSchema = z.object({
|
|
138
|
+
name: z.string().trim().min(1),
|
|
139
|
+
purpose: z.string().trim().min(1),
|
|
140
|
+
owner: z.string().trim().min(1).optional(),
|
|
141
|
+
docs: z.url().optional(),
|
|
142
|
+
tags: z.array(z.string().trim().min(1)).optional(),
|
|
143
|
+
reviewBy: z.iso.date().optional(),
|
|
144
|
+
enabled: z.boolean().default(true),
|
|
145
|
+
rules: rulesSchema
|
|
146
|
+
}).strict();
|
|
147
|
+
var reportingSchema = z.object({
|
|
148
|
+
uri: z.url().refine(
|
|
149
|
+
(value) => !/[\x00-\x20\x7f;,]/.test(value),
|
|
150
|
+
"Invalid reporting value"
|
|
151
|
+
).optional(),
|
|
152
|
+
to: z.string().regex(/^[A-Za-z0-9_-]+$/).optional()
|
|
153
|
+
}).strict();
|
|
154
|
+
var policyConfigSchema = z.object({
|
|
155
|
+
base: baseSchema.default({}),
|
|
156
|
+
ruleSets: z.array(ruleSetSchema).default([]),
|
|
157
|
+
reporting: reportingSchema.optional()
|
|
158
|
+
}).strict().superRefine((config, ctx) => {
|
|
159
|
+
const names = /* @__PURE__ */ new Set();
|
|
160
|
+
config.ruleSets.forEach((rule, i) => {
|
|
161
|
+
if (names.has(rule.name))
|
|
162
|
+
ctx.addIssue({
|
|
163
|
+
code: "custom",
|
|
164
|
+
path: ["ruleSets", i, "name"],
|
|
165
|
+
message: `Duplicate rule set name: ${rule.name}`
|
|
166
|
+
});
|
|
167
|
+
names.add(rule.name);
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// src/matching/index.ts
|
|
172
|
+
var friendly = {
|
|
173
|
+
scripts: "script-src",
|
|
174
|
+
connect: "connect-src",
|
|
175
|
+
images: "img-src",
|
|
176
|
+
styles: "style-src",
|
|
177
|
+
fonts: "font-src",
|
|
178
|
+
frames: "frame-src",
|
|
179
|
+
forms: "form-action",
|
|
180
|
+
media: "media-src",
|
|
181
|
+
workers: "worker-src",
|
|
182
|
+
manifest: "manifest-src",
|
|
183
|
+
default: "default-src",
|
|
184
|
+
objects: "object-src",
|
|
185
|
+
baseUri: "base-uri",
|
|
186
|
+
frameAncestors: "frame-ancestors"
|
|
187
|
+
};
|
|
188
|
+
var fallbacks = {
|
|
189
|
+
"script-src-elem": ["script-src-elem", "script-src", "default-src"],
|
|
190
|
+
"script-src-attr": ["script-src-attr", "script-src", "default-src"],
|
|
191
|
+
"style-src-elem": ["style-src-elem", "style-src", "default-src"],
|
|
192
|
+
"style-src-attr": ["style-src-attr", "style-src", "default-src"],
|
|
193
|
+
"worker-src": ["worker-src", "child-src", "script-src", "default-src"],
|
|
194
|
+
"frame-src": ["frame-src", "child-src", "default-src"]
|
|
195
|
+
};
|
|
196
|
+
for (const name of [
|
|
197
|
+
"script-src",
|
|
198
|
+
"style-src",
|
|
199
|
+
"child-src",
|
|
200
|
+
"connect-src",
|
|
201
|
+
"font-src",
|
|
202
|
+
"img-src",
|
|
203
|
+
"manifest-src",
|
|
204
|
+
"media-src",
|
|
205
|
+
"object-src"
|
|
206
|
+
]) {
|
|
207
|
+
fallbacks[name] = [name, "default-src"];
|
|
208
|
+
}
|
|
209
|
+
for (const name of [
|
|
210
|
+
"default-src",
|
|
211
|
+
"form-action",
|
|
212
|
+
"base-uri",
|
|
213
|
+
"frame-ancestors"
|
|
214
|
+
])
|
|
215
|
+
fallbacks[name] = [name];
|
|
216
|
+
function decision(status, effectiveDirective, reason, matchedSource) {
|
|
217
|
+
return {
|
|
218
|
+
status,
|
|
219
|
+
allowed: status === "indeterminate" ? null : status === "allowed",
|
|
220
|
+
...effectiveDirective && { effectiveDirective },
|
|
221
|
+
...reason && { reason },
|
|
222
|
+
...matchedSource && { matchedSource }
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function schemeMatches(source, target) {
|
|
226
|
+
source = source.toLowerCase();
|
|
227
|
+
target = target.toLowerCase();
|
|
228
|
+
return source === target || source === "http" && target === "https" || source === "ws" && ["wss", "http", "https"].includes(target) || source === "wss" && target === "https";
|
|
229
|
+
}
|
|
230
|
+
function scheme(url) {
|
|
231
|
+
return url.protocol.slice(0, -1).toLowerCase();
|
|
232
|
+
}
|
|
233
|
+
function defaultPort(s) {
|
|
234
|
+
return { http: "80", https: "443", ws: "80", wss: "443", ftp: "21" }[s];
|
|
235
|
+
}
|
|
236
|
+
function selfMatches(url, origin) {
|
|
237
|
+
if (scheme(url) === "blob") return false;
|
|
238
|
+
if (origin.origin !== "null" && origin.origin === url.origin) return true;
|
|
239
|
+
const os = scheme(origin), us = scheme(url);
|
|
240
|
+
const portsMatch = origin.port === url.port || !origin.port && !url.port;
|
|
241
|
+
return origin.hostname !== "" && origin.hostname === url.hostname && portsMatch && (us === "https" || us === "wss" || os === "http" && (us === "http" || us === "ws"));
|
|
242
|
+
}
|
|
243
|
+
function segmentBytes(segment) {
|
|
244
|
+
const bytes = [];
|
|
245
|
+
for (let i = 0; i < segment.length; ) {
|
|
246
|
+
const encoded = segment.slice(i).match(/^%([0-9a-f]{2})/i);
|
|
247
|
+
if (encoded) {
|
|
248
|
+
bytes.push(parseInt(encoded[1], 16));
|
|
249
|
+
i += 3;
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
const point = segment.codePointAt(i);
|
|
253
|
+
const character = String.fromCodePoint(point);
|
|
254
|
+
bytes.push(...new TextEncoder().encode(character));
|
|
255
|
+
i += character.length;
|
|
256
|
+
}
|
|
257
|
+
return bytes.join(",");
|
|
258
|
+
}
|
|
259
|
+
function pathMatches(pattern, target) {
|
|
260
|
+
if (!pattern || pattern === "/" && !target) return true;
|
|
261
|
+
const a = pattern.split("/"), b = target.split("/");
|
|
262
|
+
if (a.length > b.length || !pattern.endsWith("/") && a.length !== b.length)
|
|
263
|
+
return false;
|
|
264
|
+
if (pattern.endsWith("/")) a.pop();
|
|
265
|
+
return a.every((part, i) => segmentBytes(part) === segmentBytes(b[i]));
|
|
266
|
+
}
|
|
267
|
+
function sourceMatches(source, url, origin, redirectCount) {
|
|
268
|
+
const lower = source.toLowerCase(), targetScheme = scheme(url);
|
|
269
|
+
if (lower === "'self'")
|
|
270
|
+
return origin ? selfMatches(url, origin) ? "yes" : "no" : "unknown";
|
|
271
|
+
if (source === "*")
|
|
272
|
+
return ["http", "https"].includes(targetScheme) ? "yes" : origin ? scheme(origin) === targetScheme ? "yes" : "no" : "unknown";
|
|
273
|
+
const schemeOnly = source.match(/^([a-z][a-z0-9+.-]*):$/i);
|
|
274
|
+
if (schemeOnly)
|
|
275
|
+
return schemeMatches(schemeOnly[1], targetScheme) ? "yes" : "no";
|
|
276
|
+
const host = source.match(
|
|
277
|
+
/^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9.-]+)(?::(\*|[0-9]+))?(\/[^?#]*)?$/i
|
|
278
|
+
);
|
|
279
|
+
if (!host) return "no";
|
|
280
|
+
const [, explicitScheme, patternHost, port, path] = host;
|
|
281
|
+
if (!url.hostname || /^\[/.test(url.hostname) || /^\d+(?:\.\d+){3}$/.test(url.hostname))
|
|
282
|
+
return "no";
|
|
283
|
+
if (!explicitScheme && !origin) return "unknown";
|
|
284
|
+
if (!schemeMatches(explicitScheme ?? scheme(origin), targetScheme))
|
|
285
|
+
return "no";
|
|
286
|
+
const domain = url.hostname.toLowerCase(), pattern = patternHost.toLowerCase();
|
|
287
|
+
if (pattern !== "*" && !(pattern.startsWith("*.") ? domain.endsWith(pattern.slice(1)) : domain === pattern))
|
|
288
|
+
return "no";
|
|
289
|
+
if (port !== "*") {
|
|
290
|
+
const targetPort = url.port || void 0;
|
|
291
|
+
if (port === void 0 ? targetPort !== void 0 : Number(port) !== Number(targetPort ?? defaultPort(targetScheme)))
|
|
292
|
+
return "no";
|
|
293
|
+
}
|
|
294
|
+
if (path && !pathMatches(path, url.pathname)) {
|
|
295
|
+
if (redirectCount === void 0) return "unknown";
|
|
296
|
+
if (redirectCount === 0) return "no";
|
|
297
|
+
}
|
|
298
|
+
return "yes";
|
|
299
|
+
}
|
|
300
|
+
function matchPolicy(directives, directive, input, options = {}) {
|
|
301
|
+
const requested = friendly[directive] ?? directive.toLowerCase();
|
|
302
|
+
const name = requested === "script-src" ? "script-src-elem" : requested === "style-src" ? "style-src-elem" : requested;
|
|
303
|
+
const chain = fallbacks[name];
|
|
304
|
+
if (!chain)
|
|
305
|
+
return decision(
|
|
306
|
+
"indeterminate",
|
|
307
|
+
void 0,
|
|
308
|
+
"Unsupported directive or inline check"
|
|
309
|
+
);
|
|
310
|
+
const effective = chain.find(
|
|
311
|
+
(key) => Object.prototype.hasOwnProperty.call(directives, key)
|
|
312
|
+
);
|
|
313
|
+
if (!effective)
|
|
314
|
+
return decision("allowed", void 0, "No applicable directive");
|
|
315
|
+
if (name.endsWith("-attr"))
|
|
316
|
+
return decision(
|
|
317
|
+
"indeterminate",
|
|
318
|
+
effective,
|
|
319
|
+
"Inline checks require element content and context"
|
|
320
|
+
);
|
|
321
|
+
if (name === "frame-ancestors")
|
|
322
|
+
return decision(
|
|
323
|
+
"indeterminate",
|
|
324
|
+
effective,
|
|
325
|
+
"Frame enforcement depends on the complete ancestor chain"
|
|
326
|
+
);
|
|
327
|
+
if (options.redirectCount !== void 0 && (!Number.isInteger(options.redirectCount) || options.redirectCount < 0))
|
|
328
|
+
throw new TypeError("redirectCount must be a non-negative integer");
|
|
329
|
+
let url, origin;
|
|
330
|
+
try {
|
|
331
|
+
url = new URL(input);
|
|
332
|
+
if (options.origin !== void 0) {
|
|
333
|
+
origin = new URL(options.origin);
|
|
334
|
+
if (origin.origin === "null") throw new Error("opaque");
|
|
335
|
+
}
|
|
336
|
+
} catch {
|
|
337
|
+
throw new TypeError("Expected an absolute URL and a non-opaque origin");
|
|
338
|
+
}
|
|
339
|
+
const sources = directives[effective];
|
|
340
|
+
const script = name === "script-src" || name === "script-src-elem";
|
|
341
|
+
const style = name === "style-src" || name === "style-src-elem";
|
|
342
|
+
const hasNoncePlaceholder = sources.includes("'nonce-{nonce}'");
|
|
343
|
+
const nonceSources = sources.filter(
|
|
344
|
+
(s) => /^'nonce-[a-z0-9+/_=-]+'$/i.test(s)
|
|
345
|
+
);
|
|
346
|
+
const hashes = sources.filter(
|
|
347
|
+
(s) => /^'sha(256|384|512)-[a-z0-9+/_=-]+'$/i.test(s)
|
|
348
|
+
);
|
|
349
|
+
if ((script || style) && options.nonce && (nonceSources.some((s) => s.slice(7, -1) === options.nonce) || hasNoncePlaceholder && options.policyNonce !== void 0 && options.nonce === options.policyNonce))
|
|
350
|
+
return decision("allowed", effective, "Matching request nonce");
|
|
351
|
+
if (script && options.integrity?.length && options.integrity.every(
|
|
352
|
+
(token) => hashes.some((hash) => {
|
|
353
|
+
const [hashAlg, hashDigest] = hash.slice(1, -1).split("-", 2);
|
|
354
|
+
const [tokenAlg, tokenDigest] = token.split("-", 2);
|
|
355
|
+
return hashAlg?.toLowerCase() === tokenAlg?.toLowerCase() && hashDigest !== void 0 && hashDigest === tokenDigest;
|
|
356
|
+
})
|
|
357
|
+
))
|
|
358
|
+
return decision("allowed", effective, "Matching integrity metadata");
|
|
359
|
+
const missingNonce = (script || style) && (nonceSources.length > 0 && options.nonce === void 0 || hasNoncePlaceholder && (options.nonce === void 0 || options.nonce !== "" && options.policyNonce === void 0));
|
|
360
|
+
const missingIntegrity = script && hashes.length > 0 && options.integrity === void 0;
|
|
361
|
+
if (script && sources.some((s) => s.toLowerCase() === "'strict-dynamic'")) {
|
|
362
|
+
if (options.parserInserted === false)
|
|
363
|
+
return decision(
|
|
364
|
+
"allowed",
|
|
365
|
+
effective,
|
|
366
|
+
"Non-parser-inserted script under strict-dynamic"
|
|
367
|
+
);
|
|
368
|
+
if (options.parserInserted === void 0 || missingNonce || missingIntegrity)
|
|
369
|
+
return decision(
|
|
370
|
+
"indeterminate",
|
|
371
|
+
effective,
|
|
372
|
+
"Script nonce, integrity or parser metadata is missing"
|
|
373
|
+
);
|
|
374
|
+
return decision(
|
|
375
|
+
"blocked",
|
|
376
|
+
effective,
|
|
377
|
+
"Parser-inserted script has no matching nonce or integrity metadata"
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
let unknown = false;
|
|
381
|
+
for (const source of sources) {
|
|
382
|
+
const match = sourceMatches(source, url, origin, options.redirectCount);
|
|
383
|
+
if (match === "yes")
|
|
384
|
+
return decision("allowed", effective, void 0, source);
|
|
385
|
+
if (match === "unknown") unknown = true;
|
|
386
|
+
}
|
|
387
|
+
if (unknown || missingNonce || missingIntegrity)
|
|
388
|
+
return decision(
|
|
389
|
+
"indeterminate",
|
|
390
|
+
effective,
|
|
391
|
+
"Origin, redirect count, nonce or integrity metadata is missing"
|
|
392
|
+
);
|
|
393
|
+
return decision("blocked", effective, "No source matched");
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// src/core.ts
|
|
397
|
+
import { z as z2 } from "zod";
|
|
398
|
+
function freeze(value) {
|
|
399
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
400
|
+
Object.values(value).forEach(freeze);
|
|
401
|
+
Object.freeze(value);
|
|
402
|
+
}
|
|
403
|
+
return value;
|
|
404
|
+
}
|
|
405
|
+
function defineRuleSet(input) {
|
|
406
|
+
const parsed = ruleSetSchema.safeParse(input);
|
|
407
|
+
if (!parsed.success) {
|
|
408
|
+
const name = typeof input?.name === "string" ? input.name : "<unnamed>";
|
|
409
|
+
const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
|
|
410
|
+
throw new z2.ZodError(
|
|
411
|
+
parsed.error.issues.map((issue) => ({
|
|
412
|
+
...issue,
|
|
413
|
+
message: `RuleSet "${name}" - ${detail}`
|
|
414
|
+
}))
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
return freeze(parsed.data);
|
|
418
|
+
}
|
|
419
|
+
function entryValue(entry) {
|
|
420
|
+
return typeof entry === "string" ? entry : entry.source;
|
|
421
|
+
}
|
|
422
|
+
function entryReason(entry) {
|
|
423
|
+
return typeof entry === "string" ? void 0 : entry.reason;
|
|
424
|
+
}
|
|
425
|
+
var Policy = class _Policy {
|
|
426
|
+
config;
|
|
427
|
+
constructor(input) {
|
|
428
|
+
const result = policyConfigSchema.safeParse(input);
|
|
429
|
+
if (!result.success) {
|
|
430
|
+
throw new z2.ZodError(
|
|
431
|
+
result.error.issues.map((issue) => {
|
|
432
|
+
const index = issue.path[0] === "ruleSets" && typeof issue.path[1] === "number" ? issue.path[1] : void 0;
|
|
433
|
+
const name = index === void 0 ? void 0 : input.ruleSets?.[index]?.name;
|
|
434
|
+
return name ? {
|
|
435
|
+
...issue,
|
|
436
|
+
message: `RuleSet "${name}" - ${issue.path.slice(2).join(".")}: ${issue.message}`
|
|
437
|
+
} : issue;
|
|
438
|
+
})
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
const config = result.data;
|
|
442
|
+
this.config = freeze(config);
|
|
443
|
+
Object.freeze(this);
|
|
444
|
+
}
|
|
445
|
+
/** Sources and their contributing rule sets. Duplicate values retain all contributors. */
|
|
446
|
+
explain() {
|
|
447
|
+
const rows = [];
|
|
448
|
+
const add = (directive, entries, ruleSet) => {
|
|
449
|
+
for (const entry of entries) {
|
|
450
|
+
const reason = entryReason(entry);
|
|
451
|
+
rows.push({
|
|
452
|
+
directive,
|
|
453
|
+
source: entryValue(entry),
|
|
454
|
+
ruleSet,
|
|
455
|
+
...reason === void 0 ? {} : { reason }
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
const collect = (rules, name) => {
|
|
460
|
+
for (const [key, value] of Object.entries(rules)) {
|
|
461
|
+
if (key === "directives" && value) {
|
|
462
|
+
for (const [directive, entries] of Object.entries(
|
|
463
|
+
value
|
|
464
|
+
))
|
|
465
|
+
add(directive, entries, name);
|
|
466
|
+
} else if (Array.isArray(value)) {
|
|
467
|
+
const directive = resourceDirectives[key] ?? baseDirectives[key];
|
|
468
|
+
if (directive) add(directive, value, name);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
collect(this.config.base, "base");
|
|
473
|
+
for (const set of this.config.ruleSets)
|
|
474
|
+
if (set.enabled) collect(set.rules, set.name);
|
|
475
|
+
return rows.sort(
|
|
476
|
+
(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")
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
/** Merged sources, deduplicated without changing path syntax. */
|
|
480
|
+
toObject() {
|
|
481
|
+
const map = /* @__PURE__ */ Object.create(null);
|
|
482
|
+
for (const row of this.explain())
|
|
483
|
+
(map[row.directive] ??= /* @__PURE__ */ new Set()).add(row.source);
|
|
484
|
+
if (this.config.base.upgradeInsecureRequests)
|
|
485
|
+
map["upgrade-insecure-requests"] = /* @__PURE__ */ new Set();
|
|
486
|
+
if (this.config.reporting?.uri)
|
|
487
|
+
map["report-uri"] = /* @__PURE__ */ new Set([this.config.reporting.uri]);
|
|
488
|
+
if (this.config.reporting?.to)
|
|
489
|
+
map["report-to"] = /* @__PURE__ */ new Set([this.config.reporting.to]);
|
|
490
|
+
return Object.fromEntries(
|
|
491
|
+
Object.entries(map).sort(([a], [b]) => a.localeCompare(b, "en")).map(([key, values]) => [key, Array.from(values).sort()])
|
|
492
|
+
);
|
|
493
|
+
}
|
|
494
|
+
/** Evaluate a URL with explicit uncertainty when browser context is missing. */
|
|
495
|
+
allows(directive, url, options = {}) {
|
|
496
|
+
const result = matchPolicy(this.toObject(), directive, url, options);
|
|
497
|
+
const contributors = result.matchedSource && result.effectiveDirective ? this.explain().filter(
|
|
498
|
+
(row) => row.directive === result.effectiveDirective && row.source === result.matchedSource
|
|
499
|
+
) : [];
|
|
500
|
+
return contributors.length ? { ...result, contributors } : result;
|
|
501
|
+
}
|
|
502
|
+
/** Render a header value. Pretty output is for display only and is not a valid HTTP header value. */
|
|
503
|
+
toHeader(options = {}) {
|
|
504
|
+
const directives = this.toObject();
|
|
505
|
+
const hasNonce = Object.values(directives).some(
|
|
506
|
+
(sources) => sources.includes(NONCE)
|
|
507
|
+
);
|
|
508
|
+
if (hasNonce && (!options.nonce || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(options.nonce)))
|
|
509
|
+
throw new Error("A valid base64 nonce is required");
|
|
510
|
+
return Object.entries(directives).map(([directive, values]) => {
|
|
511
|
+
const rendered = values.map(
|
|
512
|
+
(value) => value === NONCE ? `'nonce-${options.nonce}'` : value
|
|
513
|
+
);
|
|
514
|
+
return directive + (rendered.length ? ` ${rendered.join(" ")}` : "");
|
|
515
|
+
}).join(options.pretty ? ";\n" : "; ");
|
|
516
|
+
}
|
|
517
|
+
withRuleSet(ruleSets) {
|
|
518
|
+
const additions = Array.isArray(ruleSets) ? ruleSets : [ruleSets];
|
|
519
|
+
return new _Policy({
|
|
520
|
+
...this.config,
|
|
521
|
+
ruleSets: [...this.config.ruleSets, ...additions]
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
without(name) {
|
|
525
|
+
return new _Policy({
|
|
526
|
+
...this.config,
|
|
527
|
+
ruleSets: this.config.ruleSets.filter((set) => set.name !== name)
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
function definePolicy(input) {
|
|
532
|
+
return new Policy(input);
|
|
533
|
+
}
|
|
534
|
+
|
|
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,
|
|
547
|
+
resourceDirectives,
|
|
548
|
+
baseDirectives,
|
|
549
|
+
sourceEntrySchema,
|
|
550
|
+
rulesSchema,
|
|
551
|
+
baseSchema,
|
|
552
|
+
ruleSetSchema,
|
|
553
|
+
policyConfigSchema,
|
|
554
|
+
matchPolicy,
|
|
555
|
+
defineRuleSet,
|
|
556
|
+
Policy,
|
|
557
|
+
definePolicy
|
|
558
|
+
};
|
|
559
|
+
//# sourceMappingURL=chunk-JAXLODN4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/keywords.ts","../src/schemas.ts","../src/matching/index.ts","../src/core.ts"],"sourcesContent":["/** Allow resources from the protected document's origin. */\nexport const SELF = \"'self'\";\n/** Block all resources for a directive. */\nexport const NONE = \"'none'\";\n/** Replaced with the per-response nonce passed to toHeader({ nonce }). */\nexport const NONCE = \"'nonce-{nonce}'\";\n/** Propagate trust from nonce- or hash-authorized scripts. */\nexport const STRICT_DYNAMIC = \"'strict-dynamic'\";\n/** Include code samples in applicable violation reports. */\nexport const REPORT_SAMPLE = \"'report-sample'\";\n/** Permit WebAssembly compilation without general JavaScript evaluation. */\nexport const WASM_UNSAFE_EVAL = \"'wasm-unsafe-eval'\";\n/** Use Web Crypto to create a fresh, unpredictable per-response nonce. */\nexport function generateNonce(): string {\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return btoa(String.fromCharCode(...bytes));\n}\n\n/** Permit inline code; weakens XSS protection unless ignored by a nonce or hash. */\nexport const unsafeInline = ({ reason }: { reason: string }) => ({\n source: \"'unsafe-inline'\",\n reason,\n});\n/** Permit dynamic JavaScript evaluation; increases XSS risk. */\nexport const unsafeEval = ({ reason }: { reason: string }) => ({\n source: \"'unsafe-eval'\",\n reason,\n});\n/** Permit hashes for inline handlers; can weaken protection. */\nexport const unsafeHashes = ({ reason }: { reason: string }) => ({\n source: \"'unsafe-hashes'\",\n reason,\n});\n/** Create a CSP hash source expression. */\nexport const cspHash = (\n algorithm: 'sha256' | 'sha384' | 'sha512',\n digest: string,\n) => `'${algorithm}-${digest}'`;\n","/* eslint-disable no-control-regex -- CSP input must reject ASCII control characters. */\nimport { z } from 'zod';\nimport { NONCE } from './keywords';\n\n/** Friendly resource names mapped to CSP directives. */\nexport const resourceDirectives = {\n scripts: 'script-src',\n connect: 'connect-src',\n images: 'img-src',\n styles: 'style-src',\n fonts: 'font-src',\n frames: 'frame-src',\n forms: 'form-action',\n media: 'media-src',\n workers: 'worker-src',\n manifest: 'manifest-src',\n} as const;\nexport const baseDirectives = {\n default: 'default-src',\n objects: 'object-src',\n baseUri: 'base-uri',\n frameAncestors: 'frame-ancestors',\n} as const;\nconst risky = new Set([\"'unsafe-inline'\", \"'unsafe-eval'\", \"'unsafe-hashes'\"]);\nconst keywords = new Set([\n \"'self'\",\n \"'none'\",\n \"'strict-dynamic'\",\n \"'report-sample'\",\n \"'wasm-unsafe-eval'\",\n ...risky,\n]);\n\nfunction isSource(value: string): boolean {\n if (\n !value ||\n /[\\x00-\\x20\\x7f;,]/.test(value) ||\n /^[a-z][a-z0-9+.-]*\\/\\//i.test(value)\n )\n return false;\n if (\n keywords.has(value.toLowerCase()) ||\n value === NONCE ||\n value === '*' ||\n /^[a-z][a-z0-9+.-]*:\\/\\/\\*(?::(?:\\d+|\\*))?(?:\\/[^\\s;,#?]*)?$/i.test(value)\n )\n return true;\n if (\n /^'(nonce-[A-Za-z0-9+/_-]+={0,2}|sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2})'$/i.test(\n value,\n )\n )\n return true;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:$/.test(value)) return true;\n // CSP host-source, including scheme-less hosts, optional wildcard, port and path.\n return /^(?:[a-z][a-z0-9+.-]*:\\/\\/)?(?:\\*\\.)?(?:[a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+(?::(?:\\d+|\\*))?(?:\\/[^\\s;,#?]*)?$/i.test(\n value,\n );\n}\nconst sourceStringSchema = z\n .string()\n .refine(isSource, 'Invalid CSP source expression');\n/** A source string, or a source annotated with a human-readable reason. Risky keywords require a reason. */\nexport const sourceEntrySchema = z.union([\n sourceStringSchema.refine(\n (s) => !risky.has(s.toLowerCase()),\n 'Risky keyword requires a reason',\n ),\n z\n .object({ source: sourceStringSchema, reason: z.string().trim().min(1) })\n .strict(),\n]);\nconst sourceList = z.array(sourceEntrySchema).min(1);\nconst sourceListDirectives = new Set([\n ...Object.values(resourceDirectives),\n ...Object.values(baseDirectives),\n 'script-src-elem',\n 'script-src-attr',\n 'style-src-elem',\n 'style-src-attr',\n 'child-src',\n]);\nconst rawDirectives = z.record(\n z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/)\n .refine(\n (name) => sourceListDirectives.has(name),\n 'Unsupported raw directive; only known source-list directives are supported',\n ),\n sourceList,\n);\nconst reserved = new Set([\n 'report-uri',\n 'report-to',\n 'upgrade-insecure-requests',\n]);\nconst baseOnly = new Set([...Object.values(baseDirectives), ...reserved]);\nconst ruleShape = Object.fromEntries(\n Object.keys(resourceDirectives).map((key) => [key, sourceList.optional()]),\n) as {\n [K in keyof typeof resourceDirectives]: z.ZodOptional<typeof sourceList>;\n};\n/** Rule-set permissions. At least one directive must be supplied. */\nexport const rulesSchema = z\n .object({ ...ruleShape, directives: rawDirectives.optional() })\n .strict()\n .refine(\n (rules) =>\n Object.entries(rules).some(([key, value]) =>\n key === 'directives'\n ? Object.keys(value ?? {}).length > 0\n : value !== undefined,\n ),\n 'At least one resource directive is required',\n )\n .superRefine((rules, ctx) => {\n for (const directive of Object.keys(rules.directives ?? {})) {\n if (baseOnly.has(directive))\n ctx.addIssue({\n code: 'custom',\n path: ['directives', directive],\n message: 'Base-only or reserved directive',\n });\n }\n });\n/** Site-wide directives. */\nexport const baseSchema = z\n .object({\n ...ruleShape,\n default: sourceList.optional(),\n objects: sourceList.optional(),\n baseUri: sourceList.optional(),\n frameAncestors: sourceList.optional(),\n upgradeInsecureRequests: z.boolean().optional(),\n directives: rawDirectives.optional(),\n })\n .strict()\n .superRefine((base, ctx) => {\n for (const directive of Object.keys(base.directives ?? {})) {\n if (reserved.has(directive))\n ctx.addIssue({\n code: 'custom',\n path: ['directives', directive],\n message: 'Use the dedicated configuration field for this directive',\n });\n }\n });\n/** A named, documented and optionally disabled group of permissions. */\nexport const ruleSetSchema = z\n .object({\n name: z.string().trim().min(1),\n purpose: z.string().trim().min(1),\n owner: z.string().trim().min(1).optional(),\n docs: z.url().optional(),\n tags: z.array(z.string().trim().min(1)).optional(),\n reviewBy: z.iso.date().optional(),\n enabled: z.boolean().default(true),\n rules: rulesSchema,\n })\n .strict();\nconst reportingSchema = z\n .object({\n uri: z\n .url()\n .refine(\n (value) => !/[\\x00-\\x20\\x7f;,]/.test(value),\n 'Invalid reporting value',\n )\n .optional(),\n to: z\n .string()\n .regex(/^[A-Za-z0-9_-]+$/)\n .optional(),\n })\n .strict();\n/** Complete configuration. Zod catches duplicate names and invalid rule sets. */\nexport const policyConfigSchema = z\n .object({\n base: baseSchema.default({}),\n ruleSets: z.array(ruleSetSchema).default([]),\n reporting: reportingSchema.optional(),\n })\n .strict()\n .superRefine((config, ctx) => {\n const names = new Set<string>();\n config.ruleSets.forEach((rule, i) => {\n if (names.has(rule.name))\n ctx.addIssue({\n code: 'custom',\n path: ['ruleSets', i, 'name'],\n message: `Duplicate rule set name: ${rule.name}`,\n });\n names.add(rule.name);\n });\n });\nexport type SourceEntry = z.output<typeof sourceEntrySchema>;\nexport type Rules = z.output<typeof rulesSchema>;\nexport type ResourceKey = keyof typeof resourceDirectives;\nexport type RuleSetInput = z.input<typeof ruleSetSchema>;\nexport type RuleSet = z.output<typeof ruleSetSchema>;\nexport type PolicyConfig = z.input<typeof policyConfigSchema>;\nexport type NormalizedPolicyConfig = z.output<typeof policyConfigSchema>;\nexport type DirectiveName =\n | (typeof resourceDirectives)[ResourceKey]\n | (typeof baseDirectives)[keyof typeof baseDirectives]\n | 'upgrade-insecure-requests'\n | 'report-uri'\n | 'report-to';\n","/** Request metadata needed to evaluate checks which cannot be decided from a URL alone. */\nexport interface MatchOptions {\n /** Origin of the protected document, required for 'self' and schemeless sources. */\n origin?: string;\n /** Number of redirects before this URL; paths are not checked after a redirect. */\n redirectCount?: number;\n /** Nonce on the request; supply an empty string if the request has none. */\n nonce?: string;\n /** Rendered policy nonce for a dynamic nonce placeholder. */\n policyNonce?: string;\n /** Integrity metadata tokens on the request; supply an empty array if absent. */\n integrity?: readonly string[];\n /** Whether a script was parser-inserted. */\n parserInserted?: boolean;\n}\n\n/** A conservative CSP decision. `indeterminate` never implies browser permission. */\nexport interface AllowsResult {\n status: 'allowed' | 'blocked' | 'indeterminate';\n allowed: boolean | null;\n effectiveDirective?: string;\n matchedSource?: string;\n reason?: string;\n}\n\ntype Match = 'yes' | 'no' | 'unknown';\nconst friendly: Record<string, string> = {\n scripts: 'script-src',\n connect: 'connect-src',\n images: 'img-src',\n styles: 'style-src',\n fonts: 'font-src',\n frames: 'frame-src',\n forms: 'form-action',\n media: 'media-src',\n workers: 'worker-src',\n manifest: 'manifest-src',\n default: 'default-src',\n objects: 'object-src',\n baseUri: 'base-uri',\n frameAncestors: 'frame-ancestors',\n};\nconst fallbacks: Record<string, readonly string[]> = {\n 'script-src-elem': ['script-src-elem', 'script-src', 'default-src'],\n 'script-src-attr': ['script-src-attr', 'script-src', 'default-src'],\n 'style-src-elem': ['style-src-elem', 'style-src', 'default-src'],\n 'style-src-attr': ['style-src-attr', 'style-src', 'default-src'],\n 'worker-src': ['worker-src', 'child-src', 'script-src', 'default-src'],\n 'frame-src': ['frame-src', 'child-src', 'default-src'],\n};\nfor (const name of [\n 'script-src',\n 'style-src',\n 'child-src',\n 'connect-src',\n 'font-src',\n 'img-src',\n 'manifest-src',\n 'media-src',\n 'object-src',\n]) {\n fallbacks[name] = [name, 'default-src'];\n}\nfor (const name of [\n 'default-src',\n 'form-action',\n 'base-uri',\n 'frame-ancestors',\n])\n fallbacks[name] = [name];\n\nfunction decision(\n status: AllowsResult['status'],\n effectiveDirective?: string,\n reason?: string,\n matchedSource?: string,\n): AllowsResult {\n return {\n status,\n allowed: status === 'indeterminate' ? null : status === 'allowed',\n ...(effectiveDirective && { effectiveDirective }),\n ...(reason && { reason }),\n ...(matchedSource && { matchedSource }),\n };\n}\n\n// CSP3 §6.7.2.9: upgrades are asymmetric; ws and wss have special cases.\nfunction schemeMatches(source: string, target: string): boolean {\n source = source.toLowerCase();\n target = target.toLowerCase();\n return (\n source === target ||\n (source === 'http' && target === 'https') ||\n (source === 'ws' && ['wss', 'http', 'https'].includes(target)) ||\n (source === 'wss' && target === 'https')\n );\n}\nfunction scheme(url: URL): string {\n return url.protocol.slice(0, -1).toLowerCase();\n}\nfunction defaultPort(s: string): string | undefined {\n return (\n { http: '80', https: '443', ws: '80', wss: '443', ftp: '21' } as Record<\n string,\n string\n >\n )[s];\n}\nfunction selfMatches(url: URL, origin: URL): boolean {\n if (scheme(url) === 'blob') return false;\n if (origin.origin !== 'null' && origin.origin === url.origin) return true;\n const os = scheme(origin),\n us = scheme(url);\n const portsMatch = origin.port === url.port || (!origin.port && !url.port);\n return (\n origin.hostname !== '' &&\n origin.hostname === url.hostname &&\n portsMatch &&\n (us === 'https' ||\n us === 'wss' ||\n (os === 'http' && (us === 'http' || us === 'ws')))\n );\n}\n// Percent-decode each segment to bytes, not URI components: %2F remains inside its segment.\nfunction segmentBytes(segment: string): string {\n const bytes: number[] = [];\n for (let i = 0; i < segment.length;) {\n const encoded = segment.slice(i).match(/^%([0-9a-f]{2})/i);\n if (encoded) {\n bytes.push(parseInt(encoded[1]!, 16));\n i += 3;\n continue;\n }\n const point = segment.codePointAt(i)!;\n const character = String.fromCodePoint(point);\n bytes.push(...new TextEncoder().encode(character));\n i += character.length;\n }\n return bytes.join(',');\n}\n// CSP3 §6.7.2.12: a trailing slash makes the source a segment prefix.\nfunction pathMatches(pattern: string, target: string): boolean {\n if (!pattern || (pattern === '/' && !target)) return true;\n const a = pattern.split('/'),\n b = target.split('/');\n if (a.length > b.length || (!pattern.endsWith('/') && a.length !== b.length))\n return false;\n if (pattern.endsWith('/')) a.pop();\n return a.every((part, i) => segmentBytes(part) === segmentBytes(b[i]!));\n}\n\n// CSP3 §§6.7.2.8–12. Unknown context stays unknown instead of silently assuming it.\nfunction sourceMatches(\n source: string,\n url: URL,\n origin: URL | undefined,\n redirectCount: number | undefined,\n): Match {\n const lower = source.toLowerCase(),\n targetScheme = scheme(url);\n if (lower === \"'self'\")\n return origin ? (selfMatches(url, origin) ? 'yes' : 'no') : 'unknown';\n if (source === '*')\n return ['http', 'https'].includes(targetScheme)\n ? 'yes'\n : origin\n ? scheme(origin) === targetScheme\n ? 'yes'\n : 'no'\n : 'unknown';\n const schemeOnly = source.match(/^([a-z][a-z0-9+.-]*):$/i);\n if (schemeOnly)\n return schemeMatches(schemeOnly[1]!, targetScheme) ? 'yes' : 'no';\n // Host expressions do not admit credentials, query strings, or fragments.\n const host = source.match(\n /^(?:([a-z][a-z0-9+.-]*):\\/\\/)?(\\*|(?:\\*\\.)?[a-z0-9.-]+)(?::(\\*|[0-9]+))?(\\/[^?#]*)?$/i,\n );\n if (!host) return 'no';\n const [, explicitScheme, patternHost, port, path] = host;\n if (\n !url.hostname ||\n /^\\[/.test(url.hostname) ||\n /^\\d+(?:\\.\\d+){3}$/.test(url.hostname)\n )\n return 'no';\n if (!explicitScheme && !origin) return 'unknown';\n if (!schemeMatches(explicitScheme ?? scheme(origin!), targetScheme))\n return 'no';\n const domain = url.hostname.toLowerCase(),\n pattern = patternHost!.toLowerCase();\n if (\n pattern !== '*' &&\n !(pattern.startsWith('*.')\n ? domain.endsWith(pattern.slice(1))\n : domain === pattern)\n )\n return 'no';\n if (port !== '*') {\n const targetPort = url.port || undefined;\n if (\n port === undefined\n ? targetPort !== undefined\n : Number(port) !== Number(targetPort ?? defaultPort(targetScheme))\n )\n return 'no';\n }\n if (path && !pathMatches(path, url.pathname)) {\n if (redirectCount === undefined) return 'unknown';\n if (redirectCount === 0) return 'no';\n }\n return 'yes';\n}\n\n/**\n * Evaluate a URL against a CSP directive. This deliberately returns indeterminate when\n * relevant request context is unavailable. It is not a full browser simulation.\n * Algorithms: https://www.w3.org/TR/CSP3/#match-url-to-source-list and #directive-fallback-list\n */\nexport function matchPolicy(\n directives: Readonly<Record<string, readonly string[]>>,\n directive: string,\n input: string,\n options: MatchOptions = {},\n): AllowsResult {\n const requested = friendly[directive] ?? directive.toLowerCase();\n // URL checks for scripts and styles represent element fetches, whose explicit\n // -elem directives take precedence over script-src/style-src (CSP3 �6.8.3).\n const name =\n requested === 'script-src'\n ? 'script-src-elem'\n : requested === 'style-src'\n ? 'style-src-elem'\n : requested;\n const chain = fallbacks[name];\n if (!chain)\n return decision(\n 'indeterminate',\n undefined,\n 'Unsupported directive or inline check',\n );\n const effective = chain.find((key) =>\n Object.prototype.hasOwnProperty.call(directives, key),\n );\n if (!effective)\n return decision('allowed', undefined, 'No applicable directive');\n if (name.endsWith('-attr'))\n return decision(\n 'indeterminate',\n effective,\n 'Inline checks require element content and context',\n );\n if (name === 'frame-ancestors')\n return decision(\n 'indeterminate',\n effective,\n 'Frame enforcement depends on the complete ancestor chain',\n );\n if (\n options.redirectCount !== undefined &&\n (!Number.isInteger(options.redirectCount) || options.redirectCount < 0)\n )\n throw new TypeError('redirectCount must be a non-negative integer');\n let url: URL, origin: URL | undefined;\n try {\n url = new URL(input);\n if (options.origin !== undefined) {\n origin = new URL(options.origin);\n if (origin.origin === 'null') throw new Error('opaque');\n }\n } catch {\n throw new TypeError('Expected an absolute URL and a non-opaque origin');\n }\n const sources = directives[effective]!;\n const script = name === 'script-src' || name === 'script-src-elem';\n const style = name === 'style-src' || name === 'style-src-elem';\n const hasNoncePlaceholder = sources.includes(\"'nonce-{nonce}'\");\n const nonceSources = sources.filter((s) =>\n /^'nonce-[a-z0-9+/_=-]+'$/i.test(s),\n );\n const hashes = sources.filter((s) =>\n /^'sha(256|384|512)-[a-z0-9+/_=-]+'$/i.test(s),\n );\n if (\n (script || style) &&\n options.nonce &&\n (nonceSources.some((s) => s.slice(7, -1) === options.nonce) ||\n (hasNoncePlaceholder &&\n options.policyNonce !== undefined &&\n options.nonce === options.policyNonce))\n )\n return decision('allowed', effective, 'Matching request nonce');\n if (\n script &&\n options.integrity?.length &&\n options.integrity.every((token) =>\n hashes.some((hash) => {\n const [hashAlg, hashDigest] = hash.slice(1, -1).split('-', 2);\n const [tokenAlg, tokenDigest] = token.split('-', 2);\n return (\n hashAlg?.toLowerCase() === tokenAlg?.toLowerCase() &&\n hashDigest !== undefined &&\n hashDigest === tokenDigest\n );\n }),\n )\n )\n return decision('allowed', effective, 'Matching integrity metadata');\n const missingNonce =\n (script || style) &&\n ((nonceSources.length > 0 && options.nonce === undefined) ||\n (hasNoncePlaceholder &&\n (options.nonce === undefined ||\n (options.nonce !== '' && options.policyNonce === undefined))));\n const missingIntegrity =\n script && hashes.length > 0 && options.integrity === undefined;\n if (script && sources.some((s) => s.toLowerCase() === \"'strict-dynamic'\")) {\n if (options.parserInserted === false)\n return decision(\n 'allowed',\n effective,\n 'Non-parser-inserted script under strict-dynamic',\n );\n if (\n options.parserInserted === undefined ||\n missingNonce ||\n missingIntegrity\n )\n return decision(\n 'indeterminate',\n effective,\n 'Script nonce, integrity or parser metadata is missing',\n );\n return decision(\n 'blocked',\n effective,\n 'Parser-inserted script has no matching nonce or integrity metadata',\n );\n }\n let unknown = false;\n for (const source of sources) {\n const match = sourceMatches(source, url, origin, options.redirectCount);\n if (match === 'yes')\n return decision('allowed', effective, undefined, source);\n if (match === 'unknown') unknown = true;\n }\n if (unknown || missingNonce || missingIntegrity)\n return decision(\n 'indeterminate',\n effective,\n 'Origin, redirect count, nonce or integrity metadata is missing',\n );\n return decision('blocked', effective, 'No source matched');\n}\n","import { matchPolicy } from './matching';\nimport type { AllowsResult, MatchOptions } from './matching';\nimport { z } from 'zod';\nimport { NONCE } from './keywords';\nimport {\n baseDirectives,\n policyConfigSchema,\n resourceDirectives,\n ruleSetSchema,\n} from './schemas';\nimport type {\n NormalizedPolicyConfig,\n PolicyConfig,\n RuleSet,\n RuleSetInput,\n SourceEntry,\n} from './schemas';\n\n/** Reject literal risky strings in input lists while allowing annotated source objects.\n * Dynamic strings remain subject to runtime Zod validation. */\nexport type RequireRiskReasons<T> = T extends { source: string }\n ? T\n : T extends string\n ? Lowercase<T> extends\n \"'unsafe-inline'\" | \"'unsafe-eval'\" | \"'unsafe-hashes'\"\n ? never\n : T\n : T extends object\n ? {\n [K in keyof T]: K extends\n | 'name'\n | 'purpose'\n | 'owner'\n | 'docs'\n | 'tags'\n | 'reviewBy'\n | 'enabled'\n | 'reporting'\n ? T[K]\n : RequireRiskReasons<T[K]>;\n }\n : T;\n\nexport interface ExplainRow {\n directive: string;\n source: string;\n ruleSet: string;\n reason?: string;\n}\nexport interface HeaderOptions {\n nonce?: string;\n pretty?: boolean;\n}\nfunction freeze<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.values(value).forEach(freeze);\n Object.freeze(value);\n }\n return value;\n}\n/** Validate and freeze a rule set. */\nexport function defineRuleSet<const T extends RuleSetInput>(\n input: T & RequireRiskReasons<T>,\n): RuleSet {\n const parsed = ruleSetSchema.safeParse(input);\n if (!parsed.success) {\n const name = typeof input?.name === 'string' ? input.name : '<unnamed>';\n const detail = parsed.error.issues\n .map((issue) => `${issue.path.join('.') || '<root>'}: ${issue.message}`)\n .join('; ');\n throw new z.ZodError(\n parsed.error.issues.map((issue) => ({\n ...issue,\n message: `RuleSet \"${name}\" - ${detail}`,\n })),\n );\n }\n return freeze(parsed.data);\n}\nfunction entryValue(entry: SourceEntry): string {\n return typeof entry === 'string' ? entry : entry.source;\n}\nfunction entryReason(entry: SourceEntry): string | undefined {\n return typeof entry === 'string' ? undefined : entry.reason;\n}\n/** Immutable CSP configuration and its deterministic merged representation. */\nexport class Policy {\n readonly config: NormalizedPolicyConfig;\n constructor(input: PolicyConfig) {\n const result = policyConfigSchema.safeParse(input);\n if (!result.success) {\n throw new z.ZodError(\n result.error.issues.map((issue) => {\n const index =\n issue.path[0] === 'ruleSets' && typeof issue.path[1] === 'number'\n ? issue.path[1]\n : undefined;\n const name =\n index === undefined ? undefined : input.ruleSets?.[index]?.name;\n return name\n ? {\n ...issue,\n message: `RuleSet \"${name}\" - ${issue.path.slice(2).join('.')}: ${issue.message}`,\n }\n : issue;\n }),\n );\n }\n const config = result.data;\n this.config = freeze(config);\n Object.freeze(this);\n }\n /** Sources and their contributing rule sets. Duplicate values retain all contributors. */\n explain(): ExplainRow[] {\n const rows: ExplainRow[] = [];\n const add = (\n directive: string,\n entries: SourceEntry[],\n ruleSet: string,\n ) => {\n for (const entry of entries) {\n const reason = entryReason(entry);\n rows.push({\n directive,\n source: entryValue(entry),\n ruleSet,\n ...(reason === undefined ? {} : { reason }),\n });\n }\n };\n const collect = (rules: Record<string, unknown>, name: string) => {\n for (const [key, value] of Object.entries(rules)) {\n if (key === 'directives' && value) {\n for (const [directive, entries] of Object.entries(\n value as Record<string, SourceEntry[]>,\n ))\n add(directive, entries, name);\n } else if (Array.isArray(value)) {\n const directive =\n (resourceDirectives as Record<string, string>)[key] ??\n (baseDirectives as Record<string, string>)[key];\n if (directive) add(directive, value as SourceEntry[], name);\n }\n }\n };\n collect(this.config.base, 'base');\n for (const set of this.config.ruleSets)\n if (set.enabled) collect(set.rules, set.name);\n return rows.sort(\n (a, b) =>\n a.directive.localeCompare(b.directive, 'en') ||\n a.source.localeCompare(b.source, 'en') ||\n a.ruleSet.localeCompare(b.ruleSet, 'en') ||\n (a.reason ?? '').localeCompare(b.reason ?? '', 'en'),\n );\n }\n /** Merged sources, deduplicated without changing path syntax. */\n toObject(): Record<string, string[]> {\n const map: Record<string, Set<string>> = Object.create(null) as Record<\n string,\n Set<string>\n >;\n for (const row of this.explain())\n (map[row.directive] ??= new Set()).add(row.source);\n if (this.config.base.upgradeInsecureRequests)\n map['upgrade-insecure-requests'] = new Set();\n if (this.config.reporting?.uri)\n map['report-uri'] = new Set([this.config.reporting.uri]);\n if (this.config.reporting?.to)\n map['report-to'] = new Set([this.config.reporting.to]);\n return Object.fromEntries(\n Object.entries(map)\n .sort(([a], [b]) => a.localeCompare(b, 'en'))\n .map(([key, values]) => [key, Array.from(values).sort()]),\n );\n }\n /** Evaluate a URL with explicit uncertainty when browser context is missing. */\n allows(\n directive: string,\n url: string,\n options: MatchOptions = {},\n ): AllowsResult & { contributors?: ExplainRow[] } {\n const result = matchPolicy(this.toObject(), directive, url, options);\n const contributors =\n result.matchedSource && result.effectiveDirective\n ? this.explain().filter(\n (row) =>\n row.directive === result.effectiveDirective &&\n row.source === result.matchedSource,\n )\n : [];\n return contributors.length ? { ...result, contributors } : result;\n }\n /** Render a header value. Pretty output is for display only and is not a valid HTTP header value. */\n toHeader(options: HeaderOptions = {}): string {\n const directives = this.toObject();\n const hasNonce = Object.values(directives).some((sources) =>\n sources.includes(NONCE),\n );\n if (\n hasNonce &&\n (!options.nonce || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(options.nonce))\n )\n throw new Error('A valid base64 nonce is required');\n return Object.entries(directives)\n .map(([directive, values]) => {\n const rendered = values.map((value) =>\n value === NONCE ? `'nonce-${options.nonce}'` : value,\n );\n return directive + (rendered.length ? ` ${rendered.join(' ')}` : '');\n })\n .join(options.pretty ? ';\\n' : '; ');\n }\n /** Add one or several rule sets in a single validated, immutable update. */\n withRuleSet<const T extends readonly RuleSetInput[]>(\n ruleSets: T & (T extends RequireRiskReasons<T> ? unknown : never),\n ): Policy;\n withRuleSet<const T extends RuleSetInput>(\n ruleSet: T & RequireRiskReasons<T>,\n ): Policy;\n withRuleSet(ruleSets: RuleSetInput | readonly RuleSetInput[]): Policy {\n const additions: readonly RuleSetInput[] = Array.isArray(ruleSets)\n ? ruleSets\n : [ruleSets as RuleSetInput];\n return new Policy({\n ...this.config,\n ruleSets: [...this.config.ruleSets, ...additions],\n });\n }\n without(name: string): Policy {\n return new Policy({\n ...this.config,\n ruleSets: this.config.ruleSets.filter((set) => set.name !== name),\n });\n }\n}\n/** Validate and construct a policy. */\nexport function definePolicy<const T extends PolicyConfig>(\n input: T & RequireRiskReasons<T>,\n): Policy {\n return new Policy(input);\n}\n"],"mappings":";AACO,IAAM,OAAO;AAEb,IAAM,OAAO;AAEb,IAAM,QAAQ;AAEd,IAAM,iBAAiB;AAEvB,IAAM,gBAAgB;AAEtB,IAAM,mBAAmB;AAEzB,SAAS,gBAAwB;AACtC,QAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,aAAW,OAAO,gBAAgB,KAAK;AACvC,SAAO,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC;AAC3C;AAGO,IAAM,eAAe,CAAC,EAAE,OAAO,OAA2B;AAAA,EAC/D,QAAQ;AAAA,EACR;AACF;AAEO,IAAM,aAAa,CAAC,EAAE,OAAO,OAA2B;AAAA,EAC7D,QAAQ;AAAA,EACR;AACF;AAEO,IAAM,eAAe,CAAC,EAAE,OAAO,OAA2B;AAAA,EAC/D,QAAQ;AAAA,EACR;AACF;AAEO,IAAM,UAAU,CACrB,WACA,WACG,IAAI,SAAS,IAAI,MAAM;;;ACrC5B,SAAS,SAAS;AAIX,IAAM,qBAAqB;AAAA,EAChC,SAAS;AAAA,EACT,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,OAAO;AAAA,EACP,SAAS;AAAA,EACT,UAAU;AACZ;AACO,IAAM,iBAAiB;AAAA,EAC5B,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AAAA,EACT,gBAAgB;AAClB;AACA,IAAM,QAAQ,oBAAI,IAAI,CAAC,mBAAmB,iBAAiB,iBAAiB,CAAC;AAC7E,IAAM,WAAW,oBAAI,IAAI;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,CAAC;AAED,SAAS,SAAS,OAAwB;AACxC,MACE,CAAC,SACD,oBAAoB,KAA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