# CSPKit Design Notes

## Boundary

CSPKit handles Content-Security-Policy text only. It does not make network requests, parse HTTP messages, or emulate browser enforcement. The narrow boundary keeps the package reusable in MoonBit libraries, CLIs, wasm gateways, and static site tooling.

## Data Model

- `Directive` stores a normalized directive name, ordered values, and original order.
- `Policy` stores directives in source order.
- `Finding` stores a code, severity, optional directive name, and message.
- `PolicyDiff` records added, removed, and changed directives.
- `SourceExpression` stores classification details for each source token.
- `DirectiveSpec` stores known CSP directive metadata.
- `PolicyScore` stores grade, penalty, bonus, finding counts, directive coverage, and source counts.
- `HardeningRecommendation` stores machine-readable remediation guidance.
- `PolicyTemplate` stores reusable CSP templates for common deployment scenarios.
- `AuditRuleSpec` stores static audit rule metadata.

All parsing functions return `Result` instead of aborting.

## Parsing

The parser splits directives by semicolon and splits values by ASCII whitespace. Directive names are normalized to lowercase and limited to ASCII letters, digits, and hyphen. Values must be visible ASCII because CSP source expressions are protocol tokens rather than free-form prose.

## Audit Rules

The first version focuses on high-signal checks:

- missing `default-src`;
- missing `object-src`, `base-uri`, and `frame-ancestors`;
- duplicate directives;
- wildcard sources;
- `unsafe-inline`;
- `unsafe-eval` and `wasm-unsafe-eval`;
- risky `data:` in script/object/default contexts;
- plain HTTP sources;
- mixed `'none'` with other source expressions;
- nonce/hash source expressions as informational findings.

## Scoring and Reports

The score model combines audit findings, directive coverage, source expression risk, and hardening bonuses. It is intentionally explainable: each score includes the raw score, final clamped score, grade, penalty, bonus, severity counts, directive coverage, and source counts.

Reports can be generated as plain text, Markdown, or escaped JSON strings so the library can be used in examples, CI logs, documentation generation, or later CLI wrappers.

## Templates and Rule Catalog

CSPKit includes reusable templates for static sites, single page applications, WebAssembly apps, admin panels, upload portals, payment pages, sandboxed previews, offline docs, and development-only policies. The audit rule catalog maps known finding codes to category, trigger, remediation, and rationale.

## Diff Rules

`diff_policy` compares directives by name. A directive is:

- added when only present in the new policy;
- removed when only present in the old policy;
- changed when both exist but ordered source values differ.
