Skip to content

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

ralph(M4-002): tRPC rebase: packages/trpc onto core CoreContext - ONE tRPC instance, V1 Fastify keeps serving it unchanged

ralph93a521ac0930
diff --git a/packages/core/package.json b/packages/core/package.json
index dfd518528..cca02a875 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -3,6 +3,7 @@
"version": "0.0.1",
"type": "module",
"private": true,
+ "sideEffects": false,
"exports": {
".": "./src/index.ts",
"./modules/*.constants": "./src/modules/*.constants.ts"
@@ -14,6 +15,7 @@
"dependencies": {
"@elysiajs/cors": "1.4.2",
"@elysiajs/openapi": "1.4.15",
+ "@openpanel/auth": "workspace:^",
"@openpanel/common": "workspace:*",
"@trpc/server": "^11.17.0",
"bullmq": "6.3.3",
diff --git a/packages/core/src/context.ts b/packages/core/src/context.ts
index 4d76cf8a6..083865386 100644
--- a/packages/core/src/context.ts
+++ b/packages/core/src/context.ts
@@ -4,6 +4,7 @@
// edge reaches the query, the enqueue and the job that enqueue causes
// (ADR-007 decision 18, ADR-018 R1).
+import type { SessionValidationResult } from '@openpanel/auth';
import type { QueueProducerHandle, QueueProducers } from './jobs.registry';
import type { Logger } from './logger';
import { createServices, type Services } from './services';
@@ -20,9 +21,11 @@ export type RedisClient = unknown;
export type ServiceClients = unknown;
export type Buffers = 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 resolved session. Type-only, so nothing of `@openpanel/auth` (and
+// nothing of Prisma beneath it) is loaded at runtime — core stays importable
+// with no database, which is what lets `bun test` run offline. The declaration
+// moves here for real when auth dissolves into core (P4/P6).
+export type Session = SessionValidationResult;
/** The env-derived flags core needs. apps/api's config/env.ts is the sole
* reader of process.env; core reads none. */
diff --git a/packages/core/src/index.test.ts b/packages/core/src/index.test.ts
index d8b97f8a2..b12340bd0 100644
--- a/packages/core/src/index.test.ts
+++ b/packages/core/src/index.test.ts
@@ -18,6 +18,20 @@ test('the mount surface is curated', () => {
expect(core.queues).toBeDefined();
});
+// ONE tRPC instance (ADR-009): `initTRPC` is called in rpc/base.ts and
+// nowhere else, so `@openpanel/trpc` has to reach the builder, the router
+// factory and the two injected middleware factories through the barrel.
+// This block shrinks as the 28 routers move into core's modules (P5-P8).
+test('the rpc base is on the barrel, so there is one tRPC instance', () => {
+ expect(core.procedure).toBeDefined();
+ expect(core.middleware).toBeTypeOf('function');
+ expect(core.createTRPCRouter).toBeTypeOf('function');
+ expect(core.createCacheMiddleware).toBeTypeOf('function');
+ expect(core.createRateLimitMiddleware).toBeTypeOf('function');
+ expect(core.createAccessChecks).toBeTypeOf('function');
+ expect(core.TRPCForbiddenError).toBeTypeOf('function');
+});
+
test('a service, a client or a buffer is not on the barrel', () => {
expect(Object.keys(core)).not.toContain('createServices');
});
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 116c9c8bf..a62343b14 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -30,9 +30,44 @@ export {
REQUEST_ID_LOG_FIELD,
} from './logger';
export { dashboardRoutes, opsRoutes, publicApiRoutes } from './rest.routes';
+// The RPC base is on the barrel because it is the seam `@openpanel/trpc`
+// builds its 28 routers on: ONE tRPC instance, mounted by V1's Fastify
+// adapter and by V2's `createTrpcFetchHandler` alike (ADR-009). Those routers
+// move into `modules/<name>/<name>.rpc.ts` with their waves (P5-P8), and this
+// block shrinks back to what apps/api needs when the last one has moved.
+export type {
+ CacheMiddlewareDeps,
+ EnforceRateLimit,
+ Meta,
+ RateLimitOptions,
+ RpcCache,
+ TrpcContext,
+ TrpcContextOptions,
+} from './rpc/base';
+export {
+ createCacheMiddleware,
+ createRateLimitMiddleware,
+ createTRPCRouter,
+ middleware,
+ procedure,
+} from './rpc/base';
+export {
+ TRPCAccessError,
+ TRPCBadRequestError,
+ TRPCForbiddenError,
+ TRPCInternalServerError,
+ TRPCNotFoundError,
+} from './rpc/errors';
export {
createTrpcFetchHandler,
TRPC_ENDPOINT,
} from './rpc/handler';
export type { AppRouter } from './rpc.router';
export { appRouter } from './rpc.router';
+export type {
+ AccessChecks,
+ AccessLookups,
+ OrganizationAccessLike,
+ ProjectAccessLike,
+} from './shared/access';
+export { createAccessChecks } from './shared/access';
diff --git a/packages/core/src/rpc/base.test.ts b/packages/core/src/rpc/base.test.ts
index aac9365c6..1efa03749 100644
--- a/packages/core/src/rpc/base.test.ts
+++ b/packages/core/src/rpc/base.test.ts
@@ -1,7 +1,7 @@
import { expect, test } from 'bun:test';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
-import { stubHttpCtx } from '../../test/rpc-fixtures';
+import { stubHttpCtx, TEST_SESSION } from '../../test/rpc-fixtures';
import type { CookieOptions } from '../shared/cookie';
import * as baseModule from './base';
import {
@@ -115,13 +115,20 @@ test('a signed cookie with no signer throws instead of going out unsigned', asyn
expect(resHeaders.getSetCookie()).toHaveLength(0);
});
-test('resolvedSession is undefined until session() has resolved', async () => {
- const { trpcCtx } = build();
- const ctx = await trpcCtx;
+// V1 resolved the session in a Fastify onRequest hook, before any procedure
+// ran, and 134 call sites read `ctx.session` as a value. The context builder
+// resolves it once for the same reason - and it is what lets `onError` log the
+// session without awaiting.
+test('the session is resolved once, before any procedure runs', async () => {
+ const stub = stubHttpCtx();
+ expect(stub.sessionCalls).toBe(0);
+
+ const ctx = await makeTrpcContext(stub.ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
- expect(ctx.resolvedSession).toBeUndefined();
- await ctx.session();
- expect(ctx.resolvedSession).toEqual({ userId: 'user_1' });
+ expect(stub.sessionCalls).toBe(1);
+ expect(ctx.session).toEqual(TEST_SESSION);
});
test('the HttpCtx is inherited, not copied — services stay lazy', async () => {
diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.ts
index b5ec56a8b..a2e935b38 100644
--- a/packages/core/src/rpc/base.ts
+++ b/packages/core/src/rpc/base.ts
@@ -27,13 +27,41 @@ export interface Meta {
readOnlyMutation?: boolean;
}
-/** What tRPC procedures see. Everything except `resolvedSession` is `HttpCtx`. */
-export interface TrpcContext extends HttpCtx {
+/**
+ * What tRPC procedures see: `HttpCtx` with `session` already resolved, plus
+ * two RPC-only fields.
+ *
+ * `session` is the one field this OVERRIDES. On an HTTP route it is the lazy,
+ * memoized resolver, so a public route pays nothing; on an RPC call it is the
+ * resolved value, because V1 resolved it in a Fastify `onRequest` hook for
+ * every /trpc request and 134 procedure call sites read it as one. Resolving
+ * in the context builder is also what lets `onError` log it without awaiting.
+ *
+ * It is not merely convenience: a middleware that *changed* `session`'s type
+ * would make every standalone middleware (`cacheMiddleware`,
+ * `rateLimitMiddleware`) unusable after it, because tRPC types `.use()`
+ * against the context as overwritten so far.
+ */
+export interface TrpcContext extends Omit<HttpCtx, 'session'> {
+ readonly session: Session;
+ /**
+ * The connection's peer address — the one address a client cannot forge,
+ * and therefore the rate limiter's last-resort fallback when no trusted
+ * header is present. It is NOT `ctx.ip`: that is the *attribution* ip,
+ * which prefers client-forwarded headers and would give every request its
+ * own bucket (ADR-002 "behaviour that must be preserved explicitly" 2).
+ *
+ * `undefined` where the transport does not expose it. Elysia's
+ * `server.requestIP()` is not plumbed through `HttpCtx` yet, so the fetch
+ * mount leaves it unset and the limiter falls back to its shared
+ * `unknown` bucket — fail-closed, which is the documented intent.
+ */
+ readonly remoteAddress: string | undefined;
/**
- * The session if `session()` has already resolved, `undefined` otherwise.
- * `onError` logs it and cannot await, which is the only reason this exists.
+ * `DEMO_USER_ID` is set. Core reads no environment, so the flag arrives on
+ * the context; the demo-mode mutation ban is `enforceAccess`'s to apply.
*/
- readonly resolvedSession: Session | null | undefined;
+ readonly demoMode: boolean;
}
const t = initTRPC
@@ -85,6 +113,8 @@ export interface TrpcContextOptions {
* unsigned cookie the callback would reject.
*/
signCookie?: (value: string) => string;
+ /** `DEMO_USER_ID` is set at the call site. Defaults to off. */
+ demoMode?: boolean;
}
/**
@@ -111,8 +141,6 @@ export async function makeTrpcContext(
);
}
- let resolvedSession: Session | null | undefined;
-
const setCookie = (
name: string,
value: string,
@@ -144,21 +172,16 @@ export async function makeTrpcContext(
// 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,
- },
+ // 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 },
+ // 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.
+ remoteAddress: { value: undefined, enumerable: true },
+ demoMode: { value: options.demoMode ?? false, enumerable: true },
setCookie: { value: setCookie, enumerable: true },
});
return trpcCtx;
@@ -179,9 +202,10 @@ export interface CacheMiddlewareDeps {
/**
* 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.
+ * answer. Preserved as a flag — a thunk because V1 read the env on every
+ * request, not once when the router module loaded.
*/
- serveFromCache: boolean;
+ serveFromCache: boolean | (() => boolean);
}
const middlewareMarker = 'middlewareMarker' as 'middlewareMarker' & {
@@ -214,7 +238,11 @@ export const createCacheMiddleware =
key += JSON.stringify(rawInput).replace(/"/g, "'");
}
const cached = await cache.getJson(key);
- if (cached && serveFromCache) {
+ const serve =
+ typeof serveFromCache === 'function'
+ ? serveFromCache()
+ : serveFromCache;
+ if (cached && serve) {
return {
ok: true,
data: cached,
@@ -246,11 +274,17 @@ export interface RateLimitOptions {
* 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.
+ *
+ * The fingerprint is derived from `headers` and `remoteAddress`. `ip` is in
+ * the signature because ADR-009 names it, but a limiter must never key on it:
+ * it is the attribution address, which prefers client-forwarded headers and
+ * would give every request its own bucket (ADR-002 preserved-behaviour 2).
*/
export type EnforceRateLimit = (
args: RateLimitOptions & {
headers: Headers;
ip: string;
+ remoteAddress: string | undefined;
logger: Logger;
/** tRPC procedure path - blocks are scoped to it. */
path: string;
@@ -268,6 +302,7 @@ export const createRateLimitMiddleware =
await enforceRateLimit({
headers: ctx.headers,
ip: ctx.ip,
+ remoteAddress: ctx.remoteAddress,
logger: ctx.logger,
path,
...options,
diff --git a/packages/core/src/rpc/handler.test.ts b/packages/core/src/rpc/handler.test.ts
index d3dc30407..e3f0fdb2d 100644
--- a/packages/core/src/rpc/handler.test.ts
+++ b/packages/core/src/rpc/handler.test.ts
@@ -1,7 +1,11 @@
import { expect, test } from 'bun:test';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
-import { capturingLogger, stubHttpCtx } from '../../test/rpc-fixtures';
+import {
+ capturingLogger,
+ stubHttpCtx,
+ TEST_SESSION,
+} from '../../test/rpc-fixtures';
import type { CookieOptions } from '../shared/cookie';
import { createTRPCRouter, makeTrpcContext, procedure } from './base';
import { TRPCForbiddenError } from './errors';
@@ -105,7 +109,6 @@ test('the request logger is preferred and the resolved session is carried', asyn
const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
cookieOptions: COOKIE_OPTIONS,
});
- await trpcCtx.session();
createTrpcOnError(bootLogger)(report({ ctx: trpcCtx }));
@@ -113,7 +116,7 @@ test('the request logger is preferred and the resolved session is carried', asyn
expect(requestLogger.lines).toHaveLength(1);
expect(
(requestLogger.lines[0]?.payload as { session: unknown }).session
- ).toEqual({ userId: 'user_1' });
+ ).toEqual(TEST_SESSION);
});
test('a ctx-less failure (createContext threw) logs through the boot logger', () => {
diff --git a/packages/core/src/rpc/handler.ts b/packages/core/src/rpc/handler.ts
index 21d80eeb5..8939e67fc 100644
--- a/packages/core/src/rpc/handler.ts
+++ b/packages/core/src/rpc/handler.ts
@@ -61,7 +61,7 @@ export function createTrpcOnError(bootLogger: Logger) {
path: report.path,
input: report.input,
type: report.type,
- session: report.ctx?.resolvedSession,
+ session: report.ctx?.session,
ip,
ipHeader: header,
userAgent: report.req.headers.get('user-agent'),
diff --git a/packages/core/src/shared/access.ts b/packages/core/src/shared/access.ts
new file mode 100644
index 000000000..d58fa99a0
--- /dev/null
+++ b/packages/core/src/shared/access.ts
@@ -0,0 +1,177 @@
+// The permission ladder (ADR-007 layout: `shared/access`).
+//
+// Ported verbatim from packages/trpc/src/access.ts — the rules, the fail-closed
+// ordering and the messages are unchanged, and ADR-011 invariants 5 and 6 bind
+// them. What changed is the shape: the four data lookups arrive as an injected
+// `AccessLookups` instead of being imported from `@openpanel/db`.
+//
+// That injection is not decoration. Core must stay importable without a
+// database — `bun test` loads this package with no DATABASE_URL and no Prisma
+// client — and it is the same seam `createCacheMiddleware` and
+// `createRateLimitMiddleware` already use in rpc/base.ts. `@openpanel/trpc`
+// binds it to the real services; a test binds it to two functions.
+
+import { TRPCForbiddenError } from '../rpc/errors';
+
+/** What a project access row has to expose for the ladder to read it. */
+export interface ProjectAccessLike {
+ level: string;
+}
+
+export interface OrganizationAccessLike {
+ role: string;
+}
+
+/**
+ * The four reads the ladder needs. Deliberately the *service* functions, not a
+ * Prisma client: `getProjectAccess` carries the 5-minute Redis cache and the
+ * fail-closed swallow (ADR-011 invariant 5, 7), and reimplementing it here
+ * would be a second, diverging copy of the rule this file exists to enforce.
+ */
+export interface AccessLookups<
+ TProjectAccess extends ProjectAccessLike = ProjectAccessLike,
+ TOrganizationAccess extends OrganizationAccessLike = OrganizationAccessLike,
+> {
+ getProjectAccess(args: {
+ userId: string;
+ projectId: string;
+ }): Promise<TProjectAccess | null>;
+ /** ADR-011 invariant 6: level in {write, admin}; admin stays a superset. */
+ canWriteProject(access: TProjectAccess | null): boolean;
+ getOrganizationAccess(args: {
+ userId: string;
+ organizationId: string;
+ }): Promise<TOrganizationAccess | null>;
+ getProjectById(
+ projectId: string
+ ): Promise<{ organizationId: string | null } | null>;
+}
+
+export interface AccessChecks<
+ TProjectAccess extends ProjectAccessLike = ProjectAccessLike,
+ TOrganizationAccess extends OrganizationAccessLike = OrganizationAccessLike,
+> {
+ requireProjectAccess(args: {
+ userId: string;
+ projectId: string;
+ level: 'read' | 'write';
+ }): Promise<TProjectAccess>;
+ requireOrganizationAdmin(args: {
+ userId: string;
+ organizationId: string;
+ message?: string;
+ }): Promise<TOrganizationAccess>;
+ requireProjectAdmin(args: {
+ userId: string;
+ projectId: string;
+ message?: string;
+ }): Promise<TOrganizationAccess>;
+}
+
+const ORGANIZATION_ADMIN_ROLE = 'org:admin';
+
+/**
+ * The permission ladder.
+ *
+ * Two independent controls, each with one job:
+ *
+ * - ADMIN is the organization role (`member.role === 'org:admin'`). It gates
+ * destruction and billing.
+ * - WRITE is the per-project access level. It gates every mutation. `admin`
+ * level counts as a superset of `write`.
+ * - READ is the floor: membership of the project, which is what queries need.
+ *
+ * They are deliberately separate. Project levels were unenforced for so long
+ * that the value stored on most rows was never chosen by anyone, so hanging
+ * destructive operations off the org role avoids retroactively giving meaning
+ * to that data.
+ */
+export function createAccessChecks<
+ TProjectAccess extends ProjectAccessLike,
+ TOrganizationAccess extends OrganizationAccessLike,
+>(
+ lookups: AccessLookups<TProjectAccess, TOrganizationAccess>
+): AccessChecks<TProjectAccess, TOrganizationAccess> {
+ /**
+ * Assert the caller may act on a project at the given level.
+ *
+ * Prefer this over calling `getProjectAccess` and testing truthiness: a
+ * truthy result only proves membership, which is how a read-only member
+ * could delete reports and publish private analytics (GHSA-f9rx-pxgw-c6rg).
+ */
+ async function requireProjectAccess({
+ userId,
+ projectId,
+ level,
+ }: {
+ userId: string;
+ projectId: string;
+ level: 'read' | 'write';
+ }): Promise<TProjectAccess> {
+ const access = await lookups.getProjectAccess({ userId, projectId });
+
+ if (!access) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+
+ if (level === 'write' && !lookups.canWriteProject(access)) {
+ throw new TRPCForbiddenError('You have read-only access to this project');
+ }
+
+ return access;
+ }
+
+ /** Assert the caller is an admin of the organization. */
+ async function requireOrganizationAdmin({
+ userId,
+ organizationId,
+ message = 'Only organization admins can do this',
+ }: {
+ userId: string;
+ organizationId: string;
+ message?: string;
+ }): Promise<TOrganizationAccess> {
+ const access = await lookups.getOrganizationAccess({
+ userId,
+ organizationId,
+ });
+
+ if (access?.role !== ORGANIZATION_ADMIN_ROLE) {
+ throw new TRPCForbiddenError(message);
+ }
+
+ return access;
+ }
+
+ /**
+ * Assert the caller is an admin of the organization that owns a project, for
+ * the destructive procedures that only receive a `projectId`.
+ */
+ async function requireProjectAdmin({
+ userId,
+ projectId,
+ message,
+ }: {
+ userId: string;
+ projectId: string;
+ message?: string;
+ }): Promise<TOrganizationAccess> {
+ const project = await lookups.getProjectById(projectId);
+
+ if (!project?.organizationId) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+
+ return await requireOrganizationAdmin({
+ userId,
+ organizationId: project.organizationId,
+ message,
+ });
+ }
+
+ return {
+ requireProjectAccess,
+ requireOrganizationAdmin,
+ requireProjectAdmin,
+ };
+}
diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.ts
index 2e6107d29..9ebffdfd6 100644
--- a/packages/core/test/rpc-fixtures.ts
+++ b/packages/core/test/rpc-fixtures.ts
@@ -6,6 +6,7 @@ import {
createCtx,
extendCtx,
type HttpCtx,
+ type Session,
} from '../src/context';
import { createRecordingProducers } from '../src/jobs/testing';
import { queues } from '../src/jobs.registry';
@@ -44,6 +45,29 @@ export function capturingLogger(lines: LoggedLine[] = []): CapturedLogger {
export const TEST_REQUEST_ID = 'req_abcdefghijklmnopqrstu';
+const TEST_EPOCH = new Date('2026-09-03T00:00:00.000Z');
+
+/** A real `SessionValidationResult`, so an assertion on `ctx.session` types. */
+export const TEST_SESSION: Session = {
+ session: {
+ id: 'sess_1',
+ userId: 'user_1',
+ createdAt: TEST_EPOCH,
+ updatedAt: TEST_EPOCH,
+ expiresAt: TEST_EPOCH,
+ },
+ user: {
+ id: 'user_1',
+ email: '[email protected]',
+ firstName: null,
+ lastName: null,
+ createdAt: TEST_EPOCH,
+ updatedAt: TEST_EPOCH,
+ deletedAt: null,
+ },
+ userId: 'user_1',
+};
+
export interface HttpCtxStub {
ctx: HttpCtx;
logger: CapturedLogger;
@@ -54,7 +78,7 @@ export interface HttpCtxStub {
export function stubHttpCtx(
overrides: Partial<HttpCtx> & { logger?: CapturedLogger } = {},
- session: unknown = { userId: 'user_1' }
+ session: unknown = TEST_SESSION
): HttpCtxStub {
const logger = overrides.logger ?? capturingLogger();
const cookies: HttpCtxStub['cookies'] = [];
@@ -79,7 +103,7 @@ export function stubHttpCtx(
cookies: { get: () => undefined },
session: () => {
stub.sessionCalls++;
- return Promise.resolve(session);
+ return Promise.resolve(session as Session | null);
},
setCookie: (name: string, value: string, options?: unknown) => {
cookies.push({ name, value, options });
diff --git a/packages/db/src/services/share.service.ts b/packages/db/src/services/share.service.ts
index 2e936991d..2764aaa32 100644
--- a/packages/db/src/services/share.service.ts
+++ b/packages/db/src/services/share.service.ts
@@ -122,7 +122,9 @@ export async function validateShareAccess(
shareId: string,
reportId: string,
ctx: {
- cookies: Record<string, string | undefined>;
+ // Read by name only, so a transport that has no cookie record (Elysia's
+ // proxy, core's CookieJar) can satisfy this without materialising one.
+ cookies: { get(name: string): string | undefined };
session?: { userId?: string | null };
},
): Promise<{ projectId: string; isValid: boolean }> {
@@ -159,7 +161,7 @@ export async function validateShareAccess(
}
// If password is set, require cookie OR member access
- const hasCookie = !!ctx.cookies[`shared-dashboard-${shareId}`];
+ const hasCookie = !!ctx.cookies.get(`shared-dashboard-${shareId}`);
const hasMemberAccess =
ctx.session?.userId &&
(await getProjectAccess({
@@ -197,7 +199,7 @@ export async function validateShareAccess(
}
// If password is set, require cookie OR member access
- const hasCookie = !!ctx.cookies[`shared-report-${shareId}`];
+ const hasCookie = !!ctx.cookies.get(`shared-report-${shareId}`);
const hasMemberAccess =
ctx.session?.userId &&
(await getProjectAccess({
@@ -219,7 +221,9 @@ export async function validateOverviewShareAccess(
shareId: string | undefined,
projectId: string,
ctx: {
- cookies: Record<string, string | undefined>;
+ // Read by name only, so a transport that has no cookie record (Elysia's
+ // proxy, core's CookieJar) can satisfy this without materialising one.
+ cookies: { get(name: string): string | undefined };
session?: { userId?: string | null };
},
): Promise<{ isValid: boolean }> {
@@ -246,7 +250,7 @@ export async function validateOverviewShareAccess(
}
// If password is set, require cookie OR member access
- const hasCookie = !!ctx.cookies[`shared-overview-${shareId}`];
+ const hasCookie = !!ctx.cookies.get(`shared-overview-${shareId}`);
const hasMemberAccess =
ctx.session?.userId &&
(await getProjectAccess({
diff --git a/packages/payments/src/polar.ts b/packages/payments/src/polar.ts
index 89da90b87..5bc6b1f66 100644
--- a/packages/payments/src/polar.ts
+++ b/packages/payments/src/polar.ts
@@ -57,7 +57,7 @@ export async function createCheckout({
lastName: string | null;
email: string;
};
- ipAddress: string;
+ ipAddress: string | undefined;
}) {
return polar.checkouts.create({
// productPriceId: priceId,
diff --git a/packages/trpc/package.json b/packages/trpc/package.json
index 0e841d803..bb3dfc7d4 100644
--- a/packages/trpc/package.json
+++ b/packages/trpc/package.json
@@ -13,14 +13,15 @@
"@openpanel/auth": "workspace:^",
"@openpanel/common": "workspace:*",
"@openpanel/constants": "workspace:*",
+ "@openpanel/core": "workspace:*",
"@openpanel/db": "workspace:*",
"@openpanel/email": "workspace:*",
"@openpanel/integrations": "workspace:^",
"@openpanel/js-runtime": "workspace:*",
"@openpanel/payments": "workspace:^",
+ "@openpanel/queue": "workspace:*",
"@openpanel/redis": "workspace:*",
"@openpanel/validation": "workspace:*",
- "@openpanel/queue": "workspace:*",
"@trpc/client": "^11.17.0",
"@trpc/server": "^11.17.0",
"date-fns": "^3.3.1",
diff --git a/packages/trpc/src/access.ts b/packages/trpc/src/access.ts
index 215ae9837..c519320f8 100644
--- a/packages/trpc/src/access.ts
+++ b/packages/trpc/src/access.ts
@@ -1,106 +1,31 @@
+// The permission ladder now lives in @openpanel/core (`shared/access`); this
+// file binds it to the real `@openpanel/db` lookups and keeps the specifier
+// V1's routers and `apps/api` already import.
+//
+// The ladder itself — the rules, the messages, GHSA-f9rx-pxgw-c6rg's fix — is
+// core's and single-sourced there.
+
+import { createAccessChecks } from '@openpanel/core';
import {
canWriteProject,
getOrganizationAccess,
getProjectAccess,
getProjectById,
} from '@openpanel/db';
-import { TRPCForbiddenError } from './errors';
export {
+ getClientAccess,
getOrganizationAccess,
getProjectAccess,
- getClientAccess,
} from '@openpanel/db';
-/**
- * The permission ladder.
- *
- * Two independent controls, each with one job:
- *
- * - ADMIN is the organization role (`member.role === 'org:admin'`). It gates
- * destruction and billing.
- * - WRITE is the per-project access level. It gates every mutation. `admin`
- * level counts as a superset of `write`.
- * - READ is the floor: membership of the project, which is what queries need.
- *
- * They are deliberately separate. Project levels were unenforced for so long
- * that the value stored on most rows was never chosen by anyone, so hanging
- * destructive operations off the org role avoids retroactively giving meaning
- * to that data.
- */
-
-/**
- * Assert the caller may act on a project at the given level.
- *
- * Prefer this over calling `getProjectAccess` and testing truthiness: a truthy
- * result only proves membership, which is how a read-only member could delete
- * reports and publish private analytics (GHSA-f9rx-pxgw-c6rg).
- */
-export async function requireProjectAccess({
- userId,
- projectId,
- level,
-}: {
- userId: string;
- projectId: string;
- level: 'read' | 'write';
-}) {
- const access = await getProjectAccess({ userId, projectId });
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
- if (level === 'write' && !canWriteProject(access)) {
- throw new TRPCForbiddenError(
- 'You have read-only access to this project',
- );
- }
-
- return access;
-}
-
-/** Assert the caller is an admin of the organization. */
-export async function requireOrganizationAdmin({
- userId,
- organizationId,
- message = 'Only organization admins can do this',
-}: {
- userId: string;
- organizationId: string;
- message?: string;
-}) {
- const access = await getOrganizationAccess({ userId, organizationId });
-
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError(message);
- }
-
- return access;
-}
-
-/**
- * Assert the caller is an admin of the organization that owns a project, for
- * the destructive procedures that only receive a `projectId`.
- */
-export async function requireProjectAdmin({
- userId,
- projectId,
- message,
-}: {
- userId: string;
- projectId: string;
- message?: string;
-}) {
- const project = await getProjectById(projectId);
-
- if (!project?.organizationId) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
+const checks = createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+});
- return requireOrganizationAdmin({
- userId,
- organizationId: project.organizationId,
- message,
- });
-}
+export const requireProjectAccess = checks.requireProjectAccess;
+export const requireOrganizationAdmin = checks.requireOrganizationAdmin;
+export const requireProjectAdmin = checks.requireProjectAdmin;
diff --git a/packages/trpc/src/errors.ts b/packages/trpc/src/errors.ts
index 785b12ca5..3217bbd29 100644
--- a/packages/trpc/src/errors.ts
+++ b/packages/trpc/src/errors.ts
@@ -1,31 +1,10 @@
-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 });
- }
-}
+// One definition, in @openpanel/core (`rpc/errors`). Re-exported here so V1's
+// routers keep their specifier until they move into core's modules (P5-P8).
+
+export {
+ TRPCAccessError,
+ TRPCBadRequestError,
+ TRPCForbiddenError,
+ TRPCInternalServerError,
+ TRPCNotFoundError,
+} from '@openpanel/core';
diff --git a/packages/trpc/src/rate-limit.ts b/packages/trpc/src/rate-limit.ts
index 10dd207d1..0a38869ee 100644
--- a/packages/trpc/src/rate-limit.ts
+++ b/packages/trpc/src/rate-limit.ts
@@ -1,10 +1,7 @@
import { getTrustedIpFromHeaders } from '@openpanel/common/server/get-client-ip';
+import type { EnforceRateLimit } from '@openpanel/core';
import { LRUCache, getRedisCache } from '@openpanel/redis';
import { TRPCError } from '@trpc/server';
-import type { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
-
-/** `fastify` is not a direct dependency here, so borrow the type tRPC exposes. */
-type FastifyRequest = CreateFastifyContextOptions['req'];
const SECOND = 1000;
const MINUTE = 60 * SECOND;
@@ -35,12 +32,6 @@ const MAX_STRIKES = Math.ceil(Math.log2(BLOCK_MAX_MS / BLOCK_BASE_MS)) + 1;
*/
const ESCALATION_COOLDOWN_MS = MINUTE;
-export interface RateLimitOptions {
- /** Requests allowed per window before the first block. */
- max: number;
- windowMs: number;
-}
-
/**
* Per-process fallback used only while Redis is unreachable. Without it a Redis
* blip would leave the sign-in endpoint completely unthrottled.
@@ -72,13 +63,15 @@ function formatDuration(ms: number): string {
/**
* The identity we rate limit on. Deliberately ignores the client-forwarded IP
* headers that `getClientIpFromHeaders` prefers - those are attacker-controlled
- * and would make every request its own bucket.
+ * and would make every request its own bucket. `ctx.ip` is exactly those
+ * headers, which is why this takes the raw `Headers` and the connection's peer
+ * address instead of anything the context already resolved.
*/
-export function getRateLimitIdentity(req: FastifyRequest) {
- const { ip, header } = getTrustedIpFromHeaders(
- req.headers,
- req.socket?.remoteAddress,
- );
+export function getRateLimitIdentity(
+ headers: Headers,
+ remoteAddress: string | undefined,
+) {
+ const { ip, header } = getTrustedIpFromHeaders(headers, remoteAddress);
return {
// Everything we cannot identify shares one bucket. Fail closed: an edge
@@ -134,17 +127,15 @@ async function escalate(strikeKey: string, blockKey: string, cooldownKey: string
* SELECT LogAttributes['ip'], count() FROM otel_logs
* WHERE Body = 'rate limit blocked' GROUP BY 1 ORDER BY 2 DESC
*/
-export async function enforceRateLimit({
- req,
+export const enforceRateLimit: EnforceRateLimit = async ({
+ headers,
+ remoteAddress,
+ logger,
path,
max,
windowMs,
-}: RateLimitOptions & {
- req: FastifyRequest;
- /** tRPC procedure path - blocks are scoped to it. */
- path: string;
-}): Promise<void> {
- const { fingerprint, ipHeader } = getRateLimitIdentity(req);
+}) => {
+ const { fingerprint, ipHeader } = getRateLimitIdentity(headers, remoteAddress);
const counterKey = key('count', path, fingerprint);
const strikeKey = key('strike', path, fingerprint);
@@ -155,12 +146,12 @@ export async function enforceRateLimit({
message: string,
payload: { strikes: number; blockMs: number; hits?: number },
) =>
- req.log?.warn(
+ logger.warn(
{
ip: fingerprint,
ipHeader,
path,
- userAgent: req.headers['user-agent'],
+ userAgent: headers.get('user-agent') ?? undefined,
strikes: payload.strikes,
blockedForSeconds: Math.ceil(payload.blockMs / SECOND),
blockedUntil: new Date(Date.now() + payload.blockMs).toISOString(),
@@ -195,7 +186,7 @@ export async function enforceRateLimit({
await redis.pexpire(counterKey, windowMs);
}
} catch (error) {
- req.log?.error({ err: error, path }, 'rate limit store unavailable');
+ logger.error({ err: error, path }, 'rate limit store unavailable');
const fallbackHits = (fallbackCounters.get(counterKey) ?? 0) + 1;
fallbackCounters.set(counterKey, fallbackHits, { ttl: windowMs });
if (fallbackHits > max) {
@@ -224,7 +215,7 @@ export async function enforceRateLimit({
escalated = await escalate(strikeKey, blockKey, cooldownKey);
}
} catch (error) {
- req.log?.error({ err: error, path }, 'rate limit store unavailable');
+ logger.error({ err: error, path }, 'rate limit store unavailable');
}
if (!escalated) {
@@ -243,14 +234,14 @@ export async function enforceRateLimit({
// Start the next window clean so the block, not a stale counter, decides.
await getRedisCache().del(counterKey);
} catch (error) {
- req.log?.error({ err: error, path }, 'rate limit store unavailable');
+ logger.error({ err: error, path }, 'rate limit store unavailable');
throw tooManyRequests(windowMs);
}
log('rate limit blocked', { ...escalated, hits });
throw tooManyRequests(escalated.blockMs);
}
-}
+};
export const __testing = {
BLOCK_BASE_MS,
diff --git a/packages/trpc/src/routers/auth.ts b/packages/trpc/src/routers/auth.ts
index 5f7dec314..715d82af7 100644
--- a/packages/trpc/src/routers/auth.ts
+++ b/packages/trpc/src/routers/auth.ts
@@ -21,6 +21,7 @@ import {
verifyTotpCode,
} from '@openpanel/auth';
import { generateSecureId } from '@openpanel/common/server';
+import type { Logger } from '@openpanel/core';
import {
connectUserToOrganization,
db,
@@ -63,7 +64,7 @@ const zProvider = z.enum(['email', 'google', 'github']);
async function consumeInviteForUser(
userId: string,
inviteId: string,
- log: { error: (obj: unknown, msg?: string) => void }
+ log: Pick<Logger, 'error'>
) {
try {
const user = await db.user.findUniqueOrThrow({ where: { id: userId } });
@@ -265,7 +266,7 @@ export const authRouter = createTRPCRouter({
setLastAuthProviderCookie(ctx.setCookie, 'email');
if (input.inviteId) {
- await consumeInviteForUser(user.id, input.inviteId, ctx.req.log);
+ await consumeInviteForUser(user.id, input.inviteId, ctx.logger);
}
return {
@@ -282,7 +283,7 @@ export const authRouter = createTRPCRouter({
)
.input(z.object({ code: zTotpOrRecoveryCode }))
.mutation(async ({ input, ctx }) => {
- const challengeId = ctx.cookies[TWO_FACTOR_COOKIE];
+ const challengeId = ctx.cookies.get(TWO_FACTOR_COOKIE);
if (!challengeId) {
throw new TRPCAccessError('No active two-factor challenge');
}
@@ -340,9 +341,9 @@ export const authRouter = createTRPCRouter({
setSessionTokenCookie(ctx.setCookie, token, session.expiresAt);
setLastAuthProviderCookie(ctx.setCookie, 'email');
- const inviteId = ctx.cookies[INVITE_COOKIE];
+ const inviteId = ctx.cookies.get(INVITE_COOKIE);
if (inviteId) {
- await consumeInviteForUser(challenge.userId, inviteId, ctx.req.log);
+ await consumeInviteForUser(challenge.userId, inviteId, ctx.logger);
ctx.setCookie(INVITE_COOKIE, '', { maxAge: 0 });
}
@@ -590,11 +591,11 @@ export const authRouter = createTRPCRouter({
}),
extendSession: publicProcedure.mutation(async ({ ctx }) => {
- if (!(ctx.session.session && ctx.cookies.session)) {
+ const token = ctx.cookies.get('session');
+ if (!(ctx.session.session && token)) {
return { extended: false };
}
- const token = ctx.cookies.session;
const session = await validateSessionToken(token);
if (session.session) {
diff --git a/packages/trpc/src/routers/share.test.ts b/packages/trpc/src/routers/share.test.ts
index 1f22ecff3..26ddade8d 100644
--- a/packages/trpc/src/routers/share.test.ts
+++ b/packages/trpc/src/routers/share.test.ts
@@ -45,11 +45,10 @@ const REPORT = {
/** An unauthenticated caller: no session, no unlock cookie. */
const anonCaller = (cookies: Record<string, string> = {}) =>
shareRouter.createCaller({
- req: { log: { info: vi.fn(), error: vi.fn() } },
- res: {},
+ logger: { info: vi.fn(), error: vi.fn() },
session: null,
setCookie: vi.fn(),
- cookies,
+ cookies: { get: (name: string) => cookies[name] },
} as never);
const privatePasswordProtectedShare = {
diff --git a/packages/trpc/src/routers/share.ts b/packages/trpc/src/routers/share.ts
index df122efe3..de7b99216 100644
--- a/packages/trpc/src/routers/share.ts
+++ b/packages/trpc/src/routers/share.ts
@@ -75,7 +75,7 @@ export const shareRouter = createTRPCRouter({
throw new TRPCNotFoundError('Share not found');
}
- const hasAccess = !!ctx.cookies[`shared-overview-${share.id}`];
+ const hasAccess = !!ctx.cookies.get(`shared-overview-${share.id}`);
if (share.password && !hasAccess) {
return lockedShare(share.id, share.organization, share.project);
}
@@ -160,7 +160,7 @@ export const shareRouter = createTRPCRouter({
throw new TRPCNotFoundError('Dashboard share not found');
}
- const hasAccess = !!ctx.cookies[`shared-dashboard-${share.id}`];
+ const hasAccess = !!ctx.cookies.get(`shared-dashboard-${share.id}`);
if (share.password && !hasAccess) {
return lockedShare(share.id, share.organization, share.project);
}
@@ -254,7 +254,7 @@ export const shareRouter = createTRPCRouter({
}
// Check password access
- const hasAccess = !!ctx.cookies[`shared-dashboard-${share.id}`];
+ const hasAccess = !!ctx.cookies.get(`shared-dashboard-${share.id}`);
if (share.password && !hasAccess) {
throw new TRPCAccessError('Password required');
}
@@ -283,7 +283,7 @@ export const shareRouter = createTRPCRouter({
throw new TRPCNotFoundError('Report share not found');
}
- const hasAccess = !!ctx.cookies[`shared-report-${share.id}`];
+ const hasAccess = !!ctx.cookies.get(`shared-report-${share.id}`);
if (share.password && !hasAccess) {
return lockedShare(share.id, share.organization, share.project);
}
diff --git a/packages/trpc/src/routers/subscription.ts b/packages/trpc/src/routers/subscription.ts
index 7dad05686..979999c70 100644
--- a/packages/trpc/src/routers/subscription.ts
+++ b/packages/trpc/src/routers/subscription.ts
@@ -105,7 +105,7 @@ export const subscriptionRouter = createTRPCRouter({
productId: input.productId,
organizationId: input.organizationId,
user,
- ipAddress: ctx.req.ip,
+ ipAddress: ctx.remoteAddress,
});
return {
diff --git a/packages/trpc/src/trpc.ts b/packages/trpc/src/trpc.ts
index 3229fe5e9..7c03f46cb 100644
--- a/packages/trpc/src/trpc.ts
+++ b/packages/trpc/src/trpc.ts
@@ -1,22 +1,84 @@
-import { TRPCError, initTRPC } from '@trpc/server';
-import type { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
-import { has } from 'ramda';
-import superjson from 'superjson';
-import { ZodError, z } from 'zod';
+// V1's tRPC surface, rebased onto @openpanel/core's RPC base (ADR-009).
+//
+// There is exactly ONE tRPC instance in the repo now: `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`.
+//
+// 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.
import { COOKIE_OPTIONS, type SessionValidationResult } from '@openpanel/auth';
+import {
+ type Ctx,
+ createCacheMiddleware,
+ createRateLimitMiddleware,
+ middleware,
+ procedure,
+ type QueueProducers,
+ type RpcCache,
+ type TrpcContext,
+} from '@openpanel/core';
import { runWithAlsSession } from '@openpanel/db';
import { getRedisCache } from '@openpanel/redis';
-import type { ISetCookie } from '@openpanel/validation';
-import { type RateLimitOptions, enforceRateLimit } from './rate-limit';
+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';
+import { enforceRateLimit } from './rate-limit';
+
+export type { Meta } from '@openpanel/core';
+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;
-export async function createContext({ req, res }: CreateFastifyContextOptions) {
- const cookies = (req as any).cookies as Record<string, string | undefined>;
- const setCookie: ISetCookie = (key, value, options) => {
- // @ts-ignore
- res.setCookie(key, value, {
+/**
+ * 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,
@@ -24,50 +86,83 @@ export async function createContext({ req, res }: CreateFastifyContextOptions) {
};
if (process.env.NODE_ENV !== 'production') {
- await new Promise((res) =>
- setTimeout(() => res(1), Math.min(Math.random() * 500, 200)),
+ await new Promise((resolve) =>
+ setTimeout(
+ () => resolve(1),
+ Math.min(
+ Math.random() * ARTIFICIAL_LATENCY_SPREAD_MS,
+ ARTIFICIAL_LATENCY_MAX_MS
+ )
+ )
);
}
+ const cookies = request.cookies;
+
return {
- req,
- res,
- session: (req as any).session as SessionValidationResult,
- // we do not get types for `setCookie` from fastify
- // so define it here and be safe in routers
+ ...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,
- cookies,
+ // 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,
};
}
-export type Context = Awaited<ReturnType<typeof createContext>>;
/**
- * Per-procedure metadata consulted by `enforceAccess`.
+ * The `Ctx` half of the context under V1.
*
- * 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.
+ * `db`/`ch`/`redis`/`clients`/`buffers` are core's `unknown` stubs until P3-P8
+ * wire the real clients, and V1's routers reach for their own singletons
+ * regardless. `queues` throws rather than returning an empty object: a V1
+ * router that tried to enqueue through core would otherwise silently do
+ * nothing.
*/
-export interface Meta {
- /** This mutation does not change project state; read access is enough. */
- readOnlyMutation?: boolean;
+function v1CtxScope(req: CreateFastifyContextOptions['req']): Ctx {
+ return {
+ db: undefined,
+ ch: undefined,
+ redis: undefined,
+ clients: undefined,
+ buffers: undefined,
+ logger: req.log,
+ queues: NOT_WIRED_QUEUES,
+ services: {},
+ requestId: String(req.id),
+ };
}
-const t = initTRPC.context<Context>().meta<Meta>().create({
- transformer: superjson,
- errorFormatter({ shape, error }) {
- return {
- ...shape,
- data: {
- ...shape.data,
- zodError:
- error.cause instanceof ZodError ? z.flattenError(error.cause) : null,
- },
- };
+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 enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
+/** 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' });
}
@@ -88,62 +183,55 @@ const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
});
// Only used on protected routes
-const enforceAccess = t.middleware(async ({ ctx, next, type, meta, getRawInput }) => {
- const sessionId = ctx.session?.session?.id ?? null;
- return runWithAlsSession(sessionId, async () => {
- const rawInput = await getRawInput();
- if (type === 'mutation' && process.env.DEMO_USER_ID) {
- throw new TRPCForbiddenError('You are not allowed to do this in demo mode');
- }
-
- if (has('projectId', rawInput)) {
- // Fails closed: any procedure that takes a top-level projectId requires
- // write access to mutate, including ones added later. Procedures that
- // resolve the project from a reportId/dashboardId/etc. are invisible to
- // this check and call requireProjectAccess in the handler instead.
- const needsWrite = type === 'mutation' && !meta?.readOnlyMutation;
-
- await requireProjectAccess({
- userId: ctx.session.userId!,
- projectId: rawInput.projectId as string,
- level: needsWrite ? 'write' : 'read',
- });
- }
+const enforceAccess = middleware(
+ async ({ ctx, next, type, meta, getRawInput }) => {
+ const sessionId = ctx.session?.session?.id ?? null;
+ return runWithAlsSession(sessionId, async () => {
+ const rawInput = await getRawInput();
+ if (type === 'mutation' && ctx.demoMode) {
+ throw new TRPCForbiddenError(
+ 'You are not allowed to do this in demo mode'
+ );
+ }
- if (has('organizationId', rawInput)) {
- const access = await getOrganizationAccess({
- userId: ctx.session.userId!,
- organizationId: rawInput.organizationId as string,
- });
+ if (has('projectId', rawInput)) {
+ // Fails closed: any procedure that takes a top-level projectId requires
+ // write access to mutate, including ones added later. Procedures that
+ // resolve the project from a reportId/dashboardId/etc. are invisible to
+ // this check and call requireProjectAccess in the handler instead.
+ const needsWrite = type === 'mutation' && !meta?.readOnlyMutation;
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this organization');
+ await requireProjectAccess({
+ userId: ctx.session.userId!,
+ projectId: rawInput.projectId as string,
+ level: needsWrite ? 'write' : 'read',
+ });
}
- }
- return next();
- });
-});
+ if (has('organizationId', rawInput)) {
+ const access = await getOrganizationAccess({
+ userId: ctx.session.userId!,
+ organizationId: rawInput.organizationId as string,
+ });
-export const createTRPCRouter = t.router;
+ if (!access) {
+ throw new TRPCForbiddenError(
+ 'You do not have access to this organization'
+ );
+ }
+ }
-/**
- * Throttle a procedure by client IP, with an exponentially growing lockout for
- * repeat offenders. See `./rate-limit` for the escalation rules and for the log
- * line (`rate limit blocked`) that carries the offending IP.
- */
-export const rateLimitMiddleware = (options: RateLimitOptions) =>
- t.middleware(async ({ ctx, next, path }) => {
- await enforceRateLimit({ req: ctx.req, path, ...options });
- return next();
- });
+ return next();
+ });
+ }
+);
-const loggerMiddleware = t.middleware(
+const loggerMiddleware = middleware(
async ({ ctx, next, getRawInput, path, input, type }) => {
const rawInput = await getRawInput();
// Only log mutations
if (type === 'mutation') {
- ctx.req.log.info(
+ ctx.logger.info(
{
path,
rawInput,
@@ -156,24 +244,31 @@ const loggerMiddleware = t.middleware(
? rawInput.projectId
: undefined,
},
- 'TRPC mutation',
+ 'TRPC mutation'
);
}
return next();
- },
+ }
);
-const sessionScopeMiddleware = t.middleware(async ({ ctx, next }) => {
+const sessionScopeMiddleware = middleware(async ({ ctx, next }) => {
const sessionId = ctx.session?.session?.id ?? null;
return runWithAlsSession(sessionId, async () => {
return next();
});
});
-export const publicProcedure = t.procedure
+/**
+ * Throttle a procedure by client IP, with an exponentially growing lockout for
+ * repeat offenders. See `./rate-limit` for the escalation rules and for the log
+ * line (`rate limit blocked`) that carries the offending IP.
+ */
+export const rateLimitMiddleware = createRateLimitMiddleware(enforceRateLimit);
+
+export const publicProcedure = procedure
.use(loggerMiddleware)
.use(sessionScopeMiddleware);
-export const protectedProcedure = t.procedure
+export const protectedProcedure = procedure
.use(enforceUserIsAuthed)
.use(enforceAccess)
.use(loggerMiddleware)
@@ -181,51 +276,24 @@ export const protectedProcedure = t.procedure
// Authenticated but WITHOUT the org/project membership check. Use for endpoints
// that must answer for any logged-in user (e.g. checking your own access to an
// org you may not belong to) and return null instead of throwing.
-export const protectedProcedureWithoutAccess = t.procedure
+export const protectedProcedureWithoutAccess = procedure
.use(enforceUserIsAuthed)
.use(loggerMiddleware)
.use(sessionScopeMiddleware);
-const middlewareMarker = 'middlewareMarker' as 'middlewareMarker' & {
- __brand: 'middlewareMarker';
+/**
+ * The Redis handle is resolved per call, not at import: `getRedisCache()` opens
+ * a connection, and V1 did not open one because a router module was loaded.
+ */
+const rpcCache: RpcCache = {
+ getJson: (key) => getRedisCache().getJson(key),
+ setJson: (key, expireInSec, value) =>
+ getRedisCache().setJson(key, expireInSec, value),
};
-export const cacheMiddleware = (
- 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 cache = await getRedisCache().getJson(key);
- if (cache && process.env.NODE_ENV === 'production') {
- return {
- ok: true,
- data: cache,
- ctx,
- marker: middlewareMarker,
- };
- }
- const result = await next();
-
- // @ts-expect-error
- if (result.data) {
- getRedisCache().setJson(
- key,
- ttl,
- // @ts-expect-error
- result.data,
- );
- }
- return result;
- });
+export const cacheMiddleware = createCacheMiddleware({
+ cache: rpcCache,
+ // A thunk, because V1 read NODE_ENV on every request rather than once when
+ // the router module was first imported.
+ serveFromCache: () => process.env.NODE_ENV === 'production',
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4877bc324..83b76e392 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1201,6 +1201,9 @@ importers:
'@elysiajs/openapi':
specifier: 1.4.15
+ '@openpanel/auth':
+ specifier: workspace:^
+ version: link:../auth
'@openpanel/common':
specifier: workspace:*
version: link:../common
@@ -1893,6 +1896,9 @@ importers:
'@openpanel/constants':
specifier: workspace:*
version: link:../constants
+ '@openpanel/core':
+ specifier: workspace:*
+ version: link:../core
'@openpanel/db':
specifier: workspace:*
version: link:../db