# Run the audit in CI

> This guide sets up a CI job that builds your site, serves it with its real response headers, runs consent-kit audit against it and fails when a check fails.

This guide sets up a CI job that builds your site, serves it with its real response headers, runs `consent-kit audit` against it and fails when a check fails. It also covers the exercise file and the two staleness checks that belong in the same job.

It assumes the site already passes the audit on your machine. If it does not, start with [Getting started](/docs/manual/getting-started/).

## What the job does

1. Installs the project, `@consent-kit/audit` and Chromium.
2. Checks that the generated files are up to date.
3. Builds the site and serves it.
4. Runs the audit and keeps its JSON report.
5. Fails if the audit exits with a non-zero code.

## 1. Install the audit and Chromium

The audit is a separate package because it brings Playwright. Add it as a dev dependency so that CI installs it with everything else:

```sh
npm install --save-dev @consent-kit/audit
```

Playwright's Chromium is a separate download. On your machine:

```sh
npx playwright install chromium
```

On a fresh CI image, also install the system libraries Chromium needs:

```sh
npx playwright install --with-deps chromium
```

If the package is missing, `consent-kit audit` says so and exits with code 2. It does not skip silently.

## 2. Serve the site with its real headers

The audit needs a running site at a URL. It does not build or serve anything itself.

How you serve it matters. `consent-kit build` writes the Content-Security-Policy to a `_headers` file, and the policy only does anything when the server sends it as a response header. Audit the site the way production serves it:

- a preview deploy on the host you use in production, or
- a local server that applies `_headers`. The example's server in `examples/static-site/src/server.ts` does this in a few lines.

> [!WARNING]
> A plain static file server does not read `_headers`. The site then runs without a Content-Security-Policy, and the audit reports on a site that is weaker than the one you ship: nothing undeclared is blocked, and the check for policy violations in the page itself cannot fire. The audit does not tell you that the header is missing.

You can confirm the header before you trust a run:

```sh
curl -sI http://localhost:4173/ | grep -i content-security-policy
```

The example site builds its inline guard in `record` mode for audits. In that mode the guard notes every attempt it blocks, and the audit turns those into warnings, so you see what the page tried to do without consent even though the guard stopped it. See [Runtime API](/docs/manual/reference/runtime-api/) for the guard modes.

> [!WARNING]
> Audit a build whose guard is in `record` mode. In `enforce` mode, the CLI default, the guard blocks an undeclared cookie or storage write before it lands, so the audit has nothing to observe and "Undeclared drift" passes. The guard mode changes the guard's text and its hash in the policy, so build the audited site and its headers together with `consent-kit build --guard-mode record`.

## 3. Run the audit

List every page that uses a declared artefact. The audit does not crawl, and its default is `/` alone.

```sh
npx consent-kit audit http://localhost:4173 \
  --page / --page /video.html --page /about.html \
  --exercise audit-exercise.mjs
```

`--registry` defaults to `privacy.registry.yaml` in the current directory. Pass it if the registry is somewhere else.

A passing run of `examples/static-site` prints:

```text
consent-kit audit of http://localhost:4173/
Pages: /, /video.html, /about.html

PASS  1. Pre-consent silence
PASS  2. Reject means reject
PASS  3. Grant activates exactly what is declared
PASS  4. Withdrawal cleans up
PASS  5. GPC honoured
PASS  6. Undeclared drift
PASS  7. Banner UX
PASS  Consent receipts: one per decision
PASS  Coverage: attribute drift
PASS  Coverage: unexercised declarations
PASS  Setup: runtime guard installed
PASS  Setup: no Content-Security-Policy violations in the page itself

Coverage: 7 of 7 declared artefacts observed; 0 undeclared; 0 used without consent; 0 with attribute drift.

Content-Security-Policy (as generated from the registry): 1 deviation from strict
  upgrade-insecure-requests is left out (automatic): The registry declares http: URLs (http://127.0.0.1:4174); upgrading them to https would break those declared loads. Declare https: URLs to get the directive back.

Presets:
  acme-analytics@1.0.0 -> processor "acme-analytics", artefacts acme_script, acme_id, acme_last_page, acme_collect  [synthetic]

Audit passed: 12 checks passed (6.7s).
```

Every check is described in the [Audit reference](/docs/manual/reference/audit/).

## 4. Fail the job on the exit code

| Exit code | Meaning |
| --- | --- |
| 0 | No check failed. Warnings do not fail the audit. |
| 1 | At least one check failed. |
| 2 | Usage error, unreadable or invalid registry, or `@consent-kit/audit` not installed. |

CI systems fail a step on any non-zero exit code, so there is nothing to parse. Do not wrap the command in something that swallows its exit code.

Warnings pass. The most common one is a declared artefact that was never observed:

```text
WARN  Coverage: unexercised declarations
      warning  localStorage key "theme" (artefact "theme") is declared but was never observed. Either no audited page or interaction uses it (add the page, or an "exercise" step), or the declaration is stale.
```

Once your pages and exercise file cover everything the registry declares, add `--strict`. The same finding then fails the job, so a declaration that goes stale is caught:

```text
FAIL  Coverage: unexercised declarations
      error    localStorage key "theme" (artefact "theme") is declared but was never observed. Either no audited page or interaction uses it (add the page, or an "exercise" step), or the declaration is stale.
```

## 5. Keep the JSON report

`--json` prints the report as one JSON object on stdout instead of the text. The exit code is the same.

```sh
npx consent-kit audit http://localhost:4173 \
  --page / --page /video.html --page /about.html \
  --exercise audit-exercise.mjs \
  --json > audit-report.json
```

Upload `audit-report.json` as a build artefact, and do it even when the audit fails: that is when you want it. The report holds every finding with its check, page and phase, and for anything undeclared a registry entry to paste. Its shape is in the [Audit reference](/docs/manual/reference/audit/#the-json-report).

With `--json` the text report is not printed. If you want both the readable log and the file, run the audit twice, or build the text from the JSON with `renderReport` from `@consent-kit/audit`.

## 6. Write an exercise file

Some artefacts only appear after an interaction. In the example site the `theme` key in `localStorage` is written when the visitor clicks the theme toggle. Without that click the audit never sees it, and reports it as unexercised.

An exercise file is an ES module whose default export is a function. The audit calls it with the Playwright page after every page load, in every check. This is `examples/static-site/audit-exercise.mjs`:

```js
// Passed to the audit as `--exercise`: runs after every page load, so the one
// artefact that needs a click (the `theme` localStorage key) is observed.
export default async function exercise(page) {
  await page.click('#theme-toggle');
}
```

The function gets a second argument, `{ path, phase, granted }`: the pathname of the page, what the audit has done so far, and the consent categories granted at that moment. Use `path` when an element only exists on some pages. The contact form here is made up; the example site has none:

```js
export default async function exercise(page, { path }) {
  await page.click('#theme-toggle');
  if (path === '/contact.html') {
    await page.fill('#email', 'audit@example.com');
    await page.click('#send');
  }
}
```

A few rules:

- Do not click the consent banner. The audit does that itself and checks the result.
- Do not skip steps before consent. The function runs before any decision, after a rejection and with the GPC signal set on purpose: an interaction that triggers something consent-bound in those states is a finding.
- If the function throws, the check that was running fails with `the check could not complete: ...`. A selector that is missing on one page fails the audit, so branch on `path`.
- The path given to `--exercise` is resolved against the current directory. A path that does not exist ends the run with a Node.js module error, not a usage message.

## 7. Check the generated files in the same job

The audit compares the running site with the registry. Two more commands check that the files generated from the registry are the ones committed. Run them first: they are fast and need no browser.

```sh
npx consent-kit build --check
```

`build --check` writes nothing and exits with code 1 if the generated files are stale. Pass the same `--out`, `--guard-mode` and `--report-url` you build with: the flags change the output, so a different set reports the files as stale.

```text
9 generated files in src/consent.gen are up to date (revision 1).
```

```text
stale  src/consent.gen/_headers
stale  src/consent.gen/csp.json
stale  src/consent.gen/guard.inline.js
consent-kit: 3 generated files out of date; run "consent-kit build"
```

If you commit the privacy documents, check them too:

```sh
npx consent-kit docs --check
```

It exits with code 1 when a document is missing or out of date. Both commands are described in the [CLI reference](/docs/manual/reference/cli/).

## An example job

This is a GitHub Actions job. The `consent-kit` and `playwright` commands are exactly the ones above. The three lines marked `your ...` depend on your project: replace them with your build command, a server that sends the `_headers` file as response headers, and your pages.

```yaml
name: privacy
on: [pull_request]

jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npx playwright install --with-deps chromium

      - name: Generated files are up to date
        run: npx consent-kit build --check

      - name: Build the site
        run: npm run build # your build

      - name: Serve the site
        run: |
          npm run serve & # your server, sending the Content-Security-Policy header
          for i in $(seq 1 30); do
            curl -sf -o /dev/null http://localhost:4173/ && break
            sleep 1
          done
          curl -sI http://localhost:4173/ | grep -i content-security-policy

      - name: Audit
        run: |
          npx consent-kit audit http://localhost:4173 \
            --page / --page /video.html --page /about.html \
            --exercise audit-exercise.mjs \
            --json > audit-report.json
        # your pages

      - name: Keep the report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: consent-kit-audit
          path: audit-report.json
```

The `grep` in the serve step fails the job when the header is missing, which the audit itself would not notice.

If you audit a preview deploy instead, drop the build and serve steps and pass the preview URL to `consent-kit audit`.

## When the job fails

Read the first `FAIL` line and its findings. The usual causes:

| Finding | What to do |
| --- | --- |
| `... is not declared in the registry` | Remove the thing, or paste the entry from the finding into `privacy.registry.yaml` and fill in its purpose. See [Write a registry entry](/docs/manual/guides/write-a-registry-entry/). |
| `missing: ... was not observed after granting it` | The page that uses the artefact is not in the `--page` list, or it needs an interaction: add the page or an exercise step. Otherwise the declaration is stale. |
| `... it needs consent to: ...` | Something consent-bound ran without consent. This is the failure the audit exists for; fix the page. |
| `the inline consent-kit guard is in the HTML ... but did not install` | The inlined guard is not byte-for-byte the generated `guard.inline.js`. Check for a formatter or minifier in the build. |
| `the Content-Security-Policy of ... refused ...` | Inline code or styles on the page. Move them into a file, or see [Loosen the CSP](/docs/manual/guides/loosen-the-csp/). |
| `the consent receipt ... policyHash is ...` | The site was built from a different registry than the one the audit read. Rebuild. |
| `the check could not complete: page.goto: net::ERR_CONNECTION_REFUSED` | The site was not up when the audit started. |

A green audit means the listed pages behaved as declared in one Chromium run. What it cannot show is in the [limits of the audit](/docs/manual/reference/audit/#limits) and in [Threat model and limits](/docs/manual/concepts/threat-model-and-limits/).
