Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M9-004): DELETE the V1 Fastify boot: apps/api/src/index.ts + app.ts retire, main.ts is the only entrypoint

ralphb1843cd04357
diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile
index cf6ddd9da..94ec29b25 100644
--- a/apps/api/Dockerfile
+++ b/apps/api/Dockerfile
@@ -21,10 +21,12 @@ RUN corepack enable && apt-get update && \
&& apt-get clean && \
rm -rf /var/lib/apt/lists/*
-# M9-003 deleted apps/worker: this image is now BOTH halves of the stack. The
-# V1 Fastify api still runs on node from `dist/`; `ROLE=worker` runs V2's
-# `src/main.ts` from source on Bun (ADR-001: "ROLE=worker moves when
-# apps/worker is deleted at P9"). Collapsing the two boots into one is P9.5.
+# M9-003 deleted apps/worker and M9-004 deleted the V1 Fastify boot: this image
+# is now ONE process in three shapes, `bun run src/main.ts` under
+# ROLE=api|worker|all, running from source with no bundle (ADR-010). The node
+# base layer stays only because `pnpm`, `pnpm codegen` and `pnpm rebuild` run in
+# it; making the image bun-only is P9.5's "one image" step, with the measured
+# before/after it owes.
COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun
ARG DATABASE_URL
@@ -68,8 +70,9 @@ COPY apps/api ./apps/api
COPY packages ./packages
COPY tooling ./tooling
-RUN pnpm codegen && \
- pnpm --filter api run build
+# No build step: ADR-010 deleted the backend bundler with the V1 boot, so the
+# only thing this stage produces is the generated Prisma client.
+RUN pnpm codegen
# PROD
FROM base AS prod
@@ -99,7 +102,7 @@ WORKDIR /app
COPY --from=build /app/package.json ./
COPY --from=prod /app/node_modules ./node_modules
-# Apps — src/ travels too, not just dist/: ROLE=worker runs src/main.ts.
+# Apps — src/ is the artifact now; there is no dist/.
COPY --from=build /app/apps/api ./apps/api
# Packages
@@ -119,20 +122,10 @@ RUN pnpm db:codegen
WORKDIR /app/apps/api
-# Drop a diagnostic report on fatal errors / SIGUSR2 so the next native
-# segfault (exit 139) leaves a stack we can read. Override per-environment
-# by setting NODE_OPTIONS in the swarm stack file. Bun ignores these flags.
-ENV NODE_OPTIONS="--report-on-fatalerror --report-on-signal --report-directory=/tmp"
-
EXPOSE 3000
-# ROLE picks the half. `api` (or unset) keeps V1's Fastify boot byte-for-byte;
-# `worker` and `all` run V2's merged process, which validates the rest of its
-# configuration itself (apps/api/src/config/env.ts). An unknown ROLE fails
-# here rather than silently starting an api: under V1's entrypoint ROLE is not
-# read at all, so a typo would otherwise look like a healthy container that
-# consumes nothing.
-#
-# `all` serves the ops surface only until M9-004 mounts publicApiRoutes /
-# dashboardRoutes on V2 — do not point production traffic at it before then.
-CMD ["sh", "-c", "case \"${ROLE:-api}\" in api) exec node dist/index.js ;; worker|all) exec bun run src/main.ts ;; *) echo \"ROLE=$ROLE is not one of: api, worker, all\" >&2; exit 1 ;; esac"]
+# ROLE picks the shape: `api` (or unset) serves HTTP only, `worker` consumes
+# only, `all` does both. `config/env.ts` validates it and fails boot loudly on
+# an unknown value, which is why this line no longer has a case statement of
+# its own.
+CMD ["bun", "run", "src/main.ts"]
diff --git a/apps/api/e2e/legacy-job-proof.ts b/apps/api/e2e/legacy-job-proof.ts
index f52ecbbd2..fb4100b47 100644
--- a/apps/api/e2e/legacy-job-proof.ts
+++ b/apps/api/e2e/legacy-job-proof.ts
@@ -280,10 +280,10 @@ async function main() {
});
const deps: AppDeps = {
- db: undefined,
- ch: undefined,
- redis: undefined,
- clients: undefined,
+ db: undefined as unknown as AppDeps['db'],
+ ch: undefined as unknown as AppDeps['ch'],
+ redis: undefined as unknown as AppDeps['redis'],
+ clients: undefined as unknown as AppDeps['clients'],
buffers,
producers,
produceIncomingEvent,
diff --git a/apps/api/package.json b/apps/api/package.json
index 705822656..4a7ea4ed3 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -3,11 +3,10 @@
"version": "0.0.4",
"type": "module",
"scripts": {
- "dev": "dotenv -e ../../.env -c -v WATCH=1 tsdown",
+ "dev": "ROLE=all dotenv -e ../../.env -- bun --watch src/main.ts",
"testing": "API_PORT=3333 pnpm dev",
"dev:worker": "ROLE=worker dotenv -e ../../.env -- bun --watch src/main.ts",
- "start": "dotenv -e ../../.env node dist/index.js",
- "build": "rm -rf dist && tsdown",
+ "start": "bun run src/main.ts",
"test:manage": "jiti scripts/test-manage-api.ts",
"e2e:sessions": "LOG_LEVEL=warn dotenv -e ../../.env -- jiti e2e/session-e2e.ts",
"e2e:sessions:stress": "LOG_LEVEL=warn dotenv -e ../../.env -- jiti e2e/session-stress.ts",
@@ -17,56 +16,23 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
- "@better-agent/adapters": "^0.1.0-beta.3",
- "@better-agent/core": "^0.1.0-beta.3",
- "@fastify/compress": "^8.1.0",
- "@fastify/cookie": "^11.0.2",
- "@fastify/cors": "^11.1.0",
- "@fastify/rate-limit": "^10.3.0",
- "@fastify/swagger": "^9.7.0",
- "@fastify/swagger-ui": "^5.2.5",
- "@fastify/websocket": "^11.2.0",
- "@hyperdx/node-opentelemetry": "catalog:",
- "@node-rs/argon2": "^2.0.2",
"@openpanel/common": "workspace:*",
- "@openpanel/constants": "workspace:*",
"@openpanel/core": "workspace:*",
"@openpanel/db": "workspace:*",
- "@openpanel/json": "workspace:*",
- "@openpanel/payments": "workspace:*",
"@openpanel/queue": "workspace:*",
"@openpanel/redis": "workspace:*",
"@openpanel/trpc": "workspace:*",
- "@openpanel/validation": "workspace:*",
- "@trpc/server": "^11.17.0",
- "fast-json-stable-hash": "^1.0.3",
- "fastify": "^5.8.5",
- "fastify-metrics": "^12.1.0",
- "fastify-raw-body": "^5.0.0",
- "fastify-zod-openapi": "^5.6.1",
+ "elysia": "1.4.30",
"pino": "catalog:",
"pino-pretty": "catalog:",
- "prom-client": "^15.1.3",
- "ramda": "^0.29.1",
- "sharp": "^0.33.5",
- "source-map-support": "^0.5.21",
"uuid": "^9.0.1",
"zod": "catalog:"
},
"devDependencies": {
"@faker-js/faker": "^9.0.1",
"@openpanel/tsconfig": "workspace:*",
- "@types/ramda": "^0.30.2",
- "@types/source-map-support": "^0.5.10",
"@types/uuid": "^10.0.0",
- "@types/ws": "^8.5.14",
- "tsdown": "0.14.2",
"typescript": "catalog:",
"vitest": "^1.0.0"
- },
- "peerDependencies": {
- "@aws-sdk/client-s3": "^3.974.0",
- "@aws-sdk/client-sts": "^3.974.0",
- "@google-cloud/storage": "^7.18.0"
}
}
diff --git a/apps/api/src/agents/app.ts b/apps/api/src/agents/app.ts
deleted file mode 100644
index cc02818e8..000000000
--- a/apps/api/src/agents/app.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-// Dissolved into @openpanel/core's assistant module (M5-005): the Better
-// Agent app definition (one agent per allowed model, the Prisma-backed
-// conversation store, the titler agent) moved to
-// packages/core/src/modules/assistant/src/app.ts. This file stays
-// (DELEGATE PATTERN) — apps/api/src/app.ts is the live Fastify route and
-// keeps calling `getChatApp()` from here unchanged.
-//
-// `getChatApp` is a lazy accessor, not a plain value export — see
-// @openpanel/core's index.ts for why a static import here would race
-// @openpanel/db's own circular buffers/base-buffer.ts import.
-export { type ChatApp, getChatApp } from '@openpanel/core';
diff --git a/apps/api/src/agents/run-context.ts b/apps/api/src/agents/run-context.ts
deleted file mode 100644
index eb58dfb66..000000000
--- a/apps/api/src/agents/run-context.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-// Dissolved into @openpanel/core's assistant module (M5-005): the
-// AsyncLocalStorage carrying per-request chat context moved to
-// packages/core/src/modules/assistant/src/run-context.ts. This file stays
-// (DELEGATE PATTERN) — apps/api/src/app.ts wraps the live `/ai/agents/*`
-// handler in `chatRunContext.run(...)`, and the core-side persistence store
-// reads the SAME singleton (resolved once via `getChatRunContext()`, see
-// @openpanel/core's index.ts for why it is a lazy accessor rather than a
-// plain value export).
-export { type ChatRunContext, getChatRunContext } from '@openpanel/core';
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
deleted file mode 100644
index a4f5ccde9..000000000
--- a/apps/api/src/app.ts
+++ /dev/null
@@ -1,463 +0,0 @@
-/** biome-ignore-all lint/suspicious/useAwait: fastify need async or done callbacks */
-
-import { toFastifyHandler } from '@better-agent/adapters';
-import compress from '@fastify/compress';
-import cookie from '@fastify/cookie';
-import cors, { type FastifyCorsOptions } from '@fastify/cors';
-import fastifySwagger from '@fastify/swagger';
-import fastifySwaggerUI from '@fastify/swagger-ui';
-import { generateId } from '@openpanel/common';
-import { decodeSessionToken, getTrustedIpFromHeaders } from '@openpanel/core';
-import {
- EMPTY_SESSION,
- getConversationById,
- getOrganizationByProjectIdCached,
- getProjectAccess,
- getSettingsForProject,
- type IServiceClientWithProject,
- runWithAlsSession,
- type SessionValidationResult,
- validateSessionToken,
-} from '@openpanel/db';
-import type { AppRouter } from '@openpanel/trpc';
-import { appRouter, createContext } from '@openpanel/trpc';
-import type { FastifyTRPCPluginOptions } from '@trpc/server/adapters/fastify';
-import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
-import type {
- FastifyBaseLogger,
- FastifyInstance,
- FastifyRequest,
-} from 'fastify';
-import Fastify from 'fastify';
-import metricsPlugin from 'fastify-metrics';
-import {
- fastifyZodOpenApiPlugin,
- fastifyZodOpenApiTransformers,
- serializerCompiler,
- validatorCompiler,
-} from 'fastify-zod-openapi';
-import { getChatApp } from './agents/app';
-import { getChatRunContext } from './agents/run-context';
-import {
- healthcheck,
- liveness,
- readiness,
-} from './controllers/healthcheck.controller';
-import { ipHook } from './hooks/ip.hook';
-import { requestIdHook } from './hooks/request-id.hook';
-import { requestLoggingHook } from './hooks/request-logging.hook';
-import { timestampHook } from './hooks/timestamp.hook';
-import eventRouter from './routes/event.router';
-import exportRouter from './routes/export.router';
-import gscCallbackRouter from './routes/gsc-callback.router';
-import importRouter from './routes/import.router';
-import insightsRouter from './routes/insights.router';
-import liveRouter from './routes/live.router';
-import manageRouter from './routes/manage.router';
-import mcpRouter from './routes/mcp.router';
-import miscRouter from './routes/misc.router';
-import oauthRouter from './routes/oauth-callback.router';
-import profileRouter from './routes/profile.router';
-import toolsRouter from './routes/tools.router';
-import trackRouter from './routes/track.router';
-import webhookRouter from './routes/webhook.router';
-import { HttpError, normalizeError } from './utils/errors';
-import { logger } from './utils/logger';
-
-declare module 'fastify' {
- interface FastifyRequest {
- client: IServiceClientWithProject | null;
- clientSecretAuth?: boolean;
- clientIp: string;
- clientIpHeader: string;
- timestamp?: number;
- session: SessionValidationResult;
- }
-}
-
-export interface BuildAppOptions {
- /** Set to true when running under Vitest — disables logging and Prometheus metrics */
- testing?: boolean;
-}
-
-export async function buildApp(
- options: BuildAppOptions = {}
-): Promise<FastifyInstance> {
- const { testing = false } = options;
-
- const fastify = Fastify({
- maxParamLength: 15_000,
- bodyLimit: 1_048_576 * 500,
- disableRequestLogging: true,
- genReqId: (req) =>
- req.headers['request-id']
- ? String(req.headers['request-id'])
- : generateId(),
- ...(testing
- ? { logger: false }
- : { loggerInstance: logger as FastifyBaseLogger }),
- });
-
- fastify.setValidatorCompiler(validatorCompiler);
- fastify.setSerializerCompiler(serializerCompiler);
-
- // Env is read once at startup — changing CORS origins requires a
- // restart, which is already true for every other env-driven piece
- // of the server.
- const dashboardOrigins = [
- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL,
- ...(process.env.API_CORS_ORIGINS?.split(',') ?? []),
- ].filter(Boolean) as string[];
- const corsPaths = ['/trpc', '/live', '/webhook', '/oauth', '/misc', '/ai'];
-
- fastify.register(cors, () => {
- return (
- req: FastifyRequest,
- callback: (error: Error | null, options: FastifyCorsOptions) => void
- ) => {
- const isPrivatePath = corsPaths.some((p) => req.url.startsWith(p));
-
- if (isPrivatePath) {
- const origin = req.headers.origin;
- const isAllowed = origin && dashboardOrigins.includes(origin);
- return callback(null, {
- origin: isAllowed ? origin : false,
- credentials: true,
- });
- }
-
- return callback(null, { origin: '*', maxAge: 86_400 * 7 });
- };
- });
-
- await fastify.register(import('fastify-raw-body'), { global: false });
-
- fastify.addHook('onRequest', requestIdHook);
- fastify.addHook('onRequest', timestampHook);
- fastify.addHook('onRequest', ipHook);
- fastify.addHook('onResponse', requestLoggingHook);
-
- fastify.register(compress, { global: false, encodings: ['gzip', 'deflate'] });
-
- // Dashboard API
- fastify.register(async (instance) => {
- instance.register(cookie, {
- secret: process.env.COOKIE_SECRET ?? '',
- hook: 'onRequest',
- parseOptions: {},
- });
-
- instance.addHook('onRequest', async (req) => {
- if (req.cookies?.session) {
- try {
- const sessionId = decodeSessionToken(req.cookies?.session);
- const session = await runWithAlsSession(sessionId, () =>
- validateSessionToken(req.cookies.session)
- );
- req.session = session;
- } catch {
- req.session = EMPTY_SESSION;
- }
- } else if (process.env.DEMO_USER_ID) {
- try {
- const session = await runWithAlsSession('1', () =>
- validateSessionToken(null)
- );
- req.session = session;
- } catch {
- req.session = EMPTY_SESSION;
- }
- } else {
- req.session = EMPTY_SESSION;
- }
- });
-
- instance.register(fastifyTRPCPlugin, {
- prefix: '/trpc',
- trpcOptions: {
- router: appRouter,
- createContext,
- onError(ctx) {
- if (
- ctx.error.code === 'UNAUTHORIZED' &&
- ctx.path === 'organization.list'
- ) {
- return;
- }
-
- // The IP is resolved from trusted headers only (see
- // `getTrustedIpFromHeaders`), so it is the address to hand to
- // Cloudflare when an abuser needs blocking at the edge.
- const { ip, header } = getTrustedIpFromHeaders(
- ctx.req.headers,
- ctx.req.socket?.remoteAddress
- );
- const payload = {
- err: ctx.error,
- path: ctx.path,
- input: ctx.input,
- type: ctx.type,
- session: ctx.ctx?.session,
- ip,
- ipHeader: header,
- userAgent: ctx.req.headers['user-agent'],
- };
-
- // Being rate limited is the system working, not an error - logging it
- // as one buried the real errors under 15k lines a day.
- if (ctx.error.code === 'TOO_MANY_REQUESTS') {
- ctx.req.log.warn(payload, 'trpc rate limited');
- return;
- }
-
- ctx.req.log.error(payload, 'trpc error');
- },
- } satisfies FastifyTRPCPluginOptions<AppRouter>['trpcOptions'],
- });
-
- instance.register(liveRouter, { prefix: '/live' });
- instance.register(webhookRouter, { prefix: '/webhook' });
- instance.register(oauthRouter, { prefix: '/oauth' });
- instance.register(gscCallbackRouter, { prefix: '/gsc' });
- instance.register(miscRouter, { prefix: '/misc' });
- // Better Agent chat, mounted under /ai/agents/*.
- //
- // The wrapper does three things before delegating to the Better
- // Agent handler:
- // 1. Sets CORS headers on `reply.raw` (survives `reply.hijack()`
- // which bypasses @fastify/cors's onSend hook)
- // 2. Validates the session + project access (the user-visible
- // POST /run body carries `context.projectId` +
- // `context.organizationId`)
- // 3. Wraps the handler call in `chatRunContext.run(...)` so the
- // Prisma conversation-store can upsert the `Conversation`
- // row with the right owner on first save
- //
- // Preflight OPTIONS is handled by @fastify/cors before this route
- // runs, so we only skip auth/ALS for that case.
- {
- const chatApp = await getChatApp();
- const chatRunContext = await getChatRunContext();
- const agentHandler = toFastifyHandler(chatApp);
-
- instance.all('/ai/agents/*', async (request, reply) => {
- const origin = request.headers.origin;
- if (origin && dashboardOrigins.includes(origin)) {
- reply.raw.setHeader('Access-Control-Allow-Origin', origin);
- reply.raw.setHeader('Access-Control-Allow-Credentials', 'true');
- reply.raw.setHeader('Vary', 'Origin');
- }
-
- // OPTIONS preflight is already handled by @fastify/cors.
- if (request.method === 'OPTIONS') {
- return agentHandler(request, reply);
- }
-
- const userId = request.session?.session?.userId;
- if (!userId) {
- return reply.status(401).send({ message: 'Sign in required' });
- }
-
- // Parse the URL tail that comes after `/ai/agents/`.
- // Examples:
- // "claude-sonnet-4-5/run" → run
- // "claude-sonnet-4-5/conversations/abc" → load conversation
- // "__titler/run" → title stream (no project context)
- const wildcard = (request.params as { '*'?: string })['*'] ?? '';
- const segments = wildcard.split('/').filter(Boolean);
- const agentName = segments[0] ?? '';
- const route = segments[1] ?? '';
- const routeId = segments[2] ?? '';
-
- // The internal `__titler` agent has no project context — skip
- // the access check; session auth is enough.
- if (agentName === '__titler') {
- return agentHandler(request, reply);
- }
-
- // Conversation hydration: `GET /:name/conversations/:id` and
- // `GET /:name/conversations/:id/resume`. If the row exists,
- // verify ownership. If it doesn't exist yet (brand-new chat
- // the client is opening for the first time), let the agent
- // handler respond — its ConversationStore.load() returns null
- // and the adapter maps that to a 204, which Better Agent's
- // client treats as "no saved history". Returning 404 here
- // would instead put `useAgent` in an error state and block
- // the first send.
- if (route === 'conversations' && routeId) {
- const conv = await getConversationById(routeId);
- if (conv && conv.userId !== userId) {
- return reply
- .status(404)
- .send({ message: 'Conversation not found' });
- }
- return agentHandler(request, reply);
- }
-
- // Everything else (primarily `POST /:name/run`) is an active
- // run and must carry `context.projectId` + `context.organizationId`.
- const body = request.body as
- | { context?: { projectId?: string; organizationId?: string } }
- | null
- | undefined;
- const projectId = body?.context?.projectId;
- const organizationIdFromBody = body?.context?.organizationId;
-
- if (!(projectId && organizationIdFromBody)) {
- return reply.status(400).send({
- message: 'Missing projectId or organizationId in context',
- });
- }
-
- const [access, organization, settings] = await Promise.all([
- getProjectAccess({ projectId, userId }),
- getOrganizationByProjectIdCached(projectId),
- // Fetch the project's timezone up front so the tools +
- // prompt builder can resolve range presets ("6m", "7d", …)
- // into concrete dates without an async lookup per call.
- // Falls back to UTC on any error — preset resolution then
- // still works, just in UTC instead of the user's zone.
- getSettingsForProject(projectId).catch(() => ({ timezone: 'UTC' })),
- ]);
- if (
- !(access && organization) ||
- organization.id !== organizationIdFromBody
- ) {
- return reply
- .status(403)
- .send({ message: 'No access to this project' });
- }
-
- // The conversation row is created lazily: the agent's
- // `ConversationStore.save()` upserts on first save, and the
- // TRPC `conversation.rename` endpoint upserts when the titler
- // finishes first. Either path ends up with the correct owner
- // — no eager upsert needed here.
-
- return chatRunContext.run(
- {
- userId,
- projectId,
- organizationId: organization.id,
- timezone: settings.timezone || 'UTC',
- },
- () => agentHandler(request, reply)
- );
- });
- }
- instance.register(mcpRouter, { prefix: '/mcp' });
- });
-
- // Public API
- fastify.register(async (instance) => {
- await instance.register(fastifyZodOpenApiPlugin);
- await instance.register(fastifySwagger, {
- openapi: {
- info: { title: 'OpenPanel API', version: '1.0.0' },
- openapi: '3.1.0',
- tags: [
- { name: 'Track', description: 'Track events and sessions' },
- { name: 'Profile', description: 'Identify and update user profiles' },
- { name: 'Export', description: 'Export data' },
- { name: 'Import', description: 'Import historical data' },
- { name: 'Insights', description: 'Query analytics data' },
- { name: 'Manage', description: 'Manage projects and clients' },
- {
- name: 'Event',
- description: 'Legacy event ingestion (deprecated, use /track)',
- },
- ],
- },
- ...fastifyZodOpenApiTransformers,
- transform(args) {
- if (args.url === '/metrics') {
- return { schema: { ...args.schema, hide: true }, url: args.url };
- }
- return fastifyZodOpenApiTransformers.transform(args);
- },
- });
- await instance.register(fastifySwaggerUI, {
- routePrefix: '/documentation',
- });
-
- // Prometheus metrics: skip in tests (causes global state conflicts across test runs)
- if (!testing) {
- instance.register(metricsPlugin, { endpoint: '/metrics' });
- }
-
- instance.register(eventRouter, { prefix: '/event' });
- instance.register(profileRouter, { prefix: '/profile' });
- instance.register(exportRouter, { prefix: '/export' });
- instance.register(importRouter, { prefix: '/import' });
- instance.register(insightsRouter, { prefix: '/insights' });
- instance.register(trackRouter, { prefix: '/track' });
- instance.register(manageRouter, { prefix: '/manage' });
- instance.register(toolsRouter, { prefix: '/tools' });
-
- instance.get('/healthcheck', { schema: { hide: true } }, healthcheck);
- instance.get('/healthz/live', { schema: { hide: true } }, liveness);
- instance.get('/healthz/ready', { schema: { hide: true } }, readiness);
- instance.get('/', { schema: { hide: true } }, (_request, reply) =>
- reply.send({
- status: 'ok',
- message: 'Successfully running OpenPanel.dev API',
- })
- );
- });
-
- const SKIP_LOG_ERRORS = [
- 'UNAUTHORIZED',
- 'FORBIDDEN',
- 'FST_ERR_CTP_INVALID_MEDIA_TYPE',
- ];
- fastify.setErrorHandler((error, request, reply) => {
- const { status, code, message, errorName } = normalizeError(error);
-
- if (status === 429) {
- return reply.status(429).send({
- status: 429,
- error: 'Too Many Requests',
- message: 'You have exceeded the rate limit for this endpoint.',
- });
- }
-
- const skipLog =
- status < 500 && code !== undefined && SKIP_LOG_ERRORS.includes(code);
- if (!skipLog) {
- // 4xx are client-side problems (bad payloads, missing fields, etc.) —
- // log as warn so they don't drown out real server errors.
- const label =
- error instanceof HttpError ? 'internal server error' : 'request error';
- const reqCtx = {
- id: request.id,
- url: request.url,
- method: request.method,
- query: request.query,
- headers: request.headers,
- body:
- (request as FastifyRequest & { rawBody?: string }).rawBody ??
- request.body,
- };
- if (status >= 500) {
- request.log.error({ err: error, req: reqCtx }, label);
- } else {
- request.log.warn({ err: error, req: reqCtx }, label);
- }
- }
-
- if (process.env.NODE_ENV === 'production' && status === 500) {
- return reply.status(500).send('Internal server error');
- }
-
- return reply.status(status).send({
- status,
- // HttpError carries an explicit `error` payload (the underlying cause);
- // for everything else we surface the error name so the body is always
- // a stable JSON shape, regardless of what was thrown.
- error: error instanceof HttpError ? error.error : errorName,
- message,
- });
- });
-
- return fastify;
-}
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts
index 34e95c560..08786f8a5 100644
--- a/apps/api/src/config/env.ts
+++ b/apps/api/src/config/env.ts
@@ -121,7 +121,10 @@ const enabledQueuesSchema = z.preprocess(
)
);
-function splitTokens(value: string): string[] {
+function splitTokens(value: string | undefined): string[] {
+ if (value === undefined) {
+ return [];
+ }
return value
.split(',')
.map((token) => token.trim())
@@ -209,6 +212,30 @@ const envSchema = z.object({
* was.
*/
API_HOST: z.preprocess(blankToUndefined, z.string().optional()),
+ /**
+ * The CORS delegator's allowlist (apps/api/src/app.ts:107-110): the
+ * dashboard's own origin plus any extra comma-separated ones. Read once at
+ * boot, exactly as V1 did — changing an origin has always needed a restart.
+ */
+ DASHBOARD_URL: z.preprocess(blankToUndefined, z.string().optional()),
+ NEXT_PUBLIC_DASHBOARD_URL: z.preprocess(
+ blankToUndefined,
+ z.string().optional()
+ ),
+ API_CORS_ORIGINS: z.preprocess(blankToUndefined, z.string().optional()),
+ /**
+ * Signs the three GSC OAuth cookies. Always set in a real deployment
+ * (docs/ANSWERS.md §1.5); an unset value degrades to V1's `?? ''`.
+ */
+ COOKIE_SECRET: z.preprocess(
+ blankToUndefined,
+ z.string().optional().default('')
+ ),
+ /** Set on the demo deployment only. `validateSessionToken` short-circuits on
+ * it, and `enforceAccess` bans mutations for it. */
+ DEMO_USER_ID: z.preprocess(blankToUndefined, z.string().optional()),
+ /** V1's `requestLoggingHook`: the client ids whose requests log ip/UA. */
+ ENABLE_VERBOSE_LOGGING: z.preprocess(blankToUndefined, z.string().optional()),
SHUTDOWN_FORCE_EXIT_MS: z.coerce
.number()
.int()
@@ -220,6 +247,19 @@ export type Config = z.infer<typeof envSchema> & {
[key: `${string}_CONCURRENCY`]: number | undefined;
};
+/** The CORS delegator's origin allowlist, in V1's own order. */
+export function dashboardOrigins(config: Config): string[] {
+ return [
+ config.DASHBOARD_URL ?? config.NEXT_PUBLIC_DASHBOARD_URL,
+ ...splitTokens(config.API_CORS_ORIGINS),
+ ].filter((origin): origin is string => Boolean(origin));
+}
+
+/** V1's `ENABLE_VERBOSE_LOGGING`, a comma-separated client-id list. */
+export function verboseClientIds(config: Config): string[] {
+ return splitTokens(config.ENABLE_VERBOSE_LOGGING);
+}
+
/** V1's default host rule (apps/api/src/index.ts). */
export function apiHost(config: Config): string {
return config.API_HOST ?? (isProduction(config) ? '0.0.0.0' : 'localhost');
diff --git a/apps/api/src/controllers/error.html b/apps/api/src/controllers/error.html
deleted file mode 100644
index b174d613f..000000000
--- a/apps/api/src/controllers/error.html
+++ /dev/null
@@ -1,62 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Error - OpenPanel</title>
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
- <style>
- * {
- box-sizing: border-box;
- }
-
- body {
- font-family: 'Inter', sans-serif;
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- margin: 0;
- background-color: #f5f5f5;
- padding: 1rem;
- }
-
- .error-container {
- text-align: left;
- padding: 2rem;
- background-color: white;
- border-radius: 8px;
- box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
- max-width: 350px;
- }
-
- .logo {
- width: 80px;
- margin-bottom: 1.5rem;
- }
-
- h1 {
- color: #333;
- margin-bottom: 0.5rem;
- font-size: 1.5rem;
- }
-
- p {
- color: #666;
- font-size: 1rem;
- line-height: 1.5;
- }
- </style>
-</head>
-
-<body>
- <div class="error-container">
- <img src="https://openpanel.dev/logo.svg" alt="OpenPanel Logo" class="logo">
- <h1>Oops! Something went wrong</h1>
- <p>We encountered an error while processing your request. Please try again later or contact support if the problem
- persists.</p>
- </div>
-</body>
-
-</html>
\ No newline at end of file
diff --git a/apps/api/src/controllers/event.controller.test.ts b/apps/api/src/controllers/event.controller.test.ts
deleted file mode 100644
index d7aee7a58..000000000
--- a/apps/api/src/controllers/event.controller.test.ts
+++ /dev/null
@@ -1,216 +0,0 @@
-/**
- * Tests for the legacy `POST /event` compat route (ADR-015 entry 1, reversed:
- * the route is KEPT, produces to Kafka exactly like /track, and is measured
- * per client so the deferred removal decision has data).
- *
- * Covers:
- * - postEvent maps the legacy `{name, properties}` body onto the same Kafka
- * produce path /track uses, with a producer-minted event id.
- * - legacyEventUsageHook increments openpanel_legacy_event_requests_total,
- * labelled by client id, and never mints a label for an unauthenticated
- * request.
- * The `mixan-*` header fallback moved with the validator itself into
- * @openpanel/core's ingest module (M8-002) — see
- * packages/core/src/modules/ingest/src/client-auth.test.ts.
- *
- * `@openpanel/db` is partially mocked (importActual + overrides) because it
- * imports `@openpanel/queue`, which the produce assertions replace.
- */
-
-import { getAsnInfo, getGeoLocation } from '@openpanel/core';
-import { getSalts } from '@openpanel/db';
-import { produceIncomingEvent } from '@openpanel/queue';
-import type { DeprecatedPostEventPayload } from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { postEvent } from './event.controller';
-import { legacyEventUsageHook } from '@/hooks/legacy-event.hook';
-import { legacyEventRequestsTotal } from '@/metrics';
-
-vi.mock('@openpanel/queue', async () => {
- const actual =
- await vi.importActual<typeof import('@openpanel/queue')>(
- '@openpanel/queue'
- );
- return { ...actual, produceIncomingEvent: vi.fn() };
-});
-
-vi.mock('@openpanel/core', async () => {
- const actual =
- await vi.importActual<typeof import('@openpanel/core')>('@openpanel/core');
- return { ...actual, getGeoLocation: vi.fn(), getAsnInfo: vi.fn() };
-});
-
-vi.mock('@openpanel/db', async () => {
- const actual =
- await vi.importActual<typeof import('@openpanel/db')>('@openpanel/db');
- return { ...actual, getSalts: vi.fn() };
-});
-
-const PROJECT_ID = 'legacy-event-project';
-const CLIENT_ID = '11111111-1111-4111-8111-111111111111';
-const OTHER_CLIENT_ID = '22222222-2222-4222-8222-222222222222';
-const UUID_PATTERN =
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
-
-const legacyBody = (
- overrides: Partial<DeprecatedPostEventPayload> = {}
-): DeprecatedPostEventPayload => ({
- name: 'legacy_event',
- timestamp: new Date('2026-01-01T00:00:00.000Z').toISOString(),
- properties: { __referrer: '', foo: 'bar' },
- ...overrides,
-});
-
-const makeRequest = (
- body: DeprecatedPostEventPayload,
- headers: Record<string, string> = {}
-) =>
- ({
- body,
- headers: { 'user-agent': 'Mozilla/5.0 (Macintosh)', ...headers },
- clientIp: '203.0.113.10',
- timestamp: Date.now(),
- client: { id: CLIENT_ID, projectId: PROJECT_ID },
- log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
- }) as unknown as FastifyRequest<{ Body: DeprecatedPostEventPayload }>;
-
-interface ReplySpy {
- status: ReturnType<typeof vi.fn>;
- send: ReturnType<typeof vi.fn>;
-}
-
-const makeReply = (): FastifyReply & ReplySpy => {
- const reply = {
- status: vi.fn(() => reply),
- send: vi.fn(() => reply),
- } as ReplySpy;
- return reply as unknown as FastifyReply & ReplySpy;
-};
-
-const producedCall = () => {
- const call = vi.mocked(produceIncomingEvent).mock.calls[0];
- if (!call) {
- throw new Error('produceIncomingEvent was not called');
- }
- return { payload: call[0], partitionKey: call[1] };
-};
-
-const counterValue = async (clientId: string) => {
- const { values } = await legacyEventRequestsTotal.get();
- return (
- values.find((value) => value.labels.client_id === clientId)?.value ?? 0
- );
-};
-
-beforeEach(() => {
- vi.clearAllMocks();
- vi.mocked(getSalts).mockResolvedValue({
- current: 'current-salt',
- previous: 'previous-salt',
- });
- vi.mocked(getGeoLocation).mockResolvedValue({
- country: 'SE',
- city: 'Stockholm',
- region: 'Stockholm',
- longitude: 18,
- latitude: 59,
- } as Awaited<ReturnType<typeof getGeoLocation>>);
- vi.mocked(getAsnInfo).mockResolvedValue({
- asn: 1234,
- org: 'Example ISP',
- isHosting: false,
- });
- vi.mocked(produceIncomingEvent).mockResolvedValue(undefined);
-});
-
-describe('postEvent', () => {
- it('produces the legacy payload to Kafka and answers 202 "ok"', async () => {
- const request = makeRequest(legacyBody());
- const reply = makeReply();
-
- await postEvent(request, reply);
-
- expect(produceIncomingEvent).toHaveBeenCalledTimes(1);
- const { payload, partitionKey } = producedCall();
-
- expect(payload.projectId).toBe(PROJECT_ID);
- expect(payload.event.name).toBe('legacy_event');
- expect(payload.event.properties).toMatchObject({ foo: 'bar' });
- expect(payload.deviceId).toBeTruthy();
- expect(partitionKey).toBe(payload.deviceId);
-
- // V1's wire contract for this route: 202 with a plain-text body.
- expect(reply.status).toHaveBeenCalledWith(202);
- expect(reply.send).toHaveBeenCalledWith('ok');
- });
-
- it('mints the event id at the producer, like /track', async () => {
- await postEvent(makeRequest(legacyBody()), makeReply());
-
- expect(producedCall().payload.id).toMatch(UUID_PATTERN);
- });
-
- it('replaces the client-supplied timestamp with the server timestamp', async () => {
- const request = makeRequest(legacyBody());
- await postEvent(request, makeReply());
-
- const { payload } = producedCall();
- expect(payload.event.timestamp).toBe(request.timestamp);
- expect(payload.event.isTimestampFromThePast).toBe(false);
- });
-
- it('answers 400 when the client carries no project', async () => {
- const request = makeRequest(legacyBody());
- (request as { client?: unknown }).client = { id: CLIENT_ID };
- const reply = makeReply();
-
- await postEvent(request, reply);
-
- expect(produceIncomingEvent).not.toHaveBeenCalled();
- expect(reply.status).toHaveBeenCalledWith(400);
- expect(reply.send).toHaveBeenCalledWith('missing origin');
- });
-});
-
-describe('legacyEventUsageHook', () => {
- it('counts a request against its client id', async () => {
- const before = await counterValue(CLIENT_ID);
-
- await legacyEventUsageHook(makeRequest(legacyBody()));
-
- expect(await counterValue(CLIENT_ID)).toBe(before + 1);
- });
-
- it('keeps one series per client', async () => {
- const request = makeRequest(legacyBody());
- (request as { client?: unknown }).client = {
- id: OTHER_CLIENT_ID,
- projectId: PROJECT_ID,
- };
- const before = await counterValue(OTHER_CLIENT_ID);
- const otherBefore = await counterValue(CLIENT_ID);
-
- await legacyEventUsageHook(request);
-
- expect(await counterValue(OTHER_CLIENT_ID)).toBe(before + 1);
- expect(await counterValue(CLIENT_ID)).toBe(otherBefore);
- });
-
- it('mints no label for an unauthenticated request', async () => {
- const request = makeRequest(legacyBody());
- (request as { client?: unknown }).client = undefined;
-
- await legacyEventUsageHook(request);
-
- const { values } = await legacyEventRequestsTotal.get();
- expect(values.some((value) => !value.labels.client_id)).toBe(false);
- });
-
- it('is exposed under the name the removal decision will query', async () => {
- await expect(legacyEventRequestsTotal.get()).resolves.toMatchObject({
- name: 'openpanel_legacy_event_requests_total',
- type: 'counter',
- });
- });
-});
diff --git a/apps/api/src/controllers/event.controller.ts b/apps/api/src/controllers/event.controller.ts
deleted file mode 100644
index 77646cca2..000000000
--- a/apps/api/src/controllers/event.controller.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { generateId } from '@openpanel/common';
-import {
- applyBotSuspicion,
- getAsnInfo,
- getDeviceId,
- getGeoLocation,
- getStringHeaders,
- getTimestamp,
- parseUserAgent,
-} from '@openpanel/core';
-import { getSalts, sessionBuffer } from '@openpanel/db';
-import {
- type EventsQueuePayloadIncomingEvent,
- produceIncomingEvent,
-} from '@openpanel/queue';
-import type { DeprecatedPostEventPayload } from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { v4 as uuid } from 'uuid';
-
-export async function postEvent(
- request: FastifyRequest<{
- Body: DeprecatedPostEventPayload;
- }>,
- reply: FastifyReply
-) {
- const { timestamp, isTimestampFromThePast } = getTimestamp(
- request.timestamp,
- request.body
- );
- const ip = request.clientIp;
- const ua = request.headers['user-agent'] ?? 'unknown/1.0';
- const projectId = request.client?.projectId;
- const headers = getStringHeaders(request.headers);
-
- if (!projectId) {
- reply.status(400).send('missing origin');
- return;
- }
-
- const [salts, geo, asnInfo] = await Promise.all([
- getSalts(),
- getGeoLocation(ip),
- getAsnInfo(ip),
- ]);
- const { deviceId, sessionId } = await getDeviceId({
- projectId,
- ip,
- ua,
- salts,
- sessionBuffer,
- });
-
- const uaInfo = parseUserAgent(ua, request.body?.properties);
- // Mark (never block) likely bot traffic with __bot / __bot_reasons props.
- // This deprecated route has no body schema, so body can be null/undefined.
- if (request.body) {
- request.body.properties = applyBotSuspicion(request.body.properties, {
- asnInfo,
- headers: request.headers,
- clientSecretAuth: request.clientSecretAuth,
- isServer: uaInfo.isServer,
- });
- }
- const groupId = uaInfo.isServer
- ? `${projectId}:${request.body?.profileId ?? generateId()}`
- : deviceId;
- const queueData: EventsQueuePayloadIncomingEvent['payload'] = {
- // See track.controller: the producer mints the event id.
- id: uuid(),
- projectId,
- headers,
- event: {
- ...request.body,
- timestamp,
- isTimestampFromThePast,
- },
- uaInfo,
- geo,
- deviceId,
- sessionId: sessionId ?? '',
- };
-
- await produceIncomingEvent(queueData, groupId);
-
- reply.status(202).send('ok');
-}
diff --git a/apps/api/src/controllers/export.controller.ts b/apps/api/src/controllers/export.controller.ts
deleted file mode 100644
index 15b045c03..000000000
--- a/apps/api/src/controllers/export.controller.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-import { DateTime } from '@openpanel/common';
-import type { GetEventListOptions } from '@openpanel/db';
-import {
- ChartEngine,
- ClientType,
- db,
- getEventList,
- getEventsCount,
- getSettingsForProject,
-} from '@openpanel/db';
-import { zChartEvent, zChartEventFilter, zReport } from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { z } from 'zod';
-import { HttpError } from '@/utils/errors';
-
-async function getProjectId(
- request: FastifyRequest<{
- Querystring: {
- project_id?: string;
- projectId?: string;
- };
- }>
-) {
- let projectId = request.query.projectId || request.query.project_id;
-
- if (projectId) {
- if (
- request.client?.type === ClientType.read &&
- request.client?.projectId !== projectId
- ) {
- throw new HttpError('You do not have access to this project', {
- status: 403,
- });
- }
-
- const project = await db.project.findUnique({
- where: {
- organizationId: request.client?.organizationId,
- id: projectId,
- },
- });
-
- if (!project) {
- throw new HttpError('Project not found', {
- status: 404,
- });
- }
- }
-
- if (!projectId && request.client?.projectId) {
- projectId = request.client?.projectId;
- }
-
- if (!projectId) {
- throw new HttpError('project_id or projectId is required', {
- status: 400,
- });
- }
-
- return projectId;
-}
-
-export const eventsScheme = z.object({
- project_id: z.string().optional(),
- projectId: z.string().optional(),
- profileId: z.string().optional(),
- event: z.union([z.string(), z.array(z.string())]).optional(),
- start: z.coerce.string().optional(),
- end: z.coerce.string().optional(),
- page: z.coerce.number().optional().default(1),
- limit: z.coerce.number().optional().default(50),
- filters: z
- .preprocess((value) => {
- if (value == null || value === '') return undefined;
- if (Array.isArray(value)) return value;
- if (typeof value === 'string') {
- try {
- return JSON.parse(value);
- } catch {
- return undefined;
- }
- }
- return value;
- }, z.array(zChartEventFilter))
- .optional(),
- includes: z
- .preprocess(
- (arg) => {
- if (arg == null) {
- return undefined;
- }
- if (Array.isArray(arg)) {
- return arg;
- }
- if (typeof arg === 'string') {
- const parts = arg.split(',').map((s) => s.trim()).filter(Boolean);
- return parts;
- }
- return arg;
- },
- z.array(z.string())
- )
- .optional(),
-});
-
-export async function events(
- request: FastifyRequest<{
- Querystring: z.infer<typeof eventsScheme>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(request);
- const { limit, page: rawPage, event, start, end, profileId, includes, filters } = request.query;
- const take = Math.max(Math.min(limit, 1000), 1);
- const cursor = Math.max(rawPage, 1) - 1;
- const options: GetEventListOptions = {
- projectId,
- events: (Array.isArray(event) ? event : [event]).filter((s): s is string => typeof s === 'string'),
- startDate: start ? new Date(start) : undefined,
- endDate: end ? new Date(end) : undefined,
- cursor,
- take,
- profileId,
- filters,
- select: {
- profile: false,
- meta: false,
- ...includes?.reduce((acc, key) => ({ ...acc, [key]: true }), {}),
- },
- };
-
- const [data, totalCount] = await Promise.all([
- getEventList(options),
- getEventsCount(options),
- ]);
-
- reply.send({
- meta: {
- count: data.length,
- totalCount,
- pages: Math.ceil(totalCount / options.take),
- current: cursor + 1,
- },
- data,
- });
-}
-
-export const chartSchemeFull = zReport
- .pick({
- breakdowns: true,
- interval: true,
- range: true,
- previous: true,
- startDate: true,
- endDate: true,
- })
- .extend({
- project_id: z.string().optional(),
- projectId: z.string().optional(),
- series: z
- .array(
- z.object({
- name: z.string(),
- filters: zChartEvent.shape.filters.optional(),
- segment: zChartEvent.shape.segment.optional(),
- property: zChartEvent.shape.property.optional(),
- })
- )
- .optional(),
- // Backward compatibility - events will be migrated to series via preprocessing
- events: z
- .array(
- z.object({
- name: z.string(),
- filters: zChartEvent.shape.filters.optional(),
- segment: zChartEvent.shape.segment.optional(),
- property: zChartEvent.shape.property.optional(),
- })
- )
- .optional(),
- });
-
-export async function charts(
- request: FastifyRequest<{
- Querystring: z.infer<typeof chartSchemeFull>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(request);
- const { timezone } = await getSettingsForProject(projectId);
- const { events, series, ...rest } = request.query;
-
- // Use series if available, otherwise fall back to events (backward compat)
- const eventSeries = (series ?? events ?? []).map((event: any) => ({
- ...event,
- type: event.type ?? 'event',
- segment: event.segment ?? 'event',
- filters: event.filters ?? [],
- }));
-
- return ChartEngine.execute({
- ...rest,
- startDate: rest.startDate
- ? DateTime.fromISO(rest.startDate)
- .setZone(timezone)
- .toFormat('yyyy-MM-dd HH:mm:ss')
- : undefined,
- endDate: rest.endDate
- ? DateTime.fromISO(rest.endDate)
- .setZone(timezone)
- .toFormat('yyyy-MM-dd HH:mm:ss')
- : undefined,
- projectId,
- series: eventSeries,
- chartType: 'linear',
- metric: 'sum',
- });
-}
diff --git a/apps/api/src/controllers/gsc-oauth-callback.controller.ts b/apps/api/src/controllers/gsc-oauth-callback.controller.ts
deleted file mode 100644
index 0b50ecd58..000000000
--- a/apps/api/src/controllers/gsc-oauth-callback.controller.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-// Dissolved into @openpanel/core's gsc module (M5-002): state verification,
-// the Google token exchange and the gscConnection upsert moved to
-// packages/core/src/modules/gsc/gsc.service.ts#completeGscOAuthCallback.
-// This controller stays (DELEGATE PATTERN) — it keeps Fastify's signed-cookie
-// verification and the redirect shape, and delegates everything else.
-import { completeGscOAuthCallback } from '@openpanel/core';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { z } from 'zod';
-import { LogError } from '@/utils/errors';
-
-const OAUTH_SENSITIVE_KEYS = ['code', 'state'];
-
-function sanitizeOAuthQuery(
- query: Record<string, unknown> | null | undefined
-): Record<string, string> {
- if (!query || typeof query !== 'object') {
- return {};
- }
- return Object.fromEntries(
- Object.entries(query).map(([k, v]) => [
- k,
- OAUTH_SENSITIVE_KEYS.includes(k) ? '<redacted>' : String(v),
- ])
- );
-}
-
-export async function gscGoogleCallback(
- req: FastifyRequest,
- reply: FastifyReply
-) {
- try {
- const schema = z.object({
- code: z.string(),
- state: z.string(),
- });
-
- const query = schema.safeParse(req.query);
- if (!query.success) {
- throw new LogError(
- 'Invalid GSC callback query params',
- sanitizeOAuthQuery(req.query as Record<string, unknown>)
- );
- }
-
- const { code, state } = query.data;
-
- const rawStoredState = req.cookies.gsc_oauth_state ?? null;
- const rawCodeVerifier = req.cookies.gsc_code_verifier ?? null;
- const rawProjectId = req.cookies.gsc_project_id ?? null;
-
- const storedStateResult =
- rawStoredState !== null ? req.unsignCookie(rawStoredState) : null;
- const codeVerifierResult =
- rawCodeVerifier !== null ? req.unsignCookie(rawCodeVerifier) : null;
- const projectIdResult =
- rawProjectId !== null ? req.unsignCookie(rawProjectId) : null;
-
- if (
- !(
- storedStateResult?.value &&
- codeVerifierResult?.value &&
- projectIdResult?.value
- )
- ) {
- throw new LogError('Missing GSC OAuth cookies', {
- storedState: !storedStateResult?.value,
- codeVerifier: !codeVerifierResult?.value,
- projectId: !projectIdResult?.value,
- });
- }
-
- if (
- !(
- storedStateResult?.valid &&
- codeVerifierResult?.valid &&
- projectIdResult?.valid
- )
- ) {
- throw new LogError('Invalid GSC OAuth cookies', {
- storedState: !storedStateResult?.value,
- codeVerifier: !codeVerifierResult?.value,
- projectId: !projectIdResult?.value,
- });
- }
-
- const stateStr = storedStateResult?.value;
- const codeVerifierStr = codeVerifierResult?.value;
- const projectIdStr = projectIdResult?.value;
-
- let organizationId: string;
- try {
- ({ organizationId } = await completeGscOAuthCallback({
- code,
- state,
- storedState: stateStr,
- codeVerifier: codeVerifierStr,
- projectId: projectIdStr,
- }));
- } catch (error) {
- // Re-wrapped as LogError so redirectWithError shows the same
- // per-failure message it always has, sourced now from
- // gsc.service.ts#completeGscOAuthCallback instead of inline.
- const message = error instanceof Error ? error.message : String(error);
- throw new LogError(message, { projectId: projectIdStr });
- }
-
- reply.clearCookie('gsc_oauth_state');
- reply.clearCookie('gsc_code_verifier');
- reply.clearCookie('gsc_project_id');
-
- const dashboardUrl =
- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!;
- const redirectUrl = `${dashboardUrl}/${organizationId}/${projectIdStr}/settings/gsc`;
- return reply.redirect(redirectUrl);
- } catch (error) {
- req.log.error({ err: error }, 'GSC OAuth callback error');
- reply.clearCookie('gsc_oauth_state');
- reply.clearCookie('gsc_code_verifier');
- reply.clearCookie('gsc_project_id');
- return redirectWithError(reply, error);
- }
-}
-
-function redirectWithError(reply: FastifyReply, error: LogError | unknown) {
- const url = new URL(
- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!
- );
- url.pathname = '/login';
- if (error instanceof LogError) {
- url.searchParams.set('error', error.message);
- } else {
- url.searchParams.set('error', 'Failed to connect Google Search Console');
- }
- url.searchParams.set('correlationId', reply.request.id);
- return reply.redirect(url.toString());
-}
diff --git a/apps/api/src/controllers/healthcheck.controller.ts b/apps/api/src/controllers/healthcheck.controller.ts
deleted file mode 100644
index d45ce31ae..000000000
--- a/apps/api/src/controllers/healthcheck.controller.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { tryCatch } from '@openpanel/common';
-import { chQuery, db } from '@openpanel/db';
-import { getRedisCache } from '@openpanel/redis';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { isShuttingDown } from '@/utils/graceful-shutdown';
-
-export async function healthcheck(
- request: FastifyRequest,
- reply: FastifyReply
-) {
- const [redisResult, dbResult, chResult] = await Promise.all([
- tryCatch(async () => (await getRedisCache().ping()) === 'PONG'),
- tryCatch(async () => !!(await db.$executeRaw`SELECT 1`)),
- tryCatch(async () => (await chQuery('SELECT 1')).length > 0),
- ]);
-
- const dependencies = {
- redis: redisResult.ok && redisResult.data,
- db: dbResult.ok && dbResult.data,
- ch: chResult.ok && chResult.data,
- };
- const dependencyErrors = {
- redis: redisResult.error?.message,
- db: dbResult.error?.message,
- ch: chResult.error?.message,
- };
-
- const failedDependencies = Object.entries(dependencies)
- .filter(([, ok]) => !ok)
- .map(([name]) => name);
- const workingDependencies = Object.entries(dependencies)
- .filter(([, ok]) => ok)
- .map(([name]) => name);
-
- const status = failedDependencies.length === 0 ? 200 : 503;
-
- if (status === 200) {
- request.log.debug(
- {
- workingDependencies,
- failedDependencies,
- dependencies,
- },
- 'healthcheck passed'
- );
- } else {
- request.log.warn(
- {
- workingDependencies,
- failedDependencies,
- dependencies,
- dependencyErrors,
- },
- 'healthcheck failed'
- );
- }
-
- return reply.status(status).send({
- ready: status === 200,
- ...dependencies,
- failedDependencies,
- workingDependencies,
- });
-}
-
-// Kubernetes liveness — shallow, event loop only.
-export async function liveness(_request: FastifyRequest, reply: FastifyReply) {
- return reply.status(200).send({ live: true });
-}
-
-// Kubernetes readiness — shallow + shutdown-aware. Dependency health lives on
-// /healthcheck so a downstream blip cannot trigger mass pod restarts.
-export async function readiness(_request: FastifyRequest, reply: FastifyReply) {
- if (isShuttingDown()) {
- return reply.status(503).send({ ready: false, reason: 'shutting down' });
- }
-
- return reply.status(200).send({ ready: true });
-}
diff --git a/apps/api/src/controllers/import.controller.ts b/apps/api/src/controllers/import.controller.ts
deleted file mode 100644
index ae246b5ad..000000000
--- a/apps/api/src/controllers/import.controller.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { insertRawEventsBatch } from '@openpanel/core';
-import type { IClickhouseEvent } from '@openpanel/db';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-
-// Dissolved into @openpanel/core's import module (M5-004): the
-// toDots/project_id/imported_at stamping and the ClickHouse insert moved to
-// import.service.ts's `insertRawEventsBatch`. This controller stays
-// (DELEGATE PATTERN) — it is the live Fastify handler, a thin wrapper
-// resolving `request.client` and translating the result into a Fastify
-// reply.
-export async function importEvents(
- request: FastifyRequest<{
- Body: IClickhouseEvent[];
- }>,
- reply: FastifyReply
-) {
- const projectId = request.client?.projectId;
- if (!projectId) {
- throw new Error('Project ID is required');
- }
-
- try {
- const { writtenRows } = await insertRawEventsBatch(projectId, request.body);
-
- console.log(writtenRows, 'events imported');
- reply.send('OK');
- } catch (e) {
- console.error(e);
- reply.status(500).send('Error');
- }
-}
diff --git a/apps/api/src/controllers/insights.controller.ts b/apps/api/src/controllers/insights.controller.ts
deleted file mode 100644
index 7f7daed16..000000000
--- a/apps/api/src/controllers/insights.controller.ts
+++ /dev/null
@@ -1,731 +0,0 @@
-import { getDefaultIntervalByDates } from '@openpanel/constants';
-import type { IServiceClientWithProject } from '@openpanel/db';
-import {
- eventBuffer,
- findGroupsCore,
- findProfilesCore,
- getAnalyticsOverviewCore,
- getChartStartEndDate,
- getEngagementCore,
- getEntryExitPagesCore,
- getEventPropertyValuesCore,
- getFunnelCore,
- getGroupCore,
- getPagePerformanceCore,
- getProfileMetricsCore,
- getProfileSessionsCore,
- getProfileWithEvents,
- getReportDataCore,
- getRetentionCohortCore,
- getRollingActiveUsersCore,
- getSettingsForProject,
- getTopPagesCore,
- getTrafficBreakdownCore,
- getUserFlowCore,
- getWeeklyRetentionSeriesCore,
- gscGetCannibalizationCore,
- gscGetOverviewCore,
- gscGetPageDetailsCore,
- gscGetQueryDetailsCore,
- gscGetQueryOpportunitiesCore,
- gscGetTopPagesCore,
- gscGetTopQueriesCore,
- listDashboardsCore,
- listEventNamesCore,
- listEventPropertiesCore,
- listGroupTypesCore,
- listReportsCore,
- overviewService,
- queryEventsCore,
- querySessionsCore,
- resolveDateRange,
- resolveClientProjectId,
- type TrafficColumn,
-} from '@openpanel/db';
-import { zChartEventFilter, zRange } from '@openpanel/validation';
-
-/**
- * REST querystrings can't carry arrays of objects natively. Callers pass
- * `filters` as a URL-encoded JSON string; we decode it here. Empty string and
- * already-parsed arrays (e.g. from server-side dispatch) are both accepted.
- */
-const zFiltersParam = z
- .preprocess((value) => {
- if (value == null || value === '') return undefined;
- if (Array.isArray(value)) return value;
- if (typeof value === 'string') {
- try {
- return JSON.parse(value);
- } catch {
- return undefined;
- }
- }
- return value;
- }, z.array(zChartEventFilter))
- .optional();
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { z } from 'zod';
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-export const zDateRange = z.object({
- startDate: z.string().optional(),
- endDate: z.string().optional(),
- range: zRange.optional(),
-});
-
-type DateRangeInput = z.infer<typeof zDateRange>;
-
-type RequestWithProjectParam = FastifyRequest<{
- Params: { projectId?: string };
-}>;
-
-function getProjectId(req: RequestWithProjectParam): Promise<string> {
- const client = req.client!;
- return resolveClientProjectId({
- clientType: client.type === 'root' ? 'root' : 'read',
- clientProjectId: client.projectId ?? null,
- organizationId: client.organizationId,
- inputProjectId: req.params.projectId,
- });
-}
-
-function getOrgId(req: RequestWithProjectParam): string {
- return req.client!.organizationId;
-}
-
-async function resolveDates(
- projectId: string,
- data: DateRangeInput
-): Promise<{ startDate: string; endDate: string }> {
- if (!data.range || data.startDate) {
- return resolveDateRange(data.startDate, data.endDate);
- }
- const { timezone } = await getSettingsForProject(projectId);
- return getChartStartEndDate(
- { startDate: data.startDate, endDate: data.endDate, range: data.range! },
- timezone
- );
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — overview
-// ---------------------------------------------------------------------------
-
-export const zOverviewQuery = zDateRange.extend({
- interval: z.enum(['hour', 'day', 'week', 'month']).optional(),
-});
-
-export async function getOverview(
- req: FastifyRequest<{
- Params: { projectId?: string };
- Querystring: z.infer<typeof zOverviewQuery>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(
- await getAnalyticsOverviewCore({ projectId, startDate, endDate, interval: req.query.interval })
- );
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — metrics (legacy)
-// ---------------------------------------------------------------------------
-
-export const zGetMetricsQuery = z.object({
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange.default('7d'),
- filters: z.array(zChartEventFilter).default([]),
-});
-
-export async function getMetrics(
- req: FastifyRequest<{
- Params: { projectId: string };
- Querystring: z.infer<typeof zGetMetricsQuery>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { timezone } = await getSettingsForProject(projectId);
- const { startDate, endDate } = getChartStartEndDate(req.query, timezone);
- reply.send(
- await overviewService.getMetrics({
- projectId,
- filters: req.query.filters,
- startDate,
- endDate,
- interval: getDefaultIntervalByDates(startDate, endDate) ?? 'day',
- timezone,
- })
- );
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — live visitors
-// ---------------------------------------------------------------------------
-
-export async function getLiveVisitors(
- req: FastifyRequest<{ Params: { projectId: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- reply.send({ visitors: await eventBuffer.getActiveVisitorCount(projectId) });
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — active users
-// ---------------------------------------------------------------------------
-
-export const zActiveUsersQuery = z.object({
- days: z.number().int().min(1).max(90).default(7),
-});
-
-export async function getActiveUsers(
- req: FastifyRequest<{
- Params: { projectId?: string };
- Querystring: z.infer<typeof zActiveUsersQuery>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getRollingActiveUsersCore({ projectId, days: req.query.days }));
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — retention
-// ---------------------------------------------------------------------------
-
-export async function getRetentionSeries(
- req: FastifyRequest<{ Params: { projectId?: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getWeeklyRetentionSeriesCore(projectId));
-}
-
-export async function getRetentionCohort(
- req: FastifyRequest<{ Params: { projectId?: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getRetentionCohortCore(projectId));
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — pages
-// ---------------------------------------------------------------------------
-
-export async function getTopPages(
- req: FastifyRequest<{
- Params: { projectId?: string };
- Querystring: z.infer<typeof zDateRange>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await getTopPagesCore({ projectId, startDate, endDate }));
-}
-
-export const zGetTopPagesQuery = z.object({
- filters: z.array(zChartEventFilter).default([]),
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange.default('7d'),
- cursor: z.number().optional(),
- limit: z.number().default(10),
-});
-
-export async function getPages(
- req: FastifyRequest<{
- Params: { projectId: string };
- Querystring: z.infer<typeof zGetTopPagesQuery>;
- }>
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { timezone } = await getSettingsForProject(projectId);
- const { startDate, endDate } = getChartStartEndDate(req.query, timezone);
- return overviewService.getTopPages({ projectId, filters: req.query.filters, startDate, endDate, timezone });
-}
-
-export const zEntryExitQuery = zDateRange.extend({
- mode: z.enum(['entry', 'exit']).default('entry'),
-});
-
-export async function getEntryExitPages(
- req: FastifyRequest<{
- Params: { projectId?: string };
- Querystring: z.infer<typeof zEntryExitQuery>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await getEntryExitPagesCore({ projectId, startDate, endDate, mode: req.query.mode }));
-}
-
-export const zPagePerfQuery = zDateRange.extend({
- search: z.string().optional(),
- sortBy: z.enum(['sessions', 'pageviews', 'bounce_rate', 'avg_duration']).optional(),
- sortOrder: z.enum(['asc', 'desc']).optional(),
- limit: z.number().int().min(1).max(500).default(50),
-});
-
-export async function getPagePerformance(
- req: FastifyRequest<{
- Params: { projectId?: string };
- Querystring: z.infer<typeof zPagePerfQuery>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await getPagePerformanceCore({ projectId, startDate, endDate, ...req.query }));
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — overview generic (legacy)
-// ---------------------------------------------------------------------------
-
-export const overviewColumns = [
- 'referrer',
- 'referrer_name',
- 'referrer_type',
- 'utm_source',
- 'utm_medium',
- 'utm_campaign',
- 'utm_term',
- 'utm_content',
- 'region',
- 'country',
- 'city',
- 'device',
- 'brand',
- 'model',
- 'browser',
- 'browser_version',
- 'os',
- 'os_version',
-] as const;
-
-export type OverviewColumn = (typeof overviewColumns)[number];
-
-export const zOverviewGenericQuerystring = z.object({
- filters: z.array(zChartEventFilter).default([]),
- startDate: z.string().nullish(),
- endDate: z.string().nullish(),
- range: zRange.default('7d'),
- cursor: z.number().optional(),
- limit: z.number().default(10),
-});
-
-export function getOverviewGeneric(column: OverviewColumn) {
- return async (
- req: FastifyRequest<{
- Params: { projectId: string };
- Querystring: z.infer<typeof zOverviewGenericQuerystring>;
- }>,
- reply: FastifyReply
- ) => {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { timezone } = await getSettingsForProject(projectId);
- const { startDate, endDate } = getChartStartEndDate(req.query, timezone);
- reply.send(
- await overviewService.getTopGeneric({
- column,
- projectId,
- filters: req.query.filters,
- startDate,
- endDate,
- timezone,
- })
- );
- };
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — funnel
-// ---------------------------------------------------------------------------
-
-export const zFunnelQuery = zDateRange.extend({
- steps: z
- .union([z.array(z.string()), z.string().transform((s) => [s])])
- .refine((a) => a.length >= 2 && a.length <= 10, {
- message: 'steps must have between 2 and 10 items',
- }),
- windowHours: z.number().int().min(1).max(720).default(24),
- groupBy: z.enum(['session_id', 'profile_id']).default('session_id'),
-});
-
-export async function getFunnel(
- req: FastifyRequest<{
- Params: { projectId?: string };
- Querystring: z.infer<typeof zFunnelQuery>;
- }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(
- await getFunnelCore({ projectId, startDate, endDate, steps: req.query.steps, windowHours: req.query.windowHours, groupBy: req.query.groupBy })
- );
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — traffic
-// ---------------------------------------------------------------------------
-
-const referrerColumns = ['referrer_name', 'referrer_type', 'referrer', 'utm_source', 'utm_medium', 'utm_campaign'] as const;
-const geoColumns = ['country', 'region', 'city'] as const;
-const deviceColumns = ['device', 'browser', 'os'] as const;
-
-export const zReferrerQuery = zDateRange.extend({ breakdown: z.enum(referrerColumns).default('referrer_name') });
-export const zGeoQuery = zDateRange.extend({ breakdown: z.enum(geoColumns).default('country') });
-export const zDeviceQuery = zDateRange.extend({ breakdown: z.enum(deviceColumns).default('device') });
-
-export async function getTrafficReferrers(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zReferrerQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await getTrafficBreakdownCore({ projectId, startDate, endDate, column: req.query.breakdown as TrafficColumn }));
-}
-
-export async function getTrafficGeo(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zGeoQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await getTrafficBreakdownCore({ projectId, startDate, endDate, column: req.query.breakdown as TrafficColumn }));
-}
-
-export async function getTrafficDevices(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zDeviceQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await getTrafficBreakdownCore({ projectId, startDate, endDate, column: req.query.breakdown as TrafficColumn }));
-}
-
-// ---------------------------------------------------------------------------
-// Analytics — user flow & engagement
-// ---------------------------------------------------------------------------
-
-export const zUserFlowQuery = zDateRange.extend({
- startEvent: z.string(),
- endEvent: z.string().optional(),
- mode: z.enum(['after', 'before', 'between']).default('after'),
- steps: z.number().int().min(2).max(10).default(5),
- exclude: z.union([z.array(z.string()), z.string().transform((s) => [s])]).optional(),
- include: z.union([z.array(z.string()), z.string().transform((s) => [s])]).optional(),
-});
-
-export async function getUserFlow(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zUserFlowQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await getUserFlowCore({ projectId, startDate, endDate, ...req.query }));
-}
-
-export async function getEngagement(
- req: FastifyRequest<{ Params: { projectId?: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getEngagementCore(projectId));
-}
-
-// ---------------------------------------------------------------------------
-// Events
-// ---------------------------------------------------------------------------
-
-export const zEventsQuery = zDateRange.extend({
- eventNames: z.union([z.array(z.string()), z.string().transform((s) => [s])]).optional(),
- path: z.string().optional(),
- country: z.string().optional(),
- city: z.string().optional(),
- device: z.string().optional(),
- browser: z.string().optional(),
- os: z.string().optional(),
- referrer: z.string().optional(),
- referrerName: z.string().optional(),
- referrerType: z.string().optional(),
- profileId: z.string().optional(),
- properties: z.record(z.string(), z.string()).optional(),
- filters: zFiltersParam,
- limit: z.number().int().min(1).max(100).default(20),
-});
-
-export async function queryEvents(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zEventsQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await queryEventsCore({ projectId, ...req.query }));
-}
-
-export async function listEventNames(
- req: FastifyRequest<{ Params: { projectId?: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await listEventNamesCore(projectId));
-}
-
-export const zEventPropertiesQuery = z.object({ eventName: z.string().optional() });
-
-export async function listEventProperties(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zEventPropertiesQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await listEventPropertiesCore({ projectId, eventName: req.query.eventName }));
-}
-
-export const zPropertyValuesQuery = z.object({ eventName: z.string(), propertyKey: z.string() });
-
-export async function getEventPropertyValues(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zPropertyValuesQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getEventPropertyValuesCore({ projectId, ...req.query }));
-}
-
-// ---------------------------------------------------------------------------
-// Profiles
-// ---------------------------------------------------------------------------
-
-export const zProfilesQuery = z.object({
- name: z.string().optional(),
- email: z.string().optional(),
- country: z.string().optional(),
- city: z.string().optional(),
- device: z.string().optional(),
- browser: z.string().optional(),
- inactiveDays: z.number().int().min(1).optional(),
- minSessions: z.number().int().min(1).optional(),
- performedEvent: z.string().optional(),
- filters: zFiltersParam,
- sortOrder: z.enum(['asc', 'desc']).default('desc'),
- limit: z.number().int().min(1).max(100).default(20),
-});
-
-export async function findProfiles(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zProfilesQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await findProfilesCore({ projectId, ...req.query }));
-}
-
-export const zGetProfileQuery = z.object({ eventLimit: z.number().int().min(1).max(100).default(20) });
-
-export async function getProfile(
- req: FastifyRequest<{ Params: { projectId?: string; profileId: string }; Querystring: z.infer<typeof zGetProfileQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const result = await getProfileWithEvents(projectId, req.params.profileId, req.query.eventLimit);
- if (!result.profile) {
- return reply.status(404).send({ error: 'Profile not found', profileId: req.params.profileId });
- }
- return reply.send({ profile: result.profile, recentEvents: result.recent_events });
-}
-
-export const zProfileSessionsQuery = z.object({ limit: z.number().int().min(1).max(100).default(20) });
-
-export async function getProfileSessions(
- req: FastifyRequest<{ Params: { projectId?: string; profileId: string }; Querystring: z.infer<typeof zProfileSessionsQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getProfileSessionsCore(projectId, req.params.profileId, req.query.limit));
-}
-
-export async function getProfileMetrics(
- req: FastifyRequest<{ Params: { projectId?: string; profileId: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getProfileMetricsCore({ projectId, profileId: req.params.profileId }));
-}
-
-// ---------------------------------------------------------------------------
-// Sessions
-// ---------------------------------------------------------------------------
-
-export const zSessionsQuery = zDateRange.extend({
- country: z.string().optional(),
- city: z.string().optional(),
- device: z.string().optional(),
- browser: z.string().optional(),
- os: z.string().optional(),
- referrer: z.string().optional(),
- referrerName: z.string().optional(),
- referrerType: z.string().optional(),
- profileId: z.string().optional(),
- filters: zFiltersParam,
- limit: z.number().int().min(1).max(100).default(20),
-});
-
-export async function querySessions(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zSessionsQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await querySessionsCore({ projectId, ...req.query }));
-}
-
-// ---------------------------------------------------------------------------
-// Groups
-// ---------------------------------------------------------------------------
-
-export async function listGroupTypes(
- req: FastifyRequest<{ Params: { projectId?: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await listGroupTypesCore(projectId));
-}
-
-export const zGroupsQuery = z.object({
- type: z.string().optional(),
- search: z.string().optional(),
- limit: z.number().int().min(1).max(100).default(20),
-});
-
-export async function findGroups(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zGroupsQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await findGroupsCore({ projectId, ...req.query }));
-}
-
-export const zGetGroupQuery = z.object({ memberLimit: z.number().int().min(1).max(50).default(10) });
-
-export async function getGroup(
- req: FastifyRequest<{ Params: { projectId?: string; groupId: string }; Querystring: z.infer<typeof zGetGroupQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getGroupCore({ projectId, groupId: req.params.groupId, memberLimit: req.query.memberLimit }));
-}
-
-// ---------------------------------------------------------------------------
-// Dashboards & reports
-// ---------------------------------------------------------------------------
-
-export async function listDashboards(
- req: FastifyRequest<{ Params: { projectId?: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await listDashboardsCore({ projectId, organizationId: getOrgId(req as RequestWithProjectParam) }));
-}
-
-export async function listReports(
- req: FastifyRequest<{ Params: { projectId?: string; dashboardId: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await listReportsCore({ projectId, dashboardId: req.params.dashboardId, organizationId: getOrgId(req as RequestWithProjectParam) }));
-}
-
-export async function getReportData(
- req: FastifyRequest<{ Params: { projectId?: string; reportId: string } }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- return reply.send(await getReportDataCore({ projectId, reportId: req.params.reportId, organizationId: getOrgId(req as RequestWithProjectParam) }));
-}
-
-// ---------------------------------------------------------------------------
-// Google Search Console
-// ---------------------------------------------------------------------------
-
-export const zGscOverviewQuery = zDateRange.extend({
- interval: z.enum(['day', 'week', 'month']).default('day'),
-});
-
-export async function gscOverview(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zGscOverviewQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await gscGetOverviewCore({ projectId, startDate, endDate, interval: req.query.interval }));
-}
-
-export const zGscLimitQuery = zDateRange.extend({ limit: z.number().int().min(1).max(1000).default(100) });
-
-export async function gscPages(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zGscLimitQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await gscGetTopPagesCore({ projectId, startDate, endDate, limit: req.query.limit }));
-}
-
-export const zGscPageDetailsQuery = zDateRange.extend({ page: z.string().url() });
-
-export async function gscPageDetails(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zGscPageDetailsQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await gscGetPageDetailsCore({ projectId, startDate, endDate, page: req.query.page }));
-}
-
-export async function gscQueries(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zGscLimitQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await gscGetTopQueriesCore({ projectId, startDate, endDate, limit: req.query.limit }));
-}
-
-export const zGscQueryDetailsQuery = zDateRange.extend({ query: z.string() });
-
-export async function gscQueryDetails(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zGscQueryDetailsQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await gscGetQueryDetailsCore({ projectId, startDate, endDate, query: req.query.query }));
-}
-
-export const zGscOpportunitiesQuery = zDateRange.extend({ minImpressions: z.number().int().min(1).default(50) });
-
-export async function gscQueryOpportunities(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zGscOpportunitiesQuery> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await gscGetQueryOpportunitiesCore({ projectId, startDate, endDate, minImpressions: req.query.minImpressions }));
-}
-
-export async function gscCannibalization(
- req: FastifyRequest<{ Params: { projectId?: string }; Querystring: z.infer<typeof zDateRange> }>,
- reply: FastifyReply
-) {
- const projectId = await getProjectId(req as RequestWithProjectParam);
- const { startDate, endDate } = await resolveDates(projectId, req.query);
- return reply.send(await gscGetCannibalizationCore({ projectId, startDate, endDate }));
-}
diff --git a/apps/api/src/controllers/live.controller.ts b/apps/api/src/controllers/live.controller.ts
deleted file mode 100644
index 4be0a9a02..000000000
--- a/apps/api/src/controllers/live.controller.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-import type { WebSocket } from '@fastify/websocket';
-import { eventBuffer } from '@openpanel/db';
-import { setSuperJson } from '@openpanel/json';
-import { subscribeToPublishedEvent } from '@openpanel/redis';
-import { getProjectAccess } from '@openpanel/trpc';
-import { getOrganizationAccess } from '@openpanel/trpc/src/access';
-import type { FastifyRequest } from 'fastify';
-
-// Every ws handler MUST call this before its first await. Without an
-// 'error' listener, an ECONNRESET from the client (laptop sleep, network
-// flip, LB reset storm) propagates to uncaughtException and kills the
-// whole process. The ws library always emits 'close' after 'error', so
-// the existing close-based cleanup still runs.
-function guardSocket(socket: WebSocket, req: FastifyRequest) {
- socket.on('error', (err) => {
- req.log.warn({ err }, 'ws socket error');
- });
-}
-
-export function wsVisitors(
- socket: WebSocket,
- req: FastifyRequest<{
- Params: {
- projectId: string;
- };
- }>
-) {
- guardSocket(socket, req);
- const { params } = req;
- const sendCount = () => {
- eventBuffer
- .getActiveVisitorCount(params.projectId)
- .then((count) => {
- socket.send(String(count));
- })
- .catch(() => {
- socket.send('0');
- });
- };
-
- const unsubscribe = subscribeToPublishedEvent(
- 'events',
- 'batch',
- ({ projectId }) => {
- if (projectId === params.projectId) {
- sendCount();
- }
- }
- );
-
- socket.on('close', () => {
- unsubscribe();
- });
-}
-
-export async function wsProjectEvents(
- socket: WebSocket,
- req: FastifyRequest<{
- Params: {
- projectId: string;
- };
- Querystring: {
- token?: string;
- };
- }>
-) {
- guardSocket(socket, req);
- const { params } = req;
-
- const userId = req.session?.userId;
- if (!userId) {
- socket.send('No active session');
- socket.close();
- return;
- }
-
- const access = await getProjectAccess({
- userId,
- projectId: params.projectId,
- });
-
- if (!access) {
- socket.send('No access');
- socket.close();
- return;
- }
-
- const unsubscribe = subscribeToPublishedEvent(
- 'events',
- 'batch',
- ({ projectId, count }) => {
- if (projectId === params.projectId) {
- socket.send(setSuperJson({ count }));
- }
- }
- );
-
- socket.on('close', () => unsubscribe());
-}
-
-export async function wsProjectNotifications(
- socket: WebSocket,
- req: FastifyRequest<{
- Params: {
- projectId: string;
- };
- }>
-) {
- guardSocket(socket, req);
- const { params } = req;
- const userId = req.session?.userId;
-
- if (!userId) {
- socket.send('No active session');
- socket.close();
- return;
- }
-
- const access = await getProjectAccess({
- userId,
- projectId: params.projectId,
- });
-
- if (!access) {
- socket.send('No access');
- socket.close();
- return;
- }
-
- const unsubscribe = subscribeToPublishedEvent(
- 'notification',
- 'created',
- (notification) => {
- if (notification.projectId === params.projectId) {
- socket.send(setSuperJson(notification));
- }
- }
- );
-
- socket.on('close', () => unsubscribe());
-}
-
-export async function wsOrganizationEvents(
- socket: WebSocket,
- req: FastifyRequest<{
- Params: {
- organizationId: string;
- };
- }>
-) {
- guardSocket(socket, req);
- const { params } = req;
- const userId = req.session?.userId;
-
- if (!userId) {
- socket.send('No active session');
- socket.close();
- return;
- }
-
- const access = await getOrganizationAccess({
- userId,
- organizationId: params.organizationId,
- });
-
- if (!access) {
- socket.send('No access');
- socket.close();
- return;
- }
-
- const unsubscribe = subscribeToPublishedEvent(
- 'organization',
- 'subscription_updated',
- (message) => {
- socket.send(setSuperJson(message));
- }
- );
-
- socket.on('close', () => unsubscribe());
-}
diff --git a/apps/api/src/controllers/manage.controller.ts b/apps/api/src/controllers/manage.controller.ts
deleted file mode 100644
index 4839f5826..000000000
--- a/apps/api/src/controllers/manage.controller.ts
+++ /dev/null
@@ -1,407 +0,0 @@
-import {
- createClientForOrganization,
- createProjectForOrganization,
- deleteClientForOrganization,
- deleteProjectForOrganization,
- getClientForOrganization,
- getProjectForOrganization,
- listClientsForOrganization,
- listProjectsForOrganization,
- updateClientForOrganization,
- updateProjectForOrganization,
-} from '@openpanel/core';
-import type {
- zCreateProject,
- zUpdateProject,
-} from '@openpanel/core/modules/project/project.constants';
-import { db } from '@openpanel/db';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { z } from 'zod';
-import { HttpError } from '@/utils/errors';
-
-// project.service.ts + client.service.ts's /manage CRUD bodies (M6-002,
-// DELEGATE PATTERN) — zCreateProject/zUpdateProject moved with them
-// (project owns "C"); re-exported here for manage.router.ts's schemas.
-export {
- zCreateProject,
- zUpdateProject,
-} from '@openpanel/core/modules/project/project.constants';
-
-export const zCreateClient = z.object({
- name: z.string().min(1),
- projectId: z.string().optional(),
- type: z.enum(['read', 'write', 'root']).optional().default('write'),
-});
-
-export const zUpdateClient = z.object({
- name: z.string().min(1).optional(),
-});
-
-export const zCreateReference = z.object({
- projectId: z.string(),
- title: z.string().min(1),
- description: z.string().optional(),
- datetime: z.string(),
-});
-
-export const zUpdateReference = z.object({
- title: z.string().min(1).optional(),
- description: z.string().optional(),
- datetime: z.string().optional(),
-});
-
-// Projects CRUD — delegates to @openpanel/core's project.service.ts
-// (M6-002, DELEGATE PATTERN).
-export async function listProjects(
- request: FastifyRequest,
- reply: FastifyReply
-) {
- const projects = await listProjectsForOrganization(
- request.client!.organizationId
- );
- reply.send({ data: projects });
-}
-
-export async function getProject(
- request: FastifyRequest<{ Params: { id: string } }>,
- reply: FastifyReply
-) {
- const project = await getProjectForOrganization(
- request.params.id,
- request.client!.organizationId
- );
-
- if (!project) {
- throw new HttpError('Project not found', { status: 404 });
- }
-
- reply.send({ data: project });
-}
-
-export async function createProject(
- request: FastifyRequest<{ Body: z.infer<typeof zCreateProject> }>,
- reply: FastifyReply
-) {
- const { project, client } = await createProjectForOrganization(
- request.client!.organizationId,
- request.body
- );
-
- reply.send({ data: { ...project, client } });
-}
-
-export async function updateProject(
- request: FastifyRequest<{
- Params: { id: string };
- Body: z.infer<typeof zUpdateProject>;
- }>,
- reply: FastifyReply
-) {
- const project = await updateProjectForOrganization(
- request.params.id,
- request.client!.organizationId,
- request.body
- );
-
- if (!project) {
- throw new HttpError('Project not found', { status: 404 });
- }
-
- reply.send({ data: project });
-}
-
-export async function deleteProject(
- request: FastifyRequest<{ Params: { id: string } }>,
- reply: FastifyReply
-) {
- const deleted = await deleteProjectForOrganization(
- request.params.id,
- request.client!.organizationId
- );
-
- if (!deleted) {
- throw new HttpError('Project not found', { status: 404 });
- }
-
- reply.send({ success: true });
-}
-
-// Clients CRUD — delegates to @openpanel/core's client.service.ts
-// (M6-002, DELEGATE PATTERN).
-export async function listClients(
- request: FastifyRequest<{ Querystring: { projectId?: string } }>,
- reply: FastifyReply
-) {
- const clients = await listClientsForOrganization(
- request.client!.organizationId,
- request.query.projectId
- );
-
- if (clients === null) {
- throw new HttpError('Project not found', { status: 404 });
- }
-
- reply.send({ data: clients });
-}
-
-export async function getClient(
- request: FastifyRequest<{ Params: { id: string } }>,
- reply: FastifyReply
-) {
- const client = await getClientForOrganization(
- request.params.id,
- request.client!.organizationId
- );
-
- if (!client) {
- throw new HttpError('Client not found', { status: 404 });
- }
-
- reply.send({ data: client });
-}
-
-export async function createClient(
- request: FastifyRequest<{ Body: z.infer<typeof zCreateClient> }>,
- reply: FastifyReply
-) {
- const created = await createClientForOrganization(
- request.client!.organizationId,
- request.body
- );
-
- if (!created) {
- throw new HttpError('Project not found', { status: 404 });
- }
-
- reply.send({
- data: {
- ...created.client,
- secret: created.secret, // Return plain secret only once
- },
- });
-}
-
-export async function updateClient(
- request: FastifyRequest<{
- Params: { id: string };
- Body: z.infer<typeof zUpdateClient>;
- }>,
- reply: FastifyReply
-) {
- const client = await updateClientForOrganization(
- request.params.id,
- request.client!.organizationId,
- request.body
- );
-
- if (!client) {
- throw new HttpError('Client not found', { status: 404 });
- }
-
- reply.send({ data: client });
-}
-
-export async function deleteClient(
- request: FastifyRequest<{ Params: { id: string } }>,
- reply: FastifyReply
-) {
- const deleted = await deleteClientForOrganization(
- request.params.id,
- request.client!.organizationId
- );
-
- if (!deleted) {
- throw new HttpError('Client not found', { status: 404 });
- }
-
- reply.send({ success: true });
-}
-
-// References CRUD
-export async function listReferences(
- request: FastifyRequest<{ Querystring: { projectId?: string } }>,
- reply: FastifyReply
-) {
- const where: any = {};
-
- if (request.query.projectId) {
- // Verify project belongs to organization
- const project = await db.project.findFirst({
- where: {
- id: request.query.projectId,
- organizationId: request.client!.organizationId,
- },
- });
-
- if (!project) {
- throw new HttpError('Project not found', { status: 404 });
- }
-
- where.projectId = request.query.projectId;
- } else {
- // If no projectId, get all projects in org and filter references
- const projects = await db.project.findMany({
- where: {
- organizationId: request.client!.organizationId,
- },
- select: { id: true },
- });
-
- where.projectId = {
- in: projects.map((p) => p.id),
- };
- }
-
- const references = await db.reference.findMany({
- where,
- orderBy: {
- createdAt: 'desc',
- },
- });
-
- reply.send({ data: references });
-}
-
-export async function getReference(
- request: FastifyRequest<{ Params: { id: string } }>,
- reply: FastifyReply
-) {
- const reference = await db.reference.findUnique({
- where: {
- id: request.params.id,
- },
- include: {
- project: {
- select: {
- organizationId: true,
- },
- },
- },
- });
-
- if (!reference) {
- throw new HttpError('Reference not found', { status: 404 });
- }
-
- if (reference.project.organizationId !== request.client!.organizationId) {
- throw new HttpError('Reference not found', { status: 404 });
- }
-
- reply.send({ data: reference });
-}
-
-export async function createReference(
- request: FastifyRequest<{ Body: z.infer<typeof zCreateReference> }>,
- reply: FastifyReply
-) {
- const { projectId, title, description, datetime } = request.body;
-
- // Verify project belongs to organization
- const project = await db.project.findFirst({
- where: {
- id: projectId,
- organizationId: request.client!.organizationId,
- },
- });
-
- if (!project) {
- throw new HttpError('Project not found', { status: 404 });
- }
-
- const reference = await db.reference.create({
- data: {
- projectId,
- title,
- description: description || null,
- date: new Date(datetime),
- },
- });
-
- reply.send({ data: reference });
-}
-
-export async function updateReference(
- request: FastifyRequest<{
- Params: { id: string };
- Body: z.infer<typeof zUpdateReference>;
- }>,
- reply: FastifyReply
-) {
- const body = request.body;
-
- // Verify reference exists and belongs to organization
- const existing = await db.reference.findUnique({
- where: {
- id: request.params.id,
- },
- include: {
- project: {
- select: {
- organizationId: true,
- },
- },
- },
- });
-
- if (!existing) {
- throw new HttpError('Reference not found', { status: 404 });
- }
-
- if (existing.project.organizationId !== request.client!.organizationId) {
- throw new HttpError('Reference not found', { status: 404 });
- }
-
- const updateData: any = {};
- if (body.title !== undefined) {
- updateData.title = body.title;
- }
- if (body.description !== undefined) {
- updateData.description = body.description ?? null;
- }
- if (body.datetime !== undefined) {
- updateData.date = new Date(body.datetime);
- }
-
- const reference = await db.reference.update({
- where: {
- id: request.params.id,
- },
- data: updateData,
- });
-
- reply.send({ data: reference });
-}
-
-export async function deleteReference(
- request: FastifyRequest<{ Params: { id: string } }>,
- reply: FastifyReply
-) {
- const reference = await db.reference.findUnique({
- where: {
- id: request.params.id,
- },
- include: {
- project: {
- select: {
- organizationId: true,
- },
- },
- },
- });
-
- if (!reference) {
- throw new HttpError('Reference not found', { status: 404 });
- }
-
- if (reference.project.organizationId !== request.client!.organizationId) {
- throw new HttpError('Reference not found', { status: 404 });
- }
-
- await db.reference.delete({
- where: {
- id: request.params.id,
- },
- });
-
- reply.send({ success: true });
-}
diff --git a/apps/api/src/controllers/misc.controller.ts b/apps/api/src/controllers/misc.controller.ts
deleted file mode 100644
index d73e655c7..000000000
--- a/apps/api/src/controllers/misc.controller.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-// Dissolved into @openpanel/core's misc module (M7-008): favicon/OG proxy,
-// stats and geo lookup moved to
-// packages/core/src/modules/misc/misc.service.ts. This file stays
-// (DELEGATE PATTERN) — it is `misc.router.ts`'s Fastify glue, a thin wrapper
-// around the core functions, same shape as `manage.controller.ts` (M6-002).
-//
-// `GET /misc/og/clear` and `/misc/favicon/clear` are dropped, not ported
-// (ADR-015 entry #6: RULED + DEAD — `docs/ANSWERS.md` §1.4 confirms nothing
-// depends on them).
-import {
- getFavicon as getFaviconCore,
- getGeoReport,
- getOgImage as getOgImageCore,
- getStats,
- type ImageAssetResult,
- insertPingRecord,
-} from '@openpanel/core';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-
-interface GetFaviconParams {
- url: string;
-}
-
-function sendImageAsset(reply: FastifyReply, result: ImageAssetResult) {
- for (const [name, value] of Object.entries(result.headers)) {
- reply.header(name, value);
- }
- if (result.status === 200) {
- return reply.status(200).send(result.buffer);
- }
- return reply.status(result.status).send(result.body);
-}
-
-export async function getFavicon(
- request: FastifyRequest<{ Querystring: GetFaviconParams }>,
- reply: FastifyReply
-) {
- return sendImageAsset(
- reply,
- await getFaviconCore(request.query.url, request.log)
- );
-}
-
-export async function getOgImage(
- request: FastifyRequest<{ Querystring: { url: string } }>,
- reply: FastifyReply
-) {
- return sendImageAsset(
- reply,
- await getOgImageCore(request.query.url, request.log)
- );
-}
-
-export async function ping(
- request: FastifyRequest<{
- Body: {
- domain: string;
- count: number;
- };
- }>,
- reply: FastifyReply
-) {
- try {
- await insertPingRecord(request.body);
- reply.status(200).send({
- message: 'Success',
- count: request.body.count,
- domain: request.body.domain,
- });
- } catch (error) {
- request.log.error({ err: error }, 'Failed to insert ping');
- reply.status(500).send({
- error: 'Failed to insert ping',
- });
- }
-}
-
-export async function stats(_request: FastifyRequest, reply: FastifyReply) {
- reply.status(200).send(await getStats());
-}
-
-export async function getGeo(request: FastifyRequest, reply: FastifyReply) {
- const report = await getGeoReport(request.headers);
- if (!report.ok) {
- return reply.status(400).send('Bad Request');
- }
- return reply
- .status(200)
- .send({ selected: report.selected, ...report.others });
-}
diff --git a/apps/api/src/controllers/oauth-callback.controller.tsx b/apps/api/src/controllers/oauth-callback.controller.tsx
deleted file mode 100644
index 5317060df..000000000
--- a/apps/api/src/controllers/oauth-callback.controller.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-// Dissolved into @openpanel/core's auth module (M6-003): the github/google
-// token exchange, state validation, and account find-or-create/session-issue
-// logic moved to packages/core/src/modules/auth/auth.service.ts. This
-// controller stays (DELEGATE PATTERN) — it keeps Fastify's cookie reads and
-// the redirect shape, and delegates everything else, same as
-// gsc-oauth-callback.controller.ts (M5-002).
-import {
- assertOAuthState,
- completeOAuthCallback,
- fetchGithubOAuthUser,
- fetchGoogleOAuthUser,
- OAuthCallbackError,
-} from '@openpanel/core';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { z } from 'zod';
-import { LogError } from '@/utils/errors';
-
-const callbackQuery = z.object({
- code: z.string(),
- state: z.string(),
-});
-
-function parseCallbackQuery(
- req: FastifyRequest,
- provider: 'github' | 'google'
-) {
- const query = callbackQuery.safeParse(req.query);
- if (!query.success) {
- throw new LogError('Invalid callback query params', {
- error: query.error,
- query: req.query,
- provider,
- });
- }
- return query.data;
-}
-
-export async function githubCallback(req: FastifyRequest, reply: FastifyReply) {
- try {
- const { code, state } = parseCallbackQuery(req, 'github');
- const storedState = req.cookies.github_oauth_state ?? null;
- const inviteId = req.cookies.inviteId;
-
- assertOAuthState('github', state, storedState);
- const oauthUser = await fetchGithubOAuthUser(code);
-
- await completeOAuthCallback({
- provider: 'github',
- oauthUser,
- inviteId,
- setCookie: (...args) => reply.setCookie(...args),
- logger: req.log,
- });
-
- reply.clearCookie('github_oauth_state');
- return reply.redirect(
- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!
- );
- } catch (error) {
- req.log.error(error);
- reply.clearCookie('github_oauth_state');
- return redirectWithError(reply, error);
- }
-}
-
-export async function googleCallback(req: FastifyRequest, reply: FastifyReply) {
- try {
- const { code, state } = parseCallbackQuery(req, 'google');
- const storedState = req.cookies.google_oauth_state ?? null;
- const codeVerifier = req.cookies.google_code_verifier ?? null;
- const inviteId = req.cookies.inviteId;
-
- assertOAuthState('google', state, storedState);
- if (!codeVerifier) {
- throw new OAuthCallbackError('Missing oauth parameters', {
- codeVerifier: false,
- });
- }
- const oauthUser = await fetchGoogleOAuthUser(code, codeVerifier);
-
- await completeOAuthCallback({
- provider: 'google',
- oauthUser,
- inviteId,
- setCookie: (...args) => reply.setCookie(...args),
- logger: req.log,
- });
-
- reply.clearCookie('google_code_verifier');
- reply.clearCookie('google_oauth_state');
- return reply.redirect(
- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!
- );
- } catch (error) {
- req.log.error(error);
- reply.clearCookie('google_code_verifier');
- reply.clearCookie('google_oauth_state');
- return redirectWithError(reply, error);
- }
-}
-
-function redirectWithError(reply: FastifyReply, error: unknown) {
- const url = new URL(
- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!
- );
- url.pathname = '/login';
- if (error instanceof LogError || error instanceof OAuthCallbackError) {
- url.searchParams.set('error', error.message);
- } else {
- url.searchParams.set('error', 'An error occurred');
- }
- url.searchParams.set('correlationId', reply.request.id);
- return reply.redirect(url.toString());
-}
diff --git a/apps/api/src/controllers/profile.controller.ts b/apps/api/src/controllers/profile.controller.ts
deleted file mode 100644
index cc97e4c69..000000000
--- a/apps/api/src/controllers/profile.controller.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import {
- type AdjustProfilePropertyResult,
- adjustProfileProperty,
- getGeoLocation,
- identifyProfile,
- parseUserAgent,
-} from '@openpanel/core';
-import type {
- DeprecatedIncrementProfilePayload,
- DeprecatedUpdateProfilePayload,
-} from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-
-// Dissolved into @openpanel/core's profile module (M7-002): the upsert and
-// the increment/decrement arithmetic moved to profile.service.ts's
-// `identifyProfile` / `adjustProfileProperty`. These controllers stay
-// (DELEGATE PATTERN) — they are the live Fastify handlers, thin wrappers
-// resolving `request.client` and translating the result into a Fastify
-// reply, same as import.controller.ts.
-
-export async function updateProfile(
- request: FastifyRequest<{
- Body: DeprecatedUpdateProfilePayload;
- }>,
- reply: FastifyReply
-) {
- const payload = request.body;
- const projectId = request.client!.projectId;
- if (!projectId) {
- return reply.status(400).send('No projectId');
- }
- const userAgent = parseUserAgent(
- request.headers['user-agent'],
- payload.properties
- );
- const geo = await getGeoLocation(request.clientIp);
-
- await identifyProfile(projectId, payload, { geo, userAgent });
-
- reply.status(202).send(payload.profileId);
-}
-
-function sendAdjusted(
- reply: FastifyReply,
- result: AdjustProfilePropertyResult
-) {
- if (result.status === 'not-found') {
- return reply.status(404).send('Not found');
- }
- if (result.status === 'not-a-number') {
- return reply.status(400).send('Not number');
- }
- return reply.status(202).send(result.profileId);
-}
-
-export async function incrementProfileProperty(
- request: FastifyRequest<{
- Body: DeprecatedIncrementProfilePayload;
- }>,
- reply: FastifyReply
-) {
- const { profileId, property, value } = request.body;
- const projectId = request.client!.projectId;
- if (!projectId) {
- return reply.status(400).send('No projectId');
- }
-
- const result = await adjustProfileProperty(projectId, {
- profileId,
- property,
- delta: value,
- });
- return sendAdjusted(reply, result);
-}
-
-export async function decrementProfileProperty(
- request: FastifyRequest<{
- Body: DeprecatedIncrementProfilePayload;
- }>,
- reply: FastifyReply
-) {
- const { profileId, property, value } = request.body;
- const projectId = request.client?.projectId;
- if (!projectId) {
- return reply.status(400).send('No projectId');
- }
-
- const result = await adjustProfileProperty(projectId, {
- profileId,
- property,
- delta: -value,
- });
- return sendAdjusted(reply, result);
-}
diff --git a/apps/api/src/controllers/tools.controller.ts b/apps/api/src/controllers/tools.controller.ts
deleted file mode 100644
index f7ca49195..000000000
--- a/apps/api/src/controllers/tools.controller.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-// Dissolved into @openpanel/core's tools module (M7-008): site-checker and
-// ip-lookup moved to packages/core/src/modules/tools/src/{site-checker,
-// ip-lookup}.ts. This file stays (DELEGATE PATTERN) — it is `tools.router.ts`'s
-// Fastify glue, a thin wrapper around the core functions, same shape as
-// `manage.controller.ts` (M6-002).
-import { runIpLookup, runSiteCheck } from '@openpanel/core';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-
-export async function siteChecker(
- request: FastifyRequest<{ Querystring: { url?: string } }>,
- reply: FastifyReply
-) {
- const outcome = await runSiteCheck(
- request.query.url,
- request.headers,
- request.log
- );
- if (outcome.status !== 200) {
- return reply.status(outcome.status).send({ error: outcome.error });
- }
- return reply.send(outcome.result);
-}
-
-export async function ipLookup(
- request: FastifyRequest<{ Querystring: { ip?: string } }>,
- reply: FastifyReply
-) {
- const outcome = await runIpLookup(
- request.query.ip,
- request.headers,
- request.log
- );
- if (outcome.status !== 200) {
- return reply.status(outcome.status).send({ error: outcome.error });
- }
- return reply.send(outcome.result);
-}
diff --git a/apps/api/src/controllers/track.controller.ts b/apps/api/src/controllers/track.controller.ts
deleted file mode 100644
index fe1a1dd2c..000000000
--- a/apps/api/src/controllers/track.controller.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import {
- fetchDeviceIdentity,
- ingestTrack,
- type TrackOutcome,
-} from '@openpanel/core';
-import { groupBuffer, replayBuffer, sessionBuffer } from '@openpanel/db';
-import { produceIncomingEvent } from '@openpanel/queue';
-import type { ITrackHandlerPayload } from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { HttpError } from '@/utils/errors';
-
-// Dissolved into @openpanel/core's ingest module (M8-002): the whole pipeline
-// — context building, the seven payload handlers, device/session resolution
-// and the Kafka produce — moved to ingest.service.ts. These controllers stay
-// (DELEGATE PATTERN) as the live Fastify handlers: they resolve
-// `request.client`, hand the pipeline its transport, and translate the
-// outcome back into the exact replies and `HttpError`s V1 produced.
-//
-// The producer is passed in rather than imported by core: @openpanel/queue
-// imports @openpanel/core for its logger, so core cannot import it back
-// (M8-003 moves the producer into core).
-
-const ingestBuffers = {
- session: sessionBuffer,
- replay: replayBuffer,
- group: groupBuffer,
-};
-
-function replyToOutcome(outcome: TrackOutcome, reply: FastifyReply) {
- switch (outcome.status) {
- case 'ok':
- return reply.status(200).send({
- deviceId: outcome.deviceId,
- sessionId: outcome.sessionId,
- });
- case 'alias-not-supported':
- return reply.status(400).send({
- status: 400,
- error: 'Bad Request',
- message: 'Alias is not supported',
- });
- case 'invalid-type':
- return reply.status(400).send({
- status: 400,
- error: 'Bad Request',
- message: 'Invalid type',
- });
- case 'missing-project-id':
- throw new HttpError('Missing projectId', { status: 400 });
- case 'replay-missing-session-id':
- throw new HttpError('Session ID is required for replay', { status: 400 });
- case 'profile-not-found':
- throw new HttpError('Profile not found', { status: 404 });
- default:
- throw new HttpError('Property value is not a number', { status: 400 });
- }
-}
-
-export async function handler(
- request: FastifyRequest<{
- Body: ITrackHandlerPayload;
- }>,
- reply: FastifyReply
-) {
- const outcome = await ingestTrack(
- {
- projectId: request.client?.projectId,
- clientIp: request.clientIp,
- headers: request.headers,
- clientSecretAuth: request.clientSecretAuth ?? false,
- timestamp: request.timestamp,
- body: request.body,
- },
- { buffers: ingestBuffers, produceIncomingEvent }
- );
-
- return replyToOutcome(outcome, reply);
-}
-
-export async function fetchDeviceId(
- request: FastifyRequest,
- reply: FastifyReply
-) {
- const identity = await fetchDeviceIdentity(
- {
- projectId: request.client?.projectId,
- clientIp: request.clientIp,
- headers: request.headers,
- },
- { session: sessionBuffer },
- request.log
- );
-
- switch (identity.status) {
- case 'missing-project-id':
- return reply.status(400).send('No projectId');
- case 'missing-ip':
- return reply.status(400).send('Missing ip address');
- case 'missing-user-agent':
- return reply.status(400).send('Missing header: user-agent');
- default:
- return reply.status(200).send({
- deviceId: identity.deviceId,
- sessionId: identity.sessionId,
- message: identity.message,
- });
- }
-}
diff --git a/apps/api/src/controllers/webhook.controller.ts b/apps/api/src/controllers/webhook.controller.ts
deleted file mode 100644
index f9b9f112a..000000000
--- a/apps/api/src/controllers/webhook.controller.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import fs from 'node:fs';
-import path, { dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = dirname(__filename);
-
-// Dissolved into @openpanel/core's integration + subscription modules
-// (M6-006): the Slack token-exchange/upsert logic moved to
-// integration.service.ts's `completeSlackOAuthCallback`, and the Polar event
-// validation/dispatch logic moved to subscription.service.ts's
-// `handlePolarWebhookEvent`. This controller stays the LIVE route (DELEGATE
-// PATTERN) — it keeps Fastify's `rawBody` config (signature verification
-// breaks on any body parsing) and delegates to those functions, the same
-// function core's own `/webhook/slack` and `/webhook/polar` routes call.
-import {
- completeSlackOAuthCallback,
- handlePolarWebhookEvent,
-} from '@openpanel/core';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { z } from 'zod';
-
-const paramsSchema = z.object({
- code: z.string(),
- state: z.string(),
-});
-
-export async function slackWebhook(
- request: FastifyRequest<{
- Querystring: unknown;
- }>,
- reply: FastifyReply
-) {
- const parsedParams = paramsSchema.safeParse(request.query);
-
- if (!parsedParams.success) {
- request.log.error(parsedParams.error, 'Invalid params');
- return reply.status(400).send({ error: 'Invalid params' });
- }
-
- try {
- const { organizationId, projectId } = await completeSlackOAuthCallback(
- parsedParams.data
- );
-
- const dashboardUrl =
- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL;
- // Integrations are project-scoped; the org-level integrations route no
- // longer exists. Newer installs carry projectId in their metadata. Older
- // in-flight installs (started before the project-scoped routes shipped)
- // may lack it — fall back to the org landing page rather than a now-404
- // integrations URL.
- return reply.redirect(
- projectId
- ? `${dashboardUrl}/${organizationId}/${projectId}/integrations/installed`
- : `${dashboardUrl}/${organizationId}`
- );
- } catch (err) {
- request.log.error(err, 'Slack OAuth callback error');
- const html = fs.readFileSync(path.join(__dirname, 'error.html'), 'utf8');
- return reply.status(500).header('Content-Type', 'text/html').send(html);
- }
-}
-
-export async function polarWebhook(
- request: FastifyRequest<{
- Querystring: unknown;
- }>,
- reply: FastifyReply
-) {
- await handlePolarWebhookEvent(
- request.rawBody!,
- request.headers as Record<string, string>,
- request.log
- );
-
- return reply.status(202).send('OK');
-}
diff --git a/apps/api/src/hooks/client.hook.ts b/apps/api/src/hooks/client.hook.ts
deleted file mode 100644
index 8a87d14ef..000000000
--- a/apps/api/src/hooks/client.hook.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import type {
- DeprecatedPostEventPayload,
- ITrackHandlerPayload,
-} from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { SdkAuthError, validateSdkRequest } from '@/utils/auth';
-
-export async function clientHook(
- req: FastifyRequest<{
- Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
- }>,
- reply: FastifyReply
-) {
- try {
- const client = await validateSdkRequest(req);
- req.client = client;
- } catch (error) {
- if (error instanceof SdkAuthError) {
- req.log.warn({ err: error }, 'Invalid SDK request');
- return reply.status(401).send(error.message);
- }
-
- req.log.error({ err: error }, 'Invalid SDK request');
- return reply.status(500).send('Internal server error');
- }
-}
diff --git a/apps/api/src/hooks/duplicate.hook.ts b/apps/api/src/hooks/duplicate.hook.ts
deleted file mode 100644
index 6b0d312eb..000000000
--- a/apps/api/src/hooks/duplicate.hook.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { isDuplicateIngestRequest } from '@openpanel/core';
-import type {
- DeprecatedPostEventPayload,
- ITrackHandlerPayload,
-} from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-
-// Delegates to @openpanel/core's ingest module (M8-002).
-export async function duplicateHook(
- req: FastifyRequest<{
- Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
- }>,
- reply: FastifyReply
-) {
- const isDuplicate = await isDuplicateIngestRequest({
- method: req.method,
- clientIp: req.clientIp,
- headers: req.headers,
- body: req.body,
- });
-
- if (isDuplicate) {
- return reply.status(200).send('Duplicate event');
- }
-}
diff --git a/apps/api/src/hooks/ip.hook.ts b/apps/api/src/hooks/ip.hook.ts
deleted file mode 100644
index 1424b5006..000000000
--- a/apps/api/src/hooks/ip.hook.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { getClientIpFromHeaders } from '@openpanel/core';
-import type { FastifyRequest } from 'fastify';
-
-export async function ipHook(request: FastifyRequest) {
- const { ip, header } = getClientIpFromHeaders(request.headers);
-
- if (ip) {
- request.clientIp = ip;
- request.clientIpHeader = header;
- } else {
- request.clientIp = '';
- request.clientIpHeader = '';
- }
-}
diff --git a/apps/api/src/hooks/is-bot.hook.ts b/apps/api/src/hooks/is-bot.hook.ts
deleted file mode 100644
index ad1ce7af0..000000000
--- a/apps/api/src/hooks/is-bot.hook.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { checkIngestBot } from '@openpanel/core';
-import type {
- DeprecatedPostEventPayload,
- ITrackHandlerPayload,
-} from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-
-// Delegates to @openpanel/core's ingest module (M8-002), which owns the
-// client-secret exemption, the bot lookup and the bot-event write.
-export async function isBotHook(
- req: FastifyRequest<{
- Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
- }>,
- reply: FastifyReply
-) {
- const bot = await checkIngestBot({
- headers: req.headers,
- clientSecretAuth: req.clientSecretAuth ?? false,
- projectId: req.client?.projectId,
- body: req.body,
- });
-
- if (bot) {
- return reply.status(202).send({ bot });
- }
-}
diff --git a/apps/api/src/hooks/legacy-event.hook.ts b/apps/api/src/hooks/legacy-event.hook.ts
deleted file mode 100644
index f9198b9a9..000000000
--- a/apps/api/src/hooks/legacy-event.hook.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { FastifyRequest } from 'fastify';
-import { recordLegacyEventRequest } from '@/metrics';
-
-/**
- * Counts traffic on the legacy `POST /event` route per client so the deferred
- * removal decision has data (ADR-015 entry 1, reversed).
- *
- * Registered after `clientHook` and before the hooks that can short-circuit
- * the request (`isBotHook`, `subscriptionHook`), for two reasons: the label
- * can then only ever be a client id that exists in the database — an
- * unauthenticated caller must not be able to mint prometheus label values —
- * and a client whose events are dropped as bot/wind-down traffic is still a
- * client that would break if `/event` disappeared.
- */
-export async function legacyEventUsageHook(request: FastifyRequest) {
- const clientId = request.client?.id;
-
- if (clientId) {
- recordLegacyEventRequest(clientId);
- }
-}
diff --git a/apps/api/src/hooks/request-id.hook.ts b/apps/api/src/hooks/request-id.hook.ts
deleted file mode 100644
index 7d074646e..000000000
--- a/apps/api/src/hooks/request-id.hook.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import type {
- FastifyReply,
- FastifyRequest,
- HookHandlerDoneFunction,
-} from 'fastify';
-
-export async function requestIdHook(request: FastifyRequest) {
- if (!request.headers['request-id']) {
- request.headers['request-id'] = request.id;
- }
-}
diff --git a/apps/api/src/hooks/request-logging.hook.ts b/apps/api/src/hooks/request-logging.hook.ts
deleted file mode 100644
index c3f1c877c..000000000
--- a/apps/api/src/hooks/request-logging.hook.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { path, pick } from 'ramda';
-
-const ignoreLog = ['/healthcheck', '/healthz', '/metrics', '/misc'];
-const ignoreMethods = ['OPTIONS'];
-
-const getTrpcInput = (
- request: FastifyRequest
-): Record<string, unknown> | undefined => {
- const input = path<any>(['query', 'input'], request);
- try {
- return typeof input === 'string' ? JSON.parse(input).json : input;
- } catch {
- return undefined;
- }
-};
-
-export async function requestLoggingHook(
- request: FastifyRequest,
- reply: FastifyReply
-) {
- if (ignoreMethods.includes(request.method)) {
- return;
- }
- if (ignoreLog.some((path) => request.url.startsWith(path))) {
- return;
- }
- if (request.url.includes('trpc')) {
- request.log.info(
- {
- url: request.url.split('?')[0],
- method: request.method,
- input: getTrpcInput(request),
- elapsed: reply.elapsedTime,
- },
- 'request done'
- );
- } else {
- const payload: {
- url: string;
- method: string;
- elapsed: number;
- headers: Record<string, string | string[] | undefined>;
- body?: unknown;
- clientIp: string;
- clientIpHeader: string;
- userAgent: string;
- } = {
- url: request.url,
- method: request.method,
- elapsed: reply.elapsedTime,
- headers: pick(
- ['openpanel-client-id', 'openpanel-sdk-name', 'openpanel-sdk-version'],
- request.headers
- ),
- clientIp: '',
- clientIpHeader: '',
- userAgent: '',
- };
-
- if (payload.url.startsWith('/track')) {
- payload.body = request.body;
- }
-
- const clientId = request.headers['openpanel-client-id'];
- if (
- process.env.ENABLE_VERBOSE_LOGGING?.split(',').includes(
- (Array.isArray(clientId) ? clientId[0] : clientId) ?? ''
- )
- ) {
- payload.clientIp = request.clientIp;
- payload.clientIpHeader = request.clientIpHeader;
- payload.userAgent = request.headers['user-agent'] ?? '';
- }
-
- request.log.info(payload, 'request done');
- }
-}
diff --git a/apps/api/src/hooks/subscription.hook.test.ts b/apps/api/src/hooks/subscription.hook.test.ts
deleted file mode 100644
index fe5db6cf5..000000000
--- a/apps/api/src/hooks/subscription.hook.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * Tests for subscriptionHook — the preHandler that rejects ingestion for
- * organizations blocked by the wind-down sequence.
- *
- * Three behaviours matter enough to pin down: it gates on the wind-down step
- * rather than the subscription state (so an expired trial keeps ingesting
- * until it has actually been warned), it answers 202 rather than a 4xx (the
- * SDKs retry everything except 401 and 2xx), and it fails open.
- */
-
-import type { FastifyReply, FastifyRequest } from 'fastify';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const getOrganizationByProjectIdCached = vi.fn();
-
-vi.mock('@openpanel/db', () => ({
- getOrganizationByProjectIdCached: (projectId: string) =>
- getOrganizationByProjectIdCached(projectId),
-}));
-
-const { subscriptionHook } = await import('./subscription.hook');
-
-function makeReply() {
- const status = vi.fn();
- const send = vi.fn();
- const reply = { status, send };
- status.mockReturnValue(reply);
- send.mockReturnValue(reply);
- return { reply: reply as unknown as FastifyReply, status, send };
-}
-
-function makeReq(overrides: Partial<FastifyRequest> = {}) {
- return {
- client: { projectId: 'proj-1' },
- log: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
- ...overrides,
- } as unknown as FastifyRequest;
-}
-
-beforeEach(() => {
- vi.unstubAllEnvs();
- vi.stubEnv('SELF_HOSTED', 'false');
- getOrganizationByProjectIdCached.mockReset();
-});
-
-describe('subscriptionHook', () => {
- it.each(['blocked', 'final_warning'])(
- 'drops ingestion with 202 at step %s',
- async (windDownStep) => {
- getOrganizationByProjectIdCached.mockResolvedValue({
- id: 'org-1',
- windDownStep,
- });
- const { reply, status, send } = makeReply();
-
- await subscriptionHook(makeReq() as never, reply);
-
- // 202 rather than 402/403 on purpose: the SDKs treat every other
- // non-2xx as retryable and would hammer this endpoint four times per
- // event.
- expect(status).toHaveBeenCalledWith(202);
- expect(send).toHaveBeenCalledWith({ blocked: true });
- },
- );
-
- it.each(['expired_notice', 'stopping_soon'])(
- 'still accepts ingestion at step %s',
- async (windDownStep) => {
- getOrganizationByProjectIdCached.mockResolvedValue({
- id: 'org-1',
- windDownStep,
- });
- const { reply, status } = makeReply();
-
- await subscriptionHook(makeReq() as never, reply);
-
- expect(status).not.toHaveBeenCalled();
- },
- );
-
- it('accepts ingestion from an expired trial that has not been warned yet', async () => {
- // The reason the gate reads windDownStep and not subscriptionState: every
- // lapsed trial is already trial_expired, so gating on state would block
- // thousands of orgs the moment this ships.
- getOrganizationByProjectIdCached.mockResolvedValue({
- id: 'org-1',
- subscriptionState: 'trial_expired',
- windDownStep: null,
- });
- const { reply, status } = makeReply();
-
- await subscriptionHook(makeReq() as never, reply);
-
- expect(status).not.toHaveBeenCalled();
- });
-
- it('fails open when the organization lookup throws', async () => {
- getOrganizationByProjectIdCached.mockRejectedValue(new Error('redis down'));
- const { reply, status } = makeReply();
- const req = makeReq();
-
- await subscriptionHook(req as never, reply);
-
- expect(status).not.toHaveBeenCalled();
- expect(req.log.error).toHaveBeenCalled();
- });
-
- it('does nothing when self hosted', async () => {
- vi.stubEnv('SELF_HOSTED', 'true');
- const { reply, status } = makeReply();
-
- await subscriptionHook(makeReq() as never, reply);
-
- expect(getOrganizationByProjectIdCached).not.toHaveBeenCalled();
- expect(status).not.toHaveBeenCalled();
- });
-
- it('does nothing without a resolved client', async () => {
- const { reply, status } = makeReply();
-
- await subscriptionHook(makeReq({ client: null }) as never, reply);
-
- expect(getOrganizationByProjectIdCached).not.toHaveBeenCalled();
- expect(status).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/api/src/hooks/subscription.hook.ts b/apps/api/src/hooks/subscription.hook.ts
deleted file mode 100644
index 9e1a2f39b..000000000
--- a/apps/api/src/hooks/subscription.hook.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { getOrganizationByProjectIdCached } from '@openpanel/db';
-import type {
- DeprecatedPostEventPayload,
- ITrackHandlerPayload,
-} from '@openpanel/validation';
-import type { FastifyReply, FastifyRequest } from 'fastify';
-
-/**
- * Rejects ingestion for organizations that have been blocked by the wind-down
- * sequence (see packages/core/src/modules/organization/src/wind-down.ts).
- *
- * Two things worth knowing about the shape of this:
- *
- * It gates on `windDownStep`, not on `subscriptionState`. Every expired trial
- * is already in `trial_expired`, so gating on the state would block thousands
- * of orgs the moment this ships, skipping the four warning emails entirely.
- * The step only reaches 'blocked' after the org has been told three times.
- *
- * It answers 202, not 402 or 403. The SDKs treat only 401 and 2xx as terminal
- * (packages/sdks/sdk/src/api.ts); every other status is thrown and retried
- * three times with backoff, so a "correct" status code would multiply traffic
- * from exactly the clients we are trying to quiet down. This matches how
- * isBotHook already drops traffic.
- */
-
-const BLOCKED_STEPS = new Set(['blocked', 'final_warning']);
-
-export async function subscriptionHook(
- req: FastifyRequest<{
- Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
- }>,
- reply: FastifyReply,
-) {
- if (process.env.SELF_HOSTED === 'true') {
- return;
- }
-
- const projectId = req.client?.projectId;
- if (!projectId) {
- return;
- }
-
- try {
- // Cached for 5 minutes and invalidated by the Polar webhook, so paying
- // again lifts the block on the next checkout rather than on a TTL.
- const organization = await getOrganizationByProjectIdCached(projectId);
-
- if (!organization?.windDownStep) {
- return;
- }
-
- if (!BLOCKED_STEPS.has(organization.windDownStep)) {
- return;
- }
-
- req.log.info(
- {
- organizationId: organization.id,
- projectId,
- windDownStep: organization.windDownStep,
- },
- 'Ingestion blocked by wind-down',
- );
-
- return reply.status(202).send({ blocked: true });
- } catch (error) {
- // Fail open. Dropping a paying customer's events because Redis or Postgres
- // hiccuped is far worse than letting a blocked org through for a tick.
- req.log.error(
- { err: error, projectId },
- 'Wind-down check failed, allowing ingestion',
- );
- }
-}
diff --git a/apps/api/src/hooks/timestamp.hook.ts b/apps/api/src/hooks/timestamp.hook.ts
deleted file mode 100644
index 7ad0c4c62..000000000
--- a/apps/api/src/hooks/timestamp.hook.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import type { FastifyRequest } from 'fastify';
-
-export async function timestampHook(request: FastifyRequest) {
- request.timestamp = Date.now();
-}
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
deleted file mode 100644
index e55b5ae07..000000000
--- a/apps/api/src/index.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-/** biome-ignore-all lint/suspicious/useAwait: fastify need async or done callbacks */
-process.env.TZ = 'UTC';
-
-import './utils/observability';
-
-import { rawStderrWrite } from '@openpanel/core';
-import { assertKafkaConfigured } from '@openpanel/queue';
-import { getRedisPub } from '@openpanel/redis';
-import sourceMapSupport from 'source-map-support';
-import { buildApp } from './app';
-import { shutdown } from './utils/graceful-shutdown';
-import { logger } from './utils/logger';
-
-sourceMapSupport.install();
-
-// Kafka/Redpanda is the sole events transport (ADR-004) — a missing broker list
-// must kill boot, not surface as a 5xx on the first tracked event.
-try {
- assertKafkaConfigured();
-} catch (error) {
- logger.fatal({ err: error }, 'Refusing to start');
- process.exit(1);
-}
-
-const port = Number.parseInt(process.env.API_PORT || '3000', 10);
-const host =
- process.env.API_HOST ||
- (process.env.NODE_ENV === 'production' ? '0.0.0.0' : 'localhost');
-
-const startServer = async () => {
- logger.info('Starting server');
- try {
- const fastify = await buildApp();
-
- if (process.env.NODE_ENV === 'production') {
- logger.info('Registering graceful shutdown handlers');
- process.on('SIGTERM', async () => await shutdown(fastify, 'SIGTERM', 0));
- process.on('SIGINT', async () => await shutdown(fastify, 'SIGINT', 0));
-
- // After an uncaughtException / unhandledRejection the process state
- // is corrupt — don't try to gracefully drain queues/DBs. Log and
- // exit immediately so Docker can respawn the container. Anything
- // slower than this lets bad requests keep hitting a poisoned process
- // and risks blocking past Docker's stop_grace_period (→ SIGKILL).
- // Mirror fatals to the real stderr (bypassing the output interceptor,
- // so nothing ships twice) — the OTLP flush window can be lost on the
- // way down, and `docker logs` must always show why we died.
- process.on('uncaughtException', (error) => {
- logger.fatal({ err: error }, 'Uncaught exception — exiting');
- rawStderrWrite(
- `Uncaught exception — exiting: ${error?.stack ?? error}\n`
- );
- // Flush pino, then hard-exit. unref() so the safety net doesn't
- // keep the loop alive on its own.
- setTimeout(() => process.exit(1), 1000).unref();
- });
- process.on('unhandledRejection', (reason, promise) => {
- logger.fatal({ reason, promise }, 'Unhandled rejection — exiting');
- rawStderrWrite(
- `Unhandled rejection — exiting: ${
- reason instanceof Error ? reason.stack : String(reason)
- }\n`
- );
- setTimeout(() => process.exit(1), 1000).unref();
- });
- }
-
- await fastify.listen({ host, port });
-
- try {
- await getRedisPub().config('SET', 'notify-keyspace-events', 'Ex');
- } catch (error) {
- logger.warn({ err: error }, 'Failed to set redis notify-keyspace-events');
- logger.warn(
- 'If you use a managed Redis service, you may need to set this manually.'
- );
- logger.warn('Otherwise some functions may not work as expected.');
- }
- } catch (error) {
- logger.error({ err: error }, 'Failed to start server');
- }
-};
-
-startServer();
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 236965740..a4aeb2114 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -1,6 +1,7 @@
-// V2 boot entrypoint (ADR-007 §7 "apps/api — three files"; TARGET_ARCHITECTURE
-// §7 main.ts boot order). Runs on Bun; the V1 Fastify boot at `./index.ts`
-// keeps serving the golden harness untouched until it is deleted at M9-004.
+// THE boot entrypoint (ADR-007 §7 "apps/api — three files"; TARGET_ARCHITECTURE
+// §7 main.ts boot order). Runs on Bun. M9-004 deleted the V1 Fastify boot
+// (`./index.ts` + `./app.ts`), so this file is the only way the API starts and
+// `app.ts`'s mounting half lives in `buildHttpApp` below.
//
// THE ROLE TABLE (TARGET_ARCHITECTURE §7). One process, three shapes:
//
@@ -20,30 +21,40 @@
// consumers start (cloud runs 4 replicas on `events` and 6 on the rest,
// docs/ANSWERS.md §1.3), and an unknown token there fails boot the same way.
//
-// db/ch/clients are not on `AppDeps` yet — their types stay the `unknown`
-// stubs `context.ts` declares until P3/P4 land the real clients — so the
-// mounted HTTP surface is still ops-only; `dashboardRoutes`/`publicApiRoutes`
-// land at M9-004. The buffers are real from M8-001, the producers from
-// M9-001, and the workers/schedulers/consumer from here.
+// THE MOUNTED SURFACE (M9-004). `AppDeps` now carries the real db, ClickHouse,
+// Redis and outbound clients, and `buildHttpApp` hangs all four V1 scopes on
+// one Bun.serve: the root chain (CORS -> requestId -> timestamp -> ip -> the
+// error handler, in V1's order), the ops surface, the public API, the
+// dashboard surface and `/trpc`. A role that only consumes serves none of the
+// last three — V1's worker never did either.
process.env.TZ = 'UTC';
+import { createHmac } from 'node:crypto';
import {
type AppDeps,
BULL_BOARD_BASE_PATH,
type BufferDeps,
bullBoardRoutes,
+ COOKIE_OPTIONS,
+ corsDelegator,
createBuffers,
+ createClients,
createInitialSalts,
createProducers,
+ createTrpcFetchHandler,
+ dashboardRoutes,
debugRoutes,
enableEventsHeartbeat,
+ errorHandler,
+ type HttpCtx,
incomingEvent,
ingestConsumerMetrics,
type KafkaConsumerHandle,
loadIncomingEventDeps,
markEventsActivity,
opsRoutes,
+ publicApiRoutes,
type QueueDefinition,
type QueueProducerHandle,
queueKey,
@@ -53,6 +64,7 @@ import {
registerDefaultMetrics,
registerQueueMetrics,
registerSessionScrapeMetrics,
+ requestLogging,
type SessionMetricsRedis,
sessionEndEnqueueOptions,
sessionEndJobPayload,
@@ -60,8 +72,11 @@ import {
startKafkaEventsConsumer,
startSchedulers,
startWorkers,
+ TRPC_ENDPOINT,
type WorkerHandle,
} from '@openpanel/core';
+import { ch } from '@openpanel/db/src/clickhouse/client';
+import { db } from '@openpanel/db/src/prisma-client';
import {
assertKafkaConfigured,
createKafkaEventsConsumer,
@@ -75,13 +90,17 @@ import {
produceIncomingEvent,
} from '@openpanel/queue';
import { getRedisCache, getRedisPub, getRedisQueue } from '@openpanel/redis';
+import { appRouter } from '@openpanel/trpc';
+import { Elysia } from 'elysia';
import pino from 'pino';
import {
type Config,
concurrencyOverride,
+ dashboardOrigins,
isProduction,
KAFKA_QUEUE_TOKEN,
loadConfig,
+ verboseClientIds,
} from './config/env';
// The registry key and the Redis name are the same string for all seven queues
@@ -117,6 +136,9 @@ const logger = pino({ name: 'api', level: config.LOG_LEVEL });
/** ROLE=api produces and serves; it never consumes. */
const roleConsumes = config.ROLE !== 'api';
+/** ROLE=worker consumes and never serves a URL surface, exactly as V1's
+ * worker did (it ran bull-board, /debug/cron and /metrics, nothing else). */
+const roleServesHttp = config.ROLE !== 'worker';
const workersEnabled = roleConsumes && !config.DISABLE_WORKERS;
/**
@@ -166,13 +188,16 @@ function findBullQueue(producers: QueueProducerHandle, name: string) {
function buildDeps(): AppDeps {
const producers = buildProducerHandle();
return {
- // db/ch/redis/clients are `unknown` stubs in context.ts until P3/P4 land
- // the real clients — reading one before its type lands is meant to be a
- // compile error, not a runtime `undefined`.
- db: undefined,
- ch: undefined,
- redis: undefined,
- clients: undefined,
+ // The four boot handles. `packages/db` and `packages/redis` still own
+ // their own singletons and read their own env (ADR-007 §7's accepted
+ // pragmatic deviation), so these are references to those, not new
+ // connections: one Prisma client, one round-robin ClickHouse client and
+ // the cache Redis, handed down so a service reaches them through its
+ // request-scoped `Ctx` instead of importing them (TECH_DEBT §4).
+ db,
+ ch,
+ redis: getRedisCache(),
+ clients: createClients(),
buffers: createBuffers(bufferDeps(producers)),
producers,
// @openpanel/queue's Kafka producer, injected because core cannot import
@@ -303,8 +328,90 @@ function registerConsumerMetrics(deps: AppDeps): void {
);
}
+/**
+ * The three cookies the GSC OAuth flow signs (gsc.rpc.ts's `signed: true`).
+ * V1 signed them through `@fastify/cookie`'s `secret`; Elysia takes the same
+ * list, and `signCookie` below produces the identical `value.<b64 hmac>` form
+ * on the tRPC side, which writes cookies through the fetch adapter's
+ * `resHeaders` rather than through Elysia (ADR-009 constraint 1).
+ */
+const SIGNED_COOKIE_NAMES = [
+ 'gsc_oauth_state',
+ 'gsc_code_verifier',
+ 'gsc_project_id',
+];
+
+const BASE64_TRAILING_PADDING = /=+$/;
+
+/** Elysia's `signCookie` (dist/utils: HMAC-SHA256, base64, padding stripped),
+ * synchronously — `TrpcContextOptions.signCookie` is a sync signature. */
+function signCookie(value: string): string {
+ const signature = createHmac('sha256', config.COOKIE_SECRET)
+ .update(value)
+ .digest('base64')
+ .replace(BASE64_TRAILING_PADDING, '');
+ return `${value}.${signature}`;
+}
+
+/**
+ * V1's `app.ts`, merged into the one entrypoint: the four Fastify scopes
+ * become one Elysia tree.
+ *
+ * THE ROOT CHAIN ORDER IS THE CONTRACT (ADR-002 "behaviour that must be
+ * preserved explicitly" 2): cors -> requestId -> timestamp -> ip, before every
+ * route-level hook. `requestLogging` brings `requestContext` — and therefore
+ * those three hooks — with it, and the error handler is registered on the same
+ * root so it covers every scope below.
+ *
+ * `ROLE=worker` mounts NONE of the three URL surfaces: V1's worker served only
+ * bull-board, the debug routes and `/metrics`, and a worker replica answering
+ * `/track` would take traffic no load balancer routes to it.
+ */
async function buildHttpApp(deps: AppDeps) {
- const app = opsRoutes(deps);
+ const app = new Elysia({
+ // Elysia throws on an empty `secrets`, where V1 passed `secret: ''` to
+ // @fastify/cookie and simply produced signatures nobody could rely on. A
+ // deployment without COOKIE_SECRET therefore gets unsigned cookies rather
+ // than a dead process — the same outcome V1 had, arrived at explicitly.
+ cookie: config.COOKIE_SECRET
+ ? { secrets: config.COOKIE_SECRET, sign: SIGNED_COOKIE_NAMES }
+ : {},
+ })
+ .use(corsDelegator({ dashboardOrigins: dashboardOrigins(config) }))
+ .use(errorHandler(deps, { production: isProduction(config) }))
+ .use(requestLogging(deps, { verboseClientIds: verboseClientIds(config) }))
+ .use(opsRoutes(deps));
+
+ if (roleServesHttp) {
+ const trpc = createTrpcFetchHandler({
+ router: appRouter,
+ logger,
+ cookieOptions: COOKIE_OPTIONS,
+ simulateLatency: !isProduction(config),
+ signCookie,
+ demoMode: Boolean(config.DEMO_USER_ID),
+ });
+
+ app
+ .use(publicApiRoutes(deps))
+ .use(dashboardRoutes(deps))
+ // `.all('/trpc/*')`, never `/trpc/:path`: the fetch adapter derives the
+ // procedure by `pathname.slice(endpoint.length)` and a batched request
+ // puts commas in that segment (ADR-009).
+ //
+ // `parse: 'none'` is load-bearing: the adapter reads the body off the
+ // `Request` itself, and Elysia's own body parsing would have consumed
+ // the stream first — every tRPC mutation then fails with
+ // "Body already used".
+ .all(
+ `${TRPC_ENDPOINT}/*`,
+ ({ request, ctx }: { request: Request; ctx: HttpCtx }) =>
+ trpc(request, ctx),
+ { parse: 'none' }
+ );
+
+ logger.info('Public API, dashboard and /trpc surfaces mounted');
+ }
// Local-only: trigger a cron job on demand instead of waiting for its
// schedule. Two conditions, both V1's: `NODE_ENV != production`, because it
diff --git a/apps/api/src/metrics.ts b/apps/api/src/metrics.ts
deleted file mode 100644
index 5736ff8f5..000000000
--- a/apps/api/src/metrics.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import client from 'prom-client';
-
-/**
- * Metrics owned by the API process.
- *
- * `fastify-metrics` serves prom-client's global registry at `/metrics`
- * (fastify-metrics `exposeMetrics()` reads `client.register`), and prom-client
- * metrics register themselves there on construction — so declaring a metric in
- * this module is all that is needed to expose it. It resolves to the same
- * physical `prom-client` package fastify-metrics loads, which is what makes
- * one shared registry possible.
- */
-
-const LEGACY_EVENT_CLIENT_ID_LABEL = 'client_id';
-
-/**
- * ADR-015 entry 1 was reversed: `POST /event` is kept as a legacy compat route
- * rather than deleted, because production still has projects posting to it.
- * This counter is the evidence the deferred removal decision needs — when it
- * reads zero for every client, `/event` and the `mixan-*` header fallback can
- * both go (ADR-015 entry 5 is pending the same measurement).
- */
-export const legacyEventRequestsTotal = new client.Counter({
- name: 'openpanel_legacy_event_requests_total',
- help: 'Requests to the legacy POST /event ingestion route, by client id',
- labelNames: [LEGACY_EVENT_CLIENT_ID_LABEL],
-});
-
-export function recordLegacyEventRequest(clientId: string) {
- legacyEventRequestsTotal.inc({ [LEGACY_EVENT_CLIENT_ID_LABEL]: clientId });
-}
diff --git a/apps/api/src/routes/event.router.ts b/apps/api/src/routes/event.router.ts
deleted file mode 100644
index abc0b462c..000000000
--- a/apps/api/src/routes/event.router.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { FastifyPluginAsyncZodOpenApi } from 'fastify-zod-openapi';
-import * as controller from '@/controllers/event.controller';
-import { clientHook } from '@/hooks/client.hook';
-import { duplicateHook } from '@/hooks/duplicate.hook';
-import { isBotHook } from '@/hooks/is-bot.hook';
-import { legacyEventUsageHook } from '@/hooks/legacy-event.hook';
-import { subscriptionHook } from '@/hooks/subscription.hook';
-
-const eventRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
- fastify.addHook('preValidation', duplicateHook);
- fastify.addHook('preHandler', clientHook);
- // Usage metric before the hooks that can short-circuit — see the hook.
- fastify.addHook('preHandler', legacyEventUsageHook);
- fastify.addHook('preHandler', isBotHook);
- fastify.addHook('preHandler', subscriptionHook);
-
- fastify.route({
- method: 'POST',
- url: '/',
- schema: {
- tags: ['Event'],
- description:
- 'Deprecated direct event ingestion endpoint. Use /track instead.',
- },
- handler: controller.postEvent,
- });
-};
-
-export default eventRouter;
diff --git a/apps/api/src/routes/export.router.ts b/apps/api/src/routes/export.router.ts
deleted file mode 100644
index 4440e7428..000000000
--- a/apps/api/src/routes/export.router.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { Prisma } from '@openpanel/db';
-import type { FastifyRequest } from 'fastify';
-import type { FastifyPluginAsyncZodOpenApi } from 'fastify-zod-openapi';
-import {
- chartSchemeFull,
- eventsScheme,
-} from '@/controllers/export.controller';
-import * as controller from '@/controllers/export.controller';
-import { validateExportRequest } from '@/utils/auth';
-import { parseQueryString } from '@/utils/parse-zod-query-string';
-import { activateRateLimiter } from '@/utils/rate-limiter';
-
-const TAGS = ['Export'] as const;
-
-const exportRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
- await activateRateLimiter({ fastify, max: 100, timeWindow: '10 seconds' });
-
- fastify.addHook('preHandler', async (req: FastifyRequest, reply) => {
- try {
- const client = await validateExportRequest(req.headers);
- req.client = client;
- } catch (e) {
- if (e instanceof Prisma.PrismaClientKnownRequestError) {
- return reply.status(401).send({ error: 'Unauthorized', message: 'Client ID seems to be malformed' });
- }
- if (e instanceof Error) {
- return reply.status(401).send({ error: 'Unauthorized', message: e.message });
- }
- return reply.status(401).send({ error: 'Unauthorized', message: 'Unexpected error' });
- }
- });
-
- fastify.addHook('preValidation', async (req) => {
- req.query = parseQueryString(req.query as Record<string, unknown>) as typeof req.query;
- });
-
- fastify.route({
- method: 'GET',
- url: '/events',
- schema: {
- tags: TAGS,
- description: 'Export a paginated list of raw events with optional filtering by date, profile, and event type.',
- querystring: eventsScheme,
- },
- handler: controller.events,
- });
-
- fastify.route({
- method: 'GET',
- url: '/charts',
- schema: {
- tags: TAGS,
- description: 'Export aggregated chart/analytics data for a series of events over a time range.',
- querystring: chartSchemeFull,
- },
- handler: controller.charts,
- });
-};
-
-export default exportRouter;
diff --git a/apps/api/src/routes/gsc-callback.router.ts b/apps/api/src/routes/gsc-callback.router.ts
deleted file mode 100644
index 6ac0491d3..000000000
--- a/apps/api/src/routes/gsc-callback.router.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { gscGoogleCallback } from '@/controllers/gsc-oauth-callback.controller';
-import type { FastifyPluginCallback } from 'fastify';
-
-const router: FastifyPluginCallback = async (fastify) => {
- fastify.route({
- method: 'GET',
- url: '/callback',
- handler: gscGoogleCallback,
- });
-};
-
-export default router;
diff --git a/apps/api/src/routes/import.router.ts b/apps/api/src/routes/import.router.ts
deleted file mode 100644
index 5c55765a9..000000000
--- a/apps/api/src/routes/import.router.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import * as controller from '@/controllers/import.controller';
-import { validateImportRequest } from '@/utils/auth';
-import type { FastifyPluginCallback, FastifyRequest } from 'fastify';
-
-import { Prisma } from '@openpanel/db';
-
-const importRouter: FastifyPluginCallback = async (fastify) => {
- fastify.addHook('preHandler', async (req: FastifyRequest, reply) => {
- try {
- const client = await validateImportRequest(req.headers);
- req.client = client;
- } catch (e) {
- if (e instanceof Prisma.PrismaClientKnownRequestError) {
- return reply.status(401).send({
- error: 'Unauthorized',
- message: 'Client ID seems to be malformed',
- });
- }
-
- if (e instanceof Error) {
- return reply
- .status(401)
- .send({ error: 'Unauthorized', message: e.message });
- }
-
- return reply
- .status(401)
- .send({ error: 'Unauthorized', message: 'Unexpected error' });
- }
- });
-
- fastify.route({
- method: 'POST',
- url: '/events',
- schema: {
- tags: ['Import'],
- description: 'Bulk import historical events.',
- },
- handler: controller.importEvents,
- });
-};
-
-export default importRouter;
diff --git a/apps/api/src/routes/insights.router.test.ts b/apps/api/src/routes/insights.router.test.ts
deleted file mode 100644
index 7d43319ce..000000000
--- a/apps/api/src/routes/insights.router.test.ts
+++ /dev/null
@@ -1,387 +0,0 @@
-/**
- * Integration tests for the /insights/* REST routes.
- *
- * Auth is mocked (getClientByIdCached, verifyPassword, getCache).
- * ClickHouse and Postgres are real — uses the local Docker instance (pnpm dock:up).
- *
- * Fixture data (see apps/api/src/tests/setup.ts):
- * Alice — 3 events: session_start, page_view(/home), session_end — 2 days ago — Chrome / US
- * Charlie — 5 events: session_start, screen_view, page_view(/shop), purchase, session_end — 5 days ago — Firefox
- * 2 sessions (sess-charlie-1 5d ago, sess-charlie-2 10d ago)
- */
-
-import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
-
-// ─── Module mocks (hoisted before imports) ────────────────────────────────────
-
-// Mock only getClientByIdCached so auth can be controlled per-test.
-// importOriginal is fine here because real Postgres is available.
-vi.mock('@openpanel/db', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@openpanel/db')>();
- return { ...actual, getClientByIdCached: vi.fn() };
-});
-
-// Password verification is always truthy in tests.
-vi.mock('@openpanel/core', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@openpanel/core')>();
- return { ...actual, verifyPassword: vi.fn().mockResolvedValue(true) };
-});
-
-// Bypass Redis caching — no real ioredis connections in tests.
-// getRedisCache must return a truthy object; the rate limiter falls back to its
-// in-process counter when the fake client cannot serve a pipeline.
-vi.mock('@openpanel/redis', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@openpanel/redis')>();
- const fakeRedisClient = new Proxy(
- {},
- {
- get: (_t, p) =>
- p === 'status' ? 'ready' : vi.fn().mockResolvedValue(null),
- }
- );
- return {
- ...actual,
- getCache: async <T>(_key: string, _ttl: number, fn: () => Promise<T>) =>
- fn(),
- getRedisCache: vi.fn().mockReturnValue(fakeRedisClient),
- };
-});
-
-// ─── Imports (after mocks) ────────────────────────────────────────────────────
-
-import { ClientType, getClientByIdCached } from '@openpanel/db';
-import type { FastifyInstance } from 'fastify';
-import {
- FIXTURE,
- TEST_ORG_ID,
- TEST_PROJECT_ID,
-} from '../../../../test/global-setup';
-import { buildApp } from '../app';
-
-// ─── Test client constants ────────────────────────────────────────────────────
-
-const CLIENT_ID = '00000000-0000-0000-0000-000000000099';
-const CLIENT_SECRET = 'test-secret';
-
-const AUTH = {
- 'openpanel-client-id': CLIENT_ID,
- 'openpanel-client-secret': CLIENT_SECRET,
-};
-
-/** Minimal shape that satisfies validateExportRequest */
-const READ_CLIENT = {
- id: CLIENT_ID,
- type: ClientType.read,
- projectId: TEST_PROJECT_ID,
- organizationId: TEST_ORG_ID,
- secret: 'hashed-secret',
- name: 'Test Client',
- cors: null,
- description: '',
- ignoreCorsAndSecret: false,
- createdAt: new Date(),
- updatedAt: new Date(),
- project: null,
-};
-
-// ─── Lifecycle ────────────────────────────────────────────────────────────────
-
-let app: FastifyInstance;
-
-beforeAll(async () => {
- vi.mocked(getClientByIdCached).mockResolvedValue(READ_CLIENT as any);
- app = await buildApp({ testing: true });
- await app.ready();
-}, 30_000);
-
-afterAll(async () => {
- await app.close();
-}, 10_000);
-
-// ─── Helpers ──────────────────────────────────────────────────────────────────
-
-function get(path: string, headers: Record<string, string> = AUTH) {
- return app.inject({ method: 'GET', url: path, headers });
-}
-
-// ─── Auth ─────────────────────────────────────────────────────────────────────
-
-describe('auth', () => {
- it('returns 401 when no client-id header is present', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events/names`, {});
- expect(res.statusCode).toBe(401);
- });
-
- it('returns 401 when client-id is not a valid UUID', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events/names`, {
- 'openpanel-client-id': 'not-a-uuid',
- 'openpanel-client-secret': CLIENT_SECRET,
- });
- expect(res.statusCode).toBe(401);
- });
-
- it('returns 200 with valid credentials', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events/names`);
- expect(res.statusCode).toBe(200);
- });
-});
-
-// ─── Events ───────────────────────────────────────────────────────────────────
-
-describe('GET /insights/:projectId/events/names', () => {
- it('returns event_names array', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events/names`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- });
-
- it('includes events from fixture data', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events/names`);
- const body = res.json();
- expect(body).toContain('session_start');
- expect(body).toContain('page_view');
- expect(body).toContain('session_end');
- });
-});
-
-describe('GET /insights/:projectId/events', () => {
- it('returns events array', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- });
-
- it('respects limit parameter', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events?limit=2`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(body.length).toBeLessThanOrEqual(2);
- });
-
- it('filters by eventNames', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/events?eventNames=purchase`
- );
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(body.every((e: any) => e.name === 'purchase')).toBe(true);
- });
-
- it('returns 400 when limit is out of range', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events?limit=9999`);
- expect(res.statusCode).toBe(400);
- });
-});
-
-describe('GET /insights/:projectId/events/properties', () => {
- it('returns columns + properties arrays', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/events/properties`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body.columns)).toBe(true);
- expect(body.columns).toContain('path');
- expect(Array.isArray(body.properties)).toBe(true);
- });
-});
-
-describe('GET /insights/:projectId/events/property_values', () => {
- it('returns values for a known property', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/events/property_values?eventName=page_view&propertyKey=path`
- );
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body.values)).toBe(true);
- });
-
- it('returns 400 when required params are missing', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/events/property_values?eventName=page_view`
- );
- expect(res.statusCode).toBe(400);
- });
-});
-
-// ─── Profiles ─────────────────────────────────────────────────────────────────
-
-describe('GET /insights/:projectId/profiles', () => {
- it('returns profiles array', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/profiles`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- });
-
- it('includes fixture profiles', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/profiles`);
- const body = res.json();
- const emails = body.map((p: any) => p.email);
- expect(emails).toContain('[email protected]');
- expect(emails).toContain('[email protected]');
- });
-
- it('filters by browser via query params', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/profiles?browser=Firefox`
- );
- expect(res.statusCode).toBe(200);
- const body = res.json();
- // Charlie uses Firefox; Alice uses Chrome — only Charlie should appear
- const emails = body.map((p: any) => p.email);
- expect(emails).toContain('[email protected]');
- expect(emails).not.toContain('[email protected]');
- });
-});
-
-describe('GET /insights/:projectId/profiles/:profileId', () => {
- it('returns 404 for unknown profile', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/profiles/does-not-exist`
- );
- expect(res.statusCode).toBe(404);
- });
-
- it('returns profile data for known profile', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/profiles/${FIXTURE.profiles.alice}`
- );
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(body).toHaveProperty('profile');
- expect(body.profile.email).toBe('[email protected]');
- });
-});
-
-describe('GET /insights/:projectId/profiles/:profileId/sessions', () => {
- it('returns sessions for charlie', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/profiles/${FIXTURE.profiles.charlie}/sessions`
- );
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- expect(body.length).toBeGreaterThanOrEqual(1);
- });
-});
-
-// ─── Sessions ─────────────────────────────────────────────────────────────────
-
-describe('GET /insights/:projectId/sessions', () => {
- it('returns sessions array', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/sessions`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- });
-
- it('fixture has at least 3 sessions (alice-1, charlie-1, charlie-2)', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/sessions?limit=100`);
- const body = res.json();
- expect(body.length).toBeGreaterThanOrEqual(3);
- });
-});
-
-// ─── Analytics overview ───────────────────────────────────────────────────────
-
-describe('GET /insights/:projectId/overview', () => {
- it('returns analytics overview', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/overview`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- // Overview returns an object with at least some metrics
- expect(typeof body).toBe('object');
- });
-
- it('accepts interval param', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/overview?interval=day`);
- expect(res.statusCode).toBe(200);
- });
-
- it('returns 400 for invalid interval', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/overview?interval=invalid`
- );
- expect(res.statusCode).toBe(400);
- });
-});
-
-// ─── Funnel ───────────────────────────────────────────────────────────────────
-
-describe('GET /insights/:projectId/funnel', () => {
- it('returns funnel data for valid steps', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/funnel?steps=session_start&steps=session_end`
- );
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(typeof body).toBe('object');
- });
-
- it('returns 400 when fewer than 2 steps are provided', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/funnel?steps[]=session_start`
- );
- expect(res.statusCode).toBe(400);
- });
-
- it('returns 400 when steps param is missing entirely', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/funnel`);
- expect(res.statusCode).toBe(400);
- });
-});
-
-// ─── Pages ────────────────────────────────────────────────────────────────────
-
-describe('GET /insights/:projectId/pages/top', () => {
- it('returns top pages', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/pages/top`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- });
-});
-
-describe('GET /insights/:projectId/pages/entry_exit', () => {
- it('defaults to entry mode', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/pages/entry_exit`);
- expect(res.statusCode).toBe(200);
- });
-
- it('accepts mode=exit', async () => {
- const res = await get(
- `/insights/${TEST_PROJECT_ID}/pages/entry_exit?mode=exit`
- );
- expect(res.statusCode).toBe(200);
- });
-});
-
-// ─── Traffic ──────────────────────────────────────────────────────────────────
-
-describe('GET /insights/:projectId/traffic/referrers', () => {
- it('returns referrer breakdown', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/traffic/referrers`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- });
-});
-
-describe('GET /insights/:projectId/traffic/geo', () => {
- it('returns geo breakdown', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/traffic/geo`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- });
-});
-
-describe('GET /insights/:projectId/traffic/devices', () => {
- it('returns device breakdown', async () => {
- const res = await get(`/insights/${TEST_PROJECT_ID}/traffic/devices`);
- expect(res.statusCode).toBe(200);
- const body = res.json();
- expect(Array.isArray(body)).toBe(true);
- });
-});
diff --git a/apps/api/src/routes/insights.router.ts b/apps/api/src/routes/insights.router.ts
deleted file mode 100644
index 79bbb7a1e..000000000
--- a/apps/api/src/routes/insights.router.ts
+++ /dev/null
@@ -1,559 +0,0 @@
-import { Prisma } from '@openpanel/db';
-import type { FastifyRequest } from 'fastify';
-import type { FastifyPluginAsyncZodOpenApi } from 'fastify-zod-openapi';
-import { z } from 'zod';
-import * as c from '@/controllers/insights.controller';
-import {
- overviewColumns,
- zActiveUsersQuery,
- zDateRange,
- zDeviceQuery,
- zEntryExitQuery,
- zEventsQuery,
- zEventPropertiesQuery,
- zFunnelQuery,
- zGeoQuery,
- zGetGroupQuery,
- zGetMetricsQuery,
- zGetProfileQuery,
- zGetTopPagesQuery,
- zGroupsQuery,
- zGscLimitQuery,
- zGscOpportunitiesQuery,
- zGscOverviewQuery,
- zGscPageDetailsQuery,
- zGscQueryDetailsQuery,
- zOverviewGenericQuerystring,
- zOverviewQuery,
- zPagePerfQuery,
- zProfilesQuery,
- zProfileSessionsQuery,
- zPropertyValuesQuery,
- zReferrerQuery,
- zSessionsQuery,
- zUserFlowQuery,
-} from '@/controllers/insights.controller';
-import { validateExportRequest } from '@/utils/auth';
-import { parseQueryString } from '@/utils/parse-zod-query-string';
-import { activateRateLimiter } from '@/utils/rate-limiter';
-
-const projectIdParam = z.object({ projectId: z.string() });
-const profileParam = z.object({ projectId: z.string(), profileId: z.string() });
-const groupParam = z.object({ projectId: z.string(), groupId: z.string() });
-const reportParam = z.object({ projectId: z.string(), reportId: z.string() });
-
-const TAGS = ['Insights'] as const;
-
-const insightsRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
- await activateRateLimiter({ fastify, max: 100, timeWindow: '10 seconds' });
-
- fastify.addHook('preHandler', async (req: FastifyRequest, reply) => {
- try {
- const client = await validateExportRequest(req.headers);
- req.client = client;
- } catch (e) {
- if (e instanceof Prisma.PrismaClientKnownRequestError) {
- return reply.status(401).send({ error: 'Unauthorized', message: 'Client ID seems to be malformed' });
- }
- if (e instanceof Error) {
- return reply.status(401).send({ error: 'Unauthorized', message: e.message });
- }
- return reply.status(401).send({ error: 'Unauthorized', message: 'Unexpected error' });
- }
-
- });
-
- // Run parseQueryString before Fastify schema validation so coercion
- // (string→number, JSON-encoded arrays, etc.) is handled automatically.
- fastify.addHook('preValidation', async (req) => {
- req.query = parseQueryString(req.query as Record<string, unknown>) as typeof req.query;
- });
-
- // ---------------------------------------------------------------------------
- // Analytics — overview
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/overview',
- schema: {
- tags: TAGS,
- description: 'Get an overview of key metrics for the project (sessions, pageviews, bounce rate, duration).',
- params: projectIdParam,
- querystring: zOverviewQuery,
- },
- handler: c.getOverview,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/active_users',
- schema: {
- tags: TAGS,
- description: 'Get rolling active user counts over the last N days.',
- params: projectIdParam,
- querystring: zActiveUsersQuery,
- },
- handler: c.getActiveUsers,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/retention',
- schema: {
- tags: TAGS,
- description: 'Get weekly retention series data.',
- params: projectIdParam,
- },
- handler: c.getRetentionSeries,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/retention/cohort',
- schema: {
- tags: TAGS,
- description: 'Get retention cohort data.',
- params: projectIdParam,
- },
- handler: c.getRetentionCohort,
- });
-
- // ---------------------------------------------------------------------------
- // Analytics — pages
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/pages/top',
- schema: {
- tags: TAGS,
- description: 'Get the top pages by pageviews for the given date range.',
- params: projectIdParam,
- querystring: zDateRange,
- },
- handler: c.getTopPages,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/pages/entry_exit',
- schema: {
- tags: TAGS,
- description: 'Get entry or exit pages ranked by session count.',
- params: projectIdParam,
- querystring: zEntryExitQuery,
- },
- handler: c.getEntryExitPages,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/pages/performance',
- schema: {
- tags: TAGS,
- description: 'Get page-level performance metrics (bounce rate, avg duration, sessions).',
- params: projectIdParam,
- querystring: zPagePerfQuery,
- },
- handler: c.getPagePerformance,
- });
-
- // ---------------------------------------------------------------------------
- // Analytics — metrics overview (legacy insights routes)
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/metrics',
- schema: {
- tags: TAGS,
- description: 'Get aggregated website metrics including sessions, pageviews, and bounce rate.',
- params: projectIdParam,
- querystring: zGetMetricsQuery,
- },
- handler: c.getMetrics,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/live',
- schema: {
- tags: TAGS,
- description: 'Get the current number of live (active) visitors.',
- params: projectIdParam,
- },
- handler: c.getLiveVisitors,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/pages',
- schema: {
- tags: TAGS,
- description: 'Get top pages with pageview counts for the selected date range.',
- params: projectIdParam,
- querystring: zGetTopPagesQuery,
- },
- handler: c.getPages,
- });
-
- for (const column of overviewColumns) {
- fastify.route({
- method: 'GET',
- url: `/:projectId/${column}`,
- schema: {
- tags: TAGS,
- description: `Get top values for the "${column}" dimension.`,
- params: projectIdParam,
- querystring: zOverviewGenericQuerystring,
- },
- handler: c.getOverviewGeneric(column),
- });
- }
-
- // ---------------------------------------------------------------------------
- // Analytics — funnel
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/funnel',
- schema: {
- tags: TAGS,
- description: 'Get funnel conversion rates for a sequence of events.',
- params: projectIdParam,
- querystring: zFunnelQuery,
- },
- handler: c.getFunnel,
- });
-
- // ---------------------------------------------------------------------------
- // Analytics — traffic
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/traffic/referrers',
- schema: {
- tags: TAGS,
- description: 'Get traffic breakdown by referrer source.',
- params: projectIdParam,
- querystring: zReferrerQuery,
- },
- handler: c.getTrafficReferrers,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/traffic/geo',
- schema: {
- tags: TAGS,
- description: 'Get traffic breakdown by geographic dimension (country, region, city).',
- params: projectIdParam,
- querystring: zGeoQuery,
- },
- handler: c.getTrafficGeo,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/traffic/devices',
- schema: {
- tags: TAGS,
- description: 'Get traffic breakdown by device type, browser, or OS.',
- params: projectIdParam,
- querystring: zDeviceQuery,
- },
- handler: c.getTrafficDevices,
- });
-
- // ---------------------------------------------------------------------------
- // Analytics — user flow & engagement
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/user_flow',
- schema: {
- tags: TAGS,
- description: 'Get user flow paths before, after, or between specified events.',
- params: projectIdParam,
- querystring: zUserFlowQuery,
- },
- handler: c.getUserFlow,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/engagement',
- schema: {
- tags: TAGS,
- description: 'Get engagement metrics for the project.',
- params: projectIdParam,
- },
- handler: c.getEngagement,
- });
-
- // ---------------------------------------------------------------------------
- // Events
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/events',
- schema: {
- tags: TAGS,
- description: 'Query events with optional filters for date range, profile, and properties.',
- params: projectIdParam,
- querystring: zEventsQuery,
- },
- handler: c.queryEvents,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/events/names',
- schema: {
- tags: TAGS,
- description: 'List all distinct event names tracked in the project.',
- params: projectIdParam,
- },
- handler: c.listEventNames,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/events/properties',
- schema: {
- tags: TAGS,
- description: 'List all property keys for a given event name.',
- params: projectIdParam,
- querystring: zEventPropertiesQuery,
- },
- handler: c.listEventProperties,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/events/property_values',
- schema: {
- tags: TAGS,
- description: 'Get the top values for a specific event property key.',
- params: projectIdParam,
- querystring: zPropertyValuesQuery,
- },
- handler: c.getEventPropertyValues,
- });
-
- // ---------------------------------------------------------------------------
- // Profiles
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/profiles',
- schema: {
- tags: TAGS,
- description: 'Search and filter user profiles.',
- params: projectIdParam,
- querystring: zProfilesQuery,
- },
- handler: c.findProfiles,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/profiles/:profileId',
- schema: {
- tags: TAGS,
- description: 'Get a single user profile with their recent events.',
- params: profileParam,
- querystring: zGetProfileQuery,
- },
- handler: c.getProfile,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/profiles/:profileId/sessions',
- schema: {
- tags: TAGS,
- description: 'Get sessions for a specific user profile.',
- params: profileParam,
- querystring: zProfileSessionsQuery,
- },
- handler: c.getProfileSessions,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/profiles/:profileId/metrics',
- schema: {
- tags: TAGS,
- description: 'Get aggregated metrics for a specific user profile.',
- params: profileParam,
- },
- handler: c.getProfileMetrics,
- });
-
- // ---------------------------------------------------------------------------
- // Sessions
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/sessions',
- schema: {
- tags: TAGS,
- description: 'Query sessions with optional filters.',
- params: projectIdParam,
- querystring: zSessionsQuery,
- },
- handler: c.querySessions,
- });
-
- // ---------------------------------------------------------------------------
- // Groups
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/groups/types',
- schema: {
- tags: TAGS,
- description: 'List all group types defined in the project.',
- params: projectIdParam,
- },
- handler: c.listGroupTypes,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/groups',
- schema: {
- tags: TAGS,
- description: 'Search and filter groups.',
- params: projectIdParam,
- querystring: zGroupsQuery,
- },
- handler: c.findGroups,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/groups/:groupId',
- schema: {
- tags: TAGS,
- description: 'Get a single group with its members.',
- params: groupParam,
- querystring: zGetGroupQuery,
- },
- handler: c.getGroup,
- });
-
- // ---------------------------------------------------------------------------
- // Dashboards & reports
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/reports/:reportId/data',
- schema: {
- tags: TAGS,
- description: 'Get the data for a saved report.',
- params: reportParam,
- },
- handler: c.getReportData,
- });
-
- // ---------------------------------------------------------------------------
- // Google Search Console
- // ---------------------------------------------------------------------------
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/gsc/overview',
- schema: {
- tags: TAGS,
- description: 'Get a Google Search Console performance overview (clicks, impressions, CTR, position).',
- params: projectIdParam,
- querystring: zGscOverviewQuery,
- },
- handler: c.gscOverview,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/gsc/pages',
- schema: {
- tags: TAGS,
- description: 'Get top pages from Google Search Console.',
- params: projectIdParam,
- querystring: zGscLimitQuery,
- },
- handler: c.gscPages,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/gsc/pages/details',
- schema: {
- tags: TAGS,
- description: 'Get detailed GSC metrics for a specific page URL.',
- params: projectIdParam,
- querystring: zGscPageDetailsQuery,
- },
- handler: c.gscPageDetails,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/gsc/queries',
- schema: {
- tags: TAGS,
- description: 'Get top search queries from Google Search Console.',
- params: projectIdParam,
- querystring: zGscLimitQuery,
- },
- handler: c.gscQueries,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/gsc/queries/details',
- schema: {
- tags: TAGS,
- description: 'Get detailed GSC metrics for a specific search query.',
- params: projectIdParam,
- querystring: zGscQueryDetailsQuery,
- },
- handler: c.gscQueryDetails,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/gsc/queries/opportunities',
- schema: {
- tags: TAGS,
- description: 'Get GSC query opportunities (high impressions, low CTR).',
- params: projectIdParam,
- querystring: zGscOpportunitiesQuery,
- },
- handler: c.gscQueryOpportunities,
- });
-
- fastify.route({
- method: 'GET',
- url: '/:projectId/gsc/cannibalization',
- schema: {
- tags: TAGS,
- description: 'Detect keyword cannibalization across pages in Google Search Console.',
- params: projectIdParam,
- querystring: zDateRange,
- },
- handler: c.gscCannibalization,
- });
-};
-
-export default insightsRouter;
diff --git a/apps/api/src/routes/live.router.ts b/apps/api/src/routes/live.router.ts
deleted file mode 100644
index d9181ef80..000000000
--- a/apps/api/src/routes/live.router.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import * as controller from '@/controllers/live.controller';
-import fastifyWS from '@fastify/websocket';
-import type { FastifyPluginCallback } from 'fastify';
-
-const liveRouter: FastifyPluginCallback = async (fastify) => {
- fastify.register(fastifyWS);
-
- fastify.register(async (fastify) => {
- fastify.get(
- '/organization/:organizationId',
- { websocket: true },
- controller.wsOrganizationEvents,
- );
- fastify.get(
- '/visitors/:projectId',
- { websocket: true },
- controller.wsVisitors,
- );
- fastify.get(
- '/events/:projectId',
- { websocket: true },
- controller.wsProjectEvents,
- );
- fastify.get(
- '/notifications/:projectId',
- { websocket: true },
- controller.wsProjectNotifications,
- );
- });
-};
-
-export default liveRouter;
diff --git a/apps/api/src/routes/manage.router.ts b/apps/api/src/routes/manage.router.ts
deleted file mode 100644
index 815028509..000000000
--- a/apps/api/src/routes/manage.router.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import { Prisma, resolveClientProjectId } from '@openpanel/db';
-import type { FastifyRequest } from 'fastify';
-import type { FastifyPluginAsyncZodOpenApi } from 'fastify-zod-openapi';
-import { z } from 'zod';
-import * as controller from '@/controllers/manage.controller';
-import { listDashboards, listReports } from '@/controllers/insights.controller';
-import {
- zCreateClient,
- zCreateProject,
- zCreateReference,
- zUpdateClient,
- zUpdateProject,
- zUpdateReference,
-} from '@/controllers/manage.controller';
-import { validateManageRequest } from '@/utils/auth';
-import { activateRateLimiter } from '@/utils/rate-limiter';
-
-const idParam = z.object({ id: z.string() });
-
-const manageRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
- await activateRateLimiter({
- fastify,
- max: 20,
- timeWindow: '10 seconds',
- });
-
- fastify.addHook('preHandler', async (req: FastifyRequest, reply) => {
- try {
- const client = await validateManageRequest(req.headers);
- req.client = client;
- } catch (e) {
- if (e instanceof Prisma.PrismaClientKnownRequestError) {
- return reply.status(401).send({
- error: 'Unauthorized',
- message: 'Client ID seems to be malformed',
- });
- }
-
- if (e instanceof Error) {
- return reply
- .status(401)
- .send({ error: 'Unauthorized', message: e.message });
- }
-
- return reply
- .status(401)
- .send({ error: 'Unauthorized', message: 'Unexpected error' });
- }
-
- // Validate :projectId URL param belongs to this client's organization.
- const client = req.client!;
- const params = req.params as { projectId?: string };
- if (params.projectId) {
- try {
- await resolveClientProjectId({
- clientType: 'root',
- clientProjectId: null,
- organizationId: client.organizationId,
- inputProjectId: params.projectId,
- });
- } catch {
- return reply.status(403).send({ error: 'Forbidden', message: 'Project does not belong to your organization' });
- }
- }
- });
-
- // Projects routes
- fastify.route({
- method: 'GET',
- url: '/projects',
- schema: { tags: ['Manage'], description: 'List all projects for the organization.' },
- handler: controller.listProjects,
- });
-
- fastify.route({
- method: 'GET',
- url: '/projects/:id',
- schema: { params: idParam, tags: ['Manage'], description: 'Get a single project by ID.' },
- handler: controller.getProject,
- });
-
- fastify.route({
- method: 'POST',
- url: '/projects',
- schema: { body: zCreateProject, tags: ['Manage'], description: 'Create a new project and its first write client.' },
- handler: controller.createProject,
- });
-
- fastify.route({
- method: 'PATCH',
- url: '/projects/:id',
- schema: { params: idParam, body: zUpdateProject, tags: ['Manage'], description: 'Update project settings (name, domain, CORS, tracking options).' },
- handler: controller.updateProject,
- });
-
- fastify.route({
- method: 'DELETE',
- url: '/projects/:id',
- schema: { params: idParam, tags: ['Manage'], description: 'Soft-delete a project (scheduled for removal in 24 hours).' },
- handler: controller.deleteProject,
- });
-
- // Clients routes
- fastify.route({
- method: 'GET',
- url: '/clients',
- schema: { tags: ['Manage'], description: 'List all API clients for the organization, optionally filtered by project.' },
- handler: controller.listClients,
- });
-
- fastify.route({
- method: 'GET',
- url: '/clients/:id',
- schema: { params: idParam, tags: ['Manage'], description: 'Get a single API client by ID.' },
- handler: controller.getClient,
- });
-
- fastify.route({
- method: 'POST',
- url: '/clients',
- schema: { body: zCreateClient, tags: ['Manage'], description: 'Create a new API client (read, write, or root type) and return its generated secret.' },
- handler: controller.createClient,
- });
-
- fastify.route({
- method: 'PATCH',
- url: '/clients/:id',
- schema: { params: idParam, body: zUpdateClient, tags: ['Manage'], description: 'Update an API client name.' },
- handler: controller.updateClient,
- });
-
- fastify.route({
- method: 'DELETE',
- url: '/clients/:id',
- schema: { params: idParam, tags: ['Manage'], description: 'Delete an API client.' },
- handler: controller.deleteClient,
- });
-
- // References routes
- fastify.route({
- method: 'GET',
- url: '/references',
- schema: { tags: ['Manage'], description: 'List annotation references for a project.' },
- handler: controller.listReferences,
- });
-
- fastify.route({
- method: 'GET',
- url: '/references/:id',
- schema: { params: idParam, tags: ['Manage'], description: 'Get a single annotation reference by ID.' },
- handler: controller.getReference,
- });
-
- fastify.route({
- method: 'POST',
- url: '/references',
- schema: { body: zCreateReference, tags: ['Manage'] },
- handler: controller.createReference,
- });
-
- fastify.route({
- method: 'PATCH',
- url: '/references/:id',
- schema: { params: idParam, body: zUpdateReference, tags: ['Manage'] },
- handler: controller.updateReference,
- });
-
- fastify.route({
- method: 'DELETE',
- url: '/references/:id',
- schema: { params: idParam, tags: ['Manage'] },
- handler: controller.deleteReference,
- });
-
- // Dashboards & reports
- fastify.route({
- method: 'GET',
- url: '/projects/:projectId/dashboards',
- schema: {
- params: z.object({ projectId: z.string() }),
- tags: ['Manage'],
- description: 'List all dashboards for a project.',
- },
- handler: listDashboards,
- });
-
- fastify.route({
- method: 'GET',
- url: '/projects/:projectId/dashboards/:dashboardId/reports',
- schema: {
- params: z.object({ projectId: z.string(), dashboardId: z.string() }),
- tags: ['Manage'],
- description: 'List all reports in a dashboard.',
- },
- handler: listReports,
- });
-};
-
-export default manageRouter;
diff --git a/apps/api/src/routes/mcp.router.ts b/apps/api/src/routes/mcp.router.ts
deleted file mode 100644
index c3b6a7175..000000000
--- a/apps/api/src/routes/mcp.router.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-// Dissolved into @openpanel/core's mcp module (M5-007): auth, tool
-// dispatch and the streamable-HTTP protocol handling moved to
-// packages/core/src/modules/mcp/mcp.service.ts#handleStatelessMcpRequest.
-// This router stays (DELEGATE PATTERN) for rate limiting and the generic
-// 500 catch — everything protocol-shaped is core's.
-//
-// ADR-015 entry 2 (accepted): MCP is stateless-POST only. GET/SSE, DELETE
-// and the Redis session store (`mcp:session:<uuid>`, the `Mcp-Session-Id`
-// header) are REMOVED here, not delegated — MCP is the one module this wave
-// is allowed to change the endpoint surface of.
-import { handleMcpRequest } from '@openpanel/core';
-import type { FastifyPluginAsync } from 'fastify';
-import { activateRateLimiter } from '@/utils/rate-limiter';
-
-const mcpRouter: FastifyPluginAsync = async (fastify) => {
- await activateRateLimiter({ fastify, max: 60, timeWindow: '1 minute' });
-
- /**
- * POST /mcp
- *
- * Every request authenticates via ?token= query param or Authorization:
- * Bearer and runs on a fresh, per-request MCP server — no session, no
- * sticky-instance requirement.
- */
- await fastify.post('/', async (req, reply) => {
- try {
- const { status, body } = await handleMcpRequest(
- req.query as Record<string, unknown>,
- req.headers.authorization,
- req.body
- );
- return reply.status(status).send(body);
- } catch (err) {
- req.log.error({ err }, 'MCP request processing error');
- return reply.status(500).send({ error: 'Internal server error' });
- }
- });
-};
-
-export default mcpRouter;
diff --git a/apps/api/src/routes/misc.router.ts b/apps/api/src/routes/misc.router.ts
deleted file mode 100644
index 5d4ce8b45..000000000
--- a/apps/api/src/routes/misc.router.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { FastifyPluginCallback } from 'fastify';
-import * as controller from '@/controllers/misc.controller';
-
-// `/og/clear` and `/favicon/clear` are removed, not ported (M7-008,
-// ADR-015 entry #6: RULED + DEAD — `docs/ANSWERS.md` §1.4 confirms nothing
-// depends on them).
-const miscRouter: FastifyPluginCallback = async (fastify) => {
- fastify.route({
- method: 'POST',
- url: '/ping',
- handler: controller.ping,
- });
-
- fastify.route({
- method: 'GET',
- url: '/stats',
- handler: controller.stats,
- });
-
- fastify.route({
- method: 'GET',
- url: '/favicon',
- handler: controller.getFavicon,
- });
-
- fastify.route({
- method: 'GET',
- url: '/og',
- handler: controller.getOgImage,
- });
-
- fastify.route({
- method: 'GET',
- url: '/geo',
- handler: controller.getGeo,
- });
-};
-
-export default miscRouter;
diff --git a/apps/api/src/routes/oauth-callback.router.ts b/apps/api/src/routes/oauth-callback.router.ts
deleted file mode 100644
index 230ade477..000000000
--- a/apps/api/src/routes/oauth-callback.router.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import * as controller from '@/controllers/oauth-callback.controller';
-import type { FastifyPluginCallback } from 'fastify';
-
-const router: FastifyPluginCallback = async (fastify) => {
- fastify.route({
- method: 'GET',
- url: '/github/callback',
- handler: controller.githubCallback,
- });
- fastify.route({
- method: 'GET',
- url: '/google/callback',
- handler: controller.googleCallback,
- });
-};
-
-export default router;
diff --git a/apps/api/src/routes/profile.router.ts b/apps/api/src/routes/profile.router.ts
deleted file mode 100644
index d1d03d5ac..000000000
--- a/apps/api/src/routes/profile.router.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import type { FastifyPluginAsyncZodOpenApi } from 'fastify-zod-openapi';
-import * as controller from '@/controllers/profile.controller';
-import { clientHook } from '@/hooks/client.hook';
-import { isBotHook } from '@/hooks/is-bot.hook';
-import { subscriptionHook } from '@/hooks/subscription.hook';
-
-const profileRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
- fastify.addHook('preHandler', clientHook);
- fastify.addHook('preHandler', isBotHook);
- fastify.addHook('preHandler', subscriptionHook);
-
- fastify.route({
- method: 'POST',
- url: '/',
- schema: {
- tags: ['Profile'],
- description: 'Identify or update a user profile.',
- },
- handler: controller.updateProfile,
- });
-
- fastify.route({
- method: 'POST',
- url: '/increment',
- schema: {
- tags: ['Profile'],
- description: 'Increment a numeric property on a user profile.',
- },
- handler: controller.incrementProfileProperty,
- });
-
- fastify.route({
- method: 'POST',
- url: '/decrement',
- schema: {
- tags: ['Profile'],
- description: 'Decrement a numeric property on a user profile.',
- },
- handler: controller.decrementProfileProperty,
- });
-};
-
-export default profileRouter;
diff --git a/apps/api/src/routes/tools.router.ts b/apps/api/src/routes/tools.router.ts
deleted file mode 100644
index 2507a037c..000000000
--- a/apps/api/src/routes/tools.router.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import * as controller from '@/controllers/tools.controller';
-import type { FastifyPluginCallback } from 'fastify';
-
-const toolsRouter: FastifyPluginCallback = async (fastify) => {
- fastify.route({
- method: 'GET',
- url: '/site-checker',
- schema: { hide: true },
- handler: controller.siteChecker,
- });
-
- fastify.route({
- method: 'GET',
- url: '/ip-lookup',
- schema: { hide: true },
- handler: controller.ipLookup,
- });
-};
-
-export default toolsRouter;
diff --git a/apps/api/src/routes/track.router.ts b/apps/api/src/routes/track.router.ts
deleted file mode 100644
index 44d085620..000000000
--- a/apps/api/src/routes/track.router.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { zTrackHandlerPayload } from '@openpanel/validation';
-import type { FastifyPluginAsyncZodOpenApi } from 'fastify-zod-openapi';
-import { z } from 'zod';
-import { fetchDeviceId, handler } from '@/controllers/track.controller';
-import { clientHook } from '@/hooks/client.hook';
-import { duplicateHook } from '@/hooks/duplicate.hook';
-import { isBotHook } from '@/hooks/is-bot.hook';
-import { subscriptionHook } from '@/hooks/subscription.hook';
-
-const trackRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
- fastify.addHook('preValidation', duplicateHook);
- fastify.addHook('preHandler', clientHook);
- fastify.addHook('preHandler', isBotHook);
- fastify.addHook('preHandler', subscriptionHook);
-
- await fastify.route({
- method: 'POST',
- url: '/',
- schema: {
- body: zTrackHandlerPayload.and(
- z.object({
- clientId: z.string().optional(),
- clientSecret: z.string().optional(),
- })
- ),
- tags: ['Track'],
- description:
- 'Ingest a tracking event (track, identify, group, increment, decrement, replay).',
- response: {
- 200: z.object({
- deviceId: z.string(),
- sessionId: z.string(),
- }),
- },
- },
- handler,
- });
-
- await fastify.route({
- method: 'GET',
- url: '/device-id',
- schema: {
- tags: ['Track'],
- description:
- 'Get or generate a stable device ID and session ID for the current visitor.',
- response: {
- 200: z.object({
- deviceId: z.string(),
- sessionId: z.string(),
- message: z.string().optional(),
- }),
- },
- },
- handler: fetchDeviceId,
- });
-};
-
-export default trackRouter;
diff --git a/apps/api/src/routes/webhook.router.ts b/apps/api/src/routes/webhook.router.ts
deleted file mode 100644
index dbe34658d..000000000
--- a/apps/api/src/routes/webhook.router.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import * as controller from '@/controllers/webhook.controller';
-import type { FastifyPluginCallback } from 'fastify';
-
-const webhookRouter: FastifyPluginCallback = async (fastify) => {
- fastify.route({
- method: 'GET',
- url: '/slack',
- handler: controller.slackWebhook,
- });
- fastify.route({
- method: 'POST',
- url: '/polar',
- handler: controller.polarWebhook,
- config: {
- rawBody: true,
- },
- });
-};
-
-export default webhookRouter;
diff --git a/apps/api/src/utils/auth.ts b/apps/api/src/utils/auth.ts
deleted file mode 100644
index 8a5f4f37a..000000000
--- a/apps/api/src/utils/auth.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import {
- type IngestAuthErrorPayload,
- validateIngestRequest,
- verifyPassword,
-} from '@openpanel/core';
-import type { IServiceClientWithProject } from '@openpanel/db';
-import { ClientType, getClientByIdCached } from '@openpanel/db';
-import type {
- DeprecatedPostEventPayload,
- ITrackHandlerPayload,
-} from '@openpanel/validation';
-import type { FastifyRequest, RawRequestDefaultExpression } from 'fastify';
-
-// `validateSdkRequest` dissolved into @openpanel/core's ingest module
-// (M8-002): the rules live in modules/ingest/src/client-auth.ts and this is
-// the DELEGATE, kept so the Fastify hook keeps its signature and its
-// `req.clientSecretAuth` side channel. The other three validators stay here —
-// they belong to the client module, not to ingest, and no task has moved them.
-//
-// The error class stays HERE on purpose. core returns a refusal rather than
-// throwing, so the stack trace is captured in this bundle chunk instead of in
-// the ~11 MB core chunk whose ~20 MB source map `source-map-support` would
-// then parse — ~1.2s, once, on the first failed ingest auth.
-export class SdkAuthError extends Error {
- payload: IngestAuthErrorPayload;
-
- constructor(message: string, payload: IngestAuthErrorPayload) {
- super(message);
- this.name = 'SdkAuthError';
- this.message = message;
- this.payload = payload;
- }
-}
-
-export async function validateSdkRequest(
- req: FastifyRequest<{
- Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
- }>
-): Promise<IServiceClientWithProject> {
- const outcome = await validateIngestRequest({
- headers: req.headers,
- clientIp: req.clientIp,
- body: req.body,
- });
-
- // V1 set this at parse time, before validation could refuse — so it is set
- // on both branches.
- if (outcome.secretPresented) {
- req.clientSecretAuth = true;
- }
-
- if (!outcome.ok) {
- throw new SdkAuthError(outcome.message, outcome.payload);
- }
-
- return outcome.client;
-}
-
-export async function validateExportRequest(
- headers: RawRequestDefaultExpression['headers']
-): Promise<IServiceClientWithProject> {
- const clientId = headers['openpanel-client-id'] as string;
- const clientSecret = (headers['openpanel-client-secret'] as string) || '';
-
- if (
- !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(
- clientId
- )
- ) {
- throw new Error('Export: Client ID must be a valid UUIDv4');
- }
-
- const client = await getClientByIdCached(clientId);
-
- if (!client) {
- throw new Error('Export: Invalid client id');
- }
-
- if (!client.secret) {
- throw new Error('Export: Client has no secret');
- }
-
- if (client.type === ClientType.write) {
- throw new Error('Export: Client is not allowed to export');
- }
-
- if (!(await verifyPassword(clientSecret, client.secret))) {
- throw new Error('Export: Invalid client secret');
- }
-
- return client;
-}
-
-export async function validateImportRequest(
- headers: RawRequestDefaultExpression['headers']
-): Promise<IServiceClientWithProject> {
- const clientId = headers['openpanel-client-id'] as string;
- const clientSecret = (headers['openpanel-client-secret'] as string) || '';
-
- if (
- !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(
- clientId
- )
- ) {
- throw new Error('Import: Client ID must be a valid UUIDv4');
- }
-
- const client = await getClientByIdCached(clientId);
-
- if (!client) {
- throw new Error('Import: Invalid client id');
- }
-
- if (!client.secret) {
- throw new Error('Import: Client has no secret');
- }
-
- if (client.type === ClientType.write) {
- throw new Error('Import: Client is not allowed to import');
- }
-
- if (!(await verifyPassword(clientSecret, client.secret))) {
- throw new Error('Import: Invalid client secret');
- }
-
- return client;
-}
-
-export async function validateManageRequest(
- headers: RawRequestDefaultExpression['headers']
-): Promise<IServiceClientWithProject> {
- const clientId = headers['openpanel-client-id'] as string;
- const clientSecret = (headers['openpanel-client-secret'] as string) || '';
-
- if (
- !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(
- clientId
- )
- ) {
- throw new Error('Manage: Client ID must be a valid UUIDv4');
- }
-
- const client = await getClientByIdCached(clientId);
-
- if (!client) {
- throw new Error('Manage: Invalid client id');
- }
-
- if (!client.secret) {
- throw new Error('Manage: Client has no secret');
- }
-
- if (client.type !== ClientType.root) {
- throw new Error(
- 'Manage: Only root clients are allowed to manage resources'
- );
- }
-
- if (!(await verifyPassword(clientSecret, client.secret))) {
- throw new Error('Manage: Invalid client secret');
- }
-
- return client;
-}
diff --git a/apps/api/src/utils/errors.ts b/apps/api/src/utils/errors.ts
deleted file mode 100644
index b6bb8e41e..000000000
--- a/apps/api/src/utils/errors.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-export class LogError extends Error {
- public readonly payload?: Record<string, unknown>;
-
- constructor(
- message: string,
- payload?: Record<string, unknown>,
- options?: ErrorOptions
- ) {
- super(message, options);
- this.name = 'LogError';
- this.payload = payload;
-
- Object.setPrototypeOf(this, new.target.prototype);
- }
-}
-
-export class HttpError extends Error {
- public readonly status: number;
- public readonly fingerprint?: string;
- public readonly extra?: Record<string, unknown>;
- public readonly error?: Error | unknown;
- constructor(
- message: string,
- options?: {
- status?: number;
- fingerprint?: string;
- extra?: Record<string, unknown>;
- error?: Error | unknown;
- }
- ) {
- super(message);
- this.name = 'HttpError';
- this.status = options?.status ?? 500;
- this.fingerprint = options?.fingerprint;
- this.extra = options?.extra;
- this.error = options?.error;
- Object.setPrototypeOf(this, new.target.prototype);
- }
-}
-
-export interface NormalizedError {
- status: number;
- code: string | undefined;
- message: string;
- errorName: string;
-}
-
-export function normalizeError(error: unknown): NormalizedError {
- if (error instanceof Error) {
- const meta = error as Error & {
- statusCode?: unknown;
- status?: unknown;
- code?: unknown;
- };
- const status =
- typeof meta.statusCode === 'number'
- ? meta.statusCode
- : typeof meta.status === 'number'
- ? meta.status
- : 500;
- return {
- status,
- code: typeof meta.code === 'string' ? meta.code : undefined,
- message: error.message || 'Internal server error',
- errorName: error.name || 'Error',
- };
- }
-
- // Plain object thrown (e.g. `throw { statusCode: 400, message: '...' }`).
- if (typeof error === 'object' && error !== null) {
- const e = error as Record<string, unknown>;
- return {
- status: typeof e.statusCode === 'number' ? e.statusCode : 500,
- code: typeof e.code === 'string' ? e.code : undefined,
- message:
- typeof e.message === 'string' ? e.message : 'Internal server error',
- errorName: typeof e.name === 'string' ? e.name : 'Error',
- };
- }
-
- if (typeof error === 'string') {
- return { status: 500, code: undefined, message: error, errorName: 'Error' };
- }
-
- // null, undefined, number, boolean, symbol, bigint
- return {
- status: 500,
- code: undefined,
- message: 'Internal server error',
- errorName: 'Error',
- };
-}
diff --git a/apps/api/src/utils/graceful-shutdown.ts b/apps/api/src/utils/graceful-shutdown.ts
deleted file mode 100644
index b8364341a..000000000
--- a/apps/api/src/utils/graceful-shutdown.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import { ch, db } from '@openpanel/db';
-import {
- cronQueue,
- disconnectKafka,
- notificationQueue,
- sessionsQueue,
-} from '@openpanel/queue';
-import {
- getRedisCache,
- getRedisPub,
- getRedisQueue,
- getRedisSub,
-} from '@openpanel/redis';
-import type { FastifyInstance } from 'fastify';
-import { logger } from './logger';
-
-let shuttingDown = false;
-
-export function setShuttingDown(value: boolean) {
- shuttingDown = value;
-}
-
-export function isShuttingDown() {
- return shuttingDown;
-}
-
-// Graceful shutdown handler
-export async function shutdown(
- fastify: FastifyInstance,
- signal: string,
- exitCode = 0
-) {
- if (isShuttingDown()) {
- logger.warn({ signal }, 'Shutdown already in progress, ignoring signal');
- return;
- }
-
- logger.info({ signal }, 'Starting graceful shutdown');
-
- setShuttingDown(true);
-
- // Hard deadline: if any close() below hangs (Kafka producer stuck,
- // Redis still connecting, BullMQ wait), force-exit before Docker's
- // stop_grace_period elapses. Without this the container can sit in
- // "Stopping" until SIGKILL (exit 137) and look like a real crash.
- const forceExitMs = Number(process.env.SHUTDOWN_FORCE_EXIT_MS || '15000');
- const forceExit = setTimeout(() => {
- logger.error(
- { signal, forceExitMs },
- 'Graceful shutdown timed out — forcing exit'
- );
- process.exit(exitCode);
- }, forceExitMs);
- forceExit.unref();
-
- // Step 1: Wait for load balancer to stop sending traffic (matches preStop sleep)
- const gracePeriod = Number(process.env.SHUTDOWN_GRACE_PERIOD_MS || '5000');
- await new Promise((resolve) => setTimeout(resolve, gracePeriod));
-
- // Step 2: Close Fastify to drain in-flight requests
- try {
- await fastify.close();
- logger.info('Fastify server closed');
- } catch (error) {
- logger.error({ err: error }, 'Error closing Fastify server');
- }
-
- // Step 3: Close database connections
- try {
- await db.$disconnect();
- logger.info('Database connection closed');
- } catch (error) {
- logger.error({ err: error }, 'Error closing database connection');
- }
-
- // Step 4: Close ClickHouse connections
- try {
- await ch.close();
- logger.info('ClickHouse connections closed');
- } catch (error) {
- logger.error({ err: error }, 'Error closing ClickHouse connections');
- }
-
- // Step 5: Close Bull queues (graceful shutdown of queue state)
- try {
- await Promise.all([
- sessionsQueue.close(),
- cronQueue.close(),
- notificationQueue.close(),
- ]);
- logger.info('Queue state closed');
- } catch (error) {
- logger.error({ err: error }, 'Error closing queue state');
- }
-
- // Step 5.5: Disconnect Kafka producer (no-op if never initialized)
- try {
- await disconnectKafka();
- logger.info('Kafka producer disconnected');
- } catch (error) {
- logger.error({ err: error }, 'Error disconnecting Kafka producer');
- }
-
- // Step 6: Close Redis connections
- try {
- const redisConnections = [
- getRedisCache(),
- getRedisPub(),
- getRedisSub(),
- getRedisQueue(),
- ];
-
- await Promise.all(
- redisConnections.map(async (redis) => {
- if (redis.status === 'ready') {
- await redis.quit();
- }
- })
- );
- logger.info('Redis connections closed');
- } catch (error) {
- logger.error({ err: error }, 'Error closing Redis connections');
- }
-
- logger.info('Graceful shutdown completed');
- clearTimeout(forceExit);
- process.exit(exitCode);
-}
diff --git a/apps/api/src/utils/logger.ts b/apps/api/src/utils/logger.ts
deleted file mode 100644
index 6a087835e..000000000
--- a/apps/api/src/utils/logger.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { createLogger } from '@openpanel/core';
-
-export const logger = createLogger({ name: 'api' });
diff --git a/apps/api/src/utils/observability.ts b/apps/api/src/utils/observability.ts
deleted file mode 100644
index c70be1333..000000000
--- a/apps/api/src/utils/observability.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { init } from '@hyperdx/node-opentelemetry';
-import { getServiceName, interceptProcessOutput } from '@openpanel/core';
-import { logger } from './logger';
-
-// Side-effect module — must stay the first import in index.ts.
-//
-// Traces only: logs ship via the pino transport and the output interceptor,
-// so the SDK's log pipeline and console capture stay off — one shipping path
-// per signal, nothing lands twice (see logging-capture-plan.md). Metrics stay
-// on prom-client/Grafana.
-//
-// tsdown bundles most deps (and hoists external imports above this code), so
-// require-hook auto-instrumentation only reaches diagnostics_channel-based
-// instrumentation (undici/fetch). To get spans from ioredis/bullmq/pg, move
-// them to `external` in tsdown.config.ts.
-if (process.env.HYPERDX_API_KEY) {
- init({
- apiKey: process.env.HYPERDX_API_KEY,
- service: getServiceName('api'),
- consoleCapture: false,
- disableLogs: true,
- disableMetrics: true,
- disableStartupLogs: true,
- });
-}
-
-interceptProcessOutput(logger);
diff --git a/apps/api/src/utils/parse-zod-query-string.ts b/apps/api/src/utils/parse-zod-query-string.ts
deleted file mode 100644
index fd100afd3..000000000
--- a/apps/api/src/utils/parse-zod-query-string.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { getSafeJson } from '@openpanel/json';
-
-const parseScalar = (v: any): any => {
- if (Array.isArray(v)) return v.map(parseScalar);
- if (typeof v === 'object' && v !== null) return parseQueryString(v);
- if (
- typeof v === 'string' &&
- /^-?[0-9]+(\.[0-9]+)?$/i.test(v) &&
- !Number.isNaN(Number.parseFloat(v))
- )
- return Number.parseFloat(v);
- if (v === 'true') return true;
- if (v === 'false') return false;
- if (typeof v === 'string') {
- const json = getSafeJson(v);
- if (json !== null) return json;
- return v;
- }
- return null;
-};
-
-export const parseQueryString = (obj: Record<string, any>): any => {
- return Object.fromEntries(
- Object.entries(obj).map(([k, v]) => [k, parseScalar(v)]),
- );
-};
diff --git a/apps/api/src/utils/rate-limiter.ts b/apps/api/src/utils/rate-limiter.ts
deleted file mode 100644
index 16dce8d30..000000000
--- a/apps/api/src/utils/rate-limiter.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { getTrustedIpFromHeaders } from '@openpanel/core';
-import { getRedisCache } from '@openpanel/redis';
-import type { FastifyInstance, FastifyRequest } from 'fastify';
-
-export async function activateRateLimiter<T extends FastifyRequest>({
- fastify,
- max,
- timeWindow,
- keyGenerator,
-}: {
- fastify: FastifyInstance;
- max: number;
- timeWindow?: string;
- keyGenerator?: (req: T) => string | undefined;
-}) {
- await fastify.register(import('@fastify/rate-limit'), {
- max,
- timeWindow: timeWindow || '1 minute',
- errorResponseBuilder: (req, reply) => {
- return {
- statusCode: 429,
- error: 'Too Many Requests',
- message: 'You have exceeded the rate limit for this endpoint.',
- };
- },
- // In test mode use in-memory storage so tests don't need a running Redis
- redis: process.env.NODE_ENV !== 'test' ? getRedisCache() : undefined,
- keyGenerator(req) {
- if (keyGenerator) {
- const key = keyGenerator(req as T);
- if (key) {
- return key;
- }
- }
- // Only trusted headers - `x-client-ip` / `x-forwarded-for` are set by the
- // caller, so keying on them hands out a fresh bucket per request.
- return (
- (req.headers['openpanel-client-id'] as string) ||
- getTrustedIpFromHeaders(req.headers, req.socket?.remoteAddress).ip
- );
- },
- onExceeded: (req) => {
- const { ip, header } = getTrustedIpFromHeaders(
- req.headers,
- req.socket?.remoteAddress
- );
- req.log.warn(
- {
- clientId: req.headers['openpanel-client-id'],
- ip,
- ipHeader: header,
- url: req.url,
- userAgent: req.headers['user-agent'],
- },
- 'rate limit exceeded'
- );
- },
- });
-}
diff --git a/apps/api/src/utils/safe-fetch.ts b/apps/api/src/utils/safe-fetch.ts
deleted file mode 100644
index 5d2e5d722..000000000
--- a/apps/api/src/utils/safe-fetch.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * The SSRF guard lives in `@openpanel/core` so that every
- * outbound-fetch site in the monorepo can reach it - the api controllers, the
- * worker's webhook delivery and the importer's remote-file reader alike. It
- * used to live here, which is why the importer never called it
- * (GHSA-cj2r-3x54-88h7).
- *
- * This module stays as a re-export so the existing `@/utils/safe-fetch` imports
- * keep working.
- */
-export {
- assertPublicHostname,
- assertPublicUrl,
- BlockedUrlError,
- createPinnedAgent,
- isBlockedIp,
- type SafeFetchOptions,
- type SafeFetchResult,
- type SafeFetchStreamResult,
- safeFetch,
- safeFetchStream,
-} from '@openpanel/core';
diff --git a/apps/api/tsdown.config.ts b/apps/api/tsdown.config.ts
deleted file mode 100644
index e41b81168..000000000
--- a/apps/api/tsdown.config.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import type { Options } from 'tsdown';
-import { defineConfig } from 'tsdown';
-
-const options: Options = {
- clean: true,
- entry: ['src/index.ts'],
- noExternal: [/^@openpanel\/.*$/u, /^@\/.*$/u],
- external: [
- '@hyperdx/node-opentelemetry',
- 'pino',
- 'pino-pretty',
- '@node-rs/argon2',
- // object-store adapter SDKs, now in @openpanel/core
- '@aws-sdk/client-s3',
- '@aws-sdk/client-sts',
- '@google-cloud/storage',
- // native module: loads its platform binding (@img/sharp-*) via a
- // runtime require resolved from its own file location, which breaks if
- // rolldown inlines sharp's source into this bundle (M7-008)
- 'sharp',
- ],
- sourcemap: true,
- platform: 'node',
- shims: true,
- inputOptions: {
- jsx: 'react',
- },
-};
-
-if (process.env.WATCH) {
- options.watch = ['src', '../../packages'];
- options.onSuccess = 'node --enable-source-maps dist/index.js';
- options.minify = false;
-}
-
-export default defineConfig(options);
diff --git a/apps/start/src/agents/client.ts b/apps/start/src/agents/client.ts
index 7c9a61fcc..0cd836d4a 100644
--- a/apps/start/src/agents/client.ts
+++ b/apps/start/src/agents/client.ts
@@ -1,5 +1,5 @@
import { createClient } from '@better-agent/client';
-import type { ChatApp } from '../../../api/src/agents/app';
+import type { ChatApp } from '@openpanel/core';
/**
* Typed Better Agent client. The `ChatApp` import surfaces every
@@ -7,15 +7,18 @@ import type { ChatApp } from '../../../api/src/agents/app';
* `useAgent(client, { agent: 'gpt-4-1' })` is autocompleted and
* validated end-to-end.
*
- * About the relative import: `ChatApp = typeof chatApp` is the full
- * Better Agent-inferred application type, which inherently binds to
- * the server-side agent definition (models, tools, context). It can't
- * be moved into `@openpanel/validation` without dragging the entire
- * agent definition (DB services, providers, etc.) along with it. It
- * is type-only, erased at build time — no runtime coupling. The
- * shared schemas (context, client tool inputs, model whitelist) live
- * in `@openpanel/validation` so only this one type import crosses
- * the app boundary.
+ * About the import: `ChatApp = typeof chatApp` is the full Better
+ * Agent-inferred application type, which inherently binds to the
+ * server-side agent definition (models, tools, context). It can't be
+ * moved into `@openpanel/validation` without dragging the entire agent
+ * definition (DB services, providers, etc.) along with it. It is
+ * type-only, erased at build time — no runtime coupling, which is what
+ * keeps it inside ADR-008's rule that only `*.constants.ts` may be
+ * VALUE-imported here. It used to reach `apps/api/src/agents/app`
+ * relatively; M9-004 deleted that wrapper and core's barrel exports the
+ * type. The shared schemas (context, client tool inputs, model
+ * whitelist) live in `@openpanel/validation` so only this one type
+ * import crosses the app boundary.
*/
export type AppClient = ReturnType<typeof createClient<ChatApp>>;
@@ -29,12 +32,13 @@ let cachedBaseURL: string | null = null;
* the server reads the session cookie from the request.
*/
export function getChatClient(apiUrl: string): AppClient {
- if (cachedClient && cachedBaseURL === apiUrl) return cachedClient;
+ if (cachedClient && cachedBaseURL === apiUrl) {
+ return cachedClient;
+ }
cachedBaseURL = apiUrl;
cachedClient = createClient<ChatApp>({
baseURL: `${apiUrl}/ai/agents`,
- fetch: (input, init) =>
- fetch(input, { ...init, credentials: 'include' }),
+ fetch: (input, init) => fetch(input, { ...init, credentials: 'include' }),
});
return cachedClient;
}
diff --git a/packages/core/src/clients/create-clients.ts b/packages/core/src/clients/create-clients.ts
new file mode 100644
index 000000000..b191a55ef
--- /dev/null
+++ b/packages/core/src/clients/create-clients.ts
@@ -0,0 +1,62 @@
+// The `clients` handle on `AppDeps` (TARGET_ARCHITECTURE §7: "AppDeps is built
+// ONCE in main.ts (db, ch, redis, clients, buffers, producers, base logger,
+// config flags)"), built at M9-004 when main.ts became the only entrypoint.
+//
+// It is a NAMING of what already exists under `src/clients/`, not a new
+// abstraction: every member below is the exact function this package already
+// exports, gathered so a service can reach an outbound client through its
+// scoped `Ctx` instead of importing the module directly. Nothing is
+// constructed here — the geo readers open their mmdb lazily and the email /
+// Slack / Discord transports read their own credentials — so building it
+// costs one object literal per process.
+//
+// The modules under `src/modules/**` still import these functions directly.
+// Repointing them onto `ctx.clients` is the TECH_DEBT §4 wave (after P9,
+// before P12's grep gates); this handle is what that wave repoints ONTO.
+
+import { enrichInsights } from './ai/enrich';
+import { generateInsightExplanation } from './ai/explain';
+import { generateWeeklyNarrative } from './ai/narrative';
+import { sendEmail } from './email';
+import { getAsnInfo, getGeoLocation } from './geo';
+import { sendDiscordNotification } from './integrations/discord';
+import {
+ getSlackInstallUrl,
+ sendSlackNotification,
+} from './integrations/slack';
+
+export interface ServiceClients {
+ geo: {
+ getGeoLocation: typeof getGeoLocation;
+ getAsnInfo: typeof getAsnInfo;
+ };
+ email: {
+ sendEmail: typeof sendEmail;
+ };
+ slack: {
+ sendSlackNotification: typeof sendSlackNotification;
+ getSlackInstallUrl: typeof getSlackInstallUrl;
+ };
+ discord: {
+ sendDiscordNotification: typeof sendDiscordNotification;
+ };
+ ai: {
+ enrichInsights: typeof enrichInsights;
+ generateInsightExplanation: typeof generateInsightExplanation;
+ generateWeeklyNarrative: typeof generateWeeklyNarrative;
+ };
+}
+
+export function createClients(): ServiceClients {
+ return {
+ geo: { getGeoLocation, getAsnInfo },
+ email: { sendEmail },
+ slack: { sendSlackNotification, getSlackInstallUrl },
+ discord: { sendDiscordNotification },
+ ai: {
+ enrichInsights,
+ generateInsightExplanation,
+ generateWeeklyNarrative,
+ },
+ };
+}
diff --git a/packages/core/src/context.test.ts b/packages/core/src/context.test.ts
index 928b7b8db..2665a408e 100644
--- a/packages/core/src/context.test.ts
+++ b/packages/core/src/context.test.ts
@@ -54,10 +54,10 @@ function stubDeps(): {
scopes,
scoped,
deps: {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
producers: {
...producers,
diff --git a/packages/core/src/context.ts b/packages/core/src/context.ts
index 4d60d02cd..4bc1b3681 100644
--- a/packages/core/src/context.ts
+++ b/packages/core/src/context.ts
@@ -12,15 +12,19 @@ import type { IncomingEventProducer } from './modules/ingest/src/incoming-event'
import { createServices, type Services } from './services';
import type { CookieJar, CookieOptions } from './shared/cookie';
-// Handles core does not own yet. Each real type arrives with the phase that
-// builds it (db/ch/redis P3, clients P4); they are named now so AppDeps and
-// Ctx are written once in their final shape and replacing an alias moves no
-// field. `unknown` is deliberate — reading one before its type lands is a
-// compile error rather than a silent `any`.
-export type Db = unknown;
-export type ClickHouseClient = unknown;
-export type RedisClient = unknown;
-export type ServiceClients = unknown;
+// The four boot handles, landed at M9-004 when main.ts became the only
+// entrypoint and had to build a real `AppDeps` for the mounted route
+// surfaces. Each is a TYPE QUERY over the module that constructs the client,
+// so the alias cannot drift from what `main.ts` actually passes; all four are
+// type-only, so core still imports no database at runtime and `bun test`
+// still runs offline.
+export type Db = typeof import('@openpanel/db/src/prisma-client').db;
+export type ClickHouseClient =
+ typeof import('@openpanel/db/src/clickhouse/client').ch;
+export type RedisClient = ReturnType<
+ typeof import('@openpanel/redis').getRedisCache
+>;
+export type ServiceClients = import('./clients/create-clients').ServiceClients;
// Landed at M8-001: built once by `createBuffers(deps)` in main.ts, never a
// module singleton.
diff --git a/packages/core/src/http/auth.test.ts b/packages/core/src/http/auth.test.ts
index e5bee35aa..2f855c87a 100644
--- a/packages/core/src/http/auth.test.ts
+++ b/packages/core/src/http/auth.test.ts
@@ -1,7 +1,11 @@
import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
import { Elysia } from 'elysia';
import { stubAppDeps } from '../../test/http-fixtures';
-import type { AuthenticatedClient, ClientAuthOptions } from './client-auth';
+import type {
+ AuthenticatedClient,
+ ClientAuthOptions,
+ ClientAuthResult,
+} from './client-auth';
// mock.module is not hoisted, so the subject is imported inside beforeAll —
// see AGENTS.md. Both principals are stubs until P6/P8; mocking them is what
@@ -14,12 +18,18 @@ const CLIENT: AuthenticatedClient = {
secretPresented: true,
};
-let client: AuthenticatedClient | null = CLIENT;
+const REFUSAL: ClientAuthResult = {
+ ok: false,
+ ingest: false,
+ message: 'Manage: Invalid client secret',
+};
+
+let result: ClientAuthResult = { ok: true, client: CLIENT };
let session: unknown = { userId: 'user_1' };
const authenticateClient = mock(
(_deps: unknown, _headers: Headers, _options: ClientAuthOptions) =>
- Promise.resolve(client)
+ Promise.resolve(result)
);
const resolveSession = mock(() => Promise.resolve(session));
@@ -36,7 +46,7 @@ beforeAll(async () => {
});
beforeEach(() => {
- client = CLIENT;
+ result = { ok: true, client: CLIENT };
session = { userId: 'user_1' };
authenticateClient.mockClear();
resolveSession.mockClear();
@@ -56,7 +66,7 @@ function buildApp() {
const typed: AuthenticatedClient = principal;
return { id: typed.id, secretPresented: typed.secretPresented };
},
- { clientAuth: { allow: ['root'] } }
+ { clientAuth: { allow: ['root'], label: 'Manage' } }
)
.get(
'/dashboard',
@@ -87,18 +97,39 @@ test('clientAuth passes the allow list through to the authenticator', async () =
new Request('http://localhost/manage/projects', { method: 'POST' })
);
- expect(authenticateClient.mock.calls[0]?.[2]).toEqual({ allow: ['root'] });
+ expect(authenticateClient.mock.calls[0]?.[2]).toEqual({
+ allow: ['root'],
+ label: 'Manage',
+ });
+});
+
+// V1 has TWO 401 bodies and both are a wire contract: the allow-list routers
+// (/export, /insights, /import, /manage) answered with a JSON envelope
+// carrying the validator's own message, and the ingest routers (/track,
+// /event, /profile) answered with that message as plain text.
+test('clientAuth answers 401 with V1s allow-list body when nothing authenticates', async () => {
+ result = REFUSAL;
+
+ const response = await buildApp().handle(
+ new Request('http://localhost/manage/projects', { method: 'POST' })
+ );
+
+ expect(response.status).toBe(401);
+ expect(await response.json()).toEqual({
+ error: 'Unauthorized',
+ message: 'Manage: Invalid client secret',
+ });
});
-test('clientAuth answers 401 with V1s message when nothing authenticates', async () => {
- client = null;
+test('clientAuth answers 401 with V1s ingest body, which is plain text', async () => {
+ result = { ok: false, ingest: true, message: 'Missing client id' };
const response = await buildApp().handle(
new Request('http://localhost/manage/projects', { method: 'POST' })
);
expect(response.status).toBe(401);
- expect(await response.text()).toBe('Invalid client credentials');
+ expect(await response.text()).toBe('Missing client id');
});
test('session resolves through the memoized HttpCtx lookup', async () => {
diff --git a/packages/core/src/http/auth.ts b/packages/core/src/http/auth.ts
index 9eb21cfa8..d13612ae7 100644
--- a/packages/core/src/http/auth.ts
+++ b/packages/core/src/http/auth.ts
@@ -44,7 +44,10 @@ import { toIngestHeaders } from '../modules/ingest/src/headers';
import { authenticateClient, type ClientAuthOptions } from './client-auth';
import { requestContext } from './context';
-const INVALID_CLIENT_MESSAGE = 'Invalid client credentials';
+const UNAUTHORIZED = 401;
+/** V1's allow-list routers answered a 401 with this JSON envelope; its ingest
+ * routers answered with the refusal message as plain text. Both port. */
+const UNAUTHORIZED_ERROR = 'Unauthorized';
/**
* The named plugin every module reaches through `defineRoutes`. It brings
@@ -66,16 +69,26 @@ export function authMacros(deps: AppDeps) {
},
clientAuth: (options: ClientAuthOptions) => ({
async resolve({ body, ctx, status }) {
- const client = await authenticateClient(
+ const result = await authenticateClient(
deps,
toIngestHeaders(ctx.headers),
options,
{ ip: ctx.ip, body }
);
- if (!client) {
- return status(401, INVALID_CLIENT_MESSAGE);
+ if (!result.ok) {
+ if (result.ingest) {
+ ctx.logger.warn(
+ { message: result.message },
+ 'Invalid SDK request'
+ );
+ return status(UNAUTHORIZED, result.message);
+ }
+ return status(UNAUTHORIZED, {
+ error: UNAUTHORIZED_ERROR,
+ message: result.message,
+ });
}
- return { client };
+ return { client: result.client };
},
}),
});
diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.ts
index 60e0a7c73..8e582fd23 100644
--- a/packages/core/src/http/client-auth.ts
+++ b/packages/core/src/http/client-auth.ts
@@ -7,17 +7,29 @@
//
// M8-002 filled in the INGEST branch — `modules/ingest/src/client-auth.ts`
// holds V1's `validateSdkRequest` verbatim, and this file adapts it onto the
-// principal. The `allow`-list tiers (`validateExportRequest`,
-// `validateImportRequest`, `validateManageRequest`, MCP's `token: 'basic'`)
-// are NOT filled in yet: they belong to the client module, not to ingest, and
-// stay the stub that answers 401 — the same NAMED GAP every non-ingest
-// `publicApiRoutes` module's header already records.
+// principal. M9-004 filled in the `allow`-list tier, which is the one V1
+// spells three times (`validateExportRequest`, `validateImportRequest`,
+// `validateManageRequest`): identical bodies differing only by the accepted
+// `ClientType` set and by the prefix on their error strings. `allow` carries
+// that difference and the three collapse into `authenticateAllowedClient`
+// below. MCP is NOT here — it authenticates its own `token` form inside
+// `modules/mcp/src/auth.ts`, exactly as V1's mcp router did.
import type { AppDeps } from '../context';
+import { getClientByIdCached } from '../modules/client/client.service';
import {
type IngestHeaders,
validateIngestRequest,
} from '../modules/ingest/src/client-auth';
+import { headerValue } from '../modules/ingest/src/headers';
+import { verifyPassword } from '../shared/crypto';
+
+/** V1 refuses a client id that is not a UUID before it ever queries
+ * (utils/auth.ts's three validators). Same regex, same order. */
+const CLIENT_ID_UUID_REGEX =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const CLIENT_ID_HEADER = 'openpanel-client-id';
+const CLIENT_SECRET_HEADER = 'openpanel-client-secret';
/** Prisma's `ClientType` enum, by value. Moves to client.constants.ts in P7. */
export type ClientType = 'read' | 'write' | 'root';
@@ -38,15 +50,35 @@ export interface AuthenticatedClient {
secretPresented: boolean;
}
+/**
+ * The surface's name in a refusal message. V1's three validators are the same
+ * function with a different prefix — `Export: Invalid client secret` — and
+ * those strings are the 401 BODY on `/export`, `/insights`, `/import` and
+ * `/manage`, so they are a wire contract, not decoration.
+ */
+export type ClientAuthLabel = 'Export' | 'Import' | 'Manage';
+
export interface ClientAuthOptions {
/** Which client types may pass. Omitted means any, as `validateSdkRequest`. */
allow?: ClientType[];
+ /** Which of V1's three validators this route was served by. */
+ label?: ClientAuthLabel;
/** The ingest extension described above. */
ingest?: boolean;
/** MCP presents `base64(clientId:clientSecret)` instead of the two headers. */
token?: 'basic';
}
+/**
+ * A refusal is returned, never thrown — same reason
+ * `modules/ingest/src/client-auth.ts` gives, and it keeps the two 401 BODIES
+ * V1 has (plain text on the ingest routes, `{error, message}` JSON on the
+ * allow-list ones) a decision of the macro rather than of this function.
+ */
+export type ClientAuthResult =
+ | { ok: true; client: AuthenticatedClient }
+ | { ok: false; ingest: boolean; message: string };
+
/** What the ingest tier needs beyond the headers: V1 reads the attribution ip
* and the body (credential fallback, profile filter, `__revenue` gate). */
export interface ClientAuthRequest {
@@ -59,9 +91,9 @@ export async function authenticateClient(
headers: IngestHeaders,
options: ClientAuthOptions,
request?: ClientAuthRequest
-): Promise<AuthenticatedClient | null> {
+): Promise<ClientAuthResult> {
if (!options.ingest) {
- return null;
+ return await authenticateAllowedClient(headers, options);
}
const outcome = await validateIngestRequest({
@@ -71,15 +103,91 @@ export async function authenticateClient(
});
if (!outcome.ok) {
- return null;
+ return { ok: false, ingest: true, message: outcome.message };
}
const { client } = outcome;
return {
- id: client.id,
- projectId: client.projectId,
- organizationId: client.organizationId,
- type: client.type,
- secretPresented: outcome.secretPresented,
+ ok: true,
+ client: {
+ id: client.id,
+ projectId: client.projectId,
+ organizationId: client.organizationId,
+ type: client.type,
+ secretPresented: outcome.secretPresented,
+ },
};
}
+
+/** V1's per-validator "wrong type" message; every other refusal differs only
+ * by the label prefix. */
+const FORBIDDEN_TYPE_MESSAGE: Record<ClientAuthLabel, string> = {
+ Export: 'Export: Client is not allowed to export',
+ Import: 'Import: Client is not allowed to import',
+ Manage: 'Manage: Only root clients are allowed to manage resources',
+};
+
+/** V1 mapped a Prisma lookup failure onto its own message, unprefixed. */
+const MALFORMED_CLIENT_ID_MESSAGE = 'Client ID seems to be malformed';
+const PRISMA_KNOWN_REQUEST_ERROR = 'PrismaClientKnownRequestError';
+const UNEXPECTED_MESSAGE = 'Unexpected error';
+
+/**
+ * The `allow`-list tier: V1's `validateExportRequest` / `validateImportRequest`
+ * / `validateManageRequest`, which differ only by the accepted `ClientType`
+ * set and by the label their messages carry.
+ *
+ * `secretPresented` is true on success by construction: this tier verifies the
+ * secret, so reaching the return means one was presented and matched.
+ */
+async function authenticateAllowedClient(
+ headers: IngestHeaders,
+ options: ClientAuthOptions
+): Promise<ClientAuthResult> {
+ const label = options.label ?? 'Export';
+ const refuse = (message: string): ClientAuthResult => ({
+ ok: false,
+ ingest: false,
+ message,
+ });
+
+ const clientId = headerValue(headers, CLIENT_ID_HEADER) ?? '';
+ const clientSecret = headerValue(headers, CLIENT_SECRET_HEADER) ?? '';
+
+ if (!CLIENT_ID_UUID_REGEX.test(clientId)) {
+ return refuse(`${label}: Client ID must be a valid UUIDv4`);
+ }
+
+ try {
+ const client = await getClientByIdCached(clientId);
+ if (!client) {
+ return refuse(`${label}: Invalid client id`);
+ }
+ if (!client.secret) {
+ return refuse(`${label}: Client has no secret`);
+ }
+ if (options.allow && !options.allow.includes(client.type as ClientType)) {
+ return refuse(FORBIDDEN_TYPE_MESSAGE[label]);
+ }
+ if (!(await verifyPassword(clientSecret, client.secret))) {
+ return refuse(`${label}: Invalid client secret`);
+ }
+
+ return {
+ ok: true,
+ client: {
+ id: client.id,
+ projectId: client.projectId,
+ organizationId: client.organizationId,
+ type: client.type as ClientType,
+ secretPresented: true,
+ },
+ };
+ } catch (error) {
+ return refuse(
+ (error as { name?: string })?.name === PRISMA_KNOWN_REQUEST_ERROR
+ ? MALFORMED_CLIENT_ID_MESSAGE
+ : UNEXPECTED_MESSAGE
+ );
+ }
+}
diff --git a/packages/core/src/http/cors.ts b/packages/core/src/http/cors.ts
new file mode 100644
index 000000000..7e6b82179
--- /dev/null
+++ b/packages/core/src/http/cors.ts
@@ -0,0 +1,66 @@
+// The CORS delegator, ported from apps/api/src/app.ts:107-131 (ADR-002
+// "behaviour that must be preserved explicitly" 4).
+//
+// Two halves, and BOTH are the contract:
+//
+// 1. `CORS_PRIVATE_PATHS` is V1's `corsPaths` allowlist verbatim. A request
+// under one of those prefixes is only allowed from a configured dashboard
+// origin; everything else — `/track`, `/export`, `/insights`, `/import`,
+// `/manage`, `/profile`, `/event`, `/tools` — is open to any origin.
+// 2. The quirk that `/gsc` and `/mcp` are dashboard-scope routes ABSENT from
+// the list, and therefore open. Ported, not fixed.
+//
+// The origins come from `apps/api`'s config, not from `process.env`: core
+// reads no environment.
+//
+// ONE deliberate delta from V1, forced by the plugin substitution ADR-002
+// mandates (`@fastify/cors`'s per-request delegate -> `@elysiajs/cors`, whose
+// `credentials` and `maxAge` are static while only `origin` is per-request):
+// on an open path that DOES send an `Origin` header, V2 echoes that origin
+// with `vary: Origin` where V1 answered `*`, and carries
+// `access-control-allow-credentials: true`. Both forms permit exactly the same
+// set of cross-origin requests; a browser treats an echoed origin plus `Vary`
+// as it treats `*`. A request with no `Origin` header — every server-side SDK,
+// every golden replay — still gets `*`.
+
+import { cors } from '@elysiajs/cors';
+
+/** V1's `corsPaths` (apps/api/src/app.ts:111), byte-for-byte. */
+export const CORS_PRIVATE_PATHS = [
+ '/trpc',
+ '/live',
+ '/webhook',
+ '/oauth',
+ '/misc',
+ '/ai',
+] as const;
+
+/** V1's `maxAge: 86_400 * 7` on the open paths. */
+const CORS_MAX_AGE_SECONDS = 86_400 * 7;
+
+export interface CorsOptions {
+ /** `DASHBOARD_URL` plus `API_CORS_ORIGINS`, already split and filtered. */
+ dashboardOrigins: string[];
+}
+
+export function corsDelegator({ dashboardOrigins }: CorsOptions) {
+ const allowed = new Set(dashboardOrigins);
+
+ return cors({
+ origin: (request) => {
+ const path = new URL(request.url).pathname;
+ const isPrivatePath = CORS_PRIVATE_PATHS.some((prefix) =>
+ path.startsWith(prefix)
+ );
+
+ if (!isPrivatePath) {
+ return true;
+ }
+
+ const origin = request.headers.get('origin');
+ return origin !== null && allowed.has(origin);
+ },
+ credentials: true,
+ maxAge: CORS_MAX_AGE_SECONDS,
+ });
+}
diff --git a/packages/core/src/http/errors.ts b/packages/core/src/http/errors.ts
new file mode 100644
index 000000000..2dbd691f4
--- /dev/null
+++ b/packages/core/src/http/errors.ts
@@ -0,0 +1,152 @@
+// The one error handler, ported from apps/api/src/app.ts:408-460 (ADR-002
+// "behaviour that must be preserved explicitly" 6: "the error handler's shape,
+// including the absence of a not-found handler").
+//
+// The body is V1's `{status, error, message}` — ADR-003 lists that shape under
+// "behaviour that must be re-implemented deliberately", because V1 produced it
+// as a side effect of the Fastify error handler and nothing reproduces it on
+// its own. Elysia's own `VALIDATION` failures are mapped onto it too, at 400:
+// that is the status V1's zod compilers threw with, and a caller that sends a
+// bad `/track` body must keep seeing 400 rather than Elysia's 422.
+//
+// There is deliberately NO not-found handler: V1 had none, so an unmatched
+// route keeps whatever the framework answers.
+
+import { Elysia } from 'elysia';
+import type { AppDeps } from '../context';
+import { HttpError, normalizeError } from '../shared/errors';
+import { requestContext } from './context';
+
+const RATE_LIMITED_STATUS = 429;
+const SERVER_ERROR_STATUS = 500;
+
+/** V1's SKIP_LOG_ERRORS. `FST_ERR_CTP_INVALID_MEDIA_TYPE` is Fastify's and can
+ * no longer occur; it stays so the list is recognisably the same one. */
+const SKIP_LOG_ERROR_CODES = [
+ 'UNAUTHORIZED',
+ 'FORBIDDEN',
+ 'FST_ERR_CTP_INVALID_MEDIA_TYPE',
+];
+
+const VALIDATION_STATUS = 400;
+/** V1's zod compilers threw a plain `Error`, so `normalizeError` reported
+ * `Error` as the name and the body carried `"error":"Error"`. */
+const VALIDATION_ERROR_NAME = 'Error';
+
+/**
+ * Fastify names the request part it validated; Elysia names the same thing in
+ * its own vocabulary. The response body carries Fastify's word, because that
+ * string is what callers have been parsing.
+ */
+const VALIDATION_SLOT_NAMES: Record<string, string> = {
+ query: 'querystring',
+ body: 'body',
+ params: 'params',
+ headers: 'headers',
+ cookie: 'cookie',
+ response: 'response',
+};
+
+export interface ErrorHandlerOptions {
+ /** `NODE_ENV === 'production'` at the call site — core reads no environment. */
+ production: boolean;
+}
+
+export function errorHandler(deps: AppDeps, options: ErrorHandlerOptions) {
+ return new Elysia({ name: 'core/http/error-handler' })
+ .use(requestContext(deps))
+ .onError({ as: 'global' }, ({ code, error, set, request, path, ctx }) => {
+ const isValidation = code === 'VALIDATION';
+ const normalized = normalizeError(error);
+ const status = isValidation ? VALIDATION_STATUS : normalized.status;
+ const message = isValidation
+ ? validationMessage(error)
+ : normalized.message;
+ const logger = ctx?.logger ?? deps.logger;
+
+ if (status === RATE_LIMITED_STATUS) {
+ set.status = RATE_LIMITED_STATUS;
+ return {
+ status: RATE_LIMITED_STATUS,
+ error: 'Too Many Requests',
+ message: 'You have exceeded the rate limit for this endpoint.',
+ };
+ }
+
+ const skipLog =
+ status < SERVER_ERROR_STATUS &&
+ normalized.code !== undefined &&
+ SKIP_LOG_ERROR_CODES.includes(normalized.code);
+
+ if (!skipLog) {
+ // 4xx are client-side problems (bad payloads, missing fields, etc.) —
+ // log as warn so they don't drown out real server errors.
+ const label =
+ error instanceof HttpError
+ ? 'internal server error'
+ : 'request error';
+ const req = {
+ id: ctx?.requestId,
+ url: path,
+ method: request.method,
+ headers: Object.fromEntries(request.headers),
+ };
+ if (status >= SERVER_ERROR_STATUS) {
+ logger.error({ err: error, req }, label);
+ } else {
+ logger.warn({ err: error, req }, label);
+ }
+ }
+
+ set.status = status;
+
+ if (options.production && status === SERVER_ERROR_STATUS) {
+ return 'Internal server error';
+ }
+
+ return {
+ status,
+ // HttpError carries an explicit `error` payload (the underlying
+ // cause); for everything else we surface the error name so the body is
+ // always a stable JSON shape, regardless of what was thrown.
+ error: errorField(error, isValidation, normalized.errorName),
+ message,
+ };
+ });
+}
+
+/**
+ * V1's validation message, `"<slot>/<path> <zod message>"` — produced by
+ * `fastify-zod-openapi`'s compilers, and part of the response body on
+ * `/export` and `/insights`. Elysia's own message is a multi-line JSON dump,
+ * which is why this reads the structured error rather than reformatting it.
+ */
+function validationMessage(error: unknown): string {
+ // Measured on Elysia 1.4.30 with a zod (Standard Schema) validator: the
+ // instance carries `type` (the request part) and `all` (one entry per issue,
+ // with a slash-joined `path` string). `message` is the whole report
+ // pretty-printed, which is the fallback, not the answer.
+ const detail = error as {
+ type?: string;
+ all?: { path?: string; message?: string }[];
+ message?: string;
+ };
+ const issue = detail.all?.[0];
+ const slot = VALIDATION_SLOT_NAMES[detail.type ?? ''] ?? detail.type ?? '';
+
+ if (!(issue?.path && issue.message)) {
+ return detail.message ?? '';
+ }
+ return `${slot}/${issue.path} ${issue.message}`;
+}
+
+function errorField(
+ error: unknown,
+ isValidation: boolean,
+ errorName: string
+): unknown {
+ if (error instanceof HttpError) {
+ return error.error;
+ }
+ return isValidation ? VALIDATION_ERROR_NAME : errorName;
+}
diff --git a/packages/core/src/http/query.ts b/packages/core/src/http/query.ts
new file mode 100644
index 000000000..d0ef84ebf
--- /dev/null
+++ b/packages/core/src/http/query.ts
@@ -0,0 +1,63 @@
+// The querystring pre-pass, ported from
+// apps/api/src/utils/parse-zod-query-string.ts (ADR-003, "behaviour that must
+// be re-implemented deliberately": the `parseQueryString` pre-pass as an
+// Elysia lifecycle hook running BEFORE schema validation on `/export` and
+// `/insights`).
+//
+// It exists because ~31 query schemas on those two surfaces are written
+// against already-coerced values — `z.number()`, `z.boolean()`,
+// `z.array(...)` — while a querystring only ever carries strings. V1 coerced
+// in a Fastify `preValidation` hook; rewriting those schemas with `z.coerce`
+// instead would change the contract, which is why the ADR names the hook.
+//
+// `transform` is Elysia's pre-validation phase, and the hook MUTATES `query`
+// in place: reassigning the destructured binding would not reach the object
+// the validator then reads.
+
+import { getSafeJson } from '../shared/json';
+
+const NUMERIC = /^-?[0-9]+(\.[0-9]+)?$/i;
+
+function parseScalar(value: unknown): unknown {
+ if (Array.isArray(value)) {
+ return value.map(parseScalar);
+ }
+ if (typeof value === 'object' && value !== null) {
+ return parseQueryString(value as Record<string, unknown>);
+ }
+ if (typeof value === 'string') {
+ if (NUMERIC.test(value) && !Number.isNaN(Number.parseFloat(value))) {
+ return Number.parseFloat(value);
+ }
+ if (value === 'true') {
+ return true;
+ }
+ if (value === 'false') {
+ return false;
+ }
+ return getSafeJson(value) ?? value;
+ }
+ return null;
+}
+
+export function parseQueryString(
+ source: Record<string, unknown>
+): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(source).map(([key, value]) => [key, parseScalar(value)])
+ );
+}
+
+/** The `transform` hook itself. Registered LOCAL on the two route surfaces
+ * that had it in V1 — never globally, or `/track` and `/manage` would start
+ * coercing values their handlers read as strings. */
+export function parseQueryStringTransform({
+ query,
+}: {
+ query: Record<string, unknown>;
+}): void {
+ const parsed = parseQueryString(query);
+ for (const [key, value] of Object.entries(parsed)) {
+ query[key] = value;
+ }
+}
diff --git a/packages/core/src/http/session.ts b/packages/core/src/http/session.ts
index 2b6b7551e..491eb560d 100644
--- a/packages/core/src/http/session.ts
+++ b/packages/core/src/http/session.ts
@@ -1,25 +1,47 @@
// Where the session cookie becomes a session.
//
-// P2 lands the plumbing, not the resolution: `HttpCtx.session()` memoizes this
-// call, so a request that asks twice pays once, and the cookie is read through
-// `HttpCtx` rather than through a plugin whose registration order could put it
-// after the guard that needs it (ADR-002 "behaviour that must be preserved
-// explicitly" 1).
+// `HttpCtx.session()` memoizes this call, so a request that asks twice pays
+// once, and the cookie is read through `HttpCtx` rather than through a plugin
+// whose registration order could put it after the guard that needs it
+// (ADR-002 "behaviour that must be preserved explicitly" 1).
//
-// P6 fills the body in: decode the token, `runWithAlsSession`, validate, and
-// the DEMO_USER_ID branch — plus ADR-002's mandatory test, valid cookie ->
-// non-empty session and no cookie -> EMPTY_SESSION. That failure is silent
-// (a 401, not an error), which is why the test is not optional.
+// M9-004 filled the body in, porting apps/api/src/app.ts's dashboard-scope
+// `onRequest` hook: decode, `runWithAlsSession`, validate, and V1's
+// DEMO_USER_ID branch — which lives inside `validateSessionToken` itself, so
+// the no-cookie path still goes through it rather than short-circuiting here.
+//
+// `null` means "nobody is signed in", NOT `EMPTY_SESSION`: the `session`
+// macro, the bull-board guard and the four `/live` handlers all treat the
+// resolved value as truthy-means-authenticated. tRPC is the one caller that
+// wants V1's empty shape instead, and `makeTrpcContext` maps `null` back to
+// `EMPTY_SESSION` there.
import type { AppDeps, Session } from '../context';
+import { validateSessionToken } from '../modules/auth/src/login-session';
+import { decodeSessionToken } from '../modules/auth/src/token';
+import { runWithAlsSession } from '../modules/session/src/session-context';
import type { CookieJar } from '../shared/cookie';
export const SESSION_COOKIE_NAME = 'session';
-export function resolveSession(
+/** V1's ALS scope for the demo branch (apps/api/src/app.ts:163). */
+const DEMO_ALS_SESSION_ID = '1';
+
+export async function resolveSession(
_deps: AppDeps,
- _cookies: CookieJar,
+ cookies: CookieJar,
_headers: Headers
): Promise<Session | null> {
- return Promise.resolve(null);
+ const token = cookies.get(SESSION_COOKIE_NAME);
+
+ try {
+ const result = await runWithAlsSession(
+ token ? decodeSessionToken(token) : DEMO_ALS_SESSION_ID,
+ () => validateSessionToken(token ?? null)
+ );
+ return result.userId === null ? null : result;
+ } catch {
+ // V1 swallowed a malformed cookie into EMPTY_SESSION rather than a 500.
+ return null;
+ }
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 7626e7d90..1fe340aa9 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -58,6 +58,10 @@ export {
} from './clients/ai/providers';
export type { WinBackPitchInput } from './clients/ai/win-back';
export { generateWinBackPitch } from './clients/ai/win-back';
+// The `clients` handle on AppDeps (M9-004). main.ts builds it once and hands
+// it to `AppDeps`, the same way it builds the buffers and the producers.
+export type { ServiceClients } from './clients/create-clients';
+export { createClients } from './clients/create-clients';
export type { EmailData, EmailTemplate } from './clients/email';
export { sendEmail } from './clients/email';
// Dissolved from @openpanel/geo (M4-004) — apps/api's ingest and tools
@@ -145,7 +149,14 @@ export { createCtx, extendCtx } from './context';
// reads its own UI assets off disk before it can register.
export { BULL_BOARD_BASE_PATH, bullBoardRoutes } from './http/bull-board';
export { requestContext, requestLogging } from './http/context';
+// The root chain `main.ts` hangs every surface on (M9-004): V1's CORS
+// delegator and V1's error handler, both ported and both taking their
+// deployment-derived values as arguments — core reads no environment.
+export type { CorsOptions } from './http/cors';
+export { CORS_PRIVATE_PATHS, corsDelegator } from './http/cors';
export { debugRoutes } from './http/debug.routes';
+export type { ErrorHandlerOptions } from './http/errors';
+export { errorHandler } from './http/errors';
// The two runtime seams over the registry (ADR-005). `main.ts` builds
// producers in every role and workers only where the role consumes; both take
// the registry as data, so neither opens a connection until it is called.
diff --git a/packages/core/src/jobs/workers.test.ts b/packages/core/src/jobs/workers.test.ts
index 4abe9c4c7..691076498 100644
--- a/packages/core/src/jobs/workers.test.ts
+++ b/packages/core/src/jobs/workers.test.ts
@@ -24,10 +24,10 @@ function stubLogger(): Logger {
function stubDeps(): AppDeps {
return {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
producers: createRecordingProducers(queues),
produceIncomingEvent: () => Promise.resolve(),
diff --git a/packages/core/src/modules/client/client.routes.ts b/packages/core/src/modules/client/client.routes.ts
index f01ec5b4c..4c399e5c1 100644
--- a/packages/core/src/modules/client/client.routes.ts
+++ b/packages/core/src/modules/client/client.routes.ts
@@ -57,7 +57,7 @@ export const clientRoutes = defineRoutes((app) =>
return { data: clients };
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
query: listQuery,
detail: { tags: ['Manage'] },
}
@@ -78,7 +78,7 @@ export const clientRoutes = defineRoutes((app) =>
return { data: found };
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
params: idParams,
detail: { tags: ['Manage'] },
}
@@ -101,7 +101,7 @@ export const clientRoutes = defineRoutes((app) =>
};
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
body: zCreateClient,
detail: { tags: ['Manage'] },
}
@@ -123,7 +123,7 @@ export const clientRoutes = defineRoutes((app) =>
return { data: updated };
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
params: idParams,
body: zUpdateClient,
detail: { tags: ['Manage'] },
@@ -145,7 +145,7 @@ export const clientRoutes = defineRoutes((app) =>
return { success: true };
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
params: idParams,
detail: { tags: ['Manage'] },
}
diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.ts
index c4aa5ec2d..915a61196 100644
--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts
+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts
@@ -2,7 +2,7 @@
// methods themselves are exercised in cohort.service.test.ts.
import { expect, test } from 'bun:test';
-import type { Buffers, JobCtx } from '../../context';
+import type { AppDeps, Buffers, JobCtx } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
@@ -47,10 +47,10 @@ function stubJobCtx(cohort: Partial<CohortService>, jobName = 'test'): JobCtx {
misc: {} as Services['misc'],
};
return {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: createRecordingProducers(queues).queues,
diff --git a/packages/core/src/modules/export/export.routes.ts b/packages/core/src/modules/export/export.routes.ts
index 2390ebaf0..9ed94ae7f 100644
--- a/packages/core/src/modules/export/export.routes.ts
+++ b/packages/core/src/modules/export/export.routes.ts
@@ -7,20 +7,15 @@
// land at P8 without redesigning the API it replaces — no new query logic,
// every call below is the same function V1's controller calls.
//
-// NAMED GAP, same as the rest of `publicApiRoutes`: not yet reachable.
-// `authenticateClient` (http/client-auth.ts) is a P8 stub that always
-// returns null, so `clientAuth` 401s every request until it is filled in,
-// and main.ts does not mount `publicApiRoutes` until a real `AppDeps`
-// exists. `allow: ['read', 'root']` mirrors V1's rule (utils/auth.ts's
+// `allow: ['read', 'root']` mirrors V1's rule (utils/auth.ts's
// `validateExportRequest`, shared by both `/export` and `/insights`: a
// `write`-type client may not read analytics back out).
//
-// Also not ported here (ADR-003, "behaviour that must be re-implemented
-// deliberately"): the `parseQueryString` pre-pass V1 runs as a Fastify
-// `preValidation` hook, coercing JSON-encoded array/object querystring values
-// before zod sees them. It is an Elysia lifecycle-hook task of its own, not
-// specific to this module, and every zod schema below is written to be the
-// one V1 validates AFTER that hook runs.
+// M9-004 mounted this surface and landed the missing half: V1's
+// `parseQueryString` pre-pass is now `http/query.ts`'s `transform` hook,
+// registered LOCAL on both surfaces below. Every zod schema here is the one V1
+// validates AFTER that hook runs, so without it a plain `?limit=5` fails
+// validation.
//
// `listDashboards`/`listReports` (insights.controller.ts) are mounted under
// `/manage/projects/:projectId/dashboards[...]` in V1 (manage.router.ts) —
@@ -47,6 +42,8 @@ import {
import { z } from 'zod';
import type { ClientType } from '../../http/client-auth';
import { defineRoutes } from '../../http/define';
+import { parseQueryStringTransform } from '../../http/query';
+import { HttpError } from '../../shared/errors';
import {
loadDb,
resolveExportProjectId,
@@ -56,7 +53,10 @@ import {
const EXPORT_TAGS = ['Export'];
const INSIGHTS_TAGS = ['Insights'];
-const CLIENT_ALLOW: { allow: ClientType[] } = { allow: ['read', 'root'] };
+const CLIENT_ALLOW: { allow: ClientType[]; label: 'Export' } = {
+ allow: ['read', 'root'],
+ label: 'Export',
+};
// REST querystrings can't carry arrays of objects natively. Callers pass
// `filters` as a URL-encoded JSON string; decoded here (ported verbatim from
@@ -161,15 +161,18 @@ const zExportCharts = zReport
export const exportRoutes = defineRoutes((app) =>
app
+ // V1's `preValidation` coercion hook, LOCAL to this surface (see
+ // http/query.ts).
+ .onTransform(parseQueryStringTransform)
.get(
'/export/events',
- async ({ query, client, status }) => {
+ async ({ query, client }) => {
const resolved = await resolveExportProjectId(client, query);
if (!resolved.ok) {
- return status(resolved.status, {
- error: 'Error',
- message: resolved.message,
- });
+ // V1's controller threw an `HttpError` and let the error handler
+ // shape it; the body is `{status, message}` because `HttpError.error`
+ // is undefined and JSON drops it.
+ throw new HttpError(resolved.message, { status: resolved.status });
}
const { getEventList, getEventsCount } = await loadDb();
const {
@@ -229,13 +232,13 @@ export const exportRoutes = defineRoutes((app) =>
)
.get(
'/export/charts',
- async ({ query, client, status }) => {
+ async ({ query, client }) => {
const resolved = await resolveExportProjectId(client, query);
if (!resolved.ok) {
- return status(resolved.status, {
- error: 'Error',
- message: resolved.message,
- });
+ // V1's controller threw an `HttpError` and let the error handler
+ // shape it; the body is `{status, message}` because `HttpError.error`
+ // is undefined and JSON drops it.
+ throw new HttpError(resolved.message, { status: resolved.status });
}
const { ChartEngine, getSettingsForProject } = await loadDb();
const { timezone } = await getSettingsForProject(resolved.projectId);
@@ -496,6 +499,7 @@ const zGscOpportunitiesQuery = zDateRange.extend({
export const insightsRoutes = defineRoutes((app) =>
app
+ .onTransform(parseQueryStringTransform)
.get(
'/insights/:projectId/overview',
async ({ params, query, client }) => {
diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.ts
index 13f14f933..58aa9a72a 100644
--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts
+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts
@@ -2,7 +2,7 @@
// methods themselves are exercised in gsc.service.test.ts.
import { expect, test } from 'bun:test';
-import type { Buffers, JobCtx } from '../../context';
+import type { AppDeps, Buffers, JobCtx } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
@@ -43,10 +43,10 @@ function stubJobCtx(gsc: Partial<GscService>, jobName = 'test'): JobCtx {
misc: {} as Services['misc'],
};
return {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: createRecordingProducers(queues).queues,
@@ -120,10 +120,10 @@ test('gscProjectBackfill delegates to runProjectBackfill', async () => {
test('gscSync fans out one gscProjectSync enqueue per connected project', async () => {
const producers = createRecordingProducers(queues);
const ctx: JobCtx = {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: producers.queues,
diff --git a/packages/core/src/modules/health/health.routes.ts b/packages/core/src/modules/health/health.routes.ts
index cf6eeddb2..c3d56c4b0 100644
--- a/packages/core/src/modules/health/health.routes.ts
+++ b/packages/core/src/modules/health/health.routes.ts
@@ -2,15 +2,20 @@
// controllers/healthcheck.controller.ts `liveness`/`readiness` and
// apps/worker/src/index.ts's two probes, which agreed on both bodies.
//
-// `/healthcheck` — the deep db/ch/redis probe — still waits for real clients
-// on `AppDeps` (P3+); porting it against `unknown` deps would be a fake check,
-// not a deferred one. `/healthz/ready` does NOT wait for them: its two inputs
-// are the shutdown flag and the events-consumer heartbeat, both of which are
-// real from P9 (M9-002), and a readiness probe that ignores a draining process
-// is the one that actually loses requests.
+// `/healthcheck` — the deep db/ch/redis probe — landed at M9-004, when
+// `AppDeps` started carrying the real clients; before that, porting it would
+// have been a fake check rather than a deferred one. `/healthz/ready` never
+// waited for them: its two inputs are the shutdown flag and the events-consumer
+// heartbeat, both real from P9 (M9-002), and a readiness probe that ignores a
+// draining process is the one that actually loses requests.
+//
+// `GET /` lands here too: V1 served it from the public-API scope
+// (apps/api/src/app.ts:400), hidden from the OpenAPI document like the probes,
+// and self-hosters use it as a "is this thing on" check.
import { z } from 'zod';
import { defineRoutes } from '../../http/define';
+import { tryCatch } from '../../shared/try-catch';
import { currentReadiness } from './src/readiness';
// The first zod schema through the OpenAPI plugin (ADR-003): response schemas
@@ -30,6 +35,13 @@ const healthReadyResponseSchema = z.object({
});
const SERVICE_UNAVAILABLE = 503;
+const OK = 200;
+
+/** V1's `GET /` body, byte-for-byte (apps/api/src/app.ts:401-404). */
+const ROOT_BODY = {
+ status: 'ok',
+ message: 'Successfully running OpenPanel.dev API',
+} as const;
// Hidden from the OpenAPI document — ported from V1's `schema: { hide: true }`
// on `/healthz/live`, `/healthz/ready` and `/healthcheck`
@@ -56,4 +68,67 @@ export const healthRoutes = defineRoutes((app) =>
detail: { hide: true },
}
)
+ .get(
+ '/healthcheck',
+ async ({ ctx, set }) => {
+ // `chQuery` (not `ctx.ch`) so the probe goes through the same
+ // round-robin + retry path every real read takes. Lazily, because a
+ // static import would construct a ClickHouse client in every test
+ // process that touches `rest.routes.ts`.
+ const { chQuery } = await import('@openpanel/db/src/clickhouse/client');
+ const [redisResult, dbResult, chResult] = await Promise.all([
+ tryCatch(async () => (await ctx.redis.ping()) === 'PONG'),
+ tryCatch(async () => Boolean(await ctx.db.$executeRaw`SELECT 1`)),
+ tryCatch(async () => (await chQuery('SELECT 1')).length > 0),
+ ]);
+
+ const dependencies = {
+ redis: redisResult.ok && redisResult.data,
+ db: dbResult.ok && dbResult.data,
+ ch: chResult.ok && chResult.data,
+ };
+ const dependencyErrors = {
+ redis: redisResult.error?.message,
+ db: dbResult.error?.message,
+ ch: chResult.error?.message,
+ };
+
+ const failedDependencies = Object.entries(dependencies)
+ .filter(([, ok]) => !ok)
+ .map(([name]) => name);
+ const workingDependencies = Object.entries(dependencies)
+ .filter(([, ok]) => ok)
+ .map(([name]) => name);
+
+ const status =
+ failedDependencies.length === 0 ? OK : SERVICE_UNAVAILABLE;
+
+ if (status === OK) {
+ ctx.logger.debug(
+ { workingDependencies, failedDependencies, dependencies },
+ 'healthcheck passed'
+ );
+ } else {
+ ctx.logger.warn(
+ {
+ workingDependencies,
+ failedDependencies,
+ dependencies,
+ dependencyErrors,
+ },
+ 'healthcheck failed'
+ );
+ }
+
+ set.status = status;
+ return {
+ ready: status === OK,
+ ...dependencies,
+ failedDependencies,
+ workingDependencies,
+ };
+ },
+ { detail: { hide: true } }
+ )
+ .get('/', () => ROOT_BODY, { detail: { hide: true } })
);
diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.ts
index 2fa70b13b..6ff83e71f 100644
--- a/packages/core/src/modules/import/import.jobs.test.ts
+++ b/packages/core/src/modules/import/import.jobs.test.ts
@@ -2,7 +2,7 @@
// themselves are exercised in import.service.test.ts.
import { expect, test } from 'bun:test';
-import type { Buffers, JobCtx } from '../../context';
+import type { AppDeps, Buffers, JobCtx } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
@@ -43,10 +43,10 @@ function stubJobCtx(importService: Partial<ImportService>): JobCtx {
misc: {} as Services['misc'],
};
return {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: createRecordingProducers(queues).queues,
diff --git a/packages/core/src/modules/import/import.routes.ts b/packages/core/src/modules/import/import.routes.ts
index f7802652f..3ad652519 100644
--- a/packages/core/src/modules/import/import.routes.ts
+++ b/packages/core/src/modules/import/import.routes.ts
@@ -46,7 +46,7 @@ export const importRoutes = defineRoutes((app) =>
}
},
{
- clientAuth: { allow: ['read', 'root'] },
+ clientAuth: { allow: ['read', 'root'], label: 'Import' },
body: z.array(z.unknown()),
detail: {
tags: ['Import'],
diff --git a/packages/core/src/modules/import/import.service.test.ts b/packages/core/src/modules/import/import.service.test.ts
index c98fbadd0..053e0e7af 100644
--- a/packages/core/src/modules/import/import.service.test.ts
+++ b/packages/core/src/modules/import/import.service.test.ts
@@ -5,7 +5,7 @@
// (side-effect-free) import.
import { beforeAll, expect, mock, test } from 'bun:test';
-import type { Buffers } from '../../context';
+import type { AppDeps, Buffers } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
@@ -160,10 +160,10 @@ test('updateImportStatus marks a failed step with its error message', async () =
test('ImportService.enqueue adds the import job onto the import queue', async () => {
const producers = createRecordingProducers(queues);
const service = createImportService({
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: producers.queues,
diff --git a/packages/core/src/modules/ingest/ingest.routes.ts b/packages/core/src/modules/ingest/ingest.routes.ts
index ef004a509..cc55a9efc 100644
--- a/packages/core/src/modules/ingest/ingest.routes.ts
+++ b/packages/core/src/modules/ingest/ingest.routes.ts
@@ -16,26 +16,41 @@
// Both routes carry the whole chain because V1's `fastify.addHook` calls are
// plugin-scoped, so `GET /track/device-id` goes through it too.
//
-// NAMED GAPS, same as profile.routes.ts: not yet reachable — main.ts does not
-// mount `publicApiRoutes` until a real `AppDeps` exists. V1's
-// `subscriptionHook` (the wind-down gate) is NOT ported here: it belongs to
-// the subscription/organization modules and reads `process.env.SELF_HOSTED`,
-// which core does not do. It stays live on V1's router.
+// M9-004 mounted this surface and closed the two gaps its header used to
+// record. V1's `subscriptionHook` (the wind-down gate) is now the last link in
+// the chain — `duplicate -> clientAuth -> isBot -> subscription`, V1's
+// registration order exactly — with `selfHosted` read off `AppDeps.config`
+// instead of `process.env`. And `POST /event`, the legacy compat route ADR-015
+// entry 1 was reversed to KEEP, is here beside `/track`: same hook chain plus
+// the per-client usage counter the deferred removal decision needs, recorded
+// after authentication (so a label can only ever be a client id that exists)
+// and before the hooks that can short-circuit (so a client whose events are
+// dropped as bot/wind-down traffic still counts as a client that would break
+// if `/event` disappeared).
import type { AppDeps, HttpCtx } from '../../context';
import { defineRoutes } from '../../http/define';
+import type { DeprecatedPostEventPayload } from './ingest.constants';
import { zTrackHandlerPayload } from './ingest.constants';
import {
checkIngestBot,
fetchDeviceIdentity,
+ ingestLegacyEvent,
ingestTrack,
isDuplicateIngestRequest,
+ isIngestionWoundDown,
type TrackOutcome,
} from './ingest.service';
import { toIngestHeaders } from './src/headers';
+import { recordLegacyEventRequest } from './src/ingest.metrics';
const TAGS = ['Track'];
+const LEGACY_EVENT_TAGS = ['Event'];
const DUPLICATE_BODY = 'Duplicate event';
+/** V1 answers 202 with `{blocked:true}` rather than 402/403 — see
+ * `isIngestionWoundDown`. */
+const WIND_DOWN_STATUS = 202;
+const ACCEPTED_STATUS = 202;
type StatusFn = (code: number, body?: unknown) => unknown;
@@ -100,6 +115,28 @@ async function botGuard({
}
}
+/** V1's `subscriptionHook`, the last `preHandler` on both ingest routers. */
+function windDownGuard(deps: AppDeps) {
+ return async ({
+ client,
+ ctx,
+ status,
+ }: {
+ client: { projectId: string | null };
+ ctx: HttpCtx;
+ status: StatusFn;
+ }) => {
+ const blocked = await isIngestionWoundDown({
+ projectId: client.projectId,
+ selfHosted: deps.config.selfHosted,
+ logger: ctx.logger,
+ });
+ if (blocked) {
+ return status(WIND_DOWN_STATUS, { blocked: true });
+ }
+ };
+}
+
export const ingestRoutes = defineRoutes((app, deps: AppDeps) =>
app.guard(
{
@@ -146,7 +183,7 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) =>
{
clientAuth: { ingest: true },
body: zTrackHandlerPayload,
- beforeHandle: botGuard,
+ beforeHandle: [botGuard, windDownGuard(deps)],
detail: {
tags: TAGS,
description:
@@ -184,7 +221,7 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) =>
},
{
clientAuth: { ingest: true },
- beforeHandle: botGuard,
+ beforeHandle: [botGuard, windDownGuard(deps)],
detail: {
tags: TAGS,
description:
@@ -192,5 +229,47 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) =>
},
}
)
+ .post(
+ '/event',
+ async ({ body, client, ctx, status, timestamp }) => {
+ const outcome = await ingestLegacyEvent(
+ {
+ projectId: client.projectId,
+ clientIp: ctx.ip,
+ headers: toIngestHeaders(ctx.headers),
+ clientSecretAuth: client.secretPresented,
+ timestamp,
+ body: body as DeprecatedPostEventPayload | null,
+ },
+ {
+ buffers: ctx.buffers,
+ produceIncomingEvent: deps.produceIncomingEvent,
+ }
+ );
+
+ if (outcome.status === 'missing-project-id') {
+ return status(400, 'missing origin');
+ }
+
+ return status(ACCEPTED_STATUS, 'ok');
+ },
+ {
+ clientAuth: { ingest: true },
+ // V1's own order: the usage metric is a `preHandler` registered
+ // after `clientHook` and before `isBotHook`/`subscriptionHook`.
+ beforeHandle: [
+ ({ client }: { client: { id: string } }) => {
+ recordLegacyEventRequest(client.id);
+ },
+ botGuard,
+ windDownGuard(deps),
+ ],
+ detail: {
+ tags: LEGACY_EVENT_TAGS,
+ description:
+ 'Deprecated direct event ingestion endpoint. Use /track instead.',
+ },
+ }
+ )
)
);
diff --git a/packages/core/src/modules/ingest/ingest.service.ts b/packages/core/src/modules/ingest/ingest.service.ts
index 555b77d25..91e8c60e5 100644
--- a/packages/core/src/modules/ingest/ingest.service.ts
+++ b/packages/core/src/modules/ingest/ingest.service.ts
@@ -30,6 +30,7 @@ import type { ServiceDeps } from '../../services';
import { parseUserAgent } from '../../shared/parser-user-agent';
import { generateDeviceId } from '../../shared/profileId';
import { createBotEvent } from '../event/event.service';
+import { getOrganizationByProjectIdCached } from '../organization/organization.service';
import {
getProfileById,
identifyProfile,
@@ -38,6 +39,7 @@ import {
import { getSalts } from '../salt/salt.service';
import { convertClickhouseDateToJs } from '../session/src/dates';
import type {
+ DeprecatedPostEventPayload,
IAssignGroupPayload,
IDecrementPayload,
IGroupPayload,
@@ -520,6 +522,163 @@ export async function ingestTrack(
};
}
+/**
+ * V1's `subscriptionHook` (apps/api/src/hooks/subscription.hook.ts), ported
+ * for both ingestion routes.
+ *
+ * Two things worth knowing about the shape of this, both V1's:
+ *
+ * It gates on `windDownStep`, not on `subscriptionState`. Every expired trial
+ * is already in `trial_expired`, so gating on the state would block thousands
+ * of orgs the moment this ships, skipping the four warning emails entirely.
+ *
+ * It answers 202, not 402 or 403 (the caller does; this returns the verdict).
+ * The SDKs treat only 401 and 2xx as terminal, so a "correct" status code
+ * would multiply traffic from exactly the clients we are trying to quiet down.
+ *
+ * `selfHosted` arrives from `AppDeps.config` — V1 read `process.env` here and
+ * core reads none.
+ */
+const WIND_DOWN_BLOCKED_STEPS = new Set(['blocked', 'final_warning']);
+
+export async function isIngestionWoundDown(request: {
+ projectId: string | null | undefined;
+ selfHosted: boolean;
+ logger: Logger;
+}): Promise<boolean> {
+ if (request.selfHosted || !request.projectId) {
+ return false;
+ }
+
+ const { projectId, logger } = request;
+
+ try {
+ // Cached for 5 minutes and invalidated by the Polar webhook, so paying
+ // again lifts the block on the next checkout rather than on a TTL.
+ const organization = await getOrganizationByProjectIdCached(projectId);
+
+ if (
+ !(
+ organization?.windDownStep &&
+ WIND_DOWN_BLOCKED_STEPS.has(organization.windDownStep)
+ )
+ ) {
+ return false;
+ }
+
+ logger.info(
+ {
+ organizationId: organization.id,
+ projectId,
+ windDownStep: organization.windDownStep,
+ },
+ 'Ingestion blocked by wind-down'
+ );
+ return true;
+ } catch (error) {
+ // Fail open. Dropping a paying customer's events because Redis or Postgres
+ // hiccuped is far worse than letting a blocked org through for a tick.
+ logger.error(
+ { err: error, projectId },
+ 'Wind-down check failed, allowing ingestion'
+ );
+ return false;
+ }
+}
+
+/**
+ * `POST /event` — the legacy compat route (ADR-004/ADR-015 entry 1, REVERSED:
+ * kept, not deleted, because production still has projects posting to it).
+ * Ported from apps/api/src/controllers/event.controller.ts.
+ *
+ * It is NOT `ingestTrack` with a different body: the legacy payload carries a
+ * client-supplied ISO `timestamp`, has no `type` discriminator, no schema, and
+ * no identify/increment/replay branches — so it builds its own queue payload
+ * exactly as V1's controller did, minting the event id at the producer like
+ * `/track` does.
+ */
+export type LegacyEventOutcome =
+ | { status: 'ok' }
+ | { status: 'missing-project-id' };
+
+export async function ingestLegacyEvent(
+ request: {
+ projectId: string | null | undefined;
+ clientIp: string;
+ headers: IngestHeaders;
+ clientSecretAuth: boolean;
+ /** The request-arrival timestamp (V1's `timestampHook`). */
+ timestamp: number | undefined;
+ body: DeprecatedPostEventPayload | null | undefined;
+ },
+ transport: IngestTransport
+): Promise<LegacyEventOutcome> {
+ const { projectId } = request;
+ if (!projectId) {
+ return { status: 'missing-project-id' };
+ }
+
+ // The cast is V1's own call (event.controller.ts:26): `/event` has no body
+ // schema, so `getTimestamp` reads `properties` off whatever arrived.
+ const { timestamp, isTimestampFromThePast } = getTimestamp(
+ request.timestamp,
+ request.body as ITrackHandlerPayload['payload']
+ );
+ const ip = request.clientIp;
+ const ua = headerValue(request.headers, 'user-agent') ?? FALLBACK_USER_AGENT;
+ const headers = getStringHeaders(request.headers);
+
+ const [salts, geo, asnInfo] = await Promise.all([
+ getSalts(),
+ getGeoLocation(ip),
+ getAsnInfo(ip),
+ ]);
+ const { deviceId, sessionId } = await getDeviceId({
+ projectId,
+ ip,
+ ua,
+ salts,
+ sessionBuffer: transport.buffers.session,
+ });
+
+ const uaInfo = parseUserAgent(ua, request.body?.properties);
+ // Mark (never block) likely bot traffic with __bot / __bot_reasons props.
+ // This deprecated route has no body schema, so body can be null/undefined.
+ if (request.body) {
+ request.body.properties = applyBotSuspicion(request.body.properties, {
+ asnInfo,
+ headers: request.headers,
+ clientSecretAuth: request.clientSecretAuth,
+ isServer: uaInfo.isServer,
+ });
+ }
+
+ const groupId = uaInfo.isServer
+ ? `${projectId}:${request.body?.profileId ?? generateId()}`
+ : deviceId;
+
+ await transport.produceIncomingEvent(
+ {
+ // See handleTrack: the producer mints the event id.
+ id: uuid(),
+ projectId,
+ headers,
+ event: {
+ ...request.body,
+ timestamp,
+ isTimestampFromThePast,
+ },
+ uaInfo,
+ geo,
+ deviceId,
+ sessionId: sessionId ?? '',
+ } as IncomingEventPayload,
+ groupId
+ );
+
+ return { status: 'ok' };
+}
+
export type DeviceIdentity =
| { status: 'ok'; deviceId: string; sessionId: string; message: string }
| { status: 'missing-project-id' }
diff --git a/packages/core/src/modules/ingest/legacy-event.test.ts b/packages/core/src/modules/ingest/legacy-event.test.ts
new file mode 100644
index 000000000..a031d5492
--- /dev/null
+++ b/packages/core/src/modules/ingest/legacy-event.test.ts
@@ -0,0 +1,196 @@
+/**
+ * Tests for the legacy `POST /event` compat route (ADR-015 entry 1, reversed:
+ * the route is KEPT, produces to Kafka exactly like /track, and is measured
+ * per client so the deferred removal decision has data).
+ *
+ * Ported from apps/api/src/controllers/event.controller.test.ts with M9-004,
+ * when the controller and its usage hook moved into this module. The producer
+ * is an argument now, so V1's `vi.mock` of @openpanel/queue becomes a plain
+ * stub, and the counter lives on core's one registry rather than prom-client's
+ * global one — same assertions.
+ *
+ * The `mixan-*` header fallback moved with the validator itself (M8-002) — see
+ * `src/client-auth.test.ts`.
+ */
+
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ mock,
+} from 'bun:test';
+import type { Buffers } from '../../buffers/create-buffers';
+import type { GeoLocation } from '../../clients/geo';
+import type { DeprecatedPostEventPayload } from './ingest.constants';
+import type { IncomingEventPayload } from './src/incoming-event';
+import {
+ legacyEventRequestsTotal,
+ recordLegacyEventRequest,
+} from './src/ingest.metrics';
+
+const PROJECT_ID = 'legacy-event-project';
+const CLIENT_ID = '11111111-1111-4111-8111-111111111111';
+const OTHER_CLIENT_ID = '22222222-2222-4222-8222-222222222222';
+const UUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+const getGeoLocation = mock(
+ async (): Promise<GeoLocation> => ({
+ country: 'SE',
+ city: 'Stockholm',
+ region: 'AB',
+ longitude: 18,
+ latitude: 59,
+ })
+);
+const getAsnInfo = mock(async () => ({
+ asn: 1234,
+ org: 'Example ISP',
+ isHosting: false,
+}));
+const getSalts = mock(async () => ({
+ current: 'salt-current',
+ previous: 'salt-previous',
+}));
+
+mock.module('../../clients/geo', () => ({ getGeoLocation, getAsnInfo }));
+
+let ingestLegacyEvent: typeof import('./ingest.service').ingestLegacyEvent;
+
+// The salt module is spread and then overridden by name: it exports
+// fetchSalts/createInitialSalts/rotateSalt besides getSalts, so a factory
+// returning only the override makes the rest vanish.
+let realSaltService: typeof import('../salt/salt.service');
+beforeAll(async () => {
+ realSaltService = { ...(await import('../salt/salt.service')) };
+ mock.module('../salt/salt.service', () => ({ ...realSaltService, getSalts }));
+ ({ ingestLegacyEvent } = await import('./ingest.service'));
+});
+
+// salt.service.ts's own rotateSalt calls the exported `getSalts` internally (to
+// invalidate its cache), so leaving this file's fake — which has no `.clear()`
+// — in the module registry breaks salt.service.test.ts under a bare (non
+// `--isolate`) `bun test`, which shares one registry across the whole run.
+afterAll(() => {
+ mock.module('../salt/salt.service', () => realSaltService);
+});
+
+const produced: { payload: IncomingEventPayload; partitionKey: string }[] = [];
+const produceIncomingEvent = async (
+ payload: IncomingEventPayload,
+ partitionKey: string
+) => {
+ produced.push({ payload, partitionKey });
+};
+
+// The legacy route resolves a device id, which is the only buffer read on
+// this path (`getExistingSession`, once per salt candidate).
+const buffers = {
+ session: { getExistingSession: async () => null },
+ replay: {},
+ group: {},
+} as unknown as Buffers;
+
+const legacyBody = (
+ overrides: Partial<DeprecatedPostEventPayload> = {}
+): DeprecatedPostEventPayload => ({
+ name: 'legacy_event',
+ timestamp: new Date('2026-01-01T00:00:00.000Z').toISOString(),
+ properties: { __referrer: '', foo: 'bar' },
+ ...overrides,
+});
+
+const requestTimestamp = Date.now();
+
+const makeRequest = (projectId: string | null = PROJECT_ID) => ({
+ projectId,
+ clientIp: '203.0.113.10',
+ headers: { 'user-agent': 'Mozilla/5.0 (Macintosh)' },
+ clientSecretAuth: false,
+ timestamp: requestTimestamp,
+ body: legacyBody(),
+});
+
+const counterValue = async (clientId: string) => {
+ const { values } = await legacyEventRequestsTotal.get();
+ return (
+ values.find((value) => value.labels.client_id === clientId)?.value ?? 0
+ );
+};
+
+beforeEach(() => {
+ produced.length = 0;
+});
+
+describe('ingestLegacyEvent', () => {
+ it('produces the legacy payload to Kafka and reports ok', async () => {
+ const outcome = await ingestLegacyEvent(makeRequest(), {
+ buffers,
+ produceIncomingEvent,
+ });
+
+ expect(outcome.status).toBe('ok');
+ expect(produced).toHaveLength(1);
+ const { payload, partitionKey } = produced[0]!;
+
+ expect(payload.projectId).toBe(PROJECT_ID);
+ expect(payload.event.name).toBe('legacy_event');
+ expect(payload.event.properties).toMatchObject({ foo: 'bar' });
+ expect(payload.deviceId).toBeTruthy();
+ expect(partitionKey).toBe(payload.deviceId);
+ });
+
+ it('mints the event id at the producer, like /track', async () => {
+ await ingestLegacyEvent(makeRequest(), { buffers, produceIncomingEvent });
+
+ expect(produced[0]?.payload.id).toMatch(UUID_PATTERN);
+ });
+
+ it('replaces the client-supplied timestamp with the server timestamp', async () => {
+ await ingestLegacyEvent(makeRequest(), { buffers, produceIncomingEvent });
+
+ const { payload } = produced[0]!;
+ expect(payload.event.timestamp).toBe(requestTimestamp);
+ expect(payload.event.isTimestampFromThePast).toBe(false);
+ });
+
+ it('refuses when the client carries no project', async () => {
+ const outcome = await ingestLegacyEvent(makeRequest(null), {
+ buffers,
+ produceIncomingEvent,
+ });
+
+ expect(outcome.status).toBe('missing-project-id');
+ expect(produced).toHaveLength(0);
+ });
+});
+
+describe('recordLegacyEventRequest', () => {
+ it('counts a request against its client id', async () => {
+ const before = await counterValue(CLIENT_ID);
+
+ recordLegacyEventRequest(CLIENT_ID);
+
+ expect(await counterValue(CLIENT_ID)).toBe(before + 1);
+ });
+
+ it('keeps one series per client', async () => {
+ const before = await counterValue(OTHER_CLIENT_ID);
+ const otherBefore = await counterValue(CLIENT_ID);
+
+ recordLegacyEventRequest(OTHER_CLIENT_ID);
+
+ expect(await counterValue(OTHER_CLIENT_ID)).toBe(before + 1);
+ expect(await counterValue(CLIENT_ID)).toBe(otherBefore);
+ });
+
+ it('is exposed under the name the removal decision will query', async () => {
+ expect(await legacyEventRequestsTotal.get()).toMatchObject({
+ name: 'openpanel_legacy_event_requests_total',
+ type: 'counter',
+ });
+ });
+});
diff --git a/packages/core/src/modules/ingest/src/ingest.metrics.ts b/packages/core/src/modules/ingest/src/ingest.metrics.ts
index 366996c3d..36fb0b4eb 100644
--- a/packages/core/src/modules/ingest/src/ingest.metrics.ts
+++ b/packages/core/src/modules/ingest/src/ingest.metrics.ts
@@ -68,3 +68,27 @@ export const ingestConsumerMetrics = {
deadLetterFailed: (partition: string) =>
kafkaDeadLetterFailedTotal.inc({ partition }),
} satisfies ConsumerMetrics;
+
+const LEGACY_EVENT_CLIENT_ID_LABEL = 'client_id';
+
+/**
+ * ADR-015 entry 1 was reversed: `POST /event` is kept as a legacy compat route
+ * rather than deleted, because production still has projects posting to it.
+ * This counter is the evidence the deferred removal decision needs — when it
+ * reads zero for every client, `/event` and the `mixan-*` header fallback can
+ * both go (ADR-015 entry 5 is pending the same measurement).
+ *
+ * Moved from apps/api/src/metrics.ts, which registered on prom-client's global
+ * registry because `fastify-metrics` served that one. V2 has exactly one
+ * registry and it is this package's.
+ */
+export const legacyEventRequestsTotal = new client.Counter({
+ name: 'openpanel_legacy_event_requests_total',
+ help: 'Requests to the legacy POST /event ingestion route, by client id',
+ labelNames: [LEGACY_EVENT_CLIENT_ID_LABEL],
+ registers: [registry],
+});
+
+export function recordLegacyEventRequest(clientId: string): void {
+ legacyEventRequestsTotal.inc({ [LEGACY_EVENT_CLIENT_ID_LABEL]: clientId });
+}
diff --git a/packages/core/src/modules/ingest/wind-down.test.ts b/packages/core/src/modules/ingest/wind-down.test.ts
new file mode 100644
index 000000000..cad18ba4f
--- /dev/null
+++ b/packages/core/src/modules/ingest/wind-down.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Tests for `isIngestionWoundDown` — the gate that stops ingestion for
+ * organizations blocked by the wind-down sequence.
+ *
+ * Ported from apps/api/src/hooks/subscription.hook.test.ts with M9-004, when
+ * V1's `subscriptionHook` moved into the ingest module. Same three behaviours
+ * matter: it gates on the wind-down STEP rather than the subscription state
+ * (so an expired trial keeps ingesting until it has actually been warned), the
+ * caller answers 202 rather than a 4xx (the SDKs retry everything except 401
+ * and 2xx), and it fails open. `SELF_HOSTED` is a `selfHosted` argument now —
+ * core reads no environment — so V1's `vi.stubEnv` becomes a parameter.
+ */
+
+import { beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
+import type { Logger } from '../../logger';
+
+const getOrganizationByProjectIdCached = mock(
+ async (_projectId: string): Promise<unknown> => null
+);
+
+// Spread the real module: a partial factory replaces the whole barrel, and
+// every other importer of it then fails on a missing export.
+const organizationService = await import(
+ '../organization/organization.service'
+);
+mock.module('../organization/organization.service', () => ({
+ ...organizationService,
+ getOrganizationByProjectIdCached,
+}));
+
+let isIngestionWoundDown: typeof import('./ingest.service').isIngestionWoundDown;
+
+beforeAll(async () => {
+ ({ isIngestionWoundDown } = await import('./ingest.service'));
+});
+
+function makeLogger() {
+ const calls = { info: 0, warn: 0, error: 0 };
+ const noop = () => undefined;
+ const logger = {
+ info: () => {
+ calls.info++;
+ },
+ warn: () => {
+ calls.warn++;
+ },
+ error: () => {
+ calls.error++;
+ },
+ debug: noop,
+ trace: noop,
+ fatal: noop,
+ child: () => logger,
+ } as unknown as Logger;
+ return { logger, calls };
+}
+
+beforeEach(() => {
+ getOrganizationByProjectIdCached.mockReset();
+});
+
+describe('isIngestionWoundDown', () => {
+ for (const windDownStep of ['blocked', 'final_warning']) {
+ it(`blocks ingestion at step ${windDownStep}`, async () => {
+ getOrganizationByProjectIdCached.mockResolvedValue({
+ id: 'org-1',
+ windDownStep,
+ });
+ const { logger } = makeLogger();
+
+ expect(
+ await isIngestionWoundDown({
+ projectId: 'proj-1',
+ selfHosted: false,
+ logger,
+ })
+ ).toBe(true);
+ expect(getOrganizationByProjectIdCached).toHaveBeenCalledWith('proj-1');
+ });
+ }
+
+ for (const windDownStep of ['expired_notice', 'stopping_soon']) {
+ it(`still accepts ingestion at step ${windDownStep}`, async () => {
+ getOrganizationByProjectIdCached.mockResolvedValue({
+ id: 'org-1',
+ windDownStep,
+ });
+ const { logger } = makeLogger();
+
+ expect(
+ await isIngestionWoundDown({
+ projectId: 'proj-1',
+ selfHosted: false,
+ logger,
+ })
+ ).toBe(false);
+ expect(getOrganizationByProjectIdCached).toHaveBeenCalled();
+ });
+ }
+
+ it('accepts ingestion from an expired trial that has not been warned yet', async () => {
+ // The reason the gate reads windDownStep and not subscriptionState: every
+ // lapsed trial is already trial_expired, so gating on state would block
+ // thousands of orgs the moment this ships.
+ getOrganizationByProjectIdCached.mockResolvedValue({
+ id: 'org-1',
+ subscriptionState: 'trial_expired',
+ windDownStep: null,
+ });
+ const { logger } = makeLogger();
+
+ expect(
+ await isIngestionWoundDown({
+ projectId: 'proj-1',
+ selfHosted: false,
+ logger,
+ })
+ ).toBe(false);
+ });
+
+ it('fails open when the organization lookup throws', async () => {
+ getOrganizationByProjectIdCached.mockRejectedValue(new Error('redis down'));
+ const { logger, calls } = makeLogger();
+
+ expect(
+ await isIngestionWoundDown({
+ projectId: 'proj-1',
+ selfHosted: false,
+ logger,
+ })
+ ).toBe(false);
+ expect(calls.error).toBe(1);
+ });
+
+ it('does nothing when self hosted', async () => {
+ const { logger } = makeLogger();
+
+ expect(
+ await isIngestionWoundDown({
+ projectId: 'proj-1',
+ selfHosted: true,
+ logger,
+ })
+ ).toBe(false);
+ expect(getOrganizationByProjectIdCached).not.toHaveBeenCalled();
+ });
+
+ it('does nothing without a resolved client project', async () => {
+ const { logger } = makeLogger();
+
+ expect(
+ await isIngestionWoundDown({
+ projectId: null,
+ selfHosted: false,
+ logger,
+ })
+ ).toBe(false);
+ expect(getOrganizationByProjectIdCached).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.ts
index 7d7ecad70..578b0d9d8 100644
--- a/packages/core/src/modules/insight/insight.jobs.test.ts
+++ b/packages/core/src/modules/insight/insight.jobs.test.ts
@@ -2,7 +2,7 @@
// methods themselves are exercised in insight.service.test.ts.
import { expect, test } from 'bun:test';
-import type { Buffers, JobCtx } from '../../context';
+import type { AppDeps, Buffers, JobCtx } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
@@ -54,10 +54,10 @@ function stubJobCtx(
misc: {} as Services['misc'],
};
return {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: createRecordingProducers(queues).queues,
@@ -114,10 +114,10 @@ test('insightsProject delegates to runProjectInsights', async () => {
test('insightsDaily fans out one insightsProject enqueue per candidate, jobId deduped by day+project', async () => {
const producers = createRecordingProducers(queues);
const ctx: JobCtx = {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: producers.queues,
diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.ts
index 54bc75184..94bba6cf1 100644
--- a/packages/core/src/modules/insight/insight.service.test.ts
+++ b/packages/core/src/modules/insight/insight.service.test.ts
@@ -5,7 +5,7 @@
// (side-effect-free) import.
import { beforeAll, expect, mock, test } from 'bun:test';
-import type { Buffers } from '../../context';
+import type { AppDeps, Buffers } from '../../context';
const listProjectIdsForCadence = mock(async () => ['p1', 'p2']);
const getProjectCreatedAt = mock(async () => null);
@@ -166,10 +166,10 @@ test('createInsightService binds every InsightService method', () => {
child: () => logger,
};
const service = subject.createInsightService({
- db: undefined,
- ch: undefined,
- redis: undefined,
- clients: undefined,
+ db: undefined as unknown as AppDeps['db'],
+ ch: undefined as unknown as AppDeps['ch'],
+ redis: undefined as unknown as AppDeps['redis'],
+ clients: undefined as unknown as AppDeps['clients'],
buffers: undefined as unknown as Buffers,
logger,
queues:
diff --git a/packages/core/src/modules/mcp/mcp.routes.ts b/packages/core/src/modules/mcp/mcp.routes.ts
index 42889c122..7b762e15d 100644
--- a/packages/core/src/modules/mcp/mcp.routes.ts
+++ b/packages/core/src/modules/mcp/mcp.routes.ts
@@ -11,6 +11,10 @@
// Rate limiting (V1: 60/min via Fastify's activateRateLimiter) is not wired
// here yet — nothing reaches this route until dashboardRoutes mounts, so it
// is a port task for whenever that happens, not a gap specific to MCP.
+//
+// The JSON-RPC body comes off the CONTEXT, not from `request.json()`: Elysia
+// has already consumed the stream by the time the handler runs, and reading it
+// twice throws "Body already used" (M9-004, caught by the auth contracts).
import { defineRoutes } from '../../http/define';
@@ -19,15 +23,13 @@ function loadMcpService() {
}
export const mcpRoutes = defineRoutes((app) =>
- app.post('/mcp', async ({ request, set }) => {
+ app.post('/mcp', async ({ body, query, request, set }) => {
const { extractToken, handleStatelessMcpRequest } = await loadMcpService();
- const url = new URL(request.url);
const token = extractToken(
- Object.fromEntries(url.searchParams),
+ query as Record<string, string>,
request.headers.get('authorization') ?? undefined
);
- const body = await request.json();
const { status, body: responseBody } = await handleStatelessMcpRequest(
token,
diff --git a/packages/core/src/modules/notification/notification.jobs.test.ts b/packages/core/src/modules/notification/notification.jobs.test.ts
index 0f821bcc4..425be01a9 100644
--- a/packages/core/src/modules/notification/notification.jobs.test.ts
+++ b/packages/core/src/modules/notification/notification.jobs.test.ts
@@ -2,7 +2,7 @@
// dispatch logic themselves are exercised in notification.service.test.ts.
import { expect, test } from 'bun:test';
-import type { Buffers, JobCtx } from '../../context';
+import type { AppDeps, Buffers, JobCtx } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
@@ -43,10 +43,10 @@ function stubJobCtx(notification: Partial<NotificationService>): JobCtx {
misc: {} as Services['misc'],
};
return {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: createRecordingProducers(queues).queues,
diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
index 23ecb07cc..48bb8abcd 100644
--- a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
@@ -2,7 +2,7 @@
// method itself is exercised in onboarding.service.test.ts.
import { expect, test } from 'bun:test';
-import type { Buffers, JobCtx } from '../../context';
+import type { AppDeps, Buffers, JobCtx } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
@@ -46,10 +46,10 @@ function stubJobCtx(
misc: {} as Services['misc'],
};
return {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: createRecordingProducers(queues).queues,
diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.ts
index bff8dc3d2..94282b8c8 100644
--- a/packages/core/src/modules/organization/organization.jobs.test.ts
+++ b/packages/core/src/modules/organization/organization.jobs.test.ts
@@ -2,7 +2,7 @@
// method itself is exercised in organization.service.test.ts.
import { expect, test } from 'bun:test';
-import type { Buffers, JobCtx } from '../../context';
+import type { AppDeps, Buffers, JobCtx } from '../../context';
import { createRecordingProducers } from '../../jobs/testing';
import { queues } from '../../jobs.registry';
import type { Logger } from '../../logger';
@@ -49,10 +49,10 @@ function stubJobCtx(
misc: {} as Services['misc'],
};
return {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
logger: stubLogger(),
queues: createRecordingProducers(queues).queues,
diff --git a/packages/core/src/modules/profile/profile.routes.test.ts b/packages/core/src/modules/profile/profile.routes.test.ts
index 4c7e031a8..33516282b 100644
--- a/packages/core/src/modules/profile/profile.routes.test.ts
+++ b/packages/core/src/modules/profile/profile.routes.test.ts
@@ -10,6 +10,7 @@ import { stubAppDeps } from '../../../test/http-fixtures';
import type {
AuthenticatedClient,
ClientAuthOptions,
+ ClientAuthResult,
} from '../../http/client-auth';
import type {
AdjustProfilePropertyResult,
@@ -26,7 +27,7 @@ const CLIENT: AuthenticatedClient = {
};
const GEO = { country: 'SE', city: 'Stockholm' };
-let client: AuthenticatedClient | null = CLIENT;
+let clientResult: ClientAuthResult = { ok: true, client: CLIENT };
let adjustResult: AdjustProfilePropertyResult = {
status: 'ok',
profileId: 'prof-1',
@@ -34,7 +35,7 @@ let adjustResult: AdjustProfilePropertyResult = {
const authenticateClient = mock(
(_deps: unknown, _headers: Headers, _options: ClientAuthOptions) =>
- Promise.resolve(client)
+ Promise.resolve(clientResult)
);
const identifyProfile = mock(
(
@@ -68,8 +69,8 @@ beforeAll(async () => {
});
beforeEach(() => {
- client = CLIENT;
adjustResult = { status: 'ok', profileId: 'prof-1' };
+ clientResult = { ok: true, client: CLIENT };
authenticateClient.mockClear();
identifyProfile.mockClear();
adjustProfileProperty.mockClear();
@@ -140,7 +141,7 @@ test('adjust results map to V1 status codes and bodies', async () => {
});
test('a client without a project answers 400 before touching the service', async () => {
- client = { ...CLIENT, projectId: null };
+ clientResult = { ok: true, client: { ...CLIENT, projectId: null } };
const response = await post('/profile', { profileId: 'prof-1' });
@@ -150,7 +151,7 @@ test('a client without a project answers 400 before touching the service', async
});
test('every /profile route requires client credentials', async () => {
- client = null;
+ clientResult = { ok: false, ingest: true, message: 'Missing client id' };
for (const path of ['/profile', '/profile/increment', '/profile/decrement']) {
const response = await post(path, { profileId: 'prof-1' });
diff --git a/packages/core/src/modules/project/project.routes.ts b/packages/core/src/modules/project/project.routes.ts
index b60799266..fb0f32904 100644
--- a/packages/core/src/modules/project/project.routes.ts
+++ b/packages/core/src/modules/project/project.routes.ts
@@ -32,7 +32,10 @@ export const projectRoutes = defineRoutes((app) =>
async ({ client }) => ({
data: await listProjectsForOrganization(client.organizationId),
}),
- { clientAuth: { allow: ['root'] }, detail: { tags: ['Manage'] } }
+ {
+ clientAuth: { allow: ['root'], label: 'Manage' },
+ detail: { tags: ['Manage'] },
+ }
)
.get(
'/manage/projects/:id',
@@ -50,7 +53,7 @@ export const projectRoutes = defineRoutes((app) =>
return { data: project };
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
params: idParams,
detail: { tags: ['Manage'] },
}
@@ -69,7 +72,7 @@ export const projectRoutes = defineRoutes((app) =>
return { data: { ...project, client: firstClient } };
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
body: zCreateProject,
detail: { tags: ['Manage'] },
}
@@ -91,7 +94,7 @@ export const projectRoutes = defineRoutes((app) =>
return { data: project };
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
params: idParams,
body: zUpdateProject,
detail: { tags: ['Manage'] },
@@ -113,7 +116,7 @@ export const projectRoutes = defineRoutes((app) =>
return { success: true };
},
{
- clientAuth: { allow: ['root'] },
+ clientAuth: { allow: ['root'], label: 'Manage' },
params: idParams,
detail: { tags: ['Manage'] },
}
diff --git a/packages/core/src/modules/subscription/subscription.routes.ts b/packages/core/src/modules/subscription/subscription.routes.ts
index 50a8b966f..5d8ed6792 100644
--- a/packages/core/src/modules/subscription/subscription.routes.ts
+++ b/packages/core/src/modules/subscription/subscription.routes.ts
@@ -12,24 +12,28 @@
// equivalent named in ADR-002's plugin substitutions ("raw body → `await
// request.text()` in the one polar webhook handler").
//
-// NAMED GAP, same as gsc.routes.ts / import.routes.ts: this route is not yet
-// reachable — main.ts does not mount `publicApiRoutes` until a real
-// `AppDeps` exists (P3/P4/P8).
+// `parse: 'none'` is what makes that possible: Elysia parses the body before
+// the handler runs by default, and reading the consumed stream throws "Body
+// already used" (M9-004, which mounted this surface).
import { defineRoutes } from '../../http/define';
import { handlePolarWebhookEvent } from './subscription.service';
export const subscriptionRoutes = defineRoutes((app) =>
- app.post('/webhook/polar', async ({ request, ctx, status }) => {
- const rawBody = await request.text();
- const headers = Object.fromEntries(request.headers);
+ app.post(
+ '/webhook/polar',
+ async ({ request, ctx, status }) => {
+ const rawBody = await request.text();
+ const headers = Object.fromEntries(request.headers);
- try {
- await handlePolarWebhookEvent(rawBody, headers, ctx.logger);
- } catch {
- return status(500, 'Error');
- }
+ try {
+ await handlePolarWebhookEvent(rawBody, headers, ctx.logger);
+ } catch {
+ return status(500, 'Error');
+ }
- return status(202, 'OK');
- })
+ return status(202, 'OK');
+ },
+ { parse: 'none' }
+ )
);
diff --git a/packages/core/src/rpc/base.test.ts b/packages/core/src/rpc/base.test.ts
index 1efa03749..a899dc3da 100644
--- a/packages/core/src/rpc/base.test.ts
+++ b/packages/core/src/rpc/base.test.ts
@@ -131,7 +131,13 @@ test('the session is resolved once, before any procedure runs', async () => {
expect(ctx.session).toEqual(TEST_SESSION);
});
-test('the HttpCtx is inherited, not copied — services stay lazy', async () => {
+// M9-004 flipped this from "inherited" to "flattened", because tRPC merges
+// middleware context with `{...ctx, ...next.ctx}` — a spread, which copies own
+// enumerable properties ONLY. Under the prototype-chained shape every
+// inherited field vanished the first time a middleware called `next({ ctx })`,
+// and the next read was a TypeError inside a mutation (caught by the auth
+// contract suite, group c/d).
+test('the HttpCtx is flattened onto own properties, and services stay lazy', async () => {
const { ctx } = stubHttpCtx();
const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
cookieOptions: COOKIE_OPTIONS,
@@ -139,10 +145,28 @@ test('the HttpCtx is inherited, not copied — services stay lazy', async () =>
expect(trpcCtx.requestId).toBe(ctx.requestId);
expect(trpcCtx.logger).toBe(ctx.logger);
- expect(Object.getPrototypeOf(trpcCtx)).toBe(ctx);
- // `services` lives on the prototype's own descriptor; reading it here would
- // build the container, so assert only that we did not shadow it.
- expect(Object.hasOwn(trpcCtx, 'services')).toBe(false);
+ expect(Object.hasOwn(trpcCtx, 'logger')).toBe(true);
+ expect(Object.hasOwn(trpcCtx, 'db')).toBe(true);
+ expect(Object.hasOwn(trpcCtx, 'queues')).toBe(true);
+ // `services` is copied as a DESCRIPTOR, not read, so the container is still
+ // built on first access rather than by the context builder.
+ expect(
+ Object.getOwnPropertyDescriptor(trpcCtx, 'services')?.get
+ ).toBeDefined();
+});
+
+test('a middleware spread of the context keeps every field', async () => {
+ const { ctx } = stubHttpCtx();
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+
+ // Exactly what tRPC does in `next({ ctx })`.
+ const merged = { ...trpcCtx, session: trpcCtx.session };
+
+ expect(merged.logger).toBe(ctx.logger);
+ expect(merged.requestId).toBe(ctx.requestId);
+ expect(merged.queues).toBe(trpcCtx.queues);
});
test('simulateLatency delays the context, and is off by default', async () => {
diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.ts
index a2e935b38..fe96a887f 100644
--- a/packages/core/src/rpc/base.ts
+++ b/packages/core/src/rpc/base.ts
@@ -13,6 +13,7 @@ import superjson from 'superjson';
import { ZodError, z } from 'zod';
import type { HttpCtx, Session } from '../context';
import type { Logger } from '../logger';
+import { EMPTY_SESSION } from '../modules/auth/src/login-session';
import { type CookieOptions, serializeCookie } from '../shared/cookie';
/**
@@ -170,13 +171,24 @@ export async function makeTrpcContext(
);
};
- // Prototype-chained onto the HttpCtx, never spread: `{ ...ctx }` reads
- // `services` and forces the build the lazy getter exists to avoid.
- const trpcCtx = Object.create(ctx) as TrpcContext;
+ // FLAT, not prototype-chained onto the HttpCtx. tRPC merges middleware
+ // context with `{...ctx, ...next.ctx}`, which copies own enumerable
+ // properties only — so an inherited `logger`/`db`/`queues` disappears the
+ // first time a middleware calls `next({ ctx })`, and the next read of it is
+ // a TypeError in the middle of a mutation. Descriptors are COPIED rather
+ // than values read, so `services` stays a getter here; tRPC's own spread is
+ // what eventually forces it, and only on the RPC path.
+ const trpcCtx = flattenCtx(ctx) as unknown as TrpcContext;
Object.defineProperties(trpcCtx, {
// Resolved once here, shadowing HttpCtx's resolver. One HTTP request is
// one `createContext` call, so a batched request still costs one lookup.
- session: { value: await ctx.session(), enumerable: true },
+ // `HttpCtx.session()` answers `null` for "nobody is signed in" (see
+ // http/session.ts); V1's routers read `ctx.session.userId`, so the empty
+ // shape — not `null` — is what a procedure must see.
+ session: {
+ value: (await ctx.session()) ?? EMPTY_SESSION,
+ enumerable: true,
+ },
// The fetch adapter is handed a `Request`, which carries no peer address.
// Elysia's `server.requestIP()` is the source when the dashboard scope
// mounts; until then the limiter falls back to its shared bucket.
@@ -187,6 +199,23 @@ export async function makeTrpcContext(
return trpcCtx;
}
+/** Own + inherited property descriptors, own-first, on one flat object. */
+function flattenCtx(ctx: HttpCtx): Record<string, unknown> {
+ const flat: Record<string, unknown> = {};
+ let source: object | null = ctx;
+ while (source && source !== Object.prototype) {
+ for (const [key, descriptor] of Object.entries(
+ Object.getOwnPropertyDescriptors(source)
+ )) {
+ if (!Object.hasOwn(flat, key)) {
+ Object.defineProperty(flat, key, descriptor);
+ }
+ }
+ source = Object.getPrototypeOf(source);
+ }
+ return flat;
+}
+
/** The subset of the Redis cache the RPC layer uses. */
export interface RpcCache {
getJson<T = unknown>(key: string): Promise<T | null>;
diff --git a/packages/core/test/http-fixtures.ts b/packages/core/test/http-fixtures.ts
index f5ed3407a..18cd04a9f 100644
--- a/packages/core/test/http-fixtures.ts
+++ b/packages/core/test/http-fixtures.ts
@@ -38,10 +38,10 @@ export function stubAppDeps(): AppDepsStub {
scopeCalls: () => scopeCalls,
childCalls: () => childCalls,
deps: {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
producers,
produceIncomingEvent: () => Promise.resolve(),
diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.ts
index 1a8712e6d..81e6bb3cb 100644
--- a/packages/core/test/request-id-end-to-end.test.ts
+++ b/packages/core/test/request-id-end-to-end.test.ts
@@ -140,10 +140,10 @@ function stubDeps() {
const lines: CapturedLine[] = [];
const deps: AppDeps = {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
producers: producers as unknown as QueueProducerHandle,
produceIncomingEvent: () => Promise.resolve(),
diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.ts
index 4dd67c904..a9a809c9d 100644
--- a/packages/core/test/rpc-fixtures.ts
+++ b/packages/core/test/rpc-fixtures.ts
@@ -86,10 +86,10 @@ export function stubHttpCtx(
const stub = { sessionCalls: 0 };
const deps: AppDeps = {
- db: {},
- ch: {},
- redis: {},
- clients: {},
+ db: {} as AppDeps['db'],
+ ch: {} as AppDeps['ch'],
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
buffers: {} as Buffers,
producers: createRecordingProducers(queues),
produceIncomingEvent: () => Promise.resolve(),
diff --git a/packages/db/src/prisma-client.ts b/packages/db/src/prisma-client.ts
index a4eb1edcd..7f986dd46 100644
--- a/packages/db/src/prisma-client.ts
+++ b/packages/db/src/prisma-client.ts
@@ -15,6 +15,14 @@ const getPrismaClient = () => {
// emit: 'event' keeps the engine from writing prisma:error lines straight
// to stderr, so they flow through pino to the OTLP pipeline instead.
const client = new PrismaClient({
+ // Callsite-free error messages. V1 shipped a bundle, so Prisma could not
+ // resolve a call site and always produced the short
+ // `Invalid \`prisma.model.action()\` invocation:` form; V2 runs from
+ // source, where the default format would splice the file, the line and a
+ // source snippet into a message that reaches API clients verbatim (three
+ // golden error responses caught exactly that). `minimal` keeps V1's body
+ // and keeps our source layout out of a 500.
+ errorFormat: 'minimal',
log: [
{ emit: 'event', level: 'error' },
{ emit: 'event', level: 'warn' },
diff --git a/packages/trpc/src/trpc.ts b/packages/trpc/src/trpc.ts
index fb0cbbef6..69a3c690c 100644
--- a/packages/trpc/src/trpc.ts
+++ b/packages/trpc/src/trpc.ts
@@ -1,31 +1,27 @@
-// V1's tRPC surface, rebased onto @openpanel/core's RPC base (ADR-009).
+// The tRPC procedure stack, on @openpanel/core's RPC base (ADR-009).
//
-// There is exactly ONE tRPC instance in the repo now: `initTRPC` is called in
+// There is exactly ONE tRPC instance in the repo: `initTRPC` is called in
// core/src/rpc/base.ts and nowhere else, so the transformer, the
-// errorFormatter, `Meta` and the context type are single-sourced. V1 keeps its
-// Fastify adapter and V2 gets `createTrpcFetchHandler`; both mount routers
-// built from the same `procedure`.
+// errorFormatter, `Meta` and the context type are single-sourced. M9-004
+// deleted the Fastify adapter and its `createContext` with the V1 boot; the
+// one mount left is `createTrpcFetchHandler`, called from `main.ts`.
//
// What still lives here is what core cannot import without pulling a database
// into a package that must stay bootable with none: the procedures below need
// `runWithAlsSession` and the access ladder's real lookups. They move into
-// core with auth at P6, at which point this file is a re-export.
+// core with auth at P10, at which point this file is a re-export.
import {
- COOKIE_OPTIONS,
- type Ctx,
createCacheMiddleware,
createRateLimitMiddleware,
middleware,
procedure,
- type QueueProducers,
type RpcCache,
type TrpcContext,
} from '@openpanel/core';
-import { runWithAlsSession, type SessionValidationResult } from '@openpanel/db';
+import { runWithAlsSession } from '@openpanel/db';
import { getRedisCache } from '@openpanel/redis';
import { TRPCError } from '@trpc/server';
-import type { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
import { has } from 'ramda';
import { getOrganizationAccess, requireProjectAccess } from './access';
import { TRPCForbiddenError } from './errors';
@@ -37,145 +33,6 @@ export { createTRPCRouter } from '@openpanel/core';
/** What a procedure receives. Core's type, not a second declaration. */
export type Context = TrpcContext;
-/** What apps/api's hooks decorate the request with (apps/api/src/app.ts). */
-type FastifyRequestWithSession = CreateFastifyContextOptions['req'] & {
- session: SessionValidationResult;
- cookies?: Record<string, string | undefined>;
- clientIp?: string;
-};
-
-const ARTIFICIAL_LATENCY_SPREAD_MS = 500;
-const ARTIFICIAL_LATENCY_MAX_MS = 200;
-
-/**
- * The V1 Fastify adapter's context builder.
- *
- * It is deliberately not core's `makeTrpcContext`: that one writes cookies
- * through the fetch adapter's `resHeaders`, while Fastify's reply is the
- * guaranteed path out here, and V1's session is already resolved by the
- * `onRequest` hook in apps/api/src/app.ts. Everything else — the option
- * precedence, the artificial latency, the fields — is V1's, unchanged.
- *
- * V2's builder is `makeTrpcContext`; this one dies with `apps/worker` at P9.
- */
-export async function createContext({
- req,
- res,
-}: CreateFastifyContextOptions): Promise<Context> {
- const request = req as FastifyRequestWithSession;
- // @fastify/cookie decorates the reply, and this package does not depend on
- // fastify, so the decoration is named here rather than suppressed.
- const reply = res as unknown as {
- setCookie(
- name: string,
- value: string,
- options: Record<string, unknown>
- ): void;
- };
-
- const setCookie = (
- key: string,
- value: string,
- options: { maxAge?: number; signed?: boolean } = {}
- ) => {
- reply.setCookie(key, value, {
- maxAge: options.maxAge,
- signed: options.signed,
- ...COOKIE_OPTIONS,
- });
- };
-
- if (process.env.NODE_ENV !== 'production') {
- await new Promise((resolve) =>
- setTimeout(
- () => resolve(1),
- Math.min(
- Math.random() * ARTIFICIAL_LATENCY_SPREAD_MS,
- ARTIFICIAL_LATENCY_MAX_MS
- )
- )
- );
- }
-
- const cookies = request.cookies;
-
- return {
- ...v1CtxScope(req),
- headers: toHeaders(req.headers),
- // The attribution ip, as core defines it (ipHook / getClientIpFromHeaders).
- // The limiter must not key on it - that is what `remoteAddress` is for.
- ip: request.clientIp ?? '',
- remoteAddress: req.socket?.remoteAddress,
- demoMode: !!process.env.DEMO_USER_ID,
- cookies: { get: (name: string) => cookies?.[name] },
- setCookie,
- // Already resolved by app.ts's onRequest hook. Under V2 the fetch
- // adapter's context builder resolves it instead; either way a procedure
- // reads a value, exactly as V1's routers always have.
- session: request.session,
- };
-}
-
-/**
- * The `Ctx` half of the context under V1.
- *
- * `db`/`ch`/`redis`/`clients` are core's `unknown` stubs until P3-P4 wire the
- * real clients, and V1's routers reach for their own singletons regardless —
- * including the buffers, which V1 reaches through `@openpanel/db`'s delegate
- * (M8-001) rather than through this context. `queues` and `services` throw rather than returning an empty
- * object: a V1 router that reached for either through core would otherwise
- * silently do nothing (`queues`) or hit `undefined` (`services`) instead of
- * the loud error that tells it to reach `@openpanel/db`/`@openpanel/core`
- * directly, as the rest of V1 does. `services` is not built via core's
- * `createServices` here on purpose — that factory is deliberately absent from
- * the curated barrel (index.test.ts), so nothing outside `apps/api`'s
- * `main.ts` constructs a `Services` container.
- */
-function v1CtxScope(req: CreateFastifyContextOptions['req']): Ctx {
- return {
- db: undefined,
- ch: undefined,
- redis: undefined,
- clients: undefined,
- buffers: undefined as unknown as Ctx['buffers'],
- logger: req.log,
- queues: NOT_WIRED_QUEUES,
- services: NOT_WIRED_SERVICES,
- requestId: String(req.id),
- };
-}
-
-const NOT_WIRED_QUEUES = new Proxy({} as QueueProducers, {
- get(_target, name) {
- throw new Error(
- `ctx.queues.${String(name)} is not wired on the V1 Fastify path — enqueue through @openpanel/queue, as the rest of V1 does`
- );
- },
-});
-
-const NOT_WIRED_SERVICES = new Proxy({} as Ctx['services'], {
- get(_target, name) {
- throw new Error(
- `ctx.services.${String(name)} is not wired on the V1 Fastify path — reach @openpanel/core's or @openpanel/db's module directly, as the rest of V1 does`
- );
- },
-});
-
-/** Node's header bag is a record of strings and string arrays; core wants a `Headers`. */
-function toHeaders(source: Record<string, string | string[] | undefined>) {
- const headers = new Headers();
- for (const [name, value] of Object.entries(source)) {
- if (Array.isArray(value)) {
- for (const entry of value) {
- headers.append(name, entry);
- }
- } else if (value !== undefined) {
- headers.set(name, value);
- }
- }
- return headers;
-}
-
const enforceUserIsAuthed = middleware(async ({ ctx, next }) => {
if (!ctx.session?.userId) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not authenticated' });
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d1ab33cbe..9e2d606f7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -83,66 +83,15 @@ importers:
apps/api:
dependencies:
- '@aws-sdk/client-s3':
- specifier: ^3.974.0
- version: 3.984.0
- '@aws-sdk/client-sts':
- specifier: ^3.974.0
- version: 3.1117.0
- '@better-agent/adapters':
- specifier: ^0.1.0-beta.3
- version: 0.1.0-beta.3(@better-agent/[email protected])
- '@better-agent/core':
- specifier: ^0.1.0-beta.3
- version: 0.1.0-beta.3
- '@fastify/compress':
- specifier: ^8.1.0
- version: 8.1.0
- '@fastify/cookie':
- specifier: ^11.0.2
- version: 11.0.2
- '@fastify/cors':
- specifier: ^11.1.0
- version: 11.1.0
- '@fastify/rate-limit':
- specifier: ^10.3.0
- version: 10.3.0
- '@fastify/swagger':
- specifier: ^9.7.0
- version: 9.7.0([email protected])
- '@fastify/swagger-ui':
- specifier: ^5.2.5
- version: 5.2.5
- '@fastify/websocket':
- specifier: ^11.2.0
- version: 11.2.0
- '@google-cloud/storage':
- specifier: ^7.18.0
- version: 7.22.0([email protected])
- '@hyperdx/node-opentelemetry':
- specifier: 'catalog:'
- version: 0.10.3([email protected])
- '@node-rs/argon2':
- specifier: ^2.0.2
- version: 2.0.2
'@openpanel/common':
specifier: workspace:*
version: link:../../packages/common
- '@openpanel/constants':
- specifier: workspace:*
- version: link:../../packages/constants
'@openpanel/core':
specifier: workspace:*
version: link:../../packages/core
'@openpanel/db':
specifier: workspace:*
version: link:../../packages/db
- '@openpanel/json':
- specifier: workspace:*
- version: link:../../packages/json
- '@openpanel/payments':
- specifier: workspace:*
- version: link:../../packages/payments
'@openpanel/queue':
specifier: workspace:*
version: link:../../packages/queue
@@ -152,45 +101,15 @@ importers:
'@openpanel/trpc':
specifier: workspace:*
version: link:../../packages/trpc
- '@openpanel/validation':
- specifier: workspace:*
- version: link:../../packages/validation
- '@trpc/server':
- specifier: ^11.17.0
- version: 11.17.0([email protected])
- fast-json-stable-hash:
- specifier: ^1.0.3
- version: 1.0.3
- fastify:
- specifier: ^5.8.5
- version: 5.8.5
- fastify-metrics:
- specifier: ^12.1.0
- version: 12.1.0([email protected])
- fastify-raw-body:
- specifier: ^5.0.0
- version: 5.0.0
- fastify-zod-openapi:
- specifier: ^5.6.1
+ elysia:
+ specifier: 1.4.30
pino:
specifier: 'catalog:'
version: 10.3.1
pino-pretty:
specifier: 'catalog:'
version: 13.1.3
- prom-client:
- specifier: ^15.1.3
- version: 15.1.3
- ramda:
- specifier: ^0.29.1
- version: 0.29.1
- sharp:
- specifier: ^0.33.5
- version: 0.33.5
- source-map-support:
- specifier: ^0.5.21
- version: 0.5.21
uuid:
specifier: ^9.0.1
version: 9.0.1
@@ -204,21 +123,9 @@ importers:
'@openpanel/tsconfig':
specifier: workspace:*
version: link:../../tooling/typescript
- '@types/ramda':
- specifier: ^0.30.2
- version: 0.30.2
- '@types/source-map-support':
- specifier: ^0.5.10
- version: 0.5.10
'@types/uuid':
specifier: ^10.0.0
version: 10.0.0
- '@types/ws':
- specifier: ^8.5.14
- version: 8.5.14
- tsdown:
- specifier: 0.14.2
typescript:
specifier: 'catalog:'
version: 5.9.3
@@ -3013,11 +2920,6 @@ packages:
resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}
engines: {node: '>=6.9.0'}
- '@better-agent/[email protected]':
- resolution: {integrity: sha512-SSxiATXDA2ubfBkX5XDIJ33XbNiXOZ5boHVZM1AJyVVMcm0yhGZX177GesHywgHRslY4fMvPFfHPk28VlTyq/w==}
- peerDependencies:
- '@better-agent/core': 0.1.0-beta.3
-
'@better-agent/[email protected]':
resolution: {integrity: sha512-+fqFcmxHQRBE5D69Cq8EZJpU0xjNi4UfQSSSgxwz2CWmdaGAep6Xhh5CRFaJBvqXv6+WHdM3d8g2sXQKCyZqHw==}
engines: {bun: '>=1.3.3', node: '>=20'}
@@ -4447,57 +4349,9 @@ packages:
resolution: {integrity: sha512-OEl393iCOoo/z8bMezRlJu+GlRGlsKbUAN7jKB6LhnKoqKve5DXRpalbItIIcwnCjs1k/FOPjFzcA6Qn+H+YbA==}
engines: {node: '>=18.0.0', npm: '>=9.0.0'}
- '@fastify/[email protected]':
- resolution: {integrity: sha512-/c/TW2bO/v9JeEgoD/g1G5GxGeCF1Hafdf79WPmUlgYiBXummY0oX3VVq4yFkKKVBKDNlaDUYoab7g38RpPqCQ==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-wX3I5u/SYQXxbqjG7CysvzeaCe4Sv8y13MnvnaGTpqfKkJbTLpwvdIDgqrwp/+UGvXOW7OLDLoTAQCDMJJRjDQ==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-GWdwdGlgJxyvNv+QcKiGNevSspMQXncjMZ1J8IvuDQk0jvkzgWWZFNC2En3s+nHndZBGV8IbLwOI/sxCZw/mzA==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-sUw8ed8wP2SouWZTIbA7V2OQtMNpLj2W6qJOYhNdcmINTu6gsxVYXjQiM9mdi8UUDlcoDDJ/W2syPo1WB2QjYA==}
-
'@fastify/[email protected]':
resolution: {integrity: sha512-N5Oqvltoa2r9z1tbx4xjky0oRR60v+T47Ic4J1ukoVQcptLOrIdRnCSdTGmOmajZuHVKlTnfcmrjyqsGEW1ztA==}
- '@fastify/[email protected]':
- resolution: {integrity: sha512-OO/SA8As24JtT1usTUTKgGH7uLvhfwZPwlptRi2Dp5P4KKmJI3gvsZ8MIHnNwDs4sLf/aai5LzTyl66xr7qMxA==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-YdR7gqlLg1xZAQa+SX4sMNzQHY5pC54fu9oC5aYSUqBhyn6fkLkrdtKlpVdCNPlwuUuXA1PjFTEmvMF6ZVXVGw==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-kJExsp4JCms7ipzg7SJ3y8DwmePaELHxKYtg+tZow+k0znUTf3cb+npgyqm8+ATZOdmfgfydIebPDWM172wfyA==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-OA3KGBCy6KtIvLf8DINC5880o5iBlDX4SxzLQS8HorJAbqluzLRn80UXU0bxZn7UOFhFgpRJDasfwn9nG4FG4A==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-37qVVA1qZ5sgH7KpHkkC4z9SK6StIsIcOmpjvMPXNb3vx2GQxhZocogVYbr2PbbeLCQxYIPDok307xEvRZOzGA==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-eIGkG9XKQs0nyynatApA3EVrojHOuq4l6fhB4eeCk4PIOeadvOJz9/4w3vGI44Go17uaXOWEcPkaD8kuKm7g6Q==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-TMYeQLCBSy2TOFmV95hQWkiTYgC/SEx7vMdV+wnZVX4tt8VBLKzmH8vV9OzJehV0+XBfg+WxPMt5wp+JBUKsVw==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-EPRNQYqEYEYTK8yyGbcM0iHpyJaupb94bey5O6iCQfLTADr02kaZU+qeHSdd9H9TiMwTBVkrMa59V8CMbn3avQ==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-ky3I0LAkXKX/prwSDpoQ3kscBKsj2Ha6Gp1/JfgQSqyx0bm9F2bE//XmGVGj2cR9l5hUjZYn60/hqn7e+OLgWQ==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-Vp1SC1GC2Hrkd3faFILv86BzUNyFz5N4/xdExqtCgkGASOzn/x+eMe4qXIGq7cdT6wif/P/oa6r1Ruqx19paZA==}
-
- '@fastify/[email protected]':
- resolution: {integrity: sha512-3HrDPbAG1CzUCqnslgJxppvzaAZffieOVbLp1DAy1huCSynUWPifSvfdEDUR8HlJLp3sp1A36uOM2tJogADS8w==}
-
'@floating-ui/[email protected]':
resolution: {integrity: sha512-PcF++MykgmTj3CIyOQbKA/hDzOAiqI3mhuoN44WRCopIs1sgoDoU4oty4Jtqaj/y3oDU6fnVSm4QG0a3t5i0+g==}
@@ -4998,10 +4852,6 @@ packages:
resolution: {integrity: sha512-wNIFWdSUfX9Jc6ePMzxSPVgTVB4EOfDIwLQLWASyiUdHKaMsiilj9bYiGkGQCKVodd0x6bgQCV207PILGFCF9Q==}
- '@lukeed/[email protected]':
- resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==}
- engines: {node: '>=8'}
-
'@mapbox/[email protected]':
resolution: {integrity: sha512-llMXd39jtP0HpQLVI37Bf1m2ADlEb35GYSh1SDSLsBhR+5iCxiNGlT31yqbNtVHygHAtMy6dWFERpU2JgufhPg==}
engines: {node: '>=18'}
@@ -6822,9 +6672,6 @@ packages:
'@protobufjs/[email protected]':
resolution: {integrity: sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==}
- '@quansync/[email protected]':
- resolution: {integrity: sha512-lNS9hL2aS2NZgNW7BBj+6EBl4rOf8l+tQ0eRY6JWCI8jI2kc53gSoqbjojU0OnAWhzoXiOjFyGsHcDGePB3lhA==}
-
'@radix-ui/[email protected]':
resolution: {integrity: sha512-V3gRzhVNU1ldS5XhAPTom1fOIo4ccrjjJgmE+LI2h/WaFpHmx0MQApT+KZHnx8abG6Avtfcz4WoEciMnpFT3HQ==}
@@ -9691,9 +9538,6 @@ packages:
resolution: {integrity: sha512-0BzWVKtSEtignlk+XBuK88Il5wzQwbRVfEkzE8iKm02NYHMGQ/9ffB05M+zXhTCqo50DOIAT9pNSJsjFMMG4rQ==}
- '@types/[email protected]':
- resolution: {integrity: sha512-PyzHvjCalm2BRYjAU6nIB3TprYwMNOUY/7P/N8bSzp9W/yM2YrtGtAnnVtaCNSeOZ8DzKyFDvaqQs7LnWwwmBA==}
-
resolution: {integrity: sha512-1lWWZ/2YiNttGcIUxQwnvMuh55GIEbn/zlpzzEojAsbxquI/TXQZCRaXsfxG1CHjlqGoqxWePkvaM/5qYHNuvQ==}
@@ -9750,9 +9594,6 @@ packages:
resolution: {integrity: sha512-5JcVt1u5HDmlXkwOD2nslZVllBBc7HDuOICfiZah2Z0is8M8g+ddAEawbmd3VjedfDHBzxCaXLs07QEmb7y54g==}
- '@types/[email protected]':
- resolution: {integrity: sha512-tgVP2H469x9zq34Z0m/fgPewGhg/MLClalNOiPIzQlXrSS2YrKu/xCdSCKnEDwkFha51VKEKB6A9wW26/ZNwzA==}
-
resolution: {integrity: sha512-lVRe4Iz9UNgiHelKVo8QlC8fb5nfY8+p+jNQNE+UVsuuVlQnWhyWmQ/wF5pE8Ys6TdjfVpqTG9O9i2vi6E0+Sg==}
@@ -9816,9 +9657,6 @@ packages:
resolution: {integrity: sha512-JQbbmxZTZehdc2iszGKs5oC3NFnjeay7mtAWrdt7qNtAVK0g19muApzAy4bm9byz79xa2ZnO/BOBC2R8RC5Lww==}
- '@types/[email protected]':
- resolution: {integrity: sha512-bd/YFLW+URhBzMXurx7lWByOu+xzU9+kb3RboOteXYDfW+tr+JZa99OyNmPINEGB/ahzKrEuc8rcv4gnpJmxTw==}
-
resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==}
@@ -10093,9 +9931,6 @@ packages:
resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}
engines: {node: '>=6.5'}
- resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==}
-
resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==}
engines: {node: '>= 0.6'}
@@ -10363,9 +10198,6 @@ packages:
resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-fYASnYi600CsH/j9EQov7lECAniYiBFiiAtBNuZYLA2leLe9qOvZzqYHFjtIj6gD2VMoMLP14834LFWvr4IfDw==}
-
resolution: {integrity: sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g==}
@@ -10486,9 +10318,6 @@ packages:
resolution: {integrity: sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==}
- resolution: {integrity: sha512-VSWO/W6nNQdyP520F1mhf+Lc2f8pjGQOtoHHm7Ze8Go1kX7akpVIrtTa0fn+HB0QJEDVacl6aO08YE0PgXfdnQ==}
-
resolution: {integrity: sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==}
@@ -11100,10 +10929,6 @@ packages:
resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
engines: {node: '>= 0.6'}
- resolution: {integrity: sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
@@ -11773,15 +11598,6 @@ packages:
resolution: {integrity: sha512-2QF/g9/zTaPDc3BjNcVTGoBbXBgYfMTTceLaYcFJ/W9kggFUkhxD/hMEeuLKbugyef9SqAx8cpgwlIP/jinUTA==}
engines: {node: '>=4'}
- resolution: {integrity: sha512-xeXHBQkn2ISSXxbJWD828PFjtyg+/UrMDo7W4Ffcs7+YWCquxU8YjV1KoxuiL+eJ5pg3ll+bC6flVv61L3LKZg==}
- engines: {node: '>=20.18.0'}
- peerDependencies:
- oxc-resolver: '>=11.0.0'
- peerDependenciesMeta:
- oxc-resolver:
- optional: true
-
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
@@ -11792,9 +11608,6 @@ packages:
resolution: {integrity: sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==}
- resolution: {integrity: sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==}
-
resolution: {integrity: sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==}
@@ -12258,15 +12071,9 @@ packages:
resolution: {integrity: sha512-iLK3Tq2J/KbiUn/5OHyhxikHqzwFXSM2e803Dp2JtBdQjsCVuZwWvL+WqWXPPRUEuDX4c0kqID1SU84RCfxs3A==}
- resolution: {integrity: sha512-s7SJE83QKBZwg54dIbD5rCtzOBVD43V1ReWXXYqBgwCwHLYAAT0RQc/FmrQglXqWPpz6omtryJQOau5jI4Nrvg==}
-
resolution: {integrity: sha512-aZU3i3eRcSb2NCq8i6N6IlyiTyF6vqAqzBGl2NBF6ngNx/GIqfYbkLDIKZ4z4P0o/RmtsFnVqHwdrSm13o4tnQ==}
- resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==}
-
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
@@ -12279,9 +12086,6 @@ packages:
resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==}
- resolution: {integrity: sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==}
-
resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==}
@@ -12303,35 +12107,6 @@ packages:
resolution: {integrity: sha512-go2J2xODMc32hT+4Xr/bBGXMaIoiCwrwp2mMtAvKyvEFW6S/v5Gn2pBmE4nvbwNjGhpcAiOwEv7R6/GZ6XRa9w==}
hasBin: true
- resolution: {integrity: sha512-EpbT+W1jm8kMbkCPvfW4j23y3BZlXGOcO6+75EFTKDxbJIyXbldrFIoVoP0oD4CsqrKeIARvrOjbZNqK5MdRwQ==}
- peerDependencies:
- fastify: '>=5'
-
- resolution: {integrity: sha512-HCxs+YnRaWzCl+cWRYFnHmeRFyR5GVnJTAaCJQiYzQSDwK9MgJdyAsuL3nh0EWRCYMgQ5MeziymvmAhUHYHDUQ==}
-
- resolution: {integrity: sha512-2qfoaQ3BQDhZ1gtbkKZd6n0kKxJISJGM6u/skD9ljdWItAscjXrtZ1lnjr7PavmXX9j4EyCPmBDiIsLn07d5vA==}
- engines: {node: '>= 10'}
-
- resolution: {integrity: sha512-K0tzRYEViPuCV3aKu5Zcgqsew8k0OGzEqu0p1+7P+EvNGXGP7MvcyWNVoq31LUadaT0HiUtD+65tM4sKEQz0Qg==}
- engines: {node: '>=20'}
- peerDependencies:
- '@fastify/swagger': ^9.0.0
- '@fastify/swagger-ui': ^5.0.1
- fastify: '5'
- zod: ^3.25.74 || ^4.0.0
- peerDependenciesMeta:
- '@fastify/swagger':
- optional: true
- '@fastify/swagger-ui':
- optional: true
-
- resolution: {integrity: sha512-Yqptv59pQzPgQUSIm87hMqHJmdkb1+GPxdE6vW6FRyVE9G86mt7rOghitiU4JHRaTyDUk9pfeKmDeu70lAwM4Q==}
-
resolution: {integrity: sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==}
@@ -12410,10 +12185,6 @@ packages:
resolution: {integrity: sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-d3uCir8Hmg7W1Ywp8nKf2lJJYU9Nwinvo+1D39Dn09nz65UKXIxUh7j7K8zeWhxqe1WrkS7FJyON/Q/3lPoc6w==}
- engines: {node: '>=14'}
-
resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==}
engines: {node: '>=6'}
@@ -13791,13 +13562,6 @@ packages:
resolution: {integrity: sha512-YBOEogm5w9Op337yb6pAT6ZXDqlxAsQCanM3grid8lMWNxRJO/zWEJi3ZzqDL8boWfwhTFym5EFrNgWwpqcBRg==}
engines: {node: '>=6.0.0'}
- resolution: {integrity: sha512-HG0SIB9X4J8bwbxCbnd5FfPEbcXAJYTi1pBJeP/QPON+w8ovSME8iRG+ElHNxZNX2Qh6eYn1GdzJFS4cDFfx0Q==}
-
- resolution: {integrity: sha512-HqMnbz0tz2DaEJ3ntsqtx3ezzZyDE7G56A/pPY/NGmrPu76UzsWquOpHFRAf5beTNXoH2LU5cQePVvRli1nchA==}
- engines: {node: '>=20'}
-
resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==}
engines: {node: '>=16'}
@@ -13885,9 +13649,6 @@ packages:
resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==}
-
resolution: {integrity: sha512-gPWxznF6TKmUHrOQjlVo2UbaL2EJ71mb2CCeRs/2qBpi4L/g4LUVc9+3lKQ6DTUZwJswfM7ainGrLO1+fOqa2g==}
@@ -15567,9 +15328,6 @@ packages:
resolution: {integrity: sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==}
- resolution: {integrity: sha512-FhJ+YbOSBb9/rIl2ZeE/QHEsWn7PqNYt8ARAY3kIgNGOk13g9FGyIY6JIl/xB/3TFRVoTv5as0l11weORrTekA==}
-
resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==}
@@ -15957,9 +15715,6 @@ packages:
resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==}
- resolution: {integrity: sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==}
-
resolution: {integrity: sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==}
@@ -16030,15 +15785,9 @@ packages:
resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==}
- resolution: {integrity: sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==}
-
resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}
- resolution: {integrity: sha512-m7KOje7jZxrmutanlkS1daj1dS6z6BgslzOXmcSEpIlCxM3VJH7lG5QLeck/6hgF6F4crFf01UtQmNsJfweTAw==}
-
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
@@ -16106,10 +15855,6 @@ packages:
resolution: {integrity: sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==}
engines: {node: '>= 0.8'}
- resolution: {integrity: sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==}
- engines: {node: '>= 0.8'}
-
resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}
engines: {node: '>= 0.10'}
@@ -16703,10 +16448,6 @@ packages:
resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-hv9woG7Fy0M9IlRQloq/N6atV82NxLGveq+3H2WOi79dtIYWN8OaxogDm77f8YnVXJL2VD3bbqowu5E3EMhBYA==}
@@ -16731,9 +16472,6 @@ packages:
resolution: {integrity: sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==}
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
- resolution: {integrity: sha512-r5a3l5HzYlIC68TpmYKlxWjmOP6wiPJ1vWv2HeLhNsRZMrCkxeqxiHlQ21oXmQ4F3SiryXBHhAD7JZqvOJjFmg==}
-
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
@@ -16750,22 +16488,6 @@ packages:
resolution: {integrity: sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==}
- resolution: {integrity: sha512-S2pPcC8h0C8a0ZLDdUTqqtTR9jlryThF3SmH8eZw97FQwgY+hd0x07Zm5algBkmj25S4nvvOusliR1YpImK3LA==}
- engines: {node: '>=20.18.0'}
- peerDependencies:
- '@typescript/native-preview': '>=7.0.0-dev.20250601.1'
- rolldown: 1.0.0-beta.43
- typescript: ^5.0.0
- vue-tsc: ~3.0.3
- peerDependenciesMeta:
- '@typescript/native-preview':
- optional: true
- typescript:
- optional: true
- vue-tsc:
- optional: true
-
resolution: {integrity: sha512-6RcqyRx0tY1MlRLnjXPp/849Rl/CPFhzpGGwNPEPjKwqBMqPq/Rbbkxasa8s0x+IkUk46ty4jazb5skZ/Vgdhw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -16862,9 +16584,6 @@ packages:
resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-goqsB+bSlOmVX+CiFX2PFc1OV88j5jvBqIM+DgqrucHnUguAUNtiNOs+aTadq2NqsLQ+TQ3UEVG3gtSFcdlkCg==}
-
resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==}
engines: {node: '>=10'}
@@ -16898,9 +16617,6 @@ packages:
resolution: {integrity: sha512-6FtHJEvt+pVMIB9IBY+IcCJ6Z5f1iQnytgyfKMhDKgmzYG+TeH/wx1y3l27rshSbLiSanrR9ffZDrEsmjlQF2g==}
- resolution: {integrity: sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==}
-
resolution: {integrity: sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==}
@@ -17618,9 +17334,6 @@ packages:
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
- resolution: {integrity: sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==}
-
resolution: {integrity: sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==}
engines: {node: '>=18'}
@@ -17679,10 +17392,6 @@ packages:
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
engines: {node: '>=8.0'}
- resolution: {integrity: sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==}
- engines: {node: '>=12'}
-
resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}
engines: {node: '>=0.6'}
@@ -17765,28 +17474,6 @@ packages:
typescript:
optional: true
- resolution: {integrity: sha512-6ThtxVZoTlR5YJov5rYvH8N1+/S/rD/pGfehdCLGznGgbxz+73EASV1tsIIZkLw2n+SXcERqHhcB/OkyxdKv3A==}
- engines: {node: '>=20.19.0'}
- hasBin: true
- peerDependencies:
- '@arethetypeswrong/core': ^0.18.1
- publint: ^0.3.0
- typescript: ^5.0.0
- unplugin-lightningcss: ^0.4.0
- unplugin-unused: ^0.5.0
- peerDependenciesMeta:
- '@arethetypeswrong/core':
- optional: true
- publint:
- optional: true
- typescript:
- optional: true
- unplugin-lightningcss:
- optional: true
- unplugin-unused:
- optional: true
-
resolution: {integrity: sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==}
@@ -17896,9 +17583,6 @@ packages:
resolution: {integrity: sha512-8KBxZGJwUF3MpRkkJauSpvfHXk8Ssq15QXGuCBTDGeKd9PfheokkC3wAKRV3djej9O31Qa5M7Owsg8hF0GjtAw==}
- resolution: {integrity: sha512-1HTsf5/QVRmLzcGfldPFvkVsAdi1db1BBKzi7iW3KBUlOICg/nKnFS+jGqDJS3YD8VsWbAh7JiHeBvbsw8RPxA==}
-
resolution: {integrity: sha512-vaoC35CRC3xvL8Z6HkshDbi6KWM1ezK0LHN0YyxXWUn9HKzBNg/T3xSGlJZjCYspnOD3jE7bcizsp0bUXZDxnQ==}
@@ -17953,9 +17637,6 @@ packages:
typescript:
optional: true
- resolution: {integrity: sha512-QCkQoOnJF8L107gxfHL0uavn7WD9b3dpBcFX6HtfQYmjw2YzWxGuFQ0N0J6tE9oguCBJn9KOvfqYDCMPHIZrBA==}
-
resolution: {integrity: sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==}
@@ -19003,18 +18684,6 @@ packages:
utf-8-validate:
optional: true
- resolution: {integrity: sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==}
- 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
-
resolution: {integrity: sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==}
engines: {node: '>=10.0.0'}
@@ -19159,12 +18828,6 @@ packages:
resolution: {integrity: sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA==}
engines: {node: '>= 14'}
- resolution: {integrity: sha512-P2jsOOBAq/6hCwUsMCjUATZ8szkMsV5VAwZENfyxp2Hc/XPJQpVwAgevWZc65xZauCwWB9LAn7zYeiCJFAEL+A==}
- engines: {node: '>=20'}
- peerDependencies:
- zod: ^3.25.74 || ^4.0.0
-
resolution: {integrity: sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==}
peerDependencies:
@@ -22263,10 +21926,6 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
- '@better-agent/[email protected](@better-agent/[email protected])':
- dependencies:
- '@better-agent/core': 0.1.0-beta.3
-
dependencies:
'@better-agent/core': 0.1.0-beta.3
@@ -23436,104 +23095,8 @@ snapshots:
'@faker-js/[email protected]': {}
- '@fastify/[email protected]': {}
-
- '@fastify/[email protected]':
- dependencies:
- ajv: 8.18.0
- ajv-formats: 3.0.1([email protected])
- fast-uri: 3.1.0
-
- '@fastify/[email protected]':
- dependencies:
- '@fastify/accept-negotiator': 2.0.1
- fastify-plugin: 5.0.1
- mime-db: 1.54.0
- minipass: 7.1.2
- peek-stream: 1.1.3
- pump: 3.0.0
- pumpify: 2.0.1
- readable-stream: 4.5.2
-
- '@fastify/[email protected]':
- dependencies:
- cookie: 1.0.2
- fastify-plugin: 5.0.1
-
- '@fastify/[email protected]':
- dependencies:
- fastify-plugin: 5.0.1
- toad-cache: 3.7.0
-
'@fastify/[email protected]': {}
- '@fastify/[email protected]': {}
-
- '@fastify/[email protected]':
- dependencies:
- fast-json-stringify: 6.0.1
-
- '@fastify/[email protected]': {}
-
- '@fastify/[email protected]':
- dependencies:
- dequal: 2.0.3
-
- '@fastify/[email protected]':
- dependencies:
- '@fastify/forwarded': 3.0.0
- ipaddr.js: 2.5.0
-
- '@fastify/[email protected]':
- dependencies:
- '@lukeed/ms': 2.0.2
- fastify-plugin: 5.0.1
- toad-cache: 3.7.0
-
- '@fastify/[email protected]':
- dependencies:
- '@lukeed/ms': 2.0.2
- escape-html: 1.0.3
- fast-decode-uri-component: 1.0.1
- http-errors: 2.0.1
- mime: 3.0.0
-
- '@fastify/[email protected]':
- dependencies:
- '@fastify/accept-negotiator': 2.0.1
- '@fastify/send': 4.1.0
- content-disposition: 1.0.1
- fastify-plugin: 5.0.1
- fastq: 1.17.1
- glob: 13.0.3
-
- '@fastify/[email protected]':
- dependencies:
- '@fastify/static': 9.1.0
- fastify-plugin: 5.0.1
- openapi-types: 12.1.3
- rfdc: 1.4.1
- yaml: 2.8.2
-
- dependencies:
- fastify-plugin: 5.0.1
- json-schema-resolver: 3.0.0([email protected])
- openapi-types: 12.1.3
- rfdc: 1.4.1
- yaml: 2.8.2
- transitivePeerDependencies:
- - supports-color
-
- '@fastify/[email protected]':
- dependencies:
- duplexify: 4.1.3
- fastify-plugin: 5.0.1
- ws: 8.18.3
- transitivePeerDependencies:
- - bufferutil
- - utf-8-validate
-
'@floating-ui/[email protected]':
dependencies:
'@floating-ui/utils': 0.2.1
@@ -24028,8 +23591,6 @@ snapshots:
dependencies:
'@lezer/common': 1.5.0
- '@lukeed/[email protected]': {}
-
dependencies:
consola: 3.4.2
@@ -25785,7 +25346,8 @@ snapshots:
'@oxc-project/[email protected]': {}
- '@oxc-project/[email protected]': {}
+ '@oxc-project/[email protected]':
+ optional: true
'@oxc-resolver/[email protected]':
optional: true
@@ -26086,10 +25648,6 @@ snapshots:
'@protobufjs/[email protected]': {}
- '@quansync/[email protected]':
- dependencies:
- quansync: 0.2.11
-
'@radix-ui/[email protected]': {}
'@radix-ui/[email protected]': {}
@@ -27549,7 +27107,8 @@ snapshots:
'@rolldown/[email protected]': {}
- '@rolldown/[email protected]': {}
+ '@rolldown/[email protected]':
+ optional: true
'@rolldown/[email protected]': {}
@@ -29570,10 +29129,6 @@ snapshots:
dependencies:
types-ramda: 0.29.7
- '@types/[email protected]':
- dependencies:
- types-ramda: 0.30.1
-
dependencies:
types-ramda: 0.31.0
@@ -29645,10 +29200,6 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]':
- dependencies:
- source-map: 0.6.1
-
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -29720,10 +29271,6 @@ snapshots:
dependencies:
'@types/node': 24.10.1
- '@types/[email protected]':
- dependencies:
- '@types/node': 20.19.24
-
'@types/[email protected]': {}
@@ -30159,8 +29706,6 @@ snapshots:
dependencies:
event-target-shim: 5.0.1
-
dependencies:
mime-types: 2.1.35
@@ -30503,11 +30048,6 @@ snapshots:
dependencies:
possible-typed-array-names: 1.1.0
- dependencies:
- '@fastify/error': 4.0.0
- fastq: 1.17.1
-
@@ -30689,8 +30229,6 @@ snapshots:
-
@@ -31402,8 +30940,6 @@ snapshots:
-
@@ -32092,10 +31628,6 @@ snapshots:
- optionalDependencies:
- oxc-resolver: 11.19.1(@emnapi/[email protected])(@emnapi/[email protected])
-
dependencies:
call-bind-apply-helpers: 1.0.2
@@ -32108,13 +31640,6 @@ snapshots:
- dependencies:
- end-of-stream: 1.4.4
- inherits: 2.0.4
- readable-stream: 2.3.8
- stream-shift: 1.0.3
-
dependencies:
end-of-stream: 1.4.4
@@ -32912,21 +32437,8 @@ snapshots:
- dependencies:
- '@fastify/merge-json-schemas': 0.2.1
- ajv: 8.18.0
- ajv-formats: 3.0.1([email protected])
- fast-uri: 3.0.6
- json-schema-ref-resolver: 2.0.1
- rfdc: 1.4.1
-
- dependencies:
- fast-decode-uri-component: 1.0.1
-
@@ -32937,8 +32449,6 @@ snapshots:
dependencies:
fast-string-truncated-width: 3.0.3
-
@@ -32963,50 +32473,6 @@ snapshots:
path-expression-matcher: 1.4.0
strnum: 2.2.3
- dependencies:
- fastify: 5.8.5
- fastify-plugin: 5.0.1
- prom-client: 15.1.3
-
-
- dependencies:
- fastify-plugin: 5.0.1
- raw-body: 3.0.0
- secure-json-parse: 2.7.0
-
- dependencies:
- '@fastify/error': 4.0.0
- fast-json-stringify: 6.0.1
- fastify: 5.8.5
- fastify-plugin: 5.0.1
- zod: 4.3.6
- zod-openapi: 5.4.6([email protected])
- optionalDependencies:
- '@fastify/swagger': 9.7.0([email protected])
- '@fastify/swagger-ui': 5.2.5
-
- dependencies:
- '@fastify/ajv-compiler': 4.0.5
- '@fastify/error': 4.0.0
- '@fastify/fast-json-stringify-compiler': 5.0.2
- '@fastify/proxy-addr': 5.0.0
- abstract-logging: 2.0.1
- avvio: 9.1.0
- fast-json-stringify: 6.0.1
- find-my-way: 9.2.0
- light-my-request: 6.6.0
- pino: 10.3.1
- process-warning: 5.0.0
- rfdc: 1.3.1
- secure-json-parse: 4.1.0
- semver: 7.7.2
- toad-cache: 3.7.0
-
dependencies:
reusify: 1.0.4
@@ -33132,12 +32598,6 @@ snapshots:
make-dir: 2.1.0
pkg-dir: 3.0.0
- dependencies:
- fast-deep-equal: 3.1.3
- fast-querystring: 1.1.2
- safe-regex2: 4.0.1
-
dependencies:
locate-path: 3.0.0
@@ -34762,18 +34222,6 @@ snapshots:
traverse: 0.6.11
valid-url: 1.0.9
- dependencies:
- dequal: 2.0.3
-
- dependencies:
- debug: 4.4.3([email protected])
- fast-uri: 3.0.6
- rfdc: 1.4.1
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@babel/runtime': 7.29.2
@@ -34865,12 +34313,6 @@ snapshots:
- dependencies:
- cookie: 1.1.1
- process-warning: 4.0.1
- set-cookie-parser: 2.6.0
-
dependencies:
debug: 2.6.9([email protected])
@@ -37250,12 +36692,6 @@ snapshots:
- dependencies:
- buffer-from: 1.1.2
- duplexify: 3.7.1
- through2: 2.0.5
-
@@ -37621,8 +37057,6 @@ snapshots:
-
@@ -37705,22 +37139,11 @@ snapshots:
- dependencies:
- end-of-stream: 1.4.4
- once: 1.4.0
-
dependencies:
end-of-stream: 1.4.5
once: 1.4.0
- dependencies:
- duplexify: 4.1.3
- inherits: 2.0.4
- pump: 3.0.0
-
@@ -37781,13 +37204,6 @@ snapshots:
iconv-lite: 0.4.24
unpipe: 1.0.0
- dependencies:
- bytes: 3.1.2
- http-errors: 2.0.0
- iconv-lite: 0.6.3
- unpipe: 1.0.0
-
dependencies:
bytes: 3.1.2
@@ -38648,8 +38064,6 @@ snapshots:
onetime: 5.1.2
signal-exit: 3.0.7
-
dependencies:
'@types/nlcst': 2.0.3
@@ -38688,8 +38102,6 @@ snapshots:
-
@@ -38702,23 +38114,6 @@ snapshots:
- dependencies:
- '@babel/generator': 7.28.3
- '@babel/parser': 7.29.7
- '@babel/types': 7.29.7
- ast-kit: 2.1.2
- birpc: 2.5.0
- debug: 4.4.1([email protected])
- dts-resolver: 2.1.2([email protected](@emnapi/[email protected])(@emnapi/[email protected]))
- get-tsconfig: 4.10.1
- rolldown: 1.0.0-beta.43(@emnapi/[email protected])(@emnapi/[email protected])
- optionalDependencies:
- typescript: 5.9.3
- transitivePeerDependencies:
- - oxc-resolver
- - supports-color
-
dependencies:
'@oxc-project/types': 0.94.0
@@ -38742,6 +38137,7 @@ snapshots:
transitivePeerDependencies:
- '@emnapi/core'
- '@emnapi/runtime'
+ optional: true
dependencies:
@@ -38886,10 +38282,6 @@ snapshots:
es-errors: 1.3.0
is-regex: 1.2.1
- dependencies:
- ret: 0.5.0
-
@@ -38916,8 +38308,6 @@ snapshots:
-
@@ -39770,8 +39160,6 @@ snapshots:
-
@@ -39817,8 +39205,6 @@ snapshots:
dependencies:
is-number: 7.0.0
-
@@ -39877,32 +39263,6 @@ snapshots:
optionalDependencies:
typescript: 5.9.3
- dependencies:
- ansis: 4.2.0
- cac: 6.7.14
- chokidar: 4.0.3
- debug: 4.4.1([email protected])
- diff: 8.0.2
- empathic: 2.0.0
- hookable: 5.5.3
- rolldown: 1.0.0-beta.43(@emnapi/[email protected])(@emnapi/[email protected])
- semver: 7.7.2
- tinyexec: 1.0.1
- tinyglobby: 0.2.15
- tree-kill: 1.2.2
- unconfig: 7.3.3
- optionalDependencies:
- typescript: 5.9.3
- transitivePeerDependencies:
- - '@emnapi/core'
- - '@emnapi/runtime'
- - '@typescript/native-preview'
- - oxc-resolver
- - supports-color
- - vue-tsc
-
@@ -40030,10 +39390,6 @@ snapshots:
dependencies:
ts-toolbelt: 9.6.0
- dependencies:
- ts-toolbelt: 9.6.0
-
dependencies:
ts-toolbelt: 9.6.0
@@ -40108,13 +39464,6 @@ snapshots:
- vue-sfc-transformer
- vue-tsc
- dependencies:
- '@quansync/fs': 0.1.5
- defu: 6.1.4
- jiti: 2.6.1
- quansync: 0.2.11
-
@@ -41047,8 +40396,6 @@ snapshots:
-
@@ -41199,10 +40546,6 @@ snapshots:
compress-commons: 6.0.2
readable-stream: 4.5.2
- dependencies:
- zod: 4.3.6
-
dependencies:
zod: 4.3.6