d4f82cafc4
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>
90 lines
3.4 KiB
TypeScript
90 lines
3.4 KiB
TypeScript
import { loadExtensions } from '@/lib/extensions/loader'
|
|
import { setContextFactory } from '@/lib/extensions/registry'
|
|
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')
|
|
|
|
let initialized = false
|
|
|
|
const REQUIRED_CORE_VARS = [
|
|
'NEXT_PUBLIC_SUPABASE_URL',
|
|
'NEXT_PUBLIC_SUPABASE_ANON_KEY',
|
|
'SUPABASE_SERVICE_ROLE_KEY',
|
|
'NEXT_PUBLIC_APP_URL',
|
|
'CRON_SECRET',
|
|
] as const
|
|
|
|
// Each entry is one logical requirement; if multiple names are listed, the
|
|
// requirement is satisfied when ANY of them is set. Mirrors the runtime
|
|
// fallback in extensions/general/enable-banking/lib/jwt.ts (_PRODUCTION ||
|
|
// base) so Vercel prod (which only sets the _PRODUCTION variants) doesn't
|
|
// warn on every cold start.
|
|
const REQUIRED_EXTENSION_VARS: ReadonlyArray<readonly string[]> = [
|
|
['ENABLE_BANKING_APP_ID_PRODUCTION', 'ENABLE_BANKING_APP_ID'],
|
|
['ENABLE_BANKING_PRIVATE_KEY_PRODUCTION', 'ENABLE_BANKING_PRIVATE_KEY'],
|
|
['ANTHROPIC_API_KEY'],
|
|
['OPENAI_API_KEY'],
|
|
] as const
|
|
|
|
function validateEnvironment(): void {
|
|
// During builds (CI, Docker, Vercel), env vars may be absent or set to
|
|
// placeholder sentinels. Skip validation so Next.js page collection
|
|
// doesn't fail: real validation happens at runtime.
|
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
|
if (!supabaseUrl || supabaseUrl.startsWith('__')) return
|
|
|
|
const missing: string[] = []
|
|
|
|
for (const v of REQUIRED_CORE_VARS) {
|
|
if (!process.env[v]) missing.push(v)
|
|
}
|
|
|
|
if (missing.length > 0) {
|
|
throw new Error(`Missing required environment variables: ${missing.join(', ')}`)
|
|
}
|
|
|
|
const missingExt: string[] = []
|
|
for (const aliases of REQUIRED_EXTENSION_VARS) {
|
|
if (!aliases.some((v) => !!process.env[v])) {
|
|
missingExt.push(aliases.join(' or '))
|
|
}
|
|
}
|
|
|
|
if (missingExt.length > 0) {
|
|
log.warn(`Missing extension environment variables (extensions needing them may not work): ${missingExt.join(', ')}`)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Ensure the system is initialized (extensions loaded, context factory wired,
|
|
* core event handlers registered).
|
|
* Called from API routes that emit events.
|
|
* Idempotent: safe to call multiple times.
|
|
*/
|
|
export function ensureInitialized(): void {
|
|
if (initialized) return
|
|
|
|
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()
|
|
loadExtensions()
|
|
|
|
initialized = true
|
|
}
|