Skip to content

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

ralph(P2-006): rpc/: base.ts on HttpCtx, errors verbatim, fetch-adapter handler

ralph7c05d2eaa6f5
diff --git a/packages/core/package.json b/packages/core/package.json
index dcb4aaf09..d22c79251 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -14,6 +14,7 @@
"dependencies": {
"@elysiajs/cors": "1.4.2",
"@elysiajs/openapi": "1.4.15",
+ "@openpanel/common": "workspace:*",
"@trpc/server": "^11.17.0",
"bullmq": "6.3.3",
"elysia": "1.4.30",
diff --git a/packages/core/src/rpc/base.test.ts b/packages/core/src/rpc/base.test.ts
new file mode 100644
index 000000000..aac9365c6
--- /dev/null
+++ b/packages/core/src/rpc/base.test.ts
@@ -0,0 +1,348 @@
+import { expect, test } from 'bun:test';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+import { stubHttpCtx } from '../../test/rpc-fixtures';
+import type { CookieOptions } from '../shared/cookie';
+import * as baseModule from './base';
+import {
+ createRateLimitMiddleware,
+ createTRPCRouter,
+ makeTrpcContext,
+ procedure,
+} from './base';
+import { createTrpcFetchHandler } from './handler';
+
+// V1's COOKIE_OPTIONS (packages/auth/constants.ts) with a domain filled in.
+const COOKIE_OPTIONS: CookieOptions = {
+ domain: '.openpanel.dev',
+ secure: true,
+ sameSite: 'lax',
+ httpOnly: true,
+ path: '/',
+};
+
+function build(options: Partial<Parameters<typeof makeTrpcContext>[2]> = {}) {
+ const { ctx, logger } = stubHttpCtx();
+ const resHeaders = new Headers();
+ return {
+ resHeaders,
+ logger,
+ trpcCtx: makeTrpcContext(ctx, resHeaders, {
+ cookieOptions: COOKIE_OPTIONS,
+ ...options,
+ }),
+ };
+}
+
+test('setCookie writes through resHeaders with V1 option precedence', async () => {
+ const { trpcCtx, resHeaders } = build();
+
+ // Only maxAge and signed are caller-controlled; COOKIE_OPTIONS is spread
+ // last, so everything a caller sends for the rest is ignored.
+ (await trpcCtx).setCookie('session', 'the-token', {
+ maxAge: 600,
+ domain: 'evil.example',
+ path: '/hijack',
+ secure: false,
+ sameSite: 'none',
+ httpOnly: false,
+ });
+
+ expect(resHeaders.get('set-cookie')).toBe(
+ 'session=the-token; Max-Age=600; Domain=.openpanel.dev; Path=/; HttpOnly; Secure; SameSite=Lax'
+ );
+});
+
+test('maxAge 0 survives (deleteSessionTokenCookie)', async () => {
+ const { trpcCtx, resHeaders } = build();
+
+ (await trpcCtx).setCookie('session', '', { maxAge: 0 });
+
+ expect(resHeaders.get('set-cookie')).toBe(
+ 'session=; Max-Age=0; Domain=.openpanel.dev; Path=/; HttpOnly; Secure; SameSite=Lax'
+ );
+});
+
+test('cookies append rather than overwrite', async () => {
+ const { trpcCtx, resHeaders } = build();
+ const ctx = await trpcCtx;
+
+ ctx.setCookie('gsc_oauth_state', 'a', { maxAge: 600 });
+ ctx.setCookie('gsc_code_verifier', 'b', { maxAge: 600 });
+ ctx.setCookie('gsc_project_id', 'c', { maxAge: 600 });
+
+ const all = resHeaders.getSetCookie();
+ expect(all).toHaveLength(3);
+ expect(all.map((line) => line.split('=')[0])).toEqual([
+ 'gsc_oauth_state',
+ 'gsc_code_verifier',
+ 'gsc_project_id',
+ ]);
+});
+
+test('values are url-encoded', async () => {
+ const { trpcCtx, resHeaders } = build();
+
+ (await trpcCtx).setCookie('last-auth-provider', 'a b;c');
+
+ expect(resHeaders.get('set-cookie')).toStartWith(
+ 'last-auth-provider=a%20b%3Bc;'
+ );
+});
+
+test('signed cookies use the injected signer and emit no extra attribute', async () => {
+ const { trpcCtx, resHeaders } = build({
+ signCookie: (value) => `${value}.sig`,
+ });
+
+ (await trpcCtx).setCookie('gsc_oauth_state', 'state', {
+ maxAge: 600,
+ signed: true,
+ });
+
+ const header = resHeaders.get('set-cookie') ?? '';
+ expect(header).toStartWith('gsc_oauth_state=state.sig;');
+ expect(header.toLowerCase()).not.toContain('signed');
+});
+
+test('a signed cookie with no signer throws instead of going out unsigned', async () => {
+ const { trpcCtx, resHeaders } = build();
+
+ const ctx = await trpcCtx;
+ expect(() =>
+ ctx.setCookie('gsc_oauth_state', 'state', { signed: true })
+ ).toThrow(/signCookie/);
+ expect(resHeaders.getSetCookie()).toHaveLength(0);
+});
+
+test('resolvedSession is undefined until session() has resolved', async () => {
+ const { trpcCtx } = build();
+ const ctx = await trpcCtx;
+
+ expect(ctx.resolvedSession).toBeUndefined();
+ await ctx.session();
+ expect(ctx.resolvedSession).toEqual({ userId: 'user_1' });
+});
+
+test('the HttpCtx is inherited, not copied — services stay lazy', async () => {
+ const { ctx } = stubHttpCtx();
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+
+ 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);
+});
+
+test('simulateLatency delays the context, and is off by default', async () => {
+ const random = Math.random;
+ Math.random = () => 1; // -> min(500, 200) = 200ms, deterministically
+ try {
+ const withoutStart = performance.now();
+ await build().trpcCtx;
+ const withoutMs = performance.now() - withoutStart;
+
+ const withStart = performance.now();
+ await build({ simulateLatency: true }).trpcCtx;
+ const withMs = performance.now() - withStart;
+
+ expect(withoutMs).toBeLessThan(50);
+ expect(withMs).toBeGreaterThanOrEqual(150);
+ } finally {
+ Math.random = random;
+ }
+});
+
+// ------------------------------------------------------- middleware factories
+
+function mountWith(
+ build: (
+ base: typeof import('./base')
+ ) => Parameters<typeof createTRPCRouter>[0]
+) {
+ const { ctx, logger } = stubHttpCtx();
+ const router = createTRPCRouter(build(baseModule));
+ const handler = createTrpcFetchHandler({
+ router,
+ logger,
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return {
+ logger,
+ call: (request: Request) => handler(request, ctx),
+ };
+}
+
+const postTo = (path: string) =>
+ new Request(`https://api.openpanel.dev/trpc/${path}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: '{}',
+ });
+
+function stubCache() {
+ const store = new Map<string, unknown>();
+ const reads: string[] = [];
+ const writes: { key: string; ttl: number; value: unknown }[] = [];
+ return {
+ store,
+ reads,
+ writes,
+ cache: {
+ getJson: (key: string) => {
+ reads.push(key);
+ return Promise.resolve((store.get(key) ?? null) as never);
+ },
+ setJson: (key: string, expireInSec: number, value: unknown) => {
+ writes.push({ key, ttl: expireInSec, value });
+ store.set(key, value);
+ return Promise.resolve();
+ },
+ },
+ };
+}
+
+test('the cache middleware keys on path + raw input and honours the ttl', async () => {
+ const { cache, reads, writes } = stubCache();
+ let hits = 0;
+
+ const mounted = mountWith(({ procedure: base, createCacheMiddleware }) => ({
+ overview: base
+ .use(createCacheMiddleware({ cache, serveFromCache: true })(60))
+ .input(z.object({ projectId: z.string() }))
+ .query(() => {
+ hits++;
+ return { visitors: 1 };
+ }),
+ }));
+
+ const url =
+ 'https://api.openpanel.dev/trpc/overview?input=' +
+ encodeURIComponent(JSON.stringify({ json: { projectId: 'p1' } }));
+
+ await mounted.call(new Request(url));
+ await mounted.call(new Request(url));
+
+ expect(hits).toBe(1);
+ expect(reads[0]).toBe("trpc:overview:{'projectId':'p1'}");
+ expect(writes).toHaveLength(1);
+ expect(writes[0]?.ttl).toBe(60);
+});
+
+test('the cache is written but not served when serveFromCache is off', async () => {
+ const { cache, writes } = stubCache();
+ let hits = 0;
+
+ const mounted = mountWith(({ procedure: base, createCacheMiddleware }) => ({
+ overview: base
+ .use(createCacheMiddleware({ cache, serveFromCache: false })(60))
+ .query(() => {
+ hits++;
+ return { visitors: 1 };
+ }),
+ }));
+
+ await mounted.call(new Request('https://api.openpanel.dev/trpc/overview'));
+ await mounted.call(new Request('https://api.openpanel.dev/trpc/overview'));
+
+ expect(hits).toBe(2);
+ expect(writes).toHaveLength(2);
+});
+
+test('a zero ttl bypasses the cache entirely', async () => {
+ const { cache, reads, writes } = stubCache();
+
+ const mounted = mountWith(({ procedure: base, createCacheMiddleware }) => ({
+ overview: base
+ .use(createCacheMiddleware({ cache, serveFromCache: true })(() => 0))
+ .query(() => ({ visitors: 1 })),
+ }));
+
+ await mounted.call(new Request('https://api.openpanel.dev/trpc/overview'));
+
+ expect(reads).toHaveLength(0);
+ expect(writes).toHaveLength(0);
+});
+
+test('mutations are never cached', async () => {
+ const { cache, writes } = stubCache();
+
+ const mounted = mountWith(({ procedure: base, createCacheMiddleware }) => ({
+ save: base
+ .use(createCacheMiddleware({ cache, serveFromCache: true })(60))
+ .mutation(() => ({ ok: true })),
+ }));
+
+ await mounted.call(postTo('save'));
+
+ expect(writes).toHaveLength(0);
+});
+
+test('the rate limit middleware hands the limiter ctx fields, not a request', async () => {
+ const calls: unknown[] = [];
+ const { ctx, logger } = stubHttpCtx({
+ ip: '203.0.113.7',
+ headers: new Headers({ 'user-agent': 'op-test/1.0' }),
+ });
+
+ const router = createTRPCRouter({
+ signIn: procedure
+ .use(
+ createRateLimitMiddleware(async (args) => {
+ calls.push(args);
+ await Promise.resolve();
+ })({ max: 5, windowMs: 60_000 })
+ )
+ .mutation(() => ({ ok: true })),
+ });
+ const handler = createTrpcFetchHandler({
+ router,
+ logger,
+ cookieOptions: COOKIE_OPTIONS,
+ });
+
+ await handler(postTo('signIn'), ctx);
+
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toEqual({
+ headers: ctx.headers,
+ ip: '203.0.113.7',
+ logger: ctx.logger,
+ path: 'signIn',
+ max: 5,
+ windowMs: 60_000,
+ });
+});
+
+test('a limiter rejection stops the procedure and surfaces as 429', async () => {
+ let ran = false;
+ const { ctx, logger } = stubHttpCtx();
+
+ const router = createTRPCRouter({
+ signIn: procedure
+ .use(
+ createRateLimitMiddleware(() =>
+ Promise.reject(new TRPCError({ code: 'TOO_MANY_REQUESTS' }))
+ )({ max: 5, windowMs: 60_000 })
+ )
+ .mutation(() => {
+ ran = true;
+ return { ok: true };
+ }),
+ });
+ const handler = createTrpcFetchHandler({
+ router,
+ logger,
+ cookieOptions: COOKIE_OPTIONS,
+ });
+
+ const response = await handler(postTo('signIn'), ctx);
+
+ expect(ran).toBe(false);
+ expect(response.status).toBe(429);
+ expect(logger.lines[0]?.message).toBe('trpc rate limited');
+});
diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.ts
new file mode 100644
index 000000000..b5ec56a8b
--- /dev/null
+++ b/packages/core/src/rpc/base.ts
@@ -0,0 +1,276 @@
+// The tRPC instance, its context, and the middleware factories procedures are
+// built from (ADR-009).
+//
+// The tRPC context IS the Elysia-derived `HttpCtx`: `makeTrpcContext` adds the
+// tRPC-specific bits and overrides exactly one field. There is no `req`/`res`
+// here — a procedure reads `ctx.headers`, `ctx.ip`, `ctx.logger`.
+//
+// `transformer`, `errorFormatter` and `Meta` are verbatim from
+// packages/trpc/src/trpc.ts:44-67; error semantics are unchanged by decision.
+
+import { initTRPC } from '@trpc/server';
+import superjson from 'superjson';
+import { ZodError, z } from 'zod';
+import type { HttpCtx, Session } from '../context';
+import type { Logger } from '../logger';
+import { type CookieOptions, serializeCookie } from '../shared/cookie';
+
+/**
+ * Per-procedure metadata consulted by `enforceAccess`.
+ *
+ * A tRPC mutation is not always a mutation of project *state* - the AI helpers
+ * are one-shot compute that happen to be modelled as mutations. Those may run
+ * at read level. The default is write, so forgetting to set this fails closed.
+ */
+export interface Meta {
+ /** This mutation does not change project state; read access is enough. */
+ readOnlyMutation?: boolean;
+}
+
+/** What tRPC procedures see. Everything except `resolvedSession` is `HttpCtx`. */
+export interface TrpcContext extends HttpCtx {
+ /**
+ * The session if `session()` has already resolved, `undefined` otherwise.
+ * `onError` logs it and cannot await, which is the only reason this exists.
+ */
+ readonly resolvedSession: Session | null | undefined;
+}
+
+const t = initTRPC
+ .context<TrpcContext>()
+ .meta<Meta>()
+ .create({
+ transformer: superjson,
+ errorFormatter({ shape, error }) {
+ return {
+ ...shape,
+ data: {
+ ...shape.data,
+ zodError:
+ error.cause instanceof ZodError
+ ? z.flattenError(error.cause)
+ : null,
+ },
+ };
+ },
+ });
+
+export const createTRPCRouter = t.router;
+export const middleware = t.middleware;
+/**
+ * The bare procedure. V1's `publicProcedure` / `protectedProcedure` /
+ * `protectedProcedureWithoutAccess` compose this with the logger, sessionScope,
+ * `enforceUserIsAuthed` and `enforceAccess` middlewares; those need the
+ * resolved `Session` shape and the access rules, so they land with auth (P6).
+ */
+export const procedure = t.procedure;
+
+// V1 delayed every non-production request by up to 200ms so a developer felt
+// the latency a user does. Preserved, with the flag injected: core reads no
+// process.env.
+const ARTIFICIAL_LATENCY_SPREAD_MS = 500;
+const ARTIFICIAL_LATENCY_MAX_MS = 200;
+
+export interface TrpcContextOptions {
+ /**
+ * V1's `COOKIE_OPTIONS`. Deployment-derived (it reads `DASHBOARD_URL`), so
+ * it is injected rather than imported: core reads no environment.
+ */
+ cookieOptions: CookieOptions;
+ /** `NODE_ENV !== 'production'` at the call site. */
+ simulateLatency?: boolean;
+ /**
+ * Required only if a procedure asks for `signed: true` (three cookies in the
+ * GSC OAuth flow). Absent, `setCookie` throws rather than quietly emitting an
+ * unsigned cookie the callback would reject.
+ */
+ signCookie?: (value: string) => string;
+}
+
+/**
+ * Builds the tRPC context from the request-scoped `HttpCtx`.
+ *
+ * Cookies go out through the fetch adapter's `resHeaders`, not through Elysia:
+ * the handler returns a `Response` the framework did not build, so the cookie
+ * proxy is not a guaranteed path out (ADR-009 constraint 1).
+ */
+export async function makeTrpcContext(
+ ctx: HttpCtx,
+ resHeaders: Headers,
+ options: TrpcContextOptions
+): Promise<TrpcContext> {
+ if (options.simulateLatency) {
+ await new Promise((resolve) =>
+ setTimeout(
+ () => resolve(1),
+ Math.min(
+ Math.random() * ARTIFICIAL_LATENCY_SPREAD_MS,
+ ARTIFICIAL_LATENCY_MAX_MS
+ )
+ )
+ );
+ }
+
+ let resolvedSession: Session | null | undefined;
+
+ const setCookie = (
+ name: string,
+ value: string,
+ cookie: CookieOptions = {}
+ ): void => {
+ // V1's precedence, exactly: only `maxAge` and `signed` are caller-
+ // controlled, everything else comes from COOKIE_OPTIONS spread last.
+ const merged: CookieOptions = {
+ maxAge: cookie.maxAge,
+ signed: cookie.signed,
+ ...options.cookieOptions,
+ };
+
+ if (merged.signed && !options.signCookie) {
+ throw new Error(
+ `Cookie '${name}' asked to be signed but no signCookie was provided`
+ );
+ }
+
+ resHeaders.append(
+ 'set-cookie',
+ serializeCookie(
+ name,
+ merged.signed && options.signCookie ? options.signCookie(value) : value,
+ merged
+ )
+ );
+ };
+
+ // Prototype-chained onto the HttpCtx, never spread: `{ ...ctx }` reads
+ // `services` and forces the build the lazy getter exists to avoid.
+ // defineProperties, not Object.assign, because `resolvedSession` is an
+ // accessor and Object.assign would copy its value once.
+ const trpcCtx = Object.create(ctx) as TrpcContext;
+ Object.defineProperties(trpcCtx, {
+ session: {
+ value: async (): Promise<Session | null> => {
+ resolvedSession = await ctx.session();
+ return resolvedSession;
+ },
+ enumerable: true,
+ },
+ resolvedSession: {
+ get: () => resolvedSession,
+ enumerable: true,
+ },
+ setCookie: { value: setCookie, enumerable: true },
+ });
+ return trpcCtx;
+}
+
+/** The subset of the Redis cache the RPC layer uses. */
+export interface RpcCache {
+ getJson<T = unknown>(key: string): Promise<T | null>;
+ setJson<T = unknown>(
+ key: string,
+ expireInSec: number,
+ value: T
+ ): Promise<unknown>;
+}
+
+export interface CacheMiddlewareDeps {
+ cache: RpcCache;
+ /**
+ * V1 wrote the cache everywhere but only *served* from it in production
+ * (`NODE_ENV === 'production'`), so a developer never debugged a stale
+ * answer. Preserved as a flag.
+ */
+ serveFromCache: boolean;
+}
+
+const middlewareMarker = 'middlewareMarker' as 'middlewareMarker' & {
+ __brand: 'middlewareMarker';
+};
+
+/**
+ * Query response caching, keyed by procedure path and raw input.
+ *
+ * A factory over the injected cache rather than a module singleton reaching for
+ * `getRedisCache()`: the client is built once in main.ts and handed down, so a
+ * test passes a map and a second process does not open a connection it never
+ * uses.
+ */
+export const createCacheMiddleware =
+ ({ cache, serveFromCache }: CacheMiddlewareDeps) =>
+ (cbOrTtl: number | ((input: any, opts: { path: string }) => number)) =>
+ t.middleware(async ({ ctx, next, path, type, getRawInput, input }) => {
+ const ttl =
+ typeof cbOrTtl === 'function' ? cbOrTtl(input, { path }) : cbOrTtl;
+ if (!ttl) {
+ return next();
+ }
+ const rawInput = await getRawInput();
+ if (type !== 'query') {
+ return next();
+ }
+ let key = `trpc:${path}:`;
+ if (rawInput) {
+ key += JSON.stringify(rawInput).replace(/"/g, "'");
+ }
+ const cached = await cache.getJson(key);
+ if (cached && serveFromCache) {
+ return {
+ ok: true,
+ data: cached,
+ ctx,
+ marker: middlewareMarker,
+ };
+ }
+ const result = await next();
+
+ // @ts-expect-error
+ if (result.data) {
+ cache.setJson(
+ key,
+ ttl,
+ // @ts-expect-error
+ result.data
+ );
+ }
+ return result;
+ });
+
+export interface RateLimitOptions {
+ /** Requests allowed per window before the first block. */
+ max: number;
+ windowMs: number;
+}
+
+/**
+ * The limiter itself, injected. It keys on the trusted IP and talks to Redis;
+ * both are boot-scope concerns, and injecting it is what lets a procedure be
+ * tested without one.
+ */
+export type EnforceRateLimit = (
+ args: RateLimitOptions & {
+ headers: Headers;
+ ip: string;
+ logger: Logger;
+ /** tRPC procedure path - blocks are scoped to it. */
+ path: string;
+ }
+) => Promise<void>;
+
+/**
+ * Throttle a procedure by client IP, with an exponentially growing lockout for
+ * repeat offenders. See the limiter for the escalation rules and for the log
+ * line (`rate limit blocked`) that carries the offending IP.
+ */
+export const createRateLimitMiddleware =
+ (enforceRateLimit: EnforceRateLimit) => (options: RateLimitOptions) =>
+ t.middleware(async ({ ctx, next, path }) => {
+ await enforceRateLimit({
+ headers: ctx.headers,
+ ip: ctx.ip,
+ logger: ctx.logger,
+ path,
+ ...options,
+ });
+ return next();
+ });
diff --git a/packages/core/src/rpc/errors.test.ts b/packages/core/src/rpc/errors.test.ts
new file mode 100644
index 000000000..adb603e2f
--- /dev/null
+++ b/packages/core/src/rpc/errors.test.ts
@@ -0,0 +1,28 @@
+import { expect, test } from 'bun:test';
+import { TRPCError } from '@trpc/server';
+import {
+ TRPCAccessError,
+ TRPCBadRequestError,
+ TRPCForbiddenError,
+ TRPCInternalServerError,
+ TRPCNotFoundError,
+} from './errors';
+
+// The five classes and their codes are the wire contract apps/start narrows on.
+const CASES = [
+ [TRPCAccessError, 'UNAUTHORIZED'],
+ [TRPCNotFoundError, 'NOT_FOUND'],
+ [TRPCForbiddenError, 'FORBIDDEN'],
+ [TRPCInternalServerError, 'INTERNAL_SERVER_ERROR'],
+ [TRPCBadRequestError, 'BAD_REQUEST'],
+] as const;
+
+for (const [Klass, code] of CASES) {
+ test(`${Klass.name} carries ${code} and its message`, () => {
+ const error = new Klass('nope');
+
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error.code).toBe(code);
+ expect(error.message).toBe('nope');
+ });
+}
diff --git a/packages/core/src/rpc/errors.ts b/packages/core/src/rpc/errors.ts
new file mode 100644
index 000000000..785b12ca5
--- /dev/null
+++ b/packages/core/src/rpc/errors.ts
@@ -0,0 +1,31 @@
+import { TRPCError } from '@trpc/server';
+
+export class TRPCAccessError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'UNAUTHORIZED', message });
+ }
+}
+
+export class TRPCNotFoundError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'NOT_FOUND', message });
+ }
+}
+
+export class TRPCForbiddenError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'FORBIDDEN', message });
+ }
+}
+
+export class TRPCInternalServerError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'INTERNAL_SERVER_ERROR', message });
+ }
+}
+
+export class TRPCBadRequestError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'BAD_REQUEST', message });
+ }
+}
diff --git a/packages/core/src/rpc/handler.test.ts b/packages/core/src/rpc/handler.test.ts
new file mode 100644
index 000000000..d3dc30407
--- /dev/null
+++ b/packages/core/src/rpc/handler.test.ts
@@ -0,0 +1,259 @@
+import { expect, test } from 'bun:test';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+import { capturingLogger, stubHttpCtx } from '../../test/rpc-fixtures';
+import type { CookieOptions } from '../shared/cookie';
+import { createTRPCRouter, makeTrpcContext, procedure } from './base';
+import { TRPCForbiddenError } from './errors';
+import {
+ createTrpcFetchHandler,
+ createTrpcOnError,
+ type TrpcErrorReport,
+} from './handler';
+
+const COOKIE_OPTIONS: CookieOptions = {
+ domain: '.openpanel.dev',
+ secure: true,
+ sameSite: 'lax',
+ httpOnly: true,
+ path: '/',
+};
+
+// ---------------------------------------------------------------- onError
+
+function report(overrides: Partial<TrpcErrorReport> = {}): TrpcErrorReport {
+ return {
+ error: new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'boom' }),
+ path: 'report.get',
+ input: { projectId: 'p1' },
+ type: 'query',
+ ctx: undefined,
+ req: new Request('https://api.openpanel.dev/trpc/report.get', {
+ headers: {
+ 'user-agent': 'op-test/1.0',
+ 'cf-connecting-ip': '203.0.113.7',
+ },
+ }),
+ ...overrides,
+ };
+}
+
+test('UNAUTHORIZED on organization.list is dropped', () => {
+ const logger = capturingLogger();
+
+ createTrpcOnError(logger)(
+ report({
+ error: new TRPCError({ code: 'UNAUTHORIZED' }),
+ path: 'organization.list',
+ })
+ );
+
+ expect(logger.lines).toHaveLength(0);
+});
+
+test('the drop is scoped to that one path', () => {
+ const logger = capturingLogger();
+
+ createTrpcOnError(logger)(
+ report({
+ error: new TRPCError({ code: 'UNAUTHORIZED' }),
+ path: 'organization.get',
+ })
+ );
+
+ expect(logger.lines).toHaveLength(1);
+ expect(logger.lines[0]?.level).toBe('error');
+});
+
+test('TOO_MANY_REQUESTS logs at warn as "trpc rate limited"', () => {
+ const logger = capturingLogger();
+
+ createTrpcOnError(logger)(
+ report({ error: new TRPCError({ code: 'TOO_MANY_REQUESTS' }) })
+ );
+
+ expect(logger.lines).toHaveLength(1);
+ expect(logger.lines[0]?.level).toBe('warn');
+ expect(logger.lines[0]?.message).toBe('trpc rate limited');
+});
+
+test('everything else logs at error as "trpc error", with the V1 fields', () => {
+ const logger = capturingLogger();
+ const failure = report();
+
+ createTrpcOnError(logger)(failure);
+
+ expect(logger.lines).toHaveLength(1);
+ const [line] = logger.lines;
+ expect(line?.level).toBe('error');
+ expect(line?.message).toBe('trpc error');
+ expect(line?.payload).toEqual({
+ err: failure.error,
+ path: 'report.get',
+ input: { projectId: 'p1' },
+ type: 'query',
+ session: undefined,
+ ip: '203.0.113.7',
+ ipHeader: 'cf-connecting-ip',
+ userAgent: 'op-test/1.0',
+ });
+});
+
+test('the request logger is preferred and the resolved session is carried', async () => {
+ const bootLogger = capturingLogger();
+ const { ctx, logger: requestLogger } = stubHttpCtx();
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ await trpcCtx.session();
+
+ createTrpcOnError(bootLogger)(report({ ctx: trpcCtx }));
+
+ expect(bootLogger.lines).toHaveLength(0);
+ expect(requestLogger.lines).toHaveLength(1);
+ expect(
+ (requestLogger.lines[0]?.payload as { session: unknown }).session
+ ).toEqual({ userId: 'user_1' });
+});
+
+test('a ctx-less failure (createContext threw) logs through the boot logger', () => {
+ const bootLogger = capturingLogger();
+
+ expect(() =>
+ createTrpcOnError(bootLogger)(report({ ctx: undefined }))
+ ).not.toThrow();
+
+ expect(bootLogger.lines).toHaveLength(1);
+ expect(bootLogger.lines[0]?.message).toBe('trpc error');
+});
+
+test('an untrusted forwarded ip is ignored', () => {
+ const logger = capturingLogger();
+
+ createTrpcOnError(logger)(
+ report({
+ req: new Request('https://api.openpanel.dev/trpc/report.get', {
+ headers: { 'x-client-ip': '198.51.100.9' },
+ }),
+ })
+ );
+
+ const payload = logger.lines[0]?.payload as { ip: string; ipHeader: string };
+ expect(payload.ip).toBe('');
+ expect(payload.ipHeader).toBe('');
+});
+
+// ------------------------------------------------------- the mounted handler
+
+const router = createTRPCRouter({
+ ping: procedure.query(() => ({ pong: true })),
+ signIn: procedure
+ .input(z.object({ email: z.email() }))
+ .mutation(({ ctx, input }) => {
+ ctx.setCookie('session', `token-for-${input.email}`, { maxAge: 600 });
+ return { ok: true };
+ }),
+ forbidden: procedure.query(() => {
+ throw new TRPCForbiddenError('nope');
+ }),
+});
+
+function mount() {
+ // One logger for both channels: which of the two a line took is asserted by
+ // the onError tests above, not here.
+ const logger = capturingLogger();
+ const { ctx } = stubHttpCtx({ logger });
+ const handler = createTrpcFetchHandler({
+ router,
+ logger,
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return { logger, call: (request: Request) => handler(request, ctx) };
+}
+
+test('a query resolves through the superjson envelope', async () => {
+ const response = await mount().call(
+ new Request('https://api.openpanel.dev/trpc/ping')
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ result: { data: { json: { pong: true } } },
+ });
+});
+
+test('Set-Cookie survives the raw Response the handler returns', async () => {
+ const response = await mount().call(
+ new Request('https://api.openpanel.dev/trpc/signIn', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ json: { email: '[email protected]' } }),
+ })
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get('set-cookie')).toBe(
+ 'session=token-for-carl%40openpanel.dev; Max-Age=600; Domain=.openpanel.dev; Path=/; HttpOnly; Secure; SameSite=Lax'
+ );
+});
+
+test('a ZodError is flattened onto data.zodError', async () => {
+ const response = await mount().call(
+ new Request('https://api.openpanel.dev/trpc/signIn', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ json: { email: 'not-an-email' } }),
+ })
+ );
+
+ expect(response.status).toBe(400);
+ const body = (await response.json()) as {
+ error: {
+ json: { data: { code: string; zodError: { fieldErrors: unknown } } };
+ };
+ };
+ expect(body.error.json.data.code).toBe('BAD_REQUEST');
+ expect(body.error.json.data.zodError.fieldErrors).toEqual({
+ email: ['Invalid email address'],
+ });
+});
+
+test('a TRPCForbiddenError is a 403 with a null zodError', async () => {
+ const response = await mount().call(
+ new Request('https://api.openpanel.dev/trpc/forbidden')
+ );
+
+ expect(response.status).toBe(403);
+ const body = (await response.json()) as {
+ error: {
+ json: { message: string; data: { code: string; zodError: null } };
+ };
+ };
+ expect(body.error.json.message).toBe('nope');
+ expect(body.error.json.data.code).toBe('FORBIDDEN');
+ expect(body.error.json.data.zodError).toBeNull();
+});
+
+test('an unknown procedure is a 404 and is logged', async () => {
+ const mounted = mount();
+ const response = await mounted.call(
+ new Request('https://api.openpanel.dev/trpc/nope.nope')
+ );
+
+ expect(response.status).toBe(404);
+ expect(mounted.logger.lines[0]?.message).toBe('trpc error');
+});
+
+// The client does not batch today; this guards the `.all('/trpc/*')` wildcard
+// against a future httpBatchLink, whose path segment carries commas.
+test('a batched request resolves every procedure in the segment', async () => {
+ const response = await mount().call(
+ new Request('https://api.openpanel.dev/trpc/ping,ping?batch=1&input={}')
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual([
+ { result: { data: { json: { pong: true } } } },
+ { result: { data: { json: { pong: true } } } },
+ ]);
+});
diff --git a/packages/core/src/rpc/handler.ts b/packages/core/src/rpc/handler.ts
new file mode 100644
index 000000000..21d80eeb5
--- /dev/null
+++ b/packages/core/src/rpc/handler.ts
@@ -0,0 +1,113 @@
+// The tRPC mount: the official fetch adapter, one handler, one `onError`
+// (ADR-009).
+//
+// The three `onError` branches are V1's (apps/api/src/app.ts:175-206) with one
+// change and no others: the fields come from `ctx` and the `Request`, because
+// under a fetch adapter `req` is a `Request` and has neither `socket` nor a
+// logger. The messages, the levels, the payload keys and the `organization.list`
+// drop are unchanged.
+
+import { getTrustedIpFromHeaders } from '@openpanel/common/server/get-client-ip';
+import type { AnyRouter, TRPCError } from '@trpc/server';
+import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
+import type { HttpCtx } from '../context';
+import type { Logger } from '../logger';
+import {
+ makeTrpcContext,
+ type TrpcContext,
+ type TrpcContextOptions,
+} from './base';
+
+/**
+ * The fetch adapter derives the procedure path with
+ * `pathname.slice(endpoint.length)`, and a batched request puts commas in that
+ * segment — so the route it mounts on is `.all('/trpc/*')`, not `/trpc/:path`.
+ */
+export const TRPC_ENDPOINT = '/trpc';
+
+/** The fetch adapter's `onError` argument, structurally. */
+export interface TrpcErrorReport {
+ error: TRPCError;
+ path: string | undefined;
+ input: unknown;
+ type: 'query' | 'mutation' | 'subscription' | 'unknown';
+ ctx: TrpcContext | undefined;
+ req: Request;
+}
+
+/** Silenced deliberately: the dashboard probes it while signed out. */
+const SILENCED_UNAUTHORIZED_PATH = 'organization.list';
+
+/**
+ * `bootLogger` is the fallback for when `createContext` itself threw — there is
+ * no `ctx` then, and a naive `ctx.logger.error(...)` would turn a
+ * context-construction failure into a second throw inside the error handler.
+ */
+export function createTrpcOnError(bootLogger: Logger) {
+ return function onError(report: TrpcErrorReport): void {
+ if (
+ report.error.code === 'UNAUTHORIZED' &&
+ report.path === SILENCED_UNAUTHORIZED_PATH
+ ) {
+ 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(report.req.headers);
+ const payload = {
+ err: report.error,
+ path: report.path,
+ input: report.input,
+ type: report.type,
+ session: report.ctx?.resolvedSession,
+ ip,
+ ipHeader: header,
+ userAgent: report.req.headers.get('user-agent'),
+ };
+
+ const logger = report.ctx?.logger ?? bootLogger;
+
+ // Being rate limited is the system working, not an error - logging it
+ // as one buried the real errors under 15k lines a day.
+ if (report.error.code === 'TOO_MANY_REQUESTS') {
+ logger.warn(payload, 'trpc rate limited');
+ return;
+ }
+
+ logger.error(payload, 'trpc error');
+ };
+}
+
+export interface TrpcFetchHandlerOptions extends TrpcContextOptions {
+ router: AnyRouter;
+ /** Used only when `createContext` threw. Every other line goes to `ctx.logger`. */
+ logger: Logger;
+ endpoint?: string;
+}
+
+/**
+ * The handler `app.ts` hangs on `.all('/trpc/*')`. It returns a raw `Response`,
+ * so `/trpc` sits outside Elysia's response lifecycle — as it sat outside
+ * Fastify's in V1.
+ */
+export function createTrpcFetchHandler(options: TrpcFetchHandlerOptions) {
+ const {
+ router,
+ logger,
+ endpoint = TRPC_ENDPOINT,
+ ...contextOptions
+ } = options;
+ const onError = createTrpcOnError(logger);
+
+ return (request: Request, ctx: HttpCtx): Promise<Response> =>
+ fetchRequestHandler({
+ endpoint,
+ req: request,
+ router,
+ createContext: ({ resHeaders }) =>
+ makeTrpcContext(ctx, resHeaders, contextOptions),
+ onError,
+ });
+}
diff --git a/packages/core/src/shared/cookie.ts b/packages/core/src/shared/cookie.ts
index f87799e9e..3ee3e9206 100644
--- a/packages/core/src/shared/cookie.ts
+++ b/packages/core/src/shared/cookie.ts
@@ -17,3 +17,46 @@ export type ISetCookie = (
value: string,
options: CookieOptions
) => void;
+
+const SAME_SITE_ATTRIBUTE = {
+ lax: 'Lax',
+ strict: 'Strict',
+ none: 'None',
+} as const;
+
+/**
+ * Serializes one `Set-Cookie` header value.
+ *
+ * Attribute order follows the `cookie` package V1 served these through
+ * (@fastify/cookie), so a header produced here is byte-comparable with V1's.
+ * `signed` is deliberately not emitted: it is not a cookie attribute, it is an
+ * instruction to the caller's signer.
+ */
+export function serializeCookie(
+ name: string,
+ value: string,
+ options: CookieOptions = {}
+): string {
+ let header = `${name}=${encodeURIComponent(value)}`;
+
+ if (options.maxAge !== undefined) {
+ header += `; Max-Age=${Math.floor(options.maxAge)}`;
+ }
+ if (options.domain) {
+ header += `; Domain=${options.domain}`;
+ }
+ if (options.path) {
+ header += `; Path=${options.path}`;
+ }
+ if (options.httpOnly) {
+ header += '; HttpOnly';
+ }
+ if (options.secure) {
+ header += '; Secure';
+ }
+ if (options.sameSite) {
+ header += `; SameSite=${SAME_SITE_ATTRIBUTE[options.sameSite]}`;
+ }
+
+ return header;
+}
diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.ts
new file mode 100644
index 000000000..6b6338c22
--- /dev/null
+++ b/packages/core/test/rpc-fixtures.ts
@@ -0,0 +1,99 @@
+// Stubs shared by the rpc tests. Not a test file (no `*.test.ts` suffix), so
+// the runner does not pick it up.
+
+import {
+ type AppDeps,
+ createCtx,
+ extendCtx,
+ type HttpCtx,
+} from '../src/context';
+import { createRecordingProducers } from '../src/jobs/testing';
+import { queues } from '../src/jobs.registry';
+import type { LogFn, Logger } from '../src/logger';
+
+export interface LoggedLine {
+ level: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
+ payload: unknown;
+ message: unknown;
+}
+
+export interface CapturedLogger extends Logger {
+ lines: LoggedLine[];
+}
+
+/** A logger that records instead of writing, so a branch is assertable. */
+export function capturingLogger(lines: LoggedLine[] = []): CapturedLogger {
+ const at =
+ (level: LoggedLine['level']): LogFn =>
+ (payload: unknown, message?: unknown) => {
+ lines.push({ level, payload, message });
+ };
+
+ const logger: CapturedLogger = {
+ lines,
+ fatal: at('fatal'),
+ error: at('error'),
+ warn: at('warn'),
+ info: at('info'),
+ debug: at('debug'),
+ trace: at('trace'),
+ child: () => logger,
+ };
+ return logger;
+}
+
+export const TEST_REQUEST_ID = 'req_abcdefghijklmnopqrstu';
+
+export interface HttpCtxStub {
+ ctx: HttpCtx;
+ logger: CapturedLogger;
+ /** Cookies written through the *unwrapped* HttpCtx.setCookie, if any. */
+ cookies: { name: string; value: string; options: unknown }[];
+ sessionCalls: number;
+}
+
+export function stubHttpCtx(
+ overrides: Partial<HttpCtx> & { logger?: CapturedLogger } = {},
+ session: unknown = { userId: 'user_1' }
+): HttpCtxStub {
+ const logger = overrides.logger ?? capturingLogger();
+ const cookies: HttpCtxStub['cookies'] = [];
+ const stub = { sessionCalls: 0 };
+
+ const deps: AppDeps = {
+ db: {},
+ ch: {},
+ redis: {},
+ clients: {},
+ buffers: {},
+ producers: createRecordingProducers(queues),
+ logger,
+ config: { selfHosted: false },
+ };
+
+ const ctx = extendCtx(
+ createCtx(deps, { requestId: TEST_REQUEST_ID, logger }),
+ {
+ headers: new Headers(),
+ ip: '',
+ cookies: {},
+ session: () => {
+ stub.sessionCalls++;
+ return Promise.resolve(session);
+ },
+ setCookie: (name: string, value: string, options?: unknown) => {
+ cookies.push({ name, value, options });
+ },
+ ...overrides,
+ }
+ );
+
+ return {
+ ctx,
+ logger,
+ cookies,
+ get sessionCalls() {
+ return stub.sessionCalls;
+ },
+ };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 50ec58aef..0070319e8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1204,6 +1204,9 @@ importers:
'@elysiajs/openapi':
specifier: 1.4.15
+ '@openpanel/common':
+ specifier: workspace:*
+ version: link:../common
'@trpc/server':
specifier: ^11.17.0
version: 11.17.0([email protected])
@@ -23994,7 +23997,7 @@ snapshots:
resolve: 1.22.12
resolve-from: 5.0.0
resolve.exports: 2.0.3
- semver: 7.7.4
+ semver: 7.8.5
send: 0.18.0([email protected])
slugify: 1.6.9
source-map-support: 0.5.21
@@ -24036,7 +24039,7 @@ snapshots:
getenv: 1.0.0
glob: 7.1.6
resolve-from: 5.0.0
- semver: 7.7.4
+ semver: 7.8.5
slash: 3.0.0
slugify: 1.6.9
xcode: 3.0.1
@@ -25242,7 +25245,7 @@ snapshots:
'@npmcli/[email protected]':
dependencies:
'@gar/promisify': 1.1.3
- semver: 7.7.4
+ semver: 7.8.5
'@npmcli/[email protected]':
dependencies:
@@ -25279,7 +25282,7 @@ snapshots:
perfect-debounce: 2.0.0
pkg-types: 2.3.0
scule: 1.3.0
- semver: 7.7.4
+ semver: 7.8.5
srvx: 0.9.8
std-env: 3.10.0
tinyexec: 1.1.1
@@ -27900,7 +27903,7 @@ snapshots:
hermes-profile-transformer: 0.0.6
node-stream-zip: 1.15.0
ora: 5.4.1
- semver: 7.7.4
+ semver: 7.8.5
strip-ansi: 5.2.0
wcwidth: 1.0.1
yaml: 2.8.2
@@ -27966,7 +27969,7 @@ snapshots:
node-fetch: 2.7.0
open: 6.4.0
ora: 5.4.1
- semver: 7.7.4
+ semver: 7.8.5
shell-quote: 1.8.3
sudo-prompt: 9.2.1
transitivePeerDependencies:
@@ -27995,7 +27998,7 @@ snapshots:
fs-extra: 8.1.0
graceful-fs: 4.2.11
prompts: 2.4.2
- semver: 7.7.4
+ semver: 7.8.5
transitivePeerDependencies:
- bufferutil
- encoding
@@ -37889,7 +37892,7 @@ snapshots:
dependencies:
hosted-git-info: 7.0.2
proc-log: 4.2.0
- semver: 7.7.4
+ semver: 7.8.5
validate-npm-package-name: 5.0.1