import type { CaptureResult } from 'posthog-js' import { afterEach, describe, expect, it, vi } from 'vitest' import tf from '../../infra/threadbare.tf?raw' import { API_HOST, ASSETS_HOST, beforeSend } from './analytics' const init = vi.hoisted(() => vi.fn()) vi.mock('posthog-js', () => ({ default: { init } })) const DID = 'did:plc:example' const THREAD = encodeURIComponent(`at://${DID}/app.bsky.feed.post/3kexample`) describe('beforeSend', () => { it('keeps OAuth parameters and thread URIs out of every URL it sends', () => { const callback = 'https://threadbare.substandard.blog/oauth/callback?state=s&iss=https%3A%2F%2Fbsky.social&code=c' const event = beforeSend({ uuid: '0', event: '$pageview', properties: { $current_url: `https://threadbare.substandard.blog/?ref=x#thread?uri=${THREAD}&branch=${THREAD}`, $referrer: callback, $initial_person_info: { u: callback, r: '$direct' }, $pathname: '/oauth/callback', }, $set_once: { $initial_current_url: callback }, } as CaptureResult) const sent = JSON.stringify(event) for (const leaked of [DID, 'code=', 'state=', 'iss=']) expect(sent).not.toContain(leaked) expect(event?.properties.$current_url).toBe('https://threadbare.substandard.blog/?ref=x#thread') expect(event?.properties.$referrer).toBe('https://threadbare.substandard.blog/oauth/callback') expect(event?.properties.$pathname).toBe('/oauth/callback') }) }) describe('startAnalytics', () => { afterEach(() => { vi.unstubAllEnvs() vi.unstubAllGlobals() vi.resetModules() init.mockClear() }) async function startOn(hostname: string) { vi.stubEnv('PROD', true) vi.stubGlobal('location', { hostname }) const { startAnalytics } = await import('./analytics') await startAnalytics() } it('reports from threadbare.substandard.blog with a host-only cookie', async () => { await startOn('threadbare.substandard.blog') expect(init).toHaveBeenCalledOnce() // A .substandard.blog cookie would reach the frontpage, which stores nothing. expect(init.mock.calls[0][1]).toMatchObject({ cross_subdomain_cookie: false }) }) it('stays silent on any other host', async () => { await startOn('threadbare.example.com') expect(init).not.toHaveBeenCalled() }) }) describe('threadbare CSP', () => { const directive = (name: string) => tf.match(new RegExp(`"${name} ([^;"]*);`))?.[1].split(' ') ?? [] it('lets posthog-js load its extensions and send events', () => { expect(directive('script-src')).toContain(ASSETS_HOST) expect(directive('connect-src').some((source) => source === 'https:' || source === API_HOST)).toBe(true) }) })