From b6b10ad08198b562e1a946aa0719bde73f919344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=B1=CF=8D=CF=81=CE=BF=CF=82=20=CE=91=CF=80?= =?UTF-8?q?=CE=BF=CF=83=CF=84=CF=8C=CE=BB=CE=BF=CF=85=20=28Stavros=20Apost?= =?UTF-8?q?olou=29?= Date: Sat, 21 Nov 2026 16:01:53 +0200 Subject: [PATCH 1/6] feat(analytics): count page views and waitlist outcomes, with no cookie and no person Two events only, page_view (a route pattern) and waitlist_submit (one of five outcomes), through posthog-js 1.453.2 loaded after the page has loaded. Memory persistence, no person profile, no autocapture, recording, survey or flags. The browser reports to this site's own /ingest path, which forwards to the EU cloud with a short list of headers (no Cookie, no Authorization, no address). Off until NEXT_PUBLIC_POSTHOG_KEY is set. Co-Authored-By: Claude Sonnet 5.5 --- .env.example | 8 ++ app/(site)/layout.tsx | 2 + app/ingest/[...path]/route.ts | 9 ++ components/alpha/AnalyticsPageView.tsx | 15 ++ components/alpha/WaitlistForm.tsx | 6 + lib/analytics-browser.test.ts | 75 ++++++++++ lib/analytics-proxy.test.ts | 87 ++++++++++++ lib/analytics-proxy.ts | 69 ++++++++++ lib/analytics.test.ts | 103 ++++++++++++++ lib/analytics.ts | 156 +++++++++++++++++++++ lib/waitlist.ts | 6 +- next.config.ts | 4 + package.json | 2 + pnpm-lock.yaml | 182 ++++++++++++++++++++++++- proxy.ts | 5 +- 15 files changed, 722 insertions(+), 7 deletions(-) create mode 100644 app/ingest/[...path]/route.ts create mode 100644 components/alpha/AnalyticsPageView.tsx create mode 100644 lib/analytics-browser.test.ts create mode 100644 lib/analytics-proxy.test.ts create mode 100644 lib/analytics-proxy.ts create mode 100644 lib/analytics.test.ts create mode 100644 lib/analytics.ts diff --git a/.env.example b/.env.example index c87cce9..7fffed5 100644 --- a/.env.example +++ b/.env.example @@ -31,3 +31,11 @@ TURNSTILE_SECRET_KEY= # local dev: `vercel env pull .env.local` after linking. UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= + +# --- PostHog (counts only: page views by route, waitlist outcomes) --- +# The project key of the EU Cloud project: PostHog, Project settings. Public by +# design (it can only write events), so NEXT_PUBLIC_ is right. Read at build +# time. Leave blank and nothing is loaded or sent. Set it only after the +# privacy notice has been approved. The browser reports to this site's own +# /ingest path, which forwards to the EU cloud, so no host variable exists. +NEXT_PUBLIC_POSTHOG_KEY= diff --git a/app/(site)/layout.tsx b/app/(site)/layout.tsx index e8221ae..d7da93b 100644 --- a/app/(site)/layout.tsx +++ b/app/(site)/layout.tsx @@ -1,4 +1,5 @@ import { AlphaNotice } from '@/components/alpha/AlphaNotice'; +import { AnalyticsPageView } from '@/components/alpha/AnalyticsPageView'; import { InPageLinks } from '@/components/alpha/InPageLinks'; import { SiteHeader } from '@/components/alpha/SiteHeader'; import { OpeningSequence, SkipLink } from '@ekdotico/domico/components'; @@ -18,6 +19,7 @@ export default function SiteLayout({ <> + diff --git a/app/ingest/[...path]/route.ts b/app/ingest/[...path]/route.ts new file mode 100644 index 0000000..4046f25 --- /dev/null +++ b/app/ingest/[...path]/route.ts @@ -0,0 +1,9 @@ +import { forward } from '@/lib/analytics-proxy'; + +// The path the browser reports to; see lib/analytics-proxy.ts. +type Context = { params: Promise<{ path: string[] }> }; + +const handle = async (request: Request, { params }: Context) => + forward(request, (await params).path); + +export { handle as GET, handle as POST, handle as OPTIONS }; diff --git a/components/alpha/AnalyticsPageView.tsx b/components/alpha/AnalyticsPageView.tsx new file mode 100644 index 0000000..aa9312f --- /dev/null +++ b/components/alpha/AnalyticsPageView.tsx @@ -0,0 +1,15 @@ +'use client'; + +import { usePathname } from 'next/navigation'; +import { useEffect } from 'react'; +import { capture, routePattern } from '@/lib/analytics'; + +// Counts a visit as the pattern of its route. Renders nothing, and does nothing +// until NEXT_PUBLIC_POSTHOG_KEY is set (lib/analytics.ts). +export function AnalyticsPageView() { + const pathname = usePathname(); + useEffect(() => { + capture({ name: 'page_view', props: { route: routePattern(pathname) } }); + }, [pathname]); + return null; +} diff --git a/components/alpha/WaitlistForm.tsx b/components/alpha/WaitlistForm.tsx index 4b53fec..d4f3e41 100644 --- a/components/alpha/WaitlistForm.tsx +++ b/components/alpha/WaitlistForm.tsx @@ -5,6 +5,7 @@ import { type FormEvent, useActionState, useEffect, useId, useRef, useState } fr import { Button, Checkbox, FormFault, TextField, Tooltip } from '@ekdotico/domico/components'; import { InfoIcon } from '@ekdotico/domico/icons'; import { submitWaitlist, type WaitlistState } from '@/app/(site)/actions'; +import { capture, outcomeOf } from '@/lib/analytics'; import { ATTRIBUTION_FIELDS, cleanAttribution, referrerHost, UTM_PARAMS } from '@/lib/attribution'; import { TURNSTILE_ACTION, TURNSTILE_SCRIPT, turnstileSiteKey } from '@/lib/turnstile'; @@ -82,6 +83,11 @@ const TESTING_HINT = export function WaitlistForm({ headingLevel = 2 }: { headingLevel?: 2 | 3 }) { const [state, formAction] = useActionState(submitWaitlist, null); + // Counts how a submission ended: one of five names, never the address. + useEffect(() => { + if (state) capture({ name: 'waitlist_submit', props: { outcome: outcomeOf(state) } }); + }, [state]); + if (state?.status === 'ok') { return (
diff --git a/lib/analytics-browser.test.ts b/lib/analytics-browser.test.ts new file mode 100644 index 0000000..7de02f6 --- /dev/null +++ b/lib/analytics-browser.test.ts @@ -0,0 +1,75 @@ +// @vitest-environment happy-dom +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +const SENTINEL_ADDRESS = 'reader-SENTINEL@example.org'; +const SENTINEL_TOKEN = 'turnstile-SENTINEL-0xABC'; + +afterAll(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +// The real library, a made-up key, and every network path replaced, so nothing leaves the test. +async function run(): Promise { + vi.stubEnv('NEXT_PUBLIC_POSTHOG_KEY', 'phc_test_key_not_real'); + const bodies: string[] = []; + const sink = vi.fn(async (_url: unknown, init?: { body?: unknown }) => { + bodies.push(String(init?.body ?? '')); + return new Response('{"status":1}', { status: 200 }); + }); + vi.stubGlobal('fetch', sink); + window.fetch = sink as unknown as typeof window.fetch; + Object.defineProperty(navigator, 'sendBeacon', { value: (_: string, d: unknown) => (bodies.push(String(d)), true), configurable: true }); + + // The library sends by XMLHttpRequest unless told otherwise; record that too. + class RecordingXhr { + status = 200; + readyState = 4; + responseText = '{"status":1}'; + onreadystatechange: (() => void) | null = null; + open() {} + setRequestHeader() {} + send(body?: unknown) { + bodies.push(String(body ?? '')); + queueMicrotask(() => this.onreadystatechange?.()); + } + } + vi.stubGlobal('XMLHttpRequest', RecordingXhr); + window.XMLHttpRequest = RecordingXhr as never; + + const { default: posthog } = await import('posthog-js'); + const { buildConfig, outcomeOf } = await import('./analytics'); + posthog.init('phc_test_key_not_real', { ...buildConfig(), disable_compression: true, request_batching: false, opt_out_useragent_filter: true }); + // A submission whose result carries what must never be sent. + const state = { status: 'refused', message: SENTINEL_ADDRESS, email: SENTINEL_ADDRESS, token: SENTINEL_TOKEN } as never; + posthog.capture('waitlist_submit', { outcome: outcomeOf(state), email: SENTINEL_ADDRESS }); + posthog.capture('$autocapture', { $el_text: SENTINEL_ADDRESS }); + await new Promise((r) => setTimeout(r, 300)); + return bodies; +} + +describe('the browser, with analytics on', () => { + let bodies: string[]; + // One session for both tests: the library initialises once per page. + beforeAll(async () => { + bodies = await run(); + }); + + // Rule 23: the privacy notice says no analytics cookies, and it stays true. + it('writes no ph_ cookie and no ph_ key to localStorage or sessionStorage', () => { + expect(document.cookie).not.toMatch(/ph_/); + for (const store of [localStorage, sessionStorage]) { + expect(Object.keys(store).filter((k) => /ph_|posthog/i.test(k))).toEqual([]); + } + }); + + // Rule 24: no address and no Turnstile token in anything sent. + it('sends no address and no spam-check token in any request', () => { + const all = bodies.join('\n'); + // The permitted event did go out, so an empty body cannot pass this test. + expect(all).toContain('waitlist_submit'); + expect(all).toContain('"outcome":"error"'); + expect(all).not.toContain('SENTINEL'); + expect(all).not.toContain('$autocapture'); + }); +}); diff --git a/lib/analytics-proxy.test.ts b/lib/analytics-proxy.test.ts new file mode 100644 index 0000000..9f74098 --- /dev/null +++ b/lib/analytics-proxy.test.ts @@ -0,0 +1,87 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { config } from '../proxy'; +import { ASSETS_ORIGIN, forward, INGEST_ORIGIN, upstreamUrl } from './analytics-proxy'; + +afterEach(() => vi.unstubAllGlobals()); + +function stubUpstream(headers: Record = {}) { + const fetchMock = vi.fn(async () => new Response('{"status":1}', { status: 200, headers })); + vi.stubGlobal('fetch', fetchMock); + return fetchMock; +} + +const post = (headers: Record) => + new Request('https://alpha.ekdoti.co/ingest/e/?ip=0', { method: 'POST', body: '{}', headers }); + +describe('the analytics forward', () => { + // Rule 13 and rule 15e: nothing that identifies the reader's session reaches PostHog. + it('forwards no cookie, no credential and no address', async () => { + const fetchMock = stubUpstream(); + await forward( + post({ + 'content-type': 'application/json', + cookie: 'ekd-alpha-notice=1; session=SENTINEL', + authorization: 'Bearer SENTINEL', + 'x-forwarded-for': '203.0.113.7', + 'x-real-ip': '203.0.113.7', + forwarded: 'for=203.0.113.7', + referer: 'https://alpha.ekdoti.co/?email=SENTINEL', + origin: 'https://alpha.ekdoti.co', + }), + ['e', ''], + ); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + const sent = new Headers(init.headers); + expect(url).toBe(`${INGEST_ORIGIN}/e/?ip=0`); + expect([...sent.keys()]).toEqual(['content-type']); + expect(JSON.stringify([...sent])).not.toContain('SENTINEL'); + }); + + it('sends settings and scripts to the assets host and events to the ingestion host', () => { + expect(upstreamUrl(['array', 'phc_x', 'config.js'], '')).toBe(`${ASSETS_ORIGIN}/array/phc_x/config.js`); + expect(upstreamUrl(['static', 'a.js'], '')).toBe(`${ASSETS_ORIGIN}/static/a.js`); + expect(upstreamUrl(['e', ''], '?ver=1')).toBe(`${INGEST_ORIGIN}/e/?ver=1`); + }); + + it('refuses a path that could leave PostHog or climb out of it', () => { + for (const segments of [['..', 'x'], ['a', '%2e%2e'], ['a b'], ['//evil.example'], ['a\\b']]) { + expect(upstreamUrl(segments, '')).toBeNull(); + } + }); + + it('answers 405 to other methods and 413 to a large body, and sends neither upstream', async () => { + const fetchMock = stubUpstream(); + expect((await forward(new Request('https://alpha.ekdoti.co/ingest/e/', { method: 'DELETE' }), ['e', ''])).status).toBe(405); + const big = new Request('https://alpha.ekdoti.co/ingest/e/', { + method: 'POST', + body: 'x'.repeat(300_000), + }); + expect((await forward(big, ['e', ''])).status).toBe(413); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('passes no Set-Cookie back to the browser', async () => { + stubUpstream({ 'set-cookie': 'ph=1', 'content-type': 'application/json' }); + const res = await forward(post({}), ['e', '']); + expect(res.headers.get('set-cookie')).toBeNull(); + expect(res.headers.get('content-type')).toBe('application/json'); + }); + + it('is invisible when PostHog does not answer', async () => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('down'))); + expect((await forward(post({}), ['e', ''])).status).toBe(502); + }); +}); + +// Rule 20, for a site with no gate: the path is left out of the policy's matcher on purpose. +describe('the policy matcher', () => { + const matches = (path: string) => new RegExp(`^${config.matcher[0]}$`).test(path); + + it('leaves /ingest to the forward and keeps the policy on every page', () => { + expect(matches('/ingest/e/')).toBe(false); + expect(matches('/ingest')).toBe(false); + expect(matches('/')).toBe(true); + expect(matches('/privacy')).toBe(true); + expect(matches('/ingestion-notes')).toBe(true); + }); +}); diff --git a/lib/analytics-proxy.ts b/lib/analytics-proxy.ts new file mode 100644 index 0000000..34bf8c5 --- /dev/null +++ b/lib/analytics-proxy.ts @@ -0,0 +1,69 @@ +// The same-origin path the browser reports to (app/ingest/[...path]/route.ts). +// It forwards to PostHog's EU cloud and nothing else, and it forwards only what +// is listed here: the request's Cookie and Authorization headers, a client +// address and the page it came from never reach PostHog, because a header that +// is not on the list is not copied. EU only, and fixed in code, so no variable +// can point it elsewhere. + +export const INGEST_ORIGIN = 'https://eu.i.posthog.com'; +export const ASSETS_ORIGIN = 'https://eu-assets.i.posthog.com'; + +// posthog-js loads its settings and any extension from the assets host, under +// these two first segments; everything else is an event on the ingestion host. +const ASSET_SEGMENTS = ['static', 'array']; +const SAFE_PATH = /^[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*\/?$/; +const FORWARD_REQUEST_HEADERS = ['content-type', 'content-encoding', 'accept', 'user-agent']; +const FORWARD_RESPONSE_HEADERS = ['content-type', 'cache-control']; +const MAX_BODY_BYTES = 256 * 1024; + +/** Where a path under /ingest goes, or null if it is not one we forward. */ +export function upstreamUrl(segments: string[], search: string): string | null { + const path = segments.join('/'); + if (!SAFE_PATH.test(path) || segments.some((s) => s === '.' || s === '..')) return null; + const origin = ASSET_SEGMENTS.includes(segments[0] ?? '') ? ASSETS_ORIGIN : INGEST_ORIGIN; + return `${origin}/${path}${search}`; +} + +/** The headers sent upstream: the listed ones present on the request, no others. */ +export function forwardHeaders(incoming: Headers): Headers { + const out = new Headers(); + for (const name of FORWARD_REQUEST_HEADERS) { + const value = incoming.get(name); + if (value !== null) out.set(name, value); + } + return out; +} + +export async function forward(request: Request, segments: string[]): Promise { + if (!['GET', 'POST', 'OPTIONS'].includes(request.method)) return new Response(null, { status: 405 }); + const url = upstreamUrl(segments, new URL(request.url).search); + if (url === null) return new Response(null, { status: 404 }); + + let body: ArrayBuffer | undefined; + if (request.method === 'POST') { + const length = Number(request.headers.get('content-length') ?? 0); + if (length > MAX_BODY_BYTES) return new Response(null, { status: 413 }); + body = await request.arrayBuffer(); + if (body.byteLength > MAX_BODY_BYTES) return new Response(null, { status: 413 }); + } + + try { + const upstream = await fetch(url, { + method: request.method, + headers: forwardHeaders(request.headers), + body, + redirect: 'manual', + cache: 'no-store', + signal: AbortSignal.timeout(5000), + }); + const headers = new Headers(); + for (const name of FORWARD_RESPONSE_HEADERS) { + const value = upstream.headers.get(name); + if (value !== null) headers.set(name, value); + } + return new Response(upstream.body, { status: upstream.status, headers }); + } catch { + // PostHog being unreachable is invisible to the page. + return new Response(null, { status: 502 }); + } +} diff --git a/lib/analytics.test.ts b/lib/analytics.test.ts new file mode 100644 index 0000000..2ec5f90 --- /dev/null +++ b/lib/analytics.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, expectTypeOf, it } from 'vitest'; +import { type AnalyticsEvent, buildConfig, outcomeOf, routePattern, scrub } from './analytics'; + +const SENTINEL = 'SENTINEL-reader@example.org-turnstile-0xABC'; + +describe('what an event can hold', () => { + it('names a route by pattern, whatever path or query it is given', () => { + expect(routePattern('/privacy')).toBe('/privacy'); + expect(routePattern('/privacy/')).toBe('/privacy'); + expect(routePattern('/')).toBe('/'); + expect(routePattern(`/privacy?email=${SENTINEL}#${SENTINEL}`)).toBe('/privacy'); + expect(routePattern(`/${SENTINEL}`)).toBe('other'); + expect(routePattern('other')).toBe('other'); + }); + + // Rule 15a: text the reader, a page or a form wrote reaches no event. + it('puts no input text into any event, however it is offered', () => { + const offered = { + event: 'waitlist_submit', + properties: { + outcome: SENTINEL, + email: SENTINEL, + 'cf-turnstile-response': SENTINEL, + $current_url: `https://alpha.ekdoti.co/?email=${SENTINEL}`, + $title: SENTINEL, + $set: { email: SENTINEL }, + }, + }; + const sent = scrub(offered); + expect(JSON.stringify(sent)).not.toContain('SENTINEL'); + expect(sent?.properties).toMatchObject({ outcome: 'error' }); + }); + + // Rule 24: the outcome comes from the status alone, never the message or the address. + it('gives the outcome of a submission without the address or the message', () => { + expect(outcomeOf({ status: 'ok' })).toBe('ok'); + expect(outcomeOf({ status: 'invalid', message: SENTINEL })).toBe('invalid'); + expect(outcomeOf({ status: 'refused', message: SENTINEL, limited: true })).toBe('rate_limited'); + expect(outcomeOf({ status: 'refused', message: SENTINEL })).toBe('error'); + for (const result of [{ status: 'invalid', message: SENTINEL }, { status: 'refused', message: SENTINEL }] as const) { + expect(outcomeOf(result)).not.toContain('SENTINEL'); + } + }); +}); + +// Rule 15b: the hook PostHog calls before it sends. +describe('scrub', () => { + it('drops an event that is not on the list', () => { + expect(scrub({ event: '$pageview', properties: {} })).toBeNull(); + expect(scrub({ event: '$autocapture', properties: {} })).toBeNull(); + expect(scrub({ event: 'toString', properties: {} })).toBeNull(); + expect(scrub(null)).toBeNull(); + }); + + it('drops a property that is not in the schema, and always disables GeoIP', () => { + const sent = scrub({ + event: 'page_view', + properties: { + route: '/privacy', + token: 'phc_test', + distinct_id: 'x', + $current_url: 'https://alpha.ekdoti.co/privacy', + $pathname: '/privacy', + $referrer: 'https://example.org/', + $set_once: { a: 1 }, + $initial_referrer: 'x', + extra: 'x', + }, + }); + expect(sent?.properties).toEqual({ + route: '/privacy', + token: 'phc_test', + distinct_id: 'x', + $geoip_disable: true, + }); + }); + + it('keeps nothing in the browser, and nothing about a person or a page', () => { + expect(buildConfig()).toMatchObject({ + persistence: 'memory', + person_profiles: 'never', + autocapture: false, + capture_pageview: false, + capture_pageleave: false, + disable_session_recording: true, + disable_surveys: true, + advanced_disable_flags: true, + api_host: '/ingest', + }); + }); +}); + +// Rule 15c: no event has a property that is an open string. +describe('the event list', () => { + it('is two events, each with one closed property', () => { + expectTypeOf().toEqualTypeOf<'page_view' | 'waitlist_submit'>(); + expectTypeOf['props']['route']>().not.toEqualTypeOf(); + expectTypeOf['props']['outcome']>().not.toEqualTypeOf(); + // @ts-expect-error free text is not a route + const bad: AnalyticsEvent = { name: 'page_view', props: { route: 'free text' } }; + expect(bad).toBeDefined(); + }); +}); diff --git a/lib/analytics.ts b/lib/analytics.ts new file mode 100644 index 0000000..44f7ad8 --- /dev/null +++ b/lib/analytics.ts @@ -0,0 +1,156 @@ +import type { PostHogConfig } from 'posthog-js'; +import type { WaitlistResult } from '@/lib/waitlist'; + +// Counts only. Two events, no person, nothing stored in the browser. +// +// A closed list is the only way to capture: `capture` takes one of the two +// events below and nothing else, and every field of an event is a member of a +// closed set. No field holds text a reader, an address or a page wrote. +// +// Off until the variable is set: without NEXT_PUBLIC_POSTHOG_KEY every function +// here returns at once and posthog-js is never fetched. The browser talks only +// to this site's own /ingest path (app/ingest, lib/analytics-proxy.ts), which +// forwards to PostHog's EU cloud. + +/** The route patterns a visit can name. A path that is none of them is `other`. */ +export const ROUTES = ['/', '/privacy', '/confirmed', 'other'] as const; +export type Route = (typeof ROUTES)[number]; + +/** + * How a waitlist submission ended. `already` is in the list because the baseline + * names it, and nothing sends it: the reply never says whether an address was + * already on the list (lib/waitlist.ts), so the browser cannot know. + */ +export const OUTCOMES = ['ok', 'already', 'invalid', 'rate_limited', 'error'] as const; +export type Outcome = (typeof OUTCOMES)[number]; + +export type AnalyticsEvent = + | { name: 'page_view'; props: { route: Route } } + | { name: 'waitlist_submit'; props: { outcome: Outcome } }; + +type EventName = AnalyticsEvent['name']; + +/** The one property each event may carry, and the values it may take. */ +const SCHEMA: { [N in EventName]: { key: string; values: readonly string[]; fallback: string } } = { + page_view: { key: 'route', values: ROUTES, fallback: 'other' }, + waitlist_submit: { key: 'outcome', values: OUTCOMES, fallback: 'error' }, +}; + +// What posthog-js needs on every event to be accepted, and nothing more. Every +// other property, `$current_url`, `$pathname`, `$referrer`, `$title`, `$set`, +// `$set_once` and the `$initial_*` family included, is dropped by `scrub`. +const SYSTEM_PROPERTIES: readonly string[] = [ + 'token', + 'distinct_id', + '$lib', + '$lib_version', + '$process_person_profile', + '$geoip_disable', +]; + +const isEventName = (name: unknown): name is EventName => + typeof name === 'string' && Object.hasOwn(SCHEMA, name); + +/** A visit's path as the pattern it matches, never the path itself. */ +export function routePattern(pathname: string): Route { + const path = pathname.split(/[?#]/)[0] ?? ''; + const trimmed = path.length > 1 ? path.replace(/\/+$/, '') : path; + return (ROUTES as readonly string[]).includes(trimmed) && trimmed !== 'other' ? (trimmed as Route) : 'other'; +} + +/** The outcome of a submission, from what the form is told and nothing it typed. */ +export function outcomeOf(result: WaitlistResult): Outcome { + if (result.status === 'ok') return 'ok'; + if (result.status === 'invalid') return 'invalid'; + return result.limited === true ? 'rate_limited' : 'error'; +} + +/** + * The hook PostHog calls with each event before it is sent. An event that is not + * on the list is dropped; one that is keeps its one schema property, if that + * holds a member of the closed set, and the system properties. + */ +export function scrub }>( + event: T | null, +): T | null { + if (!event || !isEventName(event.event)) return null; + const { key, values, fallback } = SCHEMA[event.event]; + const given = event.properties ?? {}; + const properties: Record = {}; + for (const name of SYSTEM_PROPERTIES) if (name in given) properties[name] = given[name]; + const value = given[key]; + properties[key] = typeof value === 'string' && values.includes(value) ? value : fallback; + properties.$geoip_disable = true; + return { ...event, properties }; +} + +/** The key, or null when analytics is off. Read where Next inlines it. */ +function projectKey(): string | null { + const key = process.env.NEXT_PUBLIC_POSTHOG_KEY; + return typeof key === 'string' && key.trim() !== '' ? key.trim() : null; +} + +/** + * Every option written out, so a change of the SDK's defaults changes nothing + * here. No cookie and no localStorage (`memory`), no person, no autocapture, no + * recording, no survey, no flags, and the site's own origin as the host. + */ +export function buildConfig(): Partial { + return { + api_host: '/ingest', + ui_host: 'https://eu.posthog.com', + defaults: '2026-08-30', + persistence: 'memory', + person_profiles: 'never', + autocapture: false, + capture_dead_clicks: false, + capture_heatmaps: false, + rageclick: false, + capture_exceptions: false, + capture_pageview: false, + capture_pageleave: false, + capture_performance: false, + disable_session_recording: true, + disable_surveys: true, + advanced_disable_flags: true, + save_referrer: false, + before_send: (event) => scrub(event), + }; +} + +type Client = typeof import('posthog-js').default; +let loading: Promise | undefined; + +function afterLoad(run: () => void): void { + if (document.readyState === 'complete') run(); + else window.addEventListener('load', run, { once: true }); +} + +/** posthog-js, fetched once after the page has loaded; null when off or failed. */ +function load(): Promise { + loading ??= new Promise((resolve) => { + const key = projectKey(); + if (key === null || typeof window === 'undefined') return resolve(null); + afterLoad(() => { + import('posthog-js') + .then(({ default: posthog }) => { + posthog.init(key, buildConfig()); + resolve(posthog); + }) + .catch(() => resolve(null)); + }); + }); + return loading; +} + +/** Sends one event. Never throws, and never waits for anything the page needs. */ +export function capture(event: AnalyticsEvent): void { + if (projectKey() === null) return; + void load().then((client) => { + try { + client?.capture(event.name, event.props); + } catch { + // Analytics must never break a page. + } + }); +} diff --git a/lib/waitlist.ts b/lib/waitlist.ts index bf2527a..2556096 100644 --- a/lib/waitlist.ts +++ b/lib/waitlist.ts @@ -28,7 +28,7 @@ import { TURNSTILE_ACTION, TURNSTILE_ORIGIN } from '@/lib/turnstile'; export type WaitlistResult = | { status: 'ok' } | { status: 'invalid'; message: string } - | { status: 'refused'; message: string }; + | { status: 'refused'; message: string; limited?: true }; const MESSAGES = { check: @@ -98,7 +98,7 @@ export async function joinWaitlist(form: FormData, headers: Headers): Promise=18' react-dom: '>=18' + peerDependenciesMeta: + react: + optional: true + react-dom: + optional: true '@emnapi/core@1.10.0': resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==} @@ -500,6 +511,15 @@ packages: '@oxc-project/types@0.156.0': resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + '@posthog/browser-common@0.12.2': + resolution: {integrity: sha512-ZfqE1ntvsFPaD5I1IRh/wRL6JPW6Zlo8NDTOc0s5OtK7JeER9jE/byLjSHQ1/cKZk3MD8JG7F1hANUhnos6dOg==} + + '@posthog/core@1.69.2': + resolution: {integrity: sha512-toMfPKklwLW+a4ZY3/EzM3GNMVXmk2ylGb8NPJXRH4igXMoI8wgNL2jqXOiglWAXqFBLZGYFN1oQx6LVmUTxTg==} + + '@posthog/types@1.427.0': + resolution: {integrity: sha512-2RPVfuGIx0iys78mTOcfdzN7/w7AM1Ak3yu9++4/FonPf08mwGqDkJjThz2dA/34666ToNw5Q4fZoFdgvfNUHw==} + '@rolldown/binding-android-arm-eabi@1.2.19': resolution: {integrity: sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -639,6 +659,15 @@ packages: '@types/react@19.2.18': resolution: {integrity: sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==} + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + + '@types/whatwg-mimetype@3.0.2': + resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==} + + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + '@typescript-eslint/eslint-plugin@8.69.0': resolution: {integrity: sha512-t5jQTKPIgVW1PE6dR6H6Qz5gm8zjMlX5/2gRaOGd9eO6V7J+tQc6iWKukEe7dY8u9HyYasQ0yfF0/FSSTEO2gA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -951,6 +980,10 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true + buffer-image-size@0.6.4: + resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==} + engines: {node: '>=4.0'} + call-bind-apply-helpers@1.0.2: resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} engines: {node: '>= 0.4'} @@ -994,6 +1027,9 @@ packages: convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + core-js@3.51.0: + resolution: {integrity: sha512-7bDKx/5jm5MxzsXxc93g6Z2+4ZsuT/MddrfRmTDJNAkWsYWHU8EVNEsBiIEWnMAMCHMmRfUEjkuo3jeNBOIHRw==} + cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -1052,6 +1088,9 @@ packages: resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==} engines: {node: '>=0.10.0'} + dompurify@3.4.18: + resolution: {integrity: sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==} + dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -1062,6 +1101,10 @@ packages: emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + es-abstract-get@1.0.0: resolution: {integrity: sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==} engines: {node: '>= 0.4'} @@ -1262,6 +1305,9 @@ packages: picomatch: optional: true + fflate@0.4.9: + resolution: {integrity: sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==} + file-entry-cache@8.0.0: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} engines: {node: '>=16.0.0'} @@ -1347,6 +1393,10 @@ packages: resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} engines: {node: '>= 0.4'} + happy-dom@21.0.4: + resolution: {integrity: sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==} + engines: {node: '>=20.0.0'} + has-bigints@1.1.0: resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} engines: {node: '>= 0.4'} @@ -1813,6 +1863,25 @@ packages: resolution: {integrity: sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==} engines: {node: ^10 || ^12 || >=14} + posthog-js@1.453.2: + resolution: {integrity: sha512-dwWSNoTwGPm/dUCcjT69Bnoq7hCx+qPbnX9kax9HR8yjTd7EbIiza1VPW7LZxu7l1JnaZGXFygw4IWQIiqXGeQ==} + peerDependencies: + '@types/react': '>=16.8.0' + react: '>=16.8.0' + peerDependenciesMeta: + '@types/react': + optional: true + react: + optional: true + + preact@10.29.8: + resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} + peerDependencies: + preact-render-to-string: '>=5' + peerDependenciesMeta: + preact-render-to-string: + optional: true + prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} @@ -1824,6 +1893,9 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} + query-selector-shadow-dom@1.0.1: + resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==} + queue-microtask@1.2.3: resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} @@ -2188,6 +2260,16 @@ packages: jsdom: optional: true + web-vitals@6.2.1: + resolution: {integrity: sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==} + + web-vitals@6.2.3: + resolution: {integrity: sha512-Dmy+vdO1UPMqXiAtZSNayhl4f794Bxfd94W4HIj2HlYtczEQfEOon969memlcpcHrTuOKLa5baFjX7WbgmOq+A==} + + whatwg-mimetype@3.0.0: + resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} + engines: {node: '>=12'} + which-boxed-primitive@1.1.1: resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} engines: {node: '>= 0.4'} @@ -2218,6 +2300,18 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} + ws@8.23.0: + resolution: {integrity: sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -2342,7 +2436,7 @@ snapshots: zod: 4.5.4 '@ekdotico/domico@0.48.0(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': - dependencies: + optionalDependencies: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) @@ -2639,6 +2733,21 @@ snapshots: '@oxc-project/types@0.156.0': {} + '@posthog/browser-common@0.12.2': + dependencies: + '@posthog/core': 1.69.2 + '@posthog/types': 1.427.0 + dompurify: 3.4.18 + preact: 10.29.8 + transitivePeerDependencies: + - preact-render-to-string + + '@posthog/core@1.69.2': + dependencies: + '@posthog/types': 1.427.0 + + '@posthog/types@1.427.0': {} + '@rolldown/binding-android-arm-eabi@1.2.19': optional: true @@ -2729,6 +2838,15 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/trusted-types@2.0.7': + optional: true + + '@types/whatwg-mimetype@3.0.2': {} + + '@types/ws@8.18.2': + dependencies: + '@types/node': 24.13.3 + '@typescript-eslint/eslint-plugin@8.69.0(@typescript-eslint/parser@8.69.0(eslint@9.39.5)(typescript@6.0.3))(eslint@9.39.5)(typescript@6.0.3)': dependencies: '@eslint-community/regexpp': 4.12.2 @@ -3043,6 +3161,10 @@ snapshots: node-releases: 2.0.54 update-browserslist-db: 1.3.2(browserslist@4.28.9) + buffer-image-size@0.6.4: + dependencies: + '@types/node': 24.13.3 + call-bind-apply-helpers@1.0.2: dependencies: es-errors: 1.3.0 @@ -3083,6 +3205,8 @@ snapshots: convert-source-map@2.0.0: {} + core-js@3.51.0: {} + cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -3139,6 +3263,10 @@ snapshots: dependencies: esutils: 2.0.3 + dompurify@3.4.18: + optionalDependencies: + '@types/trusted-types': 2.0.7 + dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -3149,6 +3277,8 @@ snapshots: emoji-regex@9.2.2: {} + entities@7.0.1: {} + es-abstract-get@1.0.0: dependencies: es-errors: 1.3.0 @@ -3494,6 +3624,8 @@ snapshots: optionalDependencies: picomatch: 4.0.7 + fflate@0.4.9: {} + file-entry-cache@8.0.0: dependencies: flat-cache: 4.0.1 @@ -3588,6 +3720,19 @@ snapshots: gopd@1.2.0: {} + happy-dom@21.0.4: + dependencies: + '@types/node': 24.13.3 + '@types/whatwg-mimetype': 3.0.2 + '@types/ws': 8.18.2 + buffer-image-size: 0.6.4 + entities: 7.0.1 + whatwg-mimetype: 3.0.0 + ws: 8.23.0 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + has-bigints@1.1.0: {} has-flag@4.0.0: {} @@ -4030,6 +4175,26 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.4 + posthog-js@1.453.2(@types/react@19.2.18)(react@19.2.8): + dependencies: + '@posthog/browser-common': 0.12.2 + '@posthog/core': 1.69.2 + '@posthog/types': 1.427.0 + core-js: 3.51.0 + dompurify: 3.4.18 + fflate: 0.4.9 + preact: 10.29.8 + query-selector-shadow-dom: 1.0.1 + web-vitals: 6.2.3 + web-vitals-soft-navs: web-vitals@6.2.1 + optionalDependencies: + '@types/react': 19.2.18 + react: 19.2.8 + transitivePeerDependencies: + - preact-render-to-string + + preact@10.29.8: {} + prelude-ls@1.2.1: {} prop-types@15.8.1: @@ -4040,6 +4205,8 @@ snapshots: punycode@2.3.1: {} + query-selector-shadow-dom@1.0.1: {} + queue-microtask@1.2.3: {} react-dom@19.2.8(react@19.2.8): @@ -4450,7 +4617,7 @@ snapshots: '@types/node': 24.13.3 fsevents: 2.3.3 - vitest@5.0.0(@types/node@24.13.3)(vite@8.2.4(@types/node@24.13.3)): + vitest@5.0.0(@types/node@24.13.3)(happy-dom@21.0.4)(vite@8.2.4(@types/node@24.13.3)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.0(vite@8.2.4(@types/node@24.13.3)) @@ -4468,9 +4635,16 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 24.13.3 + happy-dom: 21.0.4 transitivePeerDependencies: - msw + web-vitals@6.2.1: {} + + web-vitals@6.2.3: {} + + whatwg-mimetype@3.0.0: {} + which-boxed-primitive@1.1.1: dependencies: is-bigint: 1.1.0 @@ -4523,6 +4697,8 @@ snapshots: word-wrap@1.2.5: {} + ws@8.23.0: {} + yallist@3.1.1: {} yocto-queue@0.1.0: {} diff --git a/proxy.ts b/proxy.ts index 2d4b8f4..9b8a14a 100644 --- a/proxy.ts +++ b/proxy.ts @@ -28,7 +28,10 @@ export const config = { // in next.config.ts. It loads its own scripts without a nonce and reads // Healthchecks.io from the browser, so this site's nonce policy would block // it. It carries no form and no personal data. - matcher: ['/((?!_next/|status(?:/|$)|favicon\\.ico$|apple-icon\\.png$|icon\\.svg$|robots\\.txt$|og\\.png$).*)'], + // + // /ingest is the analytics forward (app/ingest). It returns no page, so it + // takes no policy; this site has no gate, so nothing here redirects it. + matcher: ['/((?!_next/|ingest(?:/|$)|status(?:/|$)|favicon\\.ico$|apple-icon\\.png$|icon\\.svg$|robots\\.txt$|og\\.png$).*)'], }; const CSP_HEADER_NAME = 'Content-Security-Policy'; From 82c247626d708e2c36e15f444e135edf6ec68f83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=B1=CF=8D=CF=81=CE=BF=CF=82=20=CE=91=CF=80?= =?UTF-8?q?=CE=BF=CF=83=CF=84=CF=8C=CE=BB=CE=BF=CF=85=20=28Stavros=20Apost?= =?UTF-8?q?olou=29?= Date: Sat, 21 Nov 2026 16:19:39 +0200 Subject: [PATCH 2/6] fix(analytics): admit only /e/ on the forward, limit it per client, and tighten the scrub A1: the forward relays POST /ingest/e/ only (the one path posthog-js 1.453.2 calls with this configuration, recorded by lib/analytics-capture.test.ts); any other path or method is refused and reaches no upstream, and the assets host is no longer reachable. A2: 120 a minute per client through the existing Upstash limiter; over the limit 429, and when the limiter cannot count (unconfigured in production, or Upstash silent) 503, both with nothing sent upstream. A3: the scrubbed event is built from named fields, so a top-level $set or $set_once cannot pass. A5: the lazy capture() path is tested with the production configuration, and IndexedDB is asserted never opened. A7: disable_external_dependency_loading is set. Co-Authored-By: Claude Sonnet 5.5 --- app/ingest/[...path]/route.ts | 11 ++-- lib/analytics-capture.test.ts | 88 ++++++++++++++++++++++++++++++++ lib/analytics-proxy.test.ts | 95 ++++++++++++++++++++++++++++------- lib/analytics-proxy.ts | 56 ++++++++++++++------- lib/analytics.test.ts | 18 +++++++ lib/analytics.ts | 19 +++++-- lib/rate-limit.ts | 14 ++++++ 7 files changed, 256 insertions(+), 45 deletions(-) create mode 100644 lib/analytics-capture.test.ts diff --git a/app/ingest/[...path]/route.ts b/app/ingest/[...path]/route.ts index 4046f25..0276fac 100644 --- a/app/ingest/[...path]/route.ts +++ b/app/ingest/[...path]/route.ts @@ -1,9 +1,10 @@ import { forward } from '@/lib/analytics-proxy'; +import { consumeIngest } from '@/lib/rate-limit'; -// The path the browser reports to; see lib/analytics-proxy.ts. +// The path the browser reports to; see lib/analytics-proxy.ts. POST only: the +// library sends its events as one POST to /ingest/e/. type Context = { params: Promise<{ path: string[] }> }; -const handle = async (request: Request, { params }: Context) => - forward(request, (await params).path); - -export { handle as GET, handle as POST, handle as OPTIONS }; +export async function POST(request: Request, { params }: Context) { + return forward(request, (await params).path, consumeIngest); +} diff --git a/lib/analytics-capture.test.ts b/lib/analytics-capture.test.ts new file mode 100644 index 0000000..02b45c7 --- /dev/null +++ b/lib/analytics-capture.test.ts @@ -0,0 +1,88 @@ +// @vitest-environment happy-dom +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { ALLOWED_SEGMENTS } from './analytics-proxy'; + +// The lazy path as the site runs it: capture() fetches posthog-js after the +// page has loaded and starts it with buildConfig() as it is, compression and +// batching included. Every network path is replaced, so nothing leaves the test. +const requests: { url: string; via: string }[] = []; +const idb = { open: vi.fn(), deleteDatabase: vi.fn(), databases: vi.fn(async () => []) }; + +beforeAll(async () => { + vi.stubEnv('NEXT_PUBLIC_POSTHOG_KEY', 'phc_test_key_not_real'); + const sink = vi.fn(async (url: unknown) => { + requests.push({ url: String(url), via: 'fetch' }); + return new Response('{"status":1}', { status: 200 }); + }); + vi.stubGlobal('fetch', sink); + window.fetch = sink as unknown as typeof window.fetch; + class RecordingXhr { + status = 200; + readyState = 4; + responseText = '{"status":1}'; + onreadystatechange: (() => void) | null = null; + private url = ''; + open(_method: string, url: string) { + this.url = url; + } + setRequestHeader() {} + send() { + requests.push({ url: this.url, via: 'xhr' }); + queueMicrotask(() => this.onreadystatechange?.()); + } + } + vi.stubGlobal('XMLHttpRequest', RecordingXhr); + window.XMLHttpRequest = RecordingXhr as never; + Object.defineProperty(navigator, 'sendBeacon', { + value: (url: string) => (requests.push({ url, via: 'beacon' }), true), + configurable: true, + }); + + // The library drops events from a browser it takes for a bot: happy-dom + // reports itself as automated (navigator.webdriver) and by its own agent. + Object.defineProperty(navigator, 'webdriver', { value: false, configurable: true }); + Object.defineProperty(navigator, 'userAgent', { + value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36', + configurable: true, + }); + // happy-dom has no IndexedDB: a stub that records being opened proves the + // library never reaches for it, where an absent API would prove nothing. + vi.stubGlobal('indexedDB', idb); + window.indexedDB = idb as never; + + const { capture } = await import('./analytics'); + capture({ name: 'page_view', props: { route: '/' } }); + capture({ name: 'waitlist_submit', props: { outcome: 'ok' } }); + // posthog-js is fetched after the window's load event, then flushes on its own timer. + await new Promise((r) => setTimeout(r, 4000)); +}, 15000); + +afterAll(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +describe('capture(), the lazy path, with the production configuration', () => { + // The list ALLOWED_SEGMENTS is taken from this: a library update that calls + // anywhere else fails here, and the forward would have answered it 404. + it('calls the site\'s own /ingest/e/ and nothing else, and the forward admits exactly that', () => { + expect(requests.length).toBeGreaterThan(0); + const paths = new Set(requests.map(({ url }) => new URL(url, 'https://alpha.ekdoti.co').pathname)); + expect([...paths]).toEqual(['/ingest/e/']); + expect([...ALLOWED_SEGMENTS]).toEqual(['e']); + }); + + // Rule 23, with the storage the first test left out. + it('opens no IndexedDB database, and sets no ph_ cookie or storage key', async () => { + expect(idb.open).not.toHaveBeenCalled(); + expect(idb.deleteDatabase).not.toHaveBeenCalled(); + expect(document.cookie).not.toMatch(/ph_/); + expect(Object.keys(localStorage).filter((k) => /ph_|posthog/i.test(k))).toEqual([]); + expect(Object.keys(sessionStorage).filter((k) => /ph_|posthog/i.test(k))).toEqual([]); + }); + + it('loads nothing from the assets host, so the forward need not admit it', () => { + const assets = requests.filter(({ url }) => /\/ingest\/(static|array)\//.test(url)); + expect(assets).toEqual([]); + }); +}); diff --git a/lib/analytics-proxy.test.ts b/lib/analytics-proxy.test.ts index 9f74098..f3bc7fb 100644 --- a/lib/analytics-proxy.test.ts +++ b/lib/analytics-proxy.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { config } from '../proxy'; -import { ASSETS_ORIGIN, forward, INGEST_ORIGIN, upstreamUrl } from './analytics-proxy'; +import { forward, INGEST_ORIGIN, upstreamUrl, type Limit } from './analytics-proxy'; afterEach(() => vi.unstubAllGlobals()); @@ -10,8 +10,9 @@ function stubUpstream(headers: Record = {}) { return fetchMock; } -const post = (headers: Record) => - new Request('https://alpha.ekdoti.co/ingest/e/?ip=0', { method: 'POST', body: '{}', headers }); +const open: Limit = async () => ({ allowed: true }); +const post = (headers: Record = {}, path = 'e/') => + new Request(`https://alpha.ekdoti.co/ingest/${path}?ip=0`, { method: 'POST', body: '{}', headers }); describe('the analytics forward', () => { // Rule 13 and rule 15e: nothing that identifies the reader's session reaches PostHog. @@ -29,6 +30,7 @@ describe('the analytics forward', () => { origin: 'https://alpha.ekdoti.co', }), ['e', ''], + open, ); const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; const sent = new Headers(init.headers); @@ -37,39 +39,96 @@ describe('the analytics forward', () => { expect(JSON.stringify([...sent])).not.toContain('SENTINEL'); }); - it('sends settings and scripts to the assets host and events to the ingestion host', () => { - expect(upstreamUrl(['array', 'phc_x', 'config.js'], '')).toBe(`${ASSETS_ORIGIN}/array/phc_x/config.js`); - expect(upstreamUrl(['static', 'a.js'], '')).toBe(`${ASSETS_ORIGIN}/static/a.js`); + // A1: the forward is not a relay to every PostHog endpoint. + it('answers 404 to any path but /e/, and sends nothing upstream', async () => { + const fetchMock = stubUpstream(); + const limit = vi.fn(open); + const others = [ + ['i', 'v0', 'e', ''], + ['batch', ''], + ['capture', ''], + ['flags', ''], + ['static', 'array.js'], + ['array', 'phc_x', 'config.js'], + ['api', 'environments', ''], + ['decide', ''], + ['e', 'extra'], + ['e', '', ''], + ['..', 'x'], + ['e', '..'], + ['//evil.example'], + ['E', ''], + [], + ]; + for (const segments of others) { + const res = await forward(post({}, segments.join('/')), segments, limit); + expect(res.status, JSON.stringify(segments)).toBe(404); + } + expect(fetchMock).not.toHaveBeenCalled(); + expect(limit).not.toHaveBeenCalled(); + }); + + it('admits /e and /e/ to the ingestion host, and nothing else', () => { expect(upstreamUrl(['e', ''], '?ver=1')).toBe(`${INGEST_ORIGIN}/e/?ver=1`); + expect(upstreamUrl(['e'], '')).toBe(`${INGEST_ORIGIN}/e/`); }); - it('refuses a path that could leave PostHog or climb out of it', () => { - for (const segments of [['..', 'x'], ['a', '%2e%2e'], ['a b'], ['//evil.example'], ['a\\b']]) { - expect(upstreamUrl(segments, '')).toBeNull(); + it('answers 405 to any method but POST, and sends nothing', async () => { + const fetchMock = stubUpstream(); + for (const method of ['GET', 'DELETE', 'PUT', 'OPTIONS']) { + const res = await forward(new Request('https://alpha.ekdoti.co/ingest/e/', { method }), ['e', ''], open); + expect(res.status, method).toBe(405); } + expect(fetchMock).not.toHaveBeenCalled(); }); - it('answers 405 to other methods and 413 to a large body, and sends neither upstream', async () => { + it('answers 413 to a large body and sends nothing', async () => { const fetchMock = stubUpstream(); - expect((await forward(new Request('https://alpha.ekdoti.co/ingest/e/', { method: 'DELETE' }), ['e', ''])).status).toBe(405); - const big = new Request('https://alpha.ekdoti.co/ingest/e/', { - method: 'POST', - body: 'x'.repeat(300_000), - }); - expect((await forward(big, ['e', ''])).status).toBe(413); + const big = new Request('https://alpha.ekdoti.co/ingest/e/', { method: 'POST', body: 'x'.repeat(300_000) }); + expect((await forward(big, ['e', ''], open)).status).toBe(413); expect(fetchMock).not.toHaveBeenCalled(); }); it('passes no Set-Cookie back to the browser', async () => { stubUpstream({ 'set-cookie': 'ph=1', 'content-type': 'application/json' }); - const res = await forward(post({}), ['e', '']); + const res = await forward(post(), ['e', ''], open); expect(res.headers.get('set-cookie')).toBeNull(); expect(res.headers.get('content-type')).toBe('application/json'); }); it('is invisible when PostHog does not answer', async () => { vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('down'))); - expect((await forward(post({}), ['e', ''])).status).toBe(502); + expect((await forward(post(), ['e', ''], open)).status).toBe(502); + }); +}); + +// A2: a per-client limit, and what happens when it cannot count. +describe('the limit on the forward', () => { + it('answers 429 over the limit, and sends nothing upstream', async () => { + const fetchMock = stubUpstream(); + const res = await forward(post(), ['e', ''], async () => ({ allowed: false })); + expect(res.status).toBe(429); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('counts the request it is given, with the headers of that request', async () => { + stubUpstream(); + const limit = vi.fn(open); + await forward(post({ 'x-real-ip': '203.0.113.9' }), ['e', ''], limit); + expect(limit).toHaveBeenCalledOnce(); + expect(limit.mock.calls[0]![0].get('x-real-ip')).toBe('203.0.113.9'); + }); + + // The limiter throws when the store is not configured in production, and on a + // store error: an unlimited relay is not acceptable, and the page must not + // break, so nothing is forwarded and the library drops the event quietly. + it('answers 503 and sends nothing upstream when the limiter cannot count', async () => { + const fetchMock = stubUpstream(); + const res = await forward(post(), ['e', ''], async () => { + throw new Error('store not configured'); + }); + expect(res.status).toBe(503); + expect(fetchMock).not.toHaveBeenCalled(); }); }); diff --git a/lib/analytics-proxy.ts b/lib/analytics-proxy.ts index 34bf8c5..3a80896 100644 --- a/lib/analytics-proxy.ts +++ b/lib/analytics-proxy.ts @@ -6,22 +6,25 @@ // can point it elsewhere. export const INGEST_ORIGIN = 'https://eu.i.posthog.com'; -export const ASSETS_ORIGIN = 'https://eu-assets.i.posthog.com'; -// posthog-js loads its settings and any extension from the assets host, under -// these two first segments; everything else is an event on the ingestion host. -const ASSET_SEGMENTS = ['static', 'array']; -const SAFE_PATH = /^[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*\/?$/; +// The one first segment posthog-js 1.453.2 calls with the configuration of +// lib/analytics.ts, as lib/analytics-capture.test.ts records it. Anything else, +// a /batch/ of another project or a /api/ path included, is a 404 and reaches +// nobody. Nothing is admitted from the assets host (so none is named here): the +// test shows the library loads no settings or script from it with every +// feature off. +export const ALLOWED_SEGMENTS: readonly string[] = ['e']; const FORWARD_REQUEST_HEADERS = ['content-type', 'content-encoding', 'accept', 'user-agent']; const FORWARD_RESPONSE_HEADERS = ['content-type', 'cache-control']; const MAX_BODY_BYTES = 256 * 1024; /** Where a path under /ingest goes, or null if it is not one we forward. */ export function upstreamUrl(segments: string[], search: string): string | null { - const path = segments.join('/'); - if (!SAFE_PATH.test(path) || segments.some((s) => s === '.' || s === '..')) return null; - const origin = ASSET_SEGMENTS.includes(segments[0] ?? '') ? ASSETS_ORIGIN : INGEST_ORIGIN; - return `${origin}/${path}${search}`; + // /e or /e/ and nothing after it. + const [first, ...rest] = segments; + if (first === undefined || !ALLOWED_SEGMENTS.includes(first)) return null; + if (rest.length > 1 || (rest.length === 1 && rest[0] !== '')) return null; + return `${INGEST_ORIGIN}/${first}/${search}`; } /** The headers sent upstream: the listed ones present on the request, no others. */ @@ -34,22 +37,39 @@ export function forwardHeaders(incoming: Headers): Headers { return out; } -export async function forward(request: Request, segments: string[]): Promise { - if (!['GET', 'POST', 'OPTIONS'].includes(request.method)) return new Response(null, { status: 405 }); +/** + * Whether this client may send one more. Injected, so the forward can be tested + * without a store; the route passes the site's limiter (lib/rate-limit.ts). + */ +export type Limit = (headers: Headers) => Promise<{ allowed: boolean }>; + +// Order: method and path first, because a request that would be refused anyway +// costs no count; then the limit, before the body is read or anything is sent. +export async function forward(request: Request, segments: string[], limit: Limit): Promise { + if (request.method !== 'POST') return new Response(null, { status: 405 }); const url = upstreamUrl(segments, new URL(request.url).search); if (url === null) return new Response(null, { status: 404 }); - let body: ArrayBuffer | undefined; - if (request.method === 'POST') { - const length = Number(request.headers.get('content-length') ?? 0); - if (length > MAX_BODY_BYTES) return new Response(null, { status: 413 }); - body = await request.arrayBuffer(); - if (body.byteLength > MAX_BODY_BYTES) return new Response(null, { status: 413 }); + // An unlimited relay is not acceptable, and analytics must not break a page: + // when the limiter cannot count (not configured in production, or Upstash + // does not answer), nothing is forwarded and the answer is 503. The library + // drops the event and the page never knows. + let allowed: boolean; + try { + ({ allowed } = await limit(request.headers)); + } catch { + return new Response(null, { status: 503 }); } + if (!allowed) return new Response(null, { status: 429 }); + + const length = Number(request.headers.get('content-length') ?? 0); + if (length > MAX_BODY_BYTES) return new Response(null, { status: 413 }); + const body = await request.arrayBuffer(); + if (body.byteLength > MAX_BODY_BYTES) return new Response(null, { status: 413 }); try { const upstream = await fetch(url, { - method: request.method, + method: 'POST', headers: forwardHeaders(request.headers), body, redirect: 'manual', diff --git a/lib/analytics.test.ts b/lib/analytics.test.ts index 2ec5f90..43fa21b 100644 --- a/lib/analytics.test.ts +++ b/lib/analytics.test.ts @@ -75,6 +75,23 @@ describe('scrub', () => { }); }); + // A3: `$set` and `$set_once` sit beside `properties`, not inside it. + it('drops a top-level $set and $set_once, and keeps only the event, its id and its time', () => { + const when = new Date(0); + const sent = scrub({ + event: 'waitlist_submit', + uuid: 'u-1', + timestamp: when, + properties: { outcome: 'ok' }, + $set: { email: SENTINEL }, + $set_once: { email: SENTINEL }, + extra: SENTINEL, + } as Parameters[0]); + expect(Object.keys(sent ?? {}).sort()).toEqual(['event', 'properties', 'timestamp', 'uuid']); + expect(sent).toMatchObject({ uuid: 'u-1', timestamp: when }); + expect(JSON.stringify(sent)).not.toContain('SENTINEL'); + }); + it('keeps nothing in the browser, and nothing about a person or a page', () => { expect(buildConfig()).toMatchObject({ persistence: 'memory', @@ -85,6 +102,7 @@ describe('scrub', () => { disable_session_recording: true, disable_surveys: true, advanced_disable_flags: true, + disable_external_dependency_loading: true, api_host: '/ingest', }); }); diff --git a/lib/analytics.ts b/lib/analytics.ts index 44f7ad8..c85233d 100644 --- a/lib/analytics.ts +++ b/lib/analytics.ts @@ -70,9 +70,9 @@ export function outcomeOf(result: WaitlistResult): Outcome { * on the list is dropped; one that is keeps its one schema property, if that * holds a member of the closed set, and the system properties. */ -export function scrub }>( - event: T | null, -): T | null { +export function scrub< + T extends { event: string; uuid?: string; timestamp?: Date; properties?: Record }, +>(event: T | null): T | null { if (!event || !isEventName(event.event)) return null; const { key, values, fallback } = SCHEMA[event.event]; const given = event.properties ?? {}; @@ -81,7 +81,15 @@ export function scrub } = { + event: event.event, + properties, + }; + if (event.uuid !== undefined) scrubbed.uuid = event.uuid; + if (event.timestamp !== undefined) scrubbed.timestamp = event.timestamp; + return scrubbed as unknown as T; } /** The key, or null when analytics is off. Read where Next inlines it. */ @@ -114,6 +122,9 @@ export function buildConfig(): Partial { disable_surveys: true, advanced_disable_flags: true, save_referrer: false, + // No script from anywhere: the toolbar, which a URL fragment can start, and + // every extension are fetched as external dependencies. + disable_external_dependency_loading: true, before_send: (event) => scrub(event), }; } diff --git a/lib/rate-limit.ts b/lib/rate-limit.ts index a0a8077..69c3bac 100644 --- a/lib/rate-limit.ts +++ b/lib/rate-limit.ts @@ -64,6 +64,11 @@ const LIMITERS = { 'client-day': limiter('rl:waitlist:client-day', 10, '24 h'), address: limiter('rl:waitlist:address', 3, '24 h'), global: limiter('rl:waitlist:global', 250, '24 h'), + // ingest 120 analytics posts a minute per address of origin (the forward + // at /ingest). A page sends a handful; this stops the path being + // used as a free relay. The window is a minute, so the key is gone + // a minute later, well inside the day the other buckets keep. + ingest: limiter('rl:ingest:client', 120, '1 m'), }; export type LimitScope = keyof typeof LIMITERS; @@ -89,6 +94,15 @@ async function consume(scope: LimitScope, identifier: string): Promise { + return consume('ingest', clientKey(headers)); +} + /** Count one signup from this client. Checked before the Turnstile call. */ export async function consumeClient(headers: Headers): Promise { const key = clientKey(headers); From 7c6da6b20f5ec0f1689672822d483dc7ac5918ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=B1=CF=8D=CF=81=CE=BF=CF=82=20=CE=91=CF=80?= =?UTF-8?q?=CE=BF=CF=83=CF=84=CF=8C=CE=BB=CE=BF=CF=85=20=28Stavros=20Apost?= =?UTF-8?q?olou=29?= Date: Sat, 21 Nov 2026 16:23:47 +0200 Subject: [PATCH 3/6] feat(privacy): say what is counted, and name the measurement service The owner-approved wording of reports/texts-for-approval.md, items 1a, 1b and 1c: a Counting visits paragraph after Where you signed up from, and the measurement service among the providers. The cookie paragraph, the basis, the retention paragraph and the date are untouched. lib/privacy-text.test.tsx pins the whole text. Co-Authored-By: Claude Sonnet 5.5 --- app/(site)/privacy/page.tsx | 16 ++++++++++- lib/privacy-text.test.tsx | 54 +++++++++++++++++++++++++++++++++++++ vitest.config.mts | 2 +- 3 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 lib/privacy-text.test.tsx diff --git a/app/(site)/privacy/page.tsx b/app/(site)/privacy/page.tsx index 266b5e0..784cfb2 100644 --- a/app/(site)/privacy/page.tsx +++ b/app/(site)/privacy/page.tsx @@ -56,6 +56,18 @@ export default function PrivacyPage() { www.linkedin.com, without the page you were on. It is kept only once you confirm your address, and nothing is stored in your browser for it.

+

+ Counting visits. To learn how many people read this site and whether the + form works, each page you open sends one short message to a measurement service. It + says which page was opened (the home page, this page, the confirmation page, or + another) and carries what your browser sends with any request, such as its name and + version. When you send the form, a second message says whether it worked or failed, + and never the address you entered. Nothing is stored in your browser for this. The + messages of one visit share a random number that lasts only while the page is open, + so there is no identifier that lasts beyond the page, and nothing links one visit to + the next. The service does not receive your network address; it sees only that of + the provider that hosts this site, and works out no location. +

Who holds it. The Ekdotico team, reachable at{' '} {SITE_META.contact}. @@ -72,7 +84,9 @@ export default function PrivacyPage() { Who else handles it. Service providers who process it for us and on our instructions: an email service in the European Union, which stores the waitlist, sends its emails, and records when and from which network address you confirmed, as - evidence of your consent; the provider that hosts this site; and a spam-check + evidence of your consent; the provider that hosts this site; a measurement service + in the European Union, which receives the messages described under + "Counting visits" through this site's own address; and a spam-check service, which looks at your browser and network address to tell a person from a program. Where any of them may process data outside the European Union, safeguards recognised by the GDPR, such as standard contractual clauses, apply. You can ask us diff --git a/lib/privacy-text.test.tsx b/lib/privacy-text.test.tsx new file mode 100644 index 0000000..9fe1119 --- /dev/null +++ b/lib/privacy-text.test.tsx @@ -0,0 +1,54 @@ +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, it, vi } from 'vitest'; + +// The privacy page's footer is a client component of the design package; the +// words under test are the page's own. +vi.mock('@/components/alpha/SiteFooter', () => ({ SiteFooter: () => null })); + +const { default: PrivacyPage } = await import('@/app/(site)/privacy/page'); + +// The owner's approved wording, character for character (reports/texts-for-approval.md, +// items 1a, 1b and 1c). A later edit to any of it fails here and needs the owner. +const COUNTING_VISITS = + 'Counting visits. To learn how many people read this site and whether the form works, each page you open sends one short message to a measurement service. It says which page was opened (the home page, this page, the confirmation page, or another) and carries what your browser sends with any request, such as its name and version. When you send the form, a second message says whether it worked or failed, and never the address you entered. Nothing is stored in your browser for this. The messages of one visit share a random number that lasts only while the page is open, so there is no identifier that lasts beyond the page, and nothing links one visit to the next. The service does not receive your network address; it sees only that of the provider that hosts this site, and works out no location.'; +const PROCESSOR_CLAUSE = + 'a measurement service in the European Union, which receives the messages described under "Counting visits" through this site\'s own address;'; +const COOKIES = + 'Cookies. This site sets no advertising or analytics cookies. Your browser keeps a few settings for it, such as the appearance you choose.'; + +// The page's visible text, one string per paragraph, tags and entities gone. +function paragraphs(): string[] { + const html = renderToStaticMarkup(); + return [...html.matchAll(/]*>([\s\S]*?)<\/p>/g)].map(([, inner]) => + inner + .replace(/<[^>]+>/g, '') + .replace(/"/g, '"') + .replace(/'|'|'/g, "'") + .replace(/&/g, '&') + .replace(/\s+/g, ' ') + .trim(), + ); +} + +describe('the privacy page, counting visits', () => { + it('carries the approved paragraph, whole, directly after "Where you signed up from"', () => { + const all = paragraphs(); + const at = all.findIndex((p) => p.startsWith('Where you signed up from.')); + expect(at).toBeGreaterThanOrEqual(0); + expect(all[at + 1]).toBe(COUNTING_VISITS); + expect(all[at + 2]).toMatch(/^Who holds it\./); + }); + + it('names the measurement service among the processors, after the host and before the spam check', () => { + const handled = paragraphs().find((p) => p.startsWith('Who else handles it.')) ?? ''; + expect(handled).toContain(`the provider that hosts this site; ${PROCESSOR_CLAUSE} and a spam-check service`); + }); + + it('leaves the cookie paragraph exactly as it was', () => { + expect(paragraphs()).toContain(COOKIES); + }); + + it('has the paragraph once', () => { + expect(paragraphs().filter((p) => p.startsWith('Counting visits.'))).toHaveLength(1); + }); +}); diff --git a/vitest.config.mts b/vitest.config.mts index fc336a7..c618fbc 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -2,5 +2,5 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ resolve: { alias: { '@': import.meta.dirname } }, - test: { include: ['lib/**/*.test.ts'] }, + test: { include: ['lib/**/*.test.{ts,tsx}'] }, }); From c57d690d5bd191b4f1153c41168e7e21afbc4a23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=B1=CF=8D=CF=81=CE=BF=CF=82=20=CE=91=CF=80?= =?UTF-8?q?=CE=BF=CF=83=CF=84=CF=8C=CE=BB=CE=BF=CF=85=20=28Stavros=20Apost?= =?UTF-8?q?olou=29?= Date: Sat, 21 Nov 2026 16:27:16 +0200 Subject: [PATCH 4/6] feat(privacy): state the basis for counting visits The owner-approved sentence after the legitimate-interest sentence in Why we may hold it, and the right to object now to any of these. The retention paragraph and the date are untouched. The pinning test covers both sentences, the whole paragraph, and the unchanged retention paragraph. Co-Authored-By: Claude Sonnet 5.5 --- app/(site)/privacy/page.tsx | 5 +++-- lib/privacy-text.test.tsx | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/app/(site)/privacy/page.tsx b/app/(site)/privacy/page.tsx index 784cfb2..049625c 100644 --- a/app/(site)/privacy/page.tsx +++ b/app/(site)/privacy/page.tsx @@ -77,8 +77,9 @@ export default function PrivacyPage() { given when you send the form and again when you open the confirmation link. You can withdraw it at any time through the unsubscribe link in any of our emails. For the spam check and for recording where you signed up from, our legitimate interest in - keeping the form working and in knowing which posts reach people. You can object to - either by writing to us. + keeping the form working and in knowing which posts reach people. For counting + visits, our legitimate interest in knowing whether the site and its form work. You + can object to any of these by writing to us.

Who else handles it. Service providers who process it for us and on our diff --git a/lib/privacy-text.test.tsx b/lib/privacy-text.test.tsx index 9fe1119..e984a26 100644 --- a/lib/privacy-text.test.tsx +++ b/lib/privacy-text.test.tsx @@ -44,6 +44,22 @@ describe('the privacy page, counting visits', () => { expect(handled).toContain(`the provider that hosts this site; ${PROCESSOR_CLAUSE} and a spam-check service`); }); + // The owner's approved basis sentence, and the changed last sentence, with + // everything else in the paragraph as it was. + it('states the basis for counting, and lets the reader object to any of the three', () => { + const why = paragraphs().find((p) => p.startsWith('Why we may hold it.')) ?? ''; + expect(why).toBe( + 'Why we may hold it. For the waitlist and the testing email, your consent, given when you send the form and again when you open the confirmation link. You can withdraw it at any time through the unsubscribe link in any of our emails. For the spam check and for recording where you signed up from, our legitimate interest in keeping the form working and in knowing which posts reach people. For counting visits, our legitimate interest in knowing whether the site and its form work. You can object to any of these by writing to us.', + ); + }); + + it('leaves the retention paragraph and the date as they were', () => { + const all = paragraphs(); + expect(all).toContain( + 'How long. Your address is kept until you unsubscribe or ask us to delete it, and no longer than the waitlist is needed for news of the opening; the testing list closes when testing ends, or with the waitlist. Records used to stop the form being misused are short-lived and deleted automatically.', + ); + }); + it('leaves the cookie paragraph exactly as it was', () => { expect(paragraphs()).toContain(COOKIES); }); From c1b61ed59ac99b64e586a240684764b51bcfcd9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=B1=CF=8D=CF=81=CE=BF=CF=82=20=CE=91=CF=80?= =?UTF-8?q?=CE=BF=CF=83=CF=84=CF=8C=CE=BB=CE=BF=CF=85=20=28Stavros=20Apost?= =?UTF-8?q?olou=29?= Date: Sat, 21 Nov 2026 17:26:29 +0200 Subject: [PATCH 5/6] feat(privacy): keep the counts for one year, and date the notice The owner-approved retention sentence, last in How long, and Last updated 21 November 2026. The pinning test covers the whole retention paragraph and the date. Co-Authored-By: Claude Sonnet 5.5 --- app/(site)/privacy/page.tsx | 5 +++-- lib/privacy-text.test.tsx | 12 ++++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/app/(site)/privacy/page.tsx b/app/(site)/privacy/page.tsx index 049625c..0234c69 100644 --- a/app/(site)/privacy/page.tsx +++ b/app/(site)/privacy/page.tsx @@ -18,7 +18,7 @@ export const metadata: Metadata = { // project can keep without effort, or one the GDPR makes anyway. // // Change UPDATED with any change of substance. -const UPDATED = '28 October 2026'; +const UPDATED = '21 November 2026'; export default function PrivacyPage() { return ( @@ -97,7 +97,8 @@ export default function PrivacyPage() { How long. Your address is kept until you unsubscribe or ask us to delete it, and no longer than the waitlist is needed for news of the opening; the testing list closes when testing ends, or with the waitlist. Records used to stop the form being - misused are short-lived and deleted automatically. + misused are short-lived and deleted automatically. The counts of visits are kept for + one year and then deleted.

Cookies. This site sets no advertising or analytics cookies. Your browser diff --git a/lib/privacy-text.test.tsx b/lib/privacy-text.test.tsx index e984a26..21d4266 100644 --- a/lib/privacy-text.test.tsx +++ b/lib/privacy-text.test.tsx @@ -53,13 +53,17 @@ describe('the privacy page, counting visits', () => { ); }); - it('leaves the retention paragraph and the date as they were', () => { - const all = paragraphs(); - expect(all).toContain( - 'How long. Your address is kept until you unsubscribe or ask us to delete it, and no longer than the waitlist is needed for news of the opening; the testing list closes when testing ends, or with the waitlist. Records used to stop the form being misused are short-lived and deleted automatically.', + // The owner's approved retention sentence, last in the paragraph, the rest as it was. + it('keeps the counts for one year, as the last sentence of the retention paragraph', () => { + expect(paragraphs()).toContain( + 'How long. Your address is kept until you unsubscribe or ask us to delete it, and no longer than the waitlist is needed for news of the opening; the testing list closes when testing ends, or with the waitlist. Records used to stop the form being misused are short-lived and deleted automatically. The counts of visits are kept for one year and then deleted.', ); }); + it('shows the date the owner approved', () => { + expect(renderToStaticMarkup()).toContain('21 November 2026'); + }); + it('leaves the cookie paragraph exactly as it was', () => { expect(paragraphs()).toContain(COOKIES); }); From 9bc1a137c66d4284bd382486dccbadcdd85ecd90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=A3=CF=84=CE=B1=CF=8D=CF=81=CE=BF=CF=82=20=CE=91=CF=80?= =?UTF-8?q?=CE=BF=CF=83=CF=84=CF=8C=CE=BB=CE=BF=CF=85=20=28Stavros=20Apost?= =?UTF-8?q?olou=29?= Date: Sat, 21 Nov 2026 17:33:06 +0200 Subject: [PATCH 6/6] feat(privacy): the records that stop misuse cover the counting too The owner-approved wording of the How long sentence: the rate limit on the analytics path keeps a network address for a minute. The pinning test covers it. Co-Authored-By: Claude Sonnet 5.5 --- app/(site)/privacy/page.tsx | 4 ++-- lib/privacy-text.test.tsx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/(site)/privacy/page.tsx b/app/(site)/privacy/page.tsx index 0234c69..e6c86b4 100644 --- a/app/(site)/privacy/page.tsx +++ b/app/(site)/privacy/page.tsx @@ -96,8 +96,8 @@ export default function PrivacyPage() {

How long. Your address is kept until you unsubscribe or ask us to delete it, and no longer than the waitlist is needed for news of the opening; the testing list - closes when testing ends, or with the waitlist. Records used to stop the form being - misused are short-lived and deleted automatically. The counts of visits are kept for + closes when testing ends, or with the waitlist. Records used to stop the form or the + counting being misused are short-lived and deleted automatically. The counts of visits are kept for one year and then deleted.

diff --git a/lib/privacy-text.test.tsx b/lib/privacy-text.test.tsx index 21d4266..52a1940 100644 --- a/lib/privacy-text.test.tsx +++ b/lib/privacy-text.test.tsx @@ -56,7 +56,7 @@ describe('the privacy page, counting visits', () => { // The owner's approved retention sentence, last in the paragraph, the rest as it was. it('keeps the counts for one year, as the last sentence of the retention paragraph', () => { expect(paragraphs()).toContain( - 'How long. Your address is kept until you unsubscribe or ask us to delete it, and no longer than the waitlist is needed for news of the opening; the testing list closes when testing ends, or with the waitlist. Records used to stop the form being misused are short-lived and deleted automatically. The counts of visits are kept for one year and then deleted.', + 'How long. Your address is kept until you unsubscribe or ask us to delete it, and no longer than the waitlist is needed for news of the opening; the testing list closes when testing ends, or with the waitlist. Records used to stop the form or the counting being misused are short-lived and deleted automatically. The counts of visits are kept for one year and then deleted.', ); });