@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
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,1049 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/cli/index.ts
|
|
5
|
+
var import_promises2 = require("fs/promises");
|
|
6
|
+
var import_node_path2 = require("path");
|
|
7
|
+
var import_node_url = require("url");
|
|
8
|
+
var import_jiti = require("jiti");
|
|
9
|
+
|
|
10
|
+
// src/audit/index.ts
|
|
11
|
+
var sourceFindings = (policy, directive, source, ruleId, severity, message, fix) => {
|
|
12
|
+
const owners = policy.explain().filter((row) => row.directive === directive && row.source === source);
|
|
13
|
+
return owners.length ? owners.map(({ ruleSet }) => ({
|
|
14
|
+
ruleId,
|
|
15
|
+
severity,
|
|
16
|
+
message,
|
|
17
|
+
fix,
|
|
18
|
+
directive,
|
|
19
|
+
source,
|
|
20
|
+
ruleSet
|
|
21
|
+
})) : [{ ruleId, severity, message, fix, directive, source }];
|
|
22
|
+
};
|
|
23
|
+
function audit(policy, options = {}) {
|
|
24
|
+
const object = policy.toObject();
|
|
25
|
+
const findings = [];
|
|
26
|
+
const add = (id, severity, message, fix, directive) => findings.push({
|
|
27
|
+
ruleId: id,
|
|
28
|
+
severity,
|
|
29
|
+
message,
|
|
30
|
+
fix,
|
|
31
|
+
...directive ? { directive } : {}
|
|
32
|
+
});
|
|
33
|
+
if (!object["script-src"] && !object["default-src"])
|
|
34
|
+
add(
|
|
35
|
+
"missing-script-src",
|
|
36
|
+
"high",
|
|
37
|
+
"Some script execution is unrestricted.",
|
|
38
|
+
"Restrict script-src or default-src.",
|
|
39
|
+
"script-src"
|
|
40
|
+
);
|
|
41
|
+
for (const directive of [
|
|
42
|
+
"script-src",
|
|
43
|
+
"script-src-elem",
|
|
44
|
+
"script-src-attr",
|
|
45
|
+
"default-src"
|
|
46
|
+
]) {
|
|
47
|
+
const sources = object[directive];
|
|
48
|
+
if (!sources) continue;
|
|
49
|
+
const isFallback = directive === "default-src" && object["script-src"] !== void 0;
|
|
50
|
+
if (isFallback) continue;
|
|
51
|
+
const hasNonceOrHash = sources.some(
|
|
52
|
+
(s) => /^'(nonce-|sha(?:256|384|512)-)/i.test(s)
|
|
53
|
+
);
|
|
54
|
+
for (const source of sources.filter(
|
|
55
|
+
(s) => s.toLowerCase() === "'unsafe-inline'" && !hasNonceOrHash
|
|
56
|
+
))
|
|
57
|
+
findings.push(
|
|
58
|
+
...sourceFindings(
|
|
59
|
+
policy,
|
|
60
|
+
directive,
|
|
61
|
+
source,
|
|
62
|
+
"script-unsafe-inline",
|
|
63
|
+
"high",
|
|
64
|
+
"Inline scripts are permitted.",
|
|
65
|
+
"Use nonces or hashes and remove unsafe-inline."
|
|
66
|
+
)
|
|
67
|
+
);
|
|
68
|
+
for (const source of sources.filter(
|
|
69
|
+
(s) => s.toLowerCase() === "'unsafe-eval'"
|
|
70
|
+
))
|
|
71
|
+
findings.push(
|
|
72
|
+
...sourceFindings(
|
|
73
|
+
policy,
|
|
74
|
+
directive,
|
|
75
|
+
source,
|
|
76
|
+
"script-unsafe-eval",
|
|
77
|
+
"high",
|
|
78
|
+
"Dynamic JavaScript evaluation is permitted.",
|
|
79
|
+
"Remove unsafe-eval and replace dynamic evaluation."
|
|
80
|
+
)
|
|
81
|
+
);
|
|
82
|
+
if (directive !== "script-src-attr" && sources.some((source) => source.toLowerCase() === "'strict-dynamic'")) {
|
|
83
|
+
for (const source of sources) {
|
|
84
|
+
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(
|
|
85
|
+
source
|
|
86
|
+
)) {
|
|
87
|
+
findings.push(
|
|
88
|
+
...sourceFindings(
|
|
89
|
+
policy,
|
|
90
|
+
directive,
|
|
91
|
+
source,
|
|
92
|
+
"ignored-by-strict-dynamic",
|
|
93
|
+
"info",
|
|
94
|
+
"Modern browsers ignore this source for scripts under strict-dynamic.",
|
|
95
|
+
"Remove it if legacy browser fallback is not needed."
|
|
96
|
+
)
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
for (const source of sources)
|
|
102
|
+
if (["*", "https:", "http:", "data:"].includes(source.toLowerCase()) || /^(?:https?:\/\/)?\*(?::(?:\*|\d+))?(?:\/[^\s]*)?$/i.test(source))
|
|
103
|
+
findings.push(
|
|
104
|
+
...sourceFindings(
|
|
105
|
+
policy,
|
|
106
|
+
directive,
|
|
107
|
+
source,
|
|
108
|
+
"script-wildcard",
|
|
109
|
+
"high",
|
|
110
|
+
"A broad script source may permit attacker-controlled scripts.",
|
|
111
|
+
"Restrict script sources and prefer nonces or hashes."
|
|
112
|
+
)
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
const objects = object["object-src"] ?? object["default-src"];
|
|
116
|
+
if (!objects || objects.length !== 1 || objects[0]?.toLowerCase() !== "'none'")
|
|
117
|
+
add(
|
|
118
|
+
"missing-object-src",
|
|
119
|
+
"high",
|
|
120
|
+
"Object embedding is not explicitly blocked.",
|
|
121
|
+
"Set object-src to 'none'.",
|
|
122
|
+
"object-src"
|
|
123
|
+
);
|
|
124
|
+
const broad = (sources) => !sources || sources.some(
|
|
125
|
+
(source) => source === "*" || /^[a-z][a-z0-9+.-]*:$/i.test(source) || /^(?:https?:\/\/)?\*(?::(?:\*|\d+))?(?:\/[^\s]*)?$/i.test(source)
|
|
126
|
+
);
|
|
127
|
+
if (broad(object["base-uri"]))
|
|
128
|
+
add(
|
|
129
|
+
"missing-base-uri",
|
|
130
|
+
"medium",
|
|
131
|
+
"The document base URL is not sufficiently restricted.",
|
|
132
|
+
"Set base-uri to 'none' or 'self'.",
|
|
133
|
+
"base-uri"
|
|
134
|
+
);
|
|
135
|
+
if (broad(object["frame-ancestors"]))
|
|
136
|
+
add(
|
|
137
|
+
"missing-frame-ancestors",
|
|
138
|
+
"medium",
|
|
139
|
+
"Embedding by other sites is not sufficiently restricted.",
|
|
140
|
+
"Restrict frame-ancestors to trusted origins.",
|
|
141
|
+
"frame-ancestors"
|
|
142
|
+
);
|
|
143
|
+
const knownBypassDomains = [
|
|
144
|
+
"google.com",
|
|
145
|
+
"googleapis.com",
|
|
146
|
+
"googleusercontent.com",
|
|
147
|
+
"gstatic.com"
|
|
148
|
+
];
|
|
149
|
+
for (const row of policy.explain()) {
|
|
150
|
+
if (["script-src", "script-src-elem", "default-src"].includes(row.directive)) {
|
|
151
|
+
const host = row.source.match(/^(?:https?:\/\/)?(?:\*\.)?([a-z0-9.-]+)/i)?.[1]?.toLowerCase();
|
|
152
|
+
if (host && knownBypassDomains.some(
|
|
153
|
+
(domain) => host === domain || host.endsWith(`.${domain}`)
|
|
154
|
+
)) {
|
|
155
|
+
findings.push({
|
|
156
|
+
ruleId: "bypass-host",
|
|
157
|
+
severity: "medium",
|
|
158
|
+
directive: row.directive,
|
|
159
|
+
source: row.source,
|
|
160
|
+
ruleSet: row.ruleSet,
|
|
161
|
+
message: "This script host may expose JSONP or script gadgets that weaken host allowlists.",
|
|
162
|
+
fix: "Review the host for JSONP endpoints and script gadgets; prefer nonce or hash authorization."
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (/^http:/i.test(row.source))
|
|
167
|
+
findings.push({
|
|
168
|
+
ruleId: "insecure-scheme",
|
|
169
|
+
severity: "medium",
|
|
170
|
+
directive: row.directive,
|
|
171
|
+
source: row.source,
|
|
172
|
+
ruleSet: row.ruleSet,
|
|
173
|
+
message: "An insecure HTTP source is permitted.",
|
|
174
|
+
fix: "Use HTTPS where possible."
|
|
175
|
+
});
|
|
176
|
+
if (/^(?:https?:\/\/)?\*\.[a-z0-9-]+(?::(?:\*|\d+))?(?:\/|$)/i.test(
|
|
177
|
+
row.source
|
|
178
|
+
) || /^https?:\/\/\*\.(?:amazonaws\.com|azurewebsites\.net)(?:[/:]|$)/i.test(
|
|
179
|
+
row.source
|
|
180
|
+
))
|
|
181
|
+
findings.push({
|
|
182
|
+
ruleId: "broad-wildcard",
|
|
183
|
+
severity: "medium",
|
|
184
|
+
directive: row.directive,
|
|
185
|
+
source: row.source,
|
|
186
|
+
ruleSet: row.ruleSet,
|
|
187
|
+
message: "A wildcard covers an unusually broad or shared domain.",
|
|
188
|
+
fix: "List the specific trusted hosts."
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
if (!object["report-uri"] && !object["report-to"])
|
|
192
|
+
add(
|
|
193
|
+
"no-reporting",
|
|
194
|
+
"low",
|
|
195
|
+
"No reporting destination is configured.",
|
|
196
|
+
"Configure reporting and its endpoint."
|
|
197
|
+
);
|
|
198
|
+
const today = (options.now ?? /* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
199
|
+
for (const set of policy.config.ruleSets.filter((s) => s.enabled)) {
|
|
200
|
+
if (!set.owner)
|
|
201
|
+
findings.push({
|
|
202
|
+
ruleId: "ruleset-metadata",
|
|
203
|
+
severity: "low",
|
|
204
|
+
ruleSet: set.name,
|
|
205
|
+
message: "Rule set has no owner.",
|
|
206
|
+
fix: "Assign an owner."
|
|
207
|
+
});
|
|
208
|
+
if (set.reviewBy && set.reviewBy < today)
|
|
209
|
+
findings.push({
|
|
210
|
+
ruleId: "ruleset-metadata",
|
|
211
|
+
severity: "low",
|
|
212
|
+
ruleSet: set.name,
|
|
213
|
+
message: "Rule set review date has passed.",
|
|
214
|
+
fix: "Review permissions regularly."
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
for (const rule of options.rules ?? []) findings.push(...rule.check(policy));
|
|
218
|
+
for (const suppression of options.suppressions ?? [])
|
|
219
|
+
if (!suppression.reason.trim() || !suppression.ruleId || !suppression.ruleSet)
|
|
220
|
+
throw new Error(
|
|
221
|
+
"Audit suppressions require a rule id, rule set and reason"
|
|
222
|
+
);
|
|
223
|
+
return findings.filter(
|
|
224
|
+
(finding) => !(options.suppressions ?? []).some(
|
|
225
|
+
(s) => s.ruleId === finding.ruleId && s.ruleSet === finding.ruleSet
|
|
226
|
+
)
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/testing/index.ts
|
|
231
|
+
function cspSnapshot(policy) {
|
|
232
|
+
return {
|
|
233
|
+
schemaVersion: 2,
|
|
234
|
+
directives: policy.toObject(),
|
|
235
|
+
contributors: policy.explain()
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// src/cli/init.ts
|
|
240
|
+
var import_promises = require("fs/promises");
|
|
241
|
+
var import_node_path = require("path");
|
|
242
|
+
|
|
243
|
+
// src/matching/index.ts
|
|
244
|
+
var friendly = {
|
|
245
|
+
scripts: "script-src",
|
|
246
|
+
connect: "connect-src",
|
|
247
|
+
images: "img-src",
|
|
248
|
+
styles: "style-src",
|
|
249
|
+
fonts: "font-src",
|
|
250
|
+
frames: "frame-src",
|
|
251
|
+
forms: "form-action",
|
|
252
|
+
media: "media-src",
|
|
253
|
+
workers: "worker-src",
|
|
254
|
+
manifest: "manifest-src",
|
|
255
|
+
default: "default-src",
|
|
256
|
+
objects: "object-src",
|
|
257
|
+
baseUri: "base-uri",
|
|
258
|
+
frameAncestors: "frame-ancestors"
|
|
259
|
+
};
|
|
260
|
+
var fallbacks = {
|
|
261
|
+
"script-src-elem": ["script-src-elem", "script-src", "default-src"],
|
|
262
|
+
"script-src-attr": ["script-src-attr", "script-src", "default-src"],
|
|
263
|
+
"style-src-elem": ["style-src-elem", "style-src", "default-src"],
|
|
264
|
+
"style-src-attr": ["style-src-attr", "style-src", "default-src"],
|
|
265
|
+
"worker-src": ["worker-src", "child-src", "script-src", "default-src"],
|
|
266
|
+
"frame-src": ["frame-src", "child-src", "default-src"]
|
|
267
|
+
};
|
|
268
|
+
for (const name of [
|
|
269
|
+
"script-src",
|
|
270
|
+
"style-src",
|
|
271
|
+
"child-src",
|
|
272
|
+
"connect-src",
|
|
273
|
+
"font-src",
|
|
274
|
+
"img-src",
|
|
275
|
+
"manifest-src",
|
|
276
|
+
"media-src",
|
|
277
|
+
"object-src"
|
|
278
|
+
]) {
|
|
279
|
+
fallbacks[name] = [name, "default-src"];
|
|
280
|
+
}
|
|
281
|
+
for (const name of [
|
|
282
|
+
"default-src",
|
|
283
|
+
"form-action",
|
|
284
|
+
"base-uri",
|
|
285
|
+
"frame-ancestors"
|
|
286
|
+
])
|
|
287
|
+
fallbacks[name] = [name];
|
|
288
|
+
function decision(status, effectiveDirective, reason, matchedSource) {
|
|
289
|
+
return {
|
|
290
|
+
status,
|
|
291
|
+
allowed: status === "indeterminate" ? null : status === "allowed",
|
|
292
|
+
...effectiveDirective && { effectiveDirective },
|
|
293
|
+
...reason && { reason },
|
|
294
|
+
...matchedSource && { matchedSource }
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
function schemeMatches(source, target) {
|
|
298
|
+
source = source.toLowerCase();
|
|
299
|
+
target = target.toLowerCase();
|
|
300
|
+
return source === target || source === "http" && target === "https" || source === "ws" && ["wss", "http", "https"].includes(target) || source === "wss" && target === "https";
|
|
301
|
+
}
|
|
302
|
+
function scheme(url) {
|
|
303
|
+
return url.protocol.slice(0, -1).toLowerCase();
|
|
304
|
+
}
|
|
305
|
+
function defaultPort(s) {
|
|
306
|
+
return { http: "80", https: "443", ws: "80", wss: "443", ftp: "21" }[s];
|
|
307
|
+
}
|
|
308
|
+
function selfMatches(url, origin) {
|
|
309
|
+
if (scheme(url) === "blob") return false;
|
|
310
|
+
if (origin.origin !== "null" && origin.origin === url.origin) return true;
|
|
311
|
+
const os = scheme(origin), us = scheme(url);
|
|
312
|
+
const portsMatch = origin.port === url.port || !origin.port && !url.port;
|
|
313
|
+
return origin.hostname !== "" && origin.hostname === url.hostname && portsMatch && (us === "https" || us === "wss" || os === "http" && (us === "http" || us === "ws"));
|
|
314
|
+
}
|
|
315
|
+
function segmentBytes(segment) {
|
|
316
|
+
const bytes = [];
|
|
317
|
+
for (let i = 0; i < segment.length; ) {
|
|
318
|
+
const encoded = segment.slice(i).match(/^%([0-9a-f]{2})/i);
|
|
319
|
+
if (encoded) {
|
|
320
|
+
bytes.push(parseInt(encoded[1], 16));
|
|
321
|
+
i += 3;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
const point = segment.codePointAt(i);
|
|
325
|
+
const character = String.fromCodePoint(point);
|
|
326
|
+
bytes.push(...new TextEncoder().encode(character));
|
|
327
|
+
i += character.length;
|
|
328
|
+
}
|
|
329
|
+
return bytes.join(",");
|
|
330
|
+
}
|
|
331
|
+
function pathMatches(pattern, target) {
|
|
332
|
+
if (!pattern || pattern === "/" && !target) return true;
|
|
333
|
+
const a = pattern.split("/"), b = target.split("/");
|
|
334
|
+
if (a.length > b.length || !pattern.endsWith("/") && a.length !== b.length)
|
|
335
|
+
return false;
|
|
336
|
+
if (pattern.endsWith("/")) a.pop();
|
|
337
|
+
return a.every((part, i) => segmentBytes(part) === segmentBytes(b[i]));
|
|
338
|
+
}
|
|
339
|
+
function sourceMatches(source, url, origin, redirectCount) {
|
|
340
|
+
const lower = source.toLowerCase(), targetScheme = scheme(url);
|
|
341
|
+
if (lower === "'self'")
|
|
342
|
+
return origin ? selfMatches(url, origin) ? "yes" : "no" : "unknown";
|
|
343
|
+
if (source === "*")
|
|
344
|
+
return ["http", "https"].includes(targetScheme) ? "yes" : origin ? scheme(origin) === targetScheme ? "yes" : "no" : "unknown";
|
|
345
|
+
const schemeOnly = source.match(/^([a-z][a-z0-9+.-]*):$/i);
|
|
346
|
+
if (schemeOnly)
|
|
347
|
+
return schemeMatches(schemeOnly[1], targetScheme) ? "yes" : "no";
|
|
348
|
+
const host = source.match(
|
|
349
|
+
/^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9.-]+)(?::(\*|[0-9]+))?(\/[^?#]*)?$/i
|
|
350
|
+
);
|
|
351
|
+
if (!host) return "no";
|
|
352
|
+
const [, explicitScheme, patternHost, port, path] = host;
|
|
353
|
+
if (!url.hostname || /^\[/.test(url.hostname) || /^\d+(?:\.\d+){3}$/.test(url.hostname))
|
|
354
|
+
return "no";
|
|
355
|
+
if (!explicitScheme && !origin) return "unknown";
|
|
356
|
+
if (!schemeMatches(explicitScheme ?? scheme(origin), targetScheme))
|
|
357
|
+
return "no";
|
|
358
|
+
const domain = url.hostname.toLowerCase(), pattern = patternHost.toLowerCase();
|
|
359
|
+
if (pattern !== "*" && !(pattern.startsWith("*.") ? domain.endsWith(pattern.slice(1)) : domain === pattern))
|
|
360
|
+
return "no";
|
|
361
|
+
if (port !== "*") {
|
|
362
|
+
const targetPort = url.port || void 0;
|
|
363
|
+
if (port === void 0 ? targetPort !== void 0 : Number(port) !== Number(targetPort ?? defaultPort(targetScheme)))
|
|
364
|
+
return "no";
|
|
365
|
+
}
|
|
366
|
+
if (path && !pathMatches(path, url.pathname)) {
|
|
367
|
+
if (redirectCount === void 0) return "unknown";
|
|
368
|
+
if (redirectCount === 0) return "no";
|
|
369
|
+
}
|
|
370
|
+
return "yes";
|
|
371
|
+
}
|
|
372
|
+
function matchPolicy(directives, directive, input, options = {}) {
|
|
373
|
+
const requested = friendly[directive] ?? directive.toLowerCase();
|
|
374
|
+
const name = requested === "script-src" ? "script-src-elem" : requested === "style-src" ? "style-src-elem" : requested;
|
|
375
|
+
const chain = fallbacks[name];
|
|
376
|
+
if (!chain)
|
|
377
|
+
return decision(
|
|
378
|
+
"indeterminate",
|
|
379
|
+
void 0,
|
|
380
|
+
"Unsupported directive or inline check"
|
|
381
|
+
);
|
|
382
|
+
const effective = chain.find(
|
|
383
|
+
(key) => Object.prototype.hasOwnProperty.call(directives, key)
|
|
384
|
+
);
|
|
385
|
+
if (!effective)
|
|
386
|
+
return decision("allowed", void 0, "No applicable directive");
|
|
387
|
+
if (name.endsWith("-attr"))
|
|
388
|
+
return decision(
|
|
389
|
+
"indeterminate",
|
|
390
|
+
effective,
|
|
391
|
+
"Inline checks require element content and context"
|
|
392
|
+
);
|
|
393
|
+
if (name === "frame-ancestors")
|
|
394
|
+
return decision(
|
|
395
|
+
"indeterminate",
|
|
396
|
+
effective,
|
|
397
|
+
"Frame enforcement depends on the complete ancestor chain"
|
|
398
|
+
);
|
|
399
|
+
if (options.redirectCount !== void 0 && (!Number.isInteger(options.redirectCount) || options.redirectCount < 0))
|
|
400
|
+
throw new TypeError("redirectCount must be a non-negative integer");
|
|
401
|
+
let url, origin;
|
|
402
|
+
try {
|
|
403
|
+
url = new URL(input);
|
|
404
|
+
if (options.origin !== void 0) {
|
|
405
|
+
origin = new URL(options.origin);
|
|
406
|
+
if (origin.origin === "null") throw new Error("opaque");
|
|
407
|
+
}
|
|
408
|
+
} catch {
|
|
409
|
+
throw new TypeError("Expected an absolute URL and a non-opaque origin");
|
|
410
|
+
}
|
|
411
|
+
const sources = directives[effective];
|
|
412
|
+
const script = name === "script-src" || name === "script-src-elem";
|
|
413
|
+
const style = name === "style-src" || name === "style-src-elem";
|
|
414
|
+
const hasNoncePlaceholder = sources.includes("'nonce-{nonce}'");
|
|
415
|
+
const nonceSources = sources.filter(
|
|
416
|
+
(s) => /^'nonce-[a-z0-9+/_=-]+'$/i.test(s)
|
|
417
|
+
);
|
|
418
|
+
const hashes = sources.filter(
|
|
419
|
+
(s) => /^'sha(256|384|512)-[a-z0-9+/_=-]+'$/i.test(s)
|
|
420
|
+
);
|
|
421
|
+
if ((script || style) && options.nonce && (nonceSources.some((s) => s.slice(7, -1) === options.nonce) || hasNoncePlaceholder && options.policyNonce !== void 0 && options.nonce === options.policyNonce))
|
|
422
|
+
return decision("allowed", effective, "Matching request nonce");
|
|
423
|
+
if (script && options.integrity?.length && options.integrity.every(
|
|
424
|
+
(token) => hashes.some((hash) => {
|
|
425
|
+
const [hashAlg, hashDigest] = hash.slice(1, -1).split("-", 2);
|
|
426
|
+
const [tokenAlg, tokenDigest] = token.split("-", 2);
|
|
427
|
+
return hashAlg?.toLowerCase() === tokenAlg?.toLowerCase() && hashDigest !== void 0 && hashDigest === tokenDigest;
|
|
428
|
+
})
|
|
429
|
+
))
|
|
430
|
+
return decision("allowed", effective, "Matching integrity metadata");
|
|
431
|
+
const missingNonce = (script || style) && (nonceSources.length > 0 && options.nonce === void 0 || hasNoncePlaceholder && (options.nonce === void 0 || options.nonce !== "" && options.policyNonce === void 0));
|
|
432
|
+
const missingIntegrity = script && hashes.length > 0 && options.integrity === void 0;
|
|
433
|
+
if (script && sources.some((s) => s.toLowerCase() === "'strict-dynamic'")) {
|
|
434
|
+
if (options.parserInserted === false)
|
|
435
|
+
return decision(
|
|
436
|
+
"allowed",
|
|
437
|
+
effective,
|
|
438
|
+
"Non-parser-inserted script under strict-dynamic"
|
|
439
|
+
);
|
|
440
|
+
if (options.parserInserted === void 0 || missingNonce || missingIntegrity)
|
|
441
|
+
return decision(
|
|
442
|
+
"indeterminate",
|
|
443
|
+
effective,
|
|
444
|
+
"Script nonce, integrity or parser metadata is missing"
|
|
445
|
+
);
|
|
446
|
+
return decision(
|
|
447
|
+
"blocked",
|
|
448
|
+
effective,
|
|
449
|
+
"Parser-inserted script has no matching nonce or integrity metadata"
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
let unknown = false;
|
|
453
|
+
for (const source of sources) {
|
|
454
|
+
const match = sourceMatches(source, url, origin, options.redirectCount);
|
|
455
|
+
if (match === "yes")
|
|
456
|
+
return decision("allowed", effective, void 0, source);
|
|
457
|
+
if (match === "unknown") unknown = true;
|
|
458
|
+
}
|
|
459
|
+
if (unknown || missingNonce || missingIntegrity)
|
|
460
|
+
return decision(
|
|
461
|
+
"indeterminate",
|
|
462
|
+
effective,
|
|
463
|
+
"Origin, redirect count, nonce or integrity metadata is missing"
|
|
464
|
+
);
|
|
465
|
+
return decision("blocked", effective, "No source matched");
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// src/core.ts
|
|
469
|
+
var import_zod2 = require("zod");
|
|
470
|
+
|
|
471
|
+
// src/keywords.ts
|
|
472
|
+
var SELF = "'self'";
|
|
473
|
+
var NONE = "'none'";
|
|
474
|
+
var NONCE = "'nonce-{nonce}'";
|
|
475
|
+
var STRICT_DYNAMIC = "'strict-dynamic'";
|
|
476
|
+
|
|
477
|
+
// src/schemas.ts
|
|
478
|
+
var import_zod = require("zod");
|
|
479
|
+
var resourceDirectives = {
|
|
480
|
+
scripts: "script-src",
|
|
481
|
+
connect: "connect-src",
|
|
482
|
+
images: "img-src",
|
|
483
|
+
styles: "style-src",
|
|
484
|
+
fonts: "font-src",
|
|
485
|
+
frames: "frame-src",
|
|
486
|
+
forms: "form-action",
|
|
487
|
+
media: "media-src",
|
|
488
|
+
workers: "worker-src",
|
|
489
|
+
manifest: "manifest-src"
|
|
490
|
+
};
|
|
491
|
+
var baseDirectives = {
|
|
492
|
+
default: "default-src",
|
|
493
|
+
objects: "object-src",
|
|
494
|
+
baseUri: "base-uri",
|
|
495
|
+
frameAncestors: "frame-ancestors"
|
|
496
|
+
};
|
|
497
|
+
var risky = /* @__PURE__ */ new Set(["'unsafe-inline'", "'unsafe-eval'", "'unsafe-hashes'"]);
|
|
498
|
+
var keywords = /* @__PURE__ */ new Set([
|
|
499
|
+
"'self'",
|
|
500
|
+
"'none'",
|
|
501
|
+
"'strict-dynamic'",
|
|
502
|
+
"'report-sample'",
|
|
503
|
+
"'wasm-unsafe-eval'",
|
|
504
|
+
...risky
|
|
505
|
+
]);
|
|
506
|
+
function isSource(value) {
|
|
507
|
+
if (!value || /[\x00-\x20\x7f;,]/.test(value) || /^[a-z][a-z0-9+.-]*\/\//i.test(value))
|
|
508
|
+
return false;
|
|
509
|
+
if (keywords.has(value.toLowerCase()) || value === NONCE || value === "*" || /^[a-z][a-z0-9+.-]*:\/\/\*(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(value))
|
|
510
|
+
return true;
|
|
511
|
+
if (/^'(nonce-[A-Za-z0-9+/_-]+={0,2}|sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2})'$/i.test(
|
|
512
|
+
value
|
|
513
|
+
))
|
|
514
|
+
return true;
|
|
515
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:$/.test(value)) return true;
|
|
516
|
+
return /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:\*\.)?(?:[a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(
|
|
517
|
+
value
|
|
518
|
+
);
|
|
519
|
+
}
|
|
520
|
+
var sourceStringSchema = import_zod.z.string().refine(isSource, "Invalid CSP source expression");
|
|
521
|
+
var sourceEntrySchema = import_zod.z.union([
|
|
522
|
+
sourceStringSchema.refine(
|
|
523
|
+
(s) => !risky.has(s.toLowerCase()),
|
|
524
|
+
"Risky keyword requires a reason"
|
|
525
|
+
),
|
|
526
|
+
import_zod.z.object({ source: sourceStringSchema, reason: import_zod.z.string().trim().min(1) }).strict()
|
|
527
|
+
]);
|
|
528
|
+
var sourceList = import_zod.z.array(sourceEntrySchema).min(1);
|
|
529
|
+
var sourceListDirectives = /* @__PURE__ */ new Set([
|
|
530
|
+
...Object.values(resourceDirectives),
|
|
531
|
+
...Object.values(baseDirectives),
|
|
532
|
+
"script-src-elem",
|
|
533
|
+
"script-src-attr",
|
|
534
|
+
"style-src-elem",
|
|
535
|
+
"style-src-attr",
|
|
536
|
+
"child-src"
|
|
537
|
+
]);
|
|
538
|
+
var rawDirectives = import_zod.z.record(
|
|
539
|
+
import_zod.z.string().regex(/^[a-z][a-z0-9-]*$/).refine(
|
|
540
|
+
(name) => sourceListDirectives.has(name),
|
|
541
|
+
"Unsupported raw directive; only known source-list directives are supported"
|
|
542
|
+
),
|
|
543
|
+
sourceList
|
|
544
|
+
);
|
|
545
|
+
var reserved = /* @__PURE__ */ new Set([
|
|
546
|
+
"report-uri",
|
|
547
|
+
"report-to",
|
|
548
|
+
"upgrade-insecure-requests"
|
|
549
|
+
]);
|
|
550
|
+
var baseOnly = /* @__PURE__ */ new Set([...Object.values(baseDirectives), ...reserved]);
|
|
551
|
+
var ruleShape = Object.fromEntries(
|
|
552
|
+
Object.keys(resourceDirectives).map((key) => [key, sourceList.optional()])
|
|
553
|
+
);
|
|
554
|
+
var rulesSchema = import_zod.z.object({ ...ruleShape, directives: rawDirectives.optional() }).strict().refine(
|
|
555
|
+
(rules) => Object.entries(rules).some(
|
|
556
|
+
([key, value]) => key === "directives" ? Object.keys(value ?? {}).length > 0 : value !== void 0
|
|
557
|
+
),
|
|
558
|
+
"At least one resource directive is required"
|
|
559
|
+
).superRefine((rules, ctx) => {
|
|
560
|
+
for (const directive of Object.keys(rules.directives ?? {})) {
|
|
561
|
+
if (baseOnly.has(directive))
|
|
562
|
+
ctx.addIssue({
|
|
563
|
+
code: "custom",
|
|
564
|
+
path: ["directives", directive],
|
|
565
|
+
message: "Base-only or reserved directive"
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
var baseSchema = import_zod.z.object({
|
|
570
|
+
...ruleShape,
|
|
571
|
+
default: sourceList.optional(),
|
|
572
|
+
objects: sourceList.optional(),
|
|
573
|
+
baseUri: sourceList.optional(),
|
|
574
|
+
frameAncestors: sourceList.optional(),
|
|
575
|
+
upgradeInsecureRequests: import_zod.z.boolean().optional(),
|
|
576
|
+
directives: rawDirectives.optional()
|
|
577
|
+
}).strict().superRefine((base, ctx) => {
|
|
578
|
+
for (const directive of Object.keys(base.directives ?? {})) {
|
|
579
|
+
if (reserved.has(directive))
|
|
580
|
+
ctx.addIssue({
|
|
581
|
+
code: "custom",
|
|
582
|
+
path: ["directives", directive],
|
|
583
|
+
message: "Use the dedicated configuration field for this directive"
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
});
|
|
587
|
+
var ruleSetSchema = import_zod.z.object({
|
|
588
|
+
name: import_zod.z.string().trim().min(1),
|
|
589
|
+
purpose: import_zod.z.string().trim().min(1),
|
|
590
|
+
owner: import_zod.z.string().trim().min(1).optional(),
|
|
591
|
+
docs: import_zod.z.url().optional(),
|
|
592
|
+
tags: import_zod.z.array(import_zod.z.string().trim().min(1)).optional(),
|
|
593
|
+
reviewBy: import_zod.z.iso.date().optional(),
|
|
594
|
+
enabled: import_zod.z.boolean().default(true),
|
|
595
|
+
rules: rulesSchema
|
|
596
|
+
}).strict();
|
|
597
|
+
var reportingSchema = import_zod.z.object({
|
|
598
|
+
uri: import_zod.z.url().refine(
|
|
599
|
+
(value) => !/[\x00-\x20\x7f;,]/.test(value),
|
|
600
|
+
"Invalid reporting value"
|
|
601
|
+
).optional(),
|
|
602
|
+
to: import_zod.z.string().regex(/^[A-Za-z0-9_-]+$/).optional()
|
|
603
|
+
}).strict();
|
|
604
|
+
var policyConfigSchema = import_zod.z.object({
|
|
605
|
+
base: baseSchema.default({}),
|
|
606
|
+
ruleSets: import_zod.z.array(ruleSetSchema).default([]),
|
|
607
|
+
reporting: reportingSchema.optional()
|
|
608
|
+
}).strict().superRefine((config, ctx) => {
|
|
609
|
+
const names = /* @__PURE__ */ new Set();
|
|
610
|
+
config.ruleSets.forEach((rule, i) => {
|
|
611
|
+
if (names.has(rule.name))
|
|
612
|
+
ctx.addIssue({
|
|
613
|
+
code: "custom",
|
|
614
|
+
path: ["ruleSets", i, "name"],
|
|
615
|
+
message: `Duplicate rule set name: ${rule.name}`
|
|
616
|
+
});
|
|
617
|
+
names.add(rule.name);
|
|
618
|
+
});
|
|
619
|
+
});
|
|
620
|
+
|
|
621
|
+
// src/core.ts
|
|
622
|
+
function freeze(value) {
|
|
623
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
624
|
+
Object.values(value).forEach(freeze);
|
|
625
|
+
Object.freeze(value);
|
|
626
|
+
}
|
|
627
|
+
return value;
|
|
628
|
+
}
|
|
629
|
+
function entryValue(entry) {
|
|
630
|
+
return typeof entry === "string" ? entry : entry.source;
|
|
631
|
+
}
|
|
632
|
+
function entryReason(entry) {
|
|
633
|
+
return typeof entry === "string" ? void 0 : entry.reason;
|
|
634
|
+
}
|
|
635
|
+
var Policy = class _Policy {
|
|
636
|
+
config;
|
|
637
|
+
constructor(input) {
|
|
638
|
+
const result = policyConfigSchema.safeParse(input);
|
|
639
|
+
if (!result.success) {
|
|
640
|
+
throw new import_zod2.z.ZodError(
|
|
641
|
+
result.error.issues.map((issue) => {
|
|
642
|
+
const index = issue.path[0] === "ruleSets" && typeof issue.path[1] === "number" ? issue.path[1] : void 0;
|
|
643
|
+
const name = index === void 0 ? void 0 : input.ruleSets?.[index]?.name;
|
|
644
|
+
return name ? {
|
|
645
|
+
...issue,
|
|
646
|
+
message: `RuleSet "${name}" - ${issue.path.slice(2).join(".")}: ${issue.message}`
|
|
647
|
+
} : issue;
|
|
648
|
+
})
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
const config = result.data;
|
|
652
|
+
this.config = freeze(config);
|
|
653
|
+
Object.freeze(this);
|
|
654
|
+
}
|
|
655
|
+
/** Sources and their contributing rule sets. Duplicate values retain all contributors. */
|
|
656
|
+
explain() {
|
|
657
|
+
const rows = [];
|
|
658
|
+
const add = (directive, entries, ruleSet) => {
|
|
659
|
+
for (const entry of entries) {
|
|
660
|
+
const reason = entryReason(entry);
|
|
661
|
+
rows.push({
|
|
662
|
+
directive,
|
|
663
|
+
source: entryValue(entry),
|
|
664
|
+
ruleSet,
|
|
665
|
+
...reason === void 0 ? {} : { reason }
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
const collect = (rules, name) => {
|
|
670
|
+
for (const [key, value] of Object.entries(rules)) {
|
|
671
|
+
if (key === "directives" && value) {
|
|
672
|
+
for (const [directive, entries] of Object.entries(
|
|
673
|
+
value
|
|
674
|
+
))
|
|
675
|
+
add(directive, entries, name);
|
|
676
|
+
} else if (Array.isArray(value)) {
|
|
677
|
+
const directive = resourceDirectives[key] ?? baseDirectives[key];
|
|
678
|
+
if (directive) add(directive, value, name);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
collect(this.config.base, "base");
|
|
683
|
+
for (const set of this.config.ruleSets)
|
|
684
|
+
if (set.enabled) collect(set.rules, set.name);
|
|
685
|
+
return rows.sort(
|
|
686
|
+
(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")
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
/** Merged sources, deduplicated without changing path syntax. */
|
|
690
|
+
toObject() {
|
|
691
|
+
const map = /* @__PURE__ */ Object.create(null);
|
|
692
|
+
for (const row of this.explain())
|
|
693
|
+
(map[row.directive] ??= /* @__PURE__ */ new Set()).add(row.source);
|
|
694
|
+
if (this.config.base.upgradeInsecureRequests)
|
|
695
|
+
map["upgrade-insecure-requests"] = /* @__PURE__ */ new Set();
|
|
696
|
+
if (this.config.reporting?.uri)
|
|
697
|
+
map["report-uri"] = /* @__PURE__ */ new Set([this.config.reporting.uri]);
|
|
698
|
+
if (this.config.reporting?.to)
|
|
699
|
+
map["report-to"] = /* @__PURE__ */ new Set([this.config.reporting.to]);
|
|
700
|
+
return Object.fromEntries(
|
|
701
|
+
Object.entries(map).sort(([a], [b]) => a.localeCompare(b, "en")).map(([key, values]) => [key, Array.from(values).sort()])
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
/** Evaluate a URL with explicit uncertainty when browser context is missing. */
|
|
705
|
+
allows(directive, url, options = {}) {
|
|
706
|
+
const result = matchPolicy(this.toObject(), directive, url, options);
|
|
707
|
+
const contributors = result.matchedSource && result.effectiveDirective ? this.explain().filter(
|
|
708
|
+
(row) => row.directive === result.effectiveDirective && row.source === result.matchedSource
|
|
709
|
+
) : [];
|
|
710
|
+
return contributors.length ? { ...result, contributors } : result;
|
|
711
|
+
}
|
|
712
|
+
/** Render a header value. Pretty output is for display only and is not a valid HTTP header value. */
|
|
713
|
+
toHeader(options = {}) {
|
|
714
|
+
const directives = this.toObject();
|
|
715
|
+
const hasNonce = Object.values(directives).some(
|
|
716
|
+
(sources) => sources.includes(NONCE)
|
|
717
|
+
);
|
|
718
|
+
if (hasNonce && (!options.nonce || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(options.nonce)))
|
|
719
|
+
throw new Error("A valid base64 nonce is required");
|
|
720
|
+
return Object.entries(directives).map(([directive, values]) => {
|
|
721
|
+
const rendered = values.map(
|
|
722
|
+
(value) => value === NONCE ? `'nonce-${options.nonce}'` : value
|
|
723
|
+
);
|
|
724
|
+
return directive + (rendered.length ? ` ${rendered.join(" ")}` : "");
|
|
725
|
+
}).join(options.pretty ? ";\n" : "; ");
|
|
726
|
+
}
|
|
727
|
+
withRuleSet(ruleSets) {
|
|
728
|
+
const additions = Array.isArray(ruleSets) ? ruleSets : [ruleSets];
|
|
729
|
+
return new _Policy({
|
|
730
|
+
...this.config,
|
|
731
|
+
ruleSets: [...this.config.ruleSets, ...additions]
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
without(name) {
|
|
735
|
+
return new _Policy({
|
|
736
|
+
...this.config,
|
|
737
|
+
ruleSets: this.config.ruleSets.filter((set) => set.name !== name)
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
function definePolicy(input) {
|
|
742
|
+
return new Policy(input);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// src/cli/init.ts
|
|
746
|
+
async function initProject(cwd, options = {}) {
|
|
747
|
+
const apiOrigins = [...new Set(options.apiOrigins ?? [])];
|
|
748
|
+
for (const origin of apiOrigins) {
|
|
749
|
+
let parsed;
|
|
750
|
+
try {
|
|
751
|
+
parsed = new URL(origin);
|
|
752
|
+
} catch {
|
|
753
|
+
throw new Error(`Invalid API origin: ${origin}`);
|
|
754
|
+
}
|
|
755
|
+
if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.origin !== origin)
|
|
756
|
+
throw new Error(
|
|
757
|
+
`API origins must be HTTP(S) origins without paths, credentials or trailing slash: ${origin}`
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
if (options.reportUri) {
|
|
761
|
+
let parsed;
|
|
762
|
+
try {
|
|
763
|
+
parsed = new URL(options.reportUri);
|
|
764
|
+
} catch {
|
|
765
|
+
throw new Error("Invalid reporting URL");
|
|
766
|
+
}
|
|
767
|
+
if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash)
|
|
768
|
+
throw new Error(
|
|
769
|
+
"Reporting URL must be an HTTP(S) URL without credentials or fragment"
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
const review = new Date(options.now ?? /* @__PURE__ */ new Date());
|
|
773
|
+
review.setUTCFullYear(review.getUTCFullYear() + 1);
|
|
774
|
+
const reviewBy = review.toISOString().slice(0, 10);
|
|
775
|
+
const policy = definePolicy({
|
|
776
|
+
...options.reportUri ? { reporting: { uri: options.reportUri } } : {},
|
|
777
|
+
base: {
|
|
778
|
+
default: [SELF],
|
|
779
|
+
scripts: [SELF, NONCE, STRICT_DYNAMIC],
|
|
780
|
+
objects: [NONE],
|
|
781
|
+
baseUri: [SELF],
|
|
782
|
+
frameAncestors: [NONE],
|
|
783
|
+
upgradeInsecureRequests: true
|
|
784
|
+
},
|
|
785
|
+
ruleSets: [
|
|
786
|
+
{
|
|
787
|
+
name: "App assets",
|
|
788
|
+
purpose: "Images used by the application",
|
|
789
|
+
owner: "TODO: assign owner",
|
|
790
|
+
reviewBy,
|
|
791
|
+
rules: { images: [SELF, "data:", "blob:"] }
|
|
792
|
+
},
|
|
793
|
+
...apiOrigins.length ? [
|
|
794
|
+
{
|
|
795
|
+
name: "App API",
|
|
796
|
+
purpose: "Application API connections",
|
|
797
|
+
owner: "TODO: assign owner",
|
|
798
|
+
reviewBy,
|
|
799
|
+
rules: { connect: apiOrigins }
|
|
800
|
+
}
|
|
801
|
+
] : []
|
|
802
|
+
]
|
|
803
|
+
});
|
|
804
|
+
const apiImport = apiOrigins.length ? `import { appApi } from './rule-sets/app-api';
|
|
805
|
+
` : "";
|
|
806
|
+
const reporting = options.reportUri ? ` reporting: { uri: ${JSON.stringify(options.reportUri)} },
|
|
807
|
+
` : "";
|
|
808
|
+
const apiTest = apiOrigins.length ? ` expect(policy).toAllow('connect', ${JSON.stringify(apiOrigins[0] + "/")}, { origin: 'https://site.example', redirectCount: 0 });
|
|
809
|
+
` : "";
|
|
810
|
+
const files = {
|
|
811
|
+
"csp.config.ts": `export { policy as default } from './csp/policy';
|
|
812
|
+
`,
|
|
813
|
+
"csp/policy.ts": `import { definePolicy, SELF, NONE, NONCE, STRICT_DYNAMIC } from '@jamesbrightman/pretty-csp';
|
|
814
|
+
import { appAssets } from './rule-sets/app-assets';
|
|
815
|
+
${apiImport}
|
|
816
|
+
export const policy = definePolicy({
|
|
817
|
+
${reporting} base: { default: [SELF], scripts: [SELF, NONCE, STRICT_DYNAMIC], objects: [NONE], baseUri: [SELF], frameAncestors: [NONE], upgradeInsecureRequests: true },
|
|
818
|
+
ruleSets: [appAssets${apiOrigins.length ? ", appApi" : ""}],
|
|
819
|
+
});
|
|
820
|
+
`,
|
|
821
|
+
"csp/rule-sets/app-assets.ts": `import { defineRuleSet, SELF } from '@jamesbrightman/pretty-csp';
|
|
822
|
+
|
|
823
|
+
export const appAssets = defineRuleSet({ name: 'App assets', purpose: 'Images used by the application', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { images: [SELF, 'data:', 'blob:'] } });
|
|
824
|
+
`,
|
|
825
|
+
"csp/policy.test.ts": `import { readFile } from 'node:fs/promises';
|
|
826
|
+
import { expect, test } from 'vitest';
|
|
827
|
+
import { cspMatchers } from '@jamesbrightman/pretty-csp/testing';
|
|
828
|
+
import { policy } from './policy';
|
|
829
|
+
|
|
830
|
+
expect.extend(cspMatchers);
|
|
831
|
+
test('blocks untrusted connections and has no high-risk findings', () => {
|
|
832
|
+
${apiTest} expect(policy).toBlock('connect', 'https://untrusted.example/', { origin: 'https://site.example', redirectCount: 0 });
|
|
833
|
+
expect(policy).toPassAudit({ maxSeverity: 'low' });
|
|
834
|
+
});
|
|
835
|
+
test('matches the reviewed CSP snapshot', async () => {
|
|
836
|
+
const snapshot = JSON.parse(await readFile(new URL('../csp.snapshot.json', import.meta.url), 'utf8'));
|
|
837
|
+
expect(policy).toMatchCspSnapshot(snapshot);
|
|
838
|
+
});
|
|
839
|
+
`,
|
|
840
|
+
"csp/vitest.d.ts": `import 'vitest';
|
|
841
|
+
import type { CspAssertions } from '@jamesbrightman/pretty-csp/testing';
|
|
842
|
+
|
|
843
|
+
declare module 'vitest' {
|
|
844
|
+
interface Assertion<T> extends CspAssertions<T> {}
|
|
845
|
+
interface AsymmetricMatchersContaining extends CspAssertions {}
|
|
846
|
+
}
|
|
847
|
+
`,
|
|
848
|
+
"csp.snapshot.json": `${JSON.stringify(cspSnapshot(policy), null, 2)}
|
|
849
|
+
`
|
|
850
|
+
};
|
|
851
|
+
if (apiOrigins.length)
|
|
852
|
+
files["csp/rule-sets/app-api.ts"] = `import { defineRuleSet } from '@jamesbrightman/pretty-csp';
|
|
853
|
+
|
|
854
|
+
export const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API connections', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { connect: ${JSON.stringify(apiOrigins)} } });
|
|
855
|
+
`;
|
|
856
|
+
async function stat(path) {
|
|
857
|
+
try {
|
|
858
|
+
return await (0, import_promises.lstat)(path);
|
|
859
|
+
} catch (error) {
|
|
860
|
+
if (error.code === "ENOENT") return void 0;
|
|
861
|
+
throw error;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
for (const directory of ["csp", "csp/rule-sets"]) {
|
|
865
|
+
const dir = await stat((0, import_node_path.join)(cwd, directory));
|
|
866
|
+
if (dir?.isSymbolicLink() || dir && !dir.isDirectory())
|
|
867
|
+
throw new Error(`${directory} must be a directory and not a symlink`);
|
|
868
|
+
}
|
|
869
|
+
for (const file of Object.keys(files)) {
|
|
870
|
+
const current = await stat((0, import_node_path.join)(cwd, file));
|
|
871
|
+
if (current?.isSymbolicLink() || current && !current.isFile())
|
|
872
|
+
throw new Error(`Refusing non-file or symlink: ${file}`);
|
|
873
|
+
if (current && !options.force)
|
|
874
|
+
throw new Error(
|
|
875
|
+
`File already exists: ${file}. Use --force to replace it.`
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
if (!options.dryRun) {
|
|
879
|
+
await (0, import_promises.mkdir)((0, import_node_path.join)(cwd, "csp/rule-sets"), { recursive: true });
|
|
880
|
+
for (const [file, content] of Object.entries(files))
|
|
881
|
+
await (0, import_promises.writeFile)((0, import_node_path.join)(cwd, file), content, {
|
|
882
|
+
encoding: "utf8",
|
|
883
|
+
flag: options.force ? "w" : "wx"
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
return Object.keys(files);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
// src/cli/index.ts
|
|
890
|
+
var help = "Usage: pretty-csp <init|print|explain|audit|snapshot> [--config path] [options]";
|
|
891
|
+
var severities = {
|
|
892
|
+
info: 0,
|
|
893
|
+
low: 1,
|
|
894
|
+
medium: 2,
|
|
895
|
+
high: 3
|
|
896
|
+
};
|
|
897
|
+
function argsFor(args) {
|
|
898
|
+
const [command = "help", ...rest] = args;
|
|
899
|
+
const options = {};
|
|
900
|
+
const flags = /* @__PURE__ */ new Set([
|
|
901
|
+
"pretty",
|
|
902
|
+
"update",
|
|
903
|
+
"help",
|
|
904
|
+
"yes",
|
|
905
|
+
"dry-run",
|
|
906
|
+
"force"
|
|
907
|
+
]);
|
|
908
|
+
const values = /* @__PURE__ */ new Set([
|
|
909
|
+
"config",
|
|
910
|
+
"nonce",
|
|
911
|
+
"directive",
|
|
912
|
+
"rule-set",
|
|
913
|
+
"fail-on",
|
|
914
|
+
"file",
|
|
915
|
+
"api-origins",
|
|
916
|
+
"report-uri"
|
|
917
|
+
]);
|
|
918
|
+
for (let i = 0; i < rest.length; i++) {
|
|
919
|
+
const arg = rest[i];
|
|
920
|
+
if (!arg.startsWith("--")) throw new Error(`Unexpected argument: ${arg}`);
|
|
921
|
+
const key = arg.slice(2);
|
|
922
|
+
if (flags.has(key)) options[key] = true;
|
|
923
|
+
else if (values.has(key)) {
|
|
924
|
+
const value = rest[++i];
|
|
925
|
+
if (!value || value.startsWith("--"))
|
|
926
|
+
throw new Error(`--${key} requires a value`);
|
|
927
|
+
options[key] = value;
|
|
928
|
+
} else throw new Error(`Unknown option --${key}`);
|
|
929
|
+
}
|
|
930
|
+
return {
|
|
931
|
+
command,
|
|
932
|
+
options
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
function option(options, name) {
|
|
936
|
+
return typeof options[name] === "string" ? options[name] : void 0;
|
|
937
|
+
}
|
|
938
|
+
function isPolicy(value) {
|
|
939
|
+
return !!value && typeof value === "object" && ["toHeader", "toObject", "explain", "allows"].every(
|
|
940
|
+
(key) => typeof value[key] === "function"
|
|
941
|
+
) && "config" in value;
|
|
942
|
+
}
|
|
943
|
+
async function loadConfigFile(path) {
|
|
944
|
+
if ([".ts", ".mts", ".cts"].includes((0, import_node_path2.extname)(path).toLowerCase())) {
|
|
945
|
+
const jiti = (0, import_jiti.createJiti)(path, { moduleCache: false, fsCache: false });
|
|
946
|
+
return await jiti.import(path);
|
|
947
|
+
}
|
|
948
|
+
return await import((0, import_node_url.pathToFileURL)(path).href);
|
|
949
|
+
}
|
|
950
|
+
async function runCli(args, io, cwd = process.cwd(), loadConfig = loadConfigFile) {
|
|
951
|
+
try {
|
|
952
|
+
const { command, options } = argsFor(args);
|
|
953
|
+
if (command === "help" || command === "--help" || options.help) {
|
|
954
|
+
io.out(help);
|
|
955
|
+
return 0;
|
|
956
|
+
}
|
|
957
|
+
if (!["init", "print", "explain", "audit", "snapshot"].includes(command))
|
|
958
|
+
throw new Error(`Unsupported command: ${command}. ${help}`);
|
|
959
|
+
if (command === "init") {
|
|
960
|
+
if (!options.yes)
|
|
961
|
+
throw new Error(
|
|
962
|
+
"Use init --yes and optional --api-origins and --report-uri flags."
|
|
963
|
+
);
|
|
964
|
+
const files = await initProject(cwd, {
|
|
965
|
+
dryRun: Boolean(options["dry-run"]),
|
|
966
|
+
force: Boolean(options.force),
|
|
967
|
+
apiOrigins: option(options, "api-origins")?.split(",").map((origin) => origin.trim()),
|
|
968
|
+
reportUri: option(options, "report-uri")
|
|
969
|
+
});
|
|
970
|
+
io.out(
|
|
971
|
+
`${options["dry-run"] ? "Would write" : "Wrote"}:
|
|
972
|
+
${files.join("\n")}
|
|
973
|
+
Install @jamesbrightman/pretty-csp and Vitest, then configure your server to set the Content-Security-Policy response header with policy.toHeader({ nonce }) on each response.`
|
|
974
|
+
);
|
|
975
|
+
return 0;
|
|
976
|
+
}
|
|
977
|
+
const path = (0, import_node_path2.resolve)(cwd, option(options, "config") ?? "csp.config.ts");
|
|
978
|
+
const module2 = await loadConfig(path);
|
|
979
|
+
const candidate = module2.default ?? module2.policy;
|
|
980
|
+
const policy = candidate && typeof candidate === "object" && "policy" in candidate ? candidate.policy : candidate;
|
|
981
|
+
if (!isPolicy(policy))
|
|
982
|
+
throw new Error(
|
|
983
|
+
"Config must export a Policy as default, as policy, or as default.policy"
|
|
984
|
+
);
|
|
985
|
+
if (command === "print") {
|
|
986
|
+
io.out(
|
|
987
|
+
policy.toHeader({
|
|
988
|
+
...option(options, "nonce") ? { nonce: option(options, "nonce") } : {},
|
|
989
|
+
pretty: Boolean(options.pretty)
|
|
990
|
+
})
|
|
991
|
+
);
|
|
992
|
+
return 0;
|
|
993
|
+
}
|
|
994
|
+
if (command === "explain") {
|
|
995
|
+
const directive = option(options, "directive"), ruleSet = option(options, "rule-set");
|
|
996
|
+
const rows = policy.explain().filter(
|
|
997
|
+
(row) => (!directive || row.directive === directive) && (!ruleSet || row.ruleSet === ruleSet)
|
|
998
|
+
);
|
|
999
|
+
io.out(JSON.stringify(rows, null, 2));
|
|
1000
|
+
return 0;
|
|
1001
|
+
}
|
|
1002
|
+
if (command === "audit") {
|
|
1003
|
+
const threshold = option(options, "fail-on") ?? "high";
|
|
1004
|
+
if (!Object.hasOwn(severities, threshold))
|
|
1005
|
+
throw new Error("--fail-on must be high, medium, low or info");
|
|
1006
|
+
const findings = audit(policy);
|
|
1007
|
+
io.out(JSON.stringify(findings, null, 2));
|
|
1008
|
+
return findings.some(
|
|
1009
|
+
(finding) => severities[finding.severity] >= severities[threshold]
|
|
1010
|
+
) ? 1 : 0;
|
|
1011
|
+
}
|
|
1012
|
+
const file = (0, import_node_path2.resolve)(cwd, option(options, "file") ?? "csp.snapshot.json");
|
|
1013
|
+
const expected = `${JSON.stringify(cspSnapshot(policy), null, 2)}
|
|
1014
|
+
`;
|
|
1015
|
+
if (options.update) {
|
|
1016
|
+
await (0, import_promises2.writeFile)(file, expected, "utf8");
|
|
1017
|
+
io.out(`Updated ${file}`);
|
|
1018
|
+
return 0;
|
|
1019
|
+
}
|
|
1020
|
+
let actual;
|
|
1021
|
+
try {
|
|
1022
|
+
actual = await (0, import_promises2.readFile)(file, "utf8");
|
|
1023
|
+
} catch {
|
|
1024
|
+
throw new Error(
|
|
1025
|
+
`Snapshot not found: ${file}. Run snapshot --update to create it.`
|
|
1026
|
+
);
|
|
1027
|
+
}
|
|
1028
|
+
if (actual !== expected) {
|
|
1029
|
+
io.error(
|
|
1030
|
+
"CSP snapshot differs. Review the policy and run snapshot --update."
|
|
1031
|
+
);
|
|
1032
|
+
return 1;
|
|
1033
|
+
}
|
|
1034
|
+
io.out("CSP snapshot matches.");
|
|
1035
|
+
return 0;
|
|
1036
|
+
} catch (error) {
|
|
1037
|
+
io.error(error instanceof Error ? error.message : String(error));
|
|
1038
|
+
return 1;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
// src/cli/bin.ts
|
|
1043
|
+
void runCli(process.argv.slice(2), {
|
|
1044
|
+
out: (message) => console.log(message),
|
|
1045
|
+
error: (message) => console.error(message)
|
|
1046
|
+
}).then((code) => {
|
|
1047
|
+
process.exitCode = code;
|
|
1048
|
+
});
|
|
1049
|
+
//# sourceMappingURL=cli.cjs.map
|