@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.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/index.ts","../src/audit/index.ts","../src/testing/index.ts","../src/cli/init.ts","../src/matching/index.ts","../src/core.ts","../src/keywords.ts","../src/schemas.ts","../src/cli/bin.ts"],"sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { resolve, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { createJiti } from 'jiti';\nimport { audit } from '../audit';\nimport type { Severity } from '../audit';\nimport type { Policy } from '../core';\nimport { cspSnapshot } from '../testing';\nimport { initProject } from './init';\n\nexport interface CliIo {\n out(message: string): void;\n error(message: string): void;\n}\nconst help =\n 'Usage: pretty-csp <init|print|explain|audit|snapshot> [--config path] [options]';\nconst severities: Record<Severity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n};\nfunction argsFor(args: string[]): {\n command: string;\n options: Record<string, string | boolean>;\n} {\n const [command = 'help', ...rest] = args;\n const options: Record<string, string | boolean> = {};\n const flags = new Set([\n 'pretty',\n 'update',\n 'help',\n 'yes',\n 'dry-run',\n 'force',\n ]);\n const values = new Set([\n 'config',\n 'nonce',\n 'directive',\n 'rule-set',\n 'fail-on',\n 'file',\n 'api-origins',\n 'report-uri',\n ]);\n for (let i = 0; i < rest.length; i++) {\n const arg = rest[i]!;\n if (!arg.startsWith('--')) throw new Error(`Unexpected argument: ${arg}`);\n const key = arg.slice(2);\n if (flags.has(key)) options[key] = true;\n else if (values.has(key)) {\n const value = rest[++i];\n if (!value || value.startsWith('--'))\n throw new Error(`--${key} requires a value`);\n options[key] = value;\n } else throw new Error(`Unknown option --${key}`);\n }\n return {\n command,\n options,\n };\n}\nfunction option(\n options: Record<string, string | boolean>,\n name: string,\n): string | undefined {\n return typeof options[name] === 'string'\n ? (options[name] as string)\n : undefined;\n}\nfunction isPolicy(value: unknown): value is Policy {\n return (\n !!value &&\n typeof value === 'object' &&\n ['toHeader', 'toObject', 'explain', 'allows'].every(\n (key) =>\n typeof (value as unknown as Record<string, unknown>)[key] ===\n 'function',\n ) &&\n 'config' in value\n );\n}\n/** Load only trusted project configuration: imports execute with the user's permissions. */\nexport async function loadConfigFile(\n path: string,\n): Promise<{ default?: unknown; policy?: unknown }> {\n if (['.ts', '.mts', '.cts'].includes(extname(path).toLowerCase())) {\n const jiti = createJiti(path, { moduleCache: false, fsCache: false });\n return (await jiti.import(path)) as { default?: unknown; policy?: unknown };\n }\n return (await import(pathToFileURL(path).href)) as {\n default?: unknown;\n policy?: unknown;\n };\n}\n/** Runs a command; config is executable code and must come from a trusted project. */\nexport async function runCli(\n args: string[],\n io: CliIo,\n cwd = process.cwd(),\n loadConfig: (\n path: string,\n ) => Promise<{ default?: unknown; policy?: unknown }> = loadConfigFile,\n): Promise<number> {\n try {\n const { command, options } = argsFor(args);\n if (command === 'help' || command === '--help' || options.help) {\n io.out(help);\n return 0;\n }\n if (!['init', 'print', 'explain', 'audit', 'snapshot'].includes(command))\n throw new Error(`Unsupported command: ${command}. ${help}`);\n if (command === 'init') {\n if (!options.yes)\n throw new Error(\n 'Use init --yes and optional --api-origins and --report-uri flags.',\n );\n const files = await initProject(cwd, {\n dryRun: Boolean(options['dry-run']),\n force: Boolean(options.force),\n apiOrigins: option(options, 'api-origins')\n ?.split(',')\n .map((origin) => origin.trim()),\n reportUri: option(options, 'report-uri'),\n });\n io.out(\n `${options['dry-run'] ? 'Would write' : 'Wrote'}:\\n${files.join('\\n')}\\nInstall @jamesbrightman/pretty-csp and Vitest, then configure your server to set the Content-Security-Policy response header with policy.toHeader({ nonce }) on each response.`,\n );\n return 0;\n }\n const path = resolve(cwd, option(options, 'config') ?? 'csp.config.ts');\n const module = await loadConfig(path);\n const candidate = module.default ?? module.policy;\n const policy: unknown =\n candidate && typeof candidate === 'object' && 'policy' in candidate\n ? candidate.policy\n : candidate;\n if (!isPolicy(policy))\n throw new Error(\n 'Config must export a Policy as default, as policy, or as default.policy',\n );\n if (command === 'print') {\n io.out(\n policy.toHeader({\n ...(option(options, 'nonce')\n ? { nonce: option(options, 'nonce') }\n : {}),\n pretty: Boolean(options.pretty),\n }),\n );\n return 0;\n }\n if (command === 'explain') {\n const directive = option(options, 'directive'),\n ruleSet = option(options, 'rule-set');\n const rows = policy\n .explain()\n .filter(\n (row) =>\n (!directive || row.directive === directive) &&\n (!ruleSet || row.ruleSet === ruleSet),\n );\n io.out(JSON.stringify(rows, null, 2));\n return 0;\n }\n if (command === 'audit') {\n const threshold = option(options, 'fail-on') ?? 'high';\n if (!Object.hasOwn(severities, threshold))\n throw new Error('--fail-on must be high, medium, low or info');\n const findings = audit(policy);\n io.out(JSON.stringify(findings, null, 2));\n return findings.some(\n (finding) =>\n severities[finding.severity] >= severities[threshold as Severity],\n )\n ? 1\n : 0;\n }\n const file = resolve(cwd, option(options, 'file') ?? 'csp.snapshot.json');\n const expected = `${JSON.stringify(cspSnapshot(policy), null, 2)}\\n`;\n if (options.update) {\n await writeFile(file, expected, 'utf8');\n io.out(`Updated ${file}`);\n return 0;\n }\n let actual: string;\n try {\n actual = await readFile(file, 'utf8');\n } catch {\n throw new Error(\n `Snapshot not found: ${file}. Run snapshot --update to create it.`,\n );\n }\n if (actual !== expected) {\n io.error(\n 'CSP snapshot differs. Review the policy and run snapshot --update.',\n );\n return 1;\n }\n io.out('CSP snapshot matches.');\n return 0;\n } catch (error) {\n io.error(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n","import type { Policy } from '../core';\n\nexport type Severity = 'high' | 'medium' | 'low' | 'info';\nexport interface AuditFinding {\n ruleId: string;\n severity: Severity;\n message: string;\n fix: string;\n directive?: string;\n source?: string;\n ruleSet?: string;\n}\nexport interface AuditRule {\n id: string;\n check(policy: Policy): readonly AuditFinding[];\n}\nexport interface AuditSuppression {\n ruleId: string;\n ruleSet: string;\n reason: string;\n}\nexport interface AuditOptions {\n rules?: readonly AuditRule[];\n suppressions?: readonly AuditSuppression[];\n now?: Date;\n}\n\nconst sourceFindings = (\n policy: Policy,\n directive: string,\n source: string,\n ruleId: string,\n severity: Severity,\n message: string,\n fix: string,\n): AuditFinding[] => {\n const owners = policy\n .explain()\n .filter((row) => row.directive === directive && row.source === source);\n return owners.length\n ? owners.map(({ ruleSet }) => ({\n ruleId,\n severity,\n message,\n fix,\n directive,\n source,\n ruleSet,\n }))\n : [{ ruleId, severity, message, fix, directive, source }];\n};\n\n/** Inspect known dangerous policy patterns. Findings are advisory and do not prove a policy safe. */\nexport function audit(\n policy: Policy,\n options: AuditOptions = {},\n): AuditFinding[] {\n const object = policy.toObject();\n const findings: AuditFinding[] = [];\n const add = (\n id: string,\n severity: Severity,\n message: string,\n fix: string,\n directive?: string,\n ) =>\n findings.push({\n ruleId: id,\n severity,\n message,\n fix,\n ...(directive ? { directive } : {}),\n });\n if (!object['script-src'] && !object['default-src'])\n add(\n 'missing-script-src',\n 'high',\n 'Some script execution is unrestricted.',\n 'Restrict script-src or default-src.',\n 'script-src',\n );\n // script-src-elem falls back to script-src, then default-src. Inspect each explicit list.\n for (const directive of [\n 'script-src',\n 'script-src-elem',\n 'script-src-attr',\n 'default-src',\n ]) {\n const sources = object[directive];\n if (!sources) continue;\n const isFallback =\n directive === 'default-src' && object['script-src'] !== undefined;\n if (isFallback) continue;\n const hasNonceOrHash = sources.some((s) =>\n /^'(nonce-|sha(?:256|384|512)-)/i.test(s),\n );\n for (const source of sources.filter(\n (s) => s.toLowerCase() === \"'unsafe-inline'\" && !hasNonceOrHash,\n ))\n findings.push(\n ...sourceFindings(\n policy,\n directive,\n source,\n 'script-unsafe-inline',\n 'high',\n 'Inline scripts are permitted.',\n 'Use nonces or hashes and remove unsafe-inline.',\n ),\n );\n for (const source of sources.filter(\n (s) => s.toLowerCase() === \"'unsafe-eval'\",\n ))\n findings.push(\n ...sourceFindings(\n policy,\n directive,\n source,\n 'script-unsafe-eval',\n 'high',\n 'Dynamic JavaScript evaluation is permitted.',\n 'Remove unsafe-eval and replace dynamic evaluation.',\n ),\n );\n if (\n directive !== 'script-src-attr' &&\n sources.some((source) => source.toLowerCase() === \"'strict-dynamic'\")\n ) {\n for (const source of sources) {\n if (\n source.toLowerCase() === \"'self'\" ||\n source === '*' ||\n /^[a-z][a-z0-9+.-]*:$/i.test(source) ||\n /^(?:[a-z][a-z0-9+.-]*:\\/\\/)?(?:\\*|[a-z0-9*.-]+)(?::(?:\\*|\\d+))?(?:\\/[^\\s]*)?$/i.test(\n source,\n )\n ) {\n findings.push(\n ...sourceFindings(\n policy,\n directive,\n source,\n 'ignored-by-strict-dynamic',\n 'info',\n 'Modern browsers ignore this source for scripts under strict-dynamic.',\n 'Remove it if legacy browser fallback is not needed.',\n ),\n );\n }\n }\n }\n for (const source of sources)\n if (\n ['*', 'https:', 'http:', 'data:'].includes(source.toLowerCase()) ||\n /^(?:https?:\\/\\/)?\\*(?::(?:\\*|\\d+))?(?:\\/[^\\s]*)?$/i.test(source)\n )\n findings.push(\n ...sourceFindings(\n policy,\n directive,\n source,\n 'script-wildcard',\n 'high',\n 'A broad script source may permit attacker-controlled scripts.',\n 'Restrict script sources and prefer nonces or hashes.',\n ),\n );\n }\n const objects = object['object-src'] ?? object['default-src'];\n if (\n !objects ||\n objects.length !== 1 ||\n objects[0]?.toLowerCase() !== \"'none'\"\n )\n add(\n 'missing-object-src',\n 'high',\n 'Object embedding is not explicitly blocked.',\n \"Set object-src to 'none'.\",\n 'object-src',\n );\n const broad = (sources: string[] | undefined) =>\n !sources ||\n sources.some(\n (source) =>\n source === '*' ||\n /^[a-z][a-z0-9+.-]*:$/i.test(source) ||\n /^(?:https?:\\/\\/)?\\*(?::(?:\\*|\\d+))?(?:\\/[^\\s]*)?$/i.test(source),\n );\n if (broad(object['base-uri']))\n add(\n 'missing-base-uri',\n 'medium',\n 'The document base URL is not sufficiently restricted.',\n \"Set base-uri to 'none' or 'self'.\",\n 'base-uri',\n );\n if (broad(object['frame-ancestors']))\n add(\n 'missing-frame-ancestors',\n 'medium',\n 'Embedding by other sites is not sufficiently restricted.',\n 'Restrict frame-ancestors to trusted origins.',\n 'frame-ancestors',\n );\n // Small advisory subset informed by Google CSP Evaluator; maintain and review this data.\n // https://github.com/google/csp-evaluator/tree/master/allowlist_bypasses\n const knownBypassDomains = [\n 'google.com',\n 'googleapis.com',\n 'googleusercontent.com',\n 'gstatic.com',\n ];\n for (const row of policy.explain()) {\n if (\n ['script-src', 'script-src-elem', 'default-src'].includes(row.directive)\n ) {\n const host = row.source\n .match(/^(?:https?:\\/\\/)?(?:\\*\\.)?([a-z0-9.-]+)/i)?.[1]\n ?.toLowerCase();\n if (\n host &&\n knownBypassDomains.some(\n (domain) => host === domain || host.endsWith(`.${domain}`),\n )\n ) {\n findings.push({\n ruleId: 'bypass-host',\n severity: 'medium',\n directive: row.directive,\n source: row.source,\n ruleSet: row.ruleSet,\n message:\n 'This script host may expose JSONP or script gadgets that weaken host allowlists.',\n fix: 'Review the host for JSONP endpoints and script gadgets; prefer nonce or hash authorization.',\n });\n }\n }\n if (/^http:/i.test(row.source))\n findings.push({\n ruleId: 'insecure-scheme',\n severity: 'medium',\n directive: row.directive,\n source: row.source,\n ruleSet: row.ruleSet,\n message: 'An insecure HTTP source is permitted.',\n fix: 'Use HTTPS where possible.',\n });\n if (\n /^(?:https?:\\/\\/)?\\*\\.[a-z0-9-]+(?::(?:\\*|\\d+))?(?:\\/|$)/i.test(\n row.source,\n ) ||\n /^https?:\\/\\/\\*\\.(?:amazonaws\\.com|azurewebsites\\.net)(?:[/:]|$)/i.test(\n row.source,\n )\n )\n findings.push({\n ruleId: 'broad-wildcard',\n severity: 'medium',\n directive: row.directive,\n source: row.source,\n ruleSet: row.ruleSet,\n message: 'A wildcard covers an unusually broad or shared domain.',\n fix: 'List the specific trusted hosts.',\n });\n }\n if (!object['report-uri'] && !object['report-to'])\n add(\n 'no-reporting',\n 'low',\n 'No reporting destination is configured.',\n 'Configure reporting and its endpoint.',\n );\n const today = (options.now ?? new Date()).toISOString().slice(0, 10);\n for (const set of policy.config.ruleSets.filter((s) => s.enabled)) {\n if (!set.owner)\n findings.push({\n ruleId: 'ruleset-metadata',\n severity: 'low',\n ruleSet: set.name,\n message: 'Rule set has no owner.',\n fix: 'Assign an owner.',\n });\n if (set.reviewBy && set.reviewBy < today)\n findings.push({\n ruleId: 'ruleset-metadata',\n severity: 'low',\n ruleSet: set.name,\n message: 'Rule set review date has passed.',\n fix: 'Review permissions regularly.',\n });\n }\n for (const rule of options.rules ?? []) findings.push(...rule.check(policy));\n for (const suppression of options.suppressions ?? [])\n if (\n !suppression.reason.trim() ||\n !suppression.ruleId ||\n !suppression.ruleSet\n )\n throw new Error(\n 'Audit suppressions require a rule id, rule set and reason',\n );\n return findings.filter(\n (finding) =>\n !(options.suppressions ?? []).some(\n (s) => s.ruleId === finding.ruleId && s.ruleSet === finding.ruleSet,\n ),\n );\n}\n","import { audit } from '../audit';\nimport type { Severity } from '../audit';\nimport type { Policy } from '../core';\nimport type { MatchOptions } from '../matching';\n\n/** Matchers can be registered with either Jest's or Vitest's `expect.extend`. */\nexport const cspMatchers = {\n toAllow(\n policy: Policy,\n directive: string,\n url: string,\n options?: MatchOptions,\n ) {\n const result = policy.allows(directive, url, options);\n if (result.status === 'indeterminate')\n throw new Error(\n `Cannot assert ${directive} ${url}: indeterminate; ${result.reason ?? 'decision is indeterminate'}`,\n );\n return {\n pass: result.status === 'allowed',\n message: () =>\n `Expected ${directive} ${url} ${result.status === 'allowed' ? 'not ' : ''}to be allowed; decision: ${result.status}${result.reason ? ` (${result.reason})` : ''}`,\n };\n },\n toBlock(\n policy: Policy,\n directive: string,\n url: string,\n options?: MatchOptions,\n ) {\n const result = policy.allows(directive, url, options);\n if (result.status === 'indeterminate')\n throw new Error(\n `Cannot assert ${directive} ${url}: indeterminate; ${result.reason ?? 'decision is indeterminate'}`,\n );\n return {\n pass: result.status === 'blocked',\n message: () =>\n `Expected ${directive} ${url} ${result.status === 'blocked' ? 'not ' : ''}to be blocked; decision: ${result.status}${result.reason ? ` (${result.reason})` : ''}`,\n };\n },\n toMatchCspSnapshot(\n this: { equals(actual: unknown, expected: unknown): boolean },\n policy: Policy,\n expected: ReturnType<typeof cspSnapshot>,\n ) {\n const actual = cspSnapshot(policy);\n const pass = this.equals(actual, expected);\n return {\n pass,\n message: () =>\n pass\n ? 'Expected CSP snapshot to differ from the supplied snapshot'\n : 'CSP snapshot differs; review and update the committed snapshot',\n };\n },\n toPassAudit(policy: Policy, options: { maxSeverity?: Severity } = {}) {\n const ranks: Record<Severity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n };\n const threshold = ranks[options.maxSeverity ?? 'low'];\n const failing = audit(policy).filter(\n (finding) => ranks[finding.severity] > threshold,\n );\n return {\n pass: failing.length === 0,\n message: () =>\n failing.length\n ? `Expected CSP audit to have no findings above ${options.maxSeverity ?? 'low'}: ${failing.map((f) => `${f.ruleId} (${f.severity})`).join(', ')}`\n : 'Expected the CSP audit to exceed the permitted severity',\n };\n },\n};\n\n/** Assertion signatures for a test runner's TypeScript module augmentation. */\nexport type CspAssertions<Received = unknown> = {\n [Name in keyof typeof cspMatchers]: (\n ...args: (typeof cspMatchers)[Name] extends (\n policy: Policy,\n ...args: infer Arguments\n ) => unknown\n ? Arguments\n : never\n ) => Received extends Promise<unknown> ? Promise<void> : void;\n};\n\n/** Stable, provenance-aware input for a test runner's built-in snapshot matcher. */\nexport function cspSnapshot(policy: Policy): {\n schemaVersion: 2;\n directives: Record<string, string[]>;\n contributors: ReturnType<Policy['explain']>;\n} {\n return {\n schemaVersion: 2,\n directives: policy.toObject(),\n contributors: policy.explain(),\n };\n}\n","import { lstat, mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { definePolicy } from '../core';\nimport { SELF, NONE, NONCE, STRICT_DYNAMIC } from '../keywords';\nimport { cspSnapshot } from '../testing';\n\nexport interface InitOptions {\n force?: boolean;\n dryRun?: boolean;\n now?: Date;\n apiOrigins?: readonly string[];\n reportUri?: string;\n}\n/** Create a small TypeScript starter. Existing paths require force and symlinks are rejected. */\nexport async function initProject(\n cwd: string,\n options: InitOptions = {},\n): Promise<string[]> {\n const apiOrigins = [...new Set(options.apiOrigins ?? [])];\n for (const origin of apiOrigins) {\n let parsed: URL;\n try {\n parsed = new URL(origin);\n } catch {\n throw new Error(`Invalid API origin: ${origin}`);\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.origin !== origin\n )\n throw new Error(\n `API origins must be HTTP(S) origins without paths, credentials or trailing slash: ${origin}`,\n );\n }\n if (options.reportUri) {\n let parsed: URL;\n try {\n parsed = new URL(options.reportUri);\n } catch {\n throw new Error('Invalid reporting URL');\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n )\n throw new Error(\n 'Reporting URL must be an HTTP(S) URL without credentials or fragment',\n );\n }\n const review = new Date(options.now ?? new Date());\n review.setUTCFullYear(review.getUTCFullYear() + 1);\n const reviewBy = review.toISOString().slice(0, 10);\n const policy = definePolicy({\n ...(options.reportUri ? { reporting: { uri: options.reportUri } } : {}),\n base: {\n default: [SELF],\n scripts: [SELF, NONCE, STRICT_DYNAMIC],\n objects: [NONE],\n baseUri: [SELF],\n frameAncestors: [NONE],\n upgradeInsecureRequests: true,\n },\n ruleSets: [\n {\n name: 'App assets',\n purpose: 'Images used by the application',\n owner: 'TODO: assign owner',\n reviewBy,\n rules: { images: [SELF, 'data:', 'blob:'] },\n },\n ...(apiOrigins.length\n ? [\n {\n name: 'App API',\n purpose: 'Application API connections',\n owner: 'TODO: assign owner',\n reviewBy,\n rules: { connect: apiOrigins },\n },\n ]\n : []),\n ],\n });\n const apiImport = apiOrigins.length\n ? `import { appApi } from './rule-sets/app-api';\\n`\n : '';\n const reporting = options.reportUri\n ? ` reporting: { uri: ${JSON.stringify(options.reportUri)} },\\n`\n : '';\n const apiTest = apiOrigins.length\n ? ` expect(policy).toAllow('connect', ${JSON.stringify(apiOrigins[0] + '/')}, { origin: 'https://site.example', redirectCount: 0 });\\n`\n : '';\n const files: Record<string, string> = {\n 'csp.config.ts': `export { policy as default } from './csp/policy';\\n`,\n 'csp/policy.ts': `import { definePolicy, SELF, NONE, NONCE, STRICT_DYNAMIC } from '@jamesbrightman/pretty-csp';\\nimport { appAssets } from './rule-sets/app-assets';\\n${apiImport}\\nexport const policy = definePolicy({\\n${reporting} base: { default: [SELF], scripts: [SELF, NONCE, STRICT_DYNAMIC], objects: [NONE], baseUri: [SELF], frameAncestors: [NONE], upgradeInsecureRequests: true },\\n ruleSets: [appAssets${apiOrigins.length ? ', appApi' : ''}],\\n});\\n`,\n 'csp/rule-sets/app-assets.ts': `import { defineRuleSet, SELF } from '@jamesbrightman/pretty-csp';\\n\\nexport const appAssets = defineRuleSet({ name: 'App assets', purpose: 'Images used by the application', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { images: [SELF, 'data:', 'blob:'] } });\\n`,\n 'csp/policy.test.ts': `import { readFile } from 'node:fs/promises';\\nimport { expect, test } from 'vitest';\\nimport { cspMatchers } from '@jamesbrightman/pretty-csp/testing';\\nimport { policy } from './policy';\\n\\nexpect.extend(cspMatchers);\\ntest('blocks untrusted connections and has no high-risk findings', () => {\\n${apiTest} expect(policy).toBlock('connect', 'https://untrusted.example/', { origin: 'https://site.example', redirectCount: 0 });\\n expect(policy).toPassAudit({ maxSeverity: 'low' });\\n});\\ntest('matches the reviewed CSP snapshot', async () => {\\n const snapshot = JSON.parse(await readFile(new URL('../csp.snapshot.json', import.meta.url), 'utf8'));\\n expect(policy).toMatchCspSnapshot(snapshot);\\n});\\n`,\n 'csp/vitest.d.ts': `import 'vitest';\\nimport type { CspAssertions } from '@jamesbrightman/pretty-csp/testing';\\n\\ndeclare module 'vitest' {\\n interface Assertion<T> extends CspAssertions<T> {}\\n interface AsymmetricMatchersContaining extends CspAssertions {}\\n}\\n`,\n 'csp.snapshot.json': `${JSON.stringify(cspSnapshot(policy), null, 2)}\\n`,\n };\n if (apiOrigins.length)\n files['csp/rule-sets/app-api.ts'] =\n `import { defineRuleSet } from '@jamesbrightman/pretty-csp';\\n\\nexport const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API connections', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { connect: ${JSON.stringify(apiOrigins)} } });\\n`;\n async function stat(path: string) {\n try {\n return await lstat(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n }\n for (const directory of ['csp', 'csp/rule-sets']) {\n const dir = await stat(join(cwd, directory));\n if (dir?.isSymbolicLink() || (dir && !dir.isDirectory()))\n throw new Error(`${directory} must be a directory and not a symlink`);\n }\n for (const file of Object.keys(files)) {\n const current = await stat(join(cwd, file));\n if (current?.isSymbolicLink() || (current && !current.isFile()))\n throw new Error(`Refusing non-file or symlink: ${file}`);\n if (current && !options.force)\n throw new Error(\n `File already exists: ${file}. Use --force to replace it.`,\n );\n }\n if (!options.dryRun) {\n await mkdir(join(cwd, 'csp/rule-sets'), { recursive: true });\n for (const [file, content] of Object.entries(files))\n await writeFile(join(cwd, file), content, {\n encoding: 'utf8',\n flag: options.force ? 'w' : 'wx',\n });\n }\n return Object.keys(files);\n}\n","/** Request metadata needed to evaluate checks which cannot be decided from a URL alone. */\nexport interface MatchOptions {\n /** Origin of the protected document, required for 'self' and schemeless sources. */\n origin?: string;\n /** Number of redirects before this URL; paths are not checked after a redirect. */\n redirectCount?: number;\n /** Nonce on the request; supply an empty string if the request has none. */\n nonce?: string;\n /** Rendered policy nonce for a dynamic nonce placeholder. */\n policyNonce?: string;\n /** Integrity metadata tokens on the request; supply an empty array if absent. */\n integrity?: readonly string[];\n /** Whether a script was parser-inserted. */\n parserInserted?: boolean;\n}\n\n/** A conservative CSP decision. `indeterminate` never implies browser permission. */\nexport interface AllowsResult {\n status: 'allowed' | 'blocked' | 'indeterminate';\n allowed: boolean | null;\n effectiveDirective?: string;\n matchedSource?: string;\n reason?: string;\n}\n\ntype Match = 'yes' | 'no' | 'unknown';\nconst friendly: Record<string, string> = {\n scripts: 'script-src',\n connect: 'connect-src',\n images: 'img-src',\n styles: 'style-src',\n fonts: 'font-src',\n frames: 'frame-src',\n forms: 'form-action',\n media: 'media-src',\n workers: 'worker-src',\n manifest: 'manifest-src',\n default: 'default-src',\n objects: 'object-src',\n baseUri: 'base-uri',\n frameAncestors: 'frame-ancestors',\n};\nconst fallbacks: Record<string, readonly string[]> = {\n 'script-src-elem': ['script-src-elem', 'script-src', 'default-src'],\n 'script-src-attr': ['script-src-attr', 'script-src', 'default-src'],\n 'style-src-elem': ['style-src-elem', 'style-src', 'default-src'],\n 'style-src-attr': ['style-src-attr', 'style-src', 'default-src'],\n 'worker-src': ['worker-src', 'child-src', 'script-src', 'default-src'],\n 'frame-src': ['frame-src', 'child-src', 'default-src'],\n};\nfor (const name of [\n 'script-src',\n 'style-src',\n 'child-src',\n 'connect-src',\n 'font-src',\n 'img-src',\n 'manifest-src',\n 'media-src',\n 'object-src',\n]) {\n fallbacks[name] = [name, 'default-src'];\n}\nfor (const name of [\n 'default-src',\n 'form-action',\n 'base-uri',\n 'frame-ancestors',\n])\n fallbacks[name] = [name];\n\nfunction decision(\n status: AllowsResult['status'],\n effectiveDirective?: string,\n reason?: string,\n matchedSource?: string,\n): AllowsResult {\n return {\n status,\n allowed: status === 'indeterminate' ? null : status === 'allowed',\n ...(effectiveDirective && { effectiveDirective }),\n ...(reason && { reason }),\n ...(matchedSource && { matchedSource }),\n };\n}\n\n// CSP3 §6.7.2.9: upgrades are asymmetric; ws and wss have special cases.\nfunction schemeMatches(source: string, target: string): boolean {\n source = source.toLowerCase();\n target = target.toLowerCase();\n return (\n source === target ||\n (source === 'http' && target === 'https') ||\n (source === 'ws' && ['wss', 'http', 'https'].includes(target)) ||\n (source === 'wss' && target === 'https')\n );\n}\nfunction scheme(url: URL): string {\n return url.protocol.slice(0, -1).toLowerCase();\n}\nfunction defaultPort(s: string): string | undefined {\n return (\n { http: '80', https: '443', ws: '80', wss: '443', ftp: '21' } as Record<\n string,\n string\n >\n )[s];\n}\nfunction selfMatches(url: URL, origin: URL): boolean {\n if (scheme(url) === 'blob') return false;\n if (origin.origin !== 'null' && origin.origin === url.origin) return true;\n const os = scheme(origin),\n us = scheme(url);\n const portsMatch = origin.port === url.port || (!origin.port && !url.port);\n return (\n origin.hostname !== '' &&\n origin.hostname === url.hostname &&\n portsMatch &&\n (us === 'https' ||\n us === 'wss' ||\n (os === 'http' && (us === 'http' || us === 'ws')))\n );\n}\n// Percent-decode each segment to bytes, not URI components: %2F remains inside its segment.\nfunction segmentBytes(segment: string): string {\n const bytes: number[] = [];\n for (let i = 0; i < segment.length;) {\n const encoded = segment.slice(i).match(/^%([0-9a-f]{2})/i);\n if (encoded) {\n bytes.push(parseInt(encoded[1]!, 16));\n i += 3;\n continue;\n }\n const point = segment.codePointAt(i)!;\n const character = String.fromCodePoint(point);\n bytes.push(...new TextEncoder().encode(character));\n i += character.length;\n }\n return bytes.join(',');\n}\n// CSP3 §6.7.2.12: a trailing slash makes the source a segment prefix.\nfunction pathMatches(pattern: string, target: string): boolean {\n if (!pattern || (pattern === '/' && !target)) return true;\n const a = pattern.split('/'),\n b = target.split('/');\n if (a.length > b.length || (!pattern.endsWith('/') && a.length !== b.length))\n return false;\n if (pattern.endsWith('/')) a.pop();\n return a.every((part, i) => segmentBytes(part) === segmentBytes(b[i]!));\n}\n\n// CSP3 §§6.7.2.8–12. Unknown context stays unknown instead of silently assuming it.\nfunction sourceMatches(\n source: string,\n url: URL,\n origin: URL | undefined,\n redirectCount: number | undefined,\n): Match {\n const lower = source.toLowerCase(),\n targetScheme = scheme(url);\n if (lower === \"'self'\")\n return origin ? (selfMatches(url, origin) ? 'yes' : 'no') : 'unknown';\n if (source === '*')\n return ['http', 'https'].includes(targetScheme)\n ? 'yes'\n : origin\n ? scheme(origin) === targetScheme\n ? 'yes'\n : 'no'\n : 'unknown';\n const schemeOnly = source.match(/^([a-z][a-z0-9+.-]*):$/i);\n if (schemeOnly)\n return schemeMatches(schemeOnly[1]!, targetScheme) ? 'yes' : 'no';\n // Host expressions do not admit credentials, query strings, or fragments.\n const host = source.match(\n /^(?:([a-z][a-z0-9+.-]*):\\/\\/)?(\\*|(?:\\*\\.)?[a-z0-9.-]+)(?::(\\*|[0-9]+))?(\\/[^?#]*)?$/i,\n );\n if (!host) return 'no';\n const [, explicitScheme, patternHost, port, path] = host;\n if (\n !url.hostname ||\n /^\\[/.test(url.hostname) ||\n /^\\d+(?:\\.\\d+){3}$/.test(url.hostname)\n )\n return 'no';\n if (!explicitScheme && !origin) return 'unknown';\n if (!schemeMatches(explicitScheme ?? scheme(origin!), targetScheme))\n return 'no';\n const domain = url.hostname.toLowerCase(),\n pattern = patternHost!.toLowerCase();\n if (\n pattern !== '*' &&\n !(pattern.startsWith('*.')\n ? domain.endsWith(pattern.slice(1))\n : domain === pattern)\n )\n return 'no';\n if (port !== '*') {\n const targetPort = url.port || undefined;\n if (\n port === undefined\n ? targetPort !== undefined\n : Number(port) !== Number(targetPort ?? defaultPort(targetScheme))\n )\n return 'no';\n }\n if (path && !pathMatches(path, url.pathname)) {\n if (redirectCount === undefined) return 'unknown';\n if (redirectCount === 0) return 'no';\n }\n return 'yes';\n}\n\n/**\n * Evaluate a URL against a CSP directive. This deliberately returns indeterminate when\n * relevant request context is unavailable. It is not a full browser simulation.\n * Algorithms: https://www.w3.org/TR/CSP3/#match-url-to-source-list and #directive-fallback-list\n */\nexport function matchPolicy(\n directives: Readonly<Record<string, readonly string[]>>,\n directive: string,\n input: string,\n options: MatchOptions = {},\n): AllowsResult {\n const requested = friendly[directive] ?? directive.toLowerCase();\n // URL checks for scripts and styles represent element fetches, whose explicit\n // -elem directives take precedence over script-src/style-src (CSP3 �6.8.3).\n const name =\n requested === 'script-src'\n ? 'script-src-elem'\n : requested === 'style-src'\n ? 'style-src-elem'\n : requested;\n const chain = fallbacks[name];\n if (!chain)\n return decision(\n 'indeterminate',\n undefined,\n 'Unsupported directive or inline check',\n );\n const effective = chain.find((key) =>\n Object.prototype.hasOwnProperty.call(directives, key),\n );\n if (!effective)\n return decision('allowed', undefined, 'No applicable directive');\n if (name.endsWith('-attr'))\n return decision(\n 'indeterminate',\n effective,\n 'Inline checks require element content and context',\n );\n if (name === 'frame-ancestors')\n return decision(\n 'indeterminate',\n effective,\n 'Frame enforcement depends on the complete ancestor chain',\n );\n if (\n options.redirectCount !== undefined &&\n (!Number.isInteger(options.redirectCount) || options.redirectCount < 0)\n )\n throw new TypeError('redirectCount must be a non-negative integer');\n let url: URL, origin: URL | undefined;\n try {\n url = new URL(input);\n if (options.origin !== undefined) {\n origin = new URL(options.origin);\n if (origin.origin === 'null') throw new Error('opaque');\n }\n } catch {\n throw new TypeError('Expected an absolute URL and a non-opaque origin');\n }\n const sources = directives[effective]!;\n const script = name === 'script-src' || name === 'script-src-elem';\n const style = name === 'style-src' || name === 'style-src-elem';\n const hasNoncePlaceholder = sources.includes(\"'nonce-{nonce}'\");\n const nonceSources = sources.filter((s) =>\n /^'nonce-[a-z0-9+/_=-]+'$/i.test(s),\n );\n const hashes = sources.filter((s) =>\n /^'sha(256|384|512)-[a-z0-9+/_=-]+'$/i.test(s),\n );\n if (\n (script || style) &&\n options.nonce &&\n (nonceSources.some((s) => s.slice(7, -1) === options.nonce) ||\n (hasNoncePlaceholder &&\n options.policyNonce !== undefined &&\n options.nonce === options.policyNonce))\n )\n return decision('allowed', effective, 'Matching request nonce');\n if (\n script &&\n options.integrity?.length &&\n options.integrity.every((token) =>\n hashes.some((hash) => {\n const [hashAlg, hashDigest] = hash.slice(1, -1).split('-', 2);\n const [tokenAlg, tokenDigest] = token.split('-', 2);\n return (\n hashAlg?.toLowerCase() === tokenAlg?.toLowerCase() &&\n hashDigest !== undefined &&\n hashDigest === tokenDigest\n );\n }),\n )\n )\n return decision('allowed', effective, 'Matching integrity metadata');\n const missingNonce =\n (script || style) &&\n ((nonceSources.length > 0 && options.nonce === undefined) ||\n (hasNoncePlaceholder &&\n (options.nonce === undefined ||\n (options.nonce !== '' && options.policyNonce === undefined))));\n const missingIntegrity =\n script && hashes.length > 0 && options.integrity === undefined;\n if (script && sources.some((s) => s.toLowerCase() === \"'strict-dynamic'\")) {\n if (options.parserInserted === false)\n return decision(\n 'allowed',\n effective,\n 'Non-parser-inserted script under strict-dynamic',\n );\n if (\n options.parserInserted === undefined ||\n missingNonce ||\n missingIntegrity\n )\n return decision(\n 'indeterminate',\n effective,\n 'Script nonce, integrity or parser metadata is missing',\n );\n return decision(\n 'blocked',\n effective,\n 'Parser-inserted script has no matching nonce or integrity metadata',\n );\n }\n let unknown = false;\n for (const source of sources) {\n const match = sourceMatches(source, url, origin, options.redirectCount);\n if (match === 'yes')\n return decision('allowed', effective, undefined, source);\n if (match === 'unknown') unknown = true;\n }\n if (unknown || missingNonce || missingIntegrity)\n return decision(\n 'indeterminate',\n effective,\n 'Origin, redirect count, nonce or integrity metadata is missing',\n );\n return decision('blocked', effective, 'No source matched');\n}\n","import { matchPolicy } from './matching';\nimport type { AllowsResult, MatchOptions } from './matching';\nimport { z } from 'zod';\nimport { NONCE } from './keywords';\nimport {\n baseDirectives,\n policyConfigSchema,\n resourceDirectives,\n ruleSetSchema,\n} from './schemas';\nimport type {\n NormalizedPolicyConfig,\n PolicyConfig,\n RuleSet,\n RuleSetInput,\n SourceEntry,\n} from './schemas';\n\n/** Reject literal risky strings in input lists while allowing annotated source objects.\n * Dynamic strings remain subject to runtime Zod validation. */\nexport type RequireRiskReasons<T> = T extends { source: string }\n ? T\n : T extends string\n ? Lowercase<T> extends\n \"'unsafe-inline'\" | \"'unsafe-eval'\" | \"'unsafe-hashes'\"\n ? never\n : T\n : T extends object\n ? {\n [K in keyof T]: K extends\n | 'name'\n | 'purpose'\n | 'owner'\n | 'docs'\n | 'tags'\n | 'reviewBy'\n | 'enabled'\n | 'reporting'\n ? T[K]\n : RequireRiskReasons<T[K]>;\n }\n : T;\n\nexport interface ExplainRow {\n directive: string;\n source: string;\n ruleSet: string;\n reason?: string;\n}\nexport interface HeaderOptions {\n nonce?: string;\n pretty?: boolean;\n}\nfunction freeze<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.values(value).forEach(freeze);\n Object.freeze(value);\n }\n return value;\n}\n/** Validate and freeze a rule set. */\nexport function defineRuleSet<const T extends RuleSetInput>(\n input: T & RequireRiskReasons<T>,\n): RuleSet {\n const parsed = ruleSetSchema.safeParse(input);\n if (!parsed.success) {\n const name = typeof input?.name === 'string' ? input.name : '<unnamed>';\n const detail = parsed.error.issues\n .map((issue) => `${issue.path.join('.') || '<root>'}: ${issue.message}`)\n .join('; ');\n throw new z.ZodError(\n parsed.error.issues.map((issue) => ({\n ...issue,\n message: `RuleSet \"${name}\" - ${detail}`,\n })),\n );\n }\n return freeze(parsed.data);\n}\nfunction entryValue(entry: SourceEntry): string {\n return typeof entry === 'string' ? entry : entry.source;\n}\nfunction entryReason(entry: SourceEntry): string | undefined {\n return typeof entry === 'string' ? undefined : entry.reason;\n}\n/** Immutable CSP configuration and its deterministic merged representation. */\nexport class Policy {\n readonly config: NormalizedPolicyConfig;\n constructor(input: PolicyConfig) {\n const result = policyConfigSchema.safeParse(input);\n if (!result.success) {\n throw new z.ZodError(\n result.error.issues.map((issue) => {\n const index =\n issue.path[0] === 'ruleSets' && typeof issue.path[1] === 'number'\n ? issue.path[1]\n : undefined;\n const name =\n index === undefined ? undefined : input.ruleSets?.[index]?.name;\n return name\n ? {\n ...issue,\n message: `RuleSet \"${name}\" - ${issue.path.slice(2).join('.')}: ${issue.message}`,\n }\n : issue;\n }),\n );\n }\n const config = result.data;\n this.config = freeze(config);\n Object.freeze(this);\n }\n /** Sources and their contributing rule sets. Duplicate values retain all contributors. */\n explain(): ExplainRow[] {\n const rows: ExplainRow[] = [];\n const add = (\n directive: string,\n entries: SourceEntry[],\n ruleSet: string,\n ) => {\n for (const entry of entries) {\n const reason = entryReason(entry);\n rows.push({\n directive,\n source: entryValue(entry),\n ruleSet,\n ...(reason === undefined ? {} : { reason }),\n });\n }\n };\n const collect = (rules: Record<string, unknown>, name: string) => {\n for (const [key, value] of Object.entries(rules)) {\n if (key === 'directives' && value) {\n for (const [directive, entries] of Object.entries(\n value as Record<string, SourceEntry[]>,\n ))\n add(directive, entries, name);\n } else if (Array.isArray(value)) {\n const directive =\n (resourceDirectives as Record<string, string>)[key] ??\n (baseDirectives as Record<string, string>)[key];\n if (directive) add(directive, value as SourceEntry[], name);\n }\n }\n };\n collect(this.config.base, 'base');\n for (const set of this.config.ruleSets)\n if (set.enabled) collect(set.rules, set.name);\n return rows.sort(\n (a, b) =>\n a.directive.localeCompare(b.directive, 'en') ||\n a.source.localeCompare(b.source, 'en') ||\n a.ruleSet.localeCompare(b.ruleSet, 'en') ||\n (a.reason ?? '').localeCompare(b.reason ?? '', 'en'),\n );\n }\n /** Merged sources, deduplicated without changing path syntax. */\n toObject(): Record<string, string[]> {\n const map: Record<string, Set<string>> = Object.create(null) as Record<\n string,\n Set<string>\n >;\n for (const row of this.explain())\n (map[row.directive] ??= new Set()).add(row.source);\n if (this.config.base.upgradeInsecureRequests)\n map['upgrade-insecure-requests'] = new Set();\n if (this.config.reporting?.uri)\n map['report-uri'] = new Set([this.config.reporting.uri]);\n if (this.config.reporting?.to)\n map['report-to'] = new Set([this.config.reporting.to]);\n return Object.fromEntries(\n Object.entries(map)\n .sort(([a], [b]) => a.localeCompare(b, 'en'))\n .map(([key, values]) => [key, Array.from(values).sort()]),\n );\n }\n /** Evaluate a URL with explicit uncertainty when browser context is missing. */\n allows(\n directive: string,\n url: string,\n options: MatchOptions = {},\n ): AllowsResult & { contributors?: ExplainRow[] } {\n const result = matchPolicy(this.toObject(), directive, url, options);\n const contributors =\n result.matchedSource && result.effectiveDirective\n ? this.explain().filter(\n (row) =>\n row.directive === result.effectiveDirective &&\n row.source === result.matchedSource,\n )\n : [];\n return contributors.length ? { ...result, contributors } : result;\n }\n /** Render a header value. Pretty output is for display only and is not a valid HTTP header value. */\n toHeader(options: HeaderOptions = {}): string {\n const directives = this.toObject();\n const hasNonce = Object.values(directives).some((sources) =>\n sources.includes(NONCE),\n );\n if (\n hasNonce &&\n (!options.nonce || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(options.nonce))\n )\n throw new Error('A valid base64 nonce is required');\n return Object.entries(directives)\n .map(([directive, values]) => {\n const rendered = values.map((value) =>\n value === NONCE ? `'nonce-${options.nonce}'` : value,\n );\n return directive + (rendered.length ? ` ${rendered.join(' ')}` : '');\n })\n .join(options.pretty ? ';\\n' : '; ');\n }\n /** Add one or several rule sets in a single validated, immutable update. */\n withRuleSet<const T extends readonly RuleSetInput[]>(\n ruleSets: T & (T extends RequireRiskReasons<T> ? unknown : never),\n ): Policy;\n withRuleSet<const T extends RuleSetInput>(\n ruleSet: T & RequireRiskReasons<T>,\n ): Policy;\n withRuleSet(ruleSets: RuleSetInput | readonly RuleSetInput[]): Policy {\n const additions: readonly RuleSetInput[] = Array.isArray(ruleSets)\n ? ruleSets\n : [ruleSets as RuleSetInput];\n return new Policy({\n ...this.config,\n ruleSets: [...this.config.ruleSets, ...additions],\n });\n }\n without(name: string): Policy {\n return new Policy({\n ...this.config,\n ruleSets: this.config.ruleSets.filter((set) => set.name !== name),\n });\n }\n}\n/** Validate and construct a policy. */\nexport function definePolicy<const T extends PolicyConfig>(\n input: T & RequireRiskReasons<T>,\n): Policy {\n return new Policy(input);\n}\n","/** Allow resources from the protected document's origin. */\nexport const SELF = \"'self'\";\n/** Block all resources for a directive. */\nexport const NONE = \"'none'\";\n/** Replaced with the per-response nonce passed to toHeader({ nonce }). */\nexport const NONCE = \"'nonce-{nonce}'\";\n/** Propagate trust from nonce- or hash-authorized scripts. */\nexport const STRICT_DYNAMIC = \"'strict-dynamic'\";\n/** Include code samples in applicable violation reports. */\nexport const REPORT_SAMPLE = \"'report-sample'\";\n/** Permit WebAssembly compilation without general JavaScript evaluation. */\nexport const WASM_UNSAFE_EVAL = \"'wasm-unsafe-eval'\";\n/** Use Web Crypto to create a fresh, unpredictable per-response nonce. */\nexport function generateNonce(): string {\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return btoa(String.fromCharCode(...bytes));\n}\n\n/** Permit inline code; weakens XSS protection unless ignored by a nonce or hash. */\nexport const unsafeInline = ({ reason }: { reason: string }) => ({\n source: \"'unsafe-inline'\",\n reason,\n});\n/** Permit dynamic JavaScript evaluation; increases XSS risk. */\nexport const unsafeEval = ({ reason }: { reason: string }) => ({\n source: \"'unsafe-eval'\",\n reason,\n});\n/** Permit hashes for inline handlers; can weaken protection. */\nexport const unsafeHashes = ({ reason }: { reason: string }) => ({\n source: \"'unsafe-hashes'\",\n reason,\n});\n/** Create a CSP hash source expression. */\nexport const cspHash = (\n algorithm: 'sha256' | 'sha384' | 'sha512',\n digest: string,\n) => `'${algorithm}-${digest}'`;\n","/* eslint-disable no-control-regex -- CSP input must reject ASCII control characters. */\nimport { z } from 'zod';\nimport { NONCE } from './keywords';\n\n/** Friendly resource names mapped to CSP directives. */\nexport const resourceDirectives = {\n scripts: 'script-src',\n connect: 'connect-src',\n images: 'img-src',\n styles: 'style-src',\n fonts: 'font-src',\n frames: 'frame-src',\n forms: 'form-action',\n media: 'media-src',\n workers: 'worker-src',\n manifest: 'manifest-src',\n} as const;\nexport const baseDirectives = {\n default: 'default-src',\n objects: 'object-src',\n baseUri: 'base-uri',\n frameAncestors: 'frame-ancestors',\n} as const;\nconst risky = new Set([\"'unsafe-inline'\", \"'unsafe-eval'\", \"'unsafe-hashes'\"]);\nconst keywords = new Set([\n \"'self'\",\n \"'none'\",\n \"'strict-dynamic'\",\n \"'report-sample'\",\n \"'wasm-unsafe-eval'\",\n ...risky,\n]);\n\nfunction isSource(value: string): boolean {\n if (\n !value ||\n /[\\x00-\\x20\\x7f;,]/.test(value) ||\n /^[a-z][a-z0-9+.-]*\\/\\//i.test(value)\n )\n return false;\n if (\n keywords.has(value.toLowerCase()) ||\n value === NONCE ||\n value === '*' ||\n /^[a-z][a-z0-9+.-]*:\\/\\/\\*(?::(?:\\d+|\\*))?(?:\\/[^\\s;,#?]*)?$/i.test(value)\n )\n return true;\n if (\n /^'(nonce-[A-Za-z0-9+/_-]+={0,2}|sha(256|384|512)-[A-Za-z0-9+/_-]+={0,2})'$/i.test(\n value,\n )\n )\n return true;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:$/.test(value)) return true;\n // CSP host-source, including scheme-less hosts, optional wildcard, port and path.\n return /^(?:[a-z][a-z0-9+.-]*:\\/\\/)?(?:\\*\\.)?(?:[a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+(?::(?:\\d+|\\*))?(?:\\/[^\\s;,#?]*)?$/i.test(\n value,\n );\n}\nconst sourceStringSchema = z\n .string()\n .refine(isSource, 'Invalid CSP source expression');\n/** A source string, or a source annotated with a human-readable reason. Risky keywords require a reason. */\nexport const sourceEntrySchema = z.union([\n sourceStringSchema.refine(\n (s) => !risky.has(s.toLowerCase()),\n 'Risky keyword requires a reason',\n ),\n z\n .object({ source: sourceStringSchema, reason: z.string().trim().min(1) })\n .strict(),\n]);\nconst sourceList = z.array(sourceEntrySchema).min(1);\nconst sourceListDirectives = new Set([\n ...Object.values(resourceDirectives),\n ...Object.values(baseDirectives),\n 'script-src-elem',\n 'script-src-attr',\n 'style-src-elem',\n 'style-src-attr',\n 'child-src',\n]);\nconst rawDirectives = z.record(\n z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/)\n .refine(\n (name) => sourceListDirectives.has(name),\n 'Unsupported raw directive; only known source-list directives are supported',\n ),\n sourceList,\n);\nconst reserved = new Set([\n 'report-uri',\n 'report-to',\n 'upgrade-insecure-requests',\n]);\nconst baseOnly = new Set([...Object.values(baseDirectives), ...reserved]);\nconst ruleShape = Object.fromEntries(\n Object.keys(resourceDirectives).map((key) => [key, sourceList.optional()]),\n) as {\n [K in keyof typeof resourceDirectives]: z.ZodOptional<typeof sourceList>;\n};\n/** Rule-set permissions. At least one directive must be supplied. */\nexport const rulesSchema = z\n .object({ ...ruleShape, directives: rawDirectives.optional() })\n .strict()\n .refine(\n (rules) =>\n Object.entries(rules).some(([key, value]) =>\n key === 'directives'\n ? Object.keys(value ?? {}).length > 0\n : value !== undefined,\n ),\n 'At least one resource directive is required',\n )\n .superRefine((rules, ctx) => {\n for (const directive of Object.keys(rules.directives ?? {})) {\n if (baseOnly.has(directive))\n ctx.addIssue({\n code: 'custom',\n path: ['directives', directive],\n message: 'Base-only or reserved directive',\n });\n }\n });\n/** Site-wide directives. */\nexport const baseSchema = z\n .object({\n ...ruleShape,\n default: sourceList.optional(),\n objects: sourceList.optional(),\n baseUri: sourceList.optional(),\n frameAncestors: sourceList.optional(),\n upgradeInsecureRequests: z.boolean().optional(),\n directives: rawDirectives.optional(),\n })\n .strict()\n .superRefine((base, ctx) => {\n for (const directive of Object.keys(base.directives ?? {})) {\n if (reserved.has(directive))\n ctx.addIssue({\n code: 'custom',\n path: ['directives', directive],\n message: 'Use the dedicated configuration field for this directive',\n });\n }\n });\n/** A named, documented and optionally disabled group of permissions. */\nexport const ruleSetSchema = z\n .object({\n name: z.string().trim().min(1),\n purpose: z.string().trim().min(1),\n owner: z.string().trim().min(1).optional(),\n docs: z.url().optional(),\n tags: z.array(z.string().trim().min(1)).optional(),\n reviewBy: z.iso.date().optional(),\n enabled: z.boolean().default(true),\n rules: rulesSchema,\n })\n .strict();\nconst reportingSchema = z\n .object({\n uri: z\n .url()\n .refine(\n (value) => !/[\\x00-\\x20\\x7f;,]/.test(value),\n 'Invalid reporting value',\n )\n .optional(),\n to: z\n .string()\n .regex(/^[A-Za-z0-9_-]+$/)\n .optional(),\n })\n .strict();\n/** Complete configuration. Zod catches duplicate names and invalid rule sets. */\nexport const policyConfigSchema = z\n .object({\n base: baseSchema.default({}),\n ruleSets: z.array(ruleSetSchema).default([]),\n reporting: reportingSchema.optional(),\n })\n .strict()\n .superRefine((config, ctx) => {\n const names = new Set<string>();\n config.ruleSets.forEach((rule, i) => {\n if (names.has(rule.name))\n ctx.addIssue({\n code: 'custom',\n path: ['ruleSets', i, 'name'],\n message: `Duplicate rule set name: ${rule.name}`,\n });\n names.add(rule.name);\n });\n });\nexport type SourceEntry = z.output<typeof sourceEntrySchema>;\nexport type Rules = z.output<typeof rulesSchema>;\nexport type ResourceKey = keyof typeof resourceDirectives;\nexport type RuleSetInput = z.input<typeof ruleSetSchema>;\nexport type RuleSet = z.output<typeof ruleSetSchema>;\nexport type PolicyConfig = z.input<typeof policyConfigSchema>;\nexport type NormalizedPolicyConfig = z.output<typeof policyConfigSchema>;\nexport type DirectiveName =\n | (typeof resourceDirectives)[ResourceKey]\n | (typeof baseDirectives)[keyof typeof baseDirectives]\n | 'upgrade-insecure-requests'\n | 'report-uri'\n | 'report-to';\n","#!/usr/bin/env node\nimport { runCli } from './index';\n\nvoid runCli(process.argv.slice(2), {\n out: (message) => console.log(message),\n error: (message) => console.error(message),\n}).then((code) => {\n process.exitCode = code;\n});\n"],"mappings":";;;;AAAA,IAAAA,mBAAoC;AACpC,IAAAC,oBAAiC;AACjC,sBAA8B;AAC9B,kBAA2B;;;ACwB3B,IAAM,iBAAiB,CACrB,QACA,WACA,QACA,QACA,UACA,SACA,QACmB;AACnB,QAAM,SAAS,OACZ,QAAQ,EACR,OAAO,CAAC,QAAQ,IAAI,cAAc,aAAa,IAAI,WAAW,MAAM;AACvE,SAAO,OAAO,SACV,OAAO,IAAI,CAAC,EAAE,QAAQ,OAAO;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,IACF,CAAC,EAAE,QAAQ,UAAU,SAAS,KAAK,WAAW,OAAO,CAAC;AAC5D;AAGO,SAAS,MACd,QACA,UAAwB,CAAC,GACT;AAChB,QAAM,SAAS,OAAO,SAAS;AAC/B,QAAM,WAA2B,CAAC;AAClC,QAAM,MAAM,CACV,IACA,UACA,SACA,KACA,cAEA,SAAS,KAAK;AAAA,IACZ,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;AAAA,EACnC,CAAC;AACH,MAAI,CAAC,OAAO,YAAY,KAAK,CAAC,OAAO,aAAa;AAChD;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEF,aAAW,aAAa;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAG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AAK,UAAU,UAAU,MAAM,CAAC,CAAC;AACxC,aAAO,SAAS;AAAA,QACd,CAAC,YACC,WAAW,QAAQ,QAAQ,KAAK,WAAW,SAAqB;AAAA,MACpE,IACI,IACA;AAAA,IACN;AACA,UAAM,WAAO,2BAAQ,KAAK,OAAO,SAAS,MAAM,KAAK,mBAAmB;AACxE,UAAM,WAAW,GAAG,KAAK,UAAU,YAAY,MAAM,GAAG,MAAM,CAAC,CAAC;AAAA;AAChE,QAAI,QAAQ,QAAQ;AAClB,gBAAM,4BAAU,MAAM,UAAU,MAAM;AACtC,SAAG,IAAI,WAAW,IAAI,EAAE;AACxB,aAAO;AAAA,IACT;AACA,QAAI;AACJ,QAAI;AACF,eAAS,UAAM,2BAAS,MAAM,MAAM;AAAA,IACtC,QAAQ;AACN,YAAM,IAAI;AAAA,QACR,uBAAuB,IAAI;AAAA,MAC7B;AAAA,IACF;AACA,QAAI,WAAW,UAAU;AACvB,SAAG;AAAA,QACD;AAAA,MACF;AACA,aAAO;AAAA,IACT;AACA,OAAG,IAAI,uBAAuB;AAC9B,WAAO;AAAA,EACT,SAAS,OAAO;AACd,OAAG,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAC/D,WAAO;AAAA,EACT;AACF;;;AQ3MA,KAAK,OAAO,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EACjC,KAAK,CAAC,YAAY,QAAQ,IAAI,OAAO;AAAA,EACrC,OAAO,CAAC,YAAY,QAAQ,MAAM,OAAO;AAC3C,CAAC,EAAE,KAAK,CAAC,SAAS;AAChB,UAAQ,WAAW;AACrB,CAAC;","names":["import_promises","import_node_path","import_zod","module"]}
|
package/dist/cli.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
NONCE,
|
|
4
|
+
NONE,
|
|
5
|
+
SELF,
|
|
6
|
+
STRICT_DYNAMIC,
|
|
7
|
+
definePolicy
|
|
8
|
+
} from "./chunk-JAXLODN4.js";
|
|
9
|
+
import {
|
|
10
|
+
cspSnapshot
|
|
11
|
+
} from "./chunk-YMAXUCI4.js";
|
|
12
|
+
import {
|
|
13
|
+
audit
|
|
14
|
+
} from "./chunk-KWWYRHIP.js";
|
|
15
|
+
|
|
16
|
+
// src/cli/index.ts
|
|
17
|
+
import { readFile, writeFile as writeFile2 } from "fs/promises";
|
|
18
|
+
import { resolve, extname } from "path";
|
|
19
|
+
import { pathToFileURL } from "url";
|
|
20
|
+
import { createJiti } from "jiti";
|
|
21
|
+
|
|
22
|
+
// src/cli/init.ts
|
|
23
|
+
import { lstat, mkdir, writeFile } from "fs/promises";
|
|
24
|
+
import { join } from "path";
|
|
25
|
+
async function initProject(cwd, options = {}) {
|
|
26
|
+
const apiOrigins = [...new Set(options.apiOrigins ?? [])];
|
|
27
|
+
for (const origin of apiOrigins) {
|
|
28
|
+
let parsed;
|
|
29
|
+
try {
|
|
30
|
+
parsed = new URL(origin);
|
|
31
|
+
} catch {
|
|
32
|
+
throw new Error(`Invalid API origin: ${origin}`);
|
|
33
|
+
}
|
|
34
|
+
if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.origin !== origin)
|
|
35
|
+
throw new Error(
|
|
36
|
+
`API origins must be HTTP(S) origins without paths, credentials or trailing slash: ${origin}`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
if (options.reportUri) {
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = new URL(options.reportUri);
|
|
43
|
+
} catch {
|
|
44
|
+
throw new Error("Invalid reporting URL");
|
|
45
|
+
}
|
|
46
|
+
if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash)
|
|
47
|
+
throw new Error(
|
|
48
|
+
"Reporting URL must be an HTTP(S) URL without credentials or fragment"
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const review = new Date(options.now ?? /* @__PURE__ */ new Date());
|
|
52
|
+
review.setUTCFullYear(review.getUTCFullYear() + 1);
|
|
53
|
+
const reviewBy = review.toISOString().slice(0, 10);
|
|
54
|
+
const policy = definePolicy({
|
|
55
|
+
...options.reportUri ? { reporting: { uri: options.reportUri } } : {},
|
|
56
|
+
base: {
|
|
57
|
+
default: [SELF],
|
|
58
|
+
scripts: [SELF, NONCE, STRICT_DYNAMIC],
|
|
59
|
+
objects: [NONE],
|
|
60
|
+
baseUri: [SELF],
|
|
61
|
+
frameAncestors: [NONE],
|
|
62
|
+
upgradeInsecureRequests: true
|
|
63
|
+
},
|
|
64
|
+
ruleSets: [
|
|
65
|
+
{
|
|
66
|
+
name: "App assets",
|
|
67
|
+
purpose: "Images used by the application",
|
|
68
|
+
owner: "TODO: assign owner",
|
|
69
|
+
reviewBy,
|
|
70
|
+
rules: { images: [SELF, "data:", "blob:"] }
|
|
71
|
+
},
|
|
72
|
+
...apiOrigins.length ? [
|
|
73
|
+
{
|
|
74
|
+
name: "App API",
|
|
75
|
+
purpose: "Application API connections",
|
|
76
|
+
owner: "TODO: assign owner",
|
|
77
|
+
reviewBy,
|
|
78
|
+
rules: { connect: apiOrigins }
|
|
79
|
+
}
|
|
80
|
+
] : []
|
|
81
|
+
]
|
|
82
|
+
});
|
|
83
|
+
const apiImport = apiOrigins.length ? `import { appApi } from './rule-sets/app-api';
|
|
84
|
+
` : "";
|
|
85
|
+
const reporting = options.reportUri ? ` reporting: { uri: ${JSON.stringify(options.reportUri)} },
|
|
86
|
+
` : "";
|
|
87
|
+
const apiTest = apiOrigins.length ? ` expect(policy).toAllow('connect', ${JSON.stringify(apiOrigins[0] + "/")}, { origin: 'https://site.example', redirectCount: 0 });
|
|
88
|
+
` : "";
|
|
89
|
+
const files = {
|
|
90
|
+
"csp.config.ts": `export { policy as default } from './csp/policy';
|
|
91
|
+
`,
|
|
92
|
+
"csp/policy.ts": `import { definePolicy, SELF, NONE, NONCE, STRICT_DYNAMIC } from '@jamesbrightman/pretty-csp';
|
|
93
|
+
import { appAssets } from './rule-sets/app-assets';
|
|
94
|
+
${apiImport}
|
|
95
|
+
export const policy = definePolicy({
|
|
96
|
+
${reporting} base: { default: [SELF], scripts: [SELF, NONCE, STRICT_DYNAMIC], objects: [NONE], baseUri: [SELF], frameAncestors: [NONE], upgradeInsecureRequests: true },
|
|
97
|
+
ruleSets: [appAssets${apiOrigins.length ? ", appApi" : ""}],
|
|
98
|
+
});
|
|
99
|
+
`,
|
|
100
|
+
"csp/rule-sets/app-assets.ts": `import { defineRuleSet, SELF } from '@jamesbrightman/pretty-csp';
|
|
101
|
+
|
|
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:'] } });
|
|
103
|
+
`,
|
|
104
|
+
"csp/policy.test.ts": `import { readFile } from 'node:fs/promises';
|
|
105
|
+
import { expect, test } from 'vitest';
|
|
106
|
+
import { cspMatchers } from '@jamesbrightman/pretty-csp/testing';
|
|
107
|
+
import { policy } from './policy';
|
|
108
|
+
|
|
109
|
+
expect.extend(cspMatchers);
|
|
110
|
+
test('blocks untrusted connections and has no high-risk findings', () => {
|
|
111
|
+
${apiTest} expect(policy).toBlock('connect', 'https://untrusted.example/', { origin: 'https://site.example', redirectCount: 0 });
|
|
112
|
+
expect(policy).toPassAudit({ maxSeverity: 'low' });
|
|
113
|
+
});
|
|
114
|
+
test('matches the reviewed CSP snapshot', async () => {
|
|
115
|
+
const snapshot = JSON.parse(await readFile(new URL('../csp.snapshot.json', import.meta.url), 'utf8'));
|
|
116
|
+
expect(policy).toMatchCspSnapshot(snapshot);
|
|
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
|
+
}
|
|
126
|
+
`,
|
|
127
|
+
"csp.snapshot.json": `${JSON.stringify(cspSnapshot(policy), null, 2)}
|
|
128
|
+
`
|
|
129
|
+
};
|
|
130
|
+
if (apiOrigins.length)
|
|
131
|
+
files["csp/rule-sets/app-api.ts"] = `import { defineRuleSet } from '@jamesbrightman/pretty-csp';
|
|
132
|
+
|
|
133
|
+
export const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API connections', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { connect: ${JSON.stringify(apiOrigins)} } });
|
|
134
|
+
`;
|
|
135
|
+
async function stat(path) {
|
|
136
|
+
try {
|
|
137
|
+
return await lstat(path);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error.code === "ENOENT") return void 0;
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
for (const directory of ["csp", "csp/rule-sets"]) {
|
|
144
|
+
const dir = await stat(join(cwd, directory));
|
|
145
|
+
if (dir?.isSymbolicLink() || dir && !dir.isDirectory())
|
|
146
|
+
throw new Error(`${directory} must be a directory and not a symlink`);
|
|
147
|
+
}
|
|
148
|
+
for (const file of Object.keys(files)) {
|
|
149
|
+
const current = await stat(join(cwd, file));
|
|
150
|
+
if (current?.isSymbolicLink() || current && !current.isFile())
|
|
151
|
+
throw new Error(`Refusing non-file or symlink: ${file}`);
|
|
152
|
+
if (current && !options.force)
|
|
153
|
+
throw new Error(
|
|
154
|
+
`File already exists: ${file}. Use --force to replace it.`
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
if (!options.dryRun) {
|
|
158
|
+
await mkdir(join(cwd, "csp/rule-sets"), { recursive: true });
|
|
159
|
+
for (const [file, content] of Object.entries(files))
|
|
160
|
+
await writeFile(join(cwd, file), content, {
|
|
161
|
+
encoding: "utf8",
|
|
162
|
+
flag: options.force ? "w" : "wx"
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
return Object.keys(files);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// src/cli/index.ts
|
|
169
|
+
var help = "Usage: pretty-csp <init|print|explain|audit|snapshot> [--config path] [options]";
|
|
170
|
+
var severities = {
|
|
171
|
+
info: 0,
|
|
172
|
+
low: 1,
|
|
173
|
+
medium: 2,
|
|
174
|
+
high: 3
|
|
175
|
+
};
|
|
176
|
+
function argsFor(args) {
|
|
177
|
+
const [command = "help", ...rest] = args;
|
|
178
|
+
const options = {};
|
|
179
|
+
const flags = /* @__PURE__ */ new Set([
|
|
180
|
+
"pretty",
|
|
181
|
+
"update",
|
|
182
|
+
"help",
|
|
183
|
+
"yes",
|
|
184
|
+
"dry-run",
|
|
185
|
+
"force"
|
|
186
|
+
]);
|
|
187
|
+
const values = /* @__PURE__ */ new Set([
|
|
188
|
+
"config",
|
|
189
|
+
"nonce",
|
|
190
|
+
"directive",
|
|
191
|
+
"rule-set",
|
|
192
|
+
"fail-on",
|
|
193
|
+
"file",
|
|
194
|
+
"api-origins",
|
|
195
|
+
"report-uri"
|
|
196
|
+
]);
|
|
197
|
+
for (let i = 0; i < rest.length; i++) {
|
|
198
|
+
const arg = rest[i];
|
|
199
|
+
if (!arg.startsWith("--")) throw new Error(`Unexpected argument: ${arg}`);
|
|
200
|
+
const key = arg.slice(2);
|
|
201
|
+
if (flags.has(key)) options[key] = true;
|
|
202
|
+
else if (values.has(key)) {
|
|
203
|
+
const value = rest[++i];
|
|
204
|
+
if (!value || value.startsWith("--"))
|
|
205
|
+
throw new Error(`--${key} requires a value`);
|
|
206
|
+
options[key] = value;
|
|
207
|
+
} else throw new Error(`Unknown option --${key}`);
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
command,
|
|
211
|
+
options
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
function option(options, name) {
|
|
215
|
+
return typeof options[name] === "string" ? options[name] : void 0;
|
|
216
|
+
}
|
|
217
|
+
function isPolicy(value) {
|
|
218
|
+
return !!value && typeof value === "object" && ["toHeader", "toObject", "explain", "allows"].every(
|
|
219
|
+
(key) => typeof value[key] === "function"
|
|
220
|
+
) && "config" in value;
|
|
221
|
+
}
|
|
222
|
+
async function loadConfigFile(path) {
|
|
223
|
+
if ([".ts", ".mts", ".cts"].includes(extname(path).toLowerCase())) {
|
|
224
|
+
const jiti = createJiti(path, { moduleCache: false, fsCache: false });
|
|
225
|
+
return await jiti.import(path);
|
|
226
|
+
}
|
|
227
|
+
return await import(pathToFileURL(path).href);
|
|
228
|
+
}
|
|
229
|
+
async function runCli(args, io, cwd = process.cwd(), loadConfig = loadConfigFile) {
|
|
230
|
+
try {
|
|
231
|
+
const { command, options } = argsFor(args);
|
|
232
|
+
if (command === "help" || command === "--help" || options.help) {
|
|
233
|
+
io.out(help);
|
|
234
|
+
return 0;
|
|
235
|
+
}
|
|
236
|
+
if (!["init", "print", "explain", "audit", "snapshot"].includes(command))
|
|
237
|
+
throw new Error(`Unsupported command: ${command}. ${help}`);
|
|
238
|
+
if (command === "init") {
|
|
239
|
+
if (!options.yes)
|
|
240
|
+
throw new Error(
|
|
241
|
+
"Use init --yes and optional --api-origins and --report-uri flags."
|
|
242
|
+
);
|
|
243
|
+
const files = await initProject(cwd, {
|
|
244
|
+
dryRun: Boolean(options["dry-run"]),
|
|
245
|
+
force: Boolean(options.force),
|
|
246
|
+
apiOrigins: option(options, "api-origins")?.split(",").map((origin) => origin.trim()),
|
|
247
|
+
reportUri: option(options, "report-uri")
|
|
248
|
+
});
|
|
249
|
+
io.out(
|
|
250
|
+
`${options["dry-run"] ? "Would write" : "Wrote"}:
|
|
251
|
+
${files.join("\n")}
|
|
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.`
|
|
253
|
+
);
|
|
254
|
+
return 0;
|
|
255
|
+
}
|
|
256
|
+
const path = resolve(cwd, option(options, "config") ?? "csp.config.ts");
|
|
257
|
+
const module = await loadConfig(path);
|
|
258
|
+
const candidate = module.default ?? module.policy;
|
|
259
|
+
const policy = candidate && typeof candidate === "object" && "policy" in candidate ? candidate.policy : candidate;
|
|
260
|
+
if (!isPolicy(policy))
|
|
261
|
+
throw new Error(
|
|
262
|
+
"Config must export a Policy as default, as policy, or as default.policy"
|
|
263
|
+
);
|
|
264
|
+
if (command === "print") {
|
|
265
|
+
io.out(
|
|
266
|
+
policy.toHeader({
|
|
267
|
+
...option(options, "nonce") ? { nonce: option(options, "nonce") } : {},
|
|
268
|
+
pretty: Boolean(options.pretty)
|
|
269
|
+
})
|
|
270
|
+
);
|
|
271
|
+
return 0;
|
|
272
|
+
}
|
|
273
|
+
if (command === "explain") {
|
|
274
|
+
const directive = option(options, "directive"), ruleSet = option(options, "rule-set");
|
|
275
|
+
const rows = policy.explain().filter(
|
|
276
|
+
(row) => (!directive || row.directive === directive) && (!ruleSet || row.ruleSet === ruleSet)
|
|
277
|
+
);
|
|
278
|
+
io.out(JSON.stringify(rows, null, 2));
|
|
279
|
+
return 0;
|
|
280
|
+
}
|
|
281
|
+
if (command === "audit") {
|
|
282
|
+
const threshold = option(options, "fail-on") ?? "high";
|
|
283
|
+
if (!Object.hasOwn(severities, threshold))
|
|
284
|
+
throw new Error("--fail-on must be high, medium, low or info");
|
|
285
|
+
const findings = audit(policy);
|
|
286
|
+
io.out(JSON.stringify(findings, null, 2));
|
|
287
|
+
return findings.some(
|
|
288
|
+
(finding) => severities[finding.severity] >= severities[threshold]
|
|
289
|
+
) ? 1 : 0;
|
|
290
|
+
}
|
|
291
|
+
const file = resolve(cwd, option(options, "file") ?? "csp.snapshot.json");
|
|
292
|
+
const expected = `${JSON.stringify(cspSnapshot(policy), null, 2)}
|
|
293
|
+
`;
|
|
294
|
+
if (options.update) {
|
|
295
|
+
await writeFile2(file, expected, "utf8");
|
|
296
|
+
io.out(`Updated ${file}`);
|
|
297
|
+
return 0;
|
|
298
|
+
}
|
|
299
|
+
let actual;
|
|
300
|
+
try {
|
|
301
|
+
actual = await readFile(file, "utf8");
|
|
302
|
+
} catch {
|
|
303
|
+
throw new Error(
|
|
304
|
+
`Snapshot not found: ${file}. Run snapshot --update to create it.`
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
if (actual !== expected) {
|
|
308
|
+
io.error(
|
|
309
|
+
"CSP snapshot differs. Review the policy and run snapshot --update."
|
|
310
|
+
);
|
|
311
|
+
return 1;
|
|
312
|
+
}
|
|
313
|
+
io.out("CSP snapshot matches.");
|
|
314
|
+
return 0;
|
|
315
|
+
} catch (error) {
|
|
316
|
+
io.error(error instanceof Error ? error.message : String(error));
|
|
317
|
+
return 1;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// src/cli/bin.ts
|
|
322
|
+
void runCli(process.argv.slice(2), {
|
|
323
|
+
out: (message) => console.log(message),
|
|
324
|
+
error: (message) => console.error(message)
|
|
325
|
+
}).then((code) => {
|
|
326
|
+
process.exitCode = code;
|
|
327
|
+
});
|
|
328
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/index.ts","../src/cli/init.ts","../src/cli/bin.ts"],"sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { resolve, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { createJiti } from 'jiti';\nimport { audit } from '../audit';\nimport type { Severity } from '../audit';\nimport type { Policy } from '../core';\nimport { cspSnapshot } from '../testing';\nimport { initProject } from './init';\n\nexport interface CliIo {\n out(message: string): void;\n error(message: string): void;\n}\nconst help =\n 'Usage: pretty-csp <init|print|explain|audit|snapshot> [--config path] [options]';\nconst severities: Record<Severity, number> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n};\nfunction argsFor(args: string[]): {\n command: string;\n options: Record<string, string | boolean>;\n} {\n const [command = 'help', ...rest] = args;\n const options: Record<string, string | boolean> = {};\n const flags = new Set([\n 'pretty',\n 'update',\n 'help',\n 'yes',\n 'dry-run',\n 'force',\n ]);\n const values = new Set([\n 'config',\n 'nonce',\n 'directive',\n 'rule-set',\n 'fail-on',\n 'file',\n 'api-origins',\n 'report-uri',\n ]);\n for (let i = 0; i < rest.length; i++) {\n const arg = rest[i]!;\n if (!arg.startsWith('--')) throw new Error(`Unexpected argument: ${arg}`);\n const key = arg.slice(2);\n if (flags.has(key)) options[key] = true;\n else if (values.has(key)) {\n const value = rest[++i];\n if (!value || value.startsWith('--'))\n throw new Error(`--${key} requires a value`);\n options[key] = value;\n } else throw new Error(`Unknown option --${key}`);\n }\n return {\n command,\n options,\n };\n}\nfunction option(\n options: Record<string, string | boolean>,\n name: string,\n): string | undefined {\n return typeof options[name] === 'string'\n ? (options[name] as string)\n : undefined;\n}\nfunction isPolicy(value: unknown): value is Policy {\n return (\n !!value &&\n typeof value === 'object' &&\n ['toHeader', 'toObject', 'explain', 'allows'].every(\n (key) =>\n typeof (value as unknown as Record<string, unknown>)[key] ===\n 'function',\n ) &&\n 'config' in value\n );\n}\n/** Load only trusted project configuration: imports execute with the user's permissions. */\nexport async function loadConfigFile(\n path: string,\n): Promise<{ default?: unknown; policy?: unknown }> {\n if (['.ts', '.mts', '.cts'].includes(extname(path).toLowerCase())) {\n const jiti = createJiti(path, { moduleCache: false, fsCache: false });\n return (await jiti.import(path)) as { default?: unknown; policy?: unknown };\n }\n return (await import(pathToFileURL(path).href)) as {\n default?: unknown;\n policy?: unknown;\n };\n}\n/** Runs a command; config is executable code and must come from a trusted project. */\nexport async function runCli(\n args: string[],\n io: CliIo,\n cwd = process.cwd(),\n loadConfig: (\n path: string,\n ) => Promise<{ default?: unknown; policy?: unknown }> = loadConfigFile,\n): Promise<number> {\n try {\n const { command, options } = argsFor(args);\n if (command === 'help' || command === '--help' || options.help) {\n io.out(help);\n return 0;\n }\n if (!['init', 'print', 'explain', 'audit', 'snapshot'].includes(command))\n throw new Error(`Unsupported command: ${command}. ${help}`);\n if (command === 'init') {\n if (!options.yes)\n throw new Error(\n 'Use init --yes and optional --api-origins and --report-uri flags.',\n );\n const files = await initProject(cwd, {\n dryRun: Boolean(options['dry-run']),\n force: Boolean(options.force),\n apiOrigins: option(options, 'api-origins')\n ?.split(',')\n .map((origin) => origin.trim()),\n reportUri: option(options, 'report-uri'),\n });\n io.out(\n `${options['dry-run'] ? 'Would write' : 'Wrote'}:\\n${files.join('\\n')}\\nInstall @jamesbrightman/pretty-csp and Vitest, then configure your server to set the Content-Security-Policy response header with policy.toHeader({ nonce }) on each response.`,\n );\n return 0;\n }\n const path = resolve(cwd, option(options, 'config') ?? 'csp.config.ts');\n const module = await loadConfig(path);\n const candidate = module.default ?? module.policy;\n const policy: unknown =\n candidate && typeof candidate === 'object' && 'policy' in candidate\n ? candidate.policy\n : candidate;\n if (!isPolicy(policy))\n throw new Error(\n 'Config must export a Policy as default, as policy, or as default.policy',\n );\n if (command === 'print') {\n io.out(\n policy.toHeader({\n ...(option(options, 'nonce')\n ? { nonce: option(options, 'nonce') }\n : {}),\n pretty: Boolean(options.pretty),\n }),\n );\n return 0;\n }\n if (command === 'explain') {\n const directive = option(options, 'directive'),\n ruleSet = option(options, 'rule-set');\n const rows = policy\n .explain()\n .filter(\n (row) =>\n (!directive || row.directive === directive) &&\n (!ruleSet || row.ruleSet === ruleSet),\n );\n io.out(JSON.stringify(rows, null, 2));\n return 0;\n }\n if (command === 'audit') {\n const threshold = option(options, 'fail-on') ?? 'high';\n if (!Object.hasOwn(severities, threshold))\n throw new Error('--fail-on must be high, medium, low or info');\n const findings = audit(policy);\n io.out(JSON.stringify(findings, null, 2));\n return findings.some(\n (finding) =>\n severities[finding.severity] >= severities[threshold as Severity],\n )\n ? 1\n : 0;\n }\n const file = resolve(cwd, option(options, 'file') ?? 'csp.snapshot.json');\n const expected = `${JSON.stringify(cspSnapshot(policy), null, 2)}\\n`;\n if (options.update) {\n await writeFile(file, expected, 'utf8');\n io.out(`Updated ${file}`);\n return 0;\n }\n let actual: string;\n try {\n actual = await readFile(file, 'utf8');\n } catch {\n throw new Error(\n `Snapshot not found: ${file}. Run snapshot --update to create it.`,\n );\n }\n if (actual !== expected) {\n io.error(\n 'CSP snapshot differs. Review the policy and run snapshot --update.',\n );\n return 1;\n }\n io.out('CSP snapshot matches.');\n return 0;\n } catch (error) {\n io.error(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n","import { lstat, mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { definePolicy } from '../core';\nimport { SELF, NONE, NONCE, STRICT_DYNAMIC } from '../keywords';\nimport { cspSnapshot } from '../testing';\n\nexport interface InitOptions {\n force?: boolean;\n dryRun?: boolean;\n now?: Date;\n apiOrigins?: readonly string[];\n reportUri?: string;\n}\n/** Create a small TypeScript starter. Existing paths require force and symlinks are rejected. */\nexport async function initProject(\n cwd: string,\n options: InitOptions = {},\n): Promise<string[]> {\n const apiOrigins = [...new Set(options.apiOrigins ?? [])];\n for (const origin of apiOrigins) {\n let parsed: URL;\n try {\n parsed = new URL(origin);\n } catch {\n throw new Error(`Invalid API origin: ${origin}`);\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.origin !== origin\n )\n throw new Error(\n `API origins must be HTTP(S) origins without paths, credentials or trailing slash: ${origin}`,\n );\n }\n if (options.reportUri) {\n let parsed: URL;\n try {\n parsed = new URL(options.reportUri);\n } catch {\n throw new Error('Invalid reporting URL');\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n )\n throw new Error(\n 'Reporting URL must be an HTTP(S) URL without credentials or fragment',\n );\n }\n const review = new Date(options.now ?? new Date());\n review.setUTCFullYear(review.getUTCFullYear() + 1);\n const reviewBy = review.toISOString().slice(0, 10);\n const policy = definePolicy({\n ...(options.reportUri ? { reporting: { uri: options.reportUri } } : {}),\n base: {\n default: [SELF],\n scripts: [SELF, NONCE, STRICT_DYNAMIC],\n objects: [NONE],\n baseUri: [SELF],\n frameAncestors: [NONE],\n upgradeInsecureRequests: true,\n },\n ruleSets: [\n {\n name: 'App assets',\n purpose: 'Images used by the application',\n owner: 'TODO: assign owner',\n reviewBy,\n rules: { images: [SELF, 'data:', 'blob:'] },\n },\n ...(apiOrigins.length\n ? [\n {\n name: 'App API',\n purpose: 'Application API connections',\n owner: 'TODO: assign owner',\n reviewBy,\n rules: { connect: apiOrigins },\n },\n ]\n : []),\n ],\n });\n const apiImport = apiOrigins.length\n ? `import { appApi } from './rule-sets/app-api';\\n`\n : '';\n const reporting = options.reportUri\n ? ` reporting: { uri: ${JSON.stringify(options.reportUri)} },\\n`\n : '';\n const apiTest = apiOrigins.length\n ? ` expect(policy).toAllow('connect', ${JSON.stringify(apiOrigins[0] + '/')}, { origin: 'https://site.example', redirectCount: 0 });\\n`\n : '';\n const files: Record<string, string> = {\n 'csp.config.ts': `export { policy as default } from './csp/policy';\\n`,\n 'csp/policy.ts': `import { definePolicy, SELF, NONE, NONCE, STRICT_DYNAMIC } from '@jamesbrightman/pretty-csp';\\nimport { appAssets } from './rule-sets/app-assets';\\n${apiImport}\\nexport const policy = definePolicy({\\n${reporting} base: { default: [SELF], scripts: [SELF, NONCE, STRICT_DYNAMIC], objects: [NONE], baseUri: [SELF], frameAncestors: [NONE], upgradeInsecureRequests: true },\\n ruleSets: [appAssets${apiOrigins.length ? ', appApi' : ''}],\\n});\\n`,\n 'csp/rule-sets/app-assets.ts': `import { defineRuleSet, SELF } from '@jamesbrightman/pretty-csp';\\n\\nexport const appAssets = defineRuleSet({ name: 'App assets', purpose: 'Images used by the application', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { images: [SELF, 'data:', 'blob:'] } });\\n`,\n 'csp/policy.test.ts': `import { readFile } from 'node:fs/promises';\\nimport { expect, test } from 'vitest';\\nimport { cspMatchers } from '@jamesbrightman/pretty-csp/testing';\\nimport { policy } from './policy';\\n\\nexpect.extend(cspMatchers);\\ntest('blocks untrusted connections and has no high-risk findings', () => {\\n${apiTest} expect(policy).toBlock('connect', 'https://untrusted.example/', { origin: 'https://site.example', redirectCount: 0 });\\n expect(policy).toPassAudit({ maxSeverity: 'low' });\\n});\\ntest('matches the reviewed CSP snapshot', async () => {\\n const snapshot = JSON.parse(await readFile(new URL('../csp.snapshot.json', import.meta.url), 'utf8'));\\n expect(policy).toMatchCspSnapshot(snapshot);\\n});\\n`,\n 'csp/vitest.d.ts': `import 'vitest';\\nimport type { CspAssertions } from '@jamesbrightman/pretty-csp/testing';\\n\\ndeclare module 'vitest' {\\n interface Assertion<T> extends CspAssertions<T> {}\\n interface AsymmetricMatchersContaining extends CspAssertions {}\\n}\\n`,\n 'csp.snapshot.json': `${JSON.stringify(cspSnapshot(policy), null, 2)}\\n`,\n };\n if (apiOrigins.length)\n files['csp/rule-sets/app-api.ts'] =\n `import { defineRuleSet } from '@jamesbrightman/pretty-csp';\\n\\nexport const appApi = defineRuleSet({ name: 'App API', purpose: 'Application API connections', owner: 'TODO: assign owner', reviewBy: '${reviewBy}', rules: { connect: ${JSON.stringify(apiOrigins)} } });\\n`;\n async function stat(path: string) {\n try {\n return await lstat(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n }\n for (const directory of ['csp', 'csp/rule-sets']) {\n const dir = await stat(join(cwd, directory));\n if (dir?.isSymbolicLink() || (dir && !dir.isDirectory()))\n throw new Error(`${directory} must be a directory and not a symlink`);\n }\n for (const file of Object.keys(files)) {\n const current = await stat(join(cwd, file));\n if (current?.isSymbolicLink() || (current && !current.isFile()))\n throw new Error(`Refusing non-file or symlink: ${file}`);\n if (current && !options.force)\n throw new Error(\n `File already exists: ${file}. Use --force to replace it.`,\n );\n }\n if (!options.dryRun) {\n await mkdir(join(cwd, 'csp/rule-sets'), { recursive: true });\n for (const [file, content] of Object.entries(files))\n await writeFile(join(cwd, file), content, {\n encoding: 'utf8',\n flag: options.force ? 'w' : 'wx',\n });\n }\n return Object.keys(files);\n}\n","#!/usr/bin/env node\nimport { runCli } from './index';\n\nvoid runCli(process.argv.slice(2), {\n out: (message) => console.log(message),\n error: (message) => console.error(message),\n}).then((code) => {\n process.exitCode = code;\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,UAAU,aAAAA,kBAAiB;AACpC,SAAS,SAAS,eAAe;AACjC,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;;;ACH3B,SAAS,OAAO,OAAO,iBAAiB;AACxC,SAAS,YAAY;AAarB,eAAsB,YACpB,KACA,UAAuB,CAAC,GACL;AACnB,QAAM,aAAa,CAAC,GAAG,IAAI,IAAI,QAAQ,cAAc,CAAC,CAAC,CAAC;AACxD,aAAW,UAAU,YAAY;AAC/B,QAAI;AACJ,QAAI;AACF,eAAS,IAAI,IAAI,MAAM;AAAA,IACzB,QAAQ;AACN,YAAM,IAAI,MAAM,uBAAuB,MAAM,EAAE;AAAA,IACjD;AACA,QACE,CAAC,CAAC,SAAS,QAAQ,EAAE,SAAS,OAAO,QAAQ,KAC7C,OAAO,YACP,OAAO,YACP,OAAO,WAAW;AAElB,YAAM,IAAI;AAAA,QACR,qFAAqF,MAAM;AAAA,MAC7F;AAAA,EACJ;AACA,MAAI,QAAQ,WAAW;AACrB,QAAI;AACJ,QAAI;AACF,eAAS,IAAI,IAAI,QAAQ,SAAS;AAAA,IACpC,QAAQ;AACN,YAAM,IAAI,MAAM,uBAAuB;AAAA,IACzC;AACA,QACE,CAAC,CAAC,SAAS,QAAQ,EAAE,SAAS,OAAO,QAAQ,KAC7C,OAAO,YACP,OAAO,YACP,OAAO;AAEP,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,EACJ;AACA,QAAM,SAAS,IAAI,KAAK,QAAQ,OAAO,oB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