fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 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,49 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import crypto from 'crypto'
import { computeIdentityHash } from '../identity-hash'
const USER = '3f7c1d2e-0000-4000-8000-abcdefabcdef'
describe('computeIdentityHash', () => {
afterEach(() => vi.unstubAllEnvs())
it('returns null when the secret is unset (dev / CI / self-hosted)', () => {
vi.stubEnv('POSTHOG_SECRET_API_KEY', '')
expect(computeIdentityHash(USER)).toBeNull()
})
it('returns null for an empty distinct id rather than hashing nothing', () => {
vi.stubEnv('POSTHOG_SECRET_API_KEY', 'phs_secret')
expect(computeIdentityHash('')).toBeNull()
})
it('matches HMAC-SHA256(distinctId, secret) in hex, as PostHog expects', () => {
vi.stubEnv('POSTHOG_SECRET_API_KEY', 'phs_secret')
const expected = crypto.createHmac('sha256', 'phs_secret').update(USER).digest('hex')
expect(computeIdentityHash(USER)).toBe(expected)
expect(computeIdentityHash(USER)).toMatch(/^[a-f0-9]{64}$/)
})
it('is stable across calls for the same user', () => {
vi.stubEnv('POSTHOG_SECRET_API_KEY', 'phs_secret')
expect(computeIdentityHash(USER)).toBe(computeIdentityHash(USER))
})
it('differs per user', () => {
vi.stubEnv('POSTHOG_SECRET_API_KEY', 'phs_secret')
expect(computeIdentityHash(USER)).not.toBe(computeIdentityHash(USER.replace('3f7c', '4a8d')))
})
it('changes when the key is rotated, invalidating old hashes', () => {
vi.stubEnv('POSTHOG_SECRET_API_KEY', 'phs_old')
const before = computeIdentityHash(USER)
vi.stubEnv('POSTHOG_SECRET_API_KEY', 'phs_new')
expect(computeIdentityHash(USER)).not.toBe(before)
})
// The hash crosses to the browser; the key must not be derivable from it.
it('never echoes the secret into its output', () => {
vi.stubEnv('POSTHOG_SECRET_API_KEY', 'phs_supersecretvalue')
expect(computeIdentityHash(USER)).not.toContain('supersecretvalue')
})
})
@@ -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: '[email protected]',
fullName: 'Jakob Wennberg',
role: 'owner',
})
).toEqual({ email: '[email protected]', 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: '[email protected]' })
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' })
})
})
@@ -0,0 +1,99 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { purgeLegacyAnalyticsStorage } from '../purge-legacy-storage'
/** Minimal in-memory Storage stand-in: the suite runs in a node env. */
function makeStorage(initial: Record<string, string> = {}): Storage {
const map = new Map(Object.entries(initial))
return {
get length() {
return map.size
},
key: (i: number) => [...map.keys()][i] ?? null,
getItem: (k: string) => map.get(k) ?? null,
setItem: (k: string, v: string) => void map.set(k, v),
removeItem: (k: string) => void map.delete(k),
clear: () => map.clear(),
} as unknown as Storage
}
function keysOf(s: Storage): string[] {
return Array.from({ length: s.length }, (_, i) => s.key(i)!).sort()
}
describe('purgeLegacyAnalyticsStorage', () => {
afterEach(() => vi.unstubAllGlobals())
it('removes the real key observed in production', () => {
const local = makeStorage({ __recapt_record_engine: 'x' })
vi.stubGlobal('window', { localStorage: local, sessionStorage: makeStorage() })
expect(purgeLegacyAnalyticsStorage()).toBe(1)
expect(keysOf(local)).toEqual([])
})
// The helper this replaces used startsWith('recapt'), which never matched
// `__recapt_record_engine`. Pin the substring behaviour so it cannot regress.
it('matches by substring, not prefix', () => {
const local = makeStorage({
__recapt_record_engine: 'a',
'ph_glimt_session': 'b',
'RECAPT_UPPER': 'c',
})
vi.stubGlobal('window', { localStorage: local, sessionStorage: makeStorage() })
expect(purgeLegacyAnalyticsStorage()).toBe(3)
expect(keysOf(local)).toEqual([])
})
it("leaves the app's own keys alone", () => {
const local = makeStorage({
'Accounted:chat-sidebar-collapsed': '1',
'gnubok.inbox.onboarding.dismissed': '1',
__recapt_record_engine: 'x',
})
vi.stubGlobal('window', { localStorage: local, sessionStorage: makeStorage() })
expect(purgeLegacyAnalyticsStorage()).toBe(1)
expect(keysOf(local)).toEqual([
'Accounted:chat-sidebar-collapsed',
'gnubok.inbox.onboarding.dismissed',
])
})
it('sweeps sessionStorage too', () => {
const session = makeStorage({ glimt_buffer: 'x' })
vi.stubGlobal('window', { localStorage: makeStorage(), sessionStorage: session })
expect(purgeLegacyAnalyticsStorage()).toBe(1)
expect(keysOf(session)).toEqual([])
})
// Backwards iteration matters: removeItem() re-indexes, so a forward loop
// skips the entry after each removal.
it('removes every match even when they are adjacent', () => {
const local = makeStorage({ recapt_a: '1', recapt_b: '2', recapt_c: '3', keep: '4' })
vi.stubGlobal('window', { localStorage: local, sessionStorage: makeStorage() })
expect(purgeLegacyAnalyticsStorage()).toBe(3)
expect(keysOf(local)).toEqual(['keep'])
})
it('is a no-op on a second run', () => {
const local = makeStorage({ __recapt_record_engine: 'x' })
vi.stubGlobal('window', { localStorage: local, sessionStorage: makeStorage() })
purgeLegacyAnalyticsStorage()
expect(purgeLegacyAnalyticsStorage()).toBe(0)
})
it('never throws when storage is unavailable (private mode)', () => {
vi.stubGlobal('window', {
get localStorage(): Storage {
throw new Error('SecurityError')
},
get sessionStorage(): Storage {
throw new Error('SecurityError')
},
})
expect(() => purgeLegacyAnalyticsStorage()).not.toThrow()
})
it('returns 0 on the server', () => {
vi.stubGlobal('window', undefined)
expect(purgeLegacyAnalyticsStorage()).toBe(0)
})
})
@@ -0,0 +1,120 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { maskSensitiveText, replayMaskText } from '@/lib/analytics/replay-masking'
// Repo test convention. eventBus.clear() is deliberately absent: these are
// pure functions and importing the bus would only add module side effects.
beforeEach(() => {
vi.clearAllMocks()
})
/**
* Minimal stand-ins for the DOM elements rrweb hands to the masking
* functions (tests run in the node environment, no jsdom). `closest` is
* called once with the explicit-tag selector and, when that misses, once
* with 'th'; the fake answers each selector like a real DOM lookup would.
*/
function fakeElement(
opts: { tagged?: 'mask' | 'unmask' | 'both' | null; th?: boolean } = {}
): HTMLElement {
const attrs =
opts.tagged === 'mask'
? ['data-ph-mask']
: opts.tagged === 'unmask'
? ['data-ph-unmask']
: opts.tagged === 'both'
? ['data-ph-mask', 'data-ph-unmask']
: null
const tagged = attrs ? { hasAttribute: (name: string) => attrs.includes(name) } : null
const thAncestor = opts.th ? { hasAttribute: () => false } : null
return {
closest: (selector: string) => (selector.includes('data-ph') ? tagged : thAncestor),
} as unknown as HTMLElement
}
describe('maskSensitiveText', () => {
it('masks sv-SE formatted amounts, preserving length and whitespace', () => {
// First variant groups thousands with U+00A0 (what Intl sv-SE emits), the second with a regular space.
expect(maskSensitiveText('1 234,56 kr')).toBe('* ****** **')
expect(maskSensitiveText('1 234,56 kr')).toBe('* ****** **')
})
it('masks negative amounts with both hyphen and the Intl minus sign', () => {
expect(maskSensitiveText('-500 kr')).toBe('**** **')
expect(maskSensitiveText('−1 234 kr')).toBe('** *** **')
})
it('masks the amount inside surrounding text', () => {
expect(maskSensitiveText('Totalt 1 234 kr att betala')).toBe('Totalt * *** ** att betala')
expect(maskSensitiveText('999 kr/mån')).toBe('*** **/mån')
})
it('masks other currency markers', () => {
expect(maskSensitiveText('12,00 €')).toBe('***** *')
expect(maskSensitiveText('10 US$')).toBe('** ***')
expect(maskSensitiveText('1 000 SEK')).toBe('* *** ***')
})
it('masks person- and organisationsnummer', () => {
expect(maskSensitiveText('556677-8899')).toBe('***********')
expect(maskSensitiveText('19850101-1234')).toBe('*************')
expect(maskSensitiveText('850101+1234')).toBe('***********')
})
it('leaves non-amount, non-identity text untouched', () => {
for (const text of [
'2026-08-06',
'Verifikat A-217',
'070-123 45 67',
'5050-1055',
'[email protected]',
'10 kronor',
'E-postadress',
'Konto 1930',
]) {
expect(maskSensitiveText(text)).toBe(text)
}
})
})
describe('replayMaskText', () => {
it('masks everything when the node has no chrome ancestor', () => {
expect(replayMaskText('Acme AB', fakeElement())).toBe('**** **')
expect(replayMaskText('Kaffe till kontoret', fakeElement())).toBe('***** **** ********')
expect(replayMaskText('Acme AB', undefined)).toBe('**** **')
})
it('masks everything when rrweb passes an element without closest (text node parents can be non-Element)', () => {
expect(replayMaskText('Acme AB', {} as unknown as HTMLElement)).toBe('**** **')
})
it('shows chrome text under data-ph-unmask', () => {
expect(replayMaskText('Bokför och godkänn', fakeElement({ tagged: 'unmask' }))).toBe(
'Bokför och godkänn'
)
})
it('shows table column headers (th) without a tag', () => {
expect(replayMaskText('Datum', fakeElement({ th: true }))).toBe('Datum')
})
it('lets an explicit data-ph-mask beat the th fallback (th inside a masked container, or masked th)', () => {
expect(replayMaskText('Acme AB', fakeElement({ tagged: 'mask', th: true }))).toBe('**** **')
})
it('pattern-scrubs amounts and identity numbers even inside chrome', () => {
expect(replayMaskText('Betala 1 234 kr nu', fakeElement({ tagged: 'unmask' }))).toBe(
'Betala * *** ** nu'
)
expect(replayMaskText('Ta bort 556677-8899', fakeElement({ tagged: 'unmask' }))).toBe(
'Ta bort ***********'
)
})
it('masks everything under data-ph-mask', () => {
expect(replayMaskText('Acme AB', fakeElement({ tagged: 'mask' }))).toBe('**** **')
})
it('lets mask win when both attributes land on the same element', () => {
expect(replayMaskText('Acme AB', fakeElement({ tagged: 'both' }))).toBe('**** **')
})
})
+50
View File
@@ -0,0 +1,50 @@
/**
* 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.
*/
import { isSelfHosted } from '@/lib/env/public-flags'
export const POSTHOG_TOKEN_VAR = 'NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN'
export function isAnalyticsEnabled(): boolean {
if (isSelfHosted()) 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 (isSelfHosted()) 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
}
+26
View File
@@ -0,0 +1,26 @@
import 'server-only'
import crypto from 'crypto'
/**
* HMAC identity verification for PostHog Support (conversations).
*
* Without it, a support ticket is scoped to one browser session: the user
* loses the thread when they switch device, and recovery is by email link.
* With it, PostHog trusts that this browser really is `distinctId`, so the
* thread follows the person.
*
* The hash MUST be computed server-side. `POSTHOG_SECRET_API_KEY` is a real
* secret (it also authenticates external API requests), so it is deliberately
* NOT `NEXT_PUBLIC_`: it must never reach the client bundle. Only the derived
* hash crosses to the browser, which is safe because it is per-user and
* useless without the key.
*
* Returns null when the key is unset, which is the normal state for local
* dev, CI and self-hosted. Callers degrade to unverified (browser-scoped)
* tickets rather than failing.
*/
export function computeIdentityHash(distinctId: string): string | null {
const secret = process.env.POSTHOG_SECRET_API_KEY
if (!secret || !distinctId) return null
return crypto.createHmac('sha256', secret).update(distinctId).digest('hex')
}
+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,
})
}
+55
View File
@@ -0,0 +1,55 @@
/**
* One-time cleanup of storage left behind by Recapt.
*
* Removing the Recapt <script> stops it writing anything NEW, but every
* browser that has already loaded the app keeps whatever Recapt persisted:
* observed in production as `__recapt_record_engine` in localStorage. Nothing
* would ever remove it, because the helper that used to sweep on logout
* (lib/recapt.ts `clearRecaptIdentity`) is deleted along with the SDK.
*
* That leftover is inert, but it is third-party storage from a processor we
* have told users we no longer use (app/(public)/privacy/page.tsx), and this
* app's whole analytics posture is "nothing on the device". So we clear it.
*
* Matching is by SUBSTRING, not prefix, on purpose. The old sweep tested
* `key.startsWith('recapt')`, which never actually matched the real key:
* `__recapt_record_engine` starts with underscores. The app's own keys
* (`Accounted:chat-sidebar-collapsed`, `gnubok.inbox.onboarding.dismissed`)
* contain neither token, so there is nothing to collide with.
*
* Safe to call on every load: once the keys are gone the loop finds nothing
* and the whole thing costs one localStorage.length read.
*/
const LEGACY_MARKERS = ['recapt', 'glimt']
function purgeFrom(store: Storage): number {
let removed = 0
// Iterate backwards: removeItem() re-indexes the store, so a forward loop
// skips the entry after each removal.
for (let i = store.length - 1; i >= 0; i--) {
const key = store.key(i)
if (!key) continue
const lower = key.toLowerCase()
if (LEGACY_MARKERS.some((m) => lower.includes(m))) {
store.removeItem(key)
removed++
}
}
return removed
}
export function purgeLegacyAnalyticsStorage(): number {
if (typeof window === 'undefined') return 0
let removed = 0
try {
removed += purgeFrom(window.localStorage)
} catch {
// Storage can throw in private mode / when disabled: never break boot.
}
try {
removed += purgeFrom(window.sessionStorage)
} catch {
// Same.
}
return removed
}
+101
View File
@@ -0,0 +1,101 @@
/**
* Deny-by-default masking for PostHog session replay.
*
* Everything is masked unless it is app chrome (founder-approved 2026-08-17,
* supersedes the 2026-08-06 pattern-based default where user content was
* visible). Replays show layout, clicks and static UI text: headers, nav,
* form labels, placeholders, buttons. They never show user data: not what a
* user typed (input values are masked wholesale by rrweb, see
* instrumentation-client.ts) and not user content rendered as text
* (counterparty names, descriptions, amounts, identity numbers).
*
* What counts as chrome, i.e. renders readable in a replay:
* - Any subtree tagged `data-ph-unmask`. Tags live on the shared UI
* primitives (nav, PageHeader, Label, Button, tabs, dialog/sheet titles,
* card titles, badges, tooltips, empty states), so page code gets readable
* chrome without per-page tagging.
* - `<th>` elements with NO explicit tag anywhere above them: table column
* headers are static chrome, but the page-level dry-table pattern writes
* raw `<th className={TH_CLASS}>` per page, so there is no shared
* component to tag. An explicit data-ph-mask (on the th or any ancestor)
* always wins over this fallback.
*
* Chrome is still pattern-scrubbed (belt and braces): an i18n string that
* interpolates an amount or a person-/organisationsnummer into a title or
* button label gets that span masked even inside an unmasked subtree.
*
* `data-ph-mask` force-masks a subtree and wins over `data-ph-unmask`: the
* NEAREST tagged ancestor decides, and mask wins when both attributes land
* on the same element. Use it where user data flows into a chrome primitive
* (e.g. a Label interpolating the user's email, a dialog title carrying a
* counterparty name).
*
* Untagged text is fully masked, so the failure mode for new UI is
* over-masking (asterisks where chrome should be readable), never leaking
* a user's books.
*
* Known limit: rrweb masks text nodes and input values, not ATTRIBUTES.
* posthog-js exposes no attribute mask hook, so a title/aria-label/
* placeholder attribute is recorded as-is. An element whose attributes
* carry user data (e.g. a placeholder prefilled with an effective value)
* must carry the `ph-no-capture` class instead: rrweb's blockClass removes
* the whole element from the recording while the app UX is untouched. Do
* not put user data in title or aria-label attributes.
*/
/**
* Currency-shaped text: optional sign (Intl sv-SE renders negative amounts
* with U+2212, hand-written strings use '-'), digits with space/nbsp grouping
* and a decimal part, then a currency marker. The trailing lookahead rejects
* letter continuations so "10 kronor" or "SEKTION" never match.
*/
const AMOUNT_PATTERN = new RegExp(
// − is the Unicode minus sign Intl sv-SE emits for negative amounts.
String.raw`[-−]?\d(?:[\d\s]|[.,](?=\d))*\s?(?:kr|sek|eur|usd|nok|dkk|gbp|chf|us\$|\$|€|£)(?![\p{L}\d])`,
'giu',
)
/**
* Person-/organisationsnummer rendered as text: 6 or 8 digits, separator,
* 4 digits ("556677-8899", "19850101-1234", "850101+1234"). The digit
* lookarounds keep bankgiro ("5050-1055"), phone numbers and dates out.
*/
const IDENTITY_TEXT_PATTERN = /(?<!\d)\d{6}(?:\d{2})?[-+]\d{4}(?!\d)/g
const TAG_SELECTOR = '[data-ph-mask],[data-ph-unmask]'
/** Length-preserving mask: whitespace survives so table layout stays legible. */
function maskAll(text: string): string {
return text.replace(/\S/g, '*')
}
function maskSpan(span: string): string {
return maskAll(span)
}
/**
* Masks currency amounts and separator-formatted identity numbers inside a
* text node, leaving the surrounding text readable. Applied to CHROME text:
* non-chrome text never gets here, it is masked wholesale.
*/
export function maskSensitiveText(text: string): string {
return text.replace(AMOUNT_PATTERN, maskSpan).replace(IDENTITY_TEXT_PATTERN, maskSpan)
}
/**
* `session_recording.maskTextFn`. Runs on EVERY text node because
* `maskTextSelector: '*'` flags them all; this function then decides.
* Default is masked; only chrome shows through, and even chrome is
* pattern-scrubbed.
*
* Explicit tags are resolved FIRST, and only then the th fallback: a single
* closest() over tags-plus-th would let a th nested inside a data-ph-mask
* container win on DOM proximity and unmask it.
*/
export function replayMaskText(text: string, element?: HTMLElement): string {
const tagged = element?.closest?.(TAG_SELECTOR)
if (tagged) {
return tagged.hasAttribute('data-ph-mask') ? maskAll(text) : maskSensitiveText(text)
}
return element?.closest?.('th') ? maskSensitiveText(text) : maskAll(text)
}
+37
View File
@@ -0,0 +1,37 @@
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.
*
* This call is load-bearing for shared devices, not just tidiness.
* `posthog.reset()` also resets the conversations manager, which removes the
* `ph_conv_<token>` key holding the support-ticket session id. Without it the
* next person at the same browser would inherit the previous user's ticket
* session. Do not "optimise" this away when analytics is otherwise quiet.
*
* What it does NOT clear: `seenSurvey_<id>`. No PostHog bundle enumerates
* localStorage, so the SDK cannot find those keys to delete them. That is
* accepted, and desirable: clearing them would re-prompt every survey to the
* next person on the device. See the client-side storage inventory in
* .compliance/Data_Classification_Handling.md.
*/
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
}
}