diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1617d631..1e75627f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -140,8 +140,9 @@ jobs: grep -q 'src="/runtime-config.js"' out/index.html - name: Install Playwright's Chromium run: npx playwright install --with-deps chromium + # Includes: a self-hosted install never loads Google's tag. - name: Self-host checks - run: npx playwright test e2e/selfhost.spec.ts + run: npx playwright test e2e/selfhost.spec.ts e2e/google-analytics.spec.ts --project=chromium env: E2E_STATIC: "1" diff --git a/dashboard/e2e/google-analytics.spec.ts b/dashboard/e2e/google-analytics.spec.ts new file mode 100644 index 00000000..9c46aa26 --- /dev/null +++ b/dashboard/e2e/google-analytics.spec.ts @@ -0,0 +1,95 @@ +import { expect, test, type BrowserContext, type Route } from "@playwright/test"; + +// Google Analytics on app.coderhelm.com (components/google-analytics.tsx): +// a page view on the first load and on every client-side route change, with +// the address cut to origin and path. A self-hosted install, and any other +// host, loads nothing. The built dashboard is served as app.coderhelm.com; +// Google's tag is answered here with an empty script, so the page views are +// read from the dataLayer it would have sent. + +const APP = "https://app.coderhelm.com"; + +type Sent = { tag: string[] }; + +async function serveAsApp(context: BrowserContext, baseURL: string, runtimeConfig: string | null): Promise { + const sent: Sent = { tag: [] }; + const json = (route: Route, body: unknown, status = 200) => + route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + const api = async (route: Route) => { + const p = new URL(route.request().url()).pathname; + if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "an-admin", email: "admin@coderhelm.com", avatar_url: "", role: "owner" }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] }); + return json(route, { error: "Not mocked" }, 404); + }; + await context.route((u) => /^\/(api|auth)\//.test(u.pathname), api); + await context.route(`${APP}/**`, async (route) => { + const u = new URL(route.request().url()); + if (/^\/(api|auth)\//.test(u.pathname)) return api(route); + if (u.pathname === "/runtime-config.js" && runtimeConfig !== null) { + return route.fulfill({ contentType: "text/javascript", body: runtimeConfig }); + } + const response = await route.fetch({ url: `${baseURL}${u.pathname}${u.search}` }); + await route.fulfill({ response }); + }); + await context.route("https://www.googletagmanager.com/**", (route) => { + sent.tag.push(route.request().url()); + return route.fulfill({ contentType: "text/javascript", body: "" }); + }); + await context.route(/google-analytics\.com|analytics\.google\.com/, (route) => { + sent.tag.push(route.request().url()); + return route.fulfill({ status: 204 }); + }); + return sent; +} + +/** The page_view events gtag was given, as page_location values. */ +const pageViews = () => + ((window as unknown as { dataLayer?: IArguments[] }).dataLayer ?? []) + .map((a) => Array.from(a)) + .filter((a) => a[0] === "event" && a[1] === "page_view") + .map((a) => (a[2] as { page_location: string }).page_location); + +test("app.coderhelm.com: page views on the first load and on client-side route changes, origin and path only", async ({ browser, baseURL }) => { + const context = await browser.newContext(); + const sent = await serveAsApp(context, baseURL!, null); + const page = await context.newPage(); + await page.goto(`${APP}/?tab=secret&id=abc#frag`); + await expect.poll(() => page.evaluate(pageViews)).toEqual([`${APP}/`]); + expect(sent.tag).toEqual(["https://www.googletagmanager.com/gtag/js?id=G-6C41CN6BC6"]); + const config = await page.evaluate(() => + ((window as unknown as { dataLayer: IArguments[] }).dataLayer).map((a) => Array.from(a)).filter((a) => a[0] === "config").at(-1)?.[2], + ); + expect(config).toMatchObject({ send_page_view: false, page_location: `${APP}/`, allow_google_signals: false, allow_ad_personalization_signals: false }); + + // A client-side route change is a page view of its own, on the same document. + await page.getByRole("link", { name: /^Settings(\s|$)/ }).first().click(); + await expect(page).toHaveURL(/\/settings\/?/); + await expect.poll(() => page.evaluate(pageViews)).toEqual([`${APP}/`, expect.stringMatching(new RegExp(`^${APP}/settings/?$`))]); + expect(sent.tag).toHaveLength(1); + await context.close(); +}); + +test("a self-hosted install never loads Google's tag, even on app.coderhelm.com", async ({ browser, baseURL }) => { + const context = await browser.newContext(); + const sent = await serveAsApp(context, baseURL!, 'window.__CODERHELM_CONFIG__ = { apiUrl: "", streamUrl: "", selfHosted: true };'); + const page = await context.newPage(); + await page.goto(`${APP}/`); + await expect(page.locator("body")).toBeVisible(); + await page.waitForTimeout(1500); + expect(sent.tag).toEqual([]); + expect(await page.evaluate(pageViews)).toEqual([]); + await context.close(); +}); + +test("localhost and previews never load Google's tag", async ({ page }) => { + const tag: string[] = []; + await page.route(/googletagmanager\.com|google-analytics\.com|analytics\.google\.com/, (route) => { + tag.push(route.request().url()); + return route.abort(); + }); + await page.route((u) => /^\/(api|auth)\//.test(u.pathname), (route) => route.fulfill({ status: 401, contentType: "application/json", body: "{}" })); + await page.goto("/"); + await page.waitForTimeout(1500); + expect(tag).toEqual([]); +}); diff --git a/dashboard/src/components/google-analytics.tsx b/dashboard/src/components/google-analytics.tsx index c336572a..a0a1b869 100644 --- a/dashboard/src/components/google-analytics.tsx +++ b/dashboard/src/components/google-analytics.tsx @@ -1,8 +1,8 @@ "use client"; -import Script from "next/script"; import { usePathname } from "next/navigation"; import { useEffect } from "react"; +import { isSelfHosted } from "@/lib/runtime-config"; declare global { interface Window { @@ -12,29 +12,64 @@ declare global { const GA_MEASUREMENT_ID = "G-6C41CN6BC6"; +/** The only host the tag runs on: never a self-hosted install, localhost or a preview. */ +export const ANALYTICS_HOST = "app.coderhelm.com"; + +/** Whether this page may send analytics to the hosted dashboard's Google Analytics. */ +export function analyticsAllowed(): boolean { + return typeof window !== "undefined" && window.location.hostname === ANALYTICS_HOST && !isSelfHosted(); +} + +/** Origin and path only: dashboard addresses carry ids and filters after `?`. */ +function pageLocation(): string { + return `${window.location.origin}${window.location.pathname}`; +} + +let started = false; + +function start() { + started = true; + // The same dataLayer lib/gtm.ts pushes to; gtag must push the arguments object itself. + const layer = (window.dataLayer = window.dataLayer ?? []) as unknown[]; + window.gtag = function gtag() { + layer.push(arguments); + }; + window.gtag("js", new Date()); + const s = document.createElement("script"); + s.async = true; + s.src = `https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`; + document.head.appendChild(s); +} + +/** + * The tag's settings for the page now showing. Setting page_location here + * also stops the tag's own history page views, so each page counts once. + */ +function configure() { + window.gtag("config", GA_MEASUREMENT_ID, { + send_page_view: false, + page_location: pageLocation(), + page_referrer: "", + allow_google_signals: false, + allow_ad_personalization_signals: false, + }); +} + +/** + * Page views on app.coderhelm.com: the first load and every client-side route + * change. gtag queues calls until its script loads, so the first view is + * never lost. A self-hosted install (runtime-config.js says selfHosted) loads + * nothing. + */ export function GoogleAnalytics() { const pathname = usePathname(); useEffect(() => { - if (typeof window.gtag !== "function") return; - window.gtag("event", "page_view", { page_path: pathname }); + if (!analyticsAllowed()) return; + if (!started) start(); + configure(); + window.gtag("event", "page_view", { page_location: pageLocation(), page_title: document.title }); }, [pathname]); - return ( - <> - - - ); + return null; } diff --git a/docs/app/layout.tsx b/docs/app/layout.tsx index 399c4197..2bb85d01 100644 --- a/docs/app/layout.tsx +++ b/docs/app/layout.tsx @@ -1,5 +1,6 @@ import type { Metadata, Viewport } from 'next'; import { Geist, Geist_Mono } from 'next/font/google'; +import { Analytics } from '@/components/analytics'; import { Provider } from '@/components/provider'; import { SITE } from '@/lib/shared'; import './global.css'; @@ -33,6 +34,7 @@ export default function RootLayout({ children }: { children: React.ReactNode }) {children} + ); diff --git a/docs/components/analytics.tsx b/docs/components/analytics.tsx new file mode 100644 index 00000000..6b396853 --- /dev/null +++ b/docs/components/analytics.tsx @@ -0,0 +1,156 @@ +'use client'; + +// Google Analytics on docs.coderhelm.com only (lib/analytics.ts says what is +// sent and what never is). Nothing loads on localhost, previews or a +// self-hosted build of the docs. The tag loads once the browser is idle or +// the reader first interacts, so it never competes with the page itself. + +import { usePathname } from 'next/navigation'; +import { useEffect, useRef } from 'react'; +import { + GA_ID, + LINKER_DOMAINS, + PAGE_VIEW_MARK, + cleanUrl, + clickEvent, + isCollectUrl, + outboundHost, + scrubHit, + shouldLoad, + type DocsEvent, +} from '@/lib/analytics'; + +type Gtag = (...args: unknown[]) => void; +type AnalyticsWindow = Window & { dataLayer?: unknown[]; gtag?: Gtag; __chAnalytics?: boolean }; + +function active(): boolean { + return typeof window !== 'undefined' && (window as AnalyticsWindow).__chAnalytics === true; +} + +/** Sends one docs event; does nothing where analytics is off. */ +export function track(event: DocsEvent | null): void { + if (!event || !active()) return; + const { name, ...fields } = event; + (window as AnalyticsWindow).gtag?.('event', name, fields); +} + +function here(): string { + return cleanUrl(window.location.href) ?? window.location.origin; +} + +/** Every hit leaves through scrubHit(), whichever transport the tag picks. */ +function guardTransport(w: AnalyticsWindow) { + const beacon = navigator.sendBeacon?.bind(navigator); + if (beacon) { + navigator.sendBeacon = (url: string | URL, data?: BodyInit | null) => { + const u = String(url); + if (!isCollectUrl(u)) return beacon(url, data); + if (data != null && typeof data !== 'string') return true; // only text bodies are ever built by the tag; anything else is not sent + const hit = scrubHit(u, data); + return hit ? beacon(hit.url, hit.body) : true; + }; + } + const fetchFn = w.fetch.bind(w); + w.fetch = (input: RequestInfo | URL, init?: RequestInit) => { + const u = typeof input === 'string' || input instanceof URL ? String(input) : input.url; + if (!isCollectUrl(u)) return fetchFn(input, init); + const body = init?.body; + if (body != null && typeof body !== 'string') return Promise.resolve(new Response(null, { status: 204 })); + const hit = scrubHit(u, body); + if (!hit) return Promise.resolve(new Response(null, { status: 204 })); + return fetchFn(hit.url, { ...init, body: hit.body ?? undefined }); + }; + // The tag's last fallback is an image request. + const src = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src'); + if (src?.set && src.get) { + Object.defineProperty(HTMLImageElement.prototype, 'src', { + configurable: true, + enumerable: src.enumerable, + get: src.get, + set(this: HTMLImageElement, v: string) { + const s = String(v); + if (!isCollectUrl(s)) return src.set!.call(this, v); + const hit = scrubHit(s, null); + if (hit) src.set!.call(this, hit.url); + }, + }); + } +} + +/** + * The tag's settings for the page now showing. Setting page_location here + * also stops the tag's own history page views, so each page counts once. + */ +function configure(w: AnalyticsWindow, referrer: string) { + w.gtag?.('config', GA_ID, { + send_page_view: false, + page_location: here(), + page_referrer: referrer, + allow_google_signals: false, + allow_ad_personalization_signals: false, + linker: { domains: LINKER_DOMAINS, accept_incoming: true }, + }); +} + +function start(w: AnalyticsWindow) { + w.__chAnalytics = true; + guardTransport(w); + w.dataLayer = w.dataLayer || []; + // gtag must push the arguments object itself. + w.gtag = function gtag() { + w.dataLayer!.push(arguments); + }; + w.gtag('js', new Date()); + configure(w, document.referrer ? cleanUrl(document.referrer) ?? '' : ''); + + // Load the tag when the browser is idle or the reader first interacts. + let loaded = false; + const load = () => { + if (loaded) return; + loaded = true; + for (const t of INTERACTIONS) window.removeEventListener(t, load, true); + const s = document.createElement('script'); + s.async = true; + s.src = `https://www.googletagmanager.com/gtag/js?id=${GA_ID}`; + document.head.appendChild(s); + }; + const INTERACTIONS = ['pointerdown', 'keydown', 'scroll', 'touchstart']; + for (const t of INTERACTIONS) window.addEventListener(t, load, { capture: true, passive: true, once: true }); + const idle = () => (window.requestIdleCallback ? window.requestIdleCallback(load, { timeout: 4000 }) : setTimeout(load, 2500)); + if (document.readyState === 'complete') idle(); + else window.addEventListener('load', idle, { once: true }); + + // Clicks worth counting: copy buttons and links that leave the docs. + document.addEventListener( + 'click', + (e) => { + const el = e.target instanceof Element ? e.target : null; + if (!el) return; + const button = el.closest('button'); + if (button) return track(clickEvent(button.textContent)); + const a = el.closest('a[href]'); + const host = a ? outboundHost(a.getAttribute('href') ?? '', window.location.href) : null; + if (host) track({ name: 'outbound_click', link_domain: host }); + }, + { capture: true }, + ); +} + +/** Page views, on the first load and on every client-side navigation. */ +export function Analytics() { + const pathname = usePathname(); + const previous = useRef(null); + useEffect(() => { + const w = window as AnalyticsWindow; + if (!shouldLoad(window.location.hostname)) return; + if (!w.__chAnalytics) start(w); + else configure(w, previous.current ?? ''); + previous.current = here(); + w.gtag?.('event', 'page_view', { + page_location: here(), + page_title: document.title, + [PAGE_VIEW_MARK]: 1, + }); + }, [pathname]); + return null; +} diff --git a/docs/components/install/wizard.tsx b/docs/components/install/wizard.tsx index 5a1cc477..6f37f2cc 100644 --- a/docs/components/install/wizard.tsx +++ b/docs/components/install/wizard.tsx @@ -72,6 +72,8 @@ import { withDomainDoc, } from '@/lib/install/core'; import { AnthropicLogo, AwsColorLogo, AwsLogo, GitHubLogo } from './logos'; +import { track } from '@/components/analytics'; +import { GUIDE_TRUST, installStepEvent } from '@/lib/analytics'; // Timings (the end-to-end tests shorten them through window.__CH_*). function timing(name: string, fallback: number): number { @@ -694,6 +696,11 @@ export function InstallWizard() { const derived: StepId = s ? deriveStep(s, setup) : 'start'; const view: StepId = manual ?? derived; + // Analytics counts the step reached, by name only. + const loaded = s !== null; + useEffect(() => { + if (loaded) track(installStepEvent(view)); + }, [view, loaded]); const steps = stepsFor({ domainChoice: s?.domainChoice ?? 'aws' }); const done = useMemo(() => { const order: StepId[] = ['aws', 'domain', 'address', 'github', 'models', 'ready']; @@ -980,7 +987,7 @@ export function InstallWizard() { ) : null} - + update({ stage: e.target.value.toLowerCase() })} autoCapitalize="off" spellCheck={false} />
@@ -1018,6 +1025,7 @@ export function InstallWizard() {

A CloudFormation stack starts the installer in CodeBuild, inside your account. It downloads CoderHelm {s.version}, checks its signature and deploys CoderHelm: Lambda functions, DynamoDB tables, an S3 bucket, CloudFront and Cognito sign-in. Nothing to install on your computer.

+

Everything it creates is named after the name in your AWS account, {s.stage}: the stack is {stackName(s)}, and every resource name starts with coderhelm-{s.stage}, so you can find them in the AWS console.

The box you tick lets the stack create IAM roles. The installer needs administrator rights in your account to create CoderHelm's own, narrower roles.

{s.domainChoice === 'own' ? `Your domain: when its zone is in Route 53 in this account, the install makes the certificate and the records. Anywhere else, CoderHelm starts on its free cloudfront.net address and this page shows the two records to add; it moves to ${cleanHostname(s.hostname) || 'your domain'} once they work.` : s.domainChoice === 'coderhelm' ? `Your CoderHelm address: once your install answers, this page registers it with CoderHelm and claims ${cleanName(s.coderhelmName) || 'your name'}.${NAME_ZONE}. Your install requests the certificate in your account; CoderHelm adds the DNS records. Nothing for you to do.` : 'No domain or DNS work: CoderHelm gets a free cloudfront.net address. You can add your own domain later, in More options or in CoderHelm.'}

Two random values from this page go along: a progress ID, so this page can follow the install, and a one-time setup key, so GitHub (or CoderHelm, for hybrid) can talk to your CoderHelm directly. Both stay in your account and this browser.

@@ -1117,7 +1125,7 @@ export function InstallWizard() {

The installer runs in CodeBuild in your account. It writes its progress to a small file in your account (bucket coderhelm-setup-{s.statusId}) that this page reads: the phase, the step and, at the end, your install’s address. Nothing else.

-

Stack name: {stackName(s)}, in {REGIONS.find((r) => r.id === s.region)?.name ?? s.region}. Release {s.version}.

+

Stack name: {stackName(s)} (from the name in your AWS account, {s.stage}), in {REGIONS.find((r) => r.id === s.region)?.name ?? s.region}. Release {s.version}.

); @@ -1605,8 +1613,8 @@ export function InstallWizard() { {s.setup === 'hybrid' || hybridWanted - ? <>This page talks to AWS, GitHub, your own CoderHelm and CoderHelm's API (to check a name is free). Your install, not this page, registers with CoderHelm. What CoderHelm sees - : <>This page talks only to AWS, GitHub and your own CoderHelm. Nothing about your install goes to CoderHelm's servers.} + ? <>{GUIDE_TRUST.hybrid} What CoderHelm sees + : GUIDE_TRUST.private}

{s.launchedAt || s.url ? ( diff --git a/docs/components/search.tsx b/docs/components/search.tsx index d2068394..2aed9284 100644 --- a/docs/components/search.tsx +++ b/docs/components/search.tsx @@ -11,13 +11,25 @@ import { type SharedProps, } from 'fumadocs-ui/components/dialog/search'; import { useStaticSearch } from 'fumadocs-core/search/client'; +import { useEffect, useRef } from 'react'; +import { track } from '@/components/analytics'; /** * Search runs in the browser over an index built with the site * (/search-index.json, a static file), so it needs no server and no third party. + * Analytics counts that a search was made, once per open, never what was typed. */ export default function DocsSearchDialog(props: SharedProps) { const search = useStaticSearch({ from: '/search-index.json' }); + const counted = useRef(false); + useEffect(() => { + if (!props.open) counted.current = false; + }, [props.open]); + useEffect(() => { + if (counted.current || !search.search.trim()) return; + counted.current = true; + track({ name: 'docs_search' }); + }, [search.search]); return ( diff --git a/docs/e2e/analytics.spec.ts b/docs/e2e/analytics.spec.ts new file mode 100644 index 00000000..08195250 --- /dev/null +++ b/docs/e2e/analytics.spec.ts @@ -0,0 +1,234 @@ +// Analytics, held to what the install guide promises (lib/analytics.ts, +// GUIDE_TRUST): Google's real tag runs on docs.coderhelm.com under the CSP +// CloudFront sends, and every hit it makes is read here. No hit may carry a +// query string, a fragment, an email, the setup key, the progress id or +// anything typed. The pages come from the built site (the e2e server), served +// as https://docs.coderhelm.com; hits are answered here and never reach Google. +import { expect, test, type BrowserContext, type Page, type Request } from '@playwright/test'; +import { GA_ID, GUIDE_TRUST } from '../lib/analytics'; + +const SITE = `http://localhost:${process.env.E2E_PORT ?? 3460}`; +const DOCS = 'https://docs.coderhelm.com'; + +type Hit = { url: string; body: string }; + +/** Everything sent to Google, as one string per hit (URL plus body, decoded). */ +function text(h: Hit): string { + let t = `${h.url}\n${h.body}`; + try { + t = decodeURIComponent(t.replace(/\+/g, ' ')); + } catch { + /* keep it as sent */ + } + return t; +} + +/** The fields of every event in a hit: the URL's, merged into each body line. */ +function events(h: Hit): URLSearchParams[] { + const head = new URL(h.url).searchParams; + const lines = h.body.split('\n').filter(Boolean); + if (!lines.length) return [head]; + return lines.map((l) => { + const p = new URLSearchParams(head); + for (const [k, v] of new URLSearchParams(l)) p.set(k, v); + return p; + }); +} + +async function docsContext(context: BrowserContext, hits: Hit[], tagRequests: string[]) { + // docs.coderhelm.com is the built site, with the headers the e2e server sends (the production CSP). + await context.route(`${DOCS}/**`, async (route) => { + const u = new URL(route.request().url()); + const response = await route.fetch({ url: `${SITE}${u.pathname}${u.search}` }); + await route.fulfill({ response }); + }); + // Google's real tag, then its hits answered here. + await context.route('https://www.googletagmanager.com/gtag/js*', async (route) => { + tagRequests.push(route.request().url()); + await route.continue(); + }); + const collect = async (route: { request(): Request; fulfill(o: { status: number }): Promise }) => { + hits.push({ url: route.request().url(), body: route.request().postData() ?? '' }); + await route.fulfill({ status: 204 }); + }; + await context.route(/^https:\/\/([a-z0-9-]+\.)*(google-analytics\.com|analytics\.google\.com|googletagmanager\.com)\/.*collect/, collect); + // Nothing else leaves: AWS, GitHub and the install answer from here or not at all. + await context.route(/^https:\/\/[^/]*amazonaws\.com\//, async (route) => { + const u = new URL(route.request().url()); + if (u.pathname === '/launch/latest.json') { + return route.fulfill({ json: { version: 'v0.7.0', templateUrl: 'https://coderhelm-public.s3.amazonaws.com/launch/v0.7.0/coderhelm-launch.yaml' }, headers: { 'access-control-allow-origin': '*' } }); + } + // No progress file yet: the guide keeps its "Open AWS again" link up. + return route.fulfill({ status: 403, headers: { 'access-control-allow-origin': '*' } }); + }); + await context.route(/^https:\/\/([a-z0-9-]+\.)*(aws\.amazon\.com|github\.com)\//, (route) => route.fulfill({ status: 200, body: 'ok' })); +} + +function watchCsp(page: Page): string[] { + const violations: string[] = []; + page.on('console', (m) => { + if (/Content Security Policy|Refused to/i.test(m.text())) violations.push(m.text()); + }); + return violations; +} + +/** Every field value in a hit that is a URL with a query string or a fragment. */ +function urlsWithQuery(h: Hit): string[] { + return events(h).flatMap((e) => [...e.values()]).filter((v) => /^[a-z][a-z0-9+.-]*:\/\/[^?#]*[?#]/i.test(v)); +} + +/** Waits for the tag to send at least `n` hits with this event name. */ +async function waitFor(hits: Hit[], name: string, n = 1) { + await expect.poll(() => hits.flatMap(events).filter((e) => e.get('en') === name).length, { timeout: 15_000 }).toBeGreaterThanOrEqual(n); +} + +test('docs pages: page views with origin and path only, client-side navigation counted, no CSP violations', async ({ browser }) => { + const context = await browser.newContext(); + const hits: Hit[] = []; + const tag: string[] = []; + await docsContext(context, hits, tag); + const page = await context.newPage(); + const violations = watchCsp(page); + + await page.goto(`${DOCS}/getting-started/?utm_source=x&secret=1#frag`); + await page.mouse.move(10, 10); + await page.keyboard.press('Shift'); // an interaction loads the tag before the idle timer would + await waitFor(hits, 'page_view'); + expect(tag).toEqual([`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`]); + + // A client-side navigation is a page view of its own. + const link = page.locator('#nd-page a[href^="/"]').first(); + const to = await link.getAttribute('href'); + expect(to).toMatch(/^\/[^?#]*$/); + const target = to!.endsWith('/') ? to! : `${to}/`; + await link.click(); + await expect(page).toHaveURL(`${DOCS}${target}`); + await waitFor(hits, 'page_view', 2); + // Still the same document: the navigation happened in the page. + expect(tag).toHaveLength(1); + + const views = hits.flatMap(events).filter((e) => e.get('en') === 'page_view'); + expect(views.map((e) => e.get('dl'))).toEqual([`${DOCS}/getting-started/`, `${DOCS}${target}`]); + expect(views.every((e) => e.get('tid') === GA_ID)).toBe(true); + for (const h of hits) { + const t = text(h); + expect(t).not.toContain('secret=1'); + expect(t).not.toContain('utm_source'); + expect(t).not.toContain('#frag'); + } + expect(violations).toEqual([]); + await context.close(); +}); + +test('docs pages: search, copy and outbound clicks are counted by name, never by what was typed or the full link', async ({ browser }) => { + const context = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] }); + const hits: Hit[] = []; + await docsContext(context, hits, []); + const page = await context.newPage(); + const violations = watchCsp(page); + await page.goto(`${DOCS}/self-host/quick-start/`); + await page.keyboard.press('Shift'); + await waitFor(hits, 'page_view'); + + await page.getByRole('button', { name: 'Copy Markdown' }).first().click(); + await page.getByRole('button', { name: 'Copy Text' }).first().click(); + + await page.locator('button[data-search-full]').first().click(); + await page.getByPlaceholder(/search/i).fill('bedrockquerysecret'); + await page.keyboard.press('Escape'); + + // An outbound link: only its host is sent. + await page.evaluate(() => { + const a = document.createElement('a'); + a.href = 'https://github.com/CoderHelm/coderhelm-platform/releases?tab=secretquery#x'; + a.textContent = 'releases'; + a.target = '_blank'; + a.id = 'out'; + document.body.appendChild(a); + }); + const popup = context.waitForEvent('page'); + await page.locator('#out').click(); + await (await popup).close(); + + await waitFor(hits, 'copy_markdown'); + await waitFor(hits, 'copy_code'); + await waitFor(hits, 'docs_search'); + await waitFor(hits, 'outbound_click'); + const out = hits.flatMap(events).find((e) => e.get('en') === 'outbound_click')!; + expect(out.get('ep.link_domain')).toBe('github.com'); + for (const h of hits) { + const t = text(h); + expect(t).not.toContain('bedrockquerysecret'); + expect(t).not.toContain('secretquery'); + expect(urlsWithQuery(h)).toEqual([]); + } + expect(violations).toEqual([]); + await context.close(); +}); + +test('install guide: the trust line is what the code does; no hit carries a query string, an email, the setup key, the progress id or a form value', async ({ browser }) => { + const context = await browser.newContext(); + const hits: Hit[] = []; + await docsContext(context, hits, []); + await context.addInitScript(() => { + window.open = (() => null) as typeof window.open; + }); + const page = await context.newPage(); + const violations = watchCsp(page); + + await page.goto(`${DOCS}/self-host/install/`); + await expect(page.getByTestId('privacy')).toHaveText(GUIDE_TRUST.private); + await page.keyboard.press('Shift'); + await waitFor(hits, 'page_view'); + + // Type everything the start screen asks for, then launch: the guide puts its progress id in the address bar. + const email = 'ada.lovelace@example.org'; + await page.getByLabel('Your email').fill(email); + await page.getByLabel('AWS region').selectOption('eu-west-1'); + await page.getByTestId('launch').click(); + await expect(page.getByTestId('screen-aws')).toBeVisible(); + await expect(page).toHaveURL(/\?/); + const state = await page.evaluate(() => { + const id = localStorage.getItem('coderhelm-install:last')!; + return JSON.parse(localStorage.getItem(`coderhelm-install:${id}`)!) as { statusId: string; setupToken: string; region: string }; + }); + + // The AWS link carries the email and the setup key in its address; clicking it must not send them. + const aws = page.getByTestId('reopen-aws').first(); + await expect(aws).toHaveAttribute('href', /param_AdminEmail=/); + const popup = context.waitForEvent('page'); + await aws.click(); + await (await popup).close(); + + await waitFor(hits, 'install_step', 2); + await waitFor(hits, 'outbound_click'); + const all = hits.flatMap(events); + expect(all.filter((e) => e.get('en') === 'install_step').map((e) => e.get('ep.step'))).toEqual(expect.arrayContaining(['start', 'aws'])); + // One page view for the guide, however often the address bar changes. + expect(all.filter((e) => e.get('en') === 'page_view').map((e) => e.get('dl'))).toEqual([`${DOCS}/self-host/install/`]); + for (const h of hits) { + const t = text(h); + expect(urlsWithQuery(h)).toEqual([]); + expect(t).not.toContain(email); + expect(t).not.toMatch(/@example\.org/); + expect(t).not.toContain(state.setupToken); + expect(t).not.toContain(state.statusId); + expect(t).not.toContain('param_'); + expect(t).not.toContain('eu-west-1'); + } + expect(violations).toEqual([]); + await context.close(); +}); + +test('localhost (previews, self-hosted builds of the docs): Google’s tag never loads', async ({ page }) => { + const tag: string[] = []; + await page.route(/googletagmanager\.com|google-analytics\.com|analytics\.google\.com/, (route) => { + tag.push(route.request().url()); + return route.abort(); + }); + await page.goto('/getting-started/'); + await page.keyboard.press('Shift'); + await page.waitForTimeout(1500); + expect(tag).toEqual([]); + expect(await page.evaluate(() => 'gtag' in window)).toBe(false); +}); diff --git a/docs/e2e/csp.spec.ts b/docs/e2e/csp.spec.ts index 9b57fc87..066df827 100644 --- a/docs/e2e/csp.spec.ts +++ b/docs/e2e/csp.spec.ts @@ -147,14 +147,15 @@ async function context(browser: Browser): Promise { return ctx; } -test('the guide is served with the install guide policy; other pages keep connect-src self', async ({ request }) => { +test('the guide is served with the install guide policy; other pages reach only their own origin and Google Analytics', async ({ request }) => { const guide = await request.get('/self-host/install/'); expect(guide.headers()['content-security-policy']).toBe(CSP.installGuide); expect(CSP.installGuide).toContain("connect-src 'self' https:"); expect(CSP.installGuide).toContain("form-action 'self' https://github.com"); const other = await request.get('/'); expect(other.headers()['content-security-policy']).toBe(CSP.docs); - expect(CSP.docs).toContain("connect-src 'self';"); + // Beyond its own origin, a docs page may reach Google Analytics only (e2e/analytics.spec.ts). + expect(CSP.docs).toContain("connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com;"); }); test('real headers: the name check says Available, Taken or Reserved from CoderHelm’s API on another origin', async ({ browser }) => { diff --git a/docs/e2e/install.spec.ts b/docs/e2e/install.spec.ts index d2d5304c..b6a5d85a 100644 --- a/docs/e2e/install.spec.ts +++ b/docs/e2e/install.spec.ts @@ -158,7 +158,7 @@ test('happy path: launch, follow the install, GitHub, models, ready', async ({ p await mock(page, m); await page.goto('/self-host/install/'); await expect(page.getByTestId('step-title')).toHaveText('Install CoderHelm in your AWS account'); - await expect(page.getByTestId('privacy')).toContainText('Nothing about your install goes to CoderHelm'); + await expect(page.getByTestId('privacy')).toContainText('Nothing you type and nothing about your install is sent to CoderHelm or Google.'); // Validation speaks plainly, then the console opens with everything filled in. await page.getByTestId('launch').click(); @@ -326,6 +326,30 @@ test('once someone has signed up (setup window closed), the guide shows the inst await expect(page.getByTestId('step-title')).toHaveText('Your CoderHelm is ready'); }); +test('more options: the name in your AWS account is explained, checked in one sentence and named in the stack', async ({ page }) => { + const m = newMock(); + await mock(page, m); + await page.goto('/self-host/install/'); + await page.getByLabel('Your email').fill('ada@example.com'); + await page.getByRole('button', { name: 'More options' }).click(); + const name = page.getByLabel('Name in your AWS account'); + await expect(name).toHaveValue('prod'); + await expect(page.getByText('Names the AWS resources this install creates, so you can find them in the AWS console. Keep it unless this AWS account already has a CoderHelm; each install in one account needs its own name.')).toBeVisible(); + await expect(page.getByText('Install name')).toHaveCount(0); + await name.fill('2nd_install'); + await page.getByTestId('launch').click(); + await expect(page.getByText('Use 1 to 20 lowercase letters, digits or hyphens, starting with a letter.')).toBeVisible(); + expect(await opened(page)).toEqual([]); + await name.fill('helm-two'); + await page.getByText('What happens in AWS').click(); + await expect(page.getByText('Everything it creates is named after the name in your AWS account, helm-two: the stack is coderhelm-helm-two')).toBeVisible(); + await page.getByTestId('launch').click(); + const [link] = await opened(page); + expect(new URLSearchParams(new URL(link).hash.split('?')[1]).get('param_Stage')).toBe('helm-two'); + await page.getByText('What is happening').click(); + await expect(page.getByText('Stack name: coderhelm-helm-two (from the name in your AWS account, helm-two)')).toBeVisible(); +}); + test('more options: domain, sender, sign-up and updates go to AWS; a bad hostname opens More options with the sentence', async ({ page }) => { const m = newMock(); await mock(page, m); diff --git a/docs/lib/analytics.ts b/docs/lib/analytics.ts new file mode 100644 index 00000000..49c9d089 --- /dev/null +++ b/docs/lib/analytics.ts @@ -0,0 +1,160 @@ +// Analytics for the hosted docs, kept apart from the page so it can be tested +// without a browser (scripts/analytics.test.mjs runs this file with Node's +// type stripping: erasable TypeScript only, no imports). +// +// What is sent: anonymous page views (origin and path only) and a few named +// events with fixed, non-identifying fields. Never a query string or +// fragment (the install guide keeps progress ids there), never anything +// typed into a page, never an email, name, region or install name. +// +// Google's tag can add its own automatic events (outbound clicks with the +// full link, form submissions, site search, history page views), set in +// Google Analytics rather than here. So every hit the tag sends passes +// through scrubHit() on its way out: URLs lose their query and fragment, +// search terms, form fields and anything that looks like an email are +// dropped, and page views this code did not send are dropped too. + +/** The coderhelm.com property, so the site, the docs and the install guide are one funnel. */ +export const GA_ID = 'G-T14Q1LDRC0'; + +/** The only hostname analytics runs on: never localhost, previews or self-hosted builds of the docs. */ +export const ANALYTICS_HOST = 'docs.coderhelm.com'; + +/** Domains whose links carry the visitor across (coderhelm.com and the docs are one session). */ +export const LINKER_DOMAINS = ['coderhelm.com', 'docs.coderhelm.com']; + +/** Marks the page views this code sends, so the tag's own history page views can be told apart. */ +export const PAGE_VIEW_MARK = 'ch_pv'; + +/** The hosts Google's tag sends to and loads from (the docs CSP allows exactly these). */ +export const GA_HOSTS = ['https://*.google-analytics.com', 'https://*.analytics.google.com', 'https://www.googletagmanager.com']; + +export function shouldLoad(hostname: string): boolean { + return hostname === ANALYTICS_HOST; +} + +/** An AWS region name (eu-west-1, us-gov-west-1, ap-southeast-2). */ +const REGION = /\b(?:us|eu|ap|sa|ca|me|af|il|mx)(?:-gov|-iso[a-z]?)?-(?:north|south|east|west|central|northeast|southeast|northwest|southwest)-\d\b/gi; + +/** Region names taken out: the AWS console's host names the region the reader picked. */ +export function dropRegions(s: string): string { + return s.replace(new RegExp(`${REGION.source}\\.`, 'gi'), '').replace(REGION, ''); +} + +/** Origin and path only, with no AWS region in it. Anything that is not an http(s) URL gives null. */ +export function cleanUrl(u: string): string | null { + try { + const url = new URL(u); + if (url.protocol !== 'https:' && url.protocol !== 'http:') return null; + return dropRegions(`${url.origin}${url.pathname}`); + } catch { + return null; + } +} + +/** True for a URL Google's tag sends hits to. */ +export function isCollectUrl(u: string): boolean { + try { + const url = new URL(u); + const host = url.hostname; + const ga = host === 'google-analytics.com' || host.endsWith('.google-analytics.com') || host === 'analytics.google.com' || host.endsWith('.analytics.google.com') || host === 'www.googletagmanager.com'; + return ga && /\/collect$/.test(url.pathname); + } catch { + return false; + } +} + +const EMAIL = /[^\s@/?#&=]+@[^\s@/?#&=]+\.[a-z]{2,}/i; +const URL_LIKE = /^[a-z][a-z0-9+.-]*:\/\//i; +/** Event fields never sent, whatever their value. */ +const DROP = /^(ep|epn)\.(search_term|form_id|form_name|form_destination|form_length|form_submit_text|link_text|link_id|link_classes|file_name|video_url|video_title)$/; + +/** + * One hit's fields (a query string, or one line of a batched body) with + * URLs reduced to origin and path, and forbidden fields dropped. Returns + * null for a page view this code did not send (Google's own history page + * views would count the install guide again on every address bar change). + */ +export function scrubParams(qs: string, opts: { requireMark?: boolean } = {}): string | null { + const params = new URLSearchParams(qs); + const out = new URLSearchParams(); + let ours = false; + for (const [k, v] of params) { + if (k === `ep.${PAGE_VIEW_MARK}` || k === `epn.${PAGE_VIEW_MARK}`) { + ours = true; + continue; + } + if (DROP.test(k)) continue; + if (URL_LIKE.test(v)) { + const clean = cleanUrl(v); + if (clean) out.append(k, clean); + continue; + } + if (EMAIL.test(v)) continue; + out.append(k, dropRegions(v)); + } + if (opts.requireMark && out.get('en') === 'page_view' && !ours) return null; + return out.toString(); +} + +/** + * A whole hit: the URL's query and each line of the body. The URL carries + * the shared fields (dl, dr, dt) and, for a single event, the event itself. + * A null body line is a page view to drop; if every event is dropped the + * hit is not sent (null). + */ +export function scrubHit(url: string, body: string | null | undefined): { url: string; body: string | null } | null { + const u = new URL(url); + const lines = body ? body.split('\n').filter((l) => l.length > 0) : []; + const head = scrubParams(u.search.slice(1), { requireMark: lines.length === 0 }); + if (head === null) return null; + u.search = head; + if (!lines.length) return { url: u.toString(), body: body ?? null }; + const kept = lines.map((l) => scrubParams(l, { requireMark: true })).filter((l): l is string => l !== null); + if (!kept.length) return null; + return { url: u.toString(), body: kept.join('\n') }; +} + +/** Where a link goes, as a host only, when it leaves this site; null otherwise. */ +export function outboundHost(href: string, here: string): string | null { + try { + const url = new URL(href, here); + if (url.protocol !== 'https:' && url.protocol !== 'http:') return null; + return url.host === new URL(here).host ? null : dropRegions(url.host); + } catch { + return null; + } +} + +export type DocsEvent = + | { name: 'docs_search' } + | { name: 'copy_markdown' } + | { name: 'copy_code' } + | { name: 'outbound_click'; link_domain: string } + | { name: 'install_step'; step: string }; + +/** What a click on this element means, from the button's own words; null for most clicks. */ +export function clickEvent(text: string | null | undefined): DocsEvent | null { + const t = (text ?? '').replace(/\s+/g, ' ').trim(); + if (/^Cop(y|ied) Markdown$/.test(t)) return { name: 'copy_markdown' }; + if (/^Cop(y|ied) Text$/.test(t)) return { name: 'copy_code' }; + return null; +} + +/** The install guide's step names (lib/install/core.ts StepId); anything else is not sent. */ +const STEP_NAMES = new Set(['start', 'aws', 'domain', 'address', 'github', 'models', 'ready']); +export function installStepEvent(step: string): DocsEvent | null { + return STEP_NAMES.has(step) ? { name: 'install_step', step } : null; +} + +/** + * What the install guide says it talks to, kept beside the code that makes + * it true (e2e/analytics.spec.ts holds the page to it). The hybrid line adds + * CoderHelm's name check, so it cannot say nothing typed leaves the page. + */ +export const GUIDE_TRUST = { + private: + 'This page talks to AWS, GitHub and your own CoderHelm, and counts anonymous page views with Google Analytics. Nothing you type and nothing about your install is sent to CoderHelm or Google.', + hybrid: + "This page talks to AWS, GitHub, your own CoderHelm and CoderHelm's API (to check a name is free), and counts anonymous page views with Google Analytics. Your install, not this page, registers with CoderHelm.", +}; diff --git a/docs/lib/install/core.ts b/docs/lib/install/core.ts index 7cc5b1ea..87be72a7 100644 --- a/docs/lib/install/core.ts +++ b/docs/lib/install/core.ts @@ -236,7 +236,7 @@ export function cleanHostname(raw: string): string { export function validate(s: Pick & Partial): Record { const p: Record = {}; if (!EMAIL_RE.test(s.email.trim())) p.email = 'Enter the email you will sign in with.'; - if (!STAGE_RE.test(s.stage)) p.stage = 'Use lowercase letters, digits and hyphens, starting with a letter.'; + if (!STAGE_RE.test(s.stage)) p.stage = 'Use 1 to 20 lowercase letters, digits or hyphens, starting with a letter.'; if (!REGIONS.some((r) => r.id === s.region)) p.region = 'Pick a region from the list.'; if (s.domainChoice === 'coderhelm') { const np = nameProblem(s.coderhelmName ?? ''); diff --git a/docs/lib/install/page-info.ts b/docs/lib/install/page-info.ts index ad58f2df..2c7e0884 100644 --- a/docs/lib/install/page-info.ts +++ b/docs/lib/install/page-info.ts @@ -18,7 +18,7 @@ Source: ${SITE.url}${INSTALL_GUIDE.url} ${INSTALL_GUIDE.description} -The guide is an interactive page. It talks only to AWS, GitHub and your own CoderHelm; nothing about your install goes to CoderHelm's servers. +The guide is an interactive page. It talks to AWS, GitHub and your own CoderHelm, and counts anonymous page views with Google Analytics (origin and path only). Nothing you type and nothing about your install is sent to CoderHelm or Google. With a CoderHelm address (Hybrid), it also asks CoderHelm's API whether the name you picked is free. ## Steps diff --git a/docs/scripts/analytics.test.mjs b/docs/scripts/analytics.test.mjs new file mode 100644 index 00000000..0c691b55 --- /dev/null +++ b/docs/scripts/analytics.test.mjs @@ -0,0 +1,101 @@ +// What the docs send to Google Analytics (lib/analytics.ts), without a +// browser. The e2e test (e2e/analytics.spec.ts) runs Google's real tag; this +// one holds the scrubber to the install guide's promise for hits the tag +// could build in any configuration. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import * as a from '../lib/analytics.ts'; + +const COLLECT = 'https://region1.google-analytics.com/g/collect'; +const AWS_LINK = + 'https://eu-west-1.console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/create/review?param_AdminEmail=ada%40example.com¶m_SetupToken=TkTkTkTk¶m_StatusId=abcd1234efgh5678'; + +test('loads on docs.coderhelm.com only: never localhost, previews or a self-hosted build', () => { + assert.equal(a.shouldLoad('docs.coderhelm.com'), true); + for (const h of ['localhost', '127.0.0.1', 'coderhelm.com', 'docs-preview.coderhelm.com', 'd111test.cloudfront.net', 'docs.example.com']) { + assert.equal(a.shouldLoad(h), false, h); + } + assert.equal(a.GA_ID, 'G-T14Q1LDRC0'); + assert.deepEqual(a.LINKER_DOMAINS, ['coderhelm.com', 'docs.coderhelm.com']); +}); + +test('URLs keep origin and path only, with no AWS region', () => { + assert.equal(a.cleanUrl('https://docs.coderhelm.com/self-host/install/?id=abcd1234efgh5678&step=aws#top'), 'https://docs.coderhelm.com/self-host/install/'); + assert.equal(a.cleanUrl(AWS_LINK), 'https://console.aws.amazon.com/cloudformation/home'); + assert.equal(a.cleanUrl('mailto:ada@example.com'), null); + assert.equal(a.cleanUrl('not a url'), null); + assert.equal(a.dropRegions('coderhelm-setup-x.s3.ap-southeast-2.amazonaws.com'), 'coderhelm-setup-x.s3.amazonaws.com'); + assert.equal(a.dropRegions('us-gov-west-1.console.aws.amazon.com'), 'console.aws.amazon.com'); +}); + +test('only Google Analytics collect endpoints are scrubbed', () => { + assert.equal(a.isCollectUrl(`${COLLECT}?v=2`), true); + assert.equal(a.isCollectUrl('https://www.google-analytics.com/g/collect?v=2'), true); + assert.equal(a.isCollectUrl('https://region1.analytics.google.com/g/collect'), true); + assert.equal(a.isCollectUrl('https://api.coderhelm.com/hybrid/names/x'), false); + assert.equal(a.isCollectUrl('https://evil.example/google-analytics.com/g/collect'), false); + assert.equal(a.isCollectUrl('https://www.googletagmanager.com/gtag/js?id=x'), false); +}); + +test('a hit loses query strings, fragments, emails, the setup key, the progress id, regions, search terms and form fields', () => { + const head = new URLSearchParams({ + v: '2', + tid: a.GA_ID, + dl: 'https://docs.coderhelm.com/self-host/install/?id=abcd1234efgh5678#x', + dr: 'https://coderhelm.com/self-host/?utm_source=ada%40example.com', + dt: 'Install CoderHelm', + }); + const body = [ + new URLSearchParams({ en: 'click', 'ep.link_url': AWS_LINK, 'ep.link_domain': 'eu-west-1.console.aws.amazon.com', 'ep.outbound': 'true' }).toString(), + new URLSearchParams({ en: 'form_submit', 'ep.form_id': 'f', 'ep.form_destination': 'https://github.com/settings/apps/new?state=TkTkTkTk', 'ep.form_submit_text': 'Create' }).toString(), + new URLSearchParams({ en: 'view_search_results', 'ep.search_term': 'my secret query' }).toString(), + new URLSearchParams({ en: 'odd', 'ep.who': 'ada@example.com', 'ep.where': 'eu-west-1' }).toString(), + ].join('\n'); + const hit = a.scrubHit(`${COLLECT}?${head}`, body); + assert.ok(hit); + const all = decodeURIComponent(`${hit.url}\n${hit.body}`); + for (const bad of ['?id=', '#x', 'utm_source', 'ada@example.com', 'example.com', 'TkTkTkTk', 'abcd1234efgh5678', 'eu-west-1', 'param_', 'my secret query', 'state=', 'form_destination', 'search_term', 'Create']) { + assert.ok(!all.slice(COLLECT.length).includes(bad), `${bad} must not be sent`); + } + const u = new URL(hit.url); + assert.equal(u.searchParams.get('dl'), 'https://docs.coderhelm.com/self-host/install/'); + assert.equal(u.searchParams.get('dr'), 'https://coderhelm.com/self-host/'); + const click = new URLSearchParams(hit.body.split('\n')[0]); + assert.equal(click.get('ep.link_url'), 'https://console.aws.amazon.com/cloudformation/home'); + assert.equal(click.get('ep.link_domain'), 'console.aws.amazon.com'); +}); + +test("page views: ours are sent (without the mark); the tag's own history page views are dropped", () => { + const ours = a.scrubHit(`${COLLECT}?v=2&en=page_view&dl=https%3A%2F%2Fdocs.coderhelm.com%2F&epn.${a.PAGE_VIEW_MARK}=1`, null); + assert.ok(ours); + assert.equal(new URL(ours.url).searchParams.get('en'), 'page_view'); + assert.ok(!ours.url.includes(a.PAGE_VIEW_MARK)); + assert.equal(a.scrubHit(`${COLLECT}?v=2&en=page_view&dl=https%3A%2F%2Fdocs.coderhelm.com%2Fself-host%2Finstall%2F%3Fid%3Dx`, null), null); + // In a batch, only the foreign page view goes. + const batch = a.scrubHit(`${COLLECT}?v=2`, `en=page_view&ep.${a.PAGE_VIEW_MARK}=1\nen=page_view\nen=scroll&epn.percent_scrolled=90`); + assert.ok(batch); + assert.deepEqual(batch.body.split('\n').map((l) => new URLSearchParams(l).get('en')), ['page_view', 'scroll']); + assert.equal(a.scrubHit(`${COLLECT}?v=2`, 'en=page_view'), null); +}); + +test('events: copy buttons by their words, outbound links by host, install steps by name', () => { + assert.deepEqual(a.clickEvent(' Copy Markdown '), { name: 'copy_markdown' }); + assert.deepEqual(a.clickEvent('Copied Markdown'), { name: 'copy_markdown' }); + assert.deepEqual(a.clickEvent('Copy Text'), { name: 'copy_code' }); + assert.equal(a.clickEvent('Open Search'), null); + assert.equal(a.clickEvent(null), null); + assert.equal(a.outboundHost(AWS_LINK, 'https://docs.coderhelm.com/self-host/install/'), 'console.aws.amazon.com'); + assert.equal(a.outboundHost('/self-host/', 'https://docs.coderhelm.com/'), null); + assert.equal(a.outboundHost('https://docs.coderhelm.com/x/?q=1', 'https://docs.coderhelm.com/'), null); + assert.equal(a.outboundHost('mailto:security@coderhelm.com', 'https://docs.coderhelm.com/'), null); + assert.equal(a.outboundHost('https://coderhelm.com/pricing/?a=b', 'https://docs.coderhelm.com/'), 'coderhelm.com'); + assert.deepEqual(a.installStepEvent('aws'), { name: 'install_step', step: 'aws' }); + assert.equal(a.installStepEvent('ada@example.com'), null); +}); + +test('the install guide says what the code does', () => { + assert.match(a.GUIDE_TRUST.private, /anonymous page views with Google Analytics/); + assert.match(a.GUIDE_TRUST.private, /Nothing you type and nothing about your install is sent/); + assert.match(a.GUIDE_TRUST.hybrid, /anonymous page views with Google Analytics/); + assert.doesNotMatch(a.GUIDE_TRUST.private, /talks only to/); +}); diff --git a/docs/scripts/install-core.test.mjs b/docs/scripts/install-core.test.mjs index d1cdfbb9..0348d305 100644 --- a/docs/scripts/install-core.test.mjs +++ b/docs/scripts/install-core.test.mjs @@ -21,7 +21,9 @@ test('validation speaks plainly', () => { assert.deepEqual(c.validate({ email: 'ada@example.com', stage: 'prod', region: 'us-east-1' }), {}); const p = c.validate({ email: 'nope', stage: 'Prod!', region: 'mars-1' }); assert.match(p.email, /email/); - assert.match(p.stage, /lowercase/); + assert.equal(p.stage, 'Use 1 to 20 lowercase letters, digits or hyphens, starting with a letter.'); + assert.ok(c.validate({ email: 'a@example.com', stage: 'a'.repeat(21), region: 'us-east-1' }).stage); + assert.equal(c.validate({ email: 'a@example.com', stage: 'a'.repeat(20), region: 'us-east-1' }).stage, undefined); assert.match(p.region, /region/); }); diff --git a/infra/lib/app-stack.ts b/infra/lib/app-stack.ts index 94ac33b1..e6ff9801 100644 --- a/infra/lib/app-stack.ts +++ b/infra/lib/app-stack.ts @@ -86,7 +86,7 @@ export class AppStack extends cdk.Stack { }, contentSecurityPolicy: { contentSecurityPolicy: - "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.coderhelm.com https://stream.coderhelm.com https://www.google-analytics.com https://analytics.google.com https://www.googletagmanager.com; font-src 'self'", + "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.coderhelm.com https://stream.coderhelm.com https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com; font-src 'self'", override: true, }, }, diff --git a/infra/lib/docs-csp.json b/infra/lib/docs-csp.json index a7b36726..5adbeb35 100644 --- a/infra/lib/docs-csp.json +++ b/infra/lib/docs-csp.json @@ -1,6 +1,6 @@ { - "_comment": "The docs site's Content-Security-Policy, read by lib/docs-stack.ts (CloudFront) and by the docs e2e tests (docs/e2e/csp.spec.ts), so the tests run the guide under the policy production sends. The install guide calls CoderHelm's API, S3 progress files in any region and the install itself, which answers on any https origin (custom domains vary); the GitHub app manifest form posts to github.com. Every other page loads nothing from other origins.", - "docs": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; connect-src 'self'; form-action 'self'", + "_comment": "The docs site's Content-Security-Policy, read by lib/docs-stack.ts (CloudFront) and by the docs e2e tests (docs/e2e/csp.spec.ts), so the tests run the guide under the policy production sends. The install guide calls CoderHelm's API, S3 progress files in any region and the install itself, which answers on any https origin (custom domains vary); the GitHub app manifest form posts to github.com. Every other page loads nothing from other origins. Every page, the guide included, may load Google's tag and send it hits (script-src, connect-src and img-src name Google Analytics' hosts); docs/lib/analytics.ts loads it only on docs.coderhelm.com.", + "docs": "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com; form-action 'self'", "installGuidePath": "/self-host/install*", - "installGuide": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; connect-src 'self' https:; form-action 'self' https://github.com" + "installGuide": "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; connect-src 'self' https: https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com; form-action 'self' https://github.com" } diff --git a/infra/lib/frontend-stack.ts b/infra/lib/frontend-stack.ts index 894f96c8..41509b97 100644 --- a/infra/lib/frontend-stack.ts +++ b/infra/lib/frontend-stack.ts @@ -99,7 +99,7 @@ export class FrontendStack extends cdk.Stack { }, contentSecurityPolicy: { contentSecurityPolicy: - "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.coderhelm.com https://www.google-analytics.com https://analytics.google.com https://www.googletagmanager.com; font-src 'self'", + "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.coderhelm.com https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com; font-src 'self'", override: true, }, }, diff --git a/infra/test/static-site.test.ts b/infra/test/static-site.test.ts index d9ea24bb..b0980b1f 100644 --- a/infra/test/static-site.test.ts +++ b/infra/test/static-site.test.ts @@ -277,10 +277,15 @@ test("docs: only the install guide may call other origins; every page keeps its const directive = (policy: string, name: string) => policy.split(";").map((d) => d.trim()).find((d) => d.startsWith(name + " ")); - // The exact strings the docs e2e tests serve (lib/docs-csp.json). - assert.equal(directive(DOCS_CSP, "connect-src"), "connect-src 'self'"); + // The exact strings the docs e2e tests serve (lib/docs-csp.json). Beyond + // the docs' own origin, only Google Analytics (docs/lib/analytics.ts): its + // tag from googletagmanager.com, its hits to these hosts. + const GA = "https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com"; + assert.equal(directive(DOCS_CSP, "script-src"), "script-src 'self' 'unsafe-inline' https://www.googletagmanager.com"); + assert.equal(directive(DOCS_CSP, "img-src"), `img-src 'self' data: https: ${GA}`); + assert.equal(directive(DOCS_CSP, "connect-src"), `connect-src 'self' ${GA}`); assert.equal(directive(DOCS_CSP, "form-action"), "form-action 'self'"); - assert.equal(directive(INSTALL_GUIDE_CSP, "connect-src"), "connect-src 'self' https:"); + assert.equal(directive(INSTALL_GUIDE_CSP, "connect-src"), `connect-src 'self' https: ${GA}`); assert.equal(directive(INSTALL_GUIDE_CSP, "form-action"), "form-action 'self' https://github.com"); for (const name of ["default-src", "script-src", "style-src", "img-src", "font-src", "frame-ancestors", "base-uri"]) { assert.equal(directive(INSTALL_GUIDE_CSP, name), directive(DOCS_CSP, name), name); @@ -309,3 +314,15 @@ test("docs: only the install guide may call other origins; every page keeps its assert.equal(cfg.CacheBehaviors[0].CachePolicyId, cfg.DefaultCacheBehavior.CachePolicyId); assert.equal(cfg.CacheBehaviors[0].ViewerProtocolPolicy, "redirect-to-https"); }); + +test("site and app: the CSP lets Google Analytics 4 load and send from every host it uses", () => { + const GA_HOSTS = ["https://*.google-analytics.com", "https://*.analytics.google.com", "https://www.googletagmanager.com"]; + for (const kind of ["site", "app"] as const) { + const [[, policy]] = ofType(synth(kind), "AWS::CloudFront::ResponseHeadersPolicy"); + const csp: string = policy.Properties.ResponseHeadersPolicyConfig.SecurityHeadersConfig.ContentSecurityPolicy.ContentSecurityPolicy; + const directive = (name: string) => csp.split(";").map((d) => d.trim()).find((d) => d.startsWith(name + " ")) ?? ""; + assert.ok(directive("script-src").split(" ").includes("https://www.googletagmanager.com"), `${kind} script-src`); + // GA4 sends to regional hosts (region1.google-analytics.com), not only www. + for (const h of GA_HOSTS) assert.ok(directive("connect-src").split(" ").includes(h), `${kind} connect-src ${h}`); + } +}); diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 6548fb68..f5bf0de0 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -36,6 +36,14 @@ export const viewport: Viewport = { }; const GA_ID = "G-T14Q1LDRC0"; +// The docs (docs.coderhelm.com) send to the same property, so the site, the +// docs and the install guide are one funnel; the linker carries the visit +// across. No Google signals and no ad personalization. +const GA_CONFIG = { + allow_google_signals: false, + allow_ad_personalization_signals: false, + linker: { domains: ["coderhelm.com", "docs.coderhelm.com"], accept_incoming: true }, +}; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( @@ -46,7 +54,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })