@jamesbrightman/pretty-csp 0.0.0-stage → 0.1.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 +11 -0
- package/LICENSE +21 -0
- package/README.md +76 -2
- package/dist/chunk-KWWYRHIP.js +224 -0
- package/dist/chunk-KWWYRHIP.js.map +1 -0
- package/dist/chunk-MDUQKU6Y.js +67 -0
- package/dist/chunk-MDUQKU6Y.js.map +1 -0
- package/dist/chunk-TE3J7Y25.js +875 -0
- package/dist/chunk-TE3J7Y25.js.map +1 -0
- package/dist/cli.cjs +1667 -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 +637 -0
- package/dist/cli.js.map +1 -0
- package/dist/index-D6PmUWjD.d.cts +451 -0
- package/dist/index-D6PmUWjD.d.ts +451 -0
- package/dist/index.cjs +1146 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +79 -0
- package/dist/index.d.ts +79 -0
- package/dist/index.js +57 -0
- package/dist/index.js.map +1 -0
- package/dist/testing.cjs +310 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +35 -0
- package/dist/testing.d.ts +35 -0
- package/dist/testing.js +10 -0
- package/dist/testing.js.map +1 -0
- package/package.json +91 -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.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/index.ts","../src/cli/init.ts","../src/cli/import.ts","../src/cli/diff.ts","../src/cli/bin.ts"],"sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\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';\nimport { importDraftFiles, writeImportDraft } from './import';\nimport { diffSnapshot, readGitSnapshot } from './diff';\nimport { importHeader, importedPolicyToDraft } from '../importer';\nimport { parseViolationReports, replayReports } from '../reports';\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|diff|import|check-reports> [--config path] [options]';\nconst importHelp =\n 'Usage: pretty-csp import <header> | --file <header-file> [--output <new-directory> [--dry-run] [--mode <report-only|enforce>]]';\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 positional?: string;\n} {\n const [command = 'help', ...rest] = args;\n const options: Record<string, string | boolean> = {};\n let positional: string | undefined;\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 'output',\n 'base',\n 'language',\n 'api-origins',\n 'report-uri',\n 'mode',\n ]);\n for (let i = 0; i < rest.length; i++) {\n const arg = rest[i]!;\n if (!arg.startsWith('--')) {\n if (\n !['import', 'check-reports'].includes(command) ||\n positional !== undefined\n )\n throw new Error(`Unexpected argument: ${arg}`);\n positional = arg;\n continue;\n }\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 ...(positional === undefined ? {} : { positional }),\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, positional } = argsFor(args);\n if (command === 'help' || options.help) {\n io.out(command === 'import' ? importHelp : help);\n return 0;\n }\n if (\n ![\n 'init',\n 'print',\n 'explain',\n 'audit',\n 'snapshot',\n 'diff',\n 'import',\n 'check-reports',\n ].includes(command)\n )\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 --language, --api-origins, --report-uri and --mode flags.',\n );\n const files = await initProject(cwd, {\n dryRun: Boolean(options['dry-run']),\n force: Boolean(options.force),\n language: option(options, 'language') as\n 'javascript' | 'typescript' | undefined,\n mode: option(options, 'mode') as 'enforce' | 'report-only' | undefined,\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 policy.headerName and policy.toHeader({ nonce }) on each response.`,\n );\n return 0;\n }\n if (command === 'import') {\n const headerFile = option(options, 'file');\n const output = option(options, 'output');\n if ((!positional && !headerFile) || (positional && headerFile))\n throw new Error(\n 'import requires a header string or --file, but not both',\n );\n if (!output && (options['dry-run'] || options.mode))\n throw new Error('--dry-run and --mode require --output for import');\n if (options.force)\n throw new Error(\n 'Import requires a new output directory. --force is not supported.',\n );\n const header = headerFile\n ? (await readFile(resolve(cwd, headerFile), 'utf8')).replace(\n /\\r?\\n$/,\n '',\n )\n : positional!;\n const parsed = importHeader(header);\n const draft = importedPolicyToDraft(parsed);\n if (output) {\n const mode = option(options, 'mode') ?? 'report-only';\n if (mode !== 'enforce' && mode !== 'report-only')\n throw new Error('--mode must be enforce or report-only');\n const files = importDraftFiles(draft, mode);\n const destination = resolve(cwd, output);\n if (!options['dry-run']) await writeImportDraft(destination, files);\n io.out(\n `${options['dry-run'] ? 'Would write to' : 'Wrote to'} ${destination}:\\n${Array.from(files.keys()).join('\\n')}\\nReview the draft and assign owners before use.`,\n );\n return 0;\n }\n io.out(\n JSON.stringify(\n {\n draft,\n warnings: parsed.warnings,\n note: 'Review the draft before saving; no files were written.',\n },\n null,\n 2,\n ),\n );\n return 0;\n }\n const defaultConfig = existsSync(resolve(cwd, 'csp.config.ts'))\n ? 'csp.config.ts'\n : 'csp.config.mjs';\n const path = resolve(cwd, option(options, 'config') ?? defaultConfig);\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 === 'diff') {\n const ref = option(options, 'base');\n if (!ref)\n throw new Error(\n 'diff requires --base <git-ref> and a committed csp.snapshot.json at the repository root',\n );\n const result = diffSnapshot(await readGitSnapshot(ref, cwd), policy);\n io.out(JSON.stringify(result, null, 2));\n return 0;\n }\n if (command === 'check-reports') {\n if (!positional) throw new Error('check-reports requires a JSON file');\n const contents = await readFile(resolve(cwd, positional), 'utf8');\n const results = replayReports(\n policy.toObject(),\n parseViolationReports(contents),\n );\n io.out(JSON.stringify(results, null, 2));\n return results.some(({ result }) => result.status !== 'allowed') ? 1 : 0;\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 { sourceExpressions } from '../keywords';\nimport { cspSnapshot } from '../testing';\n\nexport interface InitOptions {\n force?: boolean;\n dryRun?: boolean;\n now?: Date;\n language?: 'javascript' | 'typescript';\n apiOrigins?: readonly string[];\n reportUri?: string;\n mode?: 'enforce' | 'report-only';\n}\n/** Create a small owned JS starter. Existing paths require force and symlinks are rejected. */\nexport async function initProject(\n cwd: string,\n options: InitOptions = {},\n): Promise<string[]> {\n const language = options.language ?? 'javascript';\n if (!['javascript', 'typescript'].includes(language))\n throw new Error('language must be javascript or typescript');\n const mode = options.mode ?? 'report-only';\n if (!['enforce', 'report-only'].includes(mode))\n throw new Error('mode must be enforce or report-only');\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 mode,\n ...(options.reportUri ? { reporting: { uri: options.reportUri } } : {}),\n base: {\n default: [sourceExpressions.self],\n scripts: [\n sourceExpressions.self,\n sourceExpressions.nonce,\n sourceExpressions.strictDynamic,\n ],\n objects: [sourceExpressions.none],\n baseUri: [sourceExpressions.self],\n frameAncestors: [sourceExpressions.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: [sourceExpressions.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 extension = language === 'typescript' ? 'ts' : 'mjs';\n const importExtension = language === 'typescript' ? '' : '.mjs';\n const apiImport = apiOrigins.length\n ? `import { appApi } from './rule-sets/app-api${importExtension}';\\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.${extension}`]: `export { policy as default } from './csp/policy${importExtension}';\\n`,\n [`csp/policy.${extension}`]: `import { definePolicy, sourceExpressions } from '@jamesbrightman/pretty-csp';\\nimport { appAssets } from './rule-sets/app-assets${importExtension}';\\n${apiImport}\\nexport const policy = definePolicy({\\n mode: ${JSON.stringify(mode)},\\n${reporting} base: { default: [sourceExpressions.self], scripts: [sourceExpressions.self, sourceExpressions.nonce, sourceExpressions.strictDynamic], objects: [sourceExpressions.none], baseUri: [sourceExpressions.self], frameAncestors: [sourceExpressions.none], upgradeInsecureRequests: true },\\n ruleSets: [appAssets${apiOrigins.length ? ', appApi' : ''}],\\n});\\n`,\n [`csp/rule-sets/app-assets.${extension}`]: `import { defineRuleSet, sourceExpressions } 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: [sourceExpressions.self, 'data:', 'blob:'] } });\\n`,\n [`csp/policy.test.${extension}`]: `import { readFile } from 'node:fs/promises';\\nimport { expect, test } from 'vitest';\\nimport { cspMatchers, cspSnapshot } from '@jamesbrightman/pretty-csp/testing';\\nimport { policy } from './policy${importExtension}';\\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.snapshot.json': `${JSON.stringify(cspSnapshot(policy), null, 2)}\\n`,\n };\n if (apiOrigins.length)\n files[`csp/rule-sets/app-api.${extension}`] =\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","import { mkdir, open, rmdir, unlink } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { parse } from 'tldts';\nimport type { PolicyConfig, RuleSetInput, SourceEntry } from '../schemas';\n\ntype SourceLists = Record<string, SourceEntry[]>;\ntype ImportMode = NonNullable<PolicyConfig['mode']>;\n\nfunction registrableDomain(source: string): string | undefined {\n const host =\n /^(?:[a-z][a-z0-9+.-]*:\\/\\/)?(?:\\*\\.)?([a-z0-9-]+(?:\\.[a-z0-9-]+)+)(?=[:/]|$)/i.exec(\n source,\n )?.[1];\n if (!host) return undefined;\n\n const { domain, isIcann, isPrivate } = parse(host, {\n allowPrivateDomains: true,\n });\n return domain && (isIcann || isPrivate) ? domain.toLowerCase() : undefined;\n}\n\n/** Split the validated draft by domain without changing its source expressions. */\nexport function importDraftFiles(\n draft: PolicyConfig,\n mode: ImportMode,\n): Map<string, string> {\n const groups = new Map<string, SourceLists>();\n const unassigned: SourceLists = {};\n for (const [directive, entries] of Object.entries(\n draft.base?.directives ?? {},\n )) {\n rejectCapturedNonces(entries, directive);\n }\n for (const ruleSet of draft.ruleSets ?? []) {\n for (const [directive, entries] of Object.entries(\n ruleSet.rules.directives ?? {},\n )) {\n rejectCapturedNonces(entries, directive);\n for (const entry of entries) {\n const domain = registrableDomain(\n typeof entry === 'string' ? entry : entry.source,\n );\n let directives = unassigned;\n if (domain) {\n directives = groups.get(domain) ?? {};\n groups.set(domain, directives);\n }\n (directives[directive] ??= []).push(entry);\n }\n }\n }\n\n const files = new Map<string, string>();\n const imports: string[] = [];\n const names: string[] = [];\n const addRuleSet = (filename: string, ruleSet: RuleSetInput) => {\n const path = `rule-sets/${filename}.mjs`;\n const name = `ruleSet${names.length + 1}`;\n files.set(\n path,\n `import { defineRuleSet } from '@jamesbrightman/pretty-csp';\\n\\nexport default defineRuleSet(${JSON.stringify(ruleSet, null, 2)});\\n`,\n );\n imports.push(`import ${name} from './${path}';`);\n names.push(name);\n };\n const sortedGroups = Array.from(groups).sort(([first], [second]) =>\n first.localeCompare(second, 'en'),\n );\n for (const [domain, directives] of sortedGroups) {\n addRuleSet(`domain-${domain}`, {\n name: domain,\n purpose: 'Imported domain group. Confirm purpose and owner before use.',\n rules: { directives },\n });\n }\n if (Object.keys(unassigned).length) {\n addRuleSet('unassigned', {\n name: 'Unassigned sources',\n purpose: 'Imported sources that need manual grouping and review.',\n rules: { directives: unassigned },\n });\n }\n files.set(\n 'csp.config.mjs',\n [\n \"import { definePolicy } from '@jamesbrightman/pretty-csp';\",\n ...imports,\n '',\n '// Review this draft before using it in an application.',\n 'export default definePolicy({',\n ` mode: ${JSON.stringify(mode)},`,\n ` base: ${JSON.stringify(draft.base ?? {}, null, 2).replace(/\\n/g, '\\n ')},`,\n ` ruleSets: [${names.join(', ')}],`,\n '});',\n '',\n ].join('\\n'),\n );\n return files;\n}\n\nfunction rejectCapturedNonces(entries: SourceEntry[], directive: string) {\n if (\n entries.some((entry) =>\n /^'nonce-/i.test(typeof entry === 'string' ? entry : entry.source),\n )\n ) {\n throw new Error(\n `Directive ${directive} contains a captured nonce. Migrate it separately using a fresh nonce per response.`,\n );\n }\n}\n\n/** Create a new output directory exclusively. Existing paths are never replaced. */\nexport async function writeImportDraft(\n output: string,\n files: ReadonlyMap<string, string>,\n): Promise<void> {\n try {\n await mkdir(output);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST')\n throw new Error(\n `Import output already exists: ${output}. Choose a new directory.`,\n );\n throw error;\n }\n\n const createdFiles: string[] = [];\n let createdRuleSets = false;\n try {\n if (files.size > 1) {\n await mkdir(join(output, 'rule-sets'));\n createdRuleSets = true;\n }\n for (const [name, content] of files) {\n const path = join(output, name);\n const file = await open(path, 'wx');\n createdFiles.push(path);\n try {\n await file.writeFile(content, 'utf8');\n } finally {\n await file.close();\n }\n }\n } catch (error) {\n try {\n for (const path of createdFiles) await unlink(path);\n if (createdRuleSets) await rmdir(join(output, 'rule-sets'));\n await rmdir(output);\n } catch {\n throw new Error(\n `Import failed and may have left partial files in ${output}`,\n { cause: error },\n );\n }\n throw error;\n }\n}\n","import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { z } from 'zod';\nimport { diffPolicies } from '../diff';\nimport type { Policy } from '../core';\nimport type { PolicyDiff } from '../diff';\n\nconst snapshotSchema = z\n .object({\n schemaVersion: z.literal(1),\n mode: z.enum(['enforce', 'report-only']),\n directives: z.record(\n z.string().regex(/^[a-z][a-z0-9-]*$/),\n z.array(z.string()),\n ),\n contributors: z.array(\n z\n .object({\n directive: z.string(),\n source: z.string(),\n ruleSet: z.string(),\n reason: z.string().optional(),\n })\n .strict(),\n ),\n })\n .strict();\n/** Read a committed snapshot without executing code from the referenced revision. */\nexport async function readGitSnapshot(\n ref: string,\n cwd: string,\n): Promise<string> {\n if (!/^[a-zA-Z0-9][a-zA-Z0-9._/~^-]*$/.test(ref))\n throw new Error('Invalid Git ref');\n const exec = promisify(execFile);\n try {\n const { stdout } = await exec(\n 'git',\n ['show', '--no-ext-diff', '--no-textconv', `${ref}:csp.snapshot.json`],\n { cwd, maxBuffer: 4 * 1024 * 1024, encoding: 'utf8' },\n );\n return stdout;\n } catch {\n throw new Error(\n 'Could not read csp.snapshot.json at the Git ref; commit a version 1 snapshot at the repository root.',\n );\n }\n}\n/** Validate a versioned untrusted snapshot and compare without loading code from it. */\nexport function diffSnapshot(json: string, current: Policy): PolicyDiff {\n let data: unknown;\n try {\n data = JSON.parse(json) as unknown;\n } catch {\n throw new Error('Invalid snapshot JSON');\n }\n const parsed = snapshotSchema.safeParse(data);\n if (!parsed.success)\n throw new Error('Invalid or unsupported CSP snapshot format');\n const snapshot = parsed.data;\n for (const row of snapshot.contributors) {\n if (!snapshot.directives[row.directive]?.includes(row.source))\n throw new Error('Snapshot contributor does not match a directive source');\n }\n for (const [directive, sources] of Object.entries(snapshot.directives)) {\n if (directive === 'report-uri' || directive === 'report-to') continue;\n for (const source of sources) {\n if (\n !snapshot.contributors.some(\n (row) => row.directive === directive && row.source === source,\n )\n )\n throw new Error('Snapshot source has no contributor');\n }\n }\n // diffPolicies only reads these three values; the adapter never executes snapshot code.\n const previous = {\n config: { mode: snapshot.mode },\n toObject: () => snapshot.directives,\n explain: () => snapshot.contributors,\n } as unknown as Policy;\n return diffPolicies(previous, current);\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,kBAAkB;AAC3B,SAAS,SAAS,eAAe;AACjC,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;;;ACJ3B,SAAS,OAAO,OAAO,iBAAiB;AACxC,SAAS,YAAY;AAerB,eAAsB,YACpB,KACA,UAAuB,CAAC,GACL;AACnB,QAAM,WAAW,QAAQ,YAAY;AACrC,MAAI,CAAC,CAAC,cAAc,YAAY,EAAE,SAAS,QAAQ;AACjD,UAAM,IAAI,MAAM,2CAA2C;AAC7D,QAAM,OAAO,QAAQ,QAAQ;AAC7B,MAAI,CAAC,CAAC,WAAW,aAAa,EAAE,SAAS,IAAI;AAC3C,UAAM,IAAI,MAAM,qCAAqC;AACvD,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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AC,SAAS;AAChB,UAAQ,WAAW;AACrB,CAAC;","names":["writeFile","mkdir","join","writeFile"]}
|
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/** Friendly resource names mapped to CSP directives. */
|
|
4
|
+
declare const resourceDirectives: {
|
|
5
|
+
readonly scripts: "script-src";
|
|
6
|
+
readonly connect: "connect-src";
|
|
7
|
+
readonly images: "img-src";
|
|
8
|
+
readonly styles: "style-src";
|
|
9
|
+
readonly fonts: "font-src";
|
|
10
|
+
readonly frames: "frame-src";
|
|
11
|
+
readonly forms: "form-action";
|
|
12
|
+
readonly media: "media-src";
|
|
13
|
+
readonly workers: "worker-src";
|
|
14
|
+
readonly manifest: "manifest-src";
|
|
15
|
+
};
|
|
16
|
+
declare const baseDirectives: {
|
|
17
|
+
readonly default: "default-src";
|
|
18
|
+
readonly objects: "object-src";
|
|
19
|
+
readonly baseUri: "base-uri";
|
|
20
|
+
readonly frameAncestors: "frame-ancestors";
|
|
21
|
+
};
|
|
22
|
+
/** Nonce placeholder, replaced only when rendering a header. */
|
|
23
|
+
declare const NONCE_PLACEHOLDER = "'nonce-{nonce}'";
|
|
24
|
+
/** A source string, or a source annotated with a human-readable reason. Risky keywords require a reason. */
|
|
25
|
+
declare const sourceEntrySchema: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
26
|
+
source: z.ZodString;
|
|
27
|
+
reason: z.ZodString;
|
|
28
|
+
}, z.core.$strict>]>;
|
|
29
|
+
/** Rule-set permissions. At least one directive must be supplied. */
|
|
30
|
+
declare const rulesSchema: z.ZodObject<{
|
|
31
|
+
directives: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
32
|
+
source: z.ZodString;
|
|
33
|
+
reason: z.ZodString;
|
|
34
|
+
}, z.core.$strict>]>>>>;
|
|
35
|
+
scripts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
36
|
+
source: z.ZodString;
|
|
37
|
+
reason: z.ZodString;
|
|
38
|
+
}, z.core.$strict>]>>>;
|
|
39
|
+
connect: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
40
|
+
source: z.ZodString;
|
|
41
|
+
reason: z.ZodString;
|
|
42
|
+
}, z.core.$strict>]>>>;
|
|
43
|
+
images: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
44
|
+
source: z.ZodString;
|
|
45
|
+
reason: z.ZodString;
|
|
46
|
+
}, z.core.$strict>]>>>;
|
|
47
|
+
styles: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
48
|
+
source: z.ZodString;
|
|
49
|
+
reason: z.ZodString;
|
|
50
|
+
}, z.core.$strict>]>>>;
|
|
51
|
+
fonts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
52
|
+
source: z.ZodString;
|
|
53
|
+
reason: z.ZodString;
|
|
54
|
+
}, z.core.$strict>]>>>;
|
|
55
|
+
frames: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
56
|
+
source: z.ZodString;
|
|
57
|
+
reason: z.ZodString;
|
|
58
|
+
}, z.core.$strict>]>>>;
|
|
59
|
+
forms: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
60
|
+
source: z.ZodString;
|
|
61
|
+
reason: z.ZodString;
|
|
62
|
+
}, z.core.$strict>]>>>;
|
|
63
|
+
media: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
64
|
+
source: z.ZodString;
|
|
65
|
+
reason: z.ZodString;
|
|
66
|
+
}, z.core.$strict>]>>>;
|
|
67
|
+
workers: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
68
|
+
source: z.ZodString;
|
|
69
|
+
reason: z.ZodString;
|
|
70
|
+
}, z.core.$strict>]>>>;
|
|
71
|
+
manifest: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
72
|
+
source: z.ZodString;
|
|
73
|
+
reason: z.ZodString;
|
|
74
|
+
}, z.core.$strict>]>>>;
|
|
75
|
+
}, z.core.$strict>;
|
|
76
|
+
/** Site-wide directives. */
|
|
77
|
+
declare const baseSchema: z.ZodObject<{
|
|
78
|
+
default: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
79
|
+
source: z.ZodString;
|
|
80
|
+
reason: z.ZodString;
|
|
81
|
+
}, z.core.$strict>]>>>;
|
|
82
|
+
objects: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
83
|
+
source: z.ZodString;
|
|
84
|
+
reason: z.ZodString;
|
|
85
|
+
}, z.core.$strict>]>>>;
|
|
86
|
+
baseUri: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
87
|
+
source: z.ZodString;
|
|
88
|
+
reason: z.ZodString;
|
|
89
|
+
}, z.core.$strict>]>>>;
|
|
90
|
+
frameAncestors: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
91
|
+
source: z.ZodString;
|
|
92
|
+
reason: z.ZodString;
|
|
93
|
+
}, z.core.$strict>]>>>;
|
|
94
|
+
upgradeInsecureRequests: z.ZodOptional<z.ZodBoolean>;
|
|
95
|
+
directives: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
96
|
+
source: z.ZodString;
|
|
97
|
+
reason: z.ZodString;
|
|
98
|
+
}, z.core.$strict>]>>>>;
|
|
99
|
+
scripts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
100
|
+
source: z.ZodString;
|
|
101
|
+
reason: z.ZodString;
|
|
102
|
+
}, z.core.$strict>]>>>;
|
|
103
|
+
connect: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
104
|
+
source: z.ZodString;
|
|
105
|
+
reason: z.ZodString;
|
|
106
|
+
}, z.core.$strict>]>>>;
|
|
107
|
+
images: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
108
|
+
source: z.ZodString;
|
|
109
|
+
reason: z.ZodString;
|
|
110
|
+
}, z.core.$strict>]>>>;
|
|
111
|
+
styles: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
112
|
+
source: z.ZodString;
|
|
113
|
+
reason: z.ZodString;
|
|
114
|
+
}, z.core.$strict>]>>>;
|
|
115
|
+
fonts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
116
|
+
source: z.ZodString;
|
|
117
|
+
reason: z.ZodString;
|
|
118
|
+
}, z.core.$strict>]>>>;
|
|
119
|
+
frames: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
120
|
+
source: z.ZodString;
|
|
121
|
+
reason: z.ZodString;
|
|
122
|
+
}, z.core.$strict>]>>>;
|
|
123
|
+
forms: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
124
|
+
source: z.ZodString;
|
|
125
|
+
reason: z.ZodString;
|
|
126
|
+
}, z.core.$strict>]>>>;
|
|
127
|
+
media: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
128
|
+
source: z.ZodString;
|
|
129
|
+
reason: z.ZodString;
|
|
130
|
+
}, z.core.$strict>]>>>;
|
|
131
|
+
workers: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
132
|
+
source: z.ZodString;
|
|
133
|
+
reason: z.ZodString;
|
|
134
|
+
}, z.core.$strict>]>>>;
|
|
135
|
+
manifest: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
136
|
+
source: z.ZodString;
|
|
137
|
+
reason: z.ZodString;
|
|
138
|
+
}, z.core.$strict>]>>>;
|
|
139
|
+
}, z.core.$strict>;
|
|
140
|
+
/** A named, documented and optionally disabled group of permissions. */
|
|
141
|
+
declare const ruleSetSchema: z.ZodObject<{
|
|
142
|
+
name: z.ZodString;
|
|
143
|
+
purpose: z.ZodString;
|
|
144
|
+
owner: z.ZodOptional<z.ZodString>;
|
|
145
|
+
docs: z.ZodOptional<z.ZodURL>;
|
|
146
|
+
tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
147
|
+
reviewBy: z.ZodOptional<z.ZodISODate>;
|
|
148
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
149
|
+
rules: z.ZodObject<{
|
|
150
|
+
directives: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
151
|
+
source: z.ZodString;
|
|
152
|
+
reason: z.ZodString;
|
|
153
|
+
}, z.core.$strict>]>>>>;
|
|
154
|
+
scripts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
155
|
+
source: z.ZodString;
|
|
156
|
+
reason: z.ZodString;
|
|
157
|
+
}, z.core.$strict>]>>>;
|
|
158
|
+
connect: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
159
|
+
source: z.ZodString;
|
|
160
|
+
reason: z.ZodString;
|
|
161
|
+
}, z.core.$strict>]>>>;
|
|
162
|
+
images: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
163
|
+
source: z.ZodString;
|
|
164
|
+
reason: z.ZodString;
|
|
165
|
+
}, z.core.$strict>]>>>;
|
|
166
|
+
styles: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
167
|
+
source: z.ZodString;
|
|
168
|
+
reason: z.ZodString;
|
|
169
|
+
}, z.core.$strict>]>>>;
|
|
170
|
+
fonts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
171
|
+
source: z.ZodString;
|
|
172
|
+
reason: z.ZodString;
|
|
173
|
+
}, z.core.$strict>]>>>;
|
|
174
|
+
frames: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
175
|
+
source: z.ZodString;
|
|
176
|
+
reason: z.ZodString;
|
|
177
|
+
}, z.core.$strict>]>>>;
|
|
178
|
+
forms: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
179
|
+
source: z.ZodString;
|
|
180
|
+
reason: z.ZodString;
|
|
181
|
+
}, z.core.$strict>]>>>;
|
|
182
|
+
media: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
183
|
+
source: z.ZodString;
|
|
184
|
+
reason: z.ZodString;
|
|
185
|
+
}, z.core.$strict>]>>>;
|
|
186
|
+
workers: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
187
|
+
source: z.ZodString;
|
|
188
|
+
reason: z.ZodString;
|
|
189
|
+
}, z.core.$strict>]>>>;
|
|
190
|
+
manifest: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
191
|
+
source: z.ZodString;
|
|
192
|
+
reason: z.ZodString;
|
|
193
|
+
}, z.core.$strict>]>>>;
|
|
194
|
+
}, z.core.$strict>;
|
|
195
|
+
}, z.core.$strict>;
|
|
196
|
+
/** Complete configuration. Zod catches duplicate names and invalid rule sets. */
|
|
197
|
+
declare const policyConfigSchema: z.ZodObject<{
|
|
198
|
+
base: z.ZodDefault<z.ZodObject<{
|
|
199
|
+
default: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
200
|
+
source: z.ZodString;
|
|
201
|
+
reason: z.ZodString;
|
|
202
|
+
}, z.core.$strict>]>>>;
|
|
203
|
+
objects: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
204
|
+
source: z.ZodString;
|
|
205
|
+
reason: z.ZodString;
|
|
206
|
+
}, z.core.$strict>]>>>;
|
|
207
|
+
baseUri: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
208
|
+
source: z.ZodString;
|
|
209
|
+
reason: z.ZodString;
|
|
210
|
+
}, z.core.$strict>]>>>;
|
|
211
|
+
frameAncestors: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
212
|
+
source: z.ZodString;
|
|
213
|
+
reason: z.ZodString;
|
|
214
|
+
}, z.core.$strict>]>>>;
|
|
215
|
+
upgradeInsecureRequests: z.ZodOptional<z.ZodBoolean>;
|
|
216
|
+
directives: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
217
|
+
source: z.ZodString;
|
|
218
|
+
reason: z.ZodString;
|
|
219
|
+
}, z.core.$strict>]>>>>;
|
|
220
|
+
scripts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
221
|
+
source: z.ZodString;
|
|
222
|
+
reason: z.ZodString;
|
|
223
|
+
}, z.core.$strict>]>>>;
|
|
224
|
+
connect: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
225
|
+
source: z.ZodString;
|
|
226
|
+
reason: z.ZodString;
|
|
227
|
+
}, z.core.$strict>]>>>;
|
|
228
|
+
images: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
229
|
+
source: z.ZodString;
|
|
230
|
+
reason: z.ZodString;
|
|
231
|
+
}, z.core.$strict>]>>>;
|
|
232
|
+
styles: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
233
|
+
source: z.ZodString;
|
|
234
|
+
reason: z.ZodString;
|
|
235
|
+
}, z.core.$strict>]>>>;
|
|
236
|
+
fonts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
237
|
+
source: z.ZodString;
|
|
238
|
+
reason: z.ZodString;
|
|
239
|
+
}, z.core.$strict>]>>>;
|
|
240
|
+
frames: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
241
|
+
source: z.ZodString;
|
|
242
|
+
reason: z.ZodString;
|
|
243
|
+
}, z.core.$strict>]>>>;
|
|
244
|
+
forms: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
245
|
+
source: z.ZodString;
|
|
246
|
+
reason: z.ZodString;
|
|
247
|
+
}, z.core.$strict>]>>>;
|
|
248
|
+
media: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
249
|
+
source: z.ZodString;
|
|
250
|
+
reason: z.ZodString;
|
|
251
|
+
}, z.core.$strict>]>>>;
|
|
252
|
+
workers: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
253
|
+
source: z.ZodString;
|
|
254
|
+
reason: z.ZodString;
|
|
255
|
+
}, z.core.$strict>]>>>;
|
|
256
|
+
manifest: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
257
|
+
source: z.ZodString;
|
|
258
|
+
reason: z.ZodString;
|
|
259
|
+
}, z.core.$strict>]>>>;
|
|
260
|
+
}, z.core.$strict>>;
|
|
261
|
+
ruleSets: z.ZodDefault<z.ZodArray<z.ZodObject<{
|
|
262
|
+
name: z.ZodString;
|
|
263
|
+
purpose: z.ZodString;
|
|
264
|
+
owner: z.ZodOptional<z.ZodString>;
|
|
265
|
+
docs: z.ZodOptional<z.ZodURL>;
|
|
266
|
+
tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
267
|
+
reviewBy: z.ZodOptional<z.ZodISODate>;
|
|
268
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
269
|
+
rules: z.ZodObject<{
|
|
270
|
+
directives: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
271
|
+
source: z.ZodString;
|
|
272
|
+
reason: z.ZodString;
|
|
273
|
+
}, z.core.$strict>]>>>>;
|
|
274
|
+
scripts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
275
|
+
source: z.ZodString;
|
|
276
|
+
reason: z.ZodString;
|
|
277
|
+
}, z.core.$strict>]>>>;
|
|
278
|
+
connect: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
279
|
+
source: z.ZodString;
|
|
280
|
+
reason: z.ZodString;
|
|
281
|
+
}, z.core.$strict>]>>>;
|
|
282
|
+
images: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
283
|
+
source: z.ZodString;
|
|
284
|
+
reason: z.ZodString;
|
|
285
|
+
}, z.core.$strict>]>>>;
|
|
286
|
+
styles: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
287
|
+
source: z.ZodString;
|
|
288
|
+
reason: z.ZodString;
|
|
289
|
+
}, z.core.$strict>]>>>;
|
|
290
|
+
fonts: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
291
|
+
source: z.ZodString;
|
|
292
|
+
reason: z.ZodString;
|
|
293
|
+
}, z.core.$strict>]>>>;
|
|
294
|
+
frames: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
295
|
+
source: z.ZodString;
|
|
296
|
+
reason: z.ZodString;
|
|
297
|
+
}, z.core.$strict>]>>>;
|
|
298
|
+
forms: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
299
|
+
source: z.ZodString;
|
|
300
|
+
reason: z.ZodString;
|
|
301
|
+
}, z.core.$strict>]>>>;
|
|
302
|
+
media: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
303
|
+
source: z.ZodString;
|
|
304
|
+
reason: z.ZodString;
|
|
305
|
+
}, z.core.$strict>]>>>;
|
|
306
|
+
workers: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
307
|
+
source: z.ZodString;
|
|
308
|
+
reason: z.ZodString;
|
|
309
|
+
}, z.core.$strict>]>>>;
|
|
310
|
+
manifest: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
|
|
311
|
+
source: z.ZodString;
|
|
312
|
+
reason: z.ZodString;
|
|
313
|
+
}, z.core.$strict>]>>>;
|
|
314
|
+
}, z.core.$strict>;
|
|
315
|
+
}, z.core.$strict>>>;
|
|
316
|
+
reporting: z.ZodOptional<z.ZodObject<{
|
|
317
|
+
uri: z.ZodOptional<z.ZodURL>;
|
|
318
|
+
to: z.ZodOptional<z.ZodString>;
|
|
319
|
+
}, z.core.$strict>>;
|
|
320
|
+
mode: z.ZodDefault<z.ZodEnum<{
|
|
321
|
+
enforce: "enforce";
|
|
322
|
+
"report-only": "report-only";
|
|
323
|
+
}>>;
|
|
324
|
+
}, z.core.$strict>;
|
|
325
|
+
type SourceEntry = z.output<typeof sourceEntrySchema>;
|
|
326
|
+
type Rules = z.output<typeof rulesSchema>;
|
|
327
|
+
type ResourceKey = keyof typeof resourceDirectives;
|
|
328
|
+
type RuleSetInput = z.input<typeof ruleSetSchema>;
|
|
329
|
+
type RuleSet = z.output<typeof ruleSetSchema>;
|
|
330
|
+
type PolicyConfig = z.input<typeof policyConfigSchema>;
|
|
331
|
+
type NormalizedPolicyConfig = z.output<typeof policyConfigSchema>;
|
|
332
|
+
type DirectiveName = (typeof resourceDirectives)[ResourceKey] | (typeof baseDirectives)[keyof typeof baseDirectives] | 'upgrade-insecure-requests' | 'report-uri' | 'report-to';
|
|
333
|
+
|
|
334
|
+
/** Request metadata needed to evaluate checks which cannot be decided from a URL alone. */
|
|
335
|
+
interface MatchOptions {
|
|
336
|
+
/** Origin of the protected document, required for 'self' and schemeless sources. */
|
|
337
|
+
origin?: string;
|
|
338
|
+
/** Number of redirects before this URL; paths are not checked after a redirect. */
|
|
339
|
+
redirectCount?: number;
|
|
340
|
+
/** Nonce on the request; supply an empty string if the request has none. */
|
|
341
|
+
nonce?: string;
|
|
342
|
+
/** Rendered policy nonce for a dynamic nonce placeholder. */
|
|
343
|
+
policyNonce?: string;
|
|
344
|
+
/** Integrity metadata tokens on the request; supply an empty array if absent. */
|
|
345
|
+
integrity?: readonly string[];
|
|
346
|
+
/** Whether a script was parser-inserted. */
|
|
347
|
+
parserInserted?: boolean;
|
|
348
|
+
}
|
|
349
|
+
/** A conservative CSP decision. `indeterminate` never implies browser permission. */
|
|
350
|
+
interface AllowsResult {
|
|
351
|
+
status: 'allowed' | 'blocked' | 'indeterminate';
|
|
352
|
+
allowed: boolean | null;
|
|
353
|
+
effectiveDirective?: string;
|
|
354
|
+
matchedSource?: string;
|
|
355
|
+
reason?: string;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Evaluate a URL against a CSP directive. This deliberately returns indeterminate when
|
|
359
|
+
* relevant request context is unavailable. It is not a full browser simulation.
|
|
360
|
+
* Algorithms: https://www.w3.org/TR/CSP3/#match-url-to-source-list and #directive-fallback-list
|
|
361
|
+
*/
|
|
362
|
+
declare function matchPolicy(directives: Readonly<Record<string, readonly string[]>>, directive: string, input: string, options?: MatchOptions): AllowsResult;
|
|
363
|
+
|
|
364
|
+
/** Relevant fields from a CSP violation. Reports do not always include enough context to replay. */
|
|
365
|
+
interface ViolationReport {
|
|
366
|
+
directive: string;
|
|
367
|
+
blockedURL: string;
|
|
368
|
+
documentURL?: string;
|
|
369
|
+
}
|
|
370
|
+
interface ReplayResult {
|
|
371
|
+
report: ViolationReport;
|
|
372
|
+
result: AllowsResult;
|
|
373
|
+
}
|
|
374
|
+
/** Parse CSP legacy reports or Reporting API envelopes. Unsupported formats fail explicitly. */
|
|
375
|
+
declare function parseViolationReports(input: unknown): ViolationReport[];
|
|
376
|
+
/** Replay without inventing nonce, redirect, integrity or parser metadata. */
|
|
377
|
+
declare function replayReports(directives: Readonly<Record<string, readonly string[]>>, reports: readonly ViolationReport[]): ReplayResult[];
|
|
378
|
+
|
|
379
|
+
/** Reject literal risky strings in input lists while allowing annotated source objects.
|
|
380
|
+
* Dynamic strings remain subject to runtime Zod validation. */
|
|
381
|
+
type RequireRiskReasons<T> = T extends {
|
|
382
|
+
source: string;
|
|
383
|
+
} ? T : T extends string ? Lowercase<T> extends "'unsafe-inline'" | "'unsafe-eval'" | "'unsafe-hashes'" ? never : T : T extends object ? {
|
|
384
|
+
[K in keyof T]: K extends 'name' | 'purpose' | 'owner' | 'docs' | 'tags' | 'reviewBy' | 'enabled' | 'mode' | 'reporting' ? T[K] : RequireRiskReasons<T[K]>;
|
|
385
|
+
} : T;
|
|
386
|
+
interface ExplainRow {
|
|
387
|
+
directive: string;
|
|
388
|
+
source: string;
|
|
389
|
+
ruleSet: string;
|
|
390
|
+
reason?: string;
|
|
391
|
+
}
|
|
392
|
+
interface HeaderOptions {
|
|
393
|
+
nonce?: string;
|
|
394
|
+
pretty?: boolean;
|
|
395
|
+
}
|
|
396
|
+
/** Validate and freeze a rule set. */
|
|
397
|
+
declare function defineRuleSet<const T extends RuleSetInput>(input: T & RequireRiskReasons<T>): RuleSet;
|
|
398
|
+
/** Immutable CSP configuration and its deterministic merged representation. */
|
|
399
|
+
declare class Policy {
|
|
400
|
+
readonly config: NormalizedPolicyConfig;
|
|
401
|
+
readonly headerName: 'Content-Security-Policy' | 'Content-Security-Policy-Report-Only';
|
|
402
|
+
constructor(input: PolicyConfig);
|
|
403
|
+
/** Sources and their contributing rule sets. Duplicate values retain all contributors. */
|
|
404
|
+
explain(): ExplainRow[];
|
|
405
|
+
/** Merged sources, deduplicated without changing path syntax. */
|
|
406
|
+
toObject(): Record<string, string[]>;
|
|
407
|
+
/** Evaluate a URL with explicit uncertainty when browser context is missing. */
|
|
408
|
+
allows(directive: string, url: string, options?: MatchOptions): AllowsResult & {
|
|
409
|
+
contributors?: ExplainRow[];
|
|
410
|
+
};
|
|
411
|
+
/** Replay supported violation report JSON without inventing missing request context. */
|
|
412
|
+
check(reports: unknown): ReplayResult[];
|
|
413
|
+
/** Render a header value. Pretty output is for display only and is not a valid HTTP header value. */
|
|
414
|
+
toHeader(options?: HeaderOptions): string;
|
|
415
|
+
private render;
|
|
416
|
+
/** Render a meta policy; report-only is not supported in meta delivery. */
|
|
417
|
+
toMetaContent(options?: HeaderOptions): string;
|
|
418
|
+
withRuleSet<const T extends RuleSetInput>(ruleSet: T & RequireRiskReasons<T>): Policy;
|
|
419
|
+
without(name: string): Policy;
|
|
420
|
+
}
|
|
421
|
+
/** Validate and construct a policy. */
|
|
422
|
+
declare function definePolicy<const T extends PolicyConfig>(input: T & RequireRiskReasons<T>): Policy;
|
|
423
|
+
|
|
424
|
+
type Severity = 'high' | 'medium' | 'low' | 'info';
|
|
425
|
+
interface AuditFinding {
|
|
426
|
+
ruleId: string;
|
|
427
|
+
severity: Severity;
|
|
428
|
+
message: string;
|
|
429
|
+
fix: string;
|
|
430
|
+
directive?: string;
|
|
431
|
+
source?: string;
|
|
432
|
+
ruleSet?: string;
|
|
433
|
+
}
|
|
434
|
+
interface AuditRule {
|
|
435
|
+
id: string;
|
|
436
|
+
check(policy: Policy): readonly AuditFinding[];
|
|
437
|
+
}
|
|
438
|
+
interface AuditSuppression {
|
|
439
|
+
ruleId: string;
|
|
440
|
+
ruleSet: string;
|
|
441
|
+
reason: string;
|
|
442
|
+
}
|
|
443
|
+
interface AuditOptions {
|
|
444
|
+
rules?: readonly AuditRule[];
|
|
445
|
+
suppressions?: readonly AuditSuppression[];
|
|
446
|
+
now?: Date;
|
|
447
|
+
}
|
|
448
|
+
/** Inspect known dangerous policy patterns. Findings are advisory and do not prove a policy safe. */
|
|
449
|
+
declare function audit(policy: Policy, options?: AuditOptions): AuditFinding[];
|
|
450
|
+
|
|
451
|
+
export { type AllowsResult as A, type DirectiveName as D, type ExplainRow as E, type HeaderOptions as H, type MatchOptions as M, NONCE_PLACEHOLDER as N, Policy as P, type ReplayResult as R, type Severity as S, type ViolationReport as V, type PolicyConfig as a, type AuditFinding as b, type AuditOptions as c, type AuditRule as d, type AuditSuppression as e, type NormalizedPolicyConfig as f, type RequireRiskReasons as g, type ResourceKey as h, type RuleSet as i, type RuleSetInput as j, type Rules as k, type SourceEntry as l, audit as m, baseDirectives as n, baseSchema as o, definePolicy as p, defineRuleSet as q, matchPolicy as r, parseViolationReports as s, policyConfigSchema as t, replayReports as u, resourceDirectives as v, ruleSetSchema as w, rulesSchema as x, sourceEntrySchema as y };
|