Skip to content

Open-source skills for designing and reviewing software with AI agents

Add consent-based analytics for egm.dev (#197)

n3wtha119668d7dc5
diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml
index 3766f99..59c8e8d 100644
--- a/.github/workflows/deploy-site.yml
+++ b/.github/workflows/deploy-site.yml
@@ -14,9 +14,9 @@
# Build and deploy the egm.dev landing site (site/) to GitHub Pages.
#
-# The site is static: no analytics, no cookies, no third-party scripts, and no
-# requests to Google hosts at runtime. Keep it that way; it is a condition of
-# the open-source release.
+# Analytics and Cookie Notification Bar run only when window.location.hostname
+# is 'egm.dev' and vars.PUBLIC_GA_MEASUREMENT_ID is configured on the repository,
+# so forks and local builds never send data to Google hosts.
#
# First deploy (launch day): repository must be public, then Settings > Pages >
# Source = GitHub Actions, custom domain = egm.dev, Enforce HTTPS. Run this
@@ -58,6 +58,8 @@ jobs:
- run: npm ci
- run: npm run check
- run: npm run build
+ env:
+ PUBLIC_GA_MEASUREMENT_ID: ${{ vars.PUBLIC_GA_MEASUREMENT_ID }}
- uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
with:
path: site/dist
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 825a4ca..2b4f531 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -25,9 +25,46 @@ on:
permissions:
contents: read
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || format('{0}-{1}', github.ref, github.run_id) }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
jobs:
+ site-validation:
+ runs-on: ubuntu-24.04
+ defaults:
+ run:
+ working-directory: site
+ env:
+ ASTRO_TELEMETRY_DISABLED: '1'
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: 22
+ cache: npm
+ cache-dependency-path: site/package-lock.json
+ - run: npm ci
+ - run: npm test
+ - run: npm run check
+ - name: Build without analytics
+ run: |
+ npm run build
+ cp dist/index.html "$RUNNER_TEMP/egm-without-analytics.html"
+ env:
+ PUBLIC_GA_MEASUREMENT_ID: ''
+ - name: Build with synthetic analytics ID
+ run: npm run build
+ env:
+ PUBLIC_GA_MEASUREMENT_ID: G-TEST
+ - name: Verify browser consent ordering
+ run: npm run test:browser -- "$RUNNER_TEMP/egm-without-analytics.html"
+
unit:
strategy:
+ fail-fast: false
matrix:
os: [ubuntu-24.04, windows-2025]
runs-on: ${{ matrix.os }}
@@ -41,3 +78,23 @@ jobs:
- run: pip install pytest==8.3.5 pyyaml==6.0.2
- run: python -m pytest tests/unit
shell: bash
+
+ ci:
+ name: CI
+ if: ${{ always() }}
+ needs: [unit, site-validation]
+ runs-on: ubuntu-24.04
+ steps:
+ - name: Require successful validation
+ env:
+ NEEDS_JSON: ${{ toJSON(needs) }}
+ run: |
+ node <<'JS'
+ const jobs = JSON.parse(process.env.NEEDS_JSON);
+ for (const [name, job] of Object.entries(jobs)) {
+ if (job.result !== 'success') {
+ console.error(`${name}: ${job.result}`);
+ process.exitCode = 1;
+ }
+ }
+ JS
diff --git a/site/README.md b/site/README.md
index ec7475c..b545856 100644
--- a/site/README.md
+++ b/site/README.md
@@ -32,11 +32,47 @@ GitHub Pages.
## Rules
-- No analytics, no cookies, no third-party scripts, and no requests to Google
- hosts at runtime. The open-source release depends on it.
- Theme only through gBreeze tokens (`src/styles/tokens.css`) and the
components' documented custom properties. Do not restyle component boxes.
- Keep skill names and commands identical to the repository README.
+- **Cookies and analytics (`egm.dev` only)**: The EGM plugin itself collects zero
+ telemetry. On the canonical `https://egm.dev` site only (when
+ `PUBLIC_GA_MEASUREMENT_ID` is set at build time and
+ `window.location.hostname === 'egm.dev'`), the page loads Google Cookie
+ Notification Bar (`cookienotificationbar.min.js`). Google Analytics 4
+ (`gtag.js`) loads only after the bar reports an affirmative accepted choice
+ with `loaded.detail.required === true`. Pending, rejected, absent, and failed
+ consent initialization never load GA. CNB's non-required fallback is not
+ affirmative consent. The documented instance `statuschange` listener updates
+ Consent Mode v2. Revocation sets GA's measurement disable flag before queuing
+ denied consent and blocks later event/config calls. CNB uses a separate data
+ layer so its defaults cannot enable analytics or advertising. Google Signals
+ and advertising storage/personalization stay disabled. URLs and referrers are
+ scrubbed before configuration. External forks, preview domains, local builds,
+ and builds without a measurement ID make zero requests to Google hosts.
+
+### Consent integration contract
+
+The integration follows the public [CNB script](https://www.gstatic.com/glue/cookienotificationbar/cookienotificationbar.min.js)
+inspected on 2026-10-30 (SHA-256
+`e99eda4f401f141e55dcf8ccc1baa988e5165c99e89372d126841b8e7d26cd26`).
+Its constructor registers the global callback on `loaded`. After fetching
+configuration and storage, it emits `detail: { required, status }`. The
+autoloaded instance is available as `glue.CookieNotificationBar.instance`.
+Its `listen('statuschange', callback)` method receives `detail: { status }`.
+Its supported `customDataLayerName` option selects the data layer for its own
+consent commands. The browser fixtures model these source contracts.
+
+Google's [programmatic Analytics opt-out documentation](https://developers.google.com/tag-platform/security/guides/privacy#turn_off_google_analytics)
+states that the tag checks `ga-disable-MEASUREMENT_ID` before setting cookies
+or sending data. This check grounds revocation after the library has loaded,
+including automatic events that do not use the page's `gtag` wrapper.
+The flag is set before denied consent is queued.
+
+Browser checks intercept every network response. They verify pending and
+rejected consent, grant, revocation before and after script execution, regrant,
+and disabled builds. Their GA fixture implements the documented disable flag;
+these are integration regression checks, not a live Google library audit.
## Skill icons
diff --git a/site/astro.config.mjs b/site/astro.config.mjs
index 1f7f48b..cc123b6 100644
--- a/site/astro.config.mjs
+++ b/site/astro.config.mjs
@@ -2,7 +2,9 @@
import { defineConfig, fontProviders } from 'astro/config';
// Static landing site for https://egm.dev, deployed to GitHub Pages.
-// No analytics, no third-party scripts, no requests to Google hosts at runtime.
+// Analytics and Cookie Notification Bar load only on canonical egm.dev when
+// PUBLIC_GA_MEASUREMENT_ID is configured; forks and local builds make zero
+// runtime requests to Google hosts.
export default defineConfig({
site: 'https://egm.dev',
output: 'static',
diff --git a/site/package.json b/site/package.json
index c9a5241..2846410 100644
--- a/site/package.json
+++ b/site/package.json
@@ -8,6 +8,8 @@
"node": ">=22.23.4"
},
"scripts": {
+ "test": "node --test",
+ "test:browser": "node scripts/verify-analytics.mjs",
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
diff --git a/site/scripts/verify-analytics.mjs b/site/scripts/verify-analytics.mjs
new file mode 100644
index 0000000..12d22c3
--- /dev/null
+++ b/site/scripts/verify-analytics.mjs
@@ -0,0 +1,188 @@
+// Copyright 2026 Google LLC
+// SPDX-License-Identifier: Apache-2.0
+
+// Verify built HTML with controlled Google script responses, without telemetry.
+// Build once without an ID and save its HTML, then build with G-TEST:
+// npm run test:browser -- /path/to/disabled-build.html
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import puppeteer from 'puppeteer-core';
+
+const enabled = await readFile(new URL('../dist/index.html', import.meta.url), 'utf8');
+assert.ok(process.argv[2], 'Pass the HTML from the build without an analytics ID');
+const disabled = await readFile(process.argv[2], 'utf8');
+const browser = await puppeteer.launch({ channel: 'chrome', executablePath: process.env.CHROME_PATH });
+const results = [];
+
+async function visit(host, { failed = false, holdGtag = false, html = enabled } = {}) {
+ const page = await browser.newPage();
+ const requests = [];
+ const errors = [];
+ let releaseGtag;
+ let observedGtag;
+ const gtagRequested = new Promise(resolve => { observedGtag = resolve; });
+ page.on('pageerror', error => errors.push(error.message));
+ await page.setRequestInterception(true);
+ page.on('request', request => {
+ const url = new URL(request.url());
+ let body = '';
+ let contentType = 'text/plain';
+ if (url.hostname === 'www.gstatic.com' || url.hostname === 'www.googletagmanager.com') {
+ requests.push(request.url());
+ if (url.pathname.endsWith('cookienotificationbar.min.js')) {
+ if (failed) return void request.abort('failed');
+ contentType = 'application/javascript';
+ body = `window.__cookieScriptLoaded = true;
+ const layer = document.currentScript.dataset.glueCookieNotificationBarCustomDataLayerName;
+ const listeners = [];
+ window.glue = { CookieNotificationBar: { instance: {
+ listen: (name, listener) => { if (name === 'statuschange') listeners.push(listener); }
+ } } };
+ window.__finishConsent = (status = 'UNKNOWN', required = true) => {
+ window[layer] = window[layer] || [];
+ window[layer].unshift(['consent', 'update', { analytics_storage: 'granted' }]);
+ window.glueCookieNotificationBarLoaded({ detail: { required, status } });
+ };
+ window.__changeConsent = status => {
+ listeners.forEach(listener => listener({ detail: { status } }));
+ window[layer].push(['consent', 'update', { analytics_storage: status === 'ACCEPTED' ? 'granted' : 'denied' }]);
+ };`;
+ } else if (url.hostname === 'www.googletagmanager.com') {
+ contentType = 'application/javascript';
+ body = `window.__gaCommands = [];
+ window.__disabledAtDenial = [];
+ const processCommand = args => {
+ window.__gaCommands.push(Array.from(args));
+ if (args[0] === 'consent' && args[2].analytics_storage === 'denied') {
+ window.__disabledAtDenial.push(window['ga-disable-G-TEST']);
+ }
+ if (['event', 'config'].includes(args[0]) && !window['ga-disable-G-TEST']) {
+ fetch('https://www.google-analytics.com/g/collect?event=' + args[0]);
+ }
+ };
+ window.dataLayer.forEach(processCommand);
+ const push = window.dataLayer.push.bind(window.dataLayer);
+ window.dataLayer.push = (...commands) => { commands.forEach(processCommand); return push(...commands); };`;
+ } else {
+ contentType = 'text/css';
+ }
+ } else if (url.hostname === 'www.google-analytics.com') {
+ requests.push(request.url());
+ } else if (request.isNavigationRequest() && request.frame() === page.mainFrame()) {
+ contentType = 'text/html';
+ body = html;
+ }
+ // Respond to every request; nothing reaches Google or another network host.
+ const respond = () => request.respond({ status: 200, contentType, headers: { 'access-control-allow-origin': '*' }, body });
+ if (holdGtag && url.hostname === 'www.googletagmanager.com') {
+ releaseGtag = respond;
+ observedGtag();
+ } else {
+ void respond();
+ }
+ });
+ await page.goto(`https://${host}/?private=secret&utm_source=test#private`, { waitUntil: 'load' });
+ const gaRequests = () => requests.filter(url => new URL(url).hostname === 'www.googletagmanager.com');
+ const collects = () => requests.filter(url => new URL(url).hostname === 'www.google-analytics.com');
+ return { page, requests, gaRequests, collects, errors, gtagRequested, releaseGtag: () => releaseGtag() };
+}
+
+try {
+ const delayed = await visit('egm.dev');
+ assert.equal(await delayed.page.evaluate(() => window.__cookieScriptLoaded), true);
+ assert.equal(delayed.gaRequests().length, 0, 'GA must not load before asynchronous configuration completes');
+ assert.equal(await delayed.page.evaluate(() => window.dataLayer.some(args => args[0] === 'config')), false);
+ await delayed.page.evaluate(() => window.__finishConsent());
+ assert.equal(delayed.gaRequests().length, 0, 'pending consent must not load GA');
+ await delayed.page.evaluate(() => window.__changeConsent('REJECTED'));
+ assert.equal(delayed.gaRequests().length, 0, 'rejected consent must not load GA');
+ assert.equal(delayed.collects().length, 0);
+ await delayed.page.evaluate(() => window.__changeConsent('ACCEPTED'));
+ await delayed.page.waitForFunction(() => window.__gaCommands !== undefined);
+ await delayed.page.waitForFunction(() => window.__gaCommands.some(args => args[0] === 'config'));
+ assert.equal(delayed.gaRequests().length, 1);
+ const config = await delayed.page.evaluate(() => window.__gaCommands.find(args => args[0] === 'config')[2]);
+ assert.equal(config.page_location, 'https://egm.dev/?utm_source=test');
+ assert.equal(config.allow_google_signals, false);
+ assert.equal(config.allow_ad_personalization_signals, false);
+ await delayed.page.waitForNetworkIdle();
+ assert.equal(delayed.collects().length, 1, 'grant must permit the initial measurement');
+ results.push({ case: 'pending, rejected, then granted', pass: true, requests: [...delayed.requests] });
+
+ await delayed.page.evaluate(() => {
+ window.gtag('event', 'positive_control');
+ });
+ await delayed.page.waitForNetworkIdle();
+ assert.equal(delayed.collects().length, 2, 'event fixture must send before revocation');
+ await delayed.page.evaluate(() => {
+ window.__changeConsent('REJECTED');
+ window.gtag('event', 'after_revocation');
+ window.gtag('config', 'G-TEST');
+ });
+ await delayed.page.waitForNetworkIdle();
+ assert.equal(delayed.collects().length, 2, 'revocation must prevent later measurements');
+ assert.equal(await delayed.page.evaluate(() => window['ga-disable-G-TEST']), true);
+ assert.equal(await delayed.page.evaluate(() => window.__disabledAtDenial.at(-1)), true);
+ results.push({ case: 'revocation blocks future measurements', pass: true });
+
+ await delayed.page.evaluate(() => {
+ window.__changeConsent('ACCEPTED');
+ window.gtag('event', 'after_regrant');
+ });
+ await delayed.page.waitForNetworkIdle();
+ assert.equal(delayed.collects().length, 3, 'a new affirmative grant must permit later events');
+ assert.equal(delayed.gaRequests().length, 1, 'regrant must reuse the loaded script');
+ results.push({ case: 'regrant resumes measurements without duplicate loading', pass: true });
+
+ await delayed.page.evaluate(() => { window.__finishConsent(); window.__finishConsent(); });
+ assert.equal(await delayed.page.evaluate(() => document.querySelectorAll('script[src*="googletagmanager.com"]').length), 1);
+ assert.equal(await delayed.page.evaluate(() => window.dataLayer.filter(args => args[0] === 'config').length), 1);
+ assert.deepEqual(delayed.errors, []);
+ results.push({ case: 'repeated callbacks', pass: true });
+ await delayed.page.close();
+
+ const race = await visit('egm.dev', { holdGtag: true });
+ await race.page.evaluate(() => window.__finishConsent('ACCEPTED'));
+ await race.gtagRequested;
+ assert.equal(await race.page.evaluate(() => window.__gaCommands), undefined);
+ await race.page.evaluate(() => window.__changeConsent('REJECTED'));
+ assert.equal(await race.page.evaluate(() => window['ga-disable-G-TEST']), true);
+ await race.releaseGtag();
+ await race.page.waitForFunction(() => window.__gaCommands !== undefined);
+ await race.page.waitForNetworkIdle();
+ assert.equal(race.collects().length, 0, 'revoking before the script executes must prevent queued measurements');
+ assert.deepEqual(race.errors, []);
+ results.push({ case: 'grant then revoke before GA response executes', pass: true });
+ await race.page.close();
+
+ for (const [status, required] of [['REJECTED', true], ['ACCEPTED', false], ['ACCEPTED', true]]) {
+ const initial = await visit('egm.dev');
+ await initial.page.evaluate((state, needed) => window.__finishConsent(state, needed), status, required);
+ await initial.page.waitForNetworkIdle();
+ const granted = status === 'ACCEPTED' && required;
+ assert.equal(initial.gaRequests().length, granted ? 1 : 0);
+ assert.equal(initial.collects().length, granted ? 1 : 0);
+ assert.deepEqual(initial.errors, []);
+ results.push({ case: `initial ${status}, required=${required}`, pass: true });
+ await initial.page.close();
+ }
+
+ const failure = await visit('egm.dev', { failed: true });
+ assert.equal(failure.gaRequests().length, 0);
+ assert.equal(await failure.page.evaluate(() => window.dataLayer.some(args => args[0] === 'config')), false);
+ assert.deepEqual(failure.errors, []);
+ results.push({ case: 'cookie script failure', pass: true });
+ await failure.page.close();
+
+ for (const [host, html] of [['preview.example.com', enabled], ['localhost', enabled], ['egm.dev', disabled]]) {
+ const gated = await visit(host, { html });
+ assert.equal(gated.requests.length, 0);
+ assert.equal(await gated.page.evaluate(() => window.dataLayer === undefined), true);
+ assert.deepEqual(gated.errors, []);
+ results.push({ case: host === 'egm.dev' ? 'measurement ID unset' : `noncanonical ${host}`, pass: true });
+ await gated.page.close();
+ }
+ console.log(JSON.stringify({ browser: await browser.version(), googleResponses: 'intercepted fixtures; no live vendor verification', results }, null, 2));
+} finally {
+ await browser.close();
+}
diff --git a/site/src/components/Footer.astro b/site/src/components/Footer.astro
index 7a77635..3746efe 100644
--- a/site/src/components/Footer.astro
+++ b/site/src/components/Footer.astro
@@ -43,6 +43,15 @@ const links = [
</li>
))
}
+ <li class="cookie-control-item">
+ <button
+ type="button"
+ class="cookie-control glue-cookie-notification-bar-control"
+ aria-hidden="true"
+ >
+ Cookies management controls
+ </button>
+ </li>
</ul>
</nav>
</div>
@@ -92,17 +101,31 @@ const links = [
gap: 4px 20px;
}
- li a {
+ li a,
+ .cookie-control {
display: inline-flex;
align-items: center;
min-block-size: 24px;
font: var(--md-sys-typescale-label-md);
text-decoration: none;
color: var(--md-sys-color-on-surface-variant);
+ background: none;
+ border: 0;
+ padding: 0;
+ cursor: pointer;
}
- li a:hover {
+ li a:hover,
+ .cookie-control:hover {
color: var(--md-sys-color-on-surface);
text-decoration: underline;
}
+
+ .cookie-control[aria-hidden='true'] {
+ display: none;
+ }
+
+ .cookie-control-item:has(.cookie-control[aria-hidden='true']) {
+ display: none;
+ }
</style>
diff --git a/site/src/layouts/Base.astro b/site/src/layouts/Base.astro
index 9d2563b..e626d77 100644
--- a/site/src/layouts/Base.astro
+++ b/site/src/layouts/Base.astro
@@ -22,6 +22,7 @@ interface Props {
const { title, description } = Astro.props;
const canonical = new URL(Astro.url.pathname, Astro.site);
const ogImage = new URL('/og.png', Astro.site);
+const gaMeasurementId = import.meta.env.PUBLIC_GA_MEASUREMENT_ID ?? '';
---
<!doctype html>
@@ -50,6 +51,123 @@ const ogImage = new URL('/og.png', Astro.site);
<meta name="twitter:image" content={ogImage} />
<Font cssVariable="--font-display" preload />
<Font cssVariable="--font-mono" />
+ {
+ gaMeasurementId && (
+ <script is:inline define:vars={{ gaMeasurementId, pageTitle: title }}>
+ // Load Google Cookie Notification Bar + GA4 only on canonical egm.dev so
+ // forks and local builds never send telemetry to Google servers.
+ if (window.location.hostname === 'egm.dev' && gaMeasurementId) {
+ window.dataLayer = window.dataLayer || [];
+ let analyticsAllowed = false;
+ const disableAnalytics = 'ga-disable-' + gaMeasurementId;
+ window[disableAnalytics] = true;
+ function gtag() {
+ if (!analyticsAllowed && (arguments[0] === 'event' || arguments[0] === 'config')) return;
+ window.dataLayer.push(arguments);
+ }
+ window.gtag = gtag;
+
+ gtag('consent', 'default', {
+ ad_storage: 'denied',
+ ad_user_data: 'denied',
+ ad_personalization: 'denied',
+ analytics_storage: 'denied',
+ wait_for_update: 500,
+ });
+ gtag('set', 'ads_data_redaction', true);
+ gtag('set', 'allow_google_signals', false);
+ gtag('set', 'allow_ad_personalization_signals', false);
+
+ const allowedParams = new Set([
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_term',
+ 'utm_content',
+ 'gclid',
+ 'dclid',
+ 'gclsrc',
+ ]);
+ const cleanUrl = new URL(window.location.href);
+ for (const key of Array.from(cleanUrl.searchParams.keys())) {
+ if (!allowedParams.has(key.toLowerCase())) {
+ cleanUrl.searchParams.delete(key);
+ }
+ }
+ cleanUrl.hash = '';
+
+ let cleanReferrer = '';
+ if (document.referrer) {
+ try {
+ const refUrl = new URL(document.referrer);
+ cleanReferrer = refUrl.origin + refUrl.pathname;
+ } catch {
+ cleanReferrer = '';
+ }
+ }
+
+ const cnbCss = document.createElement('link');
+ cnbCss.rel = 'stylesheet';
+ cnbCss.href =
+ 'https://www.gstatic.com/glue/cookienotificationbar/cookienotificationbar.min.css';
+ document.head.appendChild(cnbCss);
+
+ let analyticsStarted = false;
+ const applyConsent = (status) => {
+ analyticsAllowed = status === 'ACCEPTED';
+ window[disableAnalytics] = !analyticsAllowed;
+ gtag('consent', 'update', {
+ analytics_storage: analyticsAllowed ? 'granted' : 'denied',
+ ad_storage: 'denied',
+ ad_user_data: 'denied',
+ ad_personalization: 'denied',
+ });
+ if (!analyticsAllowed) return;
+ if (analyticsStarted) return;
+ analyticsStarted = true;
+
+ gtag('js', new Date());
+ gtag('config', gaMeasurementId, {
+ page_location: cleanUrl.toString(),
+ page_referrer: cleanReferrer,
+ page_title: pageTitle,
+ allow_google_signals: false,
+ allow_ad_personalization_signals: false,
+ });
+
+ const gtagScript = document.createElement('script');
+ gtagScript.async = true;
+ gtagScript.src =
+ 'https://www.googletagmanager.com/gtag/js?id=' +
+ encodeURIComponent(gaMeasurementId);
+ document.head.appendChild(gtagScript);
+ };
+ let consentBar;
+ window.glueCookieNotificationBarLoaded = (event) => {
+ // CNB defaults to ACCEPTED when no banner is required, including
+ // configuration fetch failure. That is not affirmative consent.
+ const instance = window.glue?.CookieNotificationBar?.instance;
+ if (event?.detail?.required !== true || !instance || consentBar) return;
+ consentBar = instance;
+ instance.listen('statuschange', (change) => applyConsent(change.detail?.status));
+ applyConsent(event.detail.status);
+ };
+
+ const cnbScript = document.createElement('script');
+ cnbScript.src =
+ 'https://www.gstatic.com/glue/cookienotificationbar/cookienotificationbar.min.js';
+ cnbScript.dataset.glueCookieNotificationBarCategory = '2A';
+ cnbScript.dataset.glueCookieNotificationBarSiteId = 'egm.dev';
+ cnbScript.dataset.glueCookieNotificationBarAutoMarginClass = 'footer';
+ // CNB's defaults can grant storage independently of an explicit choice.
+ // Keep those commands separate; the status listener owns GA consent.
+ cnbScript.dataset.glueCookieNotificationBarCustomDataLayerName = 'cookieConsentDataLayer';
+ document.head.appendChild(cnbScript);
+
+ }
+ </script>
+ )
+ }
</head>
<body>
<a class="skip-link" href="#main">Skip to content</a>
diff --git a/site/tests/analytics.test.mjs b/site/tests/analytics.test.mjs
new file mode 100644
index 0000000..89d1f6c
--- /dev/null
+++ b/site/tests/analytics.test.mjs
@@ -0,0 +1,140 @@
+// Copyright 2026 Google LLC
+// SPDX-License-Identifier: Apache-2.0
+
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import vm from 'node:vm';
+
+const layout = readFileSync(new URL('../src/layouts/Base.astro', import.meta.url), 'utf8');
+const source = layout.match(/<script is:inline define:vars=\{\{ gaMeasurementId, pageTitle: title \}\}>([\s\S]*?)<\/script>/)[1];
+
+function page({ hostname = 'egm.dev', measurementId = 'G-TEST' } = {}) {
+ const elements = [];
+ const window = {
+ location: {
+ hostname,
+ href: `https://${hostname}/guide?private=secret&utm_source=test#private`,
+ },
+ };
+ const document = {
+ referrer: 'https://example.com/start?private=secret#private',
+ createElement: (tag) => ({ tag, dataset: {} }),
+ head: {
+ appendChild: (element) => {
+ if (element.src?.includes('cookienotificationbar.min.js')) {
+ assert.equal(typeof window.glueCookieNotificationBarLoaded, 'function');
+ }
+ elements.push(element);
+ },
+ },
+ };
+ vm.runInNewContext(source, {
+ window, document, URL, gaMeasurementId: measurementId, pageTitle: 'EGM',
+ });
+ const gaScripts = () => elements.filter((element) => element.src?.includes('googletagmanager.com'));
+ const commands = () => Array.from(window.dataLayer ?? [], (args) => Array.from(args));
+ function loadConsent({ required = true, status = 'UNKNOWN' } = {}) {
+ const listeners = [];
+ const instance = { listen: (name, listener) => {
+ assert.equal(name, 'statuschange');
+ listeners.push(listener);
+ } };
+ window.glue = { CookieNotificationBar: { instance } };
+ const cookieScript = elements.find(element => element.src?.includes('cookienotificationbar.min.js'));
+ const layer = cookieScript.dataset.glueCookieNotificationBarCustomDataLayerName;
+ window[layer] = [];
+ window[layer].unshift(['consent', 'update', { analytics_storage: 'granted' }]);
+ const loaded = () => window.glueCookieNotificationBarLoaded({ detail: { required, status } });
+ loaded();
+ return {
+ loaded,
+ change: next => {
+ listeners.forEach(listener => listener({ detail: { status: next } }));
+ window[layer].push(['consent', 'update', { analytics_storage: next === 'ACCEPTED' ? 'granted' : 'denied' }]);
+ },
+ };
+ }
+ return { window, elements, gaScripts, commands, loadConsent };
+}
+
+test('pending and rejected consent never load GA; a later affirmative choice starts it', () => {
+ const p = page();
+ const cookieScript = p.elements.find((element) => element.src?.includes('cookienotificationbar.min.js'));
+ assert.ok(cookieScript);
+ assert.equal(typeof p.window.glueCookieNotificationBarLoaded, 'function');
+ assert.equal(p.gaScripts().length, 0);
+ assert.equal(p.commands().some(([command]) => command === 'config'), false);
+
+ // Loading the JS alone does not mean its asynchronous configuration is ready.
+ cookieScript.onload?.();
+ assert.equal(p.gaScripts().length, 0);
+
+ const consent = p.loadConsent();
+ assert.equal(p.gaScripts().length, 0);
+ consent.change('REJECTED');
+ p.window.gtag('event', 'should_not_send');
+ assert.equal(p.gaScripts().length, 0);
+ assert.equal(p.commands().some(([command]) => command === 'event'), false);
+ consent.change('ACCEPTED');
+ assert.equal(p.gaScripts().length, 1);
+ const commands = p.commands();
+ assert.ok(commands.findIndex(([command, type, value]) => command === 'consent' && type === 'update' && value.analytics_storage === 'granted')
+ < commands.findIndex(([command]) => command === 'config'));
+ const config = commands.find(([command]) => command === 'config')[2];
+ assert.equal(config.page_location, 'https://egm.dev/guide?utm_source=test');
+ assert.equal(config.page_referrer, 'https://example.com/start');
+ assert.equal(config.allow_google_signals, false);
+ assert.equal(config.allow_ad_personalization_signals, false);
+ assert.equal(p.window['ga-disable-G-TEST'], false);
+});
+
+test('failed cookie-bar initialization never starts GA', () => {
+ const p = page();
+ assert.equal(p.gaScripts().length, 0);
+ assert.equal(p.commands().some(([command]) => command === 'config'), false);
+ assert.equal(p.commands()[0][2].analytics_storage, 'denied');
+});
+
+test('stored affirmative choice starts GA once and revocation blocks future events', () => {
+ const p = page();
+ const consent = p.loadConsent({ status: 'ACCEPTED' });
+ consent.loaded();
+ assert.equal(p.gaScripts().length, 1);
+ assert.equal(p.commands().filter(([command]) => command === 'config').length, 1);
+ consent.change('REJECTED');
+ assert.equal(p.window['ga-disable-G-TEST'], true);
+ p.window.gtag('event', 'after_revocation');
+ p.window.gtag('config', 'G-TEST');
+ assert.equal(p.commands().some(([command]) => command === 'event'), false);
+ assert.equal(p.commands().filter(([command]) => command === 'config').length, 1);
+ assert.equal(p.commands().at(-1)[2].analytics_storage, 'denied');
+ consent.change('ACCEPTED');
+ assert.equal(p.window['ga-disable-G-TEST'], false);
+ assert.equal(p.gaScripts().length, 1);
+});
+
+for (const options of [{ status: 'REJECTED' }, { required: false, status: 'ACCEPTED' }]) {
+ test(`loaded does not imply affirmative consent: ${JSON.stringify(options)}`, () => {
+ const p = page();
+ p.loadConsent(options);
+ assert.equal(p.gaScripts().length, 0);
+ assert.equal(p.window['ga-disable-G-TEST'], true);
+ });
+}
+
+test('loaded callback without valid vendor details fails closed', () => {
+ const p = page();
+ p.window.glueCookieNotificationBarLoaded();
+ p.window.glueCookieNotificationBarLoaded({ detail: { required: true, status: 'ACCEPTED' } });
+ assert.equal(p.gaScripts().length, 0);
+});
+
+for (const options of [{ hostname: 'localhost' }, { hostname: 'preview.example.com' }, { measurementId: '' }]) {
+ test(`no Google resources outside the configured canonical site: ${JSON.stringify(options)}`, () => {
+ const p = page(options);
+ assert.equal(p.elements.length, 0);
+ assert.equal(p.window.glueCookieNotificationBarLoaded, undefined);
+ assert.equal(p.window.dataLayer, undefined);
+ });
+}