Skip to content

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

ralph(M11-001): Port the tRPC auth stack into core (P6 never landed) and mount core's appRouter: publicProcedure / protectedProcedure / protectedProcedureWithoutAccess, 29 routers rebuilt on V1's builders, routing golden identical, auth contract suite green on core

ralph92702a70f8eb
diff --git a/apps/api/e2e/trpc-routing-golden.ts b/apps/api/e2e/trpc-routing-golden.ts
new file mode 100644
index 000000000..7de486148
--- /dev/null
+++ b/apps/api/e2e/trpc-routing-golden.ts
@@ -0,0 +1,204 @@
+#!/usr/bin/env bun
+/**
+ * tRPC routing golden — proves every procedure the mounted router declares is
+ * reachable through the real HTTP lifecycle, and that the auth layer answers
+ * identically before and after the M11-001 mount swap.
+ *
+ * Only 11 of 217 procedures have any end-to-end coverage and 22 of the 29
+ * routers have none (docs/RPC_PROCEDURE_SET_EQUIVALENCE.md), so swapping
+ * `apps/api/src/main.ts`'s `appRouter` import needs a proof of its own. This
+ * is it: with the harness up, run it against the OLD mount, swap, run it
+ * against the NEW mount, and diff the two maps.
+ *
+ * It asserts REACHABILITY, not behaviour. Every request is unauthenticated
+ * with an empty input, so 401/403/400 are the expected answers — they prove
+ * the procedure was resolved and its auth/validation middleware ran. Only a
+ * 404 or a tRPC `NOT_FOUND` means the router did not resolve the path, and
+ * that is the single failure this script exists to catch.
+ *
+ * Usage (needs `verification/harness start`):
+ * cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-after.json
+ *
+ * The router is imported from whatever specifier `main.ts` mounts, read out of
+ * main.ts itself, so the same committed script measures both sides of the swap
+ * with no flag to forget. `@openpanel/trpc` opens Redis connections at import
+ * time and never releases the event loop, hence the explicit process.exit.
+ */
+import { readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// `import.meta.dir` is the Bun idiom (ADR-019 row 6), but apps/api's tsconfig
+// carries no bun type declarations, so this file uses the portable form.
+const REPO_ROOT = join(
+ dirname(fileURLToPath(import.meta.url)),
+ '..',
+ '..',
+ '..'
+);
+const MAIN_TS = join(REPO_ROOT, 'apps', 'api', 'src', 'main.ts');
+const DEFAULT_API_PORT = '3333';
+const TRPC_ENDPOINT = '/trpc';
+const REQUEST_TIMEOUT_MS = 30_000;
+const CONCURRENCY = 8;
+
+/**
+ * Every `import { … } from '…'` in main.ts. The mounted router is the one
+ * whose specifier list contains `appRouter` — matched as a whole binding
+ * rather than as a line, because biome's organizeImports merges it into the
+ * package's existing import block.
+ */
+const IMPORT_STATEMENT = /import\s*\{([^}]*)\}\s*from\s*'([^']+)'/g;
+
+function readEnvVar(key: string): string | undefined {
+ const line = readFileSync(join(REPO_ROOT, '.env'), 'utf8')
+ .split('\n')
+ .filter((l) => l.startsWith(`${key}=`))
+ .pop();
+ return (
+ line
+ ?.slice(key.length + 1)
+ .replaceAll('"', '')
+ .trim() || undefined
+ );
+}
+
+const API_BASE_URL =
+ process.env.E2E_API_URL ??
+ `http://127.0.0.1:${readEnvVar('API_PORT') ?? DEFAULT_API_PORT}`;
+
+function mountedRouterSpecifier(): string {
+ const source = readFileSync(MAIN_TS, 'utf8');
+ for (const [, bindings, specifier] of source.matchAll(IMPORT_STATEMENT)) {
+ const names = (bindings as string).split(',').map(
+ (binding) =>
+ binding
+ .trim()
+ .replace(/^type\s+/, '')
+ .split(/\s+as\s+/)[0]
+ );
+ if (names.includes('appRouter')) {
+ return specifier as string;
+ }
+ }
+ throw new Error(`no import of \`appRouter\` in ${MAIN_TS}`);
+}
+
+interface ProcedureProbe {
+ type: string;
+ status: number;
+ code: string | null;
+}
+
+/**
+ * tRPC 11.17 keys `_def.procedures` by dotted path, so the keys are the flat
+ * procedure set and each value carries its own `_def.type`.
+ */
+async function enumerateProcedures(): Promise<Map<string, string>> {
+ const specifier = mountedRouterSpecifier();
+ const module = (await import(specifier)) as {
+ appRouter: {
+ _def: { procedures: Record<string, { _def: { type: string } }> };
+ };
+ };
+ const entries = Object.entries(module.appRouter._def.procedures)
+ .map(([path, procedure]) => [path, procedure._def.type] as const)
+ .sort(([a], [b]) => a.localeCompare(b));
+ console.log(`mounted router: ${specifier}`);
+ return new Map(entries);
+}
+
+/** One unauthenticated request, shaped exactly as a superjson tRPC client sends it. */
+async function probe(path: string, type: string): Promise<ProcedureProbe> {
+ const body = JSON.stringify({ json: {} });
+ const isMutation = type === 'mutation';
+ const url = isMutation
+ ? `${API_BASE_URL}${TRPC_ENDPOINT}/${path}`
+ : `${API_BASE_URL}${TRPC_ENDPOINT}/${path}?input=${encodeURIComponent(body)}`;
+
+ try {
+ const response = await fetch(url, {
+ method: isMutation ? 'POST' : 'GET',
+ headers: { 'content-type': 'application/json' },
+ body: isMutation ? body : undefined,
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+ const raw = (await response.json().catch(() => null)) as {
+ error?: { json?: { data?: { code?: string } } };
+ } | null;
+ return {
+ type,
+ status: response.status,
+ code: raw?.error?.json?.data?.code ?? null,
+ };
+ } catch (error) {
+ return {
+ type,
+ status: -1,
+ code: `TRANSPORT_ERROR: ${(error as Error).message}`,
+ };
+ }
+}
+
+/** A path the router did not resolve — the only outcome this golden fails on. */
+function isRoutingFailure(result: ProcedureProbe): boolean {
+ return result.status === 404 || result.code === 'NOT_FOUND';
+}
+
+async function main(): Promise<number> {
+ const outputPath = process.argv[2];
+ if (!outputPath) {
+ console.error('usage: bun run e2e/trpc-routing-golden.ts <output.json>');
+ return 2;
+ }
+
+ const procedures = await enumerateProcedures();
+ const paths = [...procedures.keys()];
+ console.log(
+ `probing ${paths.length} procedures across ` +
+ `${new Set(paths.map((p) => p.split('.')[0])).size} routers at ${API_BASE_URL}`
+ );
+
+ const results: Record<string, ProcedureProbe> = {};
+ let cursor = 0;
+ await Promise.all(
+ Array.from({ length: CONCURRENCY }, async () => {
+ while (cursor < paths.length) {
+ const path = paths[cursor++] as string;
+ results[path] = await probe(path, procedures.get(path) as string);
+ }
+ })
+ );
+
+ const sorted: Record<string, ProcedureProbe> = {};
+ for (const path of paths) {
+ sorted[path] = results[path] as ProcedureProbe;
+ }
+ writeFileSync(outputPath, `${JSON.stringify(sorted, null, 2)}\n`);
+
+ const tally = new Map<string, number>();
+ for (const result of Object.values(sorted)) {
+ const key = `${result.status} ${result.code ?? 'ok'}`;
+ tally.set(key, (tally.get(key) ?? 0) + 1);
+ }
+ console.log(`\nwrote ${outputPath}`);
+ for (const [key, count] of [...tally].sort()) {
+ console.log(` ${String(count).padStart(4)} ${key}`);
+ }
+
+ const failures = Object.entries(sorted).filter(([, r]) =>
+ isRoutingFailure(r)
+ );
+ console.log(
+ `\ntrpc-routing-golden: ${paths.length - failures.length}/${paths.length} reachable, ` +
+ `${failures.length} routing failure(s)`
+ );
+ for (const [path, result] of failures) {
+ console.log(
+ ` UNREACHABLE ${path} -> ${result.status} ${result.code ?? ''}`
+ );
+ }
+ return failures.length === 0 ? 0 : 1;
+}
+
+process.exit(await main());
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index d23826bf8..df234d1db 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -33,6 +33,7 @@ process.env.TZ = 'UTC';
import { createHmac } from 'node:crypto';
import {
type AppDeps,
+ appRouter,
BULL_BOARD_BASE_PATH,
type BufferDeps,
bullBoardRoutes,
@@ -92,7 +93,6 @@ import {
} from '@openpanel/queue';
import { checkNotificationRulesForEvent } from '@openpanel/queue/src/notification-dispatch';
import { getRedisCache, getRedisPub, getRedisQueue } from '@openpanel/redis';
-import { appRouter } from '@openpanel/trpc';
import { Elysia } from 'elysia';
import pino from 'pino';
import {
diff --git a/docs/RPC_PROCEDURE_SET_EQUIVALENCE.md b/docs/RPC_PROCEDURE_SET_EQUIVALENCE.md
new file mode 100644
index 000000000..cd869985f
--- /dev/null
+++ b/docs/RPC_PROCEDURE_SET_EQUIVALENCE.md
@@ -0,0 +1,686 @@
+# tRPC procedure-set equivalence: `@openpanel/core` vs `@openpanel/trpc`
+
+Evidence for M11-001, produced 2026-09-06 on branch `rewrite/v2` at `04b211e3`.
+
+> **Status: the swap is done.** Sections 1-3 below are attempts 1 and 2's
+> findings, kept verbatim because they are what the fix was measured against.
+> The work and its re-run are in *M11-001 attempt 3* at the end of this file;
+> read that for the current state.
+
+At the time attempts 1 and 2 were written, `apps/api/src/main.ts:95` still
+mounted `@openpanel/trpc`'s `appRouter`. Core's
+`rpc.router.ts` has been typechecked since P2-009 but has never served a
+request. This file records the comparison that must pass before the mount is
+swapped.
+
+## Method
+
+A throwaway script (`packages/core/procedure-diff.tmp.ts`, since deleted)
+imported both routers and printed `Object.keys(router._def.procedures).sort()`
+— tRPC 11.17.0 keys that record by dotted procedure path, so it is the full
+flat procedure set of each router.
+
+```bash
+cd packages/core && bun run procedure-diff.tmp.ts
+```
+
+The process computes both lists in under a second and then does not exit: the
+`@openpanel/trpc` import graph opens two Redis connections at import time
+(`ss -tnp` showed two ESTAB sockets to `:6379` held by the bun pid). The lists
+were written to disk with `Bun.write` before that point and diffed separately.
+
+## Result — the diff is NOT empty
+
+```
+core(@openpanel/core): 217 procedures across 29 routers
+trpc(@openpanel/trpc): 216 procedures across 28 routers
+
+$ diff procedure-paths-trpc.txt procedure-paths-core.txt
+97a98
+> health.live
+```
+
+One line. Core is a **strict superset**: every one of the 216 procedures
+`@openpanel/trpc` serves today exists in core under the identical path, and
+core adds exactly one, `health.live`.
+
+`health.live` is not drift. It was added by P2-009 (`61ccc7cb`) as core's own
+scaffold proof and its source comment says so explicitly:
+
+> The one procedure `rpc.router.ts` mounts before the first real module lands
+> (ADR-007 decision 19) — proves the tRPC surface composes end to end. No V1
+> router named `health` exists.
+
+`apps/start` never references `health.*`, so mounting it adds a procedure no
+client calls rather than changing one any client does.
+
+M11-001 attempt 2's acceptance criterion expects **exactly this diff** and
+forbids deleting `health.live` to force it empty. Reproduced on 2026-09-06 at
+`04b211e3`, byte-identical to attempt 1's result. The procedure sets are
+equivalent; the mount swap is blocked by the routing golden below, not by this.
+
+## Per-router coverage by existing automated checks
+
+The three checks named in the task cover the tRPC surface as follows.
+
+- **session-e2e** (`apps/api/e2e/session-e2e.ts`) issues **zero** tRPC
+ requests. It drives `POST /track` and asserts ClickHouse and Redis state. Its
+ 29/29 pass says nothing about any procedure.
+- **golden REST suite** (`verification/golden/`, 137 cases: 112 `insights`,
+ 25 `export`) is REST-only. It will **not** catch a tRPC regression.
+- **auth contract suite** (`verification/contracts/auth/`) is the only check
+ that issues tRPC requests: 11 procedures across 7 routers. It asserts
+ authorization outcomes (401/403/200), not response shape.
+
+| # | Router | Procs | Covered by | Procedures exercised |
+|---|---|---:|---|---|
+| 1 | auth | 15 | **nothing** | — |
+| 2 | chart | 12 | auth contract suite (1/12) | `chart.aggregate` |
+| 3 | chat | 1 | **nothing** | — |
+| 4 | client | 4 | **nothing** | — |
+| 5 | cohort | 13 | auth contract suite (1/13) | `cohort.refresh` |
+| 6 | conversation | 4 | auth contract suite (2/4) | `conversation.get`, `conversation.rename` |
+| 7 | dashboard | 5 | auth contract suite (3/5) | `dashboard.create`, `dashboard.list`, `dashboard.delete` |
+| 8 | email | 3 | **nothing** | — |
+| 9 | event | 12 | **nothing** | — |
+| 10 | group | 14 | **nothing** | — |
+| 11 | gsc | 14 | **nothing** | — |
+| 12 | health | 1 | **nothing** | — (core-only; see diff above) |
+| 13 | import | 5 | auth contract suite (1/5) | `import.delete` |
+| 14 | insight | 3 | **nothing** | — |
+| 15 | integration | 8 | **nothing** | — |
+| 16 | notification | 4 | **nothing** | — |
+| 17 | onboarding | 2 | **nothing** | — |
+| 18 | organization | 13 | auth contract suite (1/13) | `organization.list` |
+| 19 | overview | 13 | **nothing** | — |
+| 20 | profile | 9 | **nothing** | — |
+| 21 | project | 7 | **nothing** | — |
+| 22 | realtime | 6 | **nothing** | — |
+| 23 | reference | 5 | **nothing** | — |
+| 24 | report | 10 | auth contract suite (2/10) | `report.get`, `report.update` |
+| 25 | session | 4 | **nothing** | — |
+| 26 | share | 10 | **nothing** | — |
+| 27 | subscription | 9 | **nothing** | — |
+| 28 | user | 5 | **nothing** | — |
+| 29 | widget | 6 | **nothing** | — |
+
+**11 of 217 procedures (5%) are exercised over HTTP by any of the three
+checks. 22 of 29 routers have no end-to-end coverage at all.**
+
+Not counted above, because the task named three specific checks and these are
+not them: 21 `packages/core/src/modules/*/*.rpc.test.ts` files run under
+`bun test`. They are in-process unit tests over mocked deps — they prove a
+procedure's logic, not that it is reachable through the mounted router, the
+Elysia lifecycle, the session macro or superjson.
+
+## Consequence
+
+The mount swap is a change whose blast radius is 217 procedures against 11
+procedures of end-to-end coverage. That gap is a real finding independent of
+the `health.live` diff, and it is why the task asked for this table.
+
+---
+
+# The tRPC routing golden (M11-001 attempt 2, 2026-09-06)
+
+`apps/api/e2e/trpc-routing-golden.ts` is the gate the mount swap must pass, and
+it exists because of the 11/217 coverage gap measured above. It enumerates the
+mounted router's procedures, issues one **unauthenticated** request per path
+through `/trpc/<path>` (GET `?input=` for queries, POST for mutations,
+superjson `{}`), and records `{type, status, tRPC error code}` per path. A 404
+or `NOT_FOUND` is a routing failure and exits non-zero; 400/401/403 are passes —
+they prove the procedure resolved and its validation/auth ran.
+
+The router specifier is read out of `apps/api/src/main.ts`'s `appRouter` import,
+so the same committed script measures both sides of the swap with no flag.
+
+## Both runs, harness up (`verification/harness start`), local box, 2026-09-06
+
+```
+$ cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-before.json
+mounted router: @openpanel/trpc
+probing 216 procedures across 28 routers at http://127.0.0.1:3333
+ 4 200 ok
+ 17 400 BAD_REQUEST
+ 195 401 UNAUTHORIZED
+trpc-routing-golden: 216/216 reachable, 0 routing failure(s) exit 0
+
+$ cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-after.json
+mounted router: @openpanel/core
+probing 217 procedures across 29 routers at http://127.0.0.1:3333
+ 5 200 ok
+ 193 400 BAD_REQUEST
+ 19 401 UNAUTHORIZED
+trpc-routing-golden: 217/217 reachable, 0 routing failure(s) exit 0
+```
+
+**Reachability passes on both sides**: every one of core's 217 procedures
+resolves through the real Elysia lifecycle and the tRPC fetch mount. Nothing is
+unroutable, and `health.live` is the only path present on one side only.
+
+## The maps are NOT identical — 176 of 216 shared paths answer differently
+
+```
+only in AFTER: ['health.live']
+only in BEFORE: []
+changed: 176 # all of them 401 UNAUTHORIZED -> 400 BAD_REQUEST
+ auth.totpDisable: 401 UNAUTHORIZED -> 400 BAD_REQUEST
+ chart.aggregate: 401 UNAUTHORIZED -> 400 BAD_REQUEST
+ client.list: 401 UNAUTHORIZED -> 400 BAD_REQUEST
+ ...
+```
+
+Cause: V1's routers are built on `packages/trpc/src/trpc.ts:142`'s
+`protectedProcedure = procedure.use(enforceUserIsAuthed).use(enforceAccess)…`,
+so authentication runs **before** input parsing and an anonymous caller gets
+`UNAUTHORIZED` whatever it sends. Core's ported routers use the bare
+`procedure` and do their auth **inside the handler** — `rpc/base.ts:90` says the
+middleware stack "lands with auth (P6)", and it never did. Input parsing
+therefore precedes authentication, and an anonymous caller with a malformed
+input gets `BAD_REQUEST`.
+
+## The consequence the golden's empty input hides — 3 procedures lose authorization
+
+Ordering alone would be a contract detail. But because the check moved from a
+middleware to per-handler code, a procedure can simply not have one. Probing
+**queries only** (no mutations, no side effects) with a plausible input,
+unauthenticated, on the same box and the same harness, 2026-09-06:
+
+```
+$ bun run authprobe.tmp.ts # throwaway, deleted; input {projectId, organizationId}
+mounted: @openpanel/trpc queries: 133 mounted: @openpanel/core queries: 134
+ 2 200 ok 6 200 ok
+ 9 400 BAD_REQUEST 70 400 BAD_REQUEST
+ 122 401 UNAUTHORIZED 57 401 UNAUTHORIZED
+ 1 500 INTERNAL_SERVER_ERROR
+
+401/other -> 200 (authorization LOST): client.list, subscription.getCurrent, subscription.usage
+401 UNAUTHORIZED -> 400 BAD_REQUEST: 61
+identical: 68 / 133 shared query paths
+core-only 500: subscription.products (trpc: 401 UNAUTHORIZED)
+```
+
+What the three return to a caller with no cookie and no credential:
+
+| Procedure | trpc | core | Body |
+|---|---|---|---|
+| `client.list` | 401 | **200** | `array of {createdAt,id,ignoreCorsAndSecret,name,organizationId,projectId,secret,type,updatedAt}` — the project's ingestion clients, `secret` included (ADR-011 already flags that field as the scrypt hash) |
+| `subscription.usage` | 401 | **200** | `array[31] of {count, day}` — 31 days of per-day event volume for any projectId |
+| `subscription.getCurrent` | 401 | **200** | `null` for an org with no subscription; not gated either way |
+
+`client.list`'s source comment is the whole story
+(`modules/client/client.rpc.ts:31`):
+
+> Ported verbatim: V1's `client.list` reads by projectId with no access check of
+> its own (packages/trpc/src/routers/client.ts).
+
+True of the *handler body*, and wrong about the procedure: V1's `client.list` is
+a `protectedProcedure`, so `enforceUserIsAuthed` + `enforceAccess` gated it on
+the `projectId` in the input. Dropping the stack dropped the check.
+
+`auth.session`, `onboarding.skipOnboardingCheck` and `health.live` also answer
+200 on core; the first two answer 200 on trpc too and are legitimately public.
+
+## Verdict (attempt 2 — SUPERSEDED by attempt 3 below, which did the work)
+
+The swap is **not** blocked by reachability, by the procedure set, or by
+anything `health.live` does. It is blocked because mounting core today would
+publish three authenticated read endpoints to anonymous callers and change the
+error precedence of 176 more. The fix is the P6 work `rpc/base.ts:90` defers:
+port `publicProcedure` / `protectedProcedure` / `protectedProcedureWithoutAccess`
+(and with them `enforceUserIsAuthed`, `enforceAccess`, `loggerMiddleware`,
+`sessionScopeMiddleware`) into core and rebuild the 29 routers on them. That
+restores auth-before-validation by construction and makes the missing check
+impossible rather than per-handler. It is a wave, not a line, and it is not
+M11-001's to do.
+
+Re-run this golden after that work: the diff should then be `health.live` only.
+
+---
+
+# M11-001 attempt 3: the port landed, and the swap is live
+
+Produced 2026-09-06 on branch `rewrite/v2` on top of `04b211e3`. Attempt 2's
+two artefacts above (`apps/api/e2e/trpc-routing-golden.ts` and everything up to
+its verdict) are unchanged; this section records the work that verdict named as
+the fix, and the re-run of its own gate.
+
+## What landed
+
+`packages/trpc/src/trpc.ts:35-155`'s four middlewares are now in
+`packages/core/src/rpc/base.ts`, with their logic unchanged:
+
+| Middleware | Change on the port |
+|---|---|
+| `enforceUserIsAuthed` | none, except `console.error` → `ctx.logger.error` (core has a request-scoped logger; CLAUDE.md bans `console`). Same branch, same messages. |
+| `enforceAccess` | the two lookups come through `ctx.services.auth.requireProjectAccess` / `.getOrganizationAccess` instead of `packages/trpc/src/access.ts`'s direct imports. M10-002 bound the ladder there once. Everything else — `runWithAlsSession` first, `getRawInput()` before the demo-mode ban, top-level `has('projectId')` / `has('organizationId')` only, `needsWrite = type === 'mutation' && !meta?.readOnlyMutation` — is character-for-character V1's. |
+| `loggerMiddleware` | none. |
+| `sessionScopeMiddleware` | none. |
+
+and the three builders compose them in V1's order (`trpc.ts:141-155`):
+
+```ts
+publicProcedure = procedure.use(logger).use(sessionScope);
+protectedProcedure = procedure.use(enforceUserIsAuthed)
+ .use(enforceAccess)
+ .use(logger).use(sessionScope);
+protectedProcedureWithoutAccess = procedure.use(enforceUserIsAuthed)
+ .use(logger).use(sessionScope);
+```
+
+`rpc/base.ts:90`'s "they land with auth (P6)" comment is gone; what replaces it
+says why the stack is a stack — authentication before input parsing, a check
+that cannot be forgotten, and the raw-input rule ADR-011 invariant 2 states.
+
+`apps/api/src/main.ts` imports `appRouter` from `@openpanel/core` (biome folded
+it into the existing core block at line 36). `packages/trpc` is untouched and
+still typechecks and tests green — it builds on the same `procedure`.
+
+## The rebuild: every procedure on its V1 twin's builder
+
+Derived per procedure, not per file: both routers were parsed for the
+top-level `name: builder` entries of their `createTRPCRouter({...})` object
+(comments and string literals blanked first, so a `//` line cannot be mistaken
+for an entry). 216 V1 procedures, 217 core procedures, and every shared name
+now carries the same builder.
+
+`chartProcedure` and `overviewProcedure` are V1's own share-aware builders —
+both are `publicProcedure` plus one middleware — and core now has them in the
+same shape rather than as per-handler calls. That is load-bearing for the
+golden: their access decision has to run before the input parser, or a
+`chartProcedure` path answers `BAD_REQUEST` where V1 answers `UNAUTHORIZED`.
+`chart.rpc.ts`'s `resolveShareableReport` helper is gone; the resolved report
+rides on `ctx.report`, exactly as in V1.
+
+| Router | Procs | public | protected | withoutAccess | share-aware |
+|---|---:|---:|---:|---:|---:|
+| auth | 15 | 10 | 5 | 0 | 0 |
+| chart | 12 | 0 | 7 | 0 | 5 |
+| chat | 1 | 0 | 1 | 0 | 0 |
+| client | 4 | 0 | 4 | 0 | 0 |
+| cohort | 13 | 0 | 13 | 0 | 0 |
+| conversation | 4 | 0 | 4 | 0 | 0 |
+| dashboard | 5 | 0 | 5 | 0 | 0 |
+| email | 3 | 1 | 2 | 0 | 0 |
+| event | 12 | 0 | 12 | 0 | 0 |
+| group | 14 | 0 | 14 | 0 | 0 |
+| gsc | 14 | 0 | 14 | 0 | 0 |
+| health | 1 | 1 | 0 | 0 | 0 |
+| import | 5 | 0 | 5 | 0 | 0 |
+| insight | 3 | 0 | 3 | 0 | 0 |
+| integration | 8 | 0 | 8 | 0 | 0 |
+| notification | 4 | 0 | 4 | 0 | 0 |
+| onboarding | 2 | 1 | 1 | 0 | 0 |
+| organization | 13 | 1 | 11 | 1 | 0 |
+| overview | 13 | 0 | 1 | 0 | 12 |
+| profile | 9 | 0 | 9 | 0 | 0 |
+| project | 7 | 0 | 7 | 0 | 0 |
+| realtime | 6 | 0 | 6 | 0 | 0 |
+| reference | 5 | 1 | 4 | 0 | 0 |
+| report | 10 | 0 | 10 | 0 | 0 |
+| session | 4 | 0 | 4 | 0 | 0 |
+| share | 10 | 4 | 6 | 0 | 0 |
+| subscription | 9 | 0 | 9 | 0 | 0 |
+| user | 5 | 0 | 5 | 0 | 0 |
+| widget | 6 | 3 | 3 | 0 | 0 |
+| **total** | **217** | **22** | **177** | **1** | **17** |
+
+`health.live` is core-only (P2-009) and is `publicProcedure`.
+
+**No in-handler check was removed.** ADR-011 counts 58 of them and the auth
+contract suite's group C tests 14; every one still runs, now behind the
+builder's check rather than instead of it.
+
+<details>
+<summary>All 217 procedures: path → V1 builder → core builder</summary>
+
+| Procedure | V1 builder | core builder |
+|---|---|---|
+| `chat.models` | `protectedProcedure` | `protectedProcedure` |
+| `auth.signOut` | `publicProcedure` | `publicProcedure` |
+| `auth.signInOAuth` | `publicProcedure` | `publicProcedure` |
+| `auth.signUpEmail` | `publicProcedure` | `publicProcedure` |
+| `auth.signInEmail` | `publicProcedure` | `publicProcedure` |
+| `auth.signInTotp` | `publicProcedure` | `publicProcedure` |
+| `auth.totpStatus` | `protectedProcedure` | `protectedProcedure` |
+| `auth.totpSetup` | `protectedProcedure` | `protectedProcedure` |
+| `auth.totpEnable` | `protectedProcedure` | `protectedProcedure` |
+| `auth.totpDisable` | `protectedProcedure` | `protectedProcedure` |
+| `auth.totpRegenerateRecoveryCodes` | `protectedProcedure` | `protectedProcedure` |
+| `auth.resetPassword` | `publicProcedure` | `publicProcedure` |
+| `auth.requestResetPassword` | `publicProcedure` | `publicProcedure` |
+| `auth.session` | `publicProcedure` | `publicProcedure` |
+| `auth.extendSession` | `publicProcedure` | `publicProcedure` |
+| `auth.signInShare` | `publicProcedure` | `publicProcedure` |
+| `chart.projectCard` | `protectedProcedure` | `protectedProcedure` |
+| `chart.events` | `protectedProcedure` | `protectedProcedure` |
+| `chart.properties` | `protectedProcedure` | `protectedProcedure` |
+| `chart.values` | `protectedProcedure` | `protectedProcedure` |
+| `chart.funnel` | `chartProcedure` | `chartProcedure` |
+| `chart.conversion` | `chartProcedure` | `chartProcedure` |
+| `chart.sankey` | `protectedProcedure` | `protectedProcedure` |
+| `chart.chart` | `chartProcedure` | `chartProcedure` |
+| `chart.aggregate` | `chartProcedure` | `chartProcedure` |
+| `chart.cohort` | `chartProcedure` | `chartProcedure` |
+| `chart.getProfiles` | `protectedProcedure` | `protectedProcedure` |
+| `chart.getFunnelProfiles` | `protectedProcedure` | `protectedProcedure` |
+| `client.list` | `protectedProcedure` | `protectedProcedure` |
+| `client.update` | `protectedProcedure` | `protectedProcedure` |
+| `client.create` | `protectedProcedure` | `protectedProcedure` |
+| `client.remove` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.list` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.get` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.create` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.update` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.delete` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.listProfiles` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.mostEvents` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.eventsPerDay` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.popularRoutes` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.getCount` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.preview` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.exportProfiles` | `protectedProcedure` | `protectedProcedure` |
+| `cohort.refresh` | `protectedProcedure` | `protectedProcedure` |
+| `conversation.list` | `protectedProcedure` | `protectedProcedure` |
+| `conversation.get` | `protectedProcedure` | `protectedProcedure` |
+| `conversation.rename` | `protectedProcedure` | `protectedProcedure` |
+| `conversation.delete` | `protectedProcedure` | `protectedProcedure` |
+| `dashboard.list` | `protectedProcedure` | `protectedProcedure` |
+| `dashboard.byId` | `protectedProcedure` | `protectedProcedure` |
+| `dashboard.create` | `protectedProcedure` | `protectedProcedure` |
+| `dashboard.update` | `protectedProcedure` | `protectedProcedure` |
+| `dashboard.delete` | `protectedProcedure` | `protectedProcedure` |
+| `email.unsubscribe` | `publicProcedure` | `publicProcedure` |
+| `email.getPreferences` | `protectedProcedure` | `protectedProcedure` |
+| `email.updatePreferences` | `protectedProcedure` | `protectedProcedure` |
+| `event.updateEventMeta` | `protectedProcedure` | `protectedProcedure` |
+| `event.byId` | `protectedProcedure` | `protectedProcedure` |
+| `event.details` | `protectedProcedure` | `protectedProcedure` |
+| `event.events` | `protectedProcedure` | `protectedProcedure` |
+| `event.conversionNames` | `protectedProcedure` | `protectedProcedure` |
+| `event.conversions` | `protectedProcedure` | `protectedProcedure` |
+| `event.bots` | `protectedProcedure` | `protectedProcedure` |
+| `event.pages` | `protectedProcedure` | `protectedProcedure` |
+| `event.pagesTimeseries` | `protectedProcedure` | `protectedProcedure` |
+| `event.previousPages` | `protectedProcedure` | `protectedProcedure` |
+| `event.pageTimeseries` | `protectedProcedure` | `protectedProcedure` |
+| `event.origin` | `protectedProcedure` | `protectedProcedure` |
+| `group.list` | `protectedProcedure` | `protectedProcedure` |
+| `group.byId` | `protectedProcedure` | `protectedProcedure` |
+| `group.create` | `protectedProcedure` | `protectedProcedure` |
+| `group.update` | `protectedProcedure` | `protectedProcedure` |
+| `group.delete` | `protectedProcedure` | `protectedProcedure` |
+| `group.types` | `protectedProcedure` | `protectedProcedure` |
+| `group.metrics` | `protectedProcedure` | `protectedProcedure` |
+| `group.activity` | `protectedProcedure` | `protectedProcedure` |
+| `group.memberGrowth` | `protectedProcedure` | `protectedProcedure` |
+| `group.listProfiles` | `protectedProcedure` | `protectedProcedure` |
+| `group.mostEvents` | `protectedProcedure` | `protectedProcedure` |
+| `group.popularRoutes` | `protectedProcedure` | `protectedProcedure` |
+| `group.properties` | `protectedProcedure` | `protectedProcedure` |
+| `group.listByIds` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getConnection` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.initiateOAuth` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getSites` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.selectSite` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.disconnect` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getOverview` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getPages` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getPageDetails` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getQueryDetails` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getQueries` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getSearchEngines` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getAiEngines` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getPreviousOverview` | `protectedProcedure` | `protectedProcedure` |
+| `gsc.getCannibalization` | `protectedProcedure` | `protectedProcedure` |
+| `health.live` | `— (core-only)` | `publicProcedure` |
+| `import.list` | `protectedProcedure` | `protectedProcedure` |
+| `import.get` | `protectedProcedure` | `protectedProcedure` |
+| `import.create` | `protectedProcedure` | `protectedProcedure` |
+| `import.delete` | `protectedProcedure` | `protectedProcedure` |
+| `import.retry` | `protectedProcedure` | `protectedProcedure` |
+| `insight.list` | `protectedProcedure` | `protectedProcedure` |
+| `insight.listAll` | `protectedProcedure` | `protectedProcedure` |
+| `insight.explain` | `protectedProcedure` | `protectedProcedure` |
+| `integration.get` | `protectedProcedure` | `protectedProcedure` |
+| `integration.list` | `protectedProcedure` | `protectedProcedure` |
+| `integration.createOrUpdateSlack` | `protectedProcedure` | `protectedProcedure` |
+| `integration.createOrUpdate` | `protectedProcedure` | `protectedProcedure` |
+| `integration.createOrUpdateExport` | `protectedProcedure` | `protectedProcedure` |
+| `integration.testConnection` | `protectedProcedure` | `protectedProcedure` |
+| `integration.testExportConnection` | `protectedProcedure` | `protectedProcedure` |
+| `integration.delete` | `protectedProcedure` | `protectedProcedure` |
+| `notification.list` | `protectedProcedure` | `protectedProcedure` |
+| `notification.rules` | `protectedProcedure` | `protectedProcedure` |
+| `notification.createOrUpdateRule` | `protectedProcedure` | `protectedProcedure` |
+| `notification.deleteRule` | `protectedProcedure` | `protectedProcedure` |
+| `onboarding.skipOnboardingCheck` | `publicProcedure` | `publicProcedure` |
+| `onboarding.project` | `protectedProcedure` | `protectedProcedure` |
+| `organization.get` | `protectedProcedure` | `protectedProcedure` |
+| `organization.list` | `protectedProcedure` | `protectedProcedure` |
+| `organization.myAccess` | `protectedProcedureWithoutAccess` | `protectedProcedureWithoutAccess` |
+| `organization.update` | `protectedProcedure` | `protectedProcedure` |
+| `organization.delete` | `protectedProcedure` | `protectedProcedure` |
+| `organization.cancelDeletion` | `protectedProcedure` | `protectedProcedure` |
+| `organization.inviteUser` | `protectedProcedure` | `protectedProcedure` |
+| `organization.revokeInvite` | `protectedProcedure` | `protectedProcedure` |
+| `organization.removeMember` | `protectedProcedure` | `protectedProcedure` |
+| `organization.updateMemberAccess` | `protectedProcedure` | `protectedProcedure` |
+| `organization.members` | `protectedProcedure` | `protectedProcedure` |
+| `organization.invitations` | `protectedProcedure` | `protectedProcedure` |
+| `organization.getInvite` | `publicProcedure` | `publicProcedure` |
+| `overview.liveVisitors` | `overviewProcedure` | `overviewProcedure` |
+| `overview.liveData` | `overviewProcedure` | `overviewProcedure` |
+| `overview.stats` | `overviewProcedure` | `overviewProcedure` |
+| `overview.getReferrerSpikes` | `overviewProcedure` | `overviewProcedure` |
+| `overview.topPages` | `overviewProcedure` | `overviewProcedure` |
+| `overview.topGeneric` | `overviewProcedure` | `overviewProcedure` |
+| `overview.topGenericSeries` | `overviewProcedure` | `overviewProcedure` |
+| `overview.userJourney` | `overviewProcedure` | `overviewProcedure` |
+| `overview.topEvents` | `overviewProcedure` | `overviewProcedure` |
+| `overview.topConversions` | `overviewProcedure` | `overviewProcedure` |
+| `overview.topLinkOut` | `overviewProcedure` | `overviewProcedure` |
+| `overview.runFilterCommand` | `protectedProcedure` | `protectedProcedure` |
+| `overview.map` | `overviewProcedure` | `overviewProcedure` |
+| `profile.byId` | `protectedProcedure` | `protectedProcedure` |
+| `profile.metrics` | `protectedProcedure` | `protectedProcedure` |
+| `profile.activity` | `protectedProcedure` | `protectedProcedure` |
+| `profile.mostEvents` | `protectedProcedure` | `protectedProcedure` |
+| `profile.popularRoutes` | `protectedProcedure` | `protectedProcedure` |
+| `profile.properties` | `protectedProcedure` | `protectedProcedure` |
+| `profile.list` | `protectedProcedure` | `protectedProcedure` |
+| `profile.powerUsers` | `protectedProcedure` | `protectedProcedure` |
+| `profile.values` | `protectedProcedure` | `protectedProcedure` |
+| `project.getProjectWithClients` | `protectedProcedure` | `protectedProcedure` |
+| `project.activationStatus` | `protectedProcedure` | `protectedProcedure` |
+| `project.list` | `protectedProcedure` | `protectedProcedure` |
+| `project.update` | `protectedProcedure` | `protectedProcedure` |
+| `project.create` | `protectedProcedure` | `protectedProcedure` |
+| `project.delete` | `protectedProcedure` | `protectedProcedure` |
+| `project.cancelDeletion` | `protectedProcedure` | `protectedProcedure` |
+| `realtime.coordinates` | `protectedProcedure` | `protectedProcedure` |
+| `realtime.mapBadgeDetails` | `protectedProcedure` | `protectedProcedure` |
+| `realtime.activeSessions` | `protectedProcedure` | `protectedProcedure` |
+| `realtime.paths` | `protectedProcedure` | `protectedProcedure` |
+| `realtime.referrals` | `protectedProcedure` | `protectedProcedure` |
+| `realtime.geo` | `protectedProcedure` | `protectedProcedure` |
+| `reference.getReferences` | `protectedProcedure` | `protectedProcedure` |
+| `reference.create` | `protectedProcedure` | `protectedProcedure` |
+| `reference.update` | `protectedProcedure` | `protectedProcedure` |
+| `reference.delete` | `protectedProcedure` | `protectedProcedure` |
+| `reference.getChartReferences` | `publicProcedure` | `publicProcedure` |
+| `report.list` | `protectedProcedure` | `protectedProcedure` |
+| `report.create` | `protectedProcedure` | `protectedProcedure` |
+| `report.update` | `protectedProcedure` | `protectedProcedure` |
+| `report.move` | `protectedProcedure` | `protectedProcedure` |
+| `report.delete` | `protectedProcedure` | `protectedProcedure` |
+| `report.duplicate` | `protectedProcedure` | `protectedProcedure` |
+| `report.get` | `protectedProcedure` | `protectedProcedure` |
+| `report.updateLayout` | `protectedProcedure` | `protectedProcedure` |
+| `report.getLayouts` | `protectedProcedure` | `protectedProcedure` |
+| `report.resetLayout` | `protectedProcedure` | `protectedProcedure` |
+| `session.list` | `protectedProcedure` | `protectedProcedure` |
+| `session.distinctValues` | `protectedProcedure` | `protectedProcedure` |
+| `session.byId` | `protectedProcedure` | `protectedProcedure` |
+| `session.replayChunksFrom` | `protectedProcedure` | `protectedProcedure` |
+| `share.overview` | `publicProcedure` | `publicProcedure` |
+| `share.overviewSettings` | `protectedProcedure` | `protectedProcedure` |
+| `share.createOverview` | `protectedProcedure` | `protectedProcedure` |
+| `share.dashboard` | `publicProcedure` | `publicProcedure` |
+| `share.dashboardSettings` | `protectedProcedure` | `protectedProcedure` |
+| `share.createDashboard` | `protectedProcedure` | `protectedProcedure` |
+| `share.dashboardReports` | `publicProcedure` | `publicProcedure` |
+| `share.report` | `publicProcedure` | `publicProcedure` |
+| `share.reportSettings` | `protectedProcedure` | `protectedProcedure` |
+| `share.createReport` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.getCurrent` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.checkout` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.products` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.usage` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.cancelSubscription` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.pauseSubscription` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.resumeSubscription` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.applySaveDiscount` | `protectedProcedure` | `protectedProcedure` |
+| `subscription.portal` | `protectedProcedure` | `protectedProcedure` |
+| `user.deletionBlockers` | `protectedProcedure` | `protectedProcedure` |
+| `user.delete` | `protectedProcedure` | `protectedProcedure` |
+| `user.update` | `protectedProcedure` | `protectedProcedure` |
+| `user.debugPostCookie` | `protectedProcedure` | `protectedProcedure` |
+| `user.debugGetCookie` | `protectedProcedure` | `protectedProcedure` |
+| `widget.get` | `protectedProcedure` | `protectedProcedure` |
+| `widget.toggle` | `protectedProcedure` | `protectedProcedure` |
+| `widget.updateOptions` | `protectedProcedure` | `protectedProcedure` |
+| `widget.counter` | `publicProcedure` | `publicProcedure` |
+| `widget.badge` | `publicProcedure` | `publicProcedure` |
+| `widget.realtimeData` | `publicProcedure` | `publicProcedure` |
+
+</details>
+
+## PROOF 1 — the routing golden, before and after
+
+Both runs on this box, 2026-09-06, `verification/harness start` up, the same
+harness process restarted between them so no in-process cache crossed the swap.
+`main.ts` was temporarily pointed back at `@openpanel/trpc` for the BEFORE run
+and restored for the AFTER run; the golden reads the specifier out of `main.ts`
+itself, so neither run needed a flag.
+
+```
+$ cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-before.json
+mounted router: @openpanel/trpc
+probing 216 procedures across 28 routers at http://127.0.0.1:3333
+ 4 200 ok
+ 17 400 BAD_REQUEST
+ 195 401 UNAUTHORIZED
+trpc-routing-golden: 216/216 reachable, 0 routing failure(s) exit 0
+
+$ cd apps/api && bun run e2e/trpc-routing-golden.ts /tmp/trpc-routing-after.json
+mounted router: @openpanel/core
+probing 217 procedures across 29 routers at http://127.0.0.1:3333
+ 5 200 ok
+ 17 400 BAD_REQUEST
+ 195 401 UNAUTHORIZED
+trpc-routing-golden: 217/217 reachable, 0 routing failure(s) exit 0
+```
+
+The diff of the two maps:
+
+```
+only in AFTER : ['health.live']
+only in BEFORE: []
+changed : 0
+
+shared paths identical: 216 / 216
+ AFTER-only health.live {'type': 'query', 'status': 200, 'code': None}
+```
+
+**Empty except `health.live`.** Attempt 2's 176 differing paths, its three
+401 → 200 and its one 401 → 500 are all gone, and the per-status tallies now
+match on both sides (17 `BAD_REQUEST`, 195 `UNAUTHORIZED`, plus the 4 public
+200s and core's fifth, `health.live`).
+
+## PROOF 3 — the three holes, and the 500
+
+The golden probes with an empty input, which is what let three missing checks
+hide behind a zod rejection in attempt 2. Repeating that attempt's own
+plausible-input probe — every **query** procedure, unauthenticated, input
+`{projectId: 'proj_1', organizationId: 'org_1'}` — on both mounts, same box,
+same day:
+
+```
+mounted: @openpanel/trpc queries: 133 mounted: @openpanel/core queries: 134
+ 2 200 ok 3 200 ok
+ 9 400 BAD_REQUEST 9 400 BAD_REQUEST
+ 122 401 UNAUTHORIZED 122 401 UNAUTHORIZED
+
+changed: 0
+identical: 133 / 133 shared query paths
+core-only: health.live
+```
+
+Attempt 2 measured 68/133 identical here. It is now 133/133, and the third
+core `200` is `health.live`, not a leaked endpoint.
+
+The four named procedures, requested with no cookie and no credential:
+
+```
+--- GET /trpc/client.list?input={"json":{"projectId":"proj_1","organizationId":"org_1"}}
+HTTP 401
+{"error":{"json":{"message":"Not authenticated","code":-32001,
+ "data":{"code":"UNAUTHORIZED","httpStatus":401,
+ "stack":"TRPCError: Not authenticated\n at packages/core/src/rpc/base.ts:129:15 ...
+
+--- GET /trpc/subscription.getCurrent?input={"json":{"projectId":"proj_1","organizationId":"org_1"}}
+HTTP 401 code UNAUTHORIZED message "Not authenticated"
+
+--- GET /trpc/subscription.usage?input={"json":{"projectId":"proj_1","organizationId":"org_1"}}
+HTTP 401 code UNAUTHORIZED message "Not authenticated"
+
+--- GET /trpc/subscription.products?input={"json":{"projectId":"proj_1","organizationId":"org_1"}}
+HTTP 401 code UNAUTHORIZED message "Not authenticated"
+```
+
+`@openpanel/trpc` answers all four identically (`401 UNAUTHORIZED`,
+`"Not authenticated"`, thrown at `packages/trpc/src/trpc.ts:38` rather than
+`packages/core/src/rpc/base.ts:129`). `client.list` no longer returns the
+project's ingestion clients — `secret` column included — to an anonymous
+caller, and `subscription.products` no longer 500s.
+
+## PROOF 2 — the auth contract suite, run against CORE
+
+`verification/contracts/auth/run.sh` re-seeds, restarts the harness and targets
+:3333, so with core mounted it tests core. Zero edits to `verification/`.
+
+```
+group (a) per-surface negative: 24 passed, 0 failed
+group (b) getProjectAccess golden table: 17 passed, 0 failed
+group (c) in-handler checks: 14 passed, 0 failed
+group (d) enforceAccess shape triggers: 9 passed, 0 failed
+group (e) cross-project share isolation: 7 passed, 0 failed
+AUTH CONTRACTS: all 5 groups green
+```
+
+Group (d) is the one that could only ever have passed on the ported stack: it
+asserts that a nested `projectId` does **not** trigger `enforceAccess` while a
+top-level one does, that `readOnlyMutation` downgrades the demanded level to
+read, and that the `organizationId` branch checks membership and not role.
+
+## Verdict
+
+The procedure-set diff is still exactly one line, `> health.live`. The routing
+golden's diff is now empty except that same line. The plausible-input probe is
+133/133 identical. All five auth-contract groups are green against core's
+mount. **`apps/api` serves `@openpanel/core`'s router.**
+
+Coverage is no longer 11/217: the routing golden reaches every procedure over
+HTTP, and the 217 answers are pinned to V1's on the committed
+`/tmp/trpc-routing-{before,after}.json` protocol. What it does not assert is
+response *shape* — that is still the golden REST suite's job for `/insights`
+and `/export`, and nothing's job for the other 27 routers.
+
+Two V1 middlewares did **not** move with this task and are named here so they
+are not assumed present: `rateLimitMiddleware` (10 `auth.*` procedures and
+`organization.getInvite`) and `cacheMiddleware` (chart's 60s/300s and
+overview's per-range TTLs). Both are already factories in `rpc/base.ts`
+(`createRateLimitMiddleware`, `createCacheMiddleware`) awaiting a Redis handle
+at the mount; wiring them is not in M11-001's scope and neither is visible to
+any gate this task runs.
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 8bdd338bd..8baa54df4 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -996,6 +996,9 @@ export {
createTRPCRouter,
middleware,
procedure,
+ protectedProcedure,
+ protectedProcedureWithoutAccess,
+ publicProcedure,
} from './rpc/base';
export {
TRPCAccessError,
diff --git a/packages/core/src/modules/assistant/assistant.rpc.ts b/packages/core/src/modules/assistant/assistant.rpc.ts
index ecca6f35e..5e82b43ee 100644
--- a/packages/core/src/modules/assistant/assistant.rpc.ts
+++ b/packages/core/src/modules/assistant/assistant.rpc.ts
@@ -1,16 +1,13 @@
// Ported from packages/trpc/src/routers/chat.ts (M5-005).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed` (same as cohort.rpc.ts / gsc.rpc.ts
-// / import.rpc.ts). V1 keeps serving the live route through packages/trpc's
-// own `protectedProcedure` (full stack included), now sourcing the model
-// whitelist from `@openpanel/core` instead of `@openpanel/validation`
-// directly (DELEGATE PATTERN), so nothing here is a live regression.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
getAvailableChatModels,
@@ -25,7 +22,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const chatRouter = createTRPCRouter({
- models: procedure.query(({ ctx }) => {
+ models: protectedProcedure.query(({ ctx }) => {
requireLogin(ctx.session.userId);
const providers = {
diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.ts
index 967e09522..c1810034c 100644
--- a/packages/core/src/modules/auth/auth.rpc.ts
+++ b/packages/core/src/modules/auth/auth.rpc.ts
@@ -1,18 +1,15 @@
// Ported from packages/trpc/src/routers/auth.ts (M6-003).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). This
-// router is the first to reach that comment and deliberately does not
-// resolve it: wiring a full protectedProcedure (runWithAlsSession, the
-// Redis-backed rate limiter) onto core's rpc/base.ts is a bigger change than
-// "the auth router moves" and is left for the task that actually mounts
-// `dashboardRoutes` in production (P3/P4/P8). Until then this router does
-// its own minimal "is anyone logged in" check inline, same as
-// organization.rpc.ts/project.rpc.ts. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack, including
-// rate limiting) and delegates every handler body to `./auth.service`
-// (DELEGATE PATTERN) — the same functions this router calls.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
+//
+// The ten V1 `rateLimitMiddleware` wrappers on this router did NOT move with
+// M11-001 and are not mounted; `createRateLimitMiddleware` in rpc/base.ts is
+// the seam that will carry them.
//
// This module has no queue/cron of its own, so there is no
// `ctx.services.auth` entry here — same shape as `user`/`project`.
@@ -28,7 +25,11 @@ import {
zTotpOrRecoveryCode,
} from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+} from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
disableTotp,
@@ -55,51 +56,51 @@ function requireLogin(userId: string | null | undefined): string {
}
export const authRouter = createTRPCRouter({
- signOut: procedure.mutation(async ({ ctx }) => {
+ signOut: publicProcedure.mutation(async ({ ctx }) => {
await signOutUser(ctx, ctx.setCookie, ctx.session?.session?.id);
}),
- signInOAuth: procedure
+ signInOAuth: publicProcedure
.input(z.object({ provider: zProvider, inviteId: z.string().nullish() }))
.mutation(({ input, ctx }) => startOAuthSignIn(input, ctx.setCookie)),
- signUpEmail: procedure
+ signUpEmail: publicProcedure
.input(zSignUpEmail)
.mutation(({ input, ctx }) => signUpWithEmail(ctx, input, ctx.setCookie)),
- signInEmail: procedure
+ signInEmail: publicProcedure
.input(zSignInEmail)
.mutation(({ input, ctx }) =>
signInWithEmail(ctx, input, ctx.setCookie, ctx.logger)
),
- signInTotp: procedure
+ signInTotp: publicProcedure
.input(z.object({ code: zTotpOrRecoveryCode }))
.mutation(({ input, ctx }) =>
signInWithTotp(ctx, input, ctx.cookies, ctx.setCookie, ctx.logger)
),
- totpStatus: procedure.query(({ ctx }) =>
+ totpStatus: protectedProcedure.query(({ ctx }) =>
getTotpStatus(ctx, requireLogin(ctx.session.userId))
),
- totpSetup: procedure.mutation(({ ctx }) =>
+ totpSetup: protectedProcedure.mutation(({ ctx }) =>
setupTotp(ctx, requireLogin(ctx.session.userId))
),
- totpEnable: procedure
+ totpEnable: protectedProcedure
.input(z.object({ code: zTotpCode }))
.mutation(({ input, ctx }) =>
enableTotp(ctx, requireLogin(ctx.session.userId), input.code)
),
- totpDisable: procedure
+ totpDisable: protectedProcedure
.input(z.object({ code: zTotpOrRecoveryCode }))
.mutation(({ input, ctx }) =>
disableTotp(ctx, requireLogin(ctx.session.userId), input.code)
),
- totpRegenerateRecoveryCodes: procedure
+ totpRegenerateRecoveryCodes: protectedProcedure
.input(z.object({ code: zTotpCode }))
.mutation(({ input, ctx }) =>
regenerateTotpRecoveryCodes(
@@ -109,17 +110,17 @@ export const authRouter = createTRPCRouter({
)
),
- resetPassword: procedure
+ resetPassword: publicProcedure
.input(zResetPassword)
.mutation(({ input, ctx }) => resetPasswordWithToken(ctx, input)),
- requestResetPassword: procedure
+ requestResetPassword: publicProcedure
.input(zRequestResetPassword)
.mutation(({ input, ctx }) => requestPasswordReset(ctx, input)),
- session: procedure.query(({ ctx }) => ctx.session),
+ session: publicProcedure.query(({ ctx }) => ctx.session),
- extendSession: procedure.mutation(({ ctx }) =>
+ extendSession: publicProcedure.mutation(({ ctx }) =>
extendSessionCookie(
ctx,
ctx.cookies,
@@ -128,7 +129,7 @@ export const authRouter = createTRPCRouter({
)
),
- signInShare: procedure
+ signInShare: publicProcedure
.input(zSignInShare)
.mutation(({ input, ctx }) => signInToShare(ctx, input, ctx.setCookie)),
});
diff --git a/packages/core/src/modules/chart/chart.rpc.ts b/packages/core/src/modules/chart/chart.rpc.ts
index 06ecf032c..021f1faf5 100644
--- a/packages/core/src/modules/chart/chart.rpc.ts
+++ b/packages/core/src/modules/chart/chart.rpc.ts
@@ -1,19 +1,17 @@
// Ported from packages/trpc/src/routers/chart.ts (M7-003).
//
-// Same arrangement as event.rpc.ts: V1's `protectedProcedure` / `cacheMiddleware`
-// stacks land with auth (P6), so each procedure does its own "is anyone logged
-// in" + `requireProjectAccess` off the `projectId` input, reached through
-// `ctx.services.auth` (M10-002). packages/trpc's chart router delegates its
-// handler bodies onto `./chart.service` while keeping V1's own procedure
-// stack and 60s response cache.
+// M11-001: the seven member-only procedures are back on `protectedProcedure`,
+// so `enforceAccess` reads the top-level `projectId` before the input is
+// parsed, exactly as V1 does.
//
-// V1's `chartProcedure` (funnel, conversion, chart, aggregate, cohort) also
-// admits anonymous callers holding a valid share: `shareId` + `id` resolve the
-// saved report, and the request renders that report (the caller may only move
-// the date window). `resolveShare` is that middleware, inlined.
+// `chartProcedure` (funnel, conversion, chart, aggregate, cohort) is V1's
+// share-aware builder: `publicProcedure` plus one middleware that admits an
+// anonymous caller holding a valid share — `shareId` + `id` resolve the saved
+// report, and the request renders that report (the caller may only move the
+// date window). The resolved report rides on `ctx.report`, as in V1, so a
+// handler cannot forget to resolve it.
import {
- type IReportInput,
zChartEventFilter,
zChartSeries,
zCriteria,
@@ -22,7 +20,12 @@ import {
zTimeInterval,
} from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
import type { IServiceReport } from '../report/report.service';
@@ -83,39 +86,45 @@ async function resolveShare(
return report;
}
-async function resolveShareableReport(
- ctx: TrpcContext,
- input: IReportInput & { shareId?: string; id?: string }
-): Promise<IReportInput> {
- return ctx.services.chart.resolveReportInput(
- await resolveShare(ctx, input),
- input
- );
-}
+/**
+ * V1's `chartProcedure`. The share/membership decision runs BEFORE the input
+ * is parsed and puts the resolved report on the context, so a handler reads
+ * `ctx.report` instead of re-deciding who may see it.
+ */
+const chartProcedure = publicProcedure.use(
+ async ({ ctx, next, getRawInput }) => {
+ const rawInput = (await getRawInput()) as {
+ projectId: string;
+ shareId?: string;
+ id?: string;
+ };
+ return next({ ctx: { report: await resolveShare(ctx, rawInput) } });
+ }
+);
export const chartRouter = createTRPCRouter({
- projectCard: procedure
+ projectCard: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
return ctx.services.chart.getProjectCard(input.projectId);
}),
- events: procedure
+ events: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
return ctx.services.chart.listChartEvents(input.projectId);
}),
- properties: procedure
+ properties: protectedProcedure
.input(z.object({ event: z.string().optional(), projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
return ctx.services.chart.listChartProperties(input);
}),
- values: procedure
+ values: protectedProcedure
.input(
z.object({
event: z.string(),
@@ -128,42 +137,46 @@ export const chartRouter = createTRPCRouter({
return ctx.services.chart.getChartPropertyValues(input);
}),
- funnel: procedure
+ funnel: chartProcedure
.input(zShareableReportInput)
- .query(async ({ input, ctx }) =>
+ .query(({ input, ctx }) =>
ctx.services.chart.getFunnelChart(
- await resolveShareableReport(ctx, input)
+ ctx.services.chart.resolveReportInput(ctx.report, input)
)
),
- conversion: procedure
+ conversion: chartProcedure
.input(zShareableReportInput)
- .query(async ({ input, ctx }) =>
+ .query(({ input, ctx }) =>
ctx.services.chart.getConversionChart(
- await resolveShareableReport(ctx, input)
+ ctx.services.chart.resolveReportInput(ctx.report, input)
)
),
- sankey: procedure.input(zReportInput).query(async ({ input, ctx }) => {
- await requireReadAccess(ctx, input.projectId);
- return ctx.services.chart.getSankeyChart(input);
- }),
+ sankey: protectedProcedure
+ .input(zReportInput)
+ .query(async ({ input, ctx }) => {
+ await requireReadAccess(ctx, input.projectId);
+ return ctx.services.chart.getSankeyChart(input);
+ }),
- chart: procedure
+ chart: chartProcedure
.input(zShareableReportInput)
- .query(async ({ input, ctx }) =>
- ctx.services.chart.execute(await resolveShareableReport(ctx, input))
+ .query(({ input, ctx }) =>
+ ctx.services.chart.execute(
+ ctx.services.chart.resolveReportInput(ctx.report, input)
+ )
),
- aggregate: procedure
+ aggregate: chartProcedure
.input(zShareableReportInput)
- .query(async ({ input, ctx }) =>
+ .query(({ input, ctx }) =>
ctx.services.chart.executeAggregate(
- await resolveShareableReport(ctx, input)
+ ctx.services.chart.resolveReportInput(ctx.report, input)
)
),
- cohort: procedure
+ cohort: chartProcedure
.input(
z
.object({
@@ -179,14 +192,11 @@ export const chartRouter = createTRPCRouter({
})
.and(zShareable)
)
- .query(async ({ input, ctx }) =>
- ctx.services.chart.getRetentionChart(
- await resolveShare(ctx, input),
- input
- )
+ .query(({ input, ctx }) =>
+ ctx.services.chart.getRetentionChart(ctx.report, input)
),
- getProfiles: procedure
+ getProfiles: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -201,7 +211,7 @@ export const chartRouter = createTRPCRouter({
return ctx.services.chart.bucketProfiles(input);
}),
- getFunnelProfiles: procedure
+ getFunnelProfiles: protectedProcedure
.input(
z.object({
projectId: z.string(),
diff --git a/packages/core/src/modules/client/client.rpc.ts b/packages/core/src/modules/client/client.rpc.ts
index 36d011786..af7206ec9 100644
--- a/packages/core/src/modules/client/client.rpc.ts
+++ b/packages/core/src/modules/client/client.rpc.ts
@@ -1,20 +1,19 @@
// Ported from packages/trpc/src/routers/client.ts (M6-002).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's client functions (DELEGATE
-// PATTERN). `ctx.services.client` carries this module's factory the same as
-// every other module now (M10-004).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
+//
+// `ctx.services.client` carries this module's factory (M10-004).
//
// The permission ladder itself is bound once, in auth.service.ts (M10-002);
// every procedure here reaches it through `ctx.services.auth`.
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
function requireLogin(userId: string | null | undefined): string {
@@ -25,7 +24,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const clientRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
// Ported verbatim: V1's `client.list` reads by projectId with no
@@ -33,7 +32,7 @@ export const clientRouter = createTRPCRouter({
return ctx.services.client.getClientsByProjectId(input.projectId);
}),
- update: procedure
+ update: protectedProcedure
.input(z.object({ id: z.string(), name: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -57,7 +56,7 @@ export const clientRouter = createTRPCRouter({
);
}),
- create: procedure
+ create: protectedProcedure
.input(
z.object({
name: z.string(),
@@ -95,7 +94,7 @@ export const clientRouter = createTRPCRouter({
return { ...created.client, secret: created.secret };
}),
- remove: procedure
+ remove: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/cohort/cohort.rpc.ts b/packages/core/src/modules/cohort/cohort.rpc.ts
index 11b40423e..9d2c3c45e 100644
--- a/packages/core/src/modules/cohort/cohort.rpc.ts
+++ b/packages/core/src/modules/cohort/cohort.rpc.ts
@@ -1,18 +1,14 @@
// Ported from packages/trpc/src/routers/cohort.ts (M5-003).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's cohort functions and
-// `ctx.services.cohort` (DELEGATE PATTERN), so nothing here is a live
-// regression.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
-// The per-project access ladder itself IS shared: `./src/access.ts` binds
-// core's shared/access.ts ladder to @openpanel/db's real lookups, the same
-// way packages/trpc/src/access.ts does for V1.
+// The per-project access ladder itself is bound once, in auth.service.ts
+// (M10-002); every procedure here reaches it through `ctx.services.auth`.
//
// CRUD (list/get/create/update/delete) reads/writes Prisma's `cohort` table
// directly, matching V1's router — cohort.service.ts owns only the
@@ -23,7 +19,7 @@
// @openpanel/validation's barrel rather than from cohort.validation.ts.
import { zChartEventFilter } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
import {
zCohortDefinition,
@@ -53,7 +49,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const cohortRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -84,7 +80,7 @@ export const cohortRouter = createTRPCRouter({
return cohorts;
}),
- get: procedure
+ get: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -110,62 +106,66 @@ export const cohortRouter = createTRPCRouter({
// cohort.ts) exactly — protectedProcedure's session check is the only
// gate today. Preserved as found: ADR-011 invariant 1 forbids deleting an
// in-handler check, and this router does not serve live traffic yet.
- create: procedure.input(zCohortInput).mutation(async ({ input, ctx }) => {
- requireLogin(ctx.session.userId);
-
- const db = ctx.db;
- const cohort = await db.cohort.create({
- data: {
- name: input.name,
- description: input.description,
- projectId: input.projectId,
- definition: input.definition,
- isStatic: input.isStatic,
- },
- });
-
- await ctx.services.cohort.enqueueCompute(cohort.id);
-
- return cohort;
- }),
-
- update: procedure.input(zCohortUpdate).mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- const { id, ...data } = input;
-
- const db = ctx.db;
- const existingCohort = await db.cohort.findUnique({ where: { id } });
-
- if (!existingCohort) {
- throw new TRPCNotFoundError('Cohort not found');
- }
-
- await ctx.services.auth.requireProjectAccess({
- userId,
- projectId: existingCohort.projectId,
- level: 'write',
- });
-
- const cohort = await db.cohort.update({
- where: { id },
- data: {
- ...(data.name && { name: data.name }),
- ...(data.description !== undefined && {
- description: data.description,
- }),
- ...(data.definition && { definition: data.definition }),
- ...(data.isStatic !== undefined && { isStatic: data.isStatic }),
- },
- });
-
- if (data.definition) {
+ create: protectedProcedure
+ .input(zCohortInput)
+ .mutation(async ({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+
+ const db = ctx.db;
+ const cohort = await db.cohort.create({
+ data: {
+ name: input.name,
+ description: input.description,
+ projectId: input.projectId,
+ definition: input.definition,
+ isStatic: input.isStatic,
+ },
+ });
+
await ctx.services.cohort.enqueueCompute(cohort.id);
- }
- return cohort;
- }),
+ return cohort;
+ }),
+
+ update: protectedProcedure
+ .input(zCohortUpdate)
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { id, ...data } = input;
+
+ const db = ctx.db;
+ const existingCohort = await db.cohort.findUnique({ where: { id } });
+
+ if (!existingCohort) {
+ throw new TRPCNotFoundError('Cohort not found');
+ }
+
+ await ctx.services.auth.requireProjectAccess({
+ userId,
+ projectId: existingCohort.projectId,
+ level: 'write',
+ });
+
+ const cohort = await db.cohort.update({
+ where: { id },
+ data: {
+ ...(data.name && { name: data.name }),
+ ...(data.description !== undefined && {
+ description: data.description,
+ }),
+ ...(data.definition && { definition: data.definition }),
+ ...(data.isStatic !== undefined && { isStatic: data.isStatic }),
+ },
+ });
+
+ if (data.definition) {
+ await ctx.services.cohort.enqueueCompute(cohort.id);
+ }
+
+ return cohort;
+ }),
- delete: procedure
+ delete: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -193,7 +193,7 @@ export const cohortRouter = createTRPCRouter({
return { success: true };
}),
- listProfiles: procedure
+ listProfiles: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -219,7 +219,7 @@ export const cohortRouter = createTRPCRouter({
};
}),
- mostEvents: procedure
+ mostEvents: protectedProcedure
.input(z.object({ projectId: z.string(), cohortId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -232,7 +232,7 @@ export const cohortRouter = createTRPCRouter({
return getCohortMemberEvents(ctx, input.projectId, input.cohortId);
}),
- eventsPerDay: procedure
+ eventsPerDay: protectedProcedure
.input(z.object({ projectId: z.string(), cohortId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -245,7 +245,7 @@ export const cohortRouter = createTRPCRouter({
return getCohortEventsPerDay(ctx, input.projectId, input.cohortId);
}),
- popularRoutes: procedure
+ popularRoutes: protectedProcedure
.input(z.object({ projectId: z.string(), cohortId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -258,7 +258,7 @@ export const cohortRouter = createTRPCRouter({
return getCohortMemberRoutes(ctx, input.projectId, input.cohortId);
}),
- getCount: procedure
+ getCount: protectedProcedure
.input(z.object({ cohortId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -281,7 +281,7 @@ export const cohortRouter = createTRPCRouter({
return { count };
}),
- preview: procedure
+ preview: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -306,7 +306,7 @@ export const cohortRouter = createTRPCRouter({
return { count, sampleProfiles };
}),
- exportProfiles: procedure
+ exportProfiles: protectedProcedure
.input(
z.object({
cohortId: z.string(),
@@ -353,7 +353,7 @@ export const cohortRouter = createTRPCRouter({
};
}),
- refresh: procedure
+ refresh: protectedProcedure
.input(z.object({ cohortId: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/conversation/conversation.rpc.ts b/packages/core/src/modules/conversation/conversation.rpc.ts
index 71ee750b1..530f43096 100644
--- a/packages/core/src/modules/conversation/conversation.rpc.ts
+++ b/packages/core/src/modules/conversation/conversation.rpc.ts
@@ -1,21 +1,19 @@
// Ported from packages/trpc/src/routers/conversation.ts (M5-006).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's conversation functions
-// (DELEGATE PATTERN). `ctx.services.conversation` carries this module's
-// factory the same as every other module now (M10-004).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
-// The per-project access ladder itself IS shared: `./src/access.ts` binds
-// core's shared/access.ts ladder to @openpanel/db's real lookups, the same
-// way packages/trpc/src/access.ts does for V1.
+// `ctx.services.conversation` carries this module's factory (M10-004).
+//
+// The per-project access ladder itself is bound once, in auth.service.ts
+// (M10-002); every procedure here reaches it through `ctx.services.auth`.
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
import { getOrganizationByProjectIdCached } from '../organization/organization.service';
@@ -41,7 +39,7 @@ function requireLogin(userId: string | null | undefined): string {
* user can never read or mutate another user's conversations.
*/
export const conversationRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -67,7 +65,7 @@ export const conversationRouter = createTRPCRouter({
});
}),
- get: procedure
+ get: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -81,7 +79,7 @@ export const conversationRouter = createTRPCRouter({
return conv;
}),
- rename: procedure
+ rename: protectedProcedure
// A conversation belongs to the caller, not to the project - titling your
// own chat is not a project mutation. Ownership is enforced below.
.meta({ readOnlyMutation: true })
@@ -140,7 +138,7 @@ export const conversationRouter = createTRPCRouter({
});
}),
- delete: procedure
+ delete: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/dashboard/dashboard.rpc.ts b/packages/core/src/modules/dashboard/dashboard.rpc.ts
index 5bc8cc5f9..9e9d3c6c3 100644
--- a/packages/core/src/modules/dashboard/dashboard.rpc.ts
+++ b/packages/core/src/modules/dashboard/dashboard.rpc.ts
@@ -1,16 +1,22 @@
// Ported from packages/trpc/src/routers/dashboard.ts (M7-006).
//
-// Same arrangement as project.rpc.ts: V1's `protectedProcedure` lands in
-// core with auth (rpc/base.ts), so each procedure does its own "is anyone
-// logged in" + `requireProjectAccess` check, reached through
-// `ctx.services.auth` (M10-002). The create/update/delete mutation bodies
-// moved to ./dashboard.service alongside the reads that already lived there;
-// packages/trpc's dashboard router delegates every handler body onto
-// ./dashboard.service while keeping V1's own procedure stack (DELEGATE
-// PATTERN).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
+//
+// The dashboardId-keyed procedures are invisible to `enforceAccess`; their
+// in-handler `requireProjectAccess` through `ctx.services.auth` (M10-002) is
+// the only check that fires.
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
function requireLogin(userId: string | null | undefined): string {
@@ -37,7 +43,7 @@ async function requireWriteAccess(ctx: TrpcContext, projectId: string) {
}
export const dashboardRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -48,7 +54,7 @@ export const dashboardRouter = createTRPCRouter({
return ctx.services.dashboard.getDashboardsByProjectId(input.projectId);
}),
- byId: procedure
+ byId: protectedProcedure
.input(
z.object({
id: z.string(),
@@ -70,7 +76,7 @@ export const dashboardRouter = createTRPCRouter({
return dashboard;
}),
- create: procedure
+ create: protectedProcedure
.input(
z.object({
name: z.string(),
@@ -82,7 +88,7 @@ export const dashboardRouter = createTRPCRouter({
return ctx.services.dashboard.createDashboard(input);
}),
- update: procedure
+ update: protectedProcedure
.input(
z.object({
id: z.string(),
@@ -97,7 +103,7 @@ export const dashboardRouter = createTRPCRouter({
return ctx.services.dashboard.updateDashboard(input);
}),
- delete: procedure
+ delete: protectedProcedure
.input(
z.object({
id: z.string(),
diff --git a/packages/core/src/modules/email/email.rpc.ts b/packages/core/src/modules/email/email.rpc.ts
index ade8d22dc..cb245f3cf 100644
--- a/packages/core/src/modules/email/email.rpc.ts
+++ b/packages/core/src/modules/email/email.rpc.ts
@@ -7,15 +7,15 @@
// `clients/email.ts` already wraps that package for the one thing this
// module doesn't need — sending.
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's `verifyUnsubscribeToken` +
-// `emailCategories` (DELEGATE PATTERN) — this module has no queue/cron of
-// its own, so there is no `ctx.services.email`, same as `user`/`reference`.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
+//
+// This module has no queue/cron of its own, so there is no
+// `ctx.services.email`, same as `user`/`reference`.
//
// `verifyUnsubscribeToken` is imported from @openpanel/email's own
// `unsubscribe.ts` file, not its barrel: the barrel (`@openpanel/email` ->
@@ -26,7 +26,11 @@
import { verifyUnsubscribeToken } from '@openpanel/email/src/unsubscribe';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCBadRequestError } from '../../rpc/errors';
import { emailCategories } from './email.constants';
@@ -38,7 +42,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const emailRouter = createTRPCRouter({
- unsubscribe: procedure
+ unsubscribe: publicProcedure
.input(
z.object({
email: z.string().email(),
@@ -63,7 +67,7 @@ export const emailRouter = createTRPCRouter({
return { success: true };
}),
- getPreferences: procedure.query(async ({ ctx }) => {
+ getPreferences: protectedProcedure.query(async ({ ctx }) => {
requireLogin(ctx.session.userId);
if (!ctx.session.user?.email) {
throw new Error('User not authenticated');
@@ -84,7 +88,7 @@ export const emailRouter = createTRPCRouter({
return preferences;
}),
- updatePreferences: procedure
+ updatePreferences: protectedProcedure
.input(z.object({ categories: z.record(z.string(), z.boolean()) }))
.mutation(async ({ input, ctx }) => {
requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/event/event.rpc.test.ts b/packages/core/src/modules/event/event.rpc.test.ts
index e77c7f68a..aa3b1fbcd 100644
--- a/packages/core/src/modules/event/event.rpc.test.ts
+++ b/packages/core/src/modules/event/event.rpc.test.ts
@@ -5,7 +5,10 @@
// Same shape as session.rpc.test.ts.
import { expect, test } from 'bun:test';
-import { stubHttpCtx } from '../../../test/rpc-fixtures';
+import {
+ servicesWithProjectAccess,
+ stubHttpCtx,
+} from '../../../test/rpc-fixtures';
import { makeTrpcContext } from '../../rpc/base';
import type { CookieOptions } from '../../shared/cookie';
import { eventRouter } from './event.rpc';
@@ -31,6 +34,18 @@ async function anonCaller() {
return eventRouter.createCaller(trpcCtx);
}
+/**
+ * A signed-in member. `protectedProcedure` authenticates and authorizes
+ * before the input parser runs, so reaching a zod rejection needs both.
+ */
+async function memberCaller() {
+ const { ctx } = stubHttpCtx({ services: servicesWithProjectAccess() });
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return eventRouter.createCaller(trpcCtx);
+}
+
const UNAUTHORIZED = { code: 'UNAUTHORIZED' };
test('every query rejects an unauthenticated caller before touching a database', async () => {
@@ -70,7 +85,7 @@ test('updateEventMeta rejects an unauthenticated caller before touching Postgres
});
test('events rejects a malformed filter at the input boundary', async () => {
- const caller = await anonCaller();
+ const caller = await memberCaller();
await expect(
caller.events({ ...PROJECT, filters: [{ bogus: true }] as never })
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
diff --git a/packages/core/src/modules/event/event.rpc.ts b/packages/core/src/modules/event/event.rpc.ts
index de6aefbf4..cc012881f 100644
--- a/packages/core/src/modules/event/event.rpc.ts
+++ b/packages/core/src/modules/event/event.rpc.ts
@@ -1,11 +1,11 @@
// Ported from packages/trpc/src/routers/event.ts (M7-002).
//
-// Same arrangement as session.rpc.ts: V1's `protectedProcedure` stack lands
-// with auth (P6), so until then each procedure does its own "is anyone logged
-// in" + `requireProjectAccess` off the `projectId` input (`read` for queries,
-// `write` for `updateEventMeta`). packages/trpc's event router delegates its
-// handler bodies onto `./event.service` while keeping V1's own
-// `protectedProcedure` stack.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// `bots` was V1's only `publicProcedure` here (anonymous callers were let in
// when a share-overview row existed); ADR-011 makes it protected.
@@ -21,7 +21,11 @@ import {
zTimeInterval,
} from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
import { getChartStartEndDate } from '../../shared/date';
import { getSettingsForProject } from '../organization/organization.service';
@@ -74,7 +78,7 @@ function formatClickhouseDateTime(date: Date): string {
}
export const eventRouter = createTRPCRouter({
- updateEventMeta: procedure
+ updateEventMeta: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -90,7 +94,7 @@ export const eventRouter = createTRPCRouter({
return updateEventMeta(ctx, input);
}),
- byId: procedure.input(zEventRef).query(async ({ input, ctx }) => {
+ byId: protectedProcedure.input(zEventRef).query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
const event = await getEventById(ctx, input);
@@ -100,7 +104,7 @@ export const eventRouter = createTRPCRouter({
return event;
}),
- details: procedure.input(zEventRef).query(async ({ input, ctx }) => {
+ details: protectedProcedure.input(zEventRef).query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
const details = await getEventDetails(ctx, input);
@@ -110,7 +114,7 @@ export const eventRouter = createTRPCRouter({
return details;
}),
- events: procedure
+ events: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -132,7 +136,7 @@ export const eventRouter = createTRPCRouter({
return getEventListPage(ctx, input);
}),
- conversionNames: procedure
+ conversionNames: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
@@ -140,7 +144,7 @@ export const eventRouter = createTRPCRouter({
return getConversionEventNames(ctx, input.projectId);
}),
- conversions: procedure
+ conversions: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -157,7 +161,7 @@ export const eventRouter = createTRPCRouter({
return getConversionListPage(ctx, input);
}),
- bots: procedure
+ bots: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -171,7 +175,7 @@ export const eventRouter = createTRPCRouter({
return getBotEventsPage(ctx, input);
}),
- pages: procedure
+ pages: protectedProcedure
.input(
zChartWindow.extend({
cursor: z.number().optional(),
@@ -194,7 +198,7 @@ export const eventRouter = createTRPCRouter({
});
}),
- pagesTimeseries: procedure
+ pagesTimeseries: protectedProcedure
.input(zChartWindow)
.query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
@@ -210,27 +214,29 @@ export const eventRouter = createTRPCRouter({
});
}),
- previousPages: procedure.input(zChartWindow).query(async ({ input, ctx }) => {
- await requireAccess(ctx, input.projectId, 'read');
+ previousPages: protectedProcedure
+ .input(zChartWindow)
+ .query(async ({ input, ctx }) => {
+ await requireAccess(ctx, input.projectId, 'read');
- const { timezone } = await getSettingsForProject(ctx, input.projectId);
- const { startDate, endDate } = getChartStartEndDate(input, timezone);
-
- const startMs = new Date(startDate).getTime();
- const endMs = new Date(endDate).getTime();
- const duration = endMs - startMs;
- const previousEnd = new Date(startMs - 1);
- const previousStart = new Date(previousEnd.getTime() - duration);
-
- return ctx.services.pages.getTopPages({
- projectId: input.projectId,
- startDate: formatClickhouseDateTime(previousStart),
- endDate: formatClickhouseDateTime(previousEnd),
- timezone,
- });
- }),
+ const { timezone } = await getSettingsForProject(ctx, input.projectId);
+ const { startDate, endDate } = getChartStartEndDate(input, timezone);
+
+ const startMs = new Date(startDate).getTime();
+ const endMs = new Date(endDate).getTime();
+ const duration = endMs - startMs;
+ const previousEnd = new Date(startMs - 1);
+ const previousStart = new Date(previousEnd.getTime() - duration);
+
+ return ctx.services.pages.getTopPages({
+ projectId: input.projectId,
+ startDate: formatClickhouseDateTime(previousStart),
+ endDate: formatClickhouseDateTime(previousEnd),
+ timezone,
+ });
+ }),
- pageTimeseries: procedure
+ pageTimeseries: protectedProcedure
.input(zChartWindow.extend({ origin: z.string(), path: z.string() }))
.query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
@@ -248,7 +254,7 @@ export const eventRouter = createTRPCRouter({
});
}),
- origin: procedure
+ origin: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
diff --git a/packages/core/src/modules/group/group.rpc.test.ts b/packages/core/src/modules/group/group.rpc.test.ts
index 9003fbf07..391a7be71 100644
--- a/packages/core/src/modules/group/group.rpc.test.ts
+++ b/packages/core/src/modules/group/group.rpc.test.ts
@@ -5,7 +5,10 @@
// Same shape as session.rpc.test.ts.
import { expect, test } from 'bun:test';
-import { stubHttpCtx } from '../../../test/rpc-fixtures';
+import {
+ servicesWithProjectAccess,
+ stubHttpCtx,
+} from '../../../test/rpc-fixtures';
import { makeTrpcContext } from '../../rpc/base';
import type { CookieOptions } from '../../shared/cookie';
import { groupRouter } from './group.rpc';
@@ -29,6 +32,18 @@ async function anonCaller() {
return groupRouter.createCaller(trpcCtx);
}
+/**
+ * A signed-in member. `protectedProcedure` authenticates and authorizes
+ * before the input parser runs, so reaching a zod rejection needs both.
+ */
+async function memberCaller() {
+ const { ctx } = stubHttpCtx({ services: servicesWithProjectAccess() });
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return groupRouter.createCaller(trpcCtx);
+}
+
const UNAUTHORIZED = { code: 'UNAUTHORIZED' };
test('every query rejects an unauthenticated caller before touching a database', async () => {
@@ -68,7 +83,7 @@ test('every mutation rejects an unauthenticated caller before touching a databas
});
test('create rejects an id outside zGroupId at the input boundary', async () => {
- const caller = await anonCaller();
+ const caller = await memberCaller();
await expect(
caller.create({
id: 'Not Valid',
diff --git a/packages/core/src/modules/group/group.rpc.ts b/packages/core/src/modules/group/group.rpc.ts
index 27259eff9..7e4226494 100644
--- a/packages/core/src/modules/group/group.rpc.ts
+++ b/packages/core/src/modules/group/group.rpc.ts
@@ -1,15 +1,18 @@
// Ported from packages/trpc/src/routers/group.ts (M7-002).
//
-// Same arrangement as session.rpc.ts: V1's `protectedProcedure` stack lands
-// with auth (P6), so until then each procedure does its own "is anyone logged
-// in" + `requireProjectAccess` off the `projectId` input (`read` for queries,
-// `write` for the three mutations), which is what V1's `enforceUserIsAuthed`
-// + `enforceAccess` middleware pair does implicitly. packages/trpc's group
-// router delegates its handler bodies onto `./group.service` while keeping
-// V1's own `protectedProcedure` stack.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import { zCreateGroup, zUpdateGroup } from './group.constants';
import {
@@ -53,7 +56,7 @@ async function requireAccess(
}
export const groupRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -69,32 +72,38 @@ export const groupRouter = createTRPCRouter({
return getGroupListPage(ctx, input);
}),
- byId: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
+ byId: protectedProcedure.input(zGroupRef).query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
return getGroupById(ctx, input.id, input.projectId);
}),
- create: procedure.input(zCreateGroup).mutation(async ({ input, ctx }) => {
- await requireAccess(ctx, input.projectId, 'write');
+ create: protectedProcedure
+ .input(zCreateGroup)
+ .mutation(async ({ input, ctx }) => {
+ await requireAccess(ctx, input.projectId, 'write');
- return createGroup(ctx, input);
- }),
+ return createGroup(ctx, input);
+ }),
- update: procedure.input(zUpdateGroup).mutation(async ({ input, ctx }) => {
- await requireAccess(ctx, input.projectId, 'write');
+ update: protectedProcedure
+ .input(zUpdateGroup)
+ .mutation(async ({ input, ctx }) => {
+ await requireAccess(ctx, input.projectId, 'write');
- const { id, projectId, ...data } = input;
- return updateGroup(ctx, id, projectId, data);
- }),
+ const { id, projectId, ...data } = input;
+ return updateGroup(ctx, id, projectId, data);
+ }),
- delete: procedure.input(zGroupRef).mutation(async ({ input, ctx }) => {
- await requireAccess(ctx, input.projectId, 'write');
+ delete: protectedProcedure
+ .input(zGroupRef)
+ .mutation(async ({ input, ctx }) => {
+ await requireAccess(ctx, input.projectId, 'write');
- return deleteGroup(ctx, input.id, input.projectId);
- }),
+ return deleteGroup(ctx, input.id, input.projectId);
+ }),
- types: procedure
+ types: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
@@ -102,25 +111,29 @@ export const groupRouter = createTRPCRouter({
return getGroupTypes(ctx, input.projectId);
}),
- metrics: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
+ metrics: protectedProcedure.input(zGroupRef).query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
return getGroupMetrics(ctx, input.id, input.projectId);
}),
- activity: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- await requireAccess(ctx, input.projectId, 'read');
+ activity: protectedProcedure
+ .input(zGroupRef)
+ .query(async ({ input, ctx }) => {
+ await requireAccess(ctx, input.projectId, 'read');
- return getGroupActivity(ctx, input.id, input.projectId);
- }),
+ return getGroupActivity(ctx, input.id, input.projectId);
+ }),
- memberGrowth: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- await requireAccess(ctx, input.projectId, 'read');
+ memberGrowth: protectedProcedure
+ .input(zGroupRef)
+ .query(async ({ input, ctx }) => {
+ await requireAccess(ctx, input.projectId, 'read');
- return getGroupMemberGrowth(ctx, input.id, input.projectId);
- }),
+ return getGroupMemberGrowth(ctx, input.id, input.projectId);
+ }),
- listProfiles: procedure
+ listProfiles: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -136,19 +149,23 @@ export const groupRouter = createTRPCRouter({
return getGroupMemberProfilesPage(ctx, input);
}),
- mostEvents: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- await requireAccess(ctx, input.projectId, 'read');
+ mostEvents: protectedProcedure
+ .input(zGroupRef)
+ .query(async ({ input, ctx }) => {
+ await requireAccess(ctx, input.projectId, 'read');
- return getGroupMostEvents(ctx, input.id, input.projectId);
- }),
+ return getGroupMostEvents(ctx, input.id, input.projectId);
+ }),
- popularRoutes: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- await requireAccess(ctx, input.projectId, 'read');
+ popularRoutes: protectedProcedure
+ .input(zGroupRef)
+ .query(async ({ input, ctx }) => {
+ await requireAccess(ctx, input.projectId, 'read');
- return getGroupPopularRoutes(ctx, input.id, input.projectId);
- }),
+ return getGroupPopularRoutes(ctx, input.id, input.projectId);
+ }),
- properties: procedure
+ properties: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
@@ -156,7 +173,7 @@ export const groupRouter = createTRPCRouter({
return getGroupPropertyKeys(ctx, input.projectId);
}),
- listByIds: procedure
+ listByIds: protectedProcedure
.input(z.object({ projectId: z.string(), ids: z.array(z.string()) }))
.query(async ({ input, ctx }) => {
await requireAccess(ctx, input.projectId, 'read');
diff --git a/packages/core/src/modules/gsc/gsc.rpc.ts b/packages/core/src/modules/gsc/gsc.rpc.ts
index aaa5ce23a..e2de6ffef 100644
--- a/packages/core/src/modules/gsc/gsc.rpc.ts
+++ b/packages/core/src/modules/gsc/gsc.rpc.ts
@@ -1,20 +1,22 @@
// Ported from packages/trpc/src/routers/gsc.ts (M5-002).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to `ctx.services.gsc` (DELEGATE PATTERN),
-// so nothing here is a live regression.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// The per-project access ladder itself is bound once, in auth.service.ts
// (M10-002); every procedure here reaches it through `ctx.services.auth`.
import { zRange, zTimeInterval } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import { Arctic, googleGsc } from '../auth/auth.service';
@@ -62,14 +64,14 @@ async function requireWrite(ctx: TrpcContext, projectId: string) {
}
export const gscRouter = createTRPCRouter({
- getConnection: procedure
+ getConnection: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input: { projectId }, ctx }) => {
await requireRead(ctx, projectId);
return ctx.services.gsc.getConnection(projectId);
}),
- initiateOAuth: procedure
+ initiateOAuth: protectedProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input: { projectId }, ctx }) => {
await requireWrite(ctx, projectId);
@@ -90,14 +92,14 @@ export const gscRouter = createTRPCRouter({
return { url: url.toString() };
}),
- getSites: procedure
+ getSites: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input: { projectId }, ctx }) => {
await requireRead(ctx, projectId);
return ctx.services.gsc.listSites(projectId);
}),
- selectSite: procedure
+ selectSite: protectedProcedure
.input(z.object({ projectId: z.string(), siteUrl: z.string() }))
.mutation(async ({ input: { projectId, siteUrl }, ctx }) => {
await requireWrite(ctx, projectId);
@@ -106,7 +108,7 @@ export const gscRouter = createTRPCRouter({
return { ok: true };
}),
- disconnect: procedure
+ disconnect: protectedProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input: { projectId }, ctx }) => {
await requireWrite(ctx, projectId);
@@ -115,21 +117,23 @@ export const gscRouter = createTRPCRouter({
return { ok: true };
}),
- getOverview: procedure.input(zGscDateInput).query(async ({ input, ctx }) => {
- await requireRead(ctx, input.projectId);
- const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
- input.projectId,
- input
- );
- return ctx.services.gsc.getOverview(
- input.projectId,
- startDate,
- endDate,
- toOverviewInterval(input.interval)
- );
- }),
+ getOverview: protectedProcedure
+ .input(zGscDateInput)
+ .query(async ({ input, ctx }) => {
+ await requireRead(ctx, input.projectId);
+ const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
+ input.projectId,
+ input
+ );
+ return ctx.services.gsc.getOverview(
+ input.projectId,
+ startDate,
+ endDate,
+ toOverviewInterval(input.interval)
+ );
+ }),
- getPages: procedure
+ getPages: protectedProcedure
.input(
zGscDateInput.extend({
limit: z.number().min(1).max(10_000).optional().default(100),
@@ -149,7 +153,7 @@ export const gscRouter = createTRPCRouter({
);
}),
- getPageDetails: procedure
+ getPageDetails: protectedProcedure
.input(zGscDateInput.extend({ page: z.string() }))
.query(async ({ input, ctx }) => {
await requireRead(ctx, input.projectId);
@@ -165,7 +169,7 @@ export const gscRouter = createTRPCRouter({
);
}),
- getQueryDetails: procedure
+ getQueryDetails: protectedProcedure
.input(zGscDateInput.extend({ query: z.string() }))
.query(async ({ input, ctx }) => {
await requireRead(ctx, input.projectId);
@@ -181,7 +185,7 @@ export const gscRouter = createTRPCRouter({
);
}),
- getQueries: procedure
+ getQueries: protectedProcedure
.input(
zGscDateInput.extend({
limit: z.number().min(1).max(1000).optional().default(100),
@@ -201,7 +205,7 @@ export const gscRouter = createTRPCRouter({
);
}),
- getSearchEngines: procedure
+ getSearchEngines: protectedProcedure
.input(zGscDateInput)
.query(async ({ input, ctx }) => {
await requireRead(ctx, input.projectId);
@@ -216,16 +220,18 @@ export const gscRouter = createTRPCRouter({
);
}),
- getAiEngines: procedure.input(zGscDateInput).query(async ({ input, ctx }) => {
- await requireRead(ctx, input.projectId);
- const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
- input.projectId,
- input
- );
- return ctx.services.gsc.getAiEngines(input.projectId, startDate, endDate);
- }),
+ getAiEngines: protectedProcedure
+ .input(zGscDateInput)
+ .query(async ({ input, ctx }) => {
+ await requireRead(ctx, input.projectId);
+ const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
+ input.projectId,
+ input
+ );
+ return ctx.services.gsc.getAiEngines(input.projectId, startDate, endDate);
+ }),
- getPreviousOverview: procedure
+ getPreviousOverview: protectedProcedure
.input(zGscDateInput)
.query(async ({ input, ctx }) => {
await requireRead(ctx, input.projectId);
@@ -241,7 +247,7 @@ export const gscRouter = createTRPCRouter({
);
}),
- getCannibalization: procedure
+ getCannibalization: protectedProcedure
.input(zGscDateInput)
.query(async ({ input, ctx }) => {
await requireRead(ctx, input.projectId);
diff --git a/packages/core/src/modules/health/health.rpc.ts b/packages/core/src/modules/health/health.rpc.ts
index 0bc45867f..0f2175617 100644
--- a/packages/core/src/modules/health/health.rpc.ts
+++ b/packages/core/src/modules/health/health.rpc.ts
@@ -1,10 +1,10 @@
// The one procedure `rpc.router.ts` mounts before the first real module lands
// (ADR-007 decision 19) — proves the tRPC surface composes end to end. No V1
-// router named `health` exists; the 28 real ones arrive with their module
-// waves (P5-P8).
+// router named `health` exists; the 28 real ones arrived with their module
+// waves (P5-P8). Public, as a liveness probe has to be.
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, publicProcedure } from '../../rpc/base';
export const healthRouter = createTRPCRouter({
- live: procedure.query(() => ({ live: true as const })),
+ live: publicProcedure.query(() => ({ live: true as const })),
});
diff --git a/packages/core/src/modules/import/import.rpc.ts b/packages/core/src/modules/import/import.rpc.ts
index c498651bd..a37532a07 100644
--- a/packages/core/src/modules/import/import.rpc.ts
+++ b/packages/core/src/modules/import/import.rpc.ts
@@ -1,22 +1,22 @@
// Ported from packages/trpc/src/routers/import.ts (M5-004).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed` (same as cohort.rpc.ts / gsc.rpc.ts).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// V1's router has no compute-heavy or ClickHouse-touching logic to delegate
// (it is Prisma CRUD + a BullMQ enqueue, unlike gsc/cohort), so
// packages/trpc/src/routers/import.ts stays completely unmodified — there is
-// nothing here for it to delegate to. This router exists to satisfy the
-// module map ("R") and to serve core's own (not yet live) appRouter.
+// nothing here for it to delegate to.
//
// The per-project access ladder itself is bound once, in auth.service.ts
// (M10-002); every procedure here reaches it through `ctx.services.auth`.
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import {
TRPCAccessError,
TRPCBadRequestError,
@@ -32,7 +32,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const importRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -49,7 +49,7 @@ export const importRouter = createTRPCRouter({
});
}),
- get: procedure
+ get: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -68,50 +68,52 @@ export const importRouter = createTRPCRouter({
return importRecord;
}),
- create: procedure.input(zCreateImport).mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await ctx.services.auth.requireProjectAccess({
- userId,
- projectId: input.projectId,
- level: 'write',
- });
-
- const db = ctx.db;
- const organization = await db.organization.findFirst({
- where: { projects: { some: { id: input.projectId } } },
- });
-
- if (!organization) {
- throw new TRPCNotFoundError(
- 'Could not start import, organization not found'
- );
- }
-
- if (!organization.isActive) {
- throw new TRPCBadRequestError(
- 'You cannot start an import without an active subscription!'
- );
- }
-
- const importRecord = await db.import.create({
- data: {
+ create: protectedProcedure
+ .input(zCreateImport)
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ await ctx.services.auth.requireProjectAccess({
+ userId,
projectId: input.projectId,
- config: input.config,
- status: 'pending',
- },
- });
+ level: 'write',
+ });
- const jobId = await ctx.services.import.enqueue(importRecord.id);
+ const db = ctx.db;
+ const organization = await db.organization.findFirst({
+ where: { projects: { some: { id: input.projectId } } },
+ });
- await db.import.update({
- where: { id: importRecord.id },
- data: { jobId },
- });
+ if (!organization) {
+ throw new TRPCNotFoundError(
+ 'Could not start import, organization not found'
+ );
+ }
- return { ...importRecord, jobId };
- }),
+ if (!organization.isActive) {
+ throw new TRPCBadRequestError(
+ 'You cannot start an import without an active subscription!'
+ );
+ }
+
+ const importRecord = await db.import.create({
+ data: {
+ projectId: input.projectId,
+ config: input.config,
+ status: 'pending',
+ },
+ });
+
+ const jobId = await ctx.services.import.enqueue(importRecord.id);
+
+ await db.import.update({
+ where: { id: importRecord.id },
+ data: { jobId },
+ });
+
+ return { ...importRecord, jobId };
+ }),
- delete: procedure
+ delete: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -133,7 +135,7 @@ export const importRouter = createTRPCRouter({
return db.import.delete({ where: { id: input.id } });
}),
- retry: procedure
+ retry: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/insight/insight.rpc.ts b/packages/core/src/modules/insight/insight.rpc.ts
index d28d8e3cc..d458592a4 100644
--- a/packages/core/src/modules/insight/insight.rpc.ts
+++ b/packages/core/src/modules/insight/insight.rpc.ts
@@ -1,20 +1,18 @@
// Ported from packages/trpc/src/routers/insight.ts (M5-001).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to `ctx.services.insight` (DELEGATE PATTERN),
-// so nothing here is a live regression.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// The permission ladder itself is bound once, in auth.service.ts
// (M10-002); every procedure here reaches it through `ctx.services.auth`.
import type { InsightPayload } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -33,7 +31,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const insightRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -89,7 +87,7 @@ export const insightRouter = createTRPCRouter({
.map(({ impactScore, ...rest }) => rest); // strip impactScore from the response
}),
- listAll: procedure
+ listAll: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -111,7 +109,7 @@ export const insightRouter = createTRPCRouter({
// country/device/utm (current vs baseline window), pull nearby references,
// and have the AI explain which sub-segment drove it. Cached per insight
// version so repeat clicks don't re-bill the LLM.
- explain: procedure
+ explain: protectedProcedure
.input(z.object({ insightId: z.string() }))
.mutation(async ({ input: { insightId }, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/integration/integration.rpc.ts b/packages/core/src/modules/integration/integration.rpc.ts
index dde4878ce..eeb67d237 100644
--- a/packages/core/src/modules/integration/integration.rpc.ts
+++ b/packages/core/src/modules/integration/integration.rpc.ts
@@ -1,20 +1,18 @@
// Ported from packages/trpc/src/routers/integration.ts (M6-006).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's integration functions (DELEGATE
-// PATTERN), so nothing here is a live regression.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// Every access assertion (including the data-dependent "authorize against the
// EXISTING row" rule) lives in integration.service.ts, not here — see that
// file's header for why.
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
zCreateGCSExportIntegration,
@@ -40,13 +38,13 @@ function requireLogin(userId: string | null | undefined): string {
}
export const integrationRouter = createTRPCRouter({
- get: procedure
+ get: protectedProcedure
.input(z.object({ id: z.string() }))
.query(({ input, ctx }) =>
getIntegrationById(ctx, requireLogin(ctx.session.userId), input.id)
),
- list: procedure
+ list: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(({ input, ctx }) =>
listIntegrationsForProject(
@@ -56,7 +54,7 @@ export const integrationRouter = createTRPCRouter({
)
),
- createOrUpdateSlack: procedure
+ createOrUpdateSlack: protectedProcedure
.input(zCreateSlackIntegration)
.mutation(({ input, ctx }) =>
createOrUpdateSlackIntegration(
@@ -68,7 +66,7 @@ export const integrationRouter = createTRPCRouter({
// Generic create/update for any form-configured integration. Per-type
// behavior lives in the server plugin; no switch here.
- createOrUpdate: procedure
+ createOrUpdate: protectedProcedure
.input(
z.object({
id: z.string().optional(),
@@ -83,13 +81,13 @@ export const integrationRouter = createTRPCRouter({
// Back-compat alias for the export forms; delegates to the same generic path.
// TODO: remove once the dashboard calls `createOrUpdate` directly.
- createOrUpdateExport: procedure
+ createOrUpdateExport: protectedProcedure
.input(z.union([zCreateS3ExportIntegration, zCreateGCSExportIntegration]))
.mutation(({ input, ctx }) =>
upsertIntegration(ctx, requireLogin(ctx.session.userId), input)
),
- testConnection: procedure
+ testConnection: protectedProcedure
.input(
z.object({
projectId: z.string().min(1),
@@ -102,7 +100,7 @@ export const integrationRouter = createTRPCRouter({
// Back-compat alias for the export forms; same gate as `testConnection`.
// TODO: remove once the dashboard calls `testConnection` directly.
- testExportConnection: procedure
+ testExportConnection: protectedProcedure
.input(z.union([zCreateS3ExportIntegration, zCreateGCSExportIntegration]))
.mutation(({ input, ctx }) =>
testExportIntegrationConnection(
@@ -112,7 +110,7 @@ export const integrationRouter = createTRPCRouter({
)
),
- delete: procedure
+ delete: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(({ input: { id }, ctx }) =>
deleteIntegration(ctx, requireLogin(ctx.session.userId), id)
diff --git a/packages/core/src/modules/notification/notification.rpc.ts b/packages/core/src/modules/notification/notification.rpc.ts
index 8fb818ad6..cb42d9e58 100644
--- a/packages/core/src/modules/notification/notification.rpc.ts
+++ b/packages/core/src/modules/notification/notification.rpc.ts
@@ -1,13 +1,11 @@
// Ported from packages/trpc/src/routers/notification.ts (M6-005).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's notification functions (DELEGATE
-// PATTERN), so nothing here is a live regression.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// `list`/`rules` have no access check here either — same gap V1's router has
// (ported verbatim, not fixed; see notification.service.ts's header for why
@@ -18,7 +16,7 @@
// (M10-002); every procedure here reaches it through `ctx.services.auth`.
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import { zCreateNotificationRule } from './notification.constants';
import {
@@ -38,21 +36,21 @@ function requireLogin(userId: string | null | undefined): string {
}
export const notificationRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(({ input, ctx }) => {
requireLogin(ctx.session.userId);
return listNotifications(ctx, input.projectId);
}),
- rules: procedure
+ rules: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(({ input, ctx }) => {
requireLogin(ctx.session.userId);
return listNotificationRules(ctx, input.projectId);
}),
- createOrUpdateRule: procedure
+ createOrUpdateRule: protectedProcedure
.input(zCreateNotificationRule)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -78,7 +76,7 @@ export const notificationRouter = createTRPCRouter({
return createOrUpdateNotificationRule(ctx, input);
}),
- deleteRule: procedure
+ deleteRule: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/onboarding/onboarding.rpc.ts b/packages/core/src/modules/onboarding/onboarding.rpc.ts
index afaab9698..503229a08 100644
--- a/packages/core/src/modules/onboarding/onboarding.rpc.ts
+++ b/packages/core/src/modules/onboarding/onboarding.rpc.ts
@@ -1,24 +1,23 @@
// Ported from packages/trpc/src/routers/onboarding.ts (M6-003).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed` — same shape as
-// organization.rpc.ts/project.rpc.ts. `project`'s input can carry an
-// existing `organizationId`, which V1's generic `enforceAccess` middleware
-// gates on membership (not admin — joining an org you already belong to
-// needs no more than that); this router does the same check explicitly,
-// through the organization module's own db-bound lookup (dynamically
-// imported, same as organization.rpc.ts's `./src/access`).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
-// V1 keeps serving the live route through packages/trpc's own
-// `protectedProcedure`/`publicProcedure` and delegates every handler body to
-// `./onboarding.service` (DELEGATE PATTERN) — the same functions this router
-// calls.
+// `project`'s input can carry an existing `organizationId`, which
+// `enforceAccess` gates on membership (not admin — joining an org you
+// already belong to needs no more than that); this router repeats the check
+// explicitly through the organization module's own lookup.
import { zOnboardingProject } from '@openpanel/validation';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
import {
canSkipOnboarding,
@@ -37,11 +36,11 @@ function requireLogin(userId: string | null | undefined): string {
}
export const onboardingRouter = createTRPCRouter({
- skipOnboardingCheck: procedure.query(({ ctx }) =>
+ skipOnboardingCheck: publicProcedure.query(({ ctx }) =>
canSkipOnboarding(ctx, ctx.session.userId)
),
- project: procedure
+ project: protectedProcedure
.input(zOnboardingProject)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/organization/organization.rpc.ts b/packages/core/src/modules/organization/organization.rpc.ts
index 950eb268f..87ffa15c2 100644
--- a/packages/core/src/modules/organization/organization.rpc.ts
+++ b/packages/core/src/modules/organization/organization.rpc.ts
@@ -1,20 +1,18 @@
// Ported from packages/trpc/src/routers/organization.ts (M6-001).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to `ctx.services.organization` (DELEGATE
-// PATTERN), so nothing here is a live regression.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// The organization-admin ladder itself is bound once, in auth.service.ts
// (M10-002); every procedure here reaches it through `ctx.services.auth`.
//
-// `getInvite` drops V1's rate limiting (packages/trpc's `rateLimitMiddleware`
-// lands with auth, same as `protectedProcedure` above) — V1 keeps enforcing
-// it on the live route through its own copy of this router.
+// `getInvite` still drops V1's rate limiting: `rateLimitMiddleware` did NOT
+// move with M11-001. `createRateLimitMiddleware` in rpc/base.ts is the seam
+// that will carry it.
import {
zEditOrganization,
@@ -22,7 +20,13 @@ import {
zUpdateMemberAccess,
} from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ protectedProcedureWithoutAccess,
+ publicProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import {
TRPCAccessError,
TRPCBadRequestError,
@@ -44,14 +48,14 @@ async function requireOrgAdmin(ctx: TrpcContext, organizationId: string) {
}
export const organizationRouter = createTRPCRouter({
- get: procedure
+ get: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.query(async ({ input, ctx }) => {
requireLogin(ctx.session.userId);
return ctx.services.organization.get(input.organizationId);
}),
- list: procedure.query(async ({ ctx }) => {
+ list: protectedProcedure.query(async ({ ctx }) => {
const userId = requireLogin(ctx.session.userId);
return ctx.services.organization.list(userId);
}),
@@ -59,7 +63,7 @@ export const organizationRouter = createTRPCRouter({
// Membership-exempt on purpose: any logged-in user may ask whether they have
// access to a given org. Returns null when they're not a member (instead of
// throwing), which the org-layout guard uses to render a not-found page.
- myAccess: procedure
+ myAccess: protectedProcedureWithoutAccess
.input(z.object({ organizationId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -73,14 +77,14 @@ export const organizationRouter = createTRPCRouter({
return { role: access.role };
}),
- update: procedure
+ update: protectedProcedure
.input(zEditOrganization)
.mutation(async ({ input, ctx }) => {
await requireOrgAdmin(ctx, input.id);
return ctx.services.organization.update(input);
}),
- delete: procedure
+ delete: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.mutation(async ({ input, ctx }) => {
await requireOrgAdmin(ctx, input.organizationId);
@@ -88,7 +92,7 @@ export const organizationRouter = createTRPCRouter({
return true;
}),
- cancelDeletion: procedure
+ cancelDeletion: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.mutation(async ({ input, ctx }) => {
await requireOrgAdmin(ctx, input.organizationId);
@@ -96,19 +100,21 @@ export const organizationRouter = createTRPCRouter({
return true;
}),
- inviteUser: procedure.input(zInviteUser).mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireOrgAdmin(ctx, input.organizationId);
- return ctx.services.organization.inviteUser({
- organizationId: input.organizationId,
- email: input.email,
- role: input.role,
- access: input.access,
- invitedById: userId,
- });
- }),
+ inviteUser: protectedProcedure
+ .input(zInviteUser)
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ await requireOrgAdmin(ctx, input.organizationId);
+ return ctx.services.organization.inviteUser({
+ organizationId: input.organizationId,
+ email: input.email,
+ role: input.role,
+ access: input.access,
+ invitedById: userId,
+ });
+ }),
- revokeInvite: procedure
+ revokeInvite: protectedProcedure
.input(z.object({ inviteId: z.string() }))
.mutation(async ({ input, ctx }) => {
requireLogin(ctx.session.userId);
@@ -119,7 +125,7 @@ export const organizationRouter = createTRPCRouter({
return ctx.services.organization.revokeInvite(input.inviteId);
}),
- removeMember: procedure
+ removeMember: protectedProcedure
.input(
z.object({
organizationId: z.string(),
@@ -138,7 +144,7 @@ export const organizationRouter = createTRPCRouter({
});
}),
- updateMemberAccess: procedure
+ updateMemberAccess: protectedProcedure
.input(zUpdateMemberAccess)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -153,21 +159,21 @@ export const organizationRouter = createTRPCRouter({
});
}),
- members: procedure
+ members: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.query(async ({ input, ctx }) => {
await requireOrgAdmin(ctx, input.organizationId);
return ctx.services.organization.members(input.organizationId);
}),
- invitations: procedure
+ invitations: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.query(async ({ input, ctx }) => {
await requireOrgAdmin(ctx, input.organizationId);
return ctx.services.organization.invitations(input.organizationId);
}),
- getInvite: procedure
+ getInvite: publicProcedure
.input(z.object({ inviteId: z.string().optional() }))
.query(async ({ input, ctx }) => {
if (!input.inviteId) {
diff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.ts
index 3be3fd9ac..cc82be92a 100644
--- a/packages/core/src/modules/overview/overview.rpc.ts
+++ b/packages/core/src/modules/overview/overview.rpc.ts
@@ -1,11 +1,12 @@
// Ported from packages/trpc/src/routers/overview.ts.
//
-// Same arrangement as chart.rpc.ts: V1's `publicProcedure` + share-or-session
-// `overviewProcedure` middleware and `cacheMiddleware` stacks land with auth
-// (P6), so each procedure does its own share-or-session check off the
-// `projectId`/`shareId` input. packages/trpc's overview router delegates its
-// handler bodies onto this module while keeping V1's own procedure stack and
-// response cache.
+// M11-001: `overviewProcedure` is V1's own builder — `publicProcedure` plus
+// one middleware that resolves share-or-membership off the raw
+// `projectId`/`shareId`, BEFORE the input parser. `runFilterCommand` is a
+// `protectedProcedure`, as in V1.
+//
+// V1's per-range `cacheMiddleware` did NOT move with M11-001;
+// `createCacheMiddleware` in rpc/base.ts is the seam that will carry it.
//
// `liveData`'s ClickHouse queries used to live inline in packages/trpc's
// router; they moved to `services.overview.getLiveData` (src/overview.sql.ts)
@@ -18,7 +19,12 @@ import {
} from '@openpanel/validation';
import { format } from 'date-fns';
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
import type { ServiceDeps } from '../../services';
import {
@@ -97,14 +103,16 @@ async function resolveOverviewAccess(
await requireReadAccess(ctx, input.projectId);
}
-const overviewProcedure = procedure.use(async ({ ctx, next, getRawInput }) => {
- const rawInput = (await getRawInput()) as {
- projectId: string;
- shareId?: string;
- };
- await resolveOverviewAccess(ctx, rawInput);
- return next();
-});
+const overviewProcedure = publicProcedure.use(
+ async ({ ctx, next, getRawInput }) => {
+ const rawInput = (await getRawInput()) as {
+ projectId: string;
+ shareId?: string;
+ };
+ await resolveOverviewAccess(ctx, rawInput);
+ return next();
+ }
+);
function getCurrentAndPrevious<
T extends {
@@ -414,7 +422,7 @@ export const overviewRouter = createTRPCRouter({
// ("show 7 aug to 11 aug", "from google", "mobile only for august
// last year") into structured filter changes the dashboard can apply
// through the same handlers the chat panel uses.
- runFilterCommand: procedure
+ runFilterCommand: protectedProcedure
// Computes filter changes for the caller's own UI; changes no project state.
.meta({ readOnlyMutation: true })
.input(
diff --git a/packages/core/src/modules/profile/profile.rpc.test.ts b/packages/core/src/modules/profile/profile.rpc.test.ts
index 5355c52d4..ca642af2c 100644
--- a/packages/core/src/modules/profile/profile.rpc.test.ts
+++ b/packages/core/src/modules/profile/profile.rpc.test.ts
@@ -5,7 +5,10 @@
// Same shape as session.rpc.test.ts.
import { expect, test } from 'bun:test';
-import { stubHttpCtx } from '../../../test/rpc-fixtures';
+import {
+ servicesWithProjectAccess,
+ stubHttpCtx,
+} from '../../../test/rpc-fixtures';
import { makeTrpcContext } from '../../rpc/base';
import type { CookieOptions } from '../../shared/cookie';
import { profileRouter } from './profile.rpc';
@@ -29,6 +32,18 @@ async function anonCaller() {
return profileRouter.createCaller(trpcCtx);
}
+/**
+ * A signed-in member. `protectedProcedure` authenticates and authorizes
+ * before the input parser runs, so reaching a zod rejection needs both.
+ */
+async function memberCaller() {
+ const { ctx } = stubHttpCtx({ services: servicesWithProjectAccess() });
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return profileRouter.createCaller(trpcCtx);
+}
+
const UNAUTHORIZED = { code: 'UNAUTHORIZED' };
test('every procedure rejects an unauthenticated caller before touching a database', async () => {
@@ -53,7 +68,7 @@ test('every procedure rejects an unauthenticated caller before touching a databa
});
test('list rejects a malformed filter at the input boundary', async () => {
- const caller = await anonCaller();
+ const caller = await memberCaller();
await expect(
caller.list({ projectId: 'proj_1', filters: [{ bogus: true }] as never })
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
diff --git a/packages/core/src/modules/profile/profile.rpc.ts b/packages/core/src/modules/profile/profile.rpc.ts
index 941fe632a..d31fa1e5f 100644
--- a/packages/core/src/modules/profile/profile.rpc.ts
+++ b/packages/core/src/modules/profile/profile.rpc.ts
@@ -1,16 +1,19 @@
// Ported from packages/trpc/src/routers/profile.ts (M7-002).
//
-// Same arrangement as session.rpc.ts: V1's `protectedProcedure` stack lands
-// with auth (P6), so until then each procedure does its own "is anyone logged
-// in" + `requireProjectAccess({ level: 'read' })` off the `projectId` input,
-// which is what V1's `enforceUserIsAuthed` + `enforceAccess` middleware pair
-// does implicitly. packages/trpc's profile router delegates its handler
-// bodies onto `./profile.service` while keeping V1's own `protectedProcedure`
-// stack.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
import { zChartEventFilter } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
getPowerUsers,
@@ -44,37 +47,45 @@ async function requireReadAccess(ctx: TrpcContext, projectId: string) {
}
export const profileRouter = createTRPCRouter({
- byId: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
+ byId: protectedProcedure.input(zProfileRef).query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
return getProfileById(ctx, input.profileId, input.projectId);
}),
- metrics: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- await requireReadAccess(ctx, input.projectId);
+ metrics: protectedProcedure
+ .input(zProfileRef)
+ .query(async ({ input, ctx }) => {
+ await requireReadAccess(ctx, input.projectId);
- return getProfileMetrics(ctx, input.profileId, input.projectId);
- }),
+ return getProfileMetrics(ctx, input.profileId, input.projectId);
+ }),
- activity: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- await requireReadAccess(ctx, input.projectId);
+ activity: protectedProcedure
+ .input(zProfileRef)
+ .query(async ({ input, ctx }) => {
+ await requireReadAccess(ctx, input.projectId);
- return getProfileActivity(ctx, input.profileId, input.projectId);
- }),
+ return getProfileActivity(ctx, input.profileId, input.projectId);
+ }),
- mostEvents: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- await requireReadAccess(ctx, input.projectId);
+ mostEvents: protectedProcedure
+ .input(zProfileRef)
+ .query(async ({ input, ctx }) => {
+ await requireReadAccess(ctx, input.projectId);
- return getProfileMostEvents(ctx, input.profileId, input.projectId);
- }),
+ return getProfileMostEvents(ctx, input.profileId, input.projectId);
+ }),
- popularRoutes: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- await requireReadAccess(ctx, input.projectId);
+ popularRoutes: protectedProcedure
+ .input(zProfileRef)
+ .query(async ({ input, ctx }) => {
+ await requireReadAccess(ctx, input.projectId);
- return getProfilePopularRoutes(ctx, input.profileId, input.projectId);
- }),
+ return getProfilePopularRoutes(ctx, input.profileId, input.projectId);
+ }),
- properties: procedure
+ properties: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
@@ -82,7 +93,7 @@ export const profileRouter = createTRPCRouter({
return getProfilePropertyNames(ctx, input.projectId);
}),
- list: procedure
+ list: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -99,7 +110,7 @@ export const profileRouter = createTRPCRouter({
return getProfileListPage(ctx, input);
}),
- powerUsers: procedure
+ powerUsers: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -113,7 +124,7 @@ export const profileRouter = createTRPCRouter({
return getPowerUsers(ctx, input);
}),
- values: procedure
+ values: protectedProcedure
.input(z.object({ property: z.string(), projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
diff --git a/packages/core/src/modules/project/project.rpc.ts b/packages/core/src/modules/project/project.rpc.ts
index 3fba4f205..eb6392790 100644
--- a/packages/core/src/modules/project/project.rpc.ts
+++ b/packages/core/src/modules/project/project.rpc.ts
@@ -1,21 +1,20 @@
// Ported from packages/trpc/src/routers/project.ts (M6-002).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's project functions (DELEGATE
-// PATTERN). `ctx.services.project` carries this module's factory the same
-// as every other module now (M10-004).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
+//
+// `ctx.services.project` carries this module's factory (M10-004).
//
// The project-access ladder itself is bound once, in auth.service.ts
// (M10-002); every procedure here reaches it through `ctx.services.auth`.
import { zOnboardingProject, zProjectUpdate } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
function requireLogin(userId: string | null | undefined): string {
@@ -26,7 +25,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const projectRouter = createTRPCRouter({
- getProjectWithClients: procedure
+ getProjectWithClients: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input: { projectId }, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -42,7 +41,7 @@ export const projectRouter = createTRPCRouter({
// Powers the activation checklist on the project overview: has the project
// received data, built a report, and invited a teammate yet?
- activationStatus: procedure
+ activationStatus: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input: { projectId }, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -57,7 +56,7 @@ export const projectRouter = createTRPCRouter({
return ctx.services.project.getProjectActivationStatus(projectId);
}),
- list: procedure
+ list: protectedProcedure
.input(z.object({ organizationId: z.string().nullable() }))
.query(async ({ input: { organizationId }, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -67,33 +66,35 @@ export const projectRouter = createTRPCRouter({
return ctx.services.project.getProjects({ organizationId, userId });
}),
- update: procedure.input(zProjectUpdate).mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await ctx.services.auth.requireProjectAccess({
- userId,
- projectId: input.id,
- level: 'write',
- });
-
- const project = await ctx.services.project.getProjectById(input.id);
- if (!project) {
- throw new TRPCForbiddenError('Project not found');
- }
-
- return ctx.services.project.updateProjectForOrganization(
- input.id,
- project.organizationId,
- {
- name: input.name,
- domain: input.domain,
- cors: input.cors,
- crossDomain: input.crossDomain,
- allowUnsafeRevenueTracking: input.allowUnsafeRevenueTracking,
+ update: protectedProcedure
+ .input(zProjectUpdate)
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ await ctx.services.auth.requireProjectAccess({
+ userId,
+ projectId: input.id,
+ level: 'write',
+ });
+
+ const project = await ctx.services.project.getProjectById(input.id);
+ if (!project) {
+ throw new TRPCForbiddenError('Project not found');
}
- );
- }),
- create: procedure
+ return ctx.services.project.updateProjectForOrganization(
+ input.id,
+ project.organizationId,
+ {
+ name: input.name,
+ domain: input.domain,
+ cors: input.cors,
+ crossDomain: input.crossDomain,
+ allowUnsafeRevenueTracking: input.allowUnsafeRevenueTracking,
+ }
+ );
+ }),
+
+ create: protectedProcedure
.input(zOnboardingProject)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -127,7 +128,7 @@ export const projectRouter = createTRPCRouter({
return { ...project, client };
}),
- delete: procedure
+ delete: protectedProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -142,7 +143,7 @@ export const projectRouter = createTRPCRouter({
return true;
}),
- cancelDeletion: procedure
+ cancelDeletion: protectedProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/realtime/realtime.rpc.ts b/packages/core/src/modules/realtime/realtime.rpc.ts
index add72d507..1b3ae48af 100644
--- a/packages/core/src/modules/realtime/realtime.rpc.ts
+++ b/packages/core/src/modules/realtime/realtime.rpc.ts
@@ -1,23 +1,25 @@
// Ported from packages/trpc/src/routers/realtime.ts (M6-007).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" + explicit
-// `requireProjectAccess({ level: 'read' })` check per procedure, exactly like
-// V1's `enforceUserIsAuthed` + `enforceAccess` middleware pair does implicitly
-// off the `projectId` input. packages/trpc's realtime router now DELEGATES
-// its handler bodies onto `./realtime.service`'s query functions (same as
-// notification.ts/reference.ts) while keeping V1's own full
-// `protectedProcedure` stack — so the queries have one implementation, called
-// through two access-check paths until the ONE shared tRPC instance lands
-// with auth (P6).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
+//
+// Each procedure also calls `requireProjectAccess({ level: 'read' })`
+// explicitly; `enforceAccess` already does the same off the `projectId`
+// input, and the redundant call is kept deliberately (ADR-011).
//
// The permission ladder itself is bound once, in auth.service.ts
// (M10-002); every procedure here reaches it through `ctx.services.auth`.
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
getRealtimeActiveSessions,
@@ -61,14 +63,14 @@ async function requireReadAccess(ctx: TrpcContext, projectId: string) {
}
export const realtimeRouter = createTRPCRouter({
- coordinates: procedure
+ coordinates: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
return getRealtimeCoordinates(ctx, input.projectId);
}),
- mapBadgeDetails: procedure
+ mapBadgeDetails: protectedProcedure
.input(
z.object({
detailScope: realtimeBadgeDetailScopeSchema,
@@ -84,28 +86,28 @@ export const realtimeRouter = createTRPCRouter({
return getRealtimeMapBadgeDetails(ctx, input);
}),
- activeSessions: procedure
+ activeSessions: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
return getRealtimeActiveSessions(ctx, input.projectId);
}),
- paths: procedure
+ paths: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
return getRealtimePaths(ctx, input.projectId);
}),
- referrals: procedure
+ referrals: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
return getRealtimeReferrals(ctx, input.projectId);
}),
- geo: procedure
+ geo: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
diff --git a/packages/core/src/modules/reference/reference.rpc.ts b/packages/core/src/modules/reference/reference.rpc.ts
index 06afc6a14..981ba627e 100644
--- a/packages/core/src/modules/reference/reference.rpc.ts
+++ b/packages/core/src/modules/reference/reference.rpc.ts
@@ -1,13 +1,11 @@
// Ported from packages/trpc/src/routers/reference.ts (M6-004).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's reference functions (DELEGATE
-// PATTERN).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// M10-003: the handler bodies reach the module through
// `ctx.services.reference`, so the requestId minted at the edge reaches the
@@ -20,7 +18,11 @@
import { zCreateReference, zRange } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
function requireLogin(userId: string | null | undefined): string {
@@ -31,7 +33,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const referenceRouter = createTRPCRouter({
- getReferences: procedure
+ getReferences: protectedProcedure
.input(z.object({ projectId: z.string(), cursor: z.number().optional() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -45,12 +47,14 @@ export const referenceRouter = createTRPCRouter({
return ctx.services.reference.listReferences(input);
}),
- create: procedure.input(zCreateReference).mutation(({ input, ctx }) => {
- requireLogin(ctx.session.userId);
- return ctx.services.reference.createReference(input);
- }),
+ create: protectedProcedure
+ .input(zCreateReference)
+ .mutation(({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ return ctx.services.reference.createReference(input);
+ }),
- update: procedure
+ update: protectedProcedure
.input(
z.object({
id: z.string(),
@@ -72,7 +76,7 @@ export const referenceRouter = createTRPCRouter({
return ctx.services.reference.updateReference(input);
}),
- delete: procedure
+ delete: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -87,7 +91,7 @@ export const referenceRouter = createTRPCRouter({
return ctx.services.reference.deleteReference(input.id);
}),
- getChartReferences: procedure
+ getChartReferences: publicProcedure
.input(
z.object({
projectId: z.string(),
diff --git a/packages/core/src/modules/report/report.rpc.ts b/packages/core/src/modules/report/report.rpc.ts
index 8d26ebd6c..46917d2e3 100644
--- a/packages/core/src/modules/report/report.rpc.ts
+++ b/packages/core/src/modules/report/report.rpc.ts
@@ -1,16 +1,23 @@
// Ported from packages/trpc/src/routers/report.ts (M7-006).
//
-// Same arrangement as chart.rpc.ts/project.rpc.ts: V1's `protectedProcedure`
-// lands in core with auth (rpc/base.ts), so each procedure does its own "is
-// anyone logged in" + `requireProjectAccess` check, reached through
-// `ctx.services.auth` (M10-002). The mutation bodies
-// (create/update/move/delete/duplicate/layout) moved to ./report.service
-// alongside the reads that already lived there; packages/trpc's report
-// router delegates every handler body onto ./report.service while keeping
-// V1's own procedure stack (DELEGATE PATTERN).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
+//
+// Most of this router's inputs carry a reportId or a dashboardId rather than
+// a projectId, so `enforceAccess` is blind to them and the in-handler
+// `requireProjectAccess` through `ctx.services.auth` (M10-002) is the only
+// check that fires.
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
import { zReport } from './report.constants';
@@ -49,7 +56,7 @@ async function requireWriteAccess(ctx: TrpcContext, projectId: string) {
}
export const reportRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(
z.object({
dashboardId: z.string(),
@@ -68,7 +75,7 @@ export const reportRouter = createTRPCRouter({
return ctx.services.report.getReportsByDashboardId(dashboardId);
}),
- create: procedure
+ create: protectedProcedure
.input(
z.object({
report: zReport.omit({ projectId: true }),
@@ -86,7 +93,7 @@ export const reportRouter = createTRPCRouter({
});
}),
- update: procedure
+ update: protectedProcedure
.input(
z.object({
reportId: z.string(),
@@ -99,7 +106,7 @@ export const reportRouter = createTRPCRouter({
return ctx.services.report.updateReport({ reportId, report });
}),
- move: procedure
+ move: protectedProcedure
.input(
z.object({
reportId: z.string(),
@@ -112,7 +119,7 @@ export const reportRouter = createTRPCRouter({
return ctx.services.report.moveReport({ report: dbReport, dashboardId });
}),
- delete: procedure
+ delete: protectedProcedure
.input(
z.object({
reportId: z.string(),
@@ -124,7 +131,7 @@ export const reportRouter = createTRPCRouter({
return ctx.services.report.deleteReport(reportId);
}),
- duplicate: procedure
+ duplicate: protectedProcedure
.input(
z.object({
reportId: z.string(),
@@ -136,7 +143,7 @@ export const reportRouter = createTRPCRouter({
return ctx.services.report.duplicateReport(dbReport);
}),
- get: procedure
+ get: protectedProcedure
.input(
z.object({
reportId: z.string(),
@@ -151,7 +158,7 @@ export const reportRouter = createTRPCRouter({
return report;
}),
- updateLayout: procedure
+ updateLayout: protectedProcedure
.input(
z.object({
reportId: z.string(),
@@ -164,7 +171,7 @@ export const reportRouter = createTRPCRouter({
return ctx.services.report.updateReportLayout({ reportId, layout });
}),
- getLayouts: procedure
+ getLayouts: protectedProcedure
.input(
z.object({
dashboardId: z.string(),
@@ -188,7 +195,7 @@ export const reportRouter = createTRPCRouter({
return ctx.services.report.getReportLayouts({ dashboardId, projectId });
}),
- resetLayout: procedure
+ resetLayout: protectedProcedure
.input(
z.object({
dashboardId: z.string(),
diff --git a/packages/core/src/modules/session/session.rpc.test.ts b/packages/core/src/modules/session/session.rpc.test.ts
index 96cd09648..c5db6171d 100644
--- a/packages/core/src/modules/session/session.rpc.test.ts
+++ b/packages/core/src/modules/session/session.rpc.test.ts
@@ -5,7 +5,10 @@
// Same shape as realtime.rpc.test.ts.
import { expect, test } from 'bun:test';
-import { stubHttpCtx } from '../../../test/rpc-fixtures';
+import {
+ servicesWithProjectAccess,
+ stubHttpCtx,
+} from '../../../test/rpc-fixtures';
import { makeTrpcContext } from '../../rpc/base';
import type { CookieOptions } from '../../shared/cookie';
import { sessionRouter } from './session.rpc';
@@ -30,6 +33,18 @@ async function anonCaller() {
return sessionRouter.createCaller(trpcCtx);
}
+/**
+ * A signed-in member. `protectedProcedure` authenticates and authorizes
+ * before the input parser runs, so reaching a zod rejection needs both.
+ */
+async function memberCaller() {
+ const { ctx } = stubHttpCtx({ services: servicesWithProjectAccess() });
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return sessionRouter.createCaller(trpcCtx);
+}
+
test('list rejects an unauthenticated caller before querying ClickHouse', async () => {
const caller = await anonCaller();
await expect(caller.list({ projectId: 'proj_1' })).rejects.toMatchObject({
@@ -45,7 +60,7 @@ test('distinctValues rejects an unauthenticated caller before querying ClickHous
});
test('distinctValues rejects a field outside SESSION_DISTINCT_FIELDS at the input boundary', async () => {
- const caller = await anonCaller();
+ const caller = await memberCaller();
await expect(
caller.distinctValues({
projectId: 'proj_1',
diff --git a/packages/core/src/modules/session/session.rpc.ts b/packages/core/src/modules/session/session.rpc.ts
index e245ce866..90cd67e30 100644
--- a/packages/core/src/modules/session/session.rpc.ts
+++ b/packages/core/src/modules/session/session.rpc.ts
@@ -1,11 +1,11 @@
// Ported from packages/trpc/src/routers/session.ts (M7-001).
//
-// Same arrangement as realtime.rpc.ts: V1's `protectedProcedure` stack lands
-// with auth (P6), so until then each procedure does its own "is anyone logged
-// in" + `requireProjectAccess({ level: 'read' })` off the `projectId` input,
-// which is what V1's `enforceUserIsAuthed` + `enforceAccess` middleware pair
-// does implicitly. packages/trpc's session router delegates its handler bodies
-// onto `./session.service` while keeping V1's own `protectedProcedure` stack.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// V1's file also exported `encodeCursor` / `decodeCursor`; nothing imports
// them and `shared/pagination.ts` already has the generic pair, so they were
@@ -13,7 +13,11 @@
import { zChartEventFilter } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ type TrpcContext,
+} from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
getSessionById,
@@ -41,7 +45,7 @@ async function requireReadAccess(ctx: TrpcContext, projectId: string) {
}
export const sessionRouter = createTRPCRouter({
- list: procedure
+ list: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -63,7 +67,7 @@ export const sessionRouter = createTRPCRouter({
});
}),
- distinctValues: procedure
+ distinctValues: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -76,7 +80,7 @@ export const sessionRouter = createTRPCRouter({
return getSessionDistinctValues(ctx, input.projectId, input.field);
}),
- byId: procedure
+ byId: protectedProcedure
.input(z.object({ sessionId: z.string(), projectId: z.string() }))
.query(async ({ input, ctx }) => {
await requireReadAccess(ctx, input.projectId);
@@ -84,7 +88,7 @@ export const sessionRouter = createTRPCRouter({
return getSessionById(ctx, input.sessionId, input.projectId);
}),
- replayChunksFrom: procedure
+ replayChunksFrom: protectedProcedure
.input(
z.object({
sessionId: z.string(),
diff --git a/packages/core/src/modules/share/share.rpc.ts b/packages/core/src/modules/share/share.rpc.ts
index ae6ba5055..8f98d74ae 100644
--- a/packages/core/src/modules/share/share.rpc.ts
+++ b/packages/core/src/modules/share/share.rpc.ts
@@ -1,23 +1,26 @@
// Ported from packages/trpc/src/routers/share.ts (M6-004).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's share functions (DELEGATE
-// PATTERN).
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// M10-003: the handler bodies reach the module through `ctx.services.share`,
// so the requestId minted at the edge reaches the Postgres call (ADR-018).
//
-// The permission ladder itself is bound once, in auth.service.ts
-// (M10-002); every procedure here reaches it through `ctx.services.auth`. `createOverview` has no access
-// check here either — same gap V1's router has (ported verbatim, not fixed).
+// The permission ladder itself is bound once, in auth.service.ts (M10-002);
+// every procedure here reaches it through `ctx.services.auth`.
+// `createOverview` has no in-handler check — the same gap V1's router has,
+// ported verbatim, not fixed.
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+} from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
zShareDashboard,
@@ -33,31 +36,33 @@ function requireLogin(userId: string | null | undefined): string {
}
export const shareRouter = createTRPCRouter({
- overview: procedure
+ overview: publicProcedure
.input(z.object({ shareId: z.string() }))
.query(({ input, ctx }) =>
ctx.services.share.getShareOverview(input.shareId, ctx.cookies)
),
- overviewSettings: procedure
+ overviewSettings: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(({ input, ctx }) => {
requireLogin(ctx.session.userId);
return ctx.services.share.getShareOverviewSettings(input.projectId);
}),
- createOverview: procedure.input(zShareOverview).mutation(({ input, ctx }) => {
- requireLogin(ctx.session.userId);
- return ctx.services.share.createShareOverview(input);
- }),
+ createOverview: protectedProcedure
+ .input(zShareOverview)
+ .mutation(({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ return ctx.services.share.createShareOverview(input);
+ }),
- dashboard: procedure
+ dashboard: publicProcedure
.input(z.object({ shareId: z.string() }))
.query(({ input, ctx }) =>
ctx.services.share.getShareDashboard(input.shareId, ctx.cookies)
),
- dashboardSettings: procedure
+ dashboardSettings: protectedProcedure
.input(z.object({ projectId: z.string(), dashboardId: z.string() }))
.query(({ input, ctx }) => {
requireLogin(ctx.session.userId);
@@ -67,7 +72,7 @@ export const shareRouter = createTRPCRouter({
);
}),
- createDashboard: procedure
+ createDashboard: protectedProcedure
.input(zShareDashboard)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
@@ -79,19 +84,19 @@ export const shareRouter = createTRPCRouter({
return ctx.services.share.createShareDashboard(input);
}),
- dashboardReports: procedure
+ dashboardReports: publicProcedure
.input(z.object({ shareId: z.string() }))
.query(({ input, ctx }) =>
ctx.services.share.getShareDashboardReports(input.shareId, ctx.cookies)
),
- report: procedure
+ report: publicProcedure
.input(z.object({ shareId: z.string() }))
.query(({ input, ctx }) =>
ctx.services.share.getShareReport(input.shareId, ctx.cookies)
),
- reportSettings: procedure
+ reportSettings: protectedProcedure
.input(z.object({ projectId: z.string(), reportId: z.string() }))
.query(({ input, ctx }) => {
requireLogin(ctx.session.userId);
@@ -101,7 +106,7 @@ export const shareRouter = createTRPCRouter({
);
}),
- createReport: procedure
+ createReport: protectedProcedure
.input(zShareReport)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
diff --git a/packages/core/src/modules/subscription/subscription.rpc.ts b/packages/core/src/modules/subscription/subscription.rpc.ts
index 731ec4558..5eccdb015 100644
--- a/packages/core/src/modules/subscription/subscription.rpc.ts
+++ b/packages/core/src/modules/subscription/subscription.rpc.ts
@@ -1,20 +1,18 @@
// Ported from packages/trpc/src/routers/subscription.ts (M6-006).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's subscription functions (DELEGATE
-// PATTERN), so nothing here is a live regression.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
//
// `requireOrganizationAdmin` lives in subscription.service.ts, not here —
// see that file's header. `ctx.services.subscription` carries this module's
// factory the same as every other module now (M10-004).
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
zCancelSubscription,
@@ -30,7 +28,7 @@ function requireLogin(userId: string | null | undefined): string {
}
export const subscriptionRouter = createTRPCRouter({
- getCurrent: procedure
+ getCurrent: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.query(({ input, ctx }) =>
ctx.services.subscription.getCurrentSubscriptionProduct(
@@ -38,7 +36,7 @@ export const subscriptionRouter = createTRPCRouter({
)
),
- checkout: procedure
+ checkout: protectedProcedure
.input(zCheckout)
.mutation(({ input, ctx }) =>
ctx.services.subscription.checkout(
@@ -48,19 +46,19 @@ export const subscriptionRouter = createTRPCRouter({
)
),
- products: procedure
+ products: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.query(({ input, ctx }) =>
ctx.services.subscription.listProducts(input.organizationId)
),
- usage: procedure
+ usage: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.query(({ input, ctx }) =>
ctx.services.subscription.getUsage(input.organizationId)
),
- cancelSubscription: procedure
+ cancelSubscription: protectedProcedure
.input(zCancelSubscription)
.mutation(({ input, ctx }) =>
ctx.services.subscription.cancelSubscription(
@@ -69,7 +67,7 @@ export const subscriptionRouter = createTRPCRouter({
)
),
- pauseSubscription: procedure
+ pauseSubscription: protectedProcedure
.input(zPauseSubscription)
.mutation(({ input, ctx }) =>
ctx.services.subscription.pauseSubscription(
@@ -78,7 +76,7 @@ export const subscriptionRouter = createTRPCRouter({
)
),
- resumeSubscription: procedure
+ resumeSubscription: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.mutation(({ input, ctx }) =>
ctx.services.subscription.resumeSubscription(
@@ -87,7 +85,7 @@ export const subscriptionRouter = createTRPCRouter({
)
),
- applySaveDiscount: procedure
+ applySaveDiscount: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.mutation(({ input, ctx }) =>
ctx.services.subscription.applySaveDiscount(
@@ -96,7 +94,7 @@ export const subscriptionRouter = createTRPCRouter({
)
),
- portal: procedure
+ portal: protectedProcedure
.input(z.object({ organizationId: z.string() }))
.mutation(({ input, ctx }) =>
ctx.services.subscription.portal(
diff --git a/packages/core/src/modules/user/user.rpc.ts b/packages/core/src/modules/user/user.rpc.ts
index acd14970e..0f49c7b3b 100644
--- a/packages/core/src/modules/user/user.rpc.ts
+++ b/packages/core/src/modules/user/user.rpc.ts
@@ -1,18 +1,17 @@
// Ported from packages/trpc/src/routers/user.ts (M6-001).
//
-// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
-// stack — lands in core with auth (rpc/base.ts: "those need the resolved
-// Session shape and the access rules, so they land with auth (P6)"). Until
-// then this router does its own minimal "is anyone logged in" check inline,
-// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
-// through packages/trpc's own `protectedProcedure` (full stack included) and
-// delegates its handler bodies to core's user functions (DELEGATE PATTERN) —
-// `ctx.services.user` carries this module's factory the same as every other
-// module now (M10-004); it has no queue/cron of its own, same as
-// `conversation`.
+// M11-001: every procedure is on its V1 twin's builder.
+// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE
+// the input parser, exactly as V1 does. The explicit checks in the handlers
+// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /
+// `organizationId`, so anything resolved from another id needs its own
+// (ADR-011).
+//
+// `ctx.services.user` carries this module's factory (M10-004); it has no
+// queue/cron of its own, same as `conversation`.
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import { deleteSessionTokenCookie } from '../auth/auth.service';
@@ -24,19 +23,19 @@ function requireLogin(userId: string | null | undefined): string {
}
export const userRouter = createTRPCRouter({
- deletionBlockers: procedure.query(async ({ ctx }) => {
+ deletionBlockers: protectedProcedure.query(async ({ ctx }) => {
const userId = requireLogin(ctx.session.userId);
return ctx.services.user.listUserDeletionBlockers(userId);
}),
- delete: procedure.mutation(async ({ ctx }) => {
+ delete: protectedProcedure.mutation(async ({ ctx }) => {
const userId = requireLogin(ctx.session.userId);
await ctx.services.user.deleteUserAccount(userId);
deleteSessionTokenCookie(ctx.setCookie);
return true;
}),
- update: procedure
+ update: protectedProcedure
.input(
z.object({
firstName: z.string(),
@@ -48,7 +47,7 @@ export const userRouter = createTRPCRouter({
return ctx.services.user.updateUserProfile({ userId, ...input });
}),
- debugPostCookie: procedure
+ debugPostCookie: protectedProcedure
.input(
z.object({
sameSite: z.enum(['lax', 'strict', 'none']),
@@ -66,7 +65,7 @@ export const userRouter = createTRPCRouter({
});
}),
- debugGetCookie: procedure
+ debugGetCookie: protectedProcedure
.input(
z.object({
sameSite: z.enum(['lax', 'strict', 'none']),
diff --git a/packages/core/src/modules/widget/widget.rpc.ts b/packages/core/src/modules/widget/widget.rpc.ts
index 7e778909b..90bbe45e5 100644
--- a/packages/core/src/modules/widget/widget.rpc.ts
+++ b/packages/core/src/modules/widget/widget.rpc.ts
@@ -27,7 +27,11 @@ import ShortUniqueId from 'short-unique-id';
import { z } from 'zod';
import { loadDbBuffers } from '../../buffers/lazy-db-buffers';
import type { Ctx } from '../../context';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import {
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+} from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
import { TABLE_NAMES } from '../../shared/ch-tables';
import { getSettingsForProject } from '../organization/organization.service';
@@ -67,7 +71,7 @@ async function findWidgetByType(
export const widgetRouter = createTRPCRouter({
// Get widget by projectId and type (returns null if not found or not public)
- get: procedure
+ get: protectedProcedure
.input(z.object({ projectId: z.string(), type: zWidgetType }))
.query(async ({ input, ctx }) => {
requireLogin(ctx.session.userId);
@@ -85,7 +89,7 @@ export const widgetRouter = createTRPCRouter({
}),
// Toggle widget public status (creates if doesn't exist)
- toggle: procedure
+ toggle: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -133,7 +137,7 @@ export const widgetRouter = createTRPCRouter({
}),
// Update widget options (for realtime widget)
- updateOptions: procedure
+ updateOptions: protectedProcedure
.input(
z.object({
projectId: z.string(),
@@ -169,7 +173,7 @@ export const widgetRouter = createTRPCRouter({
});
}),
- counter: procedure
+ counter: publicProcedure
.input(z.object({ shareId: z.string() }))
.query(async ({ input, ctx }) => {
const db = ctx.db;
@@ -195,7 +199,7 @@ export const widgetRouter = createTRPCRouter({
};
}),
- badge: procedure
+ badge: publicProcedure
.input(z.object({ shareId: z.string() }))
.query(async ({ input, ctx }) => {
const db = ctx.db;
@@ -241,7 +245,7 @@ export const widgetRouter = createTRPCRouter({
};
}),
- realtimeData: procedure
+ realtimeData: publicProcedure
.input(z.object({ shareId: z.string() }))
.query(async ({ input, ctx }) => {
const db = ctx.db;
diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.ts
index fe96a887f..bd1e86082 100644
--- a/packages/core/src/rpc/base.ts
+++ b/packages/core/src/rpc/base.ts
@@ -8,13 +8,16 @@
// `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 { initTRPC, TRPCError } from '@trpc/server';
+import { has } from 'ramda';
import superjson from 'superjson';
import { ZodError, z } from 'zod';
import type { HttpCtx, Session } from '../context';
import type { Logger } from '../logger';
import { EMPTY_SESSION } from '../modules/auth/src/login-session';
+import { runWithAlsSession } from '../modules/session/src/session-context';
import { type CookieOptions, serializeCookie } from '../shared/cookie';
+import { TRPCForbiddenError } from './errors';
/**
* Per-procedure metadata consulted by `enforceAccess`.
@@ -87,13 +90,157 @@ const t = initTRPC
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).
+ * The bare procedure. It authenticates NOTHING. Use one of the three builders
+ * below unless a procedure's V1 twin was written on `procedure` itself — the
+ * only ones are the share-aware `chartProcedure`/`overviewProcedure` bases,
+ * and those are `publicProcedure` plus their own middleware.
*/
export const procedure = t.procedure;
+// ---------------------------------------------------------------------------
+// The procedure stack (M11-001), ported from packages/trpc/src/trpc.ts:35-155.
+//
+// ADR-011 is this code's law; invariants 1-13 are binding. Three properties of
+// the port are load-bearing and are the reason it is a middleware stack rather
+// than per-handler code:
+//
+// 1. AUTHENTICATION RUNS BEFORE INPUT PARSING. tRPC runs `.use()` middleware
+// ahead of the `.input()` parser, so an anonymous caller gets UNAUTHORIZED
+// whatever it sends. Doing the same check inside a handler inverts that:
+// the caller learns the input shape first, and 176 procedures changed
+// answer from 401 to 400 when core mounted the bare `procedure`
+// (docs/RPC_PROCEDURE_SET_EQUIVALENCE.md).
+// 2. THE CHECK CANNOT BE FORGOTTEN. It is a property of the builder, not of a
+// line a port might drop. Three procedures (`client.list`,
+// `subscription.getCurrent`, `subscription.usage`) had no check at all
+// while this stack was missing.
+// 3. `enforceAccess` READS THE RAW, PRE-ZOD INPUT (ADR-011 invariant 2) and
+// only its TOP-LEVEL `projectId` / `organizationId`. A procedure that
+// resolves the project from a reportId/dashboardId is invisible to it and
+// keeps its in-handler check — ADR-011 counts 58 of those, and a redundant
+// check is harmless where a missing one is not.
+//
+// The lookups arrive through `ctx.services.auth` (M10-002 bound the ladder
+// there, once, in auth.service.ts); core reaches no database directly.
+// ---------------------------------------------------------------------------
+
+const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
+ if (!ctx.session?.userId) {
+ throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not authenticated' });
+ }
+
+ try {
+ return next({
+ ctx: {
+ session: { ...ctx.session },
+ },
+ });
+ } catch (error) {
+ // V1 wrote this to `console.error`; core has a request-scoped logger on
+ // the context and CLAUDE.md bans `console` in shipped code. Same branch,
+ // same outcome, same (misspelled, kept) message.
+ ctx.logger.error({ err: error }, 'Failes to get user');
+ throw new TRPCError({
+ code: 'UNAUTHORIZED',
+ message: 'Failed to get user',
+ });
+ }
+});
+
+// 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' && ctx.demoMode) {
+ 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 ctx.services.auth.requireProjectAccess({
+ userId: ctx.session.userId as string,
+ projectId: rawInput.projectId as string,
+ level: needsWrite ? 'write' : 'read',
+ });
+ }
+
+ if (has('organizationId', rawInput)) {
+ const access = await ctx.services.auth.getOrganizationAccess({
+ userId: ctx.session.userId as string,
+ organizationId: rawInput.organizationId as string,
+ });
+
+ if (!access) {
+ throw new TRPCForbiddenError(
+ 'You do not have access to this organization'
+ );
+ }
+ }
+
+ return next();
+ });
+ }
+);
+
+const loggerMiddleware = t.middleware(
+ async ({ ctx, next, getRawInput, path, input, type }) => {
+ const rawInput = await getRawInput();
+ // Only log mutations
+ if (type === 'mutation') {
+ ctx.logger.info(
+ {
+ path,
+ rawInput,
+ input,
+ userId: ctx.session?.userId,
+ organizationId: has('organizationId', rawInput)
+ ? rawInput.organizationId
+ : undefined,
+ projectId: has('projectId', rawInput)
+ ? rawInput.projectId
+ : undefined,
+ },
+ 'TRPC mutation'
+ );
+ }
+ return next();
+ }
+);
+
+const sessionScopeMiddleware = t.middleware(async ({ ctx, next }) => {
+ const sessionId = ctx.session?.session?.id ?? null;
+ return runWithAlsSession(sessionId, async () => {
+ return next();
+ });
+});
+
+/** Anyone, signed in or not. Still session-scoped and mutation-logged. */
+export const publicProcedure = procedure
+ .use(loggerMiddleware)
+ .use(sessionScopeMiddleware);
+/** Signed in, plus the project/organization check on the raw input. */
+export const protectedProcedure = procedure
+ .use(enforceUserIsAuthed)
+ .use(enforceAccess)
+ .use(loggerMiddleware)
+ .use(sessionScopeMiddleware);
+// 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 = procedure
+ .use(enforceUserIsAuthed)
+ .use(loggerMiddleware)
+ .use(sessionScopeMiddleware);
+
// 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.
diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.ts
index a9a809c9d..28d8f6781 100644
--- a/packages/core/test/rpc-fixtures.ts
+++ b/packages/core/test/rpc-fixtures.ts
@@ -12,6 +12,7 @@ import {
import { createRecordingProducers } from '../src/jobs/testing';
import { queues } from '../src/jobs.registry';
import type { LogFn, Logger } from '../src/logger';
+import type { Services } from '../src/services';
export interface LoggedLine {
level: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
@@ -97,6 +98,7 @@ export function stubHttpCtx(
config: { selfHosted: false },
};
+ const { services, ...rest } = overrides;
const ctx = extendCtx(
createCtx(deps, { requestId: TEST_REQUEST_ID, logger }),
{
@@ -110,9 +112,17 @@ export function stubHttpCtx(
setCookie: (name: string, value: string, options?: unknown) => {
cookies.push({ name, value, options });
},
- ...overrides,
+ ...rest,
}
);
+ // `services` is a getter with no setter on the prototype, so assigning it
+ // through extendCtx's Object.assign throws. Shadow it instead.
+ if (services) {
+ Object.defineProperty(ctx, 'services', {
+ value: services,
+ enumerable: true,
+ });
+ }
return {
ctx,
@@ -123,3 +133,21 @@ export function stubHttpCtx(
},
};
}
+
+/**
+ * `services` with the permission ladder already granted.
+ *
+ * `protectedProcedure` runs `enforceAccess` BEFORE the input parser
+ * (M11-001), so a test that wants to assert on a zod rejection has to get
+ * past the ladder first — and the real one reaches Postgres. Everything a
+ * procedure does after the parser is out of these tests' scope, so only the
+ * two lookups `enforceAccess` makes are stubbed.
+ */
+export function servicesWithProjectAccess(): Services {
+ return {
+ auth: {
+ requireProjectAccess: () => Promise.resolve({ level: 'write' }),
+ getOrganizationAccess: () => Promise.resolve({ role: 'org:admin' }),
+ },
+ } as unknown as Services;
+}