feat(analytics): add PostHog (EU) behind a same-origin proxy (#1237)

Recapt shuts down in four days, taking product analytics and session
replay with it. This adds PostHog Cloud EU alongside it; the Recapt
removal follows separately so events can be confirmed landing first.

Wiring choices that are not the tutorial defaults:

- Same-origin reverse proxy (/rl -> eu.i.posthog.com) instead of adding
  PostHog hosts to the CSP. connect-src 'self' and script-src 'self'
  already cover it, tracking blockers have no third-party host to match,
  and the Recapt allowlist entries in next.config.ts get replaced by
  nothing at all when they go. Needs skipTrailingSlashRedirect, since
  PostHog sends trailing-slash API requests; verified that trailing-slash
  URLs on normal routes still resolve 200 rather than 404.

- /rl is excluded from the proxy.ts matcher. Middleware runs BEFORE
  next.config rewrites, so without this updateSession() treats an
  ingestion POST as an unknown protected path and 307s it to /login.
  Verified with a control: /zz/flags/ -> 307 /login, /rl/flags/ -> 200
  from PostHog. This fails silently otherwise, because asset loads keep
  working through the rewrite while no events arrive.

- persistence: 'memory' so nothing is written to the device and no
  cookie-consent banner is required. Everything post-login is unaffected:
  AnalyticsIdentify re-identifies on each dashboard load.

- session_recording.maskTextSelector: '*'. PostHog masks inputs but not
  text by default, and this app renders org numbers (which for an
  enskild firma ARE the owner's personnummer), customer names and
  balances as ordinary text. Replays show where a user gets stuck, never
  what their books say. buildGroupProperties() also refuses to send
  org_number at all, with a test pinning it.

- Error tracking registers through the existing lib/observability sink
  rather than bypassing it, so every error-level createLogger() line is
  captured already redacted. instrumentation.ts onRequestError covers
  what escapes uncaught.

Analytics is hosted-only: isAnalyticsEnabled() short-circuits on
NEXT_PUBLIC_SELF_HOSTED and no Docker sentinel is added, so self-hosted
runs with zero third-party runtime code. Recapt got that outcome only by
accident, via a missing sentinel; here it is explicit and tested.

vitest.config.ts aliases 'server-only' to a stub: it is a build-time
guard whose real entry point always throws, which broke 48 test files the
moment a server-only module entered the graph. request-context.ts was
already carrying the same latent trap.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-07-27 14:30:49 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent 922cf16227
commit d4f82cafc4
22 changed files with 886 additions and 8 deletions
+66
View File
@@ -0,0 +1,66 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { isAnalyticsEnabled, warnIfAnalyticsMisconfigured, POSTHOG_TOKEN_VAR } from '../enabled'
describe('analytics gate', () => {
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
describe('isAnalyticsEnabled', () => {
it('returns false when NEXT_PUBLIC_SELF_HOSTED is true, even with a token', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
vi.stubEnv('NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN', 'phc_test')
expect(isAnalyticsEnabled()).toBe(false)
})
it('returns true when a token is set and not self-hosted', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN', 'phc_test')
expect(isAnalyticsEnabled()).toBe(true)
})
it('returns false when the token is unset', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN', '')
expect(isAnalyticsEnabled()).toBe(false)
})
})
describe('warnIfAnalyticsMisconfigured', () => {
it('returns true and stays quiet when configured', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN', 'phc_test')
expect(warnIfAnalyticsMisconfigured()).toBe(true)
expect(warn).not.toHaveBeenCalled()
})
it('warns in development when the token is missing', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN', '')
vi.stubEnv('NODE_ENV', 'development')
expect(warnIfAnalyticsMisconfigured()).toBe(false)
expect(warn).toHaveBeenCalledWith(expect.stringContaining(POSTHOG_TOKEN_VAR))
})
it('stays silent in production when the token is missing', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN', '')
vi.stubEnv('NODE_ENV', 'production')
expect(warnIfAnalyticsMisconfigured()).toBe(false)
expect(warn).not.toHaveBeenCalled()
})
it('stays silent on self-hosted: off is deliberate, not a misconfiguration', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
vi.stubEnv('NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN', '')
vi.stubEnv('NODE_ENV', 'development')
expect(warnIfAnalyticsMisconfigured()).toBe(false)
expect(warn).not.toHaveBeenCalled()
})
})
})
@@ -0,0 +1,78 @@
import { describe, it, expect } from 'vitest'
import { buildPersonProperties, buildGroupProperties } from '../properties'
describe('buildPersonProperties', () => {
it('carries email, name and role', () => {
expect(
buildPersonProperties({
userId: 'u1',
email: 'jakob@example.se',
fullName: 'Jakob Wennberg',
role: 'owner',
})
).toEqual({ email: 'jakob@example.se', name: 'Jakob Wennberg', role: 'owner' })
})
it('omits missing fields instead of sending nulls', () => {
expect(buildPersonProperties({ userId: 'u1', email: null, fullName: undefined })).toEqual({})
})
it('never echoes the userId into properties (it is the distinct id)', () => {
const props = buildPersonProperties({ userId: 'u1', email: 'a@b.se' })
expect(props).not.toHaveProperty('userId')
expect(props).not.toHaveProperty('user_id')
})
})
describe('buildGroupProperties', () => {
const company = {
id: 'c1',
name: 'Nordvik Bygg AB',
entityType: 'aktiebolag' as const,
accountingFramework: 'k2' as const,
paysSalaries: true,
trialEndsAt: '2026-08-01',
capabilities: ['ai', 'salary'],
}
it('carries company-shaped facts', () => {
expect(buildGroupProperties(company)).toEqual({
name: 'Nordvik Bygg AB',
entity_type: 'aktiebolag',
accounting_framework: 'k2',
pays_salaries: true,
trial_ends_at: '2026-08-01',
capabilities: ['ai', 'salary'],
})
})
// The load-bearing privacy assertion: for an enskild firma the
// organisationsnummer IS the owner's personnummer.
it('never sends org_number, whatever is passed in', () => {
const props = buildGroupProperties({
...company,
// @ts-expect-error deliberately passing a field the type forbids
org_number: '556677-8899',
orgNumber: '556677-8899',
})
expect(props).not.toHaveProperty('org_number')
expect(props).not.toHaveProperty('orgNumber')
expect(JSON.stringify(props)).not.toContain('556677')
})
it('sorts capabilities so ordering churn is not seen as a change', () => {
const a = buildGroupProperties({ ...company, capabilities: ['salary', 'ai'] })
const b = buildGroupProperties({ ...company, capabilities: ['ai', 'salary'] })
expect(a.capabilities).toEqual(b.capabilities)
})
it('does not mutate the caller capabilities array', () => {
const capabilities = ['salary', 'ai']
buildGroupProperties({ ...company, capabilities })
expect(capabilities).toEqual(['salary', 'ai'])
})
it('omits absent optional fields', () => {
expect(buildGroupProperties({ id: 'c1', name: 'Ensam EF' })).toEqual({ name: 'Ensam EF' })
})
})
+48
View File
@@ -0,0 +1,48 @@
/**
* PostHog analytics gate.
*
* Analytics is a HOSTED-ONLY feature. Self-hosted deployments never load
* PostHog: an AGPL operator running their own instance should not have their
* users' behaviour shipped to our project, and the token is not baked into
* the Docker image (no `__NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN__` sentinel in
* Dockerfile / docker-entrypoint.sh, deliberately). Recapt achieved the same
* result only by accident, via that missing sentinel; here it is explicit.
*
* Mirrors the shape of `isBankIdEnabled()` in lib/auth/bankid.ts: self-hosted
* short-circuits first, then the feature's own env var decides.
*/
export const POSTHOG_TOKEN_VAR = 'NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN'
export function isAnalyticsEnabled(): boolean {
if (process.env.NEXT_PUBLIC_SELF_HOSTED === 'true') return false
return Boolean(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN)
}
/**
* A missing token must never break the app, but it must not fail silently
* either: without it every capture is dropped and the integration looks
* healthy while zero events arrive (PostHog's own framework rule). So we warn
* loudly in development and stay a no-op in production.
*
* Returns true when the caller should proceed with initialisation.
*/
export function warnIfAnalyticsMisconfigured(): boolean {
if (isAnalyticsEnabled()) return true
// Self-hosted is a deliberate off, not a misconfiguration: stay quiet.
if (process.env.NEXT_PUBLIC_SELF_HOSTED === 'true') return false
if (process.env.NODE_ENV === 'development') {
// console, not createLogger(): this runs in the browser from
// instrumentation-client.ts before anything else is wired, and the point
// is for a developer to see it in the devtools console immediately.
// eslint-disable-next-line no-console
console.warn(
`${POSTHOG_TOKEN_VAR} variable required by PostHog is missing or un-configured, ` +
`this causes events to be silently missed. This error stops appearing once ` +
`${POSTHOG_TOKEN_VAR} is configured`
)
}
return false
}
+87
View File
@@ -0,0 +1,87 @@
import type { ObservabilityContext, ObservabilityLevel, ObservabilitySink } from '@/lib/observability'
import { getPostHogServer, flushAnalytics } from './posthog-server'
/**
* PostHog adapter for the provider-agnostic observability sink.
*
* Registering this is what makes `lib/observability` stop being a no-op: from
* then on every `error`-level line written through `createLogger()`, plus
* anything flagged `alert: true`, lands in PostHog Error Tracking already
* correlated with the log line's request context. That is far broader
* coverage than the `onRequestError` hook in instrumentation.ts, which only
* sees errors that escape uncaught.
*
* Redaction: `lib/observability/sink.ts` redacts both the error and the
* context before calling an adapter (and the logger has already redacted
* once; redaction is idempotent). This adapter therefore forwards what it is
* given and must never re-widen it by reaching for un-redacted sources.
*
* The interface requires captureException/captureMessage to be SYNCHRONOUS
* and to never throw. posthog-node's capture enqueues synchronously and
* sends afterwards, which fits: `flush()` is the drain the interface asks
* for, and callers on serverless paths await it.
*/
/** PostHog Error Tracking has no severity axis, so level rides as a property. */
function toProperties(
context: ObservabilityContext,
extra?: Record<string, unknown>
): Record<string, unknown> {
return { ...context, ...extra }
}
/**
* `distinct_id` is a reserved context key set by the logger when a request
* has an identified user. Without it PostHog would attribute the event to a
* generated id per event, which fragments the error's person view.
*/
function distinctIdFrom(context: ObservabilityContext): string | undefined {
const raw = context.distinct_id ?? context.user_id ?? context.userId
return typeof raw === 'string' && raw.length > 0 ? raw : undefined
}
export const postHogSink: ObservabilitySink = {
name: 'posthog',
captureException(error: unknown, context: ObservabilityContext): void {
try {
const posthog = getPostHogServer()
if (!posthog) return
posthog.captureException(
error instanceof Error ? error : new Error(String(error)),
distinctIdFrom(context),
toProperties(context)
)
} catch {
// Contract: must not throw.
}
},
captureMessage(message: string, level: ObservabilityLevel, context: ObservabilityContext): void {
try {
const posthog = getPostHogServer()
if (!posthog) return
const distinctId = distinctIdFrom(context)
posthog.capture({
// PostHog requires a distinct id; fall back to a stable server marker
// rather than inventing a per-event id, which would create a new
// person for every log line.
distinctId: distinctId ?? 'server',
event: '$log',
properties: toProperties(context, { message, level }),
})
} catch {
// Contract: must not throw.
}
},
async flush(): Promise<boolean> {
try {
await flushAnalytics()
return true
} catch {
// Contract: must never reject.
return false
}
},
}
+47
View File
@@ -0,0 +1,47 @@
import 'server-only'
import { PostHog } from 'posthog-node'
import { isAnalyticsEnabled } from './enabled'
/**
* Server-side PostHog client (posthog-node).
*
* posthog-js is browser-only, so anything captured from a route handler, a
* server component or the onRequestError hook goes through here.
*
* `flushAt: 1` / `flushInterval: 0` are NOT tuning: Vercel functions are torn
* down per invocation, and the SDK's default batching would let the process
* die before the enqueued event is sent. With these set, every capture sends
* on its own, and callers must still `await flushAnalytics()` before
* returning or the send races the teardown.
*
* Returns null when analytics is off (self-hosted, or no token), so callers
* degrade to a no-op instead of throwing.
*/
let client: PostHog | null = null
export function getPostHogServer(): PostHog | null {
if (!isAnalyticsEnabled()) return null
if (!client) {
client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, {
// Server-side traffic is not ad-blocked, so it talks to PostHog
// directly rather than through the /rl same-origin rewrite (which only
// exists in the browser's Next.js routing anyway). This is the only
// reader of NEXT_PUBLIC_POSTHOG_HOST; the EU default keeps it optional.
host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://eu.i.posthog.com',
flushAt: 1,
flushInterval: 0,
enableExceptionAutocapture: true,
})
}
return client
}
/** Await this before a request handler returns, or the send is dropped. */
export async function flushAnalytics(): Promise<void> {
if (!client) return
try {
await client.flush()
} catch {
// Telemetry must never fail a real request.
}
}
+78
View File
@@ -0,0 +1,78 @@
import type { AccountingFramework, CompanyRole, EntityType } from '@/types'
/**
* Property builders for PostHog identify + group calls.
*
* Pure functions on purpose: the repo's Vitest runs in a `node` environment
* and `vitest.config.ts` only matches `*.test.ts`, so component JSX is
* untestable by convention. Keeping the property shaping here means the part
* that can actually be wrong (what we send about a person and a company) is
* covered by unit tests, while the mounting component stays trivial.
*
* Two rules encoded here, both from PostHog's framework guidance:
*
* 1. PII belongs in identify() PERSON properties, never in capture() event
* properties. Only `buildPersonProperties` carries email/name.
* 2. `org_number` is deliberately NEVER sent. For an enskild firma the
* organisationsnummer IS the owner's personnummer, so it is not a company
* identifier at all: it is a national identity number for a natural
* person. `company_id` is the group key and is already unique.
*/
export interface AnalyticsUserInput {
userId: string
email?: string | null
fullName?: string | null
role?: CompanyRole | null
}
export interface AnalyticsCompanyInput {
id: string
name: string
entityType?: EntityType | null
accountingFramework?: AccountingFramework | null
paysSalaries?: boolean | null
trialEndsAt?: string | null
capabilities?: readonly string[]
}
/** Drop null/undefined so PostHog person properties don't fill with empties. */
function compact(input: Record<string, unknown>): Record<string, unknown> {
return Object.fromEntries(
Object.entries(input).filter(([, value]) => value !== null && value !== undefined)
)
}
/**
* Person properties for `posthog.identify(userId, props)`.
*
* Matches what the privacy policy discloses is transferred: user id, email
* address and company name. Do not widen this without updating
* app/(public)/privacy/page.tsx and .compliance/ropa.yaml.
*/
export function buildPersonProperties(user: AnalyticsUserInput): Record<string, unknown> {
return compact({
email: user.email,
name: user.fullName,
role: user.role,
})
}
/**
* Group properties for `posthog.group('company', companyId, props)`.
*
* Company-shaped facts only: anything that varies per user (role) belongs on
* the person, not the group. No org_number, see the file header.
*/
export function buildGroupProperties(company: AnalyticsCompanyInput): Record<string, unknown> {
return compact({
name: company.name,
entity_type: company.entityType,
accounting_framework: company.accountingFramework,
pays_salaries: company.paysSalaries,
trial_ends_at: company.trialEndsAt,
// Sorted so the same entitlement set doesn't look like a change every
// time the underlying query returns a different order.
capabilities: company.capabilities ? [...company.capabilities].sort() : undefined,
})
}
+27
View File
@@ -0,0 +1,27 @@
import posthog from 'posthog-js'
import { isAnalyticsEnabled } from './enabled'
/**
* Detach the current person from PostHog on logout.
*
* Call this ONLY on the transition out of an identified session, never on an
* initially anonymous page load: reset() discards the anonymous distinct id
* and the history attached to it, so a stray call at boot would sever the
* pre-login part of a signup funnel.
*
* Replaces clearRecaptIdentity() from lib/recapt.ts. That helper also had to
* sweep localStorage by key prefix, because Recapt cached the uid there. We
* run with `persistence: 'memory'`, so there is no cached identity to wipe:
* reset() is sufficient. (Surveys' own `seenSurvey_*` flags are deliberately
* left alone: they carry no identity, only "this browser already saw this
* survey", and clearing them would re-prompt the next person on the device.)
*/
export function resetAnalyticsIdentity(): void {
if (typeof window === 'undefined') return
if (!isAnalyticsEnabled()) return
try {
posthog.reset()
} catch {
// best-effort: we're already in a logout flow
}
}
+10
View File
@@ -4,6 +4,9 @@ import { createExtensionContext } from '@/lib/extensions/context-factory'
import { registerSupplierInvoiceHandler } from '@/lib/bookkeeping/handlers/supplier-invoice-handler'
import { registerEventLogHandler } from '@/lib/events/handlers/event-log-handler'
import { registerWebhookHandler } from '@/lib/webhooks/handler'
import { registerObservabilitySink } from '@/lib/observability'
import { postHogSink } from '@/lib/analytics/posthog-observability'
import { isAnalyticsEnabled } from '@/lib/analytics/enabled'
import { createLogger } from '@/lib/logger'
const log = createLogger('init')
@@ -70,6 +73,13 @@ export function ensureInitialized(): void {
validateEnvironment()
setContextFactory(createExtensionContext)
// Turns lib/observability from a no-op into PostHog Error Tracking. Gated,
// so with no token (core, CI, self-hosted) the sink stays the no-op and
// PostHog is never constructed and never contacted. Note the SDK is still
// BUNDLED in those builds: the imports are static, so the bytes ship even
// though nothing initialises. Making that a true zero would mean dynamic
// imports at every posthog call site, which is a deliberate non-goal here.
if (isAnalyticsEnabled()) registerObservabilitySink(postHogSink)
registerSupplierInvoiceHandler()
registerEventLogHandler()
registerWebhookHandler()