Repository navigation
frontend(fix): keep GA4 on the production hosts and the e2e suite offline - #586
Merged
Merged
Conversation
…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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Review limit reachedYou'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. View limit detailsLimit details: You’ve used the included review currently available. Review configuration: ⚙️ Run configurationConfiguration used: Repository: Ducksss/payload-components/.coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (9)
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. Comment |
4 of 5 tasks
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]>
5 of 6 tasks
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
src/lib/analytics.tssays 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.AnalyticsShellmountedgtag/js?id=G-EMGRZ0H9R9and the inlinegtag('config', …)whenever consent wasgranted, on any host, andtrackEventcalledwindow.gtag('event', …)without a host check. A local production build onlocalhost:3100with consent granted sent realPOST https://www.google-analytics.com/g/collecthits. That happened in local dev, on SSO-protected Vercel previews (any reviewer who accepted the banner), and in the e2e suite. Every spec butconsent.e2egrants consent up front, so each e2e run likely sentlocalhostpage views to the production property.The fix
isGoogleTagHost()(new, exported fromsrc/lib/analytics.ts) applies the PostHog host rule to GA4:payload-components.xyzandwww.payload-components.xyzonly. It returnsfalseduring server rendering.AnalyticsShellmounts the two GA4<Script>s only whenconsent === 'granted' && isGoogleTagHost(). The consent gate is unchanged.AnalyticsPageviewstill mounts on consent alone, because PostHog capture already has its own host gate.trackEventre-checks the host beforewindow.gtag('event', …), the way it already re-checks consent. Agtagdefined 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)intests/e2e/consent.ts:googletagmanager.com,google-analytics.com,analytics.google.com, and their subdomains) to local stubs.gtag.jsgets 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 toscript-src.window.__allowGoogleTagOnTestHost, in an init script. It follows the existing__disablePostHogNetworkpattern, and nothing else sets it.The helper is used file-wide in
consent.e2eandfrontend.e2e, and in the onetemplates.e2etest 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-rulesmapping 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 reachedAnalyticsShell. Then it asserts no GA script, and that a tracked copy action never reaches a pre-definedwindow.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.apppreview, a subdomain, and a lookalike suffix, and true behind the hook.trackInstallCommandCopyreachesgtagonly from production. Mutation-checked: removing thetrackEventhost 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 namesmountGoogleTagOffline.The
/privacycopy says what runs and when (after consent), not where, so it needed no change.#584 adds
tests/e2e/content-security-policy.e2e.spec.ts. After accepting, it assertsscript#google-tagis attached on each surface, on localhost. That spec isn't onmainyet, so this PR can't update it. Whichever of the two merges second needs one line in that spec'swatchPolicy:await mountGoogleTagOffline(context). Its own catch-all third-party route can stay. There is no file overlap between the two PRs.Test plan
pnpm lintpnpm exec tsc --noEmitpnpm run test:int: 64 files and 796 tests passed. The 1 skipped test was already skipped onmain.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. Thetemplatesfilter also matchestemplates-a11yandtemplates-visual, so 511 tests in all.webkit-landing, which never sets the hook and also runs, proxied, under the Chromium project.googletagmanager.com,google-analytics.com, oranalytics.google.com.CONNECT www.googletagmanager.com:443, so the method catches a leak.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*.testhosts are the reserved fake origins in the collection-query and contact-form specs.net::ERR_NAME_NOT_RESOLVEDunder the committed config, and localhost still resolves.🤖 Generated with Claude Code