# consent-kit

> consent-kit is a toolkit for keeping a website's cookie banner, privacy policy data and actual browser behaviour in agreement.

consent-kit is a toolkit for keeping a website's cookie banner, privacy policy data and actual browser behaviour in agreement. You describe every cookie, storage key, third-party script, iframe, endpoint, stylesheet, font and media file your site uses in one file, `privacy.registry.yaml`, together with its purpose and consent category. The registry is validated, diffed against the last released version, and compiled into the files the site needs: a [vanilla-cookieconsent](https://github.com/orestbida/cookieconsent) configuration, a policy snapshot, a guard manifest, a Content-Security-Policy and a typed storage module.

The generated files are then enforced in three places. An ESLint rule keeps application code from using raw browser storage APIs instead of the generated storage facade. A small inline script, the guard, checks cookie, storage, script and iframe writes in the browser against the registry and the visitor's current consent. The Content-Security-Policy starts from `default-src 'none'` and admits only what the registry declares, for every kind of resource. `consent-kit build --check` fails in CI when the generated files no longer match the registry.

consent-kit is tooling, not legal advice. It does not make a site compliant with GDPR, the ePrivacy Directive or any other law, and it cannot tell you whether your registry is complete or your purposes are lawful. Have your setup reviewed by someone qualified to do that.

## What the registry states

Besides purposes, processors, artefacts and collection points, the registry holds every statement the generated privacy documents need, so `consent-kit docs` writes them without hand-written inserts. A complete example is `packages/schema/fixtures/vacation-planner.registry.yaml`.

| Field | Required | What it is for |
| --- | --- | --- |
| `controller.dpo` | yes: `{ name?, contact }` or `false` | The data protection officer (Art. 13(1)(b) GDPR). `false` states that none is designated; leaving the field out is an error, because silence cannot be told from an oversight. |
| `controller.supervisoryAuthority` | yes: `{ name, url?, address? }` | Where complaints go (Art. 13(2)(d)). |
| `controller.euRepresentative` | no | The Art. 27 representative of a controller outside the Union. Absent means not needed; the registry does not record where the controller is established, so it cannot demand a statement. |
| `controller.address` | no (advisory gap in the documents) | Printed with the controller's name and contact. |
| `purposes[].legitimateInterest` | yes when `basis: legitimate_interest`, an error on any other basis | The interest pursued (Art. 13(1)(d)). |
| `purposes[].automatedDecisionMaking` | yes: `false` or `{ logic, consequences }` | Art. 13(2)(f). `true` alone is rejected: the article asks for the logic and the consequences. |
| `purposes[].dataSubjects` | yes, at least one id | Categories of data subjects (Art. 30(1)(c)). |
| `purposes[].processors` | no | Recipients no artefact shows, such as the email provider behind a form. `[]` states that there are none; without it the documents say "none declared" and report an advisory gap. |
| `processors[].role` | no, default `processor` | `processor`, `independent_controller` or `joint_controller`. |
| `collectionPoints[].title` | no | The form's name in the documents. |
| `collectionPoints[].fields[].provision` | yes: `statutory`, `contractual` or `voluntary` | Art. 13(2)(e). `consequence` (what happens without the data) is required unless the field is voluntary. |
| `artefacts[].duration` on `kind: storage` | no | `persistent` or `<n>d`. A declaration for the cookie tables; your own code has to honour it. |
| `dataCategories`, `dataSubjectCategories`, `retentionEvents` | no | Names for the ids used by purposes. Once a map exists, every id used must be declared in it. `dataCategories.<id>.special: true` marks an Art. 9 category. |
| `securityMeasures` | no (advisory gap) | General description of the security measures, for the Art. 30 record. |
| `receipts` | yes once a purpose has `basis: consent`: `{ endpoint }` or `{ optOut: { reason } }` | Where the proof of each consent decision goes. See [Consent receipts](#consent-receipts). |
| `subjectRequests` | no: `{ endpoint, notify, types, retention, requesterEmail? }` | A form on the site for access and erasure requests. See [Data subject requests](#data-subject-requests). |

A processor that no artefact uses and no purpose lists is a validation error (`processor/unreferenced`). Every one of these fields has change kinds of its own in `consent-kit diff`; none is reported as an unclassified change. `privacy.documents.json` still carries the free-form `intro` and `outro` of the privacy policy, phrase overrides and the cookie-table links, and nothing else.

## Stylesheets, fonts and media files

Three artefact kinds declare what a page loads without running it: `stylesheet`, `font` and `media`, each with `src`, `purposes` and, for a third party, a `processor`. A declared one is admitted by the Content-Security-Policy (`style-src`, `font-src`, `media-src`), listed in the cookie table and with its provider among the recipients, and known to the audit; an undeclared one is blocked by the policy and reported by the audit with an entry to paste. Files the site serves itself need no declaration.

```yaml
artefacts:
  - id: brand_font
    kind: font
    src: https://fonts.example/brand/   # an origin, a URL prefix or one file
    processor: example-fonts
    purposes: [essential]               # must not be a consent purpose
```

Such an artefact cannot be bound to a consent purpose (`artefact/consent-not-enforceable`). Nothing consent-kit generates can hold a `<link>`, a CSS `url()` or a `<video>` back until consent: CookieConsent only manages `<script>` tags, the runtime guard has no hook for these loads, and the policy is the same before and after a decision. Rather than generate a gate that would not hold, the validator refuses the combination. Host the file yourself, bind it to a purpose with another lawful basis that you can defend, or load it from a consent-gated script. The guard does not police these kinds; they appear in its manifest only so that the audit can tell a declared load from an undeclared one.

## Content-Security-Policy

`consent-kit build` writes the policy to `_headers` (Netlify / Cloudflare Pages format) and to `csp.json`. By default it is the strictest policy the registry allows:

```
default-src 'none';
script-src 'self' 'sha256-<inline guard>' <declared script origins>;
style-src 'self' <declared stylesheet origins>;   font-src 'self' <declared font origins>;
img-src 'self' <declared pixel origins>;          connect-src 'self' <declared endpoint origins>;
frame-src 'self' <declared iframe origins>;       media-src 'self' <declared media origins>;
worker-src 'self'; manifest-src 'self';
object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none';
upgrade-insecure-requests
```

No `'unsafe-inline'`, no `'unsafe-eval'`, no wildcard, no `data:` or `blob:`. Inline scripts run only by hash or nonce (the inline guard's hash is added for you); inline styles only by hash (`inlineStyleHashes`). `'self'` is the baseline of every fetch directive, including those with nothing declared, because first-party files are never declared and the compiler cannot know which kinds a site serves. `form-action` is `'self'` because the registry does not record where a form posts to. `frame-ancestors` only works as a response header: `csp.json` also carries a `meta` value for hosts that cannot set headers, without it. `upgrade-insecure-requests` is left out automatically, and reported, when the registry declares an `http:` URL.

CookieConsent works under this policy unchanged, provided its stylesheet is served by the site (`cookieconsent.css` from `'self'`, as in `examples/static-site`): it adds neither `<style>` elements nor `style` attributes.

### Loosening it

Every deviation is written in the registry's `csp` section, per directive and with a reason. There is no switch that turns the policy off.

```yaml
csp:
  allow:
    - directive: style-src
      sources: ["'unsafe-inline'"]
      reason: The legacy chat widget sets style attributes (WEB-123).
  reportOnly: true              # Content-Security-Policy-Report-Only: reports, blocks nothing
  reportUri: /csp-reports       # report-uri; a third-party URL must be a declared endpoint artefact
  reportTo: csp                 # report-to; with reportUri, a Reporting-Endpoints header is generated
  upgradeInsecureRequests: false
```

The section lives in the registry rather than in a build config file because a loosening is a declaration about what the site lets through, and the registry is what is validated, hashed, diffed against the last release and acknowledged by a person. A side file would need a second lock and a second diff to give the same trace.

- Validated: an unknown directive (`csp/unknown-directive`), a malformed source such as an unquoted keyword (`csp/invalid-source`), `'none'` or a repeated source (`csp/redundant-source`) and an undeclared third-party report endpoint are errors.
- Listed: `consent-kit check` prints every deviation with its reason (and carries them in `--json` as `csp.deviations`), and so does the audit report. Automatic ones are marked.
- Diffed: adding a source, switching to report-only or dropping `upgrade-insecure-requests` is `csp.loosened`, which needs a confirmation in `privacy.review.json` and never asks visitors again; removing one is `csp.tightened`, not material.

The audit's setup check "no Content-Security-Policy violations in the page itself" fails when a page's own markup or code is refused by its policy (an inline `<style>`, a `style` attribute, an inline handler, `eval`). A refused request to an undeclared third party is reported by "Undeclared drift" instead.

Declared URLs are located by parsing, never by their first characters: `//host/…` is third-party, and a value with a backslash, whitespace or a control character is refused, because browsers read it differently from how it is written. A declared path covers whole path segments only: `/collect` covers `/collect/x`, not `/collector`.

## Consent receipts

The consent cookie CookieConsent writes is the working copy of a visitor's choice, and it lives in their browser. A receipt is the proof the site keeps: one record per decision. A registry that asks for consent has to say where receipts go, or that it keeps none; consent-kit refuses to build it otherwise (`receipts/not-stated`).

```yaml
receipts:
  endpoint: /consent-receipts      # a site-relative path, or an https URL
```

```yaml
receipts:
  optOut:
    reason: Decisions are recorded by the parent site's consent service (PRIV-12).
```

- The endpoint is a site-relative path or an `https:` URL, located by parsing like every other declared URL. A third-party endpoint must be covered, by whole path segments, by a declared `endpoint` artefact with its processor, and the entry that matches it (the longest prefix) must be bound to a purpose that is not based on consent: a rejection is recorded too, so the endpoint cannot wait for consent (`receipts/undeclared-endpoint`, `receipts/endpoint-needs-consent`). Its origin is added to `connect-src` automatically.
- The opt-out needs a reason, and a stock non-reason ("n/a", "not needed", "TODO") is refused with the same normalising match as vague purpose texts (`receipts/vague-reason`). `consent-kit check` and `build` print it as the warning `receipts/opted-out` with the reason, `--json` carries the section as `receipts`, and the audit report states it, with the reason, before any check.
- Diffed: declaring or moving the endpoint is not material (`receipts.endpoint_declared`, `receipts.endpoint_changed`). Switching to the opt-out or removing the section needs a confirmation in `privacy.review.json` (`receipts.opted_out`, `receipts.removed`). A reworded reason is not material. None of them asks visitors again.
- Documents: with an endpoint, the privacy policy's section on withdrawing consent says that each choice is kept as proof and what the record holds. With the opt-out it says nothing about a record, and the reason, which is addressed to you, is never printed.

**What is sent.** With an endpoint, the generated `cookieconsent.config.gen.ts` imports `installConsentReceipts` from `@consent-kit/storage` (so the site needs that package as a dependency, as it does for `storage.gen.ts`) and installs it when the module is imported. It listens for CookieConsent's own `cc:onFirstConsent` and `cc:onChange` window events, which fire for the same decisions as the `onFirstConsent` and `onChange` callbacks, so a site that passes its own `onChange` to `CookieConsent.run` still sends receipts. Each decision is one POST, with `navigator.sendBeacon` (it survives the reload a withdrawal often triggers), or `fetch` with `keepalive` where the beacon is missing or refused. No retries, and nothing ever throws into the page. The body is JSON, sent as `text/plain;charset=UTF-8` so that a third-party endpoint needs no CORS preflight; parse it as JSON whatever the `Content-Type`:

```json
{
  "consentId": "6f1c2a5e-8b0d-4d6e-9f3a-2c7b1e0d4a91",
  "event": "first",
  "accepted": [{ "purpose": "analytics", "version": 1 }],
  "rejected": [{ "purpose": "media", "version": 1 }],
  "policyHash": "83918475460fd5695e91e9f178a4cd8a529ff1c26ee03856c9429305e9d0330d",
  "revision": 1,
  "timestamp": "2026-11-28T09:30:00.000Z"
}
```

| Field | What it is |
| --- | --- |
| `consentId` | CookieConsent's random id of this browser's consent, from the consent cookie. |
| `event` | `first` for the first decision (`onFirstConsent`), `change` for a later one (`onChange`). |
| `accepted`, `rejected` | Every consent purpose of the build, with its `version`, sorted by id. |
| `policyHash` | The registry's policy hash at build time: the version printed on the generated documents. |
| `revision` | CookieConsent's revision of the build. |
| `timestamp` | ISO 8601, from the visitor's clock, when the decision was made. |

Nothing else is in the body: no user agent, no page URL, no other cookie content. The request itself still carries what every request carries, the visitor's IP address and the cookies the browser holds for the endpoint's origin.

**Receiving them.** [`@consent-kit/server`](https://github.com/pavelpascari/consent-kit/tree/main/packages/server) is the receiving end: `createReceiptHandler`, a Fetch API handler that checks each receipt and appends it through a storage adapter, plus an adapter and migration for Cloudflare D1. With an endpoint, `consent-kit build` also writes `receipts.manifest.gen.json`. It lists the policy hash, revision and consent purposes with their versions that the build's generated module sends, followed by every released policy. `consent-kit release` appends each release to the `history` in `privacy.lock.json`, so receipts from pages still open on an older policy are accepted, each against that policy's own versions. The handler accepts a receipt only if it matches one of those policies exactly: every consent purpose once, each at that policy's version. In place of `consentId` it stores HMAC-SHA-256 of it under a secret key. It never stores the IP address, user agent, headers, URL or raw body. [`examples/cloudflare-receipts`](https://github.com/pavelpascari/consent-kit/tree/main/examples/cloudflare-receipts) is a complete Worker on D1 for the static site. A site with its own endpoint must do the same: hash `consentId` before storing it, and keep the IP address out of the record. `examples/static-site/src/server.ts` only collects the bodies, for the audit.

**The release history.** `privacy.lock.json` (`lockVersion` 2) keeps the last released registry and, under `history`, one entry per release, oldest first: `revision`, `policyHash`, `releasedAt`, `consentPurposes` (id to version), `otherPurposes` and `sendsReceipts`. A release appends one entry and never rewrites the earlier ones, so a diff of the lock shows each release as one new entry. A lock written before the history existed (`lockVersion` 1) is read as a history of its one release, and the next `consent-kit release` writes it in the new shape. The history feeds only the receipt manifest; `check` and `diff` still compare against the last released registry.

**Global Privacy Control.** With the GPC signal set, CookieConsent treats the visitor as having refused and fires neither event, so no receipt is sent for such a visitor. That is expected: the visitor made no choice in the banner, and the audit's GPC check verifies that nothing consent-bound runs.

**Audit.** The check "Consent receipts: one per decision" accepts everything and rejects everything, each in a fresh context, then withdraws what was accepted, and requires exactly one POST to the endpoint per decision, with exactly the fields above, the consent cookie's `consentId`, the right event and purposes, and the audited registry's policy hash. With the opt-out it is a warning that carries the reason.

## Data subject requests

With a `subjectRequests` section, consent-kit gives a site the building blocks to receive access and erasure requests. It receives, records, notifies and reminds; a person gathers or deletes the data and answers.

```yaml
subjectRequests:
  endpoint: /privacy/requests      # on the site's own domain, so the consent cookie comes along
  notify: privacy@example.com
  types: [access, erasure]
  retention: 3y                    # how long a closed request is kept
```

`consent-kit build` writes the form (`subject-request-form.<locale>.html`, a plain POST that the strict policy admits) and `subject-requests.manifest.gen.json`. The documents list the built-in purpose "Handling your data protection requests" (legal obligation) and link the form. `createSubjectRequestHandler` in `@consent-kit/server` stores each request and ties it to the browser's consent receipts by the same keyed hash. It then emails the controller's mailbox with a fulfilment checklist built from the registry. It answers with the same 303 whatever it knows, and can email the requester a confirmation link, which only a POST from its page uses. `remindDueRequests` and `sweepClosedRequests` run from a Cron Trigger. Email goes through Cloudflare's `send_email` binding, Resend or Postmark. The audit checks that the form is reachable and posts same-origin. See [the concept](/docs/manual/concepts/subject-requests/) and [the guide](/docs/manual/guides/receive-data-subject-requests/).

## Packages

A site usually needs the CLI and the storage facade, plus the audit for checking in a browser:

```sh
npm install @consent-kit/storage vanilla-cookieconsent
npm install --save-dev @consent-kit/cli @consent-kit/audit
```

The [tutorial](/docs/manual/getting-started/) starts from an empty folder.

| Package | Directory | What it provides |
| --- | --- | --- |
| `@consent-kit/schema` | `packages/schema` | Registry types and JSON Schema, `parseRegistry` / `validateRegistry`, and the semantic diff between two registry versions. |
| `@consent-kit/compiler` | `packages/compiler` | `compile` and its parts: policy snapshot, CookieConsent config, guard manifest, the strict Content-Security-Policy (`contentSecurityPolicy`, with its deviations), registry module, and the consent-gated script tags (`consentScriptTag`) and iframe placeholders (`consentEmbed`). |
| `@consent-kit/presets` | `packages/presets` | Provider presets: versioned, sourced declarations of third-party tools that a registry adopts with a `presets` entry instead of declaring the processor and artefacts by hand. See its README and CONTRIBUTING guide. |
| `@consent-kit/guard` | `packages/guard` | The browser runtime guard: `installGuard` for bundled code and `renderInlineGuard` for the inline `<head>` script. |
| `@consent-kit/storage` | `packages/storage` | `createStorage`, a typed, consent-aware facade over cookies and web storage with `clearUnconsented()` for cleanup after a withdrawal; `syncEmbeds`, which activates embed placeholders; `installConsentReceipts`, which the generated CookieConsent module calls to send consent receipts; and the generator for a project's storage module. |
| `@consent-kit/server` | `packages/server` | The receiving end of consent receipts and of data subject requests (`createSubjectRequestHandler`, its D1 store and migration, the reminder, the retention sweep and email adapters for Cloudflare, Resend and Postmark). For receipts: `createReceiptHandler`, a framework-free Fetch API handler that validates each receipt against the build's receipt manifest, hashes the consent id with HMAC-SHA-256 and appends it through a `ReceiptStore`; `createD1ReceiptStore` and the SQL migration for Cloudflare D1. See its README and `examples/cloudflare-receipts`. |
| `@consent-kit/eslint-plugin` | `packages/eslint-plugin` | The `@consent-kit/no-raw-storage` rule and a `recommended` flat config. |
| `@consent-kit/cli` | `packages/cli` | The `consent-kit` command: `check`, `diff`, `build`, `docs`, `release`, `script-tag` and `audit`. Also re-exports the helpers a site's build script needs (`parseRegistry`, `consentScriptTag`, `consentEmbed`, `guardManifest`, `contentSecurityPolicy`, `renderInlineGuard`). |
| `@consent-kit/documents` | `packages/documents` | Generates the privacy policy, cookie table, record of processing (Art. 30), processor list, field notices, imprint (§ 5 DDG) and changelog entry in English and German from a phrase library. Every phrase is an unreviewed draft until a lawyer's review is recorded; documents say so visibly. Run it as `consent-kit docs`. |
| `@consent-kit/presets` | `packages/presets` | Provider presets: versioned declarations of one third-party tool that a registry adopts in a few lines. Ships a draft Plausible preset and a synthetic one for the example site. |
| `@consent-kit/audit` | `packages/audit` | The browser audit: drives a running site with Playwright and checks what it really does against the registry, including what its Content-Security-Policy blocks and whether every banner decision sends its consent receipt. Run it as `consent-kit audit <url>` or `consent-kit-audit`. An optional peer of `@consent-kit/cli`, installed separately because it brings Playwright. |

## Development

Requires Node.js 22.6 or newer and pnpm 10. Published packages run on Node.js 22 or newer.

```sh
pnpm install
pnpm test        # vitest, all packages
pnpm typecheck   # tsc --noEmit in every package (generates the example's consent files first)
pnpm build       # compile every package to dist/ (ESM and .d.ts)
pnpm check       # typecheck, test and build
```

Inside the repository, packages resolve to each other's TypeScript source, so nothing needs building to run the tests or the CLI:

```sh
node --experimental-strip-types packages/cli/src/bin.ts check --registry packages/schema/fixtures/vacation-planner.registry.yaml
```

The published entry points (`dist/`) are set through `publishConfig` in each `package.json` and apply when a package is packed or published with pnpm. After `pnpm build`, the compiled CLI runs with plain `node`:

```sh
node packages/cli/dist/bin.js --help
```

Every package is published to npm in the `@consent-kit` scope, all at one version. [RELEASING.md](https://github.com/pavelpascari/consent-kit/blob/main/RELEASING.md) describes how a release is versioned with changesets and published.

`examples/static-site` imports files that `consent-kit build` generates (`src/consent.gen/`, git-ignored). `pnpm typecheck` generates them first, so it works on a fresh clone; `pnpm --filter @consent-kit/example-static-site build` builds the whole example site.

`examples/cloudflare-receipts` imports the receipt manifest that `consent-kit build` writes from the static site's registry into its `consent.gen/` (git-ignored), and `pnpm typecheck` generates that too. Its test (`packages/server/test/worker.test.ts`) runs the Worker in workerd through wrangler, against a local D1 database. It needs no Cloudflare account.

### The inline guard

`packages/guard/src/runtime.gen.ts` is generated from `packages/guard/src/runtime.ts` and checked in. It holds the minified text of the inline guard, whose SHA-256 hash goes into the generated Content-Security-Policy, so it must not depend on how the package was loaded. After changing `runtime.ts`, regenerate it:

```sh
pnpm generate
```

A test fails while the generated file is out of date.

The inline guard has to be inlined byte-for-byte as generated (`guard.inline.js`, including its trailing newline): the Content-Security-Policy allows it by hash, and the browser silently refuses a script whose text differs. `consent-kit audit` fails its "runtime guard installed" check when a page ships the guard but it did not run.

### Releases

Versioning uses [changesets](https://github.com/changesets/changesets). Add one with `pnpm changeset`.

## License

MIT
