@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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/schemas.ts","../src/keywords.ts","../src/matching/index.ts","../src/reports/index.ts","../src/core.ts","../src/audit/index.ts","../src/diff.ts","../src/importer/index.ts"],"sourcesContent":["export * from './schemas';\nexport * from './keywords';\nexport * from './core';\nexport * from './matching';\nexport * from './audit';\nexport * from './diff';\nexport * from './importer';\nexport * from './reports';\n","/* eslint-disable no-control-regex -- CSP input must reject ASCII control characters. */\nimport { z } from 'zod';\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/** Nonce placeholder, replaced only when rendering a header. */\nexport const NONCE_PLACEHOLDER = \"'nonce-{nonce}'\";\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_PLACEHOLDER ||\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 mode: z.enum(['enforce', 'report-only']).default('enforce'),\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","import { NONCE_PLACEHOLDER } from './schemas';\n\n/** Well-known CSP source expressions. Dangerous keywords require an explanation. */\nexport const sourceExpressions = {\n self: \"'self'\",\n none: \"'none'\",\n nonce: NONCE_PLACEHOLDER,\n strictDynamic: \"'strict-dynamic'\",\n reportSample: \"'report-sample'\",\n wasmUnsafeEval: \"'wasm-unsafe-eval'\",\n} as const;\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","/** 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 } from '../matching';\n\n/** Relevant fields from a CSP violation. Reports do not always include enough context to replay. */\nexport interface ViolationReport {\n directive: string;\n blockedURL: string;\n documentURL?: string;\n}\nexport interface ReplayResult {\n report: ViolationReport;\n result: AllowsResult;\n}\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\nfunction field(\n obj: Record<string, unknown>,\n ...keys: string[]\n): string | undefined {\n for (const key of keys)\n if (typeof obj[key] === 'string' && obj[key]) return obj[key] as string;\n return undefined;\n}\n/** Parse CSP legacy reports or Reporting API envelopes. Unsupported formats fail explicitly. */\nexport function parseViolationReports(input: unknown): ViolationReport[] {\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input) as unknown;\n } catch {\n throw new Error('Invalid report JSON');\n }\n }\n const items = Array.isArray(input) ? input : [input];\n return items.map((item, index) => {\n const envelope = record(item);\n if (!envelope) throw new Error(`Unsupported report at index ${index}`);\n const body =\n (envelope.type === 'csp' ? record(envelope.csp) : undefined) ??\n record(envelope['csp-report']) ??\n (envelope.type === 'csp-violation' ? record(envelope.body) : undefined) ??\n envelope;\n const directive = field(\n body,\n 'effective-directive',\n 'effectiveDirective',\n 'effective_directive',\n 'violated-directive',\n 'violatedDirective',\n 'violated_directive',\n );\n const blockedURL = field(\n body,\n 'blocked-uri',\n 'blockedURL',\n 'blockedUri',\n 'blocked_uri',\n );\n const documentURL = field(\n body,\n 'document-uri',\n 'documentURL',\n 'documentUri',\n 'document_uri',\n );\n if (!directive || !blockedURL)\n throw new Error(`Unsupported or incomplete report at index ${index}`);\n return {\n directive: directive.split(' ')[0]!,\n blockedURL,\n ...(documentURL ? { documentURL } : {}),\n };\n });\n}\n/** Replay without inventing nonce, redirect, integrity or parser metadata. */\nexport function replayReports(\n directives: Readonly<Record<string, readonly string[]>>,\n reports: readonly ViolationReport[],\n): ReplayResult[] {\n return reports.map((report) => {\n let origin: string | undefined;\n try {\n if (report.documentURL) {\n const parsedOrigin = new URL(report.documentURL).origin;\n if (parsedOrigin !== 'null') origin = parsedOrigin;\n }\n } catch {\n /* Preserve indeterminate result below. */\n }\n let blocked: URL;\n try {\n blocked = new URL(report.blockedURL);\n } catch {\n return {\n report,\n result: {\n status: 'indeterminate',\n allowed: null,\n reason: 'Report does not contain a replayable URL',\n },\n };\n }\n if (!['http:', 'https:', 'ws:', 'wss:'].includes(blocked.protocol)) {\n return {\n report,\n result: {\n status: 'indeterminate',\n allowed: null,\n reason: 'Report does not contain a replayable network URL',\n },\n };\n }\n const result = matchPolicy(\n directives,\n report.directive,\n report.blockedURL,\n origin ? { origin } : {},\n );\n // Violation reports may reduce cross-origin URLs to an origin, losing paths.\n // A positive match on a source with a path is therefore not proof of an allowed request.\n if (\n result.status === 'allowed' &&\n result.matchedSource &&\n result.matchedSource.replace(/^[a-z]+:\\/\\//i, '').includes('/')\n ) {\n return {\n report,\n result: {\n status: 'indeterminate',\n allowed: null,\n reason: 'Report may omit the request path',\n },\n };\n }\n return { report, result };\n });\n}\n","import { parseViolationReports, replayReports } from './reports';\nimport type { ReplayResult } from './reports';\nimport { matchPolicy } from './matching';\nimport type { AllowsResult, MatchOptions } from './matching';\nimport { z } from 'zod';\nimport {\n baseDirectives,\n NONCE_PLACEHOLDER,\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 | 'mode'\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 readonly headerName:\n 'Content-Security-Policy' | 'Content-Security-Policy-Report-Only';\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 this.headerName =\n config.mode === 'enforce'\n ? 'Content-Security-Policy'\n : 'Content-Security-Policy-Report-Only';\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 /** Replay supported violation report JSON without inventing missing request context. */\n check(reports: unknown): ReplayResult[] {\n return replayReports(this.toObject(), parseViolationReports(reports));\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 return this.render(this.toObject(), options);\n }\n private render(\n directives: Record<string, string[]>,\n options: HeaderOptions,\n ): string {\n const hasNonce = Object.values(directives).some((sources) =>\n sources.includes(NONCE_PLACEHOLDER),\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_PLACEHOLDER ? `'nonce-${options.nonce}'` : value,\n );\n return directive + (rendered.length ? ` ${rendered.join(' ')}` : '');\n })\n .join(options.pretty ? ';\\n' : '; ');\n }\n /** Render a meta policy; report-only is not supported in meta delivery. */\n toMetaContent(options: HeaderOptions = {}): string {\n if (this.config.mode === 'report-only')\n throw new Error(\n 'Report-only policies cannot be delivered in a meta element',\n );\n const directives = this.toObject();\n delete directives['frame-ancestors'];\n delete directives['report-uri'];\n delete directives['report-to'];\n delete directives.sandbox;\n return this.render(directives, options);\n }\n withRuleSet<const T extends RuleSetInput>(\n ruleSet: T & RequireRiskReasons<T>,\n ): Policy {\n return new Policy({\n ...this.config,\n ruleSets: [...this.config.ruleSets, ruleSet],\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","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 type { Policy } from './core';\n\nexport interface PolicyChange {\n directive: string;\n source: string;\n ruleSet: string;\n change: 'added' | 'removed' | 'modified';\n detail?: string;\n}\nexport interface PolicyDiff {\n changes: PolicyChange[];\n risk: 'increased' | 'unknown' | 'unchanged';\n}\n/** Compare source attribution as well as header and delivery changes. Risk is conservative, not a proof. */\nexport function diffPolicies(before: Policy, after: Policy): PolicyDiff {\n const key = (row: {\n directive: string;\n source: string;\n ruleSet: string;\n reason?: string;\n }) =>\n JSON.stringify([\n row.directive,\n row.source,\n row.ruleSet,\n row.reason ?? null,\n ]);\n const oldRows = new Map(before.explain().map((row) => [key(row), row]));\n const newRows = new Map(after.explain().map((row) => [key(row), row]));\n const changes: PolicyChange[] = [];\n for (const [id, row] of oldRows)\n if (!newRows.has(id))\n changes.push({\n directive: row.directive,\n source: row.source,\n ruleSet: row.ruleSet,\n change: 'removed',\n ...(row.reason ? { detail: row.reason } : {}),\n });\n for (const [id, row] of newRows)\n if (!oldRows.has(id))\n changes.push({\n directive: row.directive,\n source: row.source,\n ruleSet: row.ruleSet,\n change: 'added',\n ...(row.reason ? { detail: row.reason } : {}),\n });\n const beforeObj = before.toObject(),\n afterObj = after.toObject();\n for (const directive of new Set([\n ...Object.keys(beforeObj),\n ...Object.keys(afterObj),\n ])) {\n if (\n JSON.stringify(beforeObj[directive]) !==\n JSON.stringify(afterObj[directive]) &&\n !changes.some((c) => c.directive === directive)\n )\n changes.push({\n directive,\n source: '',\n ruleSet: 'base',\n change: 'modified',\n detail: 'Directive value changed',\n });\n }\n if (before.config.mode !== after.config.mode)\n changes.push({\n directive: '(mode)',\n source: '',\n ruleSet: 'base',\n change: 'modified',\n detail: `${before.config.mode} → ${after.config.mode}`,\n });\n changes.sort(\n (a, b) =>\n a.directive.localeCompare(b.directive) ||\n a.source.localeCompare(b.source) ||\n a.ruleSet.localeCompare(b.ruleSet) ||\n a.change.localeCompare(b.change),\n );\n const headersChanged =\n JSON.stringify(beforeObj) !== JSON.stringify(afterObj) ||\n before.config.mode !== after.config.mode;\n const dangerous = changes.some(\n (change) =>\n change.change === 'added' &&\n !(beforeObj[change.directive] ?? []).includes(change.source) &&\n /^(?:\\*|https?:|data:|'unsafe-(?:inline|eval|hashes)')$/.test(\n change.source,\n ),\n );\n return {\n changes,\n risk: dangerous ? 'increased' : headersChanged ? 'unknown' : 'unchanged',\n };\n}\n","import { policyConfigSchema } from '../schemas';\n/* eslint-disable no-control-regex -- reject unsafe header control characters. */\n/** A parsed header is deliberately separate from a managed policy: unknown directives,\n * empty lists and repeated directives cannot safely be represented by all policy builders. */\nexport interface ImportedDirective {\n readonly name: string;\n readonly values: readonly string[];\n /** CSP ignores subsequent occurrences of a directive. They remain available for review. */\n readonly ignored: boolean;\n}\nexport interface ImportedPolicy {\n readonly directives: readonly ImportedDirective[];\n readonly warnings: readonly string[];\n}\n\n/** Parse one CSP header without dropping unknown, empty or duplicate directives.\n * Throws on unsafe header characters and comma-separated policy lists rather than guessing.\n * This is a lossless token-level representation, not full CSP grammar validation.\n */\nexport function importHeader(header: string): ImportedPolicy {\n if (/[\\x00-\\x08\\x0a-\\x1f\\x7f,]/.test(header))\n throw new Error(\n 'Header contains a control character or multiple policies; import one policy at a time',\n );\n const seen = new Set<string>();\n const warnings: string[] = [];\n const directives: ImportedDirective[] = [];\n for (const segment of header.split(';')) {\n const trimmed = segment.trim();\n if (!trimmed) continue;\n const [rawName, ...values] = trimmed.split(/[ \\t]+/);\n if (!rawName || !/^[a-zA-Z][a-zA-Z0-9-]*$/.test(rawName))\n throw new Error(`Invalid directive name: ${rawName ?? ''}`);\n const name = rawName.toLowerCase();\n const ignored = seen.has(name);\n if (ignored)\n warnings.push(`Duplicate ${name} is ignored by CSP; retained for review`);\n seen.add(name);\n directives.push({ name, values, ignored });\n }\n return { directives, warnings };\n}\n\n/** Serialize the parsed token stream. Empty directives and ignored duplicates remain present. */\nexport function serializeImportedPolicy(policy: ImportedPolicy): string {\n return policy.directives\n .map(({ name, values }) => {\n if (\n !/^[a-z][a-z0-9-]*$/.test(name) ||\n values.some((value) => !value || /[\\x00-\\x20\\x7f;,]/.test(value))\n ) {\n throw new Error('Invalid imported directive or value');\n }\n return [name, ...values].join(' ');\n })\n .join('; ');\n}\n\n/** Convert only representable, single-policy imports into a reviewable draft config.\n * Ambiguous or unsupported constructs fail explicitly rather than broadening a policy.\n * Imported dangerous keywords are annotated for mandatory human review.\n */\nexport function importedPolicyToDraft(\n policy: ImportedPolicy,\n): import('../schemas').PolicyConfig {\n if (policy.directives.some((directive) => directive.ignored))\n throw new Error(\n 'Duplicate directives require manual review before conversion',\n );\n const base: Record<string, unknown> = {};\n const baseRaw: Record<string, import('../schemas').SourceEntry[]> = {};\n const ruleRaw: Record<string, import('../schemas').SourceEntry[]> = {};\n const baseOnly = new Set([\n 'default-src',\n 'object-src',\n 'base-uri',\n 'frame-ancestors',\n ]);\n const supported = new Set([\n 'default-src',\n 'object-src',\n 'base-uri',\n 'frame-ancestors',\n 'script-src',\n 'script-src-elem',\n 'script-src-attr',\n 'style-src',\n 'style-src-elem',\n 'style-src-attr',\n 'img-src',\n 'connect-src',\n 'font-src',\n 'frame-src',\n 'child-src',\n 'form-action',\n 'media-src',\n 'worker-src',\n 'manifest-src',\n ]);\n const risky = new Set([\n \"'unsafe-inline'\",\n \"'unsafe-eval'\",\n \"'unsafe-hashes'\",\n ]);\n for (const directive of policy.directives) {\n if (directive.name === 'upgrade-insecure-requests') {\n if (directive.values.length)\n throw new Error(\n 'upgrade-insecure-requests with values requires manual review',\n );\n base.upgradeInsecureRequests = true;\n continue;\n }\n if (\n !supported.has(directive.name) ||\n directive.values.some(\n (value) => value.toLowerCase() === \"'nonce-{nonce}'\",\n )\n ) {\n throw new Error(\n `Directive ${directive.name} contains unsupported syntax; review manually`,\n );\n }\n if (\n directive.values.length === 0 ||\n ['report-uri', 'report-to', 'sandbox'].includes(directive.name)\n ) {\n throw new Error(\n `Directive ${directive.name} requires manual review before conversion`,\n );\n }\n const entries = directive.values.map((source) =>\n risky.has(source.toLowerCase())\n ? { source, reason: 'Imported legacy policy; review required' }\n : source,\n );\n (baseOnly.has(directive.name) ? baseRaw : ruleRaw)[directive.name] =\n entries;\n }\n if (Object.keys(baseRaw).length) base.directives = baseRaw;\n const draft: import('../schemas').PolicyConfig = {\n base,\n ruleSets: Object.keys(ruleRaw).length\n ? [\n {\n name: 'Imported policy',\n purpose: 'Imported sources awaiting ownership review',\n rules: { directives: ruleRaw },\n },\n ]\n : [],\n };\n const result = policyConfigSchema.safeParse(draft);\n if (!result.success)\n throw new Error(\n `Imported policy contains unsupported sources: ${result.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; ')}`,\n );\n return draft;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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E,SAC3B;AAAA,MACE;AAAA,QACE,MAAM;AAAA,QACN,SAAS;AAAA,QACT,OAAO,EAAE,YAAY,QAAQ;AAAA,MAC/B;AAAA,IACF,IACA,CAAC;AAAA,EACP;AACA,QAAM,SAAS,mBAAmB,UAAU,KAAK;AACjD,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR,iDAAiD,OAAO,MAAM,OAAO,IAAI,CAAC,UAAU,GAAG,MAAM,KAAK,KAAK,GAAG,CAAC,KAAK,MAAM,OAAO,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA,IAC7I;AACF,SAAO;AACT;","names":["import_zod","baseOnly","risky"]}
@@ -0,0 +1,79 @@
1
+ import { P as Policy, a as PolicyConfig } from './index-D6PmUWjD.cjs';
2
+ export { A as AllowsResult, b as AuditFinding, c as AuditOptions, d as AuditRule, e as AuditSuppression, D as DirectiveName, E as ExplainRow, H as HeaderOptions, M as MatchOptions, N as NONCE_PLACEHOLDER, f as NormalizedPolicyConfig, R as ReplayResult, g as RequireRiskReasons, h as ResourceKey, i as RuleSet, j as RuleSetInput, k as Rules, S as Severity, l as SourceEntry, V as ViolationReport, m as audit, n as baseDirectives, o as baseSchema, p as definePolicy, q as defineRuleSet, r as matchPolicy, s as parseViolationReports, t as policyConfigSchema, u as replayReports, v as resourceDirectives, w as ruleSetSchema, x as rulesSchema, y as sourceEntrySchema } from './index-D6PmUWjD.cjs';
3
+ import 'zod';
4
+
5
+ /** Well-known CSP source expressions. Dangerous keywords require an explanation. */
6
+ declare const sourceExpressions: {
7
+ readonly self: "'self'";
8
+ readonly none: "'none'";
9
+ readonly nonce: "'nonce-{nonce}'";
10
+ readonly strictDynamic: "'strict-dynamic'";
11
+ readonly reportSample: "'report-sample'";
12
+ readonly wasmUnsafeEval: "'wasm-unsafe-eval'";
13
+ };
14
+ /** Use Web Crypto to create a fresh, unpredictable per-response nonce. */
15
+ declare function generateNonce(): string;
16
+ /** Permit inline code; weakens XSS protection unless ignored by a nonce or hash. */
17
+ declare const unsafeInline: ({ reason }: {
18
+ reason: string;
19
+ }) => {
20
+ source: string;
21
+ reason: string;
22
+ };
23
+ /** Permit dynamic JavaScript evaluation; increases XSS risk. */
24
+ declare const unsafeEval: ({ reason }: {
25
+ reason: string;
26
+ }) => {
27
+ source: string;
28
+ reason: string;
29
+ };
30
+ /** Permit hashes for inline handlers; can weaken protection. */
31
+ declare const unsafeHashes: ({ reason }: {
32
+ reason: string;
33
+ }) => {
34
+ source: string;
35
+ reason: string;
36
+ };
37
+ /** Create a CSP hash source expression. */
38
+ declare const cspHash: (algorithm: "sha256" | "sha384" | "sha512", digest: string) => string;
39
+
40
+ interface PolicyChange {
41
+ directive: string;
42
+ source: string;
43
+ ruleSet: string;
44
+ change: 'added' | 'removed' | 'modified';
45
+ detail?: string;
46
+ }
47
+ interface PolicyDiff {
48
+ changes: PolicyChange[];
49
+ risk: 'increased' | 'unknown' | 'unchanged';
50
+ }
51
+ /** Compare source attribution as well as header and delivery changes. Risk is conservative, not a proof. */
52
+ declare function diffPolicies(before: Policy, after: Policy): PolicyDiff;
53
+
54
+ /** A parsed header is deliberately separate from a managed policy: unknown directives,
55
+ * empty lists and repeated directives cannot safely be represented by all policy builders. */
56
+ interface ImportedDirective {
57
+ readonly name: string;
58
+ readonly values: readonly string[];
59
+ /** CSP ignores subsequent occurrences of a directive. They remain available for review. */
60
+ readonly ignored: boolean;
61
+ }
62
+ interface ImportedPolicy {
63
+ readonly directives: readonly ImportedDirective[];
64
+ readonly warnings: readonly string[];
65
+ }
66
+ /** Parse one CSP header without dropping unknown, empty or duplicate directives.
67
+ * Throws on unsafe header characters and comma-separated policy lists rather than guessing.
68
+ * This is a lossless token-level representation, not full CSP grammar validation.
69
+ */
70
+ declare function importHeader(header: string): ImportedPolicy;
71
+ /** Serialize the parsed token stream. Empty directives and ignored duplicates remain present. */
72
+ declare function serializeImportedPolicy(policy: ImportedPolicy): string;
73
+ /** Convert only representable, single-policy imports into a reviewable draft config.
74
+ * Ambiguous or unsupported constructs fail explicitly rather than broadening a policy.
75
+ * Imported dangerous keywords are annotated for mandatory human review.
76
+ */
77
+ declare function importedPolicyToDraft(policy: ImportedPolicy): PolicyConfig;
78
+
79
+ export { type ImportedDirective, type ImportedPolicy, Policy, type PolicyChange, PolicyConfig, type PolicyDiff, cspHash, diffPolicies, generateNonce, importHeader, importedPolicyToDraft, serializeImportedPolicy, sourceExpressions, unsafeEval, unsafeHashes, unsafeInline };
@@ -0,0 +1,79 @@
1
+ import { P as Policy, a as PolicyConfig } from './index-D6PmUWjD.js';
2
+ export { A as AllowsResult, b as AuditFinding, c as AuditOptions, d as AuditRule, e as AuditSuppression, D as DirectiveName, E as ExplainRow, H as HeaderOptions, M as MatchOptions, N as NONCE_PLACEHOLDER, f as NormalizedPolicyConfig, R as ReplayResult, g as RequireRiskReasons, h as ResourceKey, i as RuleSet, j as RuleSetInput, k as Rules, S as Severity, l as SourceEntry, V as ViolationReport, m as audit, n as baseDirectives, o as baseSchema, p as definePolicy, q as defineRuleSet, r as matchPolicy, s as parseViolationReports, t as policyConfigSchema, u as replayReports, v as resourceDirectives, w as ruleSetSchema, x as rulesSchema, y as sourceEntrySchema } from './index-D6PmUWjD.js';
3
+ import 'zod';
4
+
5
+ /** Well-known CSP source expressions. Dangerous keywords require an explanation. */
6
+ declare const sourceExpressions: {
7
+ readonly self: "'self'";
8
+ readonly none: "'none'";
9
+ readonly nonce: "'nonce-{nonce}'";
10
+ readonly strictDynamic: "'strict-dynamic'";
11
+ readonly reportSample: "'report-sample'";
12
+ readonly wasmUnsafeEval: "'wasm-unsafe-eval'";
13
+ };
14
+ /** Use Web Crypto to create a fresh, unpredictable per-response nonce. */
15
+ declare function generateNonce(): string;
16
+ /** Permit inline code; weakens XSS protection unless ignored by a nonce or hash. */
17
+ declare const unsafeInline: ({ reason }: {
18
+ reason: string;
19
+ }) => {
20
+ source: string;
21
+ reason: string;
22
+ };
23
+ /** Permit dynamic JavaScript evaluation; increases XSS risk. */
24
+ declare const unsafeEval: ({ reason }: {
25
+ reason: string;
26
+ }) => {
27
+ source: string;
28
+ reason: string;
29
+ };
30
+ /** Permit hashes for inline handlers; can weaken protection. */
31
+ declare const unsafeHashes: ({ reason }: {
32
+ reason: string;
33
+ }) => {
34
+ source: string;
35
+ reason: string;
36
+ };
37
+ /** Create a CSP hash source expression. */
38
+ declare const cspHash: (algorithm: "sha256" | "sha384" | "sha512", digest: string) => string;
39
+
40
+ interface PolicyChange {
41
+ directive: string;
42
+ source: string;
43
+ ruleSet: string;
44
+ change: 'added' | 'removed' | 'modified';
45
+ detail?: string;
46
+ }
47
+ interface PolicyDiff {
48
+ changes: PolicyChange[];
49
+ risk: 'increased' | 'unknown' | 'unchanged';
50
+ }
51
+ /** Compare source attribution as well as header and delivery changes. Risk is conservative, not a proof. */
52
+ declare function diffPolicies(before: Policy, after: Policy): PolicyDiff;
53
+
54
+ /** A parsed header is deliberately separate from a managed policy: unknown directives,
55
+ * empty lists and repeated directives cannot safely be represented by all policy builders. */
56
+ interface ImportedDirective {
57
+ readonly name: string;
58
+ readonly values: readonly string[];
59
+ /** CSP ignores subsequent occurrences of a directive. They remain available for review. */
60
+ readonly ignored: boolean;
61
+ }
62
+ interface ImportedPolicy {
63
+ readonly directives: readonly ImportedDirective[];
64
+ readonly warnings: readonly string[];
65
+ }
66
+ /** Parse one CSP header without dropping unknown, empty or duplicate directives.
67
+ * Throws on unsafe header characters and comma-separated policy lists rather than guessing.
68
+ * This is a lossless token-level representation, not full CSP grammar validation.
69
+ */
70
+ declare function importHeader(header: string): ImportedPolicy;
71
+ /** Serialize the parsed token stream. Empty directives and ignored duplicates remain present. */
72
+ declare function serializeImportedPolicy(policy: ImportedPolicy): string;
73
+ /** Convert only representable, single-policy imports into a reviewable draft config.
74
+ * Ambiguous or unsupported constructs fail explicitly rather than broadening a policy.
75
+ * Imported dangerous keywords are annotated for mandatory human review.
76
+ */
77
+ declare function importedPolicyToDraft(policy: ImportedPolicy): PolicyConfig;
78
+
79
+ export { type ImportedDirective, type ImportedPolicy, Policy, type PolicyChange, PolicyConfig, type PolicyDiff, cspHash, diffPolicies, generateNonce, importHeader, importedPolicyToDraft, serializeImportedPolicy, sourceExpressions, unsafeEval, unsafeHashes, unsafeInline };
package/dist/index.js ADDED
@@ -0,0 +1,57 @@
1
+ import {
2
+ NONCE_PLACEHOLDER,
3
+ Policy,
4
+ baseDirectives,
5
+ baseSchema,
6
+ cspHash,
7
+ definePolicy,
8
+ defineRuleSet,
9
+ diffPolicies,
10
+ generateNonce,
11
+ importHeader,
12
+ importedPolicyToDraft,
13
+ matchPolicy,
14
+ parseViolationReports,
15
+ policyConfigSchema,
16
+ replayReports,
17
+ resourceDirectives,
18
+ ruleSetSchema,
19
+ rulesSchema,
20
+ serializeImportedPolicy,
21
+ sourceEntrySchema,
22
+ sourceExpressions,
23
+ unsafeEval,
24
+ unsafeHashes,
25
+ unsafeInline
26
+ } from "./chunk-TE3J7Y25.js";
27
+ import {
28
+ audit
29
+ } from "./chunk-KWWYRHIP.js";
30
+ export {
31
+ NONCE_PLACEHOLDER,
32
+ Policy,
33
+ audit,
34
+ baseDirectives,
35
+ baseSchema,
36
+ cspHash,
37
+ definePolicy,
38
+ defineRuleSet,
39
+ diffPolicies,
40
+ generateNonce,
41
+ importHeader,
42
+ importedPolicyToDraft,
43
+ matchPolicy,
44
+ parseViolationReports,
45
+ policyConfigSchema,
46
+ replayReports,
47
+ resourceDirectives,
48
+ ruleSetSchema,
49
+ rulesSchema,
50
+ serializeImportedPolicy,
51
+ sourceEntrySchema,
52
+ sourceExpressions,
53
+ unsafeEval,
54
+ unsafeHashes,
55
+ unsafeInline
56
+ };
57
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}