OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(P2-007): http/: define, requestContext (derive-once proven), auth macro skeletons, hooks - on Elysia 1.4.30
ralph324634e5f0e3
diff --git a/packages/core/src/context.ts b/packages/core/src/context.tsindex c3328ca25..4d76cf8a6 100644--- a/packages/core/src/context.ts+++ b/packages/core/src/context.ts@@ -7,7 +7,7 @@import type { QueueProducerHandle, QueueProducers } from './jobs.registry';import type { Logger } from './logger';import { createServices, type Services } from './services';-import type { CookieOptions } from './shared/cookie';+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, buffers P8); they are named now so@@ -20,9 +20,8 @@ export type RedisClient = unknown;export type ServiceClients = unknown;export type Buffers = unknown;-// Elysia's cookie primitive, wrapped (P2-007), and the resolved session-// (P6 auth).-export type CookieJar = unknown;+// The resolved session (P6 auth). `CookieJar` is already real — it lives in+// shared/cookie.ts, wrapped over Elysia's primitive by http/context.ts.export type Session = unknown;/** The env-derived flags core needs. apps/api's config/env.ts is the solediff --git a/packages/core/src/http/auth.test.ts b/packages/core/src/http/auth.test.tsnew file mode 100644index 000000000..1bf3981e8--- /dev/null+++ b/packages/core/src/http/auth.test.ts@@ -0,0 +1,133 @@+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';++// 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+// lets the macro's two branches be exercised at all.+const CLIENT: AuthenticatedClient = {+ id: 'client-1',+ projectId: 'proj-1',+ type: 'root',+ secretPresented: true,+};++let client: AuthenticatedClient | null = CLIENT;+let session: unknown = { userId: 'user_1' };++const authenticateClient = mock(+ (_deps: unknown, _headers: Headers, _options: ClientAuthOptions) =>+ Promise.resolve(client)+);+const resolveSession = mock(() => Promise.resolve(session));++mock.module('./client-auth', () => ({ authenticateClient }));+mock.module('./session', () => ({+ SESSION_COOKIE_NAME: 'session',+ resolveSession,+}));++let authMacros: typeof import('./auth').authMacros;++beforeAll(async () => {+ ({ authMacros } = await import('./auth'));+});++beforeEach(() => {+ client = CLIENT;+ session = { userId: 'user_1' };+ authenticateClient.mockClear();+ resolveSession.mockClear();+});++function buildApp() {+ const { deps } = stubAppDeps();+ return (+ new Elysia()+ .use(authMacros(deps))+ // The principal is typed onto the handler by the macro: `client` here is+ // `AuthenticatedClient`, not `any`, and reading it off an unguarded+ // handler does not compile.+ .post(+ '/manage/projects',+ ({ client: principal }) => {+ const typed: AuthenticatedClient = principal;+ return { id: typed.id, secretPresented: typed.secretPresented };+ },+ { clientAuth: { allow: ['root'] } }+ )+ .get(+ '/dashboard',+ ({ session: principal }) => ({ ok: principal !== null }),+ {+ session: true,+ }+ )+ .get('/open', () => 'anonymous')+ );+}++test('clientAuth resolves the principal onto the handler', async () => {+ const response = await buildApp().handle(+ new Request('http://localhost/manage/projects', { method: 'POST' })+ );++ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({+ id: 'client-1',+ secretPresented: true,+ });+ expect(authenticateClient).toHaveBeenCalledTimes(1);+});++test('clientAuth passes the allow list through to the authenticator', async () => {+ await buildApp().handle(+ new Request('http://localhost/manage/projects', { method: 'POST' })+ );++ expect(authenticateClient.mock.calls[0]?.[2]).toEqual({ allow: ['root'] });+});++test('clientAuth answers 401 with V1s message when nothing authenticates', async () => {+ client = null;++ 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');+});++test('session resolves through the memoized HttpCtx lookup', async () => {+ const response = await buildApp().handle(+ new Request('http://localhost/dashboard')+ );++ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({ ok: true });+ expect(resolveSession).toHaveBeenCalledTimes(1);+});++test('session answers 401 when the cookie resolves to nothing', async () => {+ session = null;++ const response = await buildApp().handle(+ new Request('http://localhost/dashboard')+ );++ expect(response.status).toBe(401);+});++// ADR-002 problem 2: a route is unauthenticated because it did not ask for a+// tier, not because of which `.use()` it was nested under.+test('a route that requests no tier authenticates nobody', async () => {+ const response = await buildApp().handle(+ new Request('http://localhost/open')+ );++ expect(response.status).toBe(200);+ expect(authenticateClient).not.toHaveBeenCalled();+ expect(resolveSession).not.toHaveBeenCalled();+});diff --git a/packages/core/src/http/auth.ts b/packages/core/src/http/auth.tsnew file mode 100644index 000000000..ff1297d85--- /dev/null+++ b/packages/core/src/http/auth.ts@@ -0,0 +1,76 @@+// Caller authentication, declared once and requested per route (ADR-011 A-i).+//+// A macro authenticates the CALLER and stops. Everything below it is preserved+// verbatim by whichever wave ports the router, and is listed here because a+// missing authorization check is silent: a broken chart throws, a dropped+// access check returns 200 with somebody else's data.+//+// ADR-011 A-iii invariants, binding:+// 1. Macros authenticate the caller only. A route or procedure holding a+// reportId/dashboardId/cohortId/importId/referenceId/ruleId/insightId/+// integrationId/conversationId/clientId does its own check in the handler.+// Porting a router NEVER deletes an in-handler check.+// 2. `enforceAccess` triggers on the RAW pre-zod input, top-level keys only,+// so `{projectId: null}` still reaches the project lookup and fails closed.+// 3. `needsWrite = mutation && !meta.readOnlyMutation`; the opt-out stays on+// exactly `conversation.rename` and `overview.runFilterCommand`.+// 4. The organizationId check is membership only, never admin. The 12+// `org:admin` gates stay hand-written.+// 5. `getProjectAccess`: zero ProjectAccess rows in the org => write; one row+// anywhere in the org => every unlisted project is null; all exceptions+// swallowed => null (fail-closed).+// 6. `canWriteProject` = level in {write, admin}; admin stays a superset.+// 7. 5-minute Redis cache + 60s in-process LRU on both access lookups;+// removeMember/updateMemberAccess do not clear them. Sessions survive+// revocation (docs/ANSWERS.md §3: acceptable).+// 8. The nine cross-object binding checks in DISC-011 §4.4.+// 9. chartProcedure's share branch overwrites the caller's projectId with the+// report's — explicit in the builder, not an accident of spread order.+// 10. `/live/visitors/:projectId` stays unauthenticated; the other three /live+// routes keep session + access, and all four keep reject-after-upgrade.+// 11. Invites stay bearer tokens: no invite.email vs user.email comparison.+// 12. `resolveClientProjectId` is the single client->project resolution point.+// 13. Public-API routes never see a session cookie, however the scopes compose.+//+// Elysia 1.4.30 carries the option-bearing macro shape, so ADR-011's+// `requireClient(ctx, opts)` fallback is NOT taken: `clientAuth: { allow: [...] }`+// types the resolved client onto the handler, and a route that does not request+// the macro has no `client` binding at all — "did this route authenticate?" is+// a type question. Verified by http/auth.test.ts and by `tsc --noEmit`.++import { Elysia } from 'elysia';+import type { AppDeps } from '../context';+import { authenticateClient, type ClientAuthOptions } from './client-auth';+import { requestContext } from './context';++const INVALID_CLIENT_MESSAGE = 'Invalid client credentials';++/**+ * The named plugin every module reaches through `defineRoutes`. It brings+ * `requestContext(deps)` with it, so `ctx` and the tiers arrive together and a+ * route cannot request a tier without the context that resolves it.+ */+export function authMacros(deps: AppDeps) {+ return new Elysia({ name: 'core/auth-macros' })+ .use(requestContext(deps))+ .macro({+ session: {+ async resolve({ ctx, status }) {+ const session = await ctx.session();+ if (!session) {+ return status(401);+ }+ return { session };+ },+ },+ clientAuth: (options: ClientAuthOptions) => ({+ async resolve({ ctx, status }) {+ const client = await authenticateClient(deps, ctx.headers, options);+ if (!client) {+ return status(401, INVALID_CLIENT_MESSAGE);+ }+ return { client };+ },+ }),+ });+}diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.tsnew file mode 100644index 000000000..29c7e427d--- /dev/null+++ b/packages/core/src/http/client-auth.ts@@ -0,0 +1,48 @@+// Where API/SDK credentials become a client principal.+//+// V1 has five near-identical validators — `validateSdkRequest`,+// `validateExportRequest`, `validateImportRequest`, `validateManageRequest`+// and the MCP copy — that differ only by the accepted `ClientType` set and by+// the ingest extension. They collapse into this one function (ADR-011 A-i).+//+// P8 fills the body in, moving it onto `services.client.authenticate` and+// porting the ingest branch verbatim: the `ignoreCorsAndSecret` short-circuit,+// the unanchored wildcard origin regex, CORS-OR-secret ordering, the+// ip/profile_id project filters, the `__revenue` gate, the body-field+// credential fallback and the 5-minute verify cache. The signature and the+// macro over it are what P2 fixes.++import type { AppDeps } from '../context';++/** Prisma's `ClientType` enum, by value. Moves to client.constants.ts in P7. */+export type ClientType = 'read' | 'write' | 'root';++export interface AuthenticatedClient {+ id: string;+ projectId: string;+ type: ClientType;+ /**+ * Whether a client secret was PRESENTED, set before it is verified — V1 sets+ * `req.clientSecretAuth` at parse time (utils/auth.ts:62-64) and `isBotHook`+ * reads it afterwards as "this is a server-side SDK, never a bot". The+ * side-channel survives as a field on the principal (ADR-011 A-i).+ */+ secretPresented: boolean;+}++export interface ClientAuthOptions {+ /** Which client types may pass. Omitted means any, as `validateSdkRequest`. */+ allow?: ClientType[];+ /** The ingest extension described above. */+ ingest?: boolean;+ /** MCP presents `base64(clientId:clientSecret)` instead of the two headers. */+ token?: 'basic';+}++export function authenticateClient(+ _deps: AppDeps,+ _headers: Headers,+ _options: ClientAuthOptions+): Promise<AuthenticatedClient | null> {+ return Promise.resolve(null);+}diff --git a/packages/core/src/http/context.test.ts b/packages/core/src/http/context.test.tsnew file mode 100644index 000000000..34b5aec40--- /dev/null+++ b/packages/core/src/http/context.test.ts@@ -0,0 +1,262 @@+import { beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';+import { Elysia } from 'elysia';+import { stubAppDeps } from '../../test/http-fixtures';+import type { HttpCtx } from '../context';+import type { Services } from '../services';++// mock.module is not hoisted, so the subjects are imported inside beforeAll —+// see AGENTS.md. Mocking createServices is what makes "not built yet"+// observable at all: the real container is `{}` either way.+const createServices = mock((): Services => ({}));+mock.module('../services', () => ({ createServices }));++const resolveSession = mock(() => Promise.resolve({ userId: 'user_1' }));+mock.module('./session', () => ({+ SESSION_COOKIE_NAME: 'session',+ resolveSession,+}));++let requestContext: typeof import('./context').requestContext;+let requestLogging: typeof import('./context').requestLogging;++beforeAll(async () => {+ ({ requestContext, requestLogging } = await import('./context'));+});++beforeEach(() => {+ createServices.mockClear();+ resolveSession.mockClear();+});++// onAfterResponse runs after `handle` resolves — the response is already on+// its way out, which is the point of logging there.+const settled = () => new Promise((resolve) => setTimeout(resolve, 0));++// The claim ADR-002 and ADR-007 both rest on: thirty modules may each start+// from `.use(requestContext(deps))` and one request still builds one Ctx.+test('derives one ctx per request however many modules use the plugin', async () => {+ const { deps, scopeCalls, childCalls } = stubAppDeps();+ const seen: HttpCtx[] = [];++ // Each observer records the ctx it was handed; the route is registered on+ // the parent AFTER them, because an Elysia hook only applies to routes+ // declared after it.+ const observing = () =>+ new Elysia()+ .use(requestContext(deps))+ .onAfterResponse({ as: 'global' }, ({ ctx }) => {+ seen.push(ctx);+ });++ const app = new Elysia()+ .use(observing())+ .use(observing())+ .use(observing())+ .get('/a', ({ ctx }) => ctx.requestId);++ const response = await app.handle(+ new Request('http://localhost/a', { headers: { 'request-id': 'once' } })+ );++ expect(await response.text()).toBe('once');+ await settled();++ expect(scopeCalls()).toBe(1);+ expect(childCalls()).toEqual([{ requestId: 'once' }]);+ expect(seen).toHaveLength(3);+ expect(seen[0]).toBe(seen[1] as HttpCtx);+ expect(seen[1]).toBe(seen[2] as HttpCtx);+});++describe('the derived HttpCtx', () => {+ const build = () => {+ const stub = stubAppDeps();+ const app = new Elysia()+ .use(requestContext(stub.deps))+ .get('/', ({ ctx }) => ({+ requestId: ctx.requestId,+ ip: ctx.ip,+ userAgent: ctx.headers.get('user-agent'),+ session: ctx.cookies.get('session'),+ missing: ctx.cookies.get('nothing') ?? null,+ }))+ .get('/services', ({ ctx }) => ({+ first: ctx.services,+ second: ctx.services,+ }))+ .get('/session', async ({ ctx }) => {+ await ctx.session();+ await ctx.session();+ return 'resolved';+ })+ .get('/set-cookie', ({ ctx }) => {+ ctx.setCookie('session', 'token-1', {+ maxAge: 60,+ path: '/',+ httpOnly: true,+ sameSite: 'lax',+ secure: true,+ });+ return 'set';+ });+ return { app, ...stub };+ };++ test('carries headers, the attribution ip and the cookies', async () => {+ const { app } = build();++ const response = await app.handle(+ new Request('http://localhost/', {+ headers: {+ 'request-id': 'ctx-fields',+ 'x-real-ip': '203.0.113.11',+ 'user-agent': 'op-sdk/1.0',+ cookie: 'session=cookie-value; other=1',+ },+ })+ );++ expect(await response.json()).toEqual({+ requestId: 'ctx-fields',+ ip: '203.0.113.11',+ userAgent: 'op-sdk/1.0',+ session: 'cookie-value',+ missing: null,+ });+ });++ test('leaves services unbuilt until a handler reads them, then builds once', async () => {+ const { app } = build();++ await app.handle(new Request('http://localhost/'));+ expect(createServices).not.toHaveBeenCalled();++ await app.handle(new Request('http://localhost/services'));+ expect(createServices).toHaveBeenCalledTimes(1);+ });++ test('memoizes session() so two guards and a handler cost one lookup', async () => {+ const { app } = build();++ await app.handle(new Request('http://localhost/session'));++ expect(resolveSession).toHaveBeenCalledTimes(1);+ });++ test('writes Set-Cookie through Elysia with V1 attributes', async () => {+ const { app } = build();++ const response = await app.handle(+ new Request('http://localhost/set-cookie')+ );++ expect(response.headers.getSetCookie()).toEqual([+ 'session=token-1; Max-Age=60; Path=/; HttpOnly; Secure; SameSite=Lax',+ ]);+ });+});++describe('requestLogging', () => {+ const build = (verboseClientIds?: string[]) => {+ const stub = stubAppDeps();+ const app = new Elysia()+ .use(requestLogging(stub.deps, { verboseClientIds }))+ .get('/healthz/live', () => 'ok')+ .get('/trpc/report.list', () => 'ok')+ .post('/track', ({ body }) => body)+ .get('/export/events', () => 'ok');+ return { app, ...stub };+ };++ const lines = (stub: ReturnType<typeof build>) =>+ stub.logger.lines.filter((line) => line.message === 'request done');++ test('logs one line per request, with the requestId bound by the child logger', async () => {+ const stub = build();++ await stub.app.handle(+ new Request('http://localhost/export/events', {+ headers: {+ 'request-id': 'logged',+ 'openpanel-client-id': 'client-1',+ 'openpanel-sdk-name': 'web',+ },+ })+ );++ await settled();++ expect(stub.childCalls()).toEqual([{ requestId: 'logged' }]);+ expect(lines(stub)).toHaveLength(1);+ expect(lines(stub)[0]?.payload).toMatchObject({+ url: '/export/events',+ method: 'GET',+ headers: {+ 'openpanel-client-id': 'client-1',+ 'openpanel-sdk-name': 'web',+ },+ clientIp: '',+ clientIpHeader: '',+ userAgent: '',+ });+ });++ test('skips the health, metrics and misc surfaces and OPTIONS', async () => {+ const stub = build();++ await stub.app.handle(new Request('http://localhost/healthz/live'));+ await stub.app.handle(+ new Request('http://localhost/export/events', { method: 'OPTIONS' })+ );++ await settled();++ expect(lines(stub)).toHaveLength(0);+ });++ test('logs the tRPC input rather than the query string', async () => {+ const stub = build();++ await stub.app.handle(+ new Request(+ `http://localhost/trpc/report.list?input=${encodeURIComponent(+ JSON.stringify({ json: { projectId: 'proj-1' } })+ )}`+ )+ );++ await settled();++ expect(lines(stub)[0]?.payload).toMatchObject({+ url: '/trpc/report.list',+ input: { projectId: 'proj-1' },+ });+ });++ test('logs the /track body, and the ip only for a verbose client id', async () => {+ const stub = build(['client-verbose']);++ await stub.app.handle(+ new Request('http://localhost/track', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'openpanel-client-id': 'client-verbose',+ 'x-real-ip': '203.0.113.12',+ 'user-agent': 'op-sdk/1.0',+ },+ body: JSON.stringify({ type: 'track' }),+ })+ );++ await settled();++ expect(lines(stub)[0]?.payload).toMatchObject({+ url: '/track',+ body: { type: 'track' },+ clientIp: '203.0.113.12',+ clientIpHeader: 'x-real-ip',+ userAgent: 'op-sdk/1.0',+ });+ });+});diff --git a/packages/core/src/http/context.ts b/packages/core/src/http/context.tsnew file mode 100644index 000000000..53633951c--- /dev/null+++ b/packages/core/src/http/context.ts@@ -0,0 +1,192 @@+// The per-request plugins: one derive builds `ctx`, one hook logs the request.+//+// `requestContext` is a NAMED plugin, and the name is load-bearing. Elysia+// deduplicates by it, so all 35 modules can start from+// `.use(requestContext(deps))` and the derive still runs exactly once per+// request — one `createCtx`, one child logger, one scoped producer set. The+// corollary is that the first registration wins: every module must be built+// from the same `AppDeps`, which `defineRoutes` and `rest.routes.ts` enforce+// by construction.++import { Elysia } from 'elysia';+import {+ type AppDeps,+ createCtx,+ extendCtx,+ type HttpCtx,+ type Session,+} from '../context';+import { REQUEST_ID_LOG_FIELD } from '../logger';+import type { CookieJar, CookieOptions } from '../shared/cookie';+import { clientIpHook, requestIdHook, timestampHook } from './hooks';+import { resolveSession } from './session';++/** Ported from V1's requestLoggingHook (apps/api/src/hooks/request-logging.hook.ts). */+const UNLOGGED_PATH_PREFIXES = [+ '/healthcheck',+ '/healthz',+ '/metrics',+ '/misc',+];+const UNLOGGED_METHODS = ['OPTIONS'];+const LOGGED_INGEST_HEADERS = [+ 'openpanel-client-id',+ 'openpanel-sdk-name',+ 'openpanel-sdk-version',+];++type ElysiaCookies = Record<+ string,+ { value: unknown; set(config: Record<string, unknown>): unknown }+>;++export function requestContext(deps: AppDeps) {+ return new Elysia({ name: 'core/request-context' })+ .use(requestIdHook())+ .use(timestampHook())+ .use(clientIpHook())+ .derive(+ { as: 'global' },+ ({ request, cookie, requestId, clientIp }): { ctx: HttpCtx } => {+ const logger = deps.logger.child({ [REQUEST_ID_LOG_FIELD]: requestId });+ const cookies = wrapCookies(cookie);+ let session: Promise<Session | null> | undefined;++ return {+ ctx: extendCtx(createCtx(deps, { requestId, logger }), {+ headers: request.headers,+ ip: clientIp,+ cookies,+ session: () =>+ (session ??= resolveSession(deps, cookies, request.headers)),+ setCookie: (name: string, value: string, options?: CookieOptions) =>+ writeCookie(cookie, name, value, options),+ }),+ };+ }+ );+}++export interface RequestLoggingOptions {+ /**+ * V1 read `ENABLE_VERBOSE_LOGGING` here; core reads no environment, so the+ * parsed client-id list arrives from `apps/api`'s config.+ */+ verboseClientIds?: string[];+}++/**+ * V1's `onResponse` requestLoggingHook. One `info` line per request, named+ * `request done` — the `requestId` field rides in from the child logger,+ * replacing V1's `reqId` (ADR-018 R1).+ */+export function requestLogging(+ deps: AppDeps,+ options: RequestLoggingOptions = {}+) {+ const verboseClientIds = new Set(options.verboseClientIds ?? []);++ return new Elysia({ name: 'core/http/request-logging' })+ .use(requestContext(deps))+ .onAfterResponse(+ { as: 'global' },+ ({ ctx, request, path, query, body, timestamp, clientIpHeader }) => {+ if (UNLOGGED_METHODS.includes(request.method)) {+ return;+ }+ if (UNLOGGED_PATH_PREFIXES.some((prefix) => path.startsWith(prefix))) {+ return;+ }++ const elapsed = Date.now() - timestamp;++ if (path.includes('trpc')) {+ ctx.logger.info(+ {+ url: path,+ method: request.method,+ input: parseTrpcInput(query.input),+ elapsed,+ },+ 'request done'+ );+ return;+ }++ const clientId = request.headers.get('openpanel-client-id');+ const verbose = clientId !== null && verboseClientIds.has(clientId);++ ctx.logger.info(+ {+ url: path,+ method: request.method,+ elapsed,+ headers: pickHeaders(request.headers, LOGGED_INGEST_HEADERS),+ // V1 logs the whole /track body here; ADR-018 R6's budget for it+ // is P9's call, not this port's.+ body: path.startsWith('/track') ? body : undefined,+ clientIp: verbose ? ctx.ip : '',+ clientIpHeader: verbose ? clientIpHeader : '',+ userAgent: verbose ? (request.headers.get('user-agent') ?? '') : '',+ },+ 'request done'+ );+ }+ );+}++function wrapCookies(cookie: ElysiaCookies): CookieJar {+ return {+ get(name) {+ const value = cookie[name]?.value;+ return typeof value === 'string' ? value : undefined;+ },+ };+}++// `signed` is deliberately not forwarded: Elysia signs by app-level+// `cookie: { secrets, sign: [...] }` config, not per write, so app.ts lists+// the signed names (P3). Everything else maps one-to-one.+function writeCookie(+ cookie: ElysiaCookies,+ name: string,+ value: string,+ options: CookieOptions = {}+): void {+ cookie[name]?.set({+ value,+ maxAge: options.maxAge,+ domain: options.domain,+ path: options.path,+ sameSite: options.sameSite,+ secure: options.secure,+ httpOnly: options.httpOnly,+ });+}++// The dashboard sends the tRPC input as a JSON query param; a batched or+// malformed one is not worth an error inside a logging hook.+function parseTrpcInput(input: string | undefined): unknown {+ if (typeof input !== 'string') {+ return input;+ }+ try {+ return (JSON.parse(input) as { json?: unknown }).json;+ } catch {+ return undefined;+ }+}++function pickHeaders(+ headers: Headers,+ names: string[]+): Record<string, string> {+ const picked: Record<string, string> = {};+ for (const name of names) {+ const value = headers.get(name);+ if (value !== null) {+ picked[name] = value;+ }+ }+ return picked;+}diff --git a/packages/core/src/http/define.test.ts b/packages/core/src/http/define.test.tsnew file mode 100644index 000000000..f07e0f95a--- /dev/null+++ b/packages/core/src/http/define.test.ts@@ -0,0 +1,68 @@+import { expect, test } from 'bun:test';+import { Elysia } from 'elysia';+import { stubAppDeps } from '../../test/http-fixtures';+import { defineRoutes } from './define';++const healthRoutes = defineRoutes((app) =>+ app.get('/healthz/live', ({ ctx }) => ({ requestId: ctx.requestId }))+);++const exportRoutes = defineRoutes((app) =>+ app.get('/export/events', ({ ctx }) => ({ requestId: ctx.requestId }))+);++test('a module factory takes deps and hands ctx to its handlers', async () => {+ const { deps } = stubAppDeps();++ const response = await healthRoutes(deps).handle(+ new Request('http://localhost/healthz/live', {+ headers: { 'request-id': 'defined' },+ })+ );++ expect(await response.json()).toEqual({ requestId: 'defined' });+});++test('two modules compose into one surface on one ctx', async () => {+ const { deps, scopeCalls } = stubAppDeps();++ const app = new Elysia().use(healthRoutes(deps)).use(exportRoutes(deps));++ for (const path of ['/healthz/live', '/export/events']) {+ const response = await app.handle(+ new Request(`http://localhost${path}`, {+ headers: { 'request-id': 'composed' },+ })+ );+ expect(await response.json()).toEqual({ requestId: 'composed' });+ }++ // Two requests, two contexts — and not four, which is what a module-local+ // requestContext would have cost.+ expect(scopeCalls()).toBe(2);+});++test('the auth tiers are requestable from a module without extra wiring', async () => {+ const { deps } = stubAppDeps();++ const routes = defineRoutes((app) =>+ app.post('/manage/projects', ({ client }) => client.id, {+ clientAuth: { allow: ['root'] },+ })+ );++ const response = await routes(deps).handle(+ new Request('http://localhost/manage/projects', { method: 'POST' })+ );++ // The P2 authenticator resolves nobody; what is proven here is that the+ // macro ran and typed `client` onto the handler.+ expect(response.status).toBe(401);+});++// Compile-time half of the same claim, checked by `tsc --noEmit`: without the+// tier there is no principal to read.+defineRoutes((app) =>+ // @ts-expect-error - `client` exists only on a handler that requested clientAuth+ app.post('/unguarded', ({ client }) => client)+);diff --git a/packages/core/src/http/define.ts b/packages/core/src/http/define.tsnew file mode 100644index 000000000..f82b8e874--- /dev/null+++ b/packages/core/src/http/define.ts@@ -0,0 +1,24 @@+// A module's plain-HTTP half: a factory over `AppDeps` returning an Elysia+// instance. Deps flow top-down as plain arguments, the same way+// `createXService(deps, services)` does — no decorators at a distance, no+// options bag.+//+// Identity with a name. It fixes the factory signature and guarantees every+// module starts from the auth plugin, which brings `requestContext(deps)` with+// it: `ctx` is typed in handlers and `session` / `clientAuth` are requestable+// without each module re-wiring either.++import type { AppDeps } from '../context';+import { authMacros } from './auth';++export type RouteApp = ReturnType<typeof baseApp>;++export function defineRoutes<const T>(+ setup: (app: RouteApp, deps: AppDeps) => T+): (deps: AppDeps) => T {+ return (deps) => setup(baseApp(deps), deps);+}++function baseApp(deps: AppDeps) {+ return authMacros(deps);+}diff --git a/packages/core/src/http/hooks.test.ts b/packages/core/src/http/hooks.test.tsnew file mode 100644index 000000000..f3649debe--- /dev/null+++ b/packages/core/src/http/hooks.test.ts@@ -0,0 +1,146 @@+import { describe, expect, test } from 'bun:test';+import { cors } from '@elysiajs/cors';+import { Elysia } from 'elysia';+import { REQUEST_ID_LENGTH } from '../logger';+import {+ clientIpHook,+ requestIdHook,+ sanitizeRequestId,+ timestampHook,+} from './hooks';++const ALLOWED_ORIGIN = 'https://dashboard.test';++describe('sanitizeRequestId', () => {+ test('keeps an id a caller can correlate on', () => {+ expect(sanitizeRequestId('adr018-1a2b_3c')).toBe('adr018-1a2b_3c');+ });++ test('strips everything outside [A-Za-z0-9_-]', () => {+ expect(sanitizeRequestId('a b/c\n<script>')).toBe('abcscript');+ });++ test('truncates to 64 characters', () => {+ expect(sanitizeRequestId('x'.repeat(200))).toHaveLength(64);+ });++ test('reports nothing survivable rather than an empty id', () => {+ expect(sanitizeRequestId('!!!')).toBeNull();+ expect(sanitizeRequestId('')).toBeNull();+ expect(sanitizeRequestId(null)).toBeNull();+ });+});++describe('requestIdHook', () => {+ const app = new Elysia()+ .use(requestIdHook())+ .get('/', ({ requestId, requestIdFromCaller }) => ({+ requestId,+ requestIdFromCaller,+ }));++ test('honours an inbound request-id header', async () => {+ const response = await app.handle(+ new Request('http://localhost/', {+ headers: { 'request-id': 'caller-supplied' },+ })+ );++ expect(await response.json()).toEqual({+ requestId: 'caller-supplied',+ requestIdFromCaller: true,+ });+ });++ test('mints one when the header is absent or unusable', async () => {+ const cases: Record<string, string>[] = [{}, { 'request-id': '???' }];+ for (const headers of cases) {+ const body = (await (+ await app.handle(new Request('http://localhost/', { headers }))+ ).json()) as { requestId: string; requestIdFromCaller: boolean };++ expect(body.requestId).toHaveLength(REQUEST_ID_LENGTH);+ expect(body.requestIdFromCaller).toBe(false);+ }+ });+});++describe('clientIpHook', () => {+ const app = new Elysia()+ .use(clientIpHook())+ .get('/', ({ clientIp, clientIpHeader }) => ({ clientIp, clientIpHeader }));++ test('prefers the client-forwarded header, as V1 does', async () => {+ const response = await app.handle(+ new Request('http://localhost/', {+ headers: {+ 'openpanel-client-ip': '203.0.113.7',+ 'cf-connecting-ip': '198.51.100.4',+ },+ })+ );++ expect(await response.json()).toEqual({+ clientIp: '203.0.113.7',+ clientIpHeader: 'openpanel-client-ip',+ });+ });++ test('falls back to empty strings, never undefined', async () => {+ const response = await app.handle(new Request('http://localhost/'));+ expect(await response.json()).toEqual({ clientIp: '', clientIpHeader: '' });+ });+});++// ADR-002 "behaviour that must be preserved explicitly" 2. V1's order held by+// avvio's registration order; here it holds by `.use()` order plus the fact+// that cors runs at `onRequest`, an earlier phase than any `derive`.+test('root chain runs cors -> requestId -> timestamp -> ip', async () => {+ const ran: string[] = [];++ const app = new Elysia()+ .use(+ cors({+ origin: (request) => {+ ran.push('cors');+ return request.headers.get('origin') === ALLOWED_ORIGIN;+ },+ })+ )+ .use(requestIdHook())+ .derive({ as: 'global' }, ({ requestId }) => {+ ran.push(`requestId:${requestId}`);+ return {};+ })+ .use(timestampHook())+ .derive({ as: 'global' }, ({ timestamp }) => {+ ran.push(`timestamp:${typeof timestamp}`);+ return {};+ })+ .use(clientIpHook())+ .derive({ as: 'global' }, ({ clientIp }) => {+ ran.push(`ip:${clientIp}`);+ return {};+ })+ .get('/', () => 'ok');++ const response = await app.handle(+ new Request('http://localhost/', {+ headers: {+ origin: ALLOWED_ORIGIN,+ 'request-id': 'chain',+ 'x-real-ip': '203.0.113.9',+ },+ })+ );++ expect(response.headers.get('access-control-allow-origin')).toBe(+ ALLOWED_ORIGIN+ );+ expect(ran).toEqual([+ 'cors',+ 'requestId:chain',+ 'timestamp:number',+ 'ip:203.0.113.9',+ ]);+});diff --git a/packages/core/src/http/hooks.ts b/packages/core/src/http/hooks.tsnew file mode 100644index 000000000..6a19f1f15--- /dev/null+++ b/packages/core/src/http/hooks.ts@@ -0,0 +1,79 @@+// The root chain, as named Elysia plugins.+//+// V1's order is cors -> requestId -> timestamp -> ip, and it precedes every+// route-level hook including the rate limiters (apps/api/src/app.ts:130-133;+// ADR-002 "behaviour that must be preserved explicitly" 2). Here it is `.use()`+// order: `requestContext` composes these three in that order and `app.ts`+// mounts `@elysiajs/cors` ahead of it. The cors position is structural rather+// than conventional — it runs at `onRequest`, a strictly earlier lifecycle+// phase than `derive`, so it cannot be reordered by accident.+//+// The request-logging hook lives with `requestContext` in ./context.ts: it+// reads the request logger off `ctx` and would otherwise import this file's+// consumer.++import { getClientIpFromHeaders } from '@openpanel/common/server/get-client-ip';+import { Elysia } from 'elysia';+import { REQUEST_ID_HEADER, REQUEST_ID_LENGTH } from '../logger';+import { generateId } from '../shared/id';++// ADR-018 R2: an inbound request-id is honoured but never trusted verbatim —+// it reaches log storage and a log search.+const DISALLOWED_REQUEST_ID_CHARS = /[^A-Za-z0-9_-]/g;+const REQUEST_ID_MAX_LENGTH = 64;++export function sanitizeRequestId(candidate: string | null): string | null {+ if (!candidate) {+ return null;+ }+ const cleaned = candidate+ .replace(DISALLOWED_REQUEST_ID_CHARS, '')+ .slice(0, REQUEST_ID_MAX_LENGTH);+ return cleaned.length > 0 ? cleaned : null;+}++/**+ * First of the three. `requestIdFromCaller` is not decoration: ADR-018 R6+ * keeps a caller-supplied id out of per-event log sampling, so the support+ * case that supplied one still resolves.+ */+export function requestIdHook() {+ return new Elysia({ name: 'core/http/request-id' }).derive(+ { as: 'global' },+ ({ request }) => {+ const supplied = sanitizeRequestId(+ request.headers.get(REQUEST_ID_HEADER)+ );+ return {+ requestId: supplied ?? generateId(undefined, REQUEST_ID_LENGTH),+ requestIdFromCaller: supplied !== null,+ };+ }+ );+}++/** V1's timestampHook. `/track` ages an event against arrival with it. */+export function timestampHook() {+ return new Elysia({ name: 'core/http/timestamp' }).derive(+ { as: 'global' },+ () => ({ timestamp: Date.now() })+ );+}++/**+ * V1's ipHook, including the empty-string fallback.+ *+ * This is the *attribution* ip: it prefers client-forwarded headers, which is+ * right for analytics and fatal for a rate-limit bucket. The limiter keys on+ * `openpanel-client-id` and then `getTrustedIpFromHeaders`, and must never+ * read this (ADR-002 "behaviour that must be preserved explicitly" 2).+ */+export function clientIpHook() {+ return new Elysia({ name: 'core/http/client-ip' }).derive(+ { as: 'global' },+ ({ request }) => {+ const { ip, header } = getClientIpFromHeaders(request.headers);+ return { clientIp: ip, clientIpHeader: header };+ }+ );+}diff --git a/packages/core/src/http/session.ts b/packages/core/src/http/session.tsnew file mode 100644index 000000000..2b6b7551e--- /dev/null+++ b/packages/core/src/http/session.ts@@ -0,0 +1,25 @@+// 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).+//+// 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.++import type { AppDeps, Session } from '../context';+import type { CookieJar } from '../shared/cookie';++export const SESSION_COOKIE_NAME = 'session';++export function resolveSession(+ _deps: AppDeps,+ _cookies: CookieJar,+ _headers: Headers+): Promise<Session | null> {+ return Promise.resolve(null);+}diff --git a/packages/core/src/shared/cookie.ts b/packages/core/src/shared/cookie.tsindex 3ee3e9206..a56869672 100644--- a/packages/core/src/shared/cookie.ts+++ b/packages/core/src/shared/cookie.ts@@ -60,3 +60,14 @@ export function serializeCookie(return header;}++/**+ * The read half of a request's cookies, transport-agnostic.+ *+ * `HttpCtx.cookies` is this and not Elysia's cookie record: a module reads a+ * cookie by name and nothing else, so the framework's proxy stays behind+ * `http/context.ts` and a `Ctx` never carries an Elysia type.+ */+export interface CookieJar {+ get(name: string): string | undefined;+}diff --git a/packages/core/test/http-fixtures.ts b/packages/core/test/http-fixtures.tsnew file mode 100644index 000000000..99472948d--- /dev/null+++ b/packages/core/test/http-fixtures.ts@@ -0,0 +1,51 @@+// Stubs shared by the http tests. Not a test file (no `*.test.ts` suffix), so+// the runner does not pick it up.++import type { AppDeps } from '../src/context';+import { createRecordingProducers } from '../src/jobs/testing';+import { queues } from '../src/jobs.registry';+import { type CapturedLogger, capturingLogger } from './rpc-fixtures';++export interface AppDepsStub {+ deps: AppDeps;+ logger: CapturedLogger;+ /** One per `createCtx` — it scopes the producers exactly once. */+ scopeCalls: () => number;+ childCalls: () => Record<string, unknown>[];+}++export function stubAppDeps(): AppDepsStub {+ const producers = createRecordingProducers(queues);+ const scope = producers.scope.bind(producers);+ let scopeCalls = 0;+ producers.scope = (meta) => {+ scopeCalls++;+ return scope(meta);+ };++ const childCalls: Record<string, unknown>[] = [];+ const base = capturingLogger();+ const logger: CapturedLogger = {+ ...base,+ child: (bindings) => {+ childCalls.push(bindings);+ return logger;+ },+ };++ return {+ logger,+ scopeCalls: () => scopeCalls,+ childCalls: () => childCalls,+ deps: {+ db: {},+ ch: {},+ redis: {},+ clients: {},+ buffers: {},+ producers,+ logger,+ config: { selfHosted: false },+ },+ };+}diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.tsindex 6b6338c22..2e6107d29 100644--- a/packages/core/test/rpc-fixtures.ts+++ b/packages/core/test/rpc-fixtures.ts@@ -76,7 +76,7 @@ export function stubHttpCtx({headers: new Headers(),ip: '',- cookies: {},+ cookies: { get: () => undefined },session: () => {stub.sessionCalls++;return Promise.resolve(session);