Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 0 ๐Ÿ“– 11 min read

Put the Pre-Consent Check in CI: Fail the Build When a New Tag Writes Before the Visitor Answers

A few days ago I wrote about what a site stores before anyone clicks the banner: open the page in a fresh profile, list the cookies, storage and requests before any answer, click Reject, and list what's new. It takes ten

A few days ago I wrote about what a site stores before anyone clicks the banner: open the page in a fresh profile, list the cookies, storage and requests before any answer, click Reject, and list what's new. It takes ten minutes, and it's correct on the day you do it.

The problem is the day after. A marketing pixel goes into one template. A tag manager gets a new trigger. A video embed shows up on the blog. None of it goes through the person who checked the banner, and nobody runs the check again until a regulator or a customer asks.

So this time I moved the check into the deploy. The goal: every deploy (and every morning) loads one page per template in a fresh browser, compares what it finds against an allow-list kept in the repository, and fails with a readable list when something new writes before the answer or after Reject.

Everything below ran on a small test site with fake hosts (shop.test for the site, tracker.test for a third-party tag) on my own machine. That keeps the results repeatable. It isn't your site, and the last section covers what a headless browser in CI can't see.

The policy lives in the repo

The allow-list is a small JSON file next to the script, so every change to it goes through review like code:

{
  "base": "https://shop.test:8443",
  "pages": ["/home.html", "/product.html", "/blog.html", "/account.html"],
  "reject_button": "Reject",
  "allow_before_answer": ["request shop.test/collect"],
  "allow_after_reject": ["cookie [email protected]"],
  "allow_per_page": {"/account.html": ["cookie [email protected]"]}
}

Each line says what is allowed and where:

  • Before any answer, the only thing allowed is a first-party request to /collect. On this test site it's a stateless page-view beacon that stores nothing on the device. Whether that's acceptable for your site is a legal question, not a technical one. The point is that someone decided it and wrote it down.
  • After Reject, the only new thing allowed is the cookie that remembers the answer. Without it, the banner would come back on every page.
  • Per page, /account.html may set a session cookie, because the login form needs one. Per-page exceptions keep that from becoming a global "sessions are fine everywhere".

Pick pages by template, not by URL count: home, a product or pricing page, an article, checkout, the login page, and any page with an embed (video, map, chat widget). Ten pages that cover every template are worth more than a hundred blog posts that share one.

The script

It's the check from the earlier article, reworked for CI: one fresh browser context per page (every page is a first visit), items written as plain strings so they can be compared against the allow-list, a non-zero exit code when something is outside it, and a diff against the previous run.

# Pre-consent check for CI: fails (exit 1) when a page stores or sends anything before the visitor answers,
# or after "Reject", that isn't on the allow-list. Also prints what changed since the last run.
# Usage: python3 ci_check.py consent-policy.json [extra Chrome flags]      (pip install playwright)
import json, sys, os
from urllib.parse import urlsplit
from playwright.sync_api import sync_playwright

def items(ctx, page, sent):
    found = {f"cookie {c['name']}@{c['domain'].lstrip('.')}" for c in ctx.cookies()}
    for f in page.frames:
        host = urlsplit(f.url).hostname
        try: keys = f.evaluate('() => Object.keys(localStorage).concat(Object.keys(sessionStorage))')
        except Exception: keys = []
        found |= {f'storage {k}@{host}' for k in keys if host}
    return found | set(sent)

cfg = json.load(open(sys.argv[1])); site = urlsplit(cfg['base']).hostname
results, problems = {}, []
with sync_playwright() as p:
    browser = p.chromium.launch(executable_path=os.environ.get('CHROME'), headless=True, args=sys.argv[2:])  # CHROME unset = Playwright's Chromium
    for path in cfg['pages']:
        ctx = browser.new_context(ignore_https_errors=True)      # fresh profile per page = a first visit
        page = ctx.new_page(); sent = []
        page.on('request', lambda r: sent.append(f"request {urlsplit(r.url).hostname}{urlsplit(r.url).path}")
                if urlsplit(r.url).hostname != site or r.resource_type in ('fetch', 'xhr', 'ping', 'beacon') else None)
        page.goto(cfg['base'] + path, wait_until='load'); page.wait_for_timeout(int(os.environ.get('WAIT_MS', 3000)))
        before = items(ctx, page, sent); sent.clear()
        try:
            page.get_by_role('button', name=cfg['reject_button']).click(timeout=3000); page.wait_for_timeout(2000)
            after = items(ctx, page, sent) - before
        except Exception:
            after = {'missing reject button'}
        ok = set(cfg['allow_per_page'].get(path, []))
        for stage, found, allow in (('before answer', before, cfg['allow_before_answer']), ('after reject', after, cfg['allow_after_reject'])):
            for it in sorted(found - set(allow) - ok): problems.append(f'FAIL {path}  {stage}: {it}')
        results[path] = {'before': sorted(before), 'after_reject': sorted(after)}
        ctx.close()
    browser.close()

last = json.load(open('preconsent-last.json')) if os.path.exists('preconsent-last.json') else {}
for path, r in results.items():
    for stage in ('before', 'after_reject'):
        for it in sorted(set(r[stage]) - set(last.get(path, {}).get(stage, []))):
            if last: print(f'NEW  {path}  {stage}: {it}')
json.dump(results, open('preconsent-last.json', 'w'), indent=1)
print('\n'.join(problems) or f'OK: {len(results)} pages, nothing outside the allow-list')
sys.exit(1 if problems else 0)

Run it as python3 ci_check.py consent-policy.json. Extra arguments go to Chrome. I passed --host-resolver-rules to point the fake hosts at my machine, and ignore_https_errors=True is only there for the self-signed test certificate, so remove it for a real site. WAIT_MS sets the wait after the page loads (3,000 ms by default). CHROME points at an installed Chrome. Leave it unset and Playwright uses its own Chromium, which is what you want in CI.

Release 1: clean, and it says so

The first release had four pages: a plain home page, a product page with the first-party beacon, a blog page, and an account page that sets a session cookie. The banner only loads the tracker after Accept.

### site_v1
OK: 4 pages, nothing outside the allow-list
exit code: 0
took 21.4 s

About five seconds per page: the default 3-second wait after load, the click, and 2 more seconds after Reject. The account page did set PHPSESSID before any answer. It passed because the policy allows it on that page only.

Release 2: a marketing tag and a leaky Reject

For the second release I changed two files, the kind of change that shows up in a pull request without anyone thinking of consent:

  • product.html got a third-party tag in the <head>, outside the banner logic.
  • blog.html got a banner mode where Reject still loads the tracker.

Same policy, same script:

### site_v2
NEW  /product.html  before: cookie [email protected]
NEW  /product.html  before: cookie [email protected]
NEW  /product.html  before: request tracker.test/b
NEW  /product.html  before: request tracker.test/t.js
NEW  /product.html  before: storage [email protected]
NEW  /blog.html  after_reject: cookie [email protected]
NEW  /blog.html  after_reject: cookie [email protected]
NEW  /blog.html  after_reject: request tracker.test/b
NEW  /blog.html  after_reject: request tracker.test/t.js
NEW  /blog.html  after_reject: storage [email protected]
FAIL /product.html  before answer: cookie [email protected]
FAIL /product.html  before answer: cookie [email protected]
FAIL /product.html  before answer: request tracker.test/b
FAIL /product.html  before answer: request tracker.test/t.js
FAIL /product.html  before answer: storage [email protected]
FAIL /blog.html  after reject: cookie [email protected]
FAIL /blog.html  after reject: cookie [email protected]
FAIL /blog.html  after reject: request tracker.test/b
FAIL /blog.html  after reject: request tracker.test/t.js
FAIL /blog.html  after reject: storage [email protected]
exit code: 1
took 21.4 s

Exit code 1 stops the pipeline. Look at what the list tells whoever reads the build log: which page, which stage, and what exactly. Two of the five items on the product page are a cookie and a local storage key set on shop.test itself by the third-party script. If you only looked for third-party cookies, you'd miss them.

The NEW lines and the FAIL lines overlap here, but they answer different questions. FAIL is "outside the policy" and decides the exit code. NEW is "different from the last run", even for items the policy allows. If someone adds a second allowed item, or an allowed cookie moves from one page to another, NEW is where you see it.

Release 3: the tag that waits

Then I tried to fool the check. In the third release the product page loads the same tracker, but 6 seconds after page load, still before any answer. Some tags behave like this when they're delayed for page speed:

### site_v3 (tag after 6 s), default 3 s wait
OK: 4 pages, nothing outside the allow-list
exit code: 0
### site_v3 (tag after 6 s), WAIT_MS=8000
FAIL /product.html  before answer: cookie [email protected]
FAIL /product.html  before answer: cookie [email protected]
FAIL /product.html  before answer: request tracker.test/b
FAIL /product.html  before answer: request tracker.test/t.js
FAIL /product.html  before answer: storage [email protected]
exit code: 1

(The NEW lines are left out of the second run.) With the default wait, the clean result was wrong. Even the 2 seconds after Reject didn't reach the 6-second mark. With WAIT_MS=8000 the script caught it. A green build only covers what happened inside the wait. I'd keep the per-deploy run short and give the nightly run a longer wait (10รขโ‚ฌโ€œ15 seconds), where an extra minute doesn't hold anyone up.

Wiring it into GitHub Actions

This is the workflow I'd start from. I validated the YAML but didn't run it on GitHub for this article. The setup lines follow Playwright's CI guide:

name: pre-consent check
on:
  workflow_dispatch:
  schedule:
    - cron: "17 5 * * *"          # every morning, catches tags added outside a deploy (tag manager, CMS)
  deployment_status:               # after each deploy, if your host reports deployments to GitHub
jobs:
  check:
    if: github.event_name != 'deployment_status' || github.event.deployment_status.state == 'success'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install playwright && python -m playwright install --with-deps chromium
      - run: python ci_check.py consent-policy.json
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: preconsent-result
          path: preconsent-last.json

The schedule matters as much as the deploy trigger. Tag managers and CMS plugins change what a page loads without any deploy, so a check that only runs on deploys can't see those changes. Point base at staging for deploy runs and at production for the nightly run. Events like deployment_status and schedule are described in GitHub's list of workflow triggers.

On a fresh CI runner there's no previous preconsent-last.json, so the NEW lines only appear when the file is kept between runs (locally, or restored from the last artifact). The FAIL lines don't depend on it.

What a headless browser in CI can't see

  • Region-dependent banners. Many consent tools behave differently in the EEA and elsewhere. A runner in a US data centre tests the US behaviour. Run the check from the regions you care about (an EU runner, or a proxy) if the answer differs.
  • Anything after an interaction. Tags fired on scroll, on a click, or on a second page view weren't tested. You can add steps for them, but each one is a separate test to keep up to date.
  • Logged-in pages, A/B variants and personalisation. The script sees one anonymous version of each page.
  • Server-side tracking. If your server forwards visit data to a third party, nothing appears in the browser, so this check can't see it.
  • Automation detection. Some scripts behave differently when they detect a headless or automated browser. If yours do, a pass proves less, and a manual check in a normal browser now and then is still worth it.
  • Whether something is allowed. The script finds things. Whether a first-party beacon or a session cookie is acceptable before consent depends on your setup and your jurisdiction. That's a decision for the people responsible for privacy, not for a CI job.

Where DataVisitors fits

DataVisitors is the privacy-friendly analytics tool from the team behind FindUtils. It's waitlist-only right now. Its privacy approach page says the tracking script sets no cookie. In the EEA, the UK, Switzerland or an unresolved country, nothing is stored on the device until your site's consent allows it. Elsewhere the default mode may use local storage, unless you choose Strict, which stores nothing anywhere until consent. In a check like this, a cookieless tag still shows up as a request, so it goes on the allow-list as a deliberate line, like the /collect beacon above. In Strict mode, or from an EU runner, it shouldn't show up as a cookie or storage key before the answer. From a US runner in the default mode, expect a local storage entry, by design. That's one more reason to run the check from the regions you care about. I didn't run this script on a DataVisitors-tagged site for this article, so that's what to verify on yours. How it works has more on how it counts visits.

Checklist

  1. Write the policy down in the repo: what's allowed before any answer, after Reject, and per page, each with a reason in the pull request.
  2. One page per template, plus every page with an embed.
  3. Fresh browser context per page, so each page is a first visit.
  4. Test Reject as well as the first load. Release 2's blog page was clean until someone clicked Reject.
  5. Fail the build on anything outside the policy, and print page, stage and item so the fix is obvious.
  6. Run it nightly against production with a longer wait, not only on deploys.
  7. Run it from the regions where your banner behaves differently.

Need help with a project? The team behind FindUtils takes on freelance work on Upwork, including a fast React front end for your web app, dashboard or admin panel, for example a front end where every third-party script waits for the visitor's answer.

๐Ÿ“ฐ Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.