@jamesbrightman/pretty-csp 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +50 -0
- package/README.md +61 -25
- package/dist/{chunk-TE3J7Y25.js → chunk-JAXLODN4.js} +47 -363
- package/dist/chunk-JAXLODN4.js.map +1 -0
- package/dist/{chunk-MDUQKU6Y.js → chunk-YMAXUCI4.js} +2 -3
- package/dist/{chunk-MDUQKU6Y.js.map → chunk-YMAXUCI4.js.map} +1 -1
- package/dist/cli.cjs +57 -675
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +43 -352
- package/dist/cli.js.map +1 -1
- package/dist/{index-D6PmUWjD.d.cts → index-CvwFjLiu.d.cts} +4 -29
- package/dist/{index-D6PmUWjD.d.ts → index-CvwFjLiu.d.ts} +4 -29
- package/dist/index.cjs +48 -364
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -51
- package/dist/index.d.ts +14 -51
- package/dist/index.js +13 -17
- package/dist/testing.cjs +1 -2
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +7 -4
- package/dist/testing.d.ts +7 -4
- package/dist/testing.js +1 -1
- package/package.json +18 -7
- package/website/static/img/how-it-works.svg +1 -1
- package/website/static/img/pretty-csp-icon.svg +6 -6
- package/dist/chunk-TE3J7Y25.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,23 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
sourceExpressions
|
|
10
|
-
} from "./chunk-TE3J7Y25.js";
|
|
3
|
+
NONCE,
|
|
4
|
+
NONE,
|
|
5
|
+
SELF,
|
|
6
|
+
STRICT_DYNAMIC,
|
|
7
|
+
definePolicy
|
|
8
|
+
} from "./chunk-JAXLODN4.js";
|
|
11
9
|
import {
|
|
12
10
|
cspSnapshot
|
|
13
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-YMAXUCI4.js";
|
|
14
12
|
import {
|
|
15
13
|
audit
|
|
16
14
|
} from "./chunk-KWWYRHIP.js";
|
|
17
15
|
|
|
18
16
|
// src/cli/index.ts
|
|
19
17
|
import { readFile, writeFile as writeFile2 } from "fs/promises";
|
|
20
|
-
import { existsSync } from "fs";
|
|
21
18
|
import { resolve, extname } from "path";
|
|
22
19
|
import { pathToFileURL } from "url";
|
|
23
20
|
import { createJiti } from "jiti";
|
|
@@ -26,12 +23,6 @@ import { createJiti } from "jiti";
|
|
|
26
23
|
import { lstat, mkdir, writeFile } from "fs/promises";
|
|
27
24
|
import { join } from "path";
|
|
28
25
|
async function initProject(cwd, options = {}) {
|
|
29
|
-
const language = options.language ?? "javascript";
|
|
30
|
-
if (!["javascript", "typescript"].includes(language))
|
|
31
|
-
throw new Error("language must be javascript or typescript");
|
|
32
|
-
const mode = options.mode ?? "report-only";
|
|
33
|
-
if (!["enforce", "report-only"].includes(mode))
|
|
34
|
-
throw new Error("mode must be enforce or report-only");
|
|
35
26
|
const apiOrigins = [...new Set(options.apiOrigins ?? [])];
|
|
36
27
|
for (const origin of apiOrigins) {
|
|
37
28
|
let parsed;
|
|
@@ -61,18 +52,13 @@ async function initProject(cwd, options = {}) {
|
|
|
61
52
|
review.setUTCFullYear(review.getUTCFullYear() + 1);
|
|
62
53
|
const reviewBy = review.toISOString().slice(0, 10);
|
|
63
54
|
const policy = definePolicy({
|
|
64
|
-
mode,
|
|
65
55
|
...options.reportUri ? { reporting: { uri: options.reportUri } } : {},
|
|
66
56
|
base: {
|
|
67
|
-
default: [
|
|
68
|
-
scripts: [
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
],
|
|
73
|
-
objects: [sourceExpressions.none],
|
|
74
|
-
baseUri: [sourceExpressions.self],
|
|
75
|
-
frameAncestors: [sourceExpressions.none],
|
|
57
|
+
default: [SELF],
|
|
58
|
+
scripts: [SELF, NONCE, STRICT_DYNAMIC],
|
|
59
|
+
objects: [NONE],
|
|
60
|
+
baseUri: [SELF],
|
|
61
|
+
frameAncestors: [NONE],
|
|
76
62
|
upgradeInsecureRequests: true
|
|
77
63
|
},
|
|
78
64
|
ruleSets: [
|
|
@@ -81,7 +67,7 @@ async function initProject(cwd, options = {}) {
|
|
|
81
67
|
purpose: "Images used by the application",
|
|
82
68
|
owner: "TODO: assign owner",
|
|
83
69
|
reviewBy,
|
|
84
|
-
rules: { images: [
|
|
70
|
+
rules: { images: [SELF, "data:", "blob:"] }
|
|
85
71
|
},
|
|
86
72
|
...apiOrigins.length ? [
|
|
87
73
|
{
|
|
@@ -94,34 +80,31 @@ async function initProject(cwd, options = {}) {
|
|
|
94
80
|
] : []
|
|
95
81
|
]
|
|
96
82
|
});
|
|
97
|
-
const
|
|
98
|
-
const importExtension = language === "typescript" ? "" : ".mjs";
|
|
99
|
-
const apiImport = apiOrigins.length ? `import { appApi } from './rule-sets/app-api${importExtension}';
|
|
83
|
+
const apiImport = apiOrigins.length ? `import { appApi } from './rule-sets/app-api';
|
|
100
84
|
` : "";
|
|
101
85
|
const reporting = options.reportUri ? ` reporting: { uri: ${JSON.stringify(options.reportUri)} },
|
|
102
86
|
` : "";
|
|
103
87
|
const apiTest = apiOrigins.length ? ` expect(policy).toAllow('connect', ${JSON.stringify(apiOrigins[0] + "/")}, { origin: 'https://site.example', redirectCount: 0 });
|
|
104
88
|
` : "";
|
|
105
89
|
const files = {
|
|
106
|
-
|
|
90
|
+
"csp.config.ts": `export { policy as default } from './csp/policy';
|
|
107
91
|
`,
|
|
108
|
-
|
|
109
|
-
import { appAssets } from './rule-sets/app-assets
|
|
92
|
+
"csp/policy.ts": `import { definePolicy, SELF, NONE, NONCE, STRICT_DYNAMIC } from '@jamesbrightman/pretty-csp';
|
|
93
|
+
import { appAssets } from './rule-sets/app-assets';
|
|
110
94
|
${apiImport}
|
|
111
95
|
export const policy = definePolicy({
|
|
112
|
-
|
|
113
|
-
${reporting} base: { default: [sourceExpressions.self], scripts: [sourceExpressions.self, sourceExpressions.nonce, sourceExpressions.strictDynamic], objects: [sourceExpressions.none], baseUri: [sourceExpressions.self], frameAncestors: [sourceExpressions.none], upgradeInsecureRequests: true },
|
|
96
|
+
${reporting} base: { default: [SELF], scripts: [SELF, NONCE, STRICT_DYNAMIC], objects: [NONE], baseUri: [SELF], frameAncestors: [NONE], upgradeInsecureRequests: true },
|
|
114
97
|
ruleSets: [appAssets${apiOrigins.length ? ", appApi" : ""}],
|
|
115
98
|
});
|
|
116
99
|
`,
|
|
117
|
-
|
|
100
|
+
"csp/rule-sets/app-assets.ts": `import { defineRuleSet, SELF } from '@jamesbrightman/pretty-csp';
|
|
118
101
|
|
|
119
|
-
export const appAssets = defineRuleSet({ name: 'App assets', purpose: 'Images used by the application', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { images: [
|
|
102
|
+
export const appAssets = defineRuleSet({ name: 'App assets', purpose: 'Images used by the application', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { images: [SELF, 'data:', 'blob:'] } });
|
|
120
103
|
`,
|
|
121
|
-
|
|
104
|
+
"csp/policy.test.ts": `import { readFile } from 'node:fs/promises';
|
|
122
105
|
import { expect, test } from 'vitest';
|
|
123
|
-
import { cspMatchers
|
|
124
|
-
import { policy } from './policy
|
|
106
|
+
import { cspMatchers } from '@jamesbrightman/pretty-csp/testing';
|
|
107
|
+
import { policy } from './policy';
|
|
125
108
|
|
|
126
109
|
expect.extend(cspMatchers);
|
|
127
110
|
test('blocks untrusted connections and has no high-risk findings', () => {
|
|
@@ -132,12 +115,20 @@ test('matches the reviewed CSP snapshot', async () => {
|
|
|
132
115
|
const snapshot = JSON.parse(await readFile(new URL('../csp.snapshot.json', import.meta.url), 'utf8'));
|
|
133
116
|
expect(policy).toMatchCspSnapshot(snapshot);
|
|
134
117
|
});
|
|
118
|
+
`,
|
|
119
|
+
"csp/vitest.d.ts": `import 'vitest';
|
|
120
|
+
import type { CspAssertions } from '@jamesbrightman/pretty-csp/testing';
|
|
121
|
+
|
|
122
|
+
declare module 'vitest' {
|
|
123
|
+
interface Assertion<T> extends CspAssertions<T> {}
|
|
124
|
+
interface AsymmetricMatchersContaining extends CspAssertions {}
|
|
125
|
+
}
|
|
135
126
|
`,
|
|
136
127
|
"csp.snapshot.json": `${JSON.stringify(cspSnapshot(policy), null, 2)}
|
|
137
128
|
`
|
|
138
129
|
};
|
|
139
130
|
if (apiOrigins.length)
|
|
140
|
-
files[
|
|
131
|
+
files["csp/rule-sets/app-api.ts"] = `import { defineRuleSet } from '@jamesbrightman/pretty-csp';
|
|
141
132
|
|
|
142
133
|
export const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API connections', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { connect: ${JSON.stringify(apiOrigins)} } });
|
|
143
134
|
`;
|
|
@@ -174,219 +165,8 @@ export const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API
|
|
|
174
165
|
return Object.keys(files);
|
|
175
166
|
}
|
|
176
167
|
|
|
177
|
-
// src/cli/import.ts
|
|
178
|
-
import { mkdir as mkdir2, open, rmdir, unlink } from "fs/promises";
|
|
179
|
-
import { join as join2 } from "path";
|
|
180
|
-
import { parse } from "tldts";
|
|
181
|
-
function registrableDomain(source) {
|
|
182
|
-
const host = /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:\*\.)?([a-z0-9-]+(?:\.[a-z0-9-]+)+)(?=[:/]|$)/i.exec(
|
|
183
|
-
source
|
|
184
|
-
)?.[1];
|
|
185
|
-
if (!host) return void 0;
|
|
186
|
-
const { domain, isIcann, isPrivate } = parse(host, {
|
|
187
|
-
allowPrivateDomains: true
|
|
188
|
-
});
|
|
189
|
-
return domain && (isIcann || isPrivate) ? domain.toLowerCase() : void 0;
|
|
190
|
-
}
|
|
191
|
-
function importDraftFiles(draft, mode) {
|
|
192
|
-
const groups = /* @__PURE__ */ new Map();
|
|
193
|
-
const unassigned = {};
|
|
194
|
-
for (const [directive, entries] of Object.entries(
|
|
195
|
-
draft.base?.directives ?? {}
|
|
196
|
-
)) {
|
|
197
|
-
rejectCapturedNonces(entries, directive);
|
|
198
|
-
}
|
|
199
|
-
for (const ruleSet of draft.ruleSets ?? []) {
|
|
200
|
-
for (const [directive, entries] of Object.entries(
|
|
201
|
-
ruleSet.rules.directives ?? {}
|
|
202
|
-
)) {
|
|
203
|
-
rejectCapturedNonces(entries, directive);
|
|
204
|
-
for (const entry of entries) {
|
|
205
|
-
const domain = registrableDomain(
|
|
206
|
-
typeof entry === "string" ? entry : entry.source
|
|
207
|
-
);
|
|
208
|
-
let directives = unassigned;
|
|
209
|
-
if (domain) {
|
|
210
|
-
directives = groups.get(domain) ?? {};
|
|
211
|
-
groups.set(domain, directives);
|
|
212
|
-
}
|
|
213
|
-
(directives[directive] ??= []).push(entry);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
const files = /* @__PURE__ */ new Map();
|
|
218
|
-
const imports = [];
|
|
219
|
-
const names = [];
|
|
220
|
-
const addRuleSet = (filename, ruleSet) => {
|
|
221
|
-
const path = `rule-sets/${filename}.mjs`;
|
|
222
|
-
const name = `ruleSet${names.length + 1}`;
|
|
223
|
-
files.set(
|
|
224
|
-
path,
|
|
225
|
-
`import { defineRuleSet } from '@jamesbrightman/pretty-csp';
|
|
226
|
-
|
|
227
|
-
export default defineRuleSet(${JSON.stringify(ruleSet, null, 2)});
|
|
228
|
-
`
|
|
229
|
-
);
|
|
230
|
-
imports.push(`import ${name} from './${path}';`);
|
|
231
|
-
names.push(name);
|
|
232
|
-
};
|
|
233
|
-
const sortedGroups = Array.from(groups).sort(
|
|
234
|
-
([first], [second]) => first.localeCompare(second, "en")
|
|
235
|
-
);
|
|
236
|
-
for (const [domain, directives] of sortedGroups) {
|
|
237
|
-
addRuleSet(`domain-${domain}`, {
|
|
238
|
-
name: domain,
|
|
239
|
-
purpose: "Imported domain group. Confirm purpose and owner before use.",
|
|
240
|
-
rules: { directives }
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
if (Object.keys(unassigned).length) {
|
|
244
|
-
addRuleSet("unassigned", {
|
|
245
|
-
name: "Unassigned sources",
|
|
246
|
-
purpose: "Imported sources that need manual grouping and review.",
|
|
247
|
-
rules: { directives: unassigned }
|
|
248
|
-
});
|
|
249
|
-
}
|
|
250
|
-
files.set(
|
|
251
|
-
"csp.config.mjs",
|
|
252
|
-
[
|
|
253
|
-
"import { definePolicy } from '@jamesbrightman/pretty-csp';",
|
|
254
|
-
...imports,
|
|
255
|
-
"",
|
|
256
|
-
"// Review this draft before using it in an application.",
|
|
257
|
-
"export default definePolicy({",
|
|
258
|
-
` mode: ${JSON.stringify(mode)},`,
|
|
259
|
-
` base: ${JSON.stringify(draft.base ?? {}, null, 2).replace(/\n/g, "\n ")},`,
|
|
260
|
-
` ruleSets: [${names.join(", ")}],`,
|
|
261
|
-
"});",
|
|
262
|
-
""
|
|
263
|
-
].join("\n")
|
|
264
|
-
);
|
|
265
|
-
return files;
|
|
266
|
-
}
|
|
267
|
-
function rejectCapturedNonces(entries, directive) {
|
|
268
|
-
if (entries.some(
|
|
269
|
-
(entry) => /^'nonce-/i.test(typeof entry === "string" ? entry : entry.source)
|
|
270
|
-
)) {
|
|
271
|
-
throw new Error(
|
|
272
|
-
`Directive ${directive} contains a captured nonce. Migrate it separately using a fresh nonce per response.`
|
|
273
|
-
);
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
async function writeImportDraft(output, files) {
|
|
277
|
-
try {
|
|
278
|
-
await mkdir2(output);
|
|
279
|
-
} catch (error) {
|
|
280
|
-
if (error.code === "EEXIST")
|
|
281
|
-
throw new Error(
|
|
282
|
-
`Import output already exists: ${output}. Choose a new directory.`
|
|
283
|
-
);
|
|
284
|
-
throw error;
|
|
285
|
-
}
|
|
286
|
-
const createdFiles = [];
|
|
287
|
-
let createdRuleSets = false;
|
|
288
|
-
try {
|
|
289
|
-
if (files.size > 1) {
|
|
290
|
-
await mkdir2(join2(output, "rule-sets"));
|
|
291
|
-
createdRuleSets = true;
|
|
292
|
-
}
|
|
293
|
-
for (const [name, content] of files) {
|
|
294
|
-
const path = join2(output, name);
|
|
295
|
-
const file = await open(path, "wx");
|
|
296
|
-
createdFiles.push(path);
|
|
297
|
-
try {
|
|
298
|
-
await file.writeFile(content, "utf8");
|
|
299
|
-
} finally {
|
|
300
|
-
await file.close();
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
} catch (error) {
|
|
304
|
-
try {
|
|
305
|
-
for (const path of createdFiles) await unlink(path);
|
|
306
|
-
if (createdRuleSets) await rmdir(join2(output, "rule-sets"));
|
|
307
|
-
await rmdir(output);
|
|
308
|
-
} catch {
|
|
309
|
-
throw new Error(
|
|
310
|
-
`Import failed and may have left partial files in ${output}`,
|
|
311
|
-
{ cause: error }
|
|
312
|
-
);
|
|
313
|
-
}
|
|
314
|
-
throw error;
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// src/cli/diff.ts
|
|
319
|
-
import { execFile } from "child_process";
|
|
320
|
-
import { promisify } from "util";
|
|
321
|
-
import { z } from "zod";
|
|
322
|
-
var snapshotSchema = z.object({
|
|
323
|
-
schemaVersion: z.literal(1),
|
|
324
|
-
mode: z.enum(["enforce", "report-only"]),
|
|
325
|
-
directives: z.record(
|
|
326
|
-
z.string().regex(/^[a-z][a-z0-9-]*$/),
|
|
327
|
-
z.array(z.string())
|
|
328
|
-
),
|
|
329
|
-
contributors: z.array(
|
|
330
|
-
z.object({
|
|
331
|
-
directive: z.string(),
|
|
332
|
-
source: z.string(),
|
|
333
|
-
ruleSet: z.string(),
|
|
334
|
-
reason: z.string().optional()
|
|
335
|
-
}).strict()
|
|
336
|
-
)
|
|
337
|
-
}).strict();
|
|
338
|
-
async function readGitSnapshot(ref, cwd) {
|
|
339
|
-
if (!/^[a-zA-Z0-9][a-zA-Z0-9._/~^-]*$/.test(ref))
|
|
340
|
-
throw new Error("Invalid Git ref");
|
|
341
|
-
const exec = promisify(execFile);
|
|
342
|
-
try {
|
|
343
|
-
const { stdout } = await exec(
|
|
344
|
-
"git",
|
|
345
|
-
["show", "--no-ext-diff", "--no-textconv", `${ref}:csp.snapshot.json`],
|
|
346
|
-
{ cwd, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }
|
|
347
|
-
);
|
|
348
|
-
return stdout;
|
|
349
|
-
} catch {
|
|
350
|
-
throw new Error(
|
|
351
|
-
"Could not read csp.snapshot.json at the Git ref; commit a version 1 snapshot at the repository root."
|
|
352
|
-
);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
function diffSnapshot(json, current) {
|
|
356
|
-
let data;
|
|
357
|
-
try {
|
|
358
|
-
data = JSON.parse(json);
|
|
359
|
-
} catch {
|
|
360
|
-
throw new Error("Invalid snapshot JSON");
|
|
361
|
-
}
|
|
362
|
-
const parsed = snapshotSchema.safeParse(data);
|
|
363
|
-
if (!parsed.success)
|
|
364
|
-
throw new Error("Invalid or unsupported CSP snapshot format");
|
|
365
|
-
const snapshot = parsed.data;
|
|
366
|
-
for (const row of snapshot.contributors) {
|
|
367
|
-
if (!snapshot.directives[row.directive]?.includes(row.source))
|
|
368
|
-
throw new Error("Snapshot contributor does not match a directive source");
|
|
369
|
-
}
|
|
370
|
-
for (const [directive, sources] of Object.entries(snapshot.directives)) {
|
|
371
|
-
if (directive === "report-uri" || directive === "report-to") continue;
|
|
372
|
-
for (const source of sources) {
|
|
373
|
-
if (!snapshot.contributors.some(
|
|
374
|
-
(row) => row.directive === directive && row.source === source
|
|
375
|
-
))
|
|
376
|
-
throw new Error("Snapshot source has no contributor");
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
const previous = {
|
|
380
|
-
config: { mode: snapshot.mode },
|
|
381
|
-
toObject: () => snapshot.directives,
|
|
382
|
-
explain: () => snapshot.contributors
|
|
383
|
-
};
|
|
384
|
-
return diffPolicies(previous, current);
|
|
385
|
-
}
|
|
386
|
-
|
|
387
168
|
// src/cli/index.ts
|
|
388
|
-
var help = "Usage: pretty-csp <init|print|explain|audit|snapshot
|
|
389
|
-
var importHelp = "Usage: pretty-csp import <header> | --file <header-file> [--output <new-directory> [--dry-run] [--mode <report-only|enforce>]]";
|
|
169
|
+
var help = "Usage: pretty-csp <init|print|explain|audit|snapshot> [--config path] [options]";
|
|
390
170
|
var severities = {
|
|
391
171
|
info: 0,
|
|
392
172
|
low: 1,
|
|
@@ -396,7 +176,6 @@ var severities = {
|
|
|
396
176
|
function argsFor(args) {
|
|
397
177
|
const [command = "help", ...rest] = args;
|
|
398
178
|
const options = {};
|
|
399
|
-
let positional;
|
|
400
179
|
const flags = /* @__PURE__ */ new Set([
|
|
401
180
|
"pretty",
|
|
402
181
|
"update",
|
|
@@ -412,21 +191,12 @@ function argsFor(args) {
|
|
|
412
191
|
"rule-set",
|
|
413
192
|
"fail-on",
|
|
414
193
|
"file",
|
|
415
|
-
"output",
|
|
416
|
-
"base",
|
|
417
|
-
"language",
|
|
418
194
|
"api-origins",
|
|
419
|
-
"report-uri"
|
|
420
|
-
"mode"
|
|
195
|
+
"report-uri"
|
|
421
196
|
]);
|
|
422
197
|
for (let i = 0; i < rest.length; i++) {
|
|
423
198
|
const arg = rest[i];
|
|
424
|
-
if (!arg.startsWith("--")) {
|
|
425
|
-
if (!["import", "check-reports"].includes(command) || positional !== void 0)
|
|
426
|
-
throw new Error(`Unexpected argument: ${arg}`);
|
|
427
|
-
positional = arg;
|
|
428
|
-
continue;
|
|
429
|
-
}
|
|
199
|
+
if (!arg.startsWith("--")) throw new Error(`Unexpected argument: ${arg}`);
|
|
430
200
|
const key = arg.slice(2);
|
|
431
201
|
if (flags.has(key)) options[key] = true;
|
|
432
202
|
else if (values.has(key)) {
|
|
@@ -438,8 +208,7 @@ function argsFor(args) {
|
|
|
438
208
|
}
|
|
439
209
|
return {
|
|
440
210
|
command,
|
|
441
|
-
options
|
|
442
|
-
...positional === void 0 ? {} : { positional }
|
|
211
|
+
options
|
|
443
212
|
};
|
|
444
213
|
}
|
|
445
214
|
function option(options, name) {
|
|
@@ -459,90 +228,32 @@ async function loadConfigFile(path) {
|
|
|
459
228
|
}
|
|
460
229
|
async function runCli(args, io, cwd = process.cwd(), loadConfig = loadConfigFile) {
|
|
461
230
|
try {
|
|
462
|
-
const { command, options
|
|
463
|
-
if (command === "help" || options.help) {
|
|
464
|
-
io.out(
|
|
231
|
+
const { command, options } = argsFor(args);
|
|
232
|
+
if (command === "help" || command === "--help" || options.help) {
|
|
233
|
+
io.out(help);
|
|
465
234
|
return 0;
|
|
466
235
|
}
|
|
467
|
-
if (![
|
|
468
|
-
"init",
|
|
469
|
-
"print",
|
|
470
|
-
"explain",
|
|
471
|
-
"audit",
|
|
472
|
-
"snapshot",
|
|
473
|
-
"diff",
|
|
474
|
-
"import",
|
|
475
|
-
"check-reports"
|
|
476
|
-
].includes(command))
|
|
236
|
+
if (!["init", "print", "explain", "audit", "snapshot"].includes(command))
|
|
477
237
|
throw new Error(`Unsupported command: ${command}. ${help}`);
|
|
478
238
|
if (command === "init") {
|
|
479
239
|
if (!options.yes)
|
|
480
240
|
throw new Error(
|
|
481
|
-
"Use init --yes and optional --
|
|
241
|
+
"Use init --yes and optional --api-origins and --report-uri flags."
|
|
482
242
|
);
|
|
483
243
|
const files = await initProject(cwd, {
|
|
484
244
|
dryRun: Boolean(options["dry-run"]),
|
|
485
245
|
force: Boolean(options.force),
|
|
486
|
-
language: option(options, "language"),
|
|
487
|
-
mode: option(options, "mode"),
|
|
488
246
|
apiOrigins: option(options, "api-origins")?.split(",").map((origin) => origin.trim()),
|
|
489
247
|
reportUri: option(options, "report-uri")
|
|
490
248
|
});
|
|
491
249
|
io.out(
|
|
492
250
|
`${options["dry-run"] ? "Would write" : "Wrote"}:
|
|
493
251
|
${files.join("\n")}
|
|
494
|
-
Install @jamesbrightman/pretty-csp and Vitest, then configure your server to set
|
|
252
|
+
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.`
|
|
495
253
|
);
|
|
496
254
|
return 0;
|
|
497
255
|
}
|
|
498
|
-
|
|
499
|
-
const headerFile = option(options, "file");
|
|
500
|
-
const output = option(options, "output");
|
|
501
|
-
if (!positional && !headerFile || positional && headerFile)
|
|
502
|
-
throw new Error(
|
|
503
|
-
"import requires a header string or --file, but not both"
|
|
504
|
-
);
|
|
505
|
-
if (!output && (options["dry-run"] || options.mode))
|
|
506
|
-
throw new Error("--dry-run and --mode require --output for import");
|
|
507
|
-
if (options.force)
|
|
508
|
-
throw new Error(
|
|
509
|
-
"Import requires a new output directory. --force is not supported."
|
|
510
|
-
);
|
|
511
|
-
const header = headerFile ? (await readFile(resolve(cwd, headerFile), "utf8")).replace(
|
|
512
|
-
/\r?\n$/,
|
|
513
|
-
""
|
|
514
|
-
) : positional;
|
|
515
|
-
const parsed = importHeader(header);
|
|
516
|
-
const draft = importedPolicyToDraft(parsed);
|
|
517
|
-
if (output) {
|
|
518
|
-
const mode = option(options, "mode") ?? "report-only";
|
|
519
|
-
if (mode !== "enforce" && mode !== "report-only")
|
|
520
|
-
throw new Error("--mode must be enforce or report-only");
|
|
521
|
-
const files = importDraftFiles(draft, mode);
|
|
522
|
-
const destination = resolve(cwd, output);
|
|
523
|
-
if (!options["dry-run"]) await writeImportDraft(destination, files);
|
|
524
|
-
io.out(
|
|
525
|
-
`${options["dry-run"] ? "Would write to" : "Wrote to"} ${destination}:
|
|
526
|
-
${Array.from(files.keys()).join("\n")}
|
|
527
|
-
Review the draft and assign owners before use.`
|
|
528
|
-
);
|
|
529
|
-
return 0;
|
|
530
|
-
}
|
|
531
|
-
io.out(
|
|
532
|
-
JSON.stringify(
|
|
533
|
-
{
|
|
534
|
-
draft,
|
|
535
|
-
warnings: parsed.warnings,
|
|
536
|
-
note: "Review the draft before saving; no files were written."
|
|
537
|
-
},
|
|
538
|
-
null,
|
|
539
|
-
2
|
|
540
|
-
)
|
|
541
|
-
);
|
|
542
|
-
return 0;
|
|
543
|
-
}
|
|
544
|
-
const defaultConfig = existsSync(resolve(cwd, "csp.config.ts")) ? "csp.config.ts" : "csp.config.mjs";
|
|
545
|
-
const path = resolve(cwd, option(options, "config") ?? defaultConfig);
|
|
256
|
+
const path = resolve(cwd, option(options, "config") ?? "csp.config.ts");
|
|
546
257
|
const module = await loadConfig(path);
|
|
547
258
|
const candidate = module.default ?? module.policy;
|
|
548
259
|
const policy = candidate && typeof candidate === "object" && "policy" in candidate ? candidate.policy : candidate;
|
|
@@ -550,26 +261,6 @@ Review the draft and assign owners before use.`
|
|
|
550
261
|
throw new Error(
|
|
551
262
|
"Config must export a Policy as default, as policy, or as default.policy"
|
|
552
263
|
);
|
|
553
|
-
if (command === "diff") {
|
|
554
|
-
const ref = option(options, "base");
|
|
555
|
-
if (!ref)
|
|
556
|
-
throw new Error(
|
|
557
|
-
"diff requires --base <git-ref> and a committed csp.snapshot.json at the repository root"
|
|
558
|
-
);
|
|
559
|
-
const result = diffSnapshot(await readGitSnapshot(ref, cwd), policy);
|
|
560
|
-
io.out(JSON.stringify(result, null, 2));
|
|
561
|
-
return 0;
|
|
562
|
-
}
|
|
563
|
-
if (command === "check-reports") {
|
|
564
|
-
if (!positional) throw new Error("check-reports requires a JSON file");
|
|
565
|
-
const contents = await readFile(resolve(cwd, positional), "utf8");
|
|
566
|
-
const results = replayReports(
|
|
567
|
-
policy.toObject(),
|
|
568
|
-
parseViolationReports(contents)
|
|
569
|
-
);
|
|
570
|
-
io.out(JSON.stringify(results, null, 2));
|
|
571
|
-
return results.some(({ result }) => result.status !== "allowed") ? 1 : 0;
|
|
572
|
-
}
|
|
573
264
|
if (command === "print") {
|
|
574
265
|
io.out(
|
|
575
266
|
policy.toHeader({
|