@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.cjs
CHANGED
|
@@ -2,9 +2,8 @@
|
|
|
2
2
|
"use strict";
|
|
3
3
|
|
|
4
4
|
// src/cli/index.ts
|
|
5
|
-
var
|
|
6
|
-
var
|
|
7
|
-
var import_node_path3 = require("path");
|
|
5
|
+
var import_promises2 = require("fs/promises");
|
|
6
|
+
var import_node_path2 = require("path");
|
|
8
7
|
var import_node_url = require("url");
|
|
9
8
|
var import_jiti = require("jiti");
|
|
10
9
|
|
|
@@ -231,8 +230,7 @@ function audit(policy, options = {}) {
|
|
|
231
230
|
// src/testing/index.ts
|
|
232
231
|
function cspSnapshot(policy) {
|
|
233
232
|
return {
|
|
234
|
-
schemaVersion:
|
|
235
|
-
mode: policy.config.mode,
|
|
233
|
+
schemaVersion: 2,
|
|
236
234
|
directives: policy.toObject(),
|
|
237
235
|
contributors: policy.explain()
|
|
238
236
|
};
|
|
@@ -467,116 +465,15 @@ function matchPolicy(directives, directive, input, options = {}) {
|
|
|
467
465
|
return decision("blocked", effective, "No source matched");
|
|
468
466
|
}
|
|
469
467
|
|
|
470
|
-
// src/reports/index.ts
|
|
471
|
-
function record(value) {
|
|
472
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
473
|
-
}
|
|
474
|
-
function field(obj, ...keys) {
|
|
475
|
-
for (const key of keys)
|
|
476
|
-
if (typeof obj[key] === "string" && obj[key]) return obj[key];
|
|
477
|
-
return void 0;
|
|
478
|
-
}
|
|
479
|
-
function parseViolationReports(input) {
|
|
480
|
-
if (typeof input === "string") {
|
|
481
|
-
try {
|
|
482
|
-
input = JSON.parse(input);
|
|
483
|
-
} catch {
|
|
484
|
-
throw new Error("Invalid report JSON");
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
const items = Array.isArray(input) ? input : [input];
|
|
488
|
-
return items.map((item, index) => {
|
|
489
|
-
const envelope = record(item);
|
|
490
|
-
if (!envelope) throw new Error(`Unsupported report at index ${index}`);
|
|
491
|
-
const body = (envelope.type === "csp" ? record(envelope.csp) : void 0) ?? record(envelope["csp-report"]) ?? (envelope.type === "csp-violation" ? record(envelope.body) : void 0) ?? envelope;
|
|
492
|
-
const directive = field(
|
|
493
|
-
body,
|
|
494
|
-
"effective-directive",
|
|
495
|
-
"effectiveDirective",
|
|
496
|
-
"effective_directive",
|
|
497
|
-
"violated-directive",
|
|
498
|
-
"violatedDirective",
|
|
499
|
-
"violated_directive"
|
|
500
|
-
);
|
|
501
|
-
const blockedURL = field(
|
|
502
|
-
body,
|
|
503
|
-
"blocked-uri",
|
|
504
|
-
"blockedURL",
|
|
505
|
-
"blockedUri",
|
|
506
|
-
"blocked_uri"
|
|
507
|
-
);
|
|
508
|
-
const documentURL = field(
|
|
509
|
-
body,
|
|
510
|
-
"document-uri",
|
|
511
|
-
"documentURL",
|
|
512
|
-
"documentUri",
|
|
513
|
-
"document_uri"
|
|
514
|
-
);
|
|
515
|
-
if (!directive || !blockedURL)
|
|
516
|
-
throw new Error(`Unsupported or incomplete report at index ${index}`);
|
|
517
|
-
return {
|
|
518
|
-
directive: directive.split(" ")[0],
|
|
519
|
-
blockedURL,
|
|
520
|
-
...documentURL ? { documentURL } : {}
|
|
521
|
-
};
|
|
522
|
-
});
|
|
523
|
-
}
|
|
524
|
-
function replayReports(directives, reports) {
|
|
525
|
-
return reports.map((report) => {
|
|
526
|
-
let origin;
|
|
527
|
-
try {
|
|
528
|
-
if (report.documentURL) {
|
|
529
|
-
const parsedOrigin = new URL(report.documentURL).origin;
|
|
530
|
-
if (parsedOrigin !== "null") origin = parsedOrigin;
|
|
531
|
-
}
|
|
532
|
-
} catch {
|
|
533
|
-
}
|
|
534
|
-
let blocked;
|
|
535
|
-
try {
|
|
536
|
-
blocked = new URL(report.blockedURL);
|
|
537
|
-
} catch {
|
|
538
|
-
return {
|
|
539
|
-
report,
|
|
540
|
-
result: {
|
|
541
|
-
status: "indeterminate",
|
|
542
|
-
allowed: null,
|
|
543
|
-
reason: "Report does not contain a replayable URL"
|
|
544
|
-
}
|
|
545
|
-
};
|
|
546
|
-
}
|
|
547
|
-
if (!["http:", "https:", "ws:", "wss:"].includes(blocked.protocol)) {
|
|
548
|
-
return {
|
|
549
|
-
report,
|
|
550
|
-
result: {
|
|
551
|
-
status: "indeterminate",
|
|
552
|
-
allowed: null,
|
|
553
|
-
reason: "Report does not contain a replayable network URL"
|
|
554
|
-
}
|
|
555
|
-
};
|
|
556
|
-
}
|
|
557
|
-
const result = matchPolicy(
|
|
558
|
-
directives,
|
|
559
|
-
report.directive,
|
|
560
|
-
report.blockedURL,
|
|
561
|
-
origin ? { origin } : {}
|
|
562
|
-
);
|
|
563
|
-
if (result.status === "allowed" && result.matchedSource && result.matchedSource.replace(/^[a-z]+:\/\//i, "").includes("/")) {
|
|
564
|
-
return {
|
|
565
|
-
report,
|
|
566
|
-
result: {
|
|
567
|
-
status: "indeterminate",
|
|
568
|
-
allowed: null,
|
|
569
|
-
reason: "Report may omit the request path"
|
|
570
|
-
}
|
|
571
|
-
};
|
|
572
|
-
}
|
|
573
|
-
return { report, result };
|
|
574
|
-
});
|
|
575
|
-
}
|
|
576
|
-
|
|
577
468
|
// src/core.ts
|
|
578
469
|
var import_zod2 = require("zod");
|
|
579
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
|
+
|
|
580
477
|
// src/schemas.ts
|
|
581
478
|
var import_zod = require("zod");
|
|
582
479
|
var resourceDirectives = {
|
|
@@ -606,11 +503,10 @@ var keywords = /* @__PURE__ */ new Set([
|
|
|
606
503
|
"'wasm-unsafe-eval'",
|
|
607
504
|
...risky
|
|
608
505
|
]);
|
|
609
|
-
var NONCE_PLACEHOLDER = "'nonce-{nonce}'";
|
|
610
506
|
function isSource(value) {
|
|
611
507
|
if (!value || /[\x00-\x20\x7f;,]/.test(value) || /^[a-z][a-z0-9+.-]*\/\//i.test(value))
|
|
612
508
|
return false;
|
|
613
|
-
if (keywords.has(value.toLowerCase()) || value ===
|
|
509
|
+
if (keywords.has(value.toLowerCase()) || value === NONCE || value === "*" || /^[a-z][a-z0-9+.-]*:\/\/\*(?::(?:\d+|\*))?(?:\/[^\s;,#?]*)?$/i.test(value))
|
|
614
510
|
return true;
|
|
615
511
|
if (/^'(nonce-[A-Za-z0-9+/_-]+={0,2}|sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2})'$/i.test(
|
|
616
512
|
value
|
|
@@ -708,8 +604,7 @@ var reportingSchema = import_zod.z.object({
|
|
|
708
604
|
var policyConfigSchema = import_zod.z.object({
|
|
709
605
|
base: baseSchema.default({}),
|
|
710
606
|
ruleSets: import_zod.z.array(ruleSetSchema).default([]),
|
|
711
|
-
reporting: reportingSchema.optional()
|
|
712
|
-
mode: import_zod.z.enum(["enforce", "report-only"]).default("enforce")
|
|
607
|
+
reporting: reportingSchema.optional()
|
|
713
608
|
}).strict().superRefine((config, ctx) => {
|
|
714
609
|
const names = /* @__PURE__ */ new Set();
|
|
715
610
|
config.ruleSets.forEach((rule, i) => {
|
|
@@ -739,7 +634,6 @@ function entryReason(entry) {
|
|
|
739
634
|
}
|
|
740
635
|
var Policy = class _Policy {
|
|
741
636
|
config;
|
|
742
|
-
headerName;
|
|
743
637
|
constructor(input) {
|
|
744
638
|
const result = policyConfigSchema.safeParse(input);
|
|
745
639
|
if (!result.success) {
|
|
@@ -756,7 +650,6 @@ var Policy = class _Policy {
|
|
|
756
650
|
}
|
|
757
651
|
const config = result.data;
|
|
758
652
|
this.config = freeze(config);
|
|
759
|
-
this.headerName = config.mode === "enforce" ? "Content-Security-Policy" : "Content-Security-Policy-Report-Only";
|
|
760
653
|
Object.freeze(this);
|
|
761
654
|
}
|
|
762
655
|
/** Sources and their contributing rule sets. Duplicate values retain all contributors. */
|
|
@@ -816,44 +709,26 @@ var Policy = class _Policy {
|
|
|
816
709
|
) : [];
|
|
817
710
|
return contributors.length ? { ...result, contributors } : result;
|
|
818
711
|
}
|
|
819
|
-
/** Replay supported violation report JSON without inventing missing request context. */
|
|
820
|
-
check(reports) {
|
|
821
|
-
return replayReports(this.toObject(), parseViolationReports(reports));
|
|
822
|
-
}
|
|
823
712
|
/** Render a header value. Pretty output is for display only and is not a valid HTTP header value. */
|
|
824
713
|
toHeader(options = {}) {
|
|
825
|
-
|
|
826
|
-
}
|
|
827
|
-
render(directives, options) {
|
|
714
|
+
const directives = this.toObject();
|
|
828
715
|
const hasNonce = Object.values(directives).some(
|
|
829
|
-
(sources) => sources.includes(
|
|
716
|
+
(sources) => sources.includes(NONCE)
|
|
830
717
|
);
|
|
831
718
|
if (hasNonce && (!options.nonce || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(options.nonce)))
|
|
832
719
|
throw new Error("A valid base64 nonce is required");
|
|
833
720
|
return Object.entries(directives).map(([directive, values]) => {
|
|
834
721
|
const rendered = values.map(
|
|
835
|
-
(value) => value ===
|
|
722
|
+
(value) => value === NONCE ? `'nonce-${options.nonce}'` : value
|
|
836
723
|
);
|
|
837
724
|
return directive + (rendered.length ? ` ${rendered.join(" ")}` : "");
|
|
838
725
|
}).join(options.pretty ? ";\n" : "; ");
|
|
839
726
|
}
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
if (this.config.mode === "report-only")
|
|
843
|
-
throw new Error(
|
|
844
|
-
"Report-only policies cannot be delivered in a meta element"
|
|
845
|
-
);
|
|
846
|
-
const directives = this.toObject();
|
|
847
|
-
delete directives["frame-ancestors"];
|
|
848
|
-
delete directives["report-uri"];
|
|
849
|
-
delete directives["report-to"];
|
|
850
|
-
delete directives.sandbox;
|
|
851
|
-
return this.render(directives, options);
|
|
852
|
-
}
|
|
853
|
-
withRuleSet(ruleSet) {
|
|
727
|
+
withRuleSet(ruleSets) {
|
|
728
|
+
const additions = Array.isArray(ruleSets) ? ruleSets : [ruleSets];
|
|
854
729
|
return new _Policy({
|
|
855
730
|
...this.config,
|
|
856
|
-
ruleSets: [...this.config.ruleSets,
|
|
731
|
+
ruleSets: [...this.config.ruleSets, ...additions]
|
|
857
732
|
});
|
|
858
733
|
}
|
|
859
734
|
without(name) {
|
|
@@ -867,24 +742,8 @@ function definePolicy(input) {
|
|
|
867
742
|
return new Policy(input);
|
|
868
743
|
}
|
|
869
744
|
|
|
870
|
-
// src/keywords.ts
|
|
871
|
-
var sourceExpressions = {
|
|
872
|
-
self: "'self'",
|
|
873
|
-
none: "'none'",
|
|
874
|
-
nonce: NONCE_PLACEHOLDER,
|
|
875
|
-
strictDynamic: "'strict-dynamic'",
|
|
876
|
-
reportSample: "'report-sample'",
|
|
877
|
-
wasmUnsafeEval: "'wasm-unsafe-eval'"
|
|
878
|
-
};
|
|
879
|
-
|
|
880
745
|
// src/cli/init.ts
|
|
881
746
|
async function initProject(cwd, options = {}) {
|
|
882
|
-
const language = options.language ?? "javascript";
|
|
883
|
-
if (!["javascript", "typescript"].includes(language))
|
|
884
|
-
throw new Error("language must be javascript or typescript");
|
|
885
|
-
const mode = options.mode ?? "report-only";
|
|
886
|
-
if (!["enforce", "report-only"].includes(mode))
|
|
887
|
-
throw new Error("mode must be enforce or report-only");
|
|
888
747
|
const apiOrigins = [...new Set(options.apiOrigins ?? [])];
|
|
889
748
|
for (const origin of apiOrigins) {
|
|
890
749
|
let parsed;
|
|
@@ -914,18 +773,13 @@ async function initProject(cwd, options = {}) {
|
|
|
914
773
|
review.setUTCFullYear(review.getUTCFullYear() + 1);
|
|
915
774
|
const reviewBy = review.toISOString().slice(0, 10);
|
|
916
775
|
const policy = definePolicy({
|
|
917
|
-
mode,
|
|
918
776
|
...options.reportUri ? { reporting: { uri: options.reportUri } } : {},
|
|
919
777
|
base: {
|
|
920
|
-
default: [
|
|
921
|
-
scripts: [
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
],
|
|
926
|
-
objects: [sourceExpressions.none],
|
|
927
|
-
baseUri: [sourceExpressions.self],
|
|
928
|
-
frameAncestors: [sourceExpressions.none],
|
|
778
|
+
default: [SELF],
|
|
779
|
+
scripts: [SELF, NONCE, STRICT_DYNAMIC],
|
|
780
|
+
objects: [NONE],
|
|
781
|
+
baseUri: [SELF],
|
|
782
|
+
frameAncestors: [NONE],
|
|
929
783
|
upgradeInsecureRequests: true
|
|
930
784
|
},
|
|
931
785
|
ruleSets: [
|
|
@@ -934,7 +788,7 @@ async function initProject(cwd, options = {}) {
|
|
|
934
788
|
purpose: "Images used by the application",
|
|
935
789
|
owner: "TODO: assign owner",
|
|
936
790
|
reviewBy,
|
|
937
|
-
rules: { images: [
|
|
791
|
+
rules: { images: [SELF, "data:", "blob:"] }
|
|
938
792
|
},
|
|
939
793
|
...apiOrigins.length ? [
|
|
940
794
|
{
|
|
@@ -947,34 +801,31 @@ async function initProject(cwd, options = {}) {
|
|
|
947
801
|
] : []
|
|
948
802
|
]
|
|
949
803
|
});
|
|
950
|
-
const
|
|
951
|
-
const importExtension = language === "typescript" ? "" : ".mjs";
|
|
952
|
-
const apiImport = apiOrigins.length ? `import { appApi } from './rule-sets/app-api${importExtension}';
|
|
804
|
+
const apiImport = apiOrigins.length ? `import { appApi } from './rule-sets/app-api';
|
|
953
805
|
` : "";
|
|
954
806
|
const reporting = options.reportUri ? ` reporting: { uri: ${JSON.stringify(options.reportUri)} },
|
|
955
807
|
` : "";
|
|
956
808
|
const apiTest = apiOrigins.length ? ` expect(policy).toAllow('connect', ${JSON.stringify(apiOrigins[0] + "/")}, { origin: 'https://site.example', redirectCount: 0 });
|
|
957
809
|
` : "";
|
|
958
810
|
const files = {
|
|
959
|
-
|
|
811
|
+
"csp.config.ts": `export { policy as default } from './csp/policy';
|
|
960
812
|
`,
|
|
961
|
-
|
|
962
|
-
import { appAssets } from './rule-sets/app-assets
|
|
813
|
+
"csp/policy.ts": `import { definePolicy, SELF, NONE, NONCE, STRICT_DYNAMIC } from '@jamesbrightman/pretty-csp';
|
|
814
|
+
import { appAssets } from './rule-sets/app-assets';
|
|
963
815
|
${apiImport}
|
|
964
816
|
export const policy = definePolicy({
|
|
965
|
-
|
|
966
|
-
${reporting} base: { default: [sourceExpressions.self], scripts: [sourceExpressions.self, sourceExpressions.nonce, sourceExpressions.strictDynamic], objects: [sourceExpressions.none], baseUri: [sourceExpressions.self], frameAncestors: [sourceExpressions.none], upgradeInsecureRequests: true },
|
|
817
|
+
${reporting} base: { default: [SELF], scripts: [SELF, NONCE, STRICT_DYNAMIC], objects: [NONE], baseUri: [SELF], frameAncestors: [NONE], upgradeInsecureRequests: true },
|
|
967
818
|
ruleSets: [appAssets${apiOrigins.length ? ", appApi" : ""}],
|
|
968
819
|
});
|
|
969
820
|
`,
|
|
970
|
-
|
|
821
|
+
"csp/rule-sets/app-assets.ts": `import { defineRuleSet, SELF } from '@jamesbrightman/pretty-csp';
|
|
971
822
|
|
|
972
|
-
export const appAssets = defineRuleSet({ name: 'App assets', purpose: 'Images used by the application', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { images: [
|
|
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:'] } });
|
|
973
824
|
`,
|
|
974
|
-
|
|
825
|
+
"csp/policy.test.ts": `import { readFile } from 'node:fs/promises';
|
|
975
826
|
import { expect, test } from 'vitest';
|
|
976
|
-
import { cspMatchers
|
|
977
|
-
import { policy } from './policy
|
|
827
|
+
import { cspMatchers } from '@jamesbrightman/pretty-csp/testing';
|
|
828
|
+
import { policy } from './policy';
|
|
978
829
|
|
|
979
830
|
expect.extend(cspMatchers);
|
|
980
831
|
test('blocks untrusted connections and has no high-risk findings', () => {
|
|
@@ -985,12 +836,20 @@ test('matches the reviewed CSP snapshot', async () => {
|
|
|
985
836
|
const snapshot = JSON.parse(await readFile(new URL('../csp.snapshot.json', import.meta.url), 'utf8'));
|
|
986
837
|
expect(policy).toMatchCspSnapshot(snapshot);
|
|
987
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
|
+
}
|
|
988
847
|
`,
|
|
989
848
|
"csp.snapshot.json": `${JSON.stringify(cspSnapshot(policy), null, 2)}
|
|
990
849
|
`
|
|
991
850
|
};
|
|
992
851
|
if (apiOrigins.length)
|
|
993
|
-
files[
|
|
852
|
+
files["csp/rule-sets/app-api.ts"] = `import { defineRuleSet } from '@jamesbrightman/pretty-csp';
|
|
994
853
|
|
|
995
854
|
export const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API connections', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { connect: ${JSON.stringify(apiOrigins)} } });
|
|
996
855
|
`;
|
|
@@ -1027,396 +886,8 @@ export const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API
|
|
|
1027
886
|
return Object.keys(files);
|
|
1028
887
|
}
|
|
1029
888
|
|
|
1030
|
-
// src/cli/import.ts
|
|
1031
|
-
var import_promises2 = require("fs/promises");
|
|
1032
|
-
var import_node_path2 = require("path");
|
|
1033
|
-
var import_tldts = require("tldts");
|
|
1034
|
-
function registrableDomain(source) {
|
|
1035
|
-
const host = /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:\*\.)?([a-z0-9-]+(?:\.[a-z0-9-]+)+)(?=[:/]|$)/i.exec(
|
|
1036
|
-
source
|
|
1037
|
-
)?.[1];
|
|
1038
|
-
if (!host) return void 0;
|
|
1039
|
-
const { domain, isIcann, isPrivate } = (0, import_tldts.parse)(host, {
|
|
1040
|
-
allowPrivateDomains: true
|
|
1041
|
-
});
|
|
1042
|
-
return domain && (isIcann || isPrivate) ? domain.toLowerCase() : void 0;
|
|
1043
|
-
}
|
|
1044
|
-
function importDraftFiles(draft, mode) {
|
|
1045
|
-
const groups = /* @__PURE__ */ new Map();
|
|
1046
|
-
const unassigned = {};
|
|
1047
|
-
for (const [directive, entries] of Object.entries(
|
|
1048
|
-
draft.base?.directives ?? {}
|
|
1049
|
-
)) {
|
|
1050
|
-
rejectCapturedNonces(entries, directive);
|
|
1051
|
-
}
|
|
1052
|
-
for (const ruleSet of draft.ruleSets ?? []) {
|
|
1053
|
-
for (const [directive, entries] of Object.entries(
|
|
1054
|
-
ruleSet.rules.directives ?? {}
|
|
1055
|
-
)) {
|
|
1056
|
-
rejectCapturedNonces(entries, directive);
|
|
1057
|
-
for (const entry of entries) {
|
|
1058
|
-
const domain = registrableDomain(
|
|
1059
|
-
typeof entry === "string" ? entry : entry.source
|
|
1060
|
-
);
|
|
1061
|
-
let directives = unassigned;
|
|
1062
|
-
if (domain) {
|
|
1063
|
-
directives = groups.get(domain) ?? {};
|
|
1064
|
-
groups.set(domain, directives);
|
|
1065
|
-
}
|
|
1066
|
-
(directives[directive] ??= []).push(entry);
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
const files = /* @__PURE__ */ new Map();
|
|
1071
|
-
const imports = [];
|
|
1072
|
-
const names = [];
|
|
1073
|
-
const addRuleSet = (filename, ruleSet) => {
|
|
1074
|
-
const path = `rule-sets/${filename}.mjs`;
|
|
1075
|
-
const name = `ruleSet${names.length + 1}`;
|
|
1076
|
-
files.set(
|
|
1077
|
-
path,
|
|
1078
|
-
`import { defineRuleSet } from '@jamesbrightman/pretty-csp';
|
|
1079
|
-
|
|
1080
|
-
export default defineRuleSet(${JSON.stringify(ruleSet, null, 2)});
|
|
1081
|
-
`
|
|
1082
|
-
);
|
|
1083
|
-
imports.push(`import ${name} from './${path}';`);
|
|
1084
|
-
names.push(name);
|
|
1085
|
-
};
|
|
1086
|
-
const sortedGroups = Array.from(groups).sort(
|
|
1087
|
-
([first], [second]) => first.localeCompare(second, "en")
|
|
1088
|
-
);
|
|
1089
|
-
for (const [domain, directives] of sortedGroups) {
|
|
1090
|
-
addRuleSet(`domain-${domain}`, {
|
|
1091
|
-
name: domain,
|
|
1092
|
-
purpose: "Imported domain group. Confirm purpose and owner before use.",
|
|
1093
|
-
rules: { directives }
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1096
|
-
if (Object.keys(unassigned).length) {
|
|
1097
|
-
addRuleSet("unassigned", {
|
|
1098
|
-
name: "Unassigned sources",
|
|
1099
|
-
purpose: "Imported sources that need manual grouping and review.",
|
|
1100
|
-
rules: { directives: unassigned }
|
|
1101
|
-
});
|
|
1102
|
-
}
|
|
1103
|
-
files.set(
|
|
1104
|
-
"csp.config.mjs",
|
|
1105
|
-
[
|
|
1106
|
-
"import { definePolicy } from '@jamesbrightman/pretty-csp';",
|
|
1107
|
-
...imports,
|
|
1108
|
-
"",
|
|
1109
|
-
"// Review this draft before using it in an application.",
|
|
1110
|
-
"export default definePolicy({",
|
|
1111
|
-
` mode: ${JSON.stringify(mode)},`,
|
|
1112
|
-
` base: ${JSON.stringify(draft.base ?? {}, null, 2).replace(/\n/g, "\n ")},`,
|
|
1113
|
-
` ruleSets: [${names.join(", ")}],`,
|
|
1114
|
-
"});",
|
|
1115
|
-
""
|
|
1116
|
-
].join("\n")
|
|
1117
|
-
);
|
|
1118
|
-
return files;
|
|
1119
|
-
}
|
|
1120
|
-
function rejectCapturedNonces(entries, directive) {
|
|
1121
|
-
if (entries.some(
|
|
1122
|
-
(entry) => /^'nonce-/i.test(typeof entry === "string" ? entry : entry.source)
|
|
1123
|
-
)) {
|
|
1124
|
-
throw new Error(
|
|
1125
|
-
`Directive ${directive} contains a captured nonce. Migrate it separately using a fresh nonce per response.`
|
|
1126
|
-
);
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
async function writeImportDraft(output, files) {
|
|
1130
|
-
try {
|
|
1131
|
-
await (0, import_promises2.mkdir)(output);
|
|
1132
|
-
} catch (error) {
|
|
1133
|
-
if (error.code === "EEXIST")
|
|
1134
|
-
throw new Error(
|
|
1135
|
-
`Import output already exists: ${output}. Choose a new directory.`
|
|
1136
|
-
);
|
|
1137
|
-
throw error;
|
|
1138
|
-
}
|
|
1139
|
-
const createdFiles = [];
|
|
1140
|
-
let createdRuleSets = false;
|
|
1141
|
-
try {
|
|
1142
|
-
if (files.size > 1) {
|
|
1143
|
-
await (0, import_promises2.mkdir)((0, import_node_path2.join)(output, "rule-sets"));
|
|
1144
|
-
createdRuleSets = true;
|
|
1145
|
-
}
|
|
1146
|
-
for (const [name, content] of files) {
|
|
1147
|
-
const path = (0, import_node_path2.join)(output, name);
|
|
1148
|
-
const file = await (0, import_promises2.open)(path, "wx");
|
|
1149
|
-
createdFiles.push(path);
|
|
1150
|
-
try {
|
|
1151
|
-
await file.writeFile(content, "utf8");
|
|
1152
|
-
} finally {
|
|
1153
|
-
await file.close();
|
|
1154
|
-
}
|
|
1155
|
-
}
|
|
1156
|
-
} catch (error) {
|
|
1157
|
-
try {
|
|
1158
|
-
for (const path of createdFiles) await (0, import_promises2.unlink)(path);
|
|
1159
|
-
if (createdRuleSets) await (0, import_promises2.rmdir)((0, import_node_path2.join)(output, "rule-sets"));
|
|
1160
|
-
await (0, import_promises2.rmdir)(output);
|
|
1161
|
-
} catch {
|
|
1162
|
-
throw new Error(
|
|
1163
|
-
`Import failed and may have left partial files in ${output}`,
|
|
1164
|
-
{ cause: error }
|
|
1165
|
-
);
|
|
1166
|
-
}
|
|
1167
|
-
throw error;
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
// src/cli/diff.ts
|
|
1172
|
-
var import_node_child_process = require("child_process");
|
|
1173
|
-
var import_node_util = require("util");
|
|
1174
|
-
var import_zod3 = require("zod");
|
|
1175
|
-
|
|
1176
|
-
// src/diff.ts
|
|
1177
|
-
function diffPolicies(before, after) {
|
|
1178
|
-
const key = (row) => JSON.stringify([
|
|
1179
|
-
row.directive,
|
|
1180
|
-
row.source,
|
|
1181
|
-
row.ruleSet,
|
|
1182
|
-
row.reason ?? null
|
|
1183
|
-
]);
|
|
1184
|
-
const oldRows = new Map(before.explain().map((row) => [key(row), row]));
|
|
1185
|
-
const newRows = new Map(after.explain().map((row) => [key(row), row]));
|
|
1186
|
-
const changes = [];
|
|
1187
|
-
for (const [id, row] of oldRows)
|
|
1188
|
-
if (!newRows.has(id))
|
|
1189
|
-
changes.push({
|
|
1190
|
-
directive: row.directive,
|
|
1191
|
-
source: row.source,
|
|
1192
|
-
ruleSet: row.ruleSet,
|
|
1193
|
-
change: "removed",
|
|
1194
|
-
...row.reason ? { detail: row.reason } : {}
|
|
1195
|
-
});
|
|
1196
|
-
for (const [id, row] of newRows)
|
|
1197
|
-
if (!oldRows.has(id))
|
|
1198
|
-
changes.push({
|
|
1199
|
-
directive: row.directive,
|
|
1200
|
-
source: row.source,
|
|
1201
|
-
ruleSet: row.ruleSet,
|
|
1202
|
-
change: "added",
|
|
1203
|
-
...row.reason ? { detail: row.reason } : {}
|
|
1204
|
-
});
|
|
1205
|
-
const beforeObj = before.toObject(), afterObj = after.toObject();
|
|
1206
|
-
for (const directive of /* @__PURE__ */ new Set([
|
|
1207
|
-
...Object.keys(beforeObj),
|
|
1208
|
-
...Object.keys(afterObj)
|
|
1209
|
-
])) {
|
|
1210
|
-
if (JSON.stringify(beforeObj[directive]) !== JSON.stringify(afterObj[directive]) && !changes.some((c) => c.directive === directive))
|
|
1211
|
-
changes.push({
|
|
1212
|
-
directive,
|
|
1213
|
-
source: "",
|
|
1214
|
-
ruleSet: "base",
|
|
1215
|
-
change: "modified",
|
|
1216
|
-
detail: "Directive value changed"
|
|
1217
|
-
});
|
|
1218
|
-
}
|
|
1219
|
-
if (before.config.mode !== after.config.mode)
|
|
1220
|
-
changes.push({
|
|
1221
|
-
directive: "(mode)",
|
|
1222
|
-
source: "",
|
|
1223
|
-
ruleSet: "base",
|
|
1224
|
-
change: "modified",
|
|
1225
|
-
detail: `${before.config.mode} \u2192 ${after.config.mode}`
|
|
1226
|
-
});
|
|
1227
|
-
changes.sort(
|
|
1228
|
-
(a, b) => a.directive.localeCompare(b.directive) || a.source.localeCompare(b.source) || a.ruleSet.localeCompare(b.ruleSet) || a.change.localeCompare(b.change)
|
|
1229
|
-
);
|
|
1230
|
-
const headersChanged = JSON.stringify(beforeObj) !== JSON.stringify(afterObj) || before.config.mode !== after.config.mode;
|
|
1231
|
-
const dangerous = changes.some(
|
|
1232
|
-
(change) => change.change === "added" && !(beforeObj[change.directive] ?? []).includes(change.source) && /^(?:\*|https?:|data:|'unsafe-(?:inline|eval|hashes)')$/.test(
|
|
1233
|
-
change.source
|
|
1234
|
-
)
|
|
1235
|
-
);
|
|
1236
|
-
return {
|
|
1237
|
-
changes,
|
|
1238
|
-
risk: dangerous ? "increased" : headersChanged ? "unknown" : "unchanged"
|
|
1239
|
-
};
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
// src/cli/diff.ts
|
|
1243
|
-
var snapshotSchema = import_zod3.z.object({
|
|
1244
|
-
schemaVersion: import_zod3.z.literal(1),
|
|
1245
|
-
mode: import_zod3.z.enum(["enforce", "report-only"]),
|
|
1246
|
-
directives: import_zod3.z.record(
|
|
1247
|
-
import_zod3.z.string().regex(/^[a-z][a-z0-9-]*$/),
|
|
1248
|
-
import_zod3.z.array(import_zod3.z.string())
|
|
1249
|
-
),
|
|
1250
|
-
contributors: import_zod3.z.array(
|
|
1251
|
-
import_zod3.z.object({
|
|
1252
|
-
directive: import_zod3.z.string(),
|
|
1253
|
-
source: import_zod3.z.string(),
|
|
1254
|
-
ruleSet: import_zod3.z.string(),
|
|
1255
|
-
reason: import_zod3.z.string().optional()
|
|
1256
|
-
}).strict()
|
|
1257
|
-
)
|
|
1258
|
-
}).strict();
|
|
1259
|
-
async function readGitSnapshot(ref, cwd) {
|
|
1260
|
-
if (!/^[a-zA-Z0-9][a-zA-Z0-9._/~^-]*$/.test(ref))
|
|
1261
|
-
throw new Error("Invalid Git ref");
|
|
1262
|
-
const exec = (0, import_node_util.promisify)(import_node_child_process.execFile);
|
|
1263
|
-
try {
|
|
1264
|
-
const { stdout } = await exec(
|
|
1265
|
-
"git",
|
|
1266
|
-
["show", "--no-ext-diff", "--no-textconv", `${ref}:csp.snapshot.json`],
|
|
1267
|
-
{ cwd, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" }
|
|
1268
|
-
);
|
|
1269
|
-
return stdout;
|
|
1270
|
-
} catch {
|
|
1271
|
-
throw new Error(
|
|
1272
|
-
"Could not read csp.snapshot.json at the Git ref; commit a version 1 snapshot at the repository root."
|
|
1273
|
-
);
|
|
1274
|
-
}
|
|
1275
|
-
}
|
|
1276
|
-
function diffSnapshot(json, current) {
|
|
1277
|
-
let data;
|
|
1278
|
-
try {
|
|
1279
|
-
data = JSON.parse(json);
|
|
1280
|
-
} catch {
|
|
1281
|
-
throw new Error("Invalid snapshot JSON");
|
|
1282
|
-
}
|
|
1283
|
-
const parsed = snapshotSchema.safeParse(data);
|
|
1284
|
-
if (!parsed.success)
|
|
1285
|
-
throw new Error("Invalid or unsupported CSP snapshot format");
|
|
1286
|
-
const snapshot = parsed.data;
|
|
1287
|
-
for (const row of snapshot.contributors) {
|
|
1288
|
-
if (!snapshot.directives[row.directive]?.includes(row.source))
|
|
1289
|
-
throw new Error("Snapshot contributor does not match a directive source");
|
|
1290
|
-
}
|
|
1291
|
-
for (const [directive, sources] of Object.entries(snapshot.directives)) {
|
|
1292
|
-
if (directive === "report-uri" || directive === "report-to") continue;
|
|
1293
|
-
for (const source of sources) {
|
|
1294
|
-
if (!snapshot.contributors.some(
|
|
1295
|
-
(row) => row.directive === directive && row.source === source
|
|
1296
|
-
))
|
|
1297
|
-
throw new Error("Snapshot source has no contributor");
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
const previous = {
|
|
1301
|
-
config: { mode: snapshot.mode },
|
|
1302
|
-
toObject: () => snapshot.directives,
|
|
1303
|
-
explain: () => snapshot.contributors
|
|
1304
|
-
};
|
|
1305
|
-
return diffPolicies(previous, current);
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
// src/importer/index.ts
|
|
1309
|
-
function importHeader(header) {
|
|
1310
|
-
if (/[\x00-\x08\x0a-\x1f\x7f,]/.test(header))
|
|
1311
|
-
throw new Error(
|
|
1312
|
-
"Header contains a control character or multiple policies; import one policy at a time"
|
|
1313
|
-
);
|
|
1314
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1315
|
-
const warnings = [];
|
|
1316
|
-
const directives = [];
|
|
1317
|
-
for (const segment of header.split(";")) {
|
|
1318
|
-
const trimmed = segment.trim();
|
|
1319
|
-
if (!trimmed) continue;
|
|
1320
|
-
const [rawName, ...values] = trimmed.split(/[ \t]+/);
|
|
1321
|
-
if (!rawName || !/^[a-zA-Z][a-zA-Z0-9-]*$/.test(rawName))
|
|
1322
|
-
throw new Error(`Invalid directive name: ${rawName ?? ""}`);
|
|
1323
|
-
const name = rawName.toLowerCase();
|
|
1324
|
-
const ignored = seen.has(name);
|
|
1325
|
-
if (ignored)
|
|
1326
|
-
warnings.push(`Duplicate ${name} is ignored by CSP; retained for review`);
|
|
1327
|
-
seen.add(name);
|
|
1328
|
-
directives.push({ name, values, ignored });
|
|
1329
|
-
}
|
|
1330
|
-
return { directives, warnings };
|
|
1331
|
-
}
|
|
1332
|
-
function importedPolicyToDraft(policy) {
|
|
1333
|
-
if (policy.directives.some((directive) => directive.ignored))
|
|
1334
|
-
throw new Error(
|
|
1335
|
-
"Duplicate directives require manual review before conversion"
|
|
1336
|
-
);
|
|
1337
|
-
const base = {};
|
|
1338
|
-
const baseRaw = {};
|
|
1339
|
-
const ruleRaw = {};
|
|
1340
|
-
const baseOnly2 = /* @__PURE__ */ new Set([
|
|
1341
|
-
"default-src",
|
|
1342
|
-
"object-src",
|
|
1343
|
-
"base-uri",
|
|
1344
|
-
"frame-ancestors"
|
|
1345
|
-
]);
|
|
1346
|
-
const supported = /* @__PURE__ */ new Set([
|
|
1347
|
-
"default-src",
|
|
1348
|
-
"object-src",
|
|
1349
|
-
"base-uri",
|
|
1350
|
-
"frame-ancestors",
|
|
1351
|
-
"script-src",
|
|
1352
|
-
"script-src-elem",
|
|
1353
|
-
"script-src-attr",
|
|
1354
|
-
"style-src",
|
|
1355
|
-
"style-src-elem",
|
|
1356
|
-
"style-src-attr",
|
|
1357
|
-
"img-src",
|
|
1358
|
-
"connect-src",
|
|
1359
|
-
"font-src",
|
|
1360
|
-
"frame-src",
|
|
1361
|
-
"child-src",
|
|
1362
|
-
"form-action",
|
|
1363
|
-
"media-src",
|
|
1364
|
-
"worker-src",
|
|
1365
|
-
"manifest-src"
|
|
1366
|
-
]);
|
|
1367
|
-
const risky2 = /* @__PURE__ */ new Set([
|
|
1368
|
-
"'unsafe-inline'",
|
|
1369
|
-
"'unsafe-eval'",
|
|
1370
|
-
"'unsafe-hashes'"
|
|
1371
|
-
]);
|
|
1372
|
-
for (const directive of policy.directives) {
|
|
1373
|
-
if (directive.name === "upgrade-insecure-requests") {
|
|
1374
|
-
if (directive.values.length)
|
|
1375
|
-
throw new Error(
|
|
1376
|
-
"upgrade-insecure-requests with values requires manual review"
|
|
1377
|
-
);
|
|
1378
|
-
base.upgradeInsecureRequests = true;
|
|
1379
|
-
continue;
|
|
1380
|
-
}
|
|
1381
|
-
if (!supported.has(directive.name) || directive.values.some(
|
|
1382
|
-
(value) => value.toLowerCase() === "'nonce-{nonce}'"
|
|
1383
|
-
)) {
|
|
1384
|
-
throw new Error(
|
|
1385
|
-
`Directive ${directive.name} contains unsupported syntax; review manually`
|
|
1386
|
-
);
|
|
1387
|
-
}
|
|
1388
|
-
if (directive.values.length === 0 || ["report-uri", "report-to", "sandbox"].includes(directive.name)) {
|
|
1389
|
-
throw new Error(
|
|
1390
|
-
`Directive ${directive.name} requires manual review before conversion`
|
|
1391
|
-
);
|
|
1392
|
-
}
|
|
1393
|
-
const entries = directive.values.map(
|
|
1394
|
-
(source) => risky2.has(source.toLowerCase()) ? { source, reason: "Imported legacy policy; review required" } : source
|
|
1395
|
-
);
|
|
1396
|
-
(baseOnly2.has(directive.name) ? baseRaw : ruleRaw)[directive.name] = entries;
|
|
1397
|
-
}
|
|
1398
|
-
if (Object.keys(baseRaw).length) base.directives = baseRaw;
|
|
1399
|
-
const draft = {
|
|
1400
|
-
base,
|
|
1401
|
-
ruleSets: Object.keys(ruleRaw).length ? [
|
|
1402
|
-
{
|
|
1403
|
-
name: "Imported policy",
|
|
1404
|
-
purpose: "Imported sources awaiting ownership review",
|
|
1405
|
-
rules: { directives: ruleRaw }
|
|
1406
|
-
}
|
|
1407
|
-
] : []
|
|
1408
|
-
};
|
|
1409
|
-
const result = policyConfigSchema.safeParse(draft);
|
|
1410
|
-
if (!result.success)
|
|
1411
|
-
throw new Error(
|
|
1412
|
-
`Imported policy contains unsupported sources: ${result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`
|
|
1413
|
-
);
|
|
1414
|
-
return draft;
|
|
1415
|
-
}
|
|
1416
|
-
|
|
1417
889
|
// src/cli/index.ts
|
|
1418
|
-
var help = "Usage: pretty-csp <init|print|explain|audit|snapshot
|
|
1419
|
-
var importHelp = "Usage: pretty-csp import <header> | --file <header-file> [--output <new-directory> [--dry-run] [--mode <report-only|enforce>]]";
|
|
890
|
+
var help = "Usage: pretty-csp <init|print|explain|audit|snapshot> [--config path] [options]";
|
|
1420
891
|
var severities = {
|
|
1421
892
|
info: 0,
|
|
1422
893
|
low: 1,
|
|
@@ -1426,7 +897,6 @@ var severities = {
|
|
|
1426
897
|
function argsFor(args) {
|
|
1427
898
|
const [command = "help", ...rest] = args;
|
|
1428
899
|
const options = {};
|
|
1429
|
-
let positional;
|
|
1430
900
|
const flags = /* @__PURE__ */ new Set([
|
|
1431
901
|
"pretty",
|
|
1432
902
|
"update",
|
|
@@ -1442,21 +912,12 @@ function argsFor(args) {
|
|
|
1442
912
|
"rule-set",
|
|
1443
913
|
"fail-on",
|
|
1444
914
|
"file",
|
|
1445
|
-
"output",
|
|
1446
|
-
"base",
|
|
1447
|
-
"language",
|
|
1448
915
|
"api-origins",
|
|
1449
|
-
"report-uri"
|
|
1450
|
-
"mode"
|
|
916
|
+
"report-uri"
|
|
1451
917
|
]);
|
|
1452
918
|
for (let i = 0; i < rest.length; i++) {
|
|
1453
919
|
const arg = rest[i];
|
|
1454
|
-
if (!arg.startsWith("--")) {
|
|
1455
|
-
if (!["import", "check-reports"].includes(command) || positional !== void 0)
|
|
1456
|
-
throw new Error(`Unexpected argument: ${arg}`);
|
|
1457
|
-
positional = arg;
|
|
1458
|
-
continue;
|
|
1459
|
-
}
|
|
920
|
+
if (!arg.startsWith("--")) throw new Error(`Unexpected argument: ${arg}`);
|
|
1460
921
|
const key = arg.slice(2);
|
|
1461
922
|
if (flags.has(key)) options[key] = true;
|
|
1462
923
|
else if (values.has(key)) {
|
|
@@ -1468,8 +929,7 @@ function argsFor(args) {
|
|
|
1468
929
|
}
|
|
1469
930
|
return {
|
|
1470
931
|
command,
|
|
1471
|
-
options
|
|
1472
|
-
...positional === void 0 ? {} : { positional }
|
|
932
|
+
options
|
|
1473
933
|
};
|
|
1474
934
|
}
|
|
1475
935
|
function option(options, name) {
|
|
@@ -1481,7 +941,7 @@ function isPolicy(value) {
|
|
|
1481
941
|
) && "config" in value;
|
|
1482
942
|
}
|
|
1483
943
|
async function loadConfigFile(path) {
|
|
1484
|
-
if ([".ts", ".mts", ".cts"].includes((0,
|
|
944
|
+
if ([".ts", ".mts", ".cts"].includes((0, import_node_path2.extname)(path).toLowerCase())) {
|
|
1485
945
|
const jiti = (0, import_jiti.createJiti)(path, { moduleCache: false, fsCache: false });
|
|
1486
946
|
return await jiti.import(path);
|
|
1487
947
|
}
|
|
@@ -1489,90 +949,32 @@ async function loadConfigFile(path) {
|
|
|
1489
949
|
}
|
|
1490
950
|
async function runCli(args, io, cwd = process.cwd(), loadConfig = loadConfigFile) {
|
|
1491
951
|
try {
|
|
1492
|
-
const { command, options
|
|
1493
|
-
if (command === "help" || options.help) {
|
|
1494
|
-
io.out(
|
|
952
|
+
const { command, options } = argsFor(args);
|
|
953
|
+
if (command === "help" || command === "--help" || options.help) {
|
|
954
|
+
io.out(help);
|
|
1495
955
|
return 0;
|
|
1496
956
|
}
|
|
1497
|
-
if (![
|
|
1498
|
-
"init",
|
|
1499
|
-
"print",
|
|
1500
|
-
"explain",
|
|
1501
|
-
"audit",
|
|
1502
|
-
"snapshot",
|
|
1503
|
-
"diff",
|
|
1504
|
-
"import",
|
|
1505
|
-
"check-reports"
|
|
1506
|
-
].includes(command))
|
|
957
|
+
if (!["init", "print", "explain", "audit", "snapshot"].includes(command))
|
|
1507
958
|
throw new Error(`Unsupported command: ${command}. ${help}`);
|
|
1508
959
|
if (command === "init") {
|
|
1509
960
|
if (!options.yes)
|
|
1510
961
|
throw new Error(
|
|
1511
|
-
"Use init --yes and optional --
|
|
962
|
+
"Use init --yes and optional --api-origins and --report-uri flags."
|
|
1512
963
|
);
|
|
1513
964
|
const files = await initProject(cwd, {
|
|
1514
965
|
dryRun: Boolean(options["dry-run"]),
|
|
1515
966
|
force: Boolean(options.force),
|
|
1516
|
-
language: option(options, "language"),
|
|
1517
|
-
mode: option(options, "mode"),
|
|
1518
967
|
apiOrigins: option(options, "api-origins")?.split(",").map((origin) => origin.trim()),
|
|
1519
968
|
reportUri: option(options, "report-uri")
|
|
1520
969
|
});
|
|
1521
970
|
io.out(
|
|
1522
971
|
`${options["dry-run"] ? "Would write" : "Wrote"}:
|
|
1523
972
|
${files.join("\n")}
|
|
1524
|
-
Install @jamesbrightman/pretty-csp and Vitest, then configure your server to set
|
|
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.`
|
|
1525
974
|
);
|
|
1526
975
|
return 0;
|
|
1527
976
|
}
|
|
1528
|
-
|
|
1529
|
-
const headerFile = option(options, "file");
|
|
1530
|
-
const output = option(options, "output");
|
|
1531
|
-
if (!positional && !headerFile || positional && headerFile)
|
|
1532
|
-
throw new Error(
|
|
1533
|
-
"import requires a header string or --file, but not both"
|
|
1534
|
-
);
|
|
1535
|
-
if (!output && (options["dry-run"] || options.mode))
|
|
1536
|
-
throw new Error("--dry-run and --mode require --output for import");
|
|
1537
|
-
if (options.force)
|
|
1538
|
-
throw new Error(
|
|
1539
|
-
"Import requires a new output directory. --force is not supported."
|
|
1540
|
-
);
|
|
1541
|
-
const header = headerFile ? (await (0, import_promises3.readFile)((0, import_node_path3.resolve)(cwd, headerFile), "utf8")).replace(
|
|
1542
|
-
/\r?\n$/,
|
|
1543
|
-
""
|
|
1544
|
-
) : positional;
|
|
1545
|
-
const parsed = importHeader(header);
|
|
1546
|
-
const draft = importedPolicyToDraft(parsed);
|
|
1547
|
-
if (output) {
|
|
1548
|
-
const mode = option(options, "mode") ?? "report-only";
|
|
1549
|
-
if (mode !== "enforce" && mode !== "report-only")
|
|
1550
|
-
throw new Error("--mode must be enforce or report-only");
|
|
1551
|
-
const files = importDraftFiles(draft, mode);
|
|
1552
|
-
const destination = (0, import_node_path3.resolve)(cwd, output);
|
|
1553
|
-
if (!options["dry-run"]) await writeImportDraft(destination, files);
|
|
1554
|
-
io.out(
|
|
1555
|
-
`${options["dry-run"] ? "Would write to" : "Wrote to"} ${destination}:
|
|
1556
|
-
${Array.from(files.keys()).join("\n")}
|
|
1557
|
-
Review the draft and assign owners before use.`
|
|
1558
|
-
);
|
|
1559
|
-
return 0;
|
|
1560
|
-
}
|
|
1561
|
-
io.out(
|
|
1562
|
-
JSON.stringify(
|
|
1563
|
-
{
|
|
1564
|
-
draft,
|
|
1565
|
-
warnings: parsed.warnings,
|
|
1566
|
-
note: "Review the draft before saving; no files were written."
|
|
1567
|
-
},
|
|
1568
|
-
null,
|
|
1569
|
-
2
|
|
1570
|
-
)
|
|
1571
|
-
);
|
|
1572
|
-
return 0;
|
|
1573
|
-
}
|
|
1574
|
-
const defaultConfig = (0, import_node_fs.existsSync)((0, import_node_path3.resolve)(cwd, "csp.config.ts")) ? "csp.config.ts" : "csp.config.mjs";
|
|
1575
|
-
const path = (0, import_node_path3.resolve)(cwd, option(options, "config") ?? defaultConfig);
|
|
977
|
+
const path = (0, import_node_path2.resolve)(cwd, option(options, "config") ?? "csp.config.ts");
|
|
1576
978
|
const module2 = await loadConfig(path);
|
|
1577
979
|
const candidate = module2.default ?? module2.policy;
|
|
1578
980
|
const policy = candidate && typeof candidate === "object" && "policy" in candidate ? candidate.policy : candidate;
|
|
@@ -1580,26 +982,6 @@ Review the draft and assign owners before use.`
|
|
|
1580
982
|
throw new Error(
|
|
1581
983
|
"Config must export a Policy as default, as policy, or as default.policy"
|
|
1582
984
|
);
|
|
1583
|
-
if (command === "diff") {
|
|
1584
|
-
const ref = option(options, "base");
|
|
1585
|
-
if (!ref)
|
|
1586
|
-
throw new Error(
|
|
1587
|
-
"diff requires --base <git-ref> and a committed csp.snapshot.json at the repository root"
|
|
1588
|
-
);
|
|
1589
|
-
const result = diffSnapshot(await readGitSnapshot(ref, cwd), policy);
|
|
1590
|
-
io.out(JSON.stringify(result, null, 2));
|
|
1591
|
-
return 0;
|
|
1592
|
-
}
|
|
1593
|
-
if (command === "check-reports") {
|
|
1594
|
-
if (!positional) throw new Error("check-reports requires a JSON file");
|
|
1595
|
-
const contents = await (0, import_promises3.readFile)((0, import_node_path3.resolve)(cwd, positional), "utf8");
|
|
1596
|
-
const results = replayReports(
|
|
1597
|
-
policy.toObject(),
|
|
1598
|
-
parseViolationReports(contents)
|
|
1599
|
-
);
|
|
1600
|
-
io.out(JSON.stringify(results, null, 2));
|
|
1601
|
-
return results.some(({ result }) => result.status !== "allowed") ? 1 : 0;
|
|
1602
|
-
}
|
|
1603
985
|
if (command === "print") {
|
|
1604
986
|
io.out(
|
|
1605
987
|
policy.toHeader({
|
|
@@ -1627,17 +1009,17 @@ Review the draft and assign owners before use.`
|
|
|
1627
1009
|
(finding) => severities[finding.severity] >= severities[threshold]
|
|
1628
1010
|
) ? 1 : 0;
|
|
1629
1011
|
}
|
|
1630
|
-
const file = (0,
|
|
1012
|
+
const file = (0, import_node_path2.resolve)(cwd, option(options, "file") ?? "csp.snapshot.json");
|
|
1631
1013
|
const expected = `${JSON.stringify(cspSnapshot(policy), null, 2)}
|
|
1632
1014
|
`;
|
|
1633
1015
|
if (options.update) {
|
|
1634
|
-
await (0,
|
|
1016
|
+
await (0, import_promises2.writeFile)(file, expected, "utf8");
|
|
1635
1017
|
io.out(`Updated ${file}`);
|
|
1636
1018
|
return 0;
|
|
1637
1019
|
}
|
|
1638
1020
|
let actual;
|
|
1639
1021
|
try {
|
|
1640
|
-
actual = await (0,
|
|
1022
|
+
actual = await (0, import_promises2.readFile)(file, "utf8");
|
|
1641
1023
|
} catch {
|
|
1642
1024
|
throw new Error(
|
|
1643
1025
|
`Snapshot not found: ${file}. Run snapshot --update to create it.`
|