Skip to content

frontend(fix): keep GA4 on the production hosts and the e2e suite offline - #586

Merged
Ducksss merged 1 commit into
mainfrom
claude/upbeat-bell-2dfaff
Oct 1, 2026
Merged

Ducksss merged 1 commit into
mainfrom
claude/upbeat-bell-2dfaff

Conversation

@Ducksss

@Ducksss Ducksss commented Oct 1, 2026

Copy link
Copy Markdown
Owner

Summary

src/lib/analytics.ts says analytics must never run off the production hosts: "Local dev and preview deploys must never write into the production dataset or leak unreleased route paths to a third party." PostHog followed that rule. GA4 did not. AnalyticsShell mounted gtag/js?id=G-EMGRZ0H9R9 and the inline gtag('config', …) whenever consent was granted, on any host, and trackEvent called window.gtag('event', …) without a host check. A local production build on localhost:3100 with consent granted sent real POST https://www.google-analytics.com/g/collect hits. That happened in local dev, on SSO-protected Vercel previews (any reviewer who accepted the banner), and in the e2e suite. Every spec but consent.e2e grants consent up front, so each e2e run likely sent localhost page views to the production property.

The fix

  • isGoogleTagHost() (new, exported from src/lib/analytics.ts) applies the PostHog host rule to GA4: payload-components.xyz and www.payload-components.xyz only. It returns false during server rendering.
  • AnalyticsShell mounts the two GA4 <Script>s only when consent === 'granted' && isGoogleTagHost(). The consent gate is unchanged. AnalyticsPageview still mounts on consent alone, because PostHog capture already has its own host gate.
  • trackEvent re-checks the host before window.gtag('event', …), the way it already re-checks consent. A gtag defined by anything else gets nothing off production.

Keeping the e2e coverage (and the suite offline)

GA4 no longer mounts on localhost, so the specs that assert on the tag opt back in through one helper, mountGoogleTagOffline(context) in tests/e2e/consent.ts:

  1. It routes every Google domain the CSP admits for GA4 (googletagmanager.com, google-analytics.com, analytics.google.com, and their subdomains) to local stubs. gtag.js gets an empty script, and anything else gets a 204. The browser checks the CSP before a request reaches the route, so the stub is still held to script-src.
  2. Then it sets the site's test hook, window.__allowGoogleTagOnTestHost, in an init script. It follows the existing __disablePostHogNetwork pattern, and nothing else sets it.

The helper is used file-wide in consent.e2e and frontend.e2e, and in the one templates.e2e test that asserts on the tag. Without it, the consent spec's "no GA script" assertions would pass on localhost for the wrong reason. Specs that only grant consent (blog, blog-visual, templates-visual, webkit-landing) now load nothing from Google at all.

A backstop: the Chromium project now launches with --host-resolver-rules mapping those same domains to ~NOTFOUND. A future spec that mounted the real tag still couldn't reach the property. Stubbed routes never need DNS, so they are unaffected.

New coverage

  • consent.e2e: "keeps GA4 off every host but production, even after opting in". It uses a context without the hook. It accepts on the real banner and waits for the PostHog $pageview, which proves the opt-in reached AnalyticsShell. Then it asserts no GA script, and that a tracked copy action never reaches a pre-defined window.gtag.
  • tests/int/analytics-contract.int.spec.ts: e2e can't run on the real hosts, so this pins both sides of the gate. isGoogleTagHost() is true on the two production hosts, false on localhost, 127.0.0.1, a *.vercel.app preview, a subdomain, and a lookalike suffix, and true behind the hook. trackInstallCommandCopy reaches gtag only from production. Mutation-checked: removing the trackEvent host check fails it.
  • content/docs/contributing.mdx: the host-gate paragraph now covers GA4 as well as PostHog, and the "Tests grant consent explicitly" rule names mountGoogleTagOffline.

The /privacy copy says what runs and when (after consent), not where, so it needed no change.

⚠️ Interaction with #584

#584 adds tests/e2e/content-security-policy.e2e.spec.ts. After accepting, it asserts script#google-tag is attached on each surface, on localhost. That spec isn't on main yet, so this PR can't update it. Whichever of the two merges second needs one line in that spec's watchPolicy: await mountGoogleTagOffline(context). Its own catch-all third-party route can stay. There is no file overlap between the two PRs.

Test plan

  • pnpm lint
  • pnpm exec tsc --noEmit
  • pnpm run test:int: 64 files and 796 tests passed. The 1 skipped test was already skipped on main.
  • E2E_PORT=3157 pnpm build:e2e && E2E_PORT=3157 PLAYWRIGHT_SERVER_MODE=production pnpm test:e2e consent frontend templates: 359 passed, 0 failed, in 4.3 min. The 152 skips are the Linux-only visual-baseline comparisons on darwin. The templates filter also matches templates-a11y and templates-visual, so 511 tests in all.
  • Egress check (throwaway harness, not committed): I ran the entire e2e suite (412 passed, 240 skipped, 0 failed) with Chromium sent through a logging forward proxy. The DNS backstop was removed for this run, so the log measures the host gate and the stubs alone. A 30-second heartbeat shows the proxy was up for the whole run. The WebKit project wasn't proxied. It runs only webkit-landing, which never sets the hook and also runs, proxied, under the Chromium project.
    • 0 connection attempts to googletagmanager.com, google-analytics.com, or analytics.google.com.
    • Positive control, run right after: setting the hook without the stubs logged CONNECT www.googletagmanager.com:443, so the method catches a leak.
    • Everything else in the log is Chromium's own background services (www.google.com, accounts.google.com, android.clients.google.com, clients2.google.com/time, content-autofill.googleapis.com). A blank tab makes them with no site loaded, and the site's pages made zero non-localhost requests. The enforced CSP would refuse page-initiated requests to those hosts anyway. The *.test hosts are the reserved fake origins in the collection-query and contact-form specs.
  • DNS backstop check: with no stubs, navigations to all six Google host patterns fail with net::ERR_NAME_NOT_RESOLVED under the committed config, and localhost still resolves.

🤖 Generated with Claude Code

…line

analytics.ts says local dev and preview deploys must never write into the
production dataset. PostHog's capture followed that rule, but GA4 did not:
AnalyticsShell mounted gtag.js and the inline config whenever consent was
granted, on any host, and trackEvent called window.gtag without a host
check. A local production build sent real g/collect hits, and so did
reviewers on Vercel previews and every e2e spec that grants consent.

isGoogleTagHost() applies the same production-host rule to GA4.
AnalyticsShell now mounts the tag only for granted consent on a
production host, and trackEvent re-checks the host before calling gtag.
The consent gate is unchanged.

The specs that assert on the tag opt back in through
mountGoogleTagOffline in tests/e2e/consent.ts. It routes every Google
origin the CSP admits for GA4 to a local stub, then sets the
__allowGoogleTagOnTestHost hook. The browser still checks the CSP before
the route, and nothing leaves the machine. As a backstop, the Chromium
project resolves those domains to nothing.

consent.e2e gains a hook-free test that pins the host gate in a real
browser. The analytics contract int spec pins both sides of the gate,
since e2e cannot run on the production hosts. The contributing docs now
say GA4 is host-limited too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 1, 2026 02:18
@vercel

vercel Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
payload-components Ready Ready Preview Oct 1, 2026 2:21am UTC
payload-components-97bf Ready Ready Preview Oct 1, 2026 2:21am UTC

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Oct 1, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 47 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository: Ducksss/payload-components/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: a1c5ea30-3f93-4fde-b180-02ceb774d48c

📥 Commits

Reviewing files that changed from the base of the PR and between ac916f5 and 5a431e0.

📒 Files selected for processing (9)
  • content/docs/contributing.mdx
  • playwright.config.ts
  • src/components/site/AnalyticsShell.tsx
  • src/lib/analytics.ts
  • tests/e2e/consent.e2e.spec.ts
  • tests/e2e/consent.ts
  • tests/e2e/frontend.e2e.spec.ts
  • tests/e2e/templates.e2e.spec.ts
  • tests/int/analytics-contract.int.spec.ts
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Ducksss
Ducksss merged commit ebd4f6e into main Oct 1, 2026
17 checks passed
@Ducksss
Ducksss deleted the claude/upbeat-bell-2dfaff branch October 1, 2026 11:38
Ducksss added a commit that referenced this pull request Oct 1, 2026
…-gated

GA4 now mounts on the production hosts only (#586), so on localhost accepting
consent no longer attaches script#google-tag, and the Accept walk in
content-security-policy.e2e.spec.ts fails at its toBeAttached check.
watchPolicy now opts the host back in through mountGoogleTagOffline, which
stubs every Google origin before it sets the test hook. The Decline walk keeps
the hook too, so it also proves that declining mounts nothing on an allowed host.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ducksss added a commit that referenced this pull request Oct 1, 2026
#584)

* config(fix): tighten the enforced CSP and browser-test it on every run

main has enforced a Content-Security-Policy since #554. This hardens it and
gives it the feedback loop a backend-free site can have.

- script-src-attr 'none' refuses inline event-handler attributes, the
  injection path that 'unsafe-inline' otherwise leaves open. React never
  renders them: all 318 prerendered routes contain none.
- frame-src 'self' drops six unused third-party embed origins. Only the
  same-origin component and template previews frame, and the Embed Basic
  catalog demo is a faux player.
- https://www.google-analytics.com is dropped; *.google-analytics.com
  already covers it.
- Script elements keep 'unsafe-inline'. Next streams build-specific inline
  RSC scripts into every static page (1,028 distinct hashes across 318
  routes, 999 of them on a single route, changing with each deploy), and
  nonces would force dynamic rendering. JSON-LD data blocks are not policed
  by script-src.
- The policy stays enforced rather than report-only. With no collector,
  report-only output would only reach visitors' consoles (see #546).
  tests/e2e/content-security-policy.e2e.spec.ts fails on any violation
  across the landing page, docs, catalog, both preview frames, templates,
  blog and case study, with consent declined and accepted. It also checks
  the served header on documents and preview frames.
- The int spec pins every directive exactly, plus the dev-only eval and
  Vercel debug allowances and the origin derived from
  NEXT_PUBLIC_POSTHOG_HOST.
- The stale CSP paragraph in docs/ai-discovery is refreshed, and AGENTS.md
  gains a gotcha for adding third-party origins.

Refs #521

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(fix): mount GA4 offline in the CSP walk now that the tag is host-gated

GA4 now mounts on the production hosts only (#586), so on localhost accepting
consent no longer attaches script#google-tag, and the Accept walk in
content-security-policy.e2e.spec.ts fails at its toBeAttached check.
watchPolicy now opts the host back in through mountGoogleTagOffline, which
stubs every Google origin before it sets the test hook. The Decline walk keeps
the hook too, so it also proves that declining mounts nothing on an allowed host.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

2 active deployments
Preview – payload-components — 5a431e00 Deployed Oct 1, 2026 by vercel[bot]
Preview – payload-components-97bf — 5a431e00 Deployed Oct 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants