Skip to content

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

ralph(M10-002): Bind the access ladder once via the auth service; delete the 22 modules/*/src/access.ts copies

ralphf0c94b68625d
diff --git a/docs/TECH_DEBT.md b/docs/TECH_DEBT.md
index 15c1b3cfa..d0188f51a 100644
--- a/docs/TECH_DEBT.md
+++ b/docs/TECH_DEBT.md
@@ -104,3 +104,191 @@ rules still report 0 violations at their unchanged `error` severity.
`pnpm run typecheck` and `cd packages/core && bun test --isolate` (1447
pass, 0 fail) both pass unaffected — this task only changes the lint config
and this doc, not any source file.
+
+### 2026-09-05 — M10-002, the 22 `modules/*/src/access.ts` copies deleted, ladder bound once via a lazy memoized helper
+
+Ran by: ralph (M10-002 implement task, docs/TECH_DEBT.md §5b). Reset three
+times on review before this attempt; the operator rewrote criteria 1-2 to
+explicitly authorize what earlier attempts got blocked or FAILed on:
+`integration.service.ts` / `subscription.service.ts` reaching the shared
+binding directly, because both are called with a bare `userId` (no `ctx`) by
+`packages/trpc`'s still-live V1 delegate routers — the exemption expires when
+`packages/trpc` dies at P10.
+
+Before, proof the 22 were byte-identical copies (via git history — the files
+are gone from the working tree by the time this entry is written):
+
+```
+$ git ls-tree -r HEAD --name-only | grep -E '^packages/core/src/modules/[^/]+/src/access\.ts$' \
+ | while read -r f; do git show "HEAD:$f" | head -n1; done | sort | uniq -c
+ 22 // Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
+```
+
+**The binding.** `modules/auth/auth.service.ts` exports one `getAccessChecks()`:
+a module-level `let accessChecksPromise`, populated the first time anything
+calls it, via `Promise.all([import('../../shared/access-lookups'),
+import('../project/project.service')])` feeding the four lookups into
+`shared/access.ts`'s `createAccessChecks(...)` — exactly once, ever. Nothing
+runs at module-import time, and nothing runs at `createAuthService(deps)`
+construction time either, which matters because `createAuthService` is NOT a
+process-lifetime singleton: `context.ts`'s `installLazyServices` calls
+`createServices(deps)` (hence `createAuthService(deps)`) fresh on the first
+`ctx.services` read of every request. `createAuthService` spreads the
+resolved checks into `AuthService`'s `requireProjectAccess` /
+`requireOrganizationAdmin` / `requireProjectAdmin`, plus three raw lookups
+(`getProjectAccess` / `getOrganizationAccess` / `getClientAccess`, each its
+own `import('../../shared/access-lookups')` — cheap after the first call,
+since the module resolves from Bun's own import cache). Every rpc/route/
+handler that HAS a `ctx` now calls `ctx.services.auth.<check>`.
+
+**The two authorized exceptions.** `integration.service.ts` (4 call sites)
+and `subscription.service.ts` (6 — 10 total, matching the earlier attempt's
+"unmemoized across its 10 call sites" diagnosis) import `getAccessChecks`
+directly from `../auth/auth.service`. `integration.service.ts`'s org-wide
+read branch also imports `getOrganizationAccess` directly from the sibling
+`shared/access-lookups.ts` — a raw lookup, not part of the `require*` ladder,
+so it never goes through `getAccessChecks()`. Neither import touches
+`@openpanel/core`'s own barrel.
+
+**Why this is not the earlier module-scope attempt that hung.** An earlier
+attempt bound `createAccessChecks(...)` at module scope in `auth.service.ts`
+(a top-level `const accessChecks = createAccessChecks({...})`, with static
+imports of `access-lookups.ts` / `project.service.ts`) and hung
+`cd packages/core && bun test` for 30 minutes. This attempt never calls
+`createAccessChecks` anywhere except inside `getAccessChecks()`'s own lazily-
+invoked body, and both its inputs are reached by dynamic `import()`, not a
+static top-level import — see the timing table below for proof the bare suite
+now exits on its own.
+
+**Fixed, not worked around: a real pre-existing test leak this task's own
+hard gate exposed.** Bare `bun test` shares one module registry across every
+file (no `--isolate`); `src/context.test.ts`, `src/http/context.test.ts` and
+`test/request-id-end-to-end.test.ts` each `mock.module('./services' /
+'../services' / '../src/services', ...)` with a stub `createServices`
+returning `{}` (no `.auth`) and never restored it. Nothing else in the suite
+read `ctx.services.auth` before this task, so the leak was invisible; this
+task adds ~20 more rpc files that do, and `group.rpc.test.ts` /
+`realtime.rpc.test.ts` / `realtime.routes.test.ts` started failing with
+`undefined is not an object (evaluating 'ctx.services.auth.requireProjectAccess')`
+— whichever context test's stub ran first, still installed. Fixed by
+snapshotting each real module BEFORE its `mock.module` call and restoring to
+that snapshot in `afterAll` (the snapshot-before-mock idiom — a live
+re-`import` during restore just reads the already-mocked registry entry back).
+The new `auth.service.access.test.ts` has the same hazard one level deeper:
+`getAccessChecks()`'s `accessChecksPromise` is a true process-lifetime memo,
+so its `afterAll` also calls a new test-only `resetAccessChecksForTests()`
+alongside restoring its two mocked modules, or its fakes would answer every
+later file's real access checks for the rest of the run.
+
+**Test that binds fake `AccessLookups`.** `auth.service.access.test.ts` mocks
+`../../shared/access-lookups` and `../project/project.service` (spreading the
+real modules, overriding only the four lookups) and exercises
+`createAuthService(...)` directly: fail-closed ordering (no access throws
+before the write-level check runs), the exact messages (`'You do not have
+access to this project'`, `'You have read-only access to this project'`,
+`'Only organization admins can do this'`, and a caller-supplied override),
+the write/admin level set, and `requireProjectAdmin`'s project→org
+resolution. `shared/access.ts` itself is untouched by this task.
+
+**Deletion proof:**
+```
+$ find packages/core/src/modules -name access.ts | wc -l
+0
+```
+
+**`pnpm run check:deps`** (`.dependency-cruiser.cjs`, both rules unchanged at
+their landed `warn` severity):
+
+| Rule | Before (M10-001) | After (M10-002) | Delta |
+|---|---:|---:|---:|
+| `core-uses-ctx-not-db-internals` | 167 | 167 | 0 |
+| `core-no-self-barrel` | 96 | 74 | −22, exactly the 22 deleted files |
+
+`core-uses-ctx-not-db-internals` counts VALUE imports of `packages/db/**`;
+all 22 deleted files imported `@openpanel/core` (the self-barrel) and
+`shared/access.ts` — never `@openpanel/db` directly — so this task's
+mechanism (deleting self-barrel copies) has zero edges of that kind to
+remove. `core-no-self-barrel` counts value-imports of
+`packages/core/src/index.ts`, which is exactly what every deleted file did
+once, for its own `createAccessChecks` binding; −22 is the 22 files, one edge
+each. `pnpm run check:deps` exits `0`
+(`x 241 dependency violations (0 errors, 241 warnings)`).
+
+**`pnpm run typecheck`** — all 25 workspaces, `Done`.
+
+**`cd packages/core && bun test`** (bare, no `--isolate` — the hard gate):
+```
+ 1455 pass
+ 0 fail
+Ran 1467 tests across 148 files. [10.73s]
+
+real 0m10.797s
+user 0m8.005s
+sys 0m1.878s
+```
+The process exited on its own; `real` tracks `user`+`sys`, not a multi-minute
+stall on an idle handle. `cd packages/core && bun test --isolate` (the
+configured suite) is also green — 1455 pass, 0 fail, `real 1m45.680s`.
+
+### 2026-09-05 — M10-002 correction: the previous "third call site" fix is reverted — it was out of scope, not authorized
+
+The independent reviewer REJECTED the attempt written up in the correction
+section that used to be here (Attempt 2): it touched 14 files under
+`packages/trpc/**` plus deleted `packages/trpc/src/access.test.ts`, none of
+which are in this task's declared scope (`packages/core/**`, `apps/api/**`,
+`docs/**`). The reviewer was right — CLAUDE.md's Scope section is explicit
+("Refactoring outside scope is a task of its own; propose it, don't do it")
+and self-justifying the change in the report instead of stopping is exactly
+the failure pattern the review exists to catch. That diff is reverted in
+full (`git checkout HEAD -- packages/trpc/`); `packages/trpc/src/access.ts`,
+its three ladder exports, its twelve router call sites and
+`packages/trpc/src/access.test.ts` are back to their pre-task state,
+byte-identical to `HEAD`.
+
+**What that leaves.** `packages/trpc/src/access.ts` does have its own
+top-level `const checks = createAccessChecks({...})` — pre-existing, from
+M4-002 (`packages/trpc` rebase onto core's `CoreContext`) and untouched by
+every M10-002 wave since, not something this task introduced or could
+authorize itself. It is wired live through `apps/api/src/main.ts`
+(`enforceAccess` middleware in `packages/trpc/src/trpc.ts`, plus fifteen V1
+router files). So criterion 1's "called from exactly ONE place in the
+codebase," read literally against the *whole repo*, is not met:
+
+```
+$ grep -rn "createAccessChecks(" --include="*.ts" packages apps | grep -v '\.test\.ts'
+packages/core/src/modules/auth/auth.service.ts:148: createAccessChecks({
+packages/trpc/src/access.ts:22:const checks = createAccessChecks({
+```
+
+Everything this task's scope can reach is consistent with the criterion:
+inside `packages/core/**`, `createAccessChecks` is called from exactly one
+place (`auth.service.ts`'s `getAccessChecks()`, memoized, lazy — see the
+2026-09-05 M10-002 entry above for the mechanism, unchanged by this
+correction). `packages/trpc/src/access.ts`'s copy is a second, independent
+binding of the same ladder to the same lookups, but it lives entirely
+outside `packages/core`, is unreachable from anything this task is allowed
+to edit, and predates this task by five waves (M4-002 → M9-CLEANUP-001).
+Fixing it requires editing `packages/trpc/**`, which is out of scope; per
+CLAUDE.md this is recorded as a follow-up, not done here. It is low-risk
+debt on its own terms: `packages/trpc` is V1's whole surface and is deleted
+entire at P10 (docs/TECH_DEBT.md's other P10 entries), taking this second
+call site with it — the exemption for integration.service.ts /
+subscription.service.ts calling `getAccessChecks()` directly already carries
+the identical "expires at P10" note for the same reason.
+
+**Follow-up (new, not this task):** collapse `packages/trpc/src/access.ts`'s
+`createAccessChecks({...})` into a call through core's `getAccessChecks()`
+(or delete the file once its callers move to `ctx.services.auth`, as
+Attempt 2 did) — scoped to `packages/trpc/**`, proposed here rather than
+done, per CLAUDE.md's Scope section.
+
+Re-verified after the revert: `pnpm run typecheck` — all 25 workspaces,
+`Done`, including `packages/trpc` (its `access.ts` still resolves
+`createAccessChecks`, `canWriteProject`, `getOrganizationAccess`,
+`getProjectAccess`, `getProjectById` off `@openpanel/core`'s barrel, which
+this task doesn't remove). `cd packages/core && bun test` (bare): 1455 pass,
+0 fail, `Ran 1467 tests across 148 files. [13.56s]`, `real 0m13.635s` —
+process exited on its own. `pnpm run check:deps`:
+`core-uses-ctx-not-db-internals` 167, `core-no-self-barrel` 74 — unchanged
+from the M10-002 entry above; this rule only cruises `packages/core/**`, and
+the revert touched nothing there.
diff --git a/packages/core/src/context.test.ts b/packages/core/src/context.test.ts
index 2665a408e..fd25e8e56 100644
--- a/packages/core/src/context.test.ts
+++ b/packages/core/src/context.test.ts
@@ -1,4 +1,4 @@
-import { beforeAll, expect, mock, test } from 'bun:test';
+import { afterAll, beforeAll, expect, mock, test } from 'bun:test';
import type { AppDeps, Buffers, Ctx } from './context';
import type { JobMeta } from './jobs/envelope';
import { createRecordingProducers } from './jobs/testing';
@@ -7,6 +7,11 @@ import { queues } from './jobs.registry';
import type { Logger } from './logger';
import type { ServiceDeps, Services } from './services';
+// Snapshotted BEFORE `mock.module` below, not after — restoring by re-`import`ing
+// './services' later would resolve the already-mocked registry entry, not the
+// real module (bare `bun test` shares one module registry across every file).
+const realServicesModule = { ...(await import('./services')) };
+
// mock.module is not hoisted, so the subject is imported inside beforeAll —
// see AGENTS.md. Mocking createServices is what makes "not built yet"
// observable at all — this suite cares about WHEN the factory runs, not what
@@ -25,6 +30,14 @@ beforeAll(async () => {
({ createCtx, extendCtx } = await import('./context'));
});
+// Without this, bare `bun test` (one shared module registry, no --isolate)
+// leaks the stub `createServices` — returning `{}` with no `.auth` — into
+// every OTHER file that later imports './context', which is most of the rpc
+// test suite via test/rpc-fixtures.ts's `stubHttpCtx`.
+afterAll(() => {
+ mock.module('./services', () => realServicesModule);
+});
+
const REQUEST_ID = 'req_abcdefghijklmnopqrstu';
function stubLogger(): Logger {
diff --git a/packages/core/src/http/context.test.ts b/packages/core/src/http/context.test.ts
index 6990db9db..7e765a6e3 100644
--- a/packages/core/src/http/context.test.ts
+++ b/packages/core/src/http/context.test.ts
@@ -1,9 +1,26 @@
-import { beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ mock,
+ test,
+} from 'bun:test';
import { Elysia } from 'elysia';
import { stubAppDeps } from '../../test/http-fixtures';
import type { HttpCtx } from '../context';
import type { Services } from '../services';
+// Snapshotted BEFORE `mock.module` below, not after — restoring by
+// re-`import`ing later would resolve the already-mocked registry entry, not
+// the real module (bare `bun test` shares one module registry across every
+// file). Without the `afterAll` restore, the stub `createServices` (`{}`,
+// no `.auth`) leaks into every OTHER file that later imports '../context' or
+// './session'.
+const realServicesModule = { ...(await import('../services')) };
+const realSessionModule = { ...(await import('./session')) };
+
// mock.module is not hoisted, so the subjects are imported inside beforeAll —
// see AGENTS.md. Mocking createServices is what makes "not built yet"
// observable at all — this suite cares about WHEN the factory runs, not what
@@ -24,6 +41,11 @@ beforeAll(async () => {
({ requestContext, requestLogging } = await import('./context'));
});
+afterAll(() => {
+ mock.module('../services', () => realServicesModule);
+ mock.module('./session', () => realSessionModule);
+});
+
beforeEach(() => {
createServices.mockClear();
resolveSession.mockClear();
diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.ts
new file mode 100644
index 000000000..8e9d68c11
--- /dev/null
+++ b/packages/core/src/modules/auth/auth.service.access.test.ts
@@ -0,0 +1,162 @@
+// M10-002 (docs/TECH_DEBT.md §5b): auth.service.ts is now the ONLY place
+// `shared/access.ts`'s ladder is bound to real lookups, via the lazy,
+// memoized `getAccessChecks()`. This proves that seam still takes a fake
+// `AccessLookups` cleanly — mocking `../../shared/access-lookups` and
+// `../project/project.service` (both reached only through dynamic imports by
+// auth.service.ts, never statically) instead of a per-module `src/access.ts`
+// copy — and that ADR-011's fail-closed ordering, messages and write-level
+// gate are unchanged.
+
+import { afterAll, beforeAll, expect, mock, test } from 'bun:test';
+import type { ServiceDeps } from '../../services';
+
+interface FakeProjectAccess {
+ level: 'read' | 'write' | 'admin';
+}
+
+let projectAccess: FakeProjectAccess | null = null;
+let organizationAccess: { role: string } | null = null;
+let projectById: { organizationId: string | null } | null = null;
+
+const getProjectAccess = mock(async () => projectAccess);
+const getOrganizationAccess = mock(async () => organizationAccess);
+const canWriteProject = mock(
+ (access: FakeProjectAccess | null) =>
+ !!access && (access.level === 'write' || access.level === 'admin')
+);
+const getProjectById = mock(async () => projectById);
+
+// Snapshotted BEFORE `mock.module` below, not after — restoring by
+// re-`import`ing later would resolve the already-mocked registry entry, not
+// the real module (bare `bun test` shares one module registry across every
+// file, and both of these are reached by plenty of other modules —
+// client.rpc.ts, project.rpc.ts, integration.service.ts, ...).
+const realAccessLookups = { ...(await import('../../shared/access-lookups')) };
+const realProjectService = { ...(await import('../project/project.service')) };
+
+mock.module('../../shared/access-lookups', () => ({
+ ...realAccessLookups,
+ getProjectAccess,
+ getOrganizationAccess,
+ canWriteProject,
+}));
+mock.module('../project/project.service', () => ({
+ ...realProjectService,
+ getProjectById,
+}));
+
+let createAuthService: typeof import('./auth.service').createAuthService;
+let resetAccessChecksForTests: typeof import('./auth.service').resetAccessChecksForTests;
+beforeAll(async () => {
+ ({ createAuthService, resetAccessChecksForTests } = await import(
+ './auth.service'
+ ));
+});
+
+afterAll(() => {
+ mock.module('../../shared/access-lookups', () => realAccessLookups);
+ mock.module('../project/project.service', () => realProjectService);
+ // `getAccessChecks()` memoizes for the life of the process — clear it so a
+ // later file in this bare run rebuilds against the real lookups just
+ // restored above, not this file's fakes.
+ resetAccessChecksForTests();
+});
+
+function authService() {
+ return createAuthService({} as unknown as ServiceDeps);
+}
+
+test('requireProjectAccess is fail-closed: no access throws before the write-level check', async () => {
+ projectAccess = null;
+ await expect(
+ authService().requireProjectAccess({
+ userId: 'user_1',
+ projectId: 'proj_1',
+ level: 'read',
+ })
+ ).rejects.toThrow('You do not have access to this project');
+ expect(canWriteProject).not.toHaveBeenCalled();
+});
+
+test('requireProjectAccess rejects a read-only member asking for write', async () => {
+ projectAccess = { level: 'read' };
+ await expect(
+ authService().requireProjectAccess({
+ userId: 'user_1',
+ projectId: 'proj_1',
+ level: 'write',
+ })
+ ).rejects.toThrow('You have read-only access to this project');
+});
+
+test('requireProjectAccess allows write and admin levels to write', async () => {
+ projectAccess = { level: 'write' };
+ await expect(
+ authService().requireProjectAccess({
+ userId: 'user_1',
+ projectId: 'proj_1',
+ level: 'write',
+ })
+ ).resolves.toEqual({ level: 'write' });
+
+ projectAccess = { level: 'admin' };
+ await expect(
+ authService().requireProjectAccess({
+ userId: 'user_1',
+ projectId: 'proj_1',
+ level: 'write',
+ })
+ ).resolves.toEqual({ level: 'admin' });
+});
+
+test('requireOrganizationAdmin rejects a non-admin with the default message', async () => {
+ organizationAccess = { role: 'member' };
+ await expect(
+ authService().requireOrganizationAdmin({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).rejects.toThrow('Only organization admins can do this');
+});
+
+test('requireOrganizationAdmin honors a caller-supplied message', async () => {
+ organizationAccess = null;
+ await expect(
+ authService().requireOrganizationAdmin({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ message: 'Only organization admins can change an org-wide integration',
+ })
+ ).rejects.toThrow(
+ 'Only organization admins can change an org-wide integration'
+ );
+});
+
+test('requireProjectAdmin fails closed when the project has no organization', async () => {
+ projectById = null;
+ await expect(
+ authService().requireProjectAdmin({ userId: 'user_1', projectId: 'proj_1' })
+ ).rejects.toThrow('You do not have access to this project');
+});
+
+test('requireProjectAdmin defers to the organization-admin gate once resolved', async () => {
+ projectById = { organizationId: 'org_1' };
+ organizationAccess = { role: 'org:admin' };
+ await expect(
+ authService().requireProjectAdmin({ userId: 'user_1', projectId: 'proj_1' })
+ ).resolves.toEqual({ role: 'org:admin' });
+});
+
+test('getProjectAccess / getOrganizationAccess reach the same fake lookups', async () => {
+ projectAccess = { level: 'admin' };
+ organizationAccess = { role: 'org:admin' };
+ await expect(
+ authService().getProjectAccess({ userId: 'user_1', projectId: 'proj_1' })
+ ).resolves.toEqual({ level: 'admin' });
+ await expect(
+ authService().getOrganizationAccess({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).resolves.toMatchObject({ role: 'org:admin' });
+});
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index 22d02cd87..39f51fad7 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -4,9 +4,20 @@
// row — moved here too (M8-005, `./src/login-session.ts`), lazily loading
// @openpanel/db's Prisma client the same way `loadRegistration` below does,
// so there is no static core -> db edge.
+//
+// M10-002 (docs/TECH_DEBT.md §5b): the permission ladder (`shared/access.ts`)
+// is bound to its real lookups exactly here, once, instead of once per module
+// in a `modules/*/src/access.ts` copy — see `getAccessChecks` below for the
+// binding itself.
import { z } from 'zod';
import type { ServiceDeps } from '../../services';
+import { type AccessChecks, createAccessChecks } from '../../shared/access';
+import type {
+ getClientAccess as GetClientAccessFn,
+ getOrganizationAccess as GetOrganizationAccessFn,
+ IProjectAccess,
+} from '../../shared/access-lookups';
import type { ISetCookie } from '../../shared/cookie';
import {
deleteSessionTokenCookie,
@@ -62,7 +73,17 @@ export {
verifyTotpCode,
} from './src/totp';
-export interface AuthService {
+export interface AuthService extends AccessChecks<IProjectAccess> {
+ getProjectAccess(args: {
+ userId: string;
+ projectId: string;
+ }): Promise<IProjectAccess | null>;
+ getOrganizationAccess(
+ ...args: Parameters<typeof GetOrganizationAccessFn>
+ ): ReturnType<typeof GetOrganizationAccessFn>;
+ getClientAccess(
+ ...args: Parameters<typeof GetClientAccessFn>
+ ): ReturnType<typeof GetClientAccessFn>;
hashPassword(password: string): Promise<string>;
verifyPasswordHash(hash: string, password: string): Promise<boolean>;
generateSessionToken(): string;
@@ -92,14 +113,88 @@ export interface AuthService {
};
}
+function loadAccessLookups() {
+ return import('../../shared/access-lookups');
+}
+
+let accessChecksPromise: Promise<AccessChecks<IProjectAccess>> | undefined;
+
+/**
+ * The single binding of `shared/access.ts`'s ladder to real lookups
+ * (M10-002, docs/TECH_DEBT.md §5b) — lazy AND memoized: `createAccessChecks`
+ * itself runs exactly once per process, on however many requests, no matter
+ * how many of this function's callers invoke it. Nothing here runs at
+ * module-import time or at `createAuthService` construction time — both
+ * `access-lookups.ts` and `project.service.ts` are reached only through the
+ * dynamic imports below, the first time an actual check is made. An earlier
+ * attempt bound this at module scope and hung `bun test` for 30 minutes.
+ *
+ * `integration.service.ts` and `subscription.service.ts` import this
+ * directly instead of going through `ctx.services.auth`: both are invoked by
+ * `packages/trpc`'s still-live V1 delegate routers with a bare `userId`, no
+ * `ctx`, so they cannot reach a service. Operator-authorized (docs/TECH_DEBT.md
+ * §5b); the exemption expires when `packages/trpc` dies at P10.
+ */
+export function getAccessChecks(): Promise<AccessChecks<IProjectAccess>> {
+ if (!accessChecksPromise) {
+ accessChecksPromise = Promise.all([
+ loadAccessLookups(),
+ import('../project/project.service'),
+ ]).then(
+ ([
+ { getProjectAccess, canWriteProject, getOrganizationAccess },
+ { getProjectById },
+ ]) =>
+ createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+ })
+ );
+ }
+ return accessChecksPromise;
+}
+
/**
- * Registered in `services.ts`. `deps` is unused today (every function here is
- * pure or reads its own env) — kept on the signature because every other
- * module's factory takes it, and a method that later needs `logger` should
- * not change the call site.
+ * Test-only escape hatch. `accessChecksPromise` is a true process-lifetime
+ * singleton by design (see `getAccessChecks` above), so a test that mocks
+ * `access-lookups`/`project.service` to prove the injection seam works must
+ * clear it afterward — otherwise, under a bare (non-`--isolate`) `bun test`,
+ * the fake closures it built would answer every later file's real access
+ * checks too.
+ */
+export function resetAccessChecksForTests(): void {
+ accessChecksPromise = undefined;
+}
+
+/**
+ * Registered in `services.ts`. `deps` is unused (every member here is either
+ * pure, reads its own env, or — for the access checks — reaches the shared,
+ * memoized `getAccessChecks()` above) — kept on the signature because every
+ * other module's factory takes it, and a method that later needs `logger`
+ * should not change the call site.
*/
export function createAuthService(_deps: ServiceDeps): AuthService {
return {
+ async requireProjectAccess(args) {
+ return (await getAccessChecks()).requireProjectAccess(args);
+ },
+ async requireOrganizationAdmin(args) {
+ return (await getAccessChecks()).requireOrganizationAdmin(args);
+ },
+ async requireProjectAdmin(args) {
+ return (await getAccessChecks()).requireProjectAdmin(args);
+ },
+ async getProjectAccess(args) {
+ return (await loadAccessLookups()).getProjectAccess(args);
+ },
+ async getOrganizationAccess(args) {
+ return (await loadAccessLookups()).getOrganizationAccess(args);
+ },
+ async getClientAccess(args) {
+ return (await loadAccessLookups()).getClientAccess(args);
+ },
hashPassword,
verifyPasswordHash,
generateSessionToken,
diff --git a/packages/core/src/modules/chart/chart.rpc.ts b/packages/core/src/modules/chart/chart.rpc.ts
index 8e5220aa0..0909513b4 100644
--- a/packages/core/src/modules/chart/chart.rpc.ts
+++ b/packages/core/src/modules/chart/chart.rpc.ts
@@ -2,9 +2,10 @@
//
// 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. packages/trpc's
-// chart router delegates its handler bodies onto `./chart.service` while
-// keeping V1's own procedure stack and 60s response cache.
+// 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.
//
// V1's `chartProcedure` (funnel, conversion, chart, aggregate, cohort) also
// admits anonymous callers holding a valid share: `shareId` + `id` resolve the
@@ -48,10 +49,6 @@ const zShareable = z.object({
const zShareableReportInput = zReportInput.and(zShareable);
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function loadReportsService() {
return import('@openpanel/core');
}
@@ -63,17 +60,12 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireAccess(
- userId: string,
- projectId: string,
- level: 'read' | 'write'
-) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level });
-}
-
async function requireReadAccess(ctx: TrpcContext, projectId: string) {
- await requireAccess(requireLogin(ctx.session.userId), projectId, 'read');
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'read',
+ });
}
/**
diff --git a/packages/core/src/modules/chart/src/access.ts b/packages/core/src/modules/chart/src/access.ts
deleted file mode 100644
index 1ec67b626..000000000
--- a/packages/core/src/modules/chart/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// session/src/access.ts and event/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/client/client.rpc.ts b/packages/core/src/modules/client/client.rpc.ts
index 621153fb8..7dc8e0d67 100644
--- a/packages/core/src/modules/client/client.rpc.ts
+++ b/packages/core/src/modules/client/client.rpc.ts
@@ -10,10 +10,8 @@
// PATTERN) — this module has no queue/cron of its own, so there is no
// `ctx.services.client`, same as `user`/`conversation`.
//
-// `./src/access.ts` binds core's shared/access.ts ladder to @openpanel/db's
-// real lookups, dynamically imported (`loadAccessChecks`) same as
-// organization.rpc.ts, so a static import here does not pull
-// @openpanel/db's prisma client into every core test file.
+// 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';
@@ -26,10 +24,6 @@ import {
updateClientForOrganization,
} from './client.service';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -50,8 +44,10 @@ export const clientRouter = createTRPCRouter({
.input(z.object({ id: z.string(), name: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { getClientAccess } = await loadAccessChecks();
- const access = await getClientAccess({ userId, clientId: input.id });
+ const access = await ctx.services.auth.getClientAccess({
+ userId,
+ clientId: input.id,
+ });
if (!access) {
throw new TRPCForbiddenError('You do not have access to this client');
}
@@ -77,11 +73,10 @@ export const clientRouter = createTRPCRouter({
)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireOrganizationAdmin } = await loadAccessChecks();
// Minting an ingestion credential - a `root` one at the caller's
// choosing - is admin-tier, not something any org member should be
// able to do.
- await requireOrganizationAdmin({
+ await ctx.services.auth.requireOrganizationAdmin({
userId,
organizationId: input.organizationId,
message: 'Only organization admins can create API clients',
@@ -112,9 +107,8 @@ export const clientRouter = createTRPCRouter({
throw new TRPCForbiddenError('You do not have access to this client');
}
- const { requireOrganizationAdmin } = await loadAccessChecks();
// Revoking a credential breaks ingestion for whoever is using it.
- await requireOrganizationAdmin({
+ await ctx.services.auth.requireOrganizationAdmin({
userId,
organizationId: client.organizationId,
message: 'Only organization admins can delete API clients',
diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.ts
index 9e1d484ac..d5b36d174 100644
--- a/packages/core/src/modules/client/client.service.ts
+++ b/packages/core/src/modules/client/client.service.ts
@@ -1,9 +1,9 @@
// Moved from packages/db/src/services/clients.service.ts (M6-002, module
// map: client owns "R,H,S" — no constants file, per the module map). packages/db
-// keeps a re-export shim: apps/api/src/utils/auth.ts, core's mcp module and
-// several other core modules' `src/access.ts` still reach `getClientByIdCached`
-// / `ClientType` through @openpanel/db's barrel — same shape as
-// packages/db/src/services/organization.service.ts since M6-001.
+// keeps a re-export shim: apps/api/src/utils/auth.ts and core's mcp module
+// still reach `getClientByIdCached` / `ClientType` through @openpanel/db's
+// barrel — same shape as packages/db/src/services/organization.service.ts
+// since M6-001.
//
// The /manage REST CRUD bodies (apps/api/src/controllers/manage.controller.ts's
// listClients/getClient/createClient/updateClient/deleteClient) move here
diff --git a/packages/core/src/modules/client/src/access.ts b/packages/core/src/modules/client/src/access.ts
deleted file mode 100644
index 28c7ac8f5..000000000
--- a/packages/core/src/modules/client/src/access.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. `getClientAccess` has no
-// ladder wrapper (V1's packages/trpc/src/access.ts re-exports it bare too),
-// only `requireOrganizationAdmin` goes through `createAccessChecks`.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-import { getProjectById } from '../../project/project.service';
-
-export { getClientAccess } from '@openpanel/core';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireOrganizationAdmin = checks.requireOrganizationAdmin;
diff --git a/packages/core/src/modules/cohort/cohort.rpc.ts b/packages/core/src/modules/cohort/cohort.rpc.ts
index 19d99e786..7f733f0c9 100644
--- a/packages/core/src/modules/cohort/cohort.rpc.ts
+++ b/packages/core/src/modules/cohort/cohort.rpc.ts
@@ -45,10 +45,6 @@ import {
const EXPORT_PROFILES_MAX_LIMIT = 10_000;
const EXPORT_PROFILES_DEFAULT_LIMIT = 10_000;
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function loadDb() {
return import('@openpanel/db/src/prisma-client').then((m) => m.db);
}
@@ -70,8 +66,7 @@ export const cohortRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
@@ -106,8 +101,7 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: cohort.projectId,
level: 'read',
@@ -150,8 +144,7 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: existingCohort.projectId,
level: 'write',
@@ -189,8 +182,7 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: cohort.projectId,
level: 'write',
@@ -218,8 +210,7 @@ export const cohortRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
@@ -236,8 +227,7 @@ export const cohortRouter = createTRPCRouter({
.input(z.object({ projectId: z.string(), cohortId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
@@ -250,8 +240,7 @@ export const cohortRouter = createTRPCRouter({
.input(z.object({ projectId: z.string(), cohortId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
@@ -264,8 +253,7 @@ export const cohortRouter = createTRPCRouter({
.input(z.object({ projectId: z.string(), cohortId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
@@ -287,8 +275,7 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: cohort.projectId,
level: 'read',
@@ -307,8 +294,7 @@ export const cohortRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
@@ -347,8 +333,7 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: cohort.projectId,
level: 'read',
@@ -379,8 +364,7 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: cohort.projectId,
level: 'write',
diff --git a/packages/core/src/modules/cohort/src/access.ts b/packages/core/src/modules/cohort/src/access.ts
deleted file mode 100644
index b82a18072..000000000
--- a/packages/core/src/modules/cohort/src/access.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/conversation/conversation.rpc.ts b/packages/core/src/modules/conversation/conversation.rpc.ts
index f1873dd89..fa3ebf40e 100644
--- a/packages/core/src/modules/conversation/conversation.rpc.ts
+++ b/packages/core/src/modules/conversation/conversation.rpc.ts
@@ -30,10 +30,6 @@ const LIST_LIMIT_DEFAULT = 50;
const TITLE_MIN_LENGTH = 1;
const TITLE_MAX_LENGTH = 80;
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function loadOrganizationService() {
return import('@openpanel/core');
}
@@ -67,8 +63,7 @@ export const conversationRouter = createTRPCRouter({
)
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
@@ -122,8 +117,7 @@ export const conversationRouter = createTRPCRouter({
throw new TRPCNotFoundError('Conversation not found');
}
} else {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
diff --git a/packages/core/src/modules/conversation/src/access.ts b/packages/core/src/modules/conversation/src/access.ts
deleted file mode 100644
index b82a18072..000000000
--- a/packages/core/src/modules/conversation/src/access.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/dashboard/dashboard.rpc.ts b/packages/core/src/modules/dashboard/dashboard.rpc.ts
index 776217526..2a5612336 100644
--- a/packages/core/src/modules/dashboard/dashboard.rpc.ts
+++ b/packages/core/src/modules/dashboard/dashboard.rpc.ts
@@ -2,11 +2,12 @@
//
// 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. 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).
+// 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).
import { z } from 'zod';
import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
@@ -20,10 +21,6 @@ import {
updateDashboard,
} from './dashboard.service';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -31,21 +28,20 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireAccess(
- userId: string,
- projectId: string,
- level: 'read' | 'write'
-) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level });
-}
-
async function requireReadAccess(ctx: TrpcContext, projectId: string) {
- await requireAccess(requireLogin(ctx.session.userId), projectId, 'read');
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'read',
+ });
}
async function requireWriteAccess(ctx: TrpcContext, projectId: string) {
- await requireAccess(requireLogin(ctx.session.userId), projectId, 'write');
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'write',
+ });
}
export const dashboardRouter = createTRPCRouter({
diff --git a/packages/core/src/modules/dashboard/src/access.ts b/packages/core/src/modules/dashboard/src/access.ts
deleted file mode 100644
index a080240fc..000000000
--- a/packages/core/src/modules/dashboard/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// chart/src/access.ts and project/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/event/event.rpc.ts b/packages/core/src/modules/event/event.rpc.ts
index 58adbfcfb..c75c69f40 100644
--- a/packages/core/src/modules/event/event.rpc.ts
+++ b/packages/core/src/modules/event/event.rpc.ts
@@ -20,7 +20,7 @@ import {
zTimeInterval,
} from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
import {
getBotEventsPage,
@@ -47,10 +47,6 @@ const zChartWindow = z.object({
interval: zTimeInterval,
});
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function loadPagesRuntime() {
return Promise.all([
import('@openpanel/core'),
@@ -77,12 +73,15 @@ function requireLogin(userId: string | null | undefined): string {
}
async function requireAccess(
- userId: string,
+ ctx: TrpcContext,
projectId: string,
level: 'read' | 'write'
) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level });
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level,
+ });
}
function formatClickhouseDateTime(date: Date): string {
@@ -101,15 +100,13 @@ export const eventRouter = createTRPCRouter({
})
)
.mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'write');
+ await requireAccess(ctx, input.projectId, 'write');
return updateEventMeta(input);
}),
byId: procedure.input(zEventRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
const event = await getEventById(input);
if (!event) {
@@ -119,8 +116,7 @@ export const eventRouter = createTRPCRouter({
}),
details: procedure.input(zEventRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
const details = await getEventDetails(input);
if (!details) {
@@ -146,8 +142,7 @@ export const eventRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getEventListPage(input);
}),
@@ -155,8 +150,7 @@ export const eventRouter = createTRPCRouter({
conversionNames: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getConversionEventNames(input.projectId);
}),
@@ -173,8 +167,7 @@ export const eventRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getConversionListPage(input);
}),
@@ -188,8 +181,7 @@ export const eventRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getBotEventsPage(input);
}),
@@ -203,8 +195,7 @@ export const eventRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
const { getSettingsForProject, getChartStartEndDate, pagesService } =
await loadPagesRuntime();
@@ -223,8 +214,7 @@ export const eventRouter = createTRPCRouter({
pagesTimeseries: procedure
.input(zChartWindow)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
const { getSettingsForProject, getChartStartEndDate, pagesService } =
await loadPagesRuntime();
@@ -240,8 +230,7 @@ export const eventRouter = createTRPCRouter({
}),
previousPages: procedure.input(zChartWindow).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
const { getSettingsForProject, getChartStartEndDate, pagesService } =
await loadPagesRuntime();
@@ -265,8 +254,7 @@ export const eventRouter = createTRPCRouter({
pageTimeseries: procedure
.input(zChartWindow.extend({ origin: z.string(), path: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
const { getSettingsForProject, getChartStartEndDate, pagesService } =
await loadPagesRuntime();
@@ -286,8 +274,7 @@ export const eventRouter = createTRPCRouter({
origin: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getTopOrigins(input.projectId);
}),
diff --git a/packages/core/src/modules/event/src/access.ts b/packages/core/src/modules/event/src/access.ts
deleted file mode 100644
index e3dff4359..000000000
--- a/packages/core/src/modules/event/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// session/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/group/group.rpc.ts b/packages/core/src/modules/group/group.rpc.ts
index e2c4b3987..28c3287b6 100644
--- a/packages/core/src/modules/group/group.rpc.ts
+++ b/packages/core/src/modules/group/group.rpc.ts
@@ -9,7 +9,7 @@
// V1's own `protectedProcedure` stack.
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import { zCreateGroup, zUpdateGroup } from './group.constants';
import {
@@ -33,10 +33,6 @@ const DEFAULT_LIST_TAKE = 50;
const zGroupRef = z.object({ id: z.string(), projectId: z.string() });
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -45,12 +41,15 @@ function requireLogin(userId: string | null | undefined): string {
}
async function requireAccess(
- userId: string,
+ ctx: TrpcContext,
projectId: string,
level: 'read' | 'write'
) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level });
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level,
+ });
}
export const groupRouter = createTRPCRouter({
@@ -65,37 +64,32 @@ export const groupRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupListPage(input);
}),
byId: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupById(input.id, input.projectId);
}),
create: procedure.input(zCreateGroup).mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'write');
+ await requireAccess(ctx, input.projectId, 'write');
return createGroup(input);
}),
update: procedure.input(zUpdateGroup).mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'write');
+ await requireAccess(ctx, input.projectId, 'write');
const { id, projectId, ...data } = input;
return updateGroup(id, projectId, data);
}),
delete: procedure.input(zGroupRef).mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'write');
+ await requireAccess(ctx, input.projectId, 'write');
return deleteGroup(input.id, input.projectId);
}),
@@ -103,29 +97,25 @@ export const groupRouter = createTRPCRouter({
types: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupTypes(input.projectId);
}),
metrics: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupMetrics(input.id, input.projectId);
}),
activity: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupActivity(input.id, input.projectId);
}),
memberGrowth: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupMemberGrowth(input.id, input.projectId);
}),
@@ -141,22 +131,19 @@ export const groupRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupMemberProfilesPage(input);
}),
mostEvents: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupMostEvents(input.id, input.projectId);
}),
popularRoutes: procedure.input(zGroupRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupPopularRoutes(input.id, input.projectId);
}),
@@ -164,8 +151,7 @@ export const groupRouter = createTRPCRouter({
properties: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupPropertyKeys(input.projectId);
}),
@@ -173,8 +159,7 @@ export const groupRouter = createTRPCRouter({
listByIds: procedure
.input(z.object({ projectId: z.string(), ids: z.array(z.string()) }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireAccess(userId, input.projectId, 'read');
+ await requireAccess(ctx, input.projectId, 'read');
return getGroupsByIds(input.projectId, input.ids);
}),
diff --git a/packages/core/src/modules/group/src/access.ts b/packages/core/src/modules/group/src/access.ts
deleted file mode 100644
index e3dff4359..000000000
--- a/packages/core/src/modules/group/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// session/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/gsc/gsc.rpc.ts b/packages/core/src/modules/gsc/gsc.rpc.ts
index 27011ee17..aaa5ce23a 100644
--- a/packages/core/src/modules/gsc/gsc.rpc.ts
+++ b/packages/core/src/modules/gsc/gsc.rpc.ts
@@ -9,23 +9,15 @@
// delegates its handler bodies to `ctx.services.gsc` (DELEGATE PATTERN),
// so nothing here is a live regression.
//
-// 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`.
import { zRange, zTimeInterval } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import { Arctic, googleGsc } from '../auth/auth.service';
-// Lazy, deliberately: ./src/access reaches @openpanel/db's real lookups,
-// which construct a real pino logger — with a transport worker thread — at
-// import time. See gsc.service.ts's header for the full reasoning.
-function loadAccessChecks() {
- return import('./src/access');
-}
-
const OAUTH_COOKIE_MAX_AGE_SECONDS = 60 * 10;
const zGscDateInput = z.object({
@@ -53,30 +45,34 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireRead(userId: string, projectId: string) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level: 'read' });
+async function requireRead(ctx: TrpcContext, projectId: string) {
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'read',
+ });
}
-async function requireWrite(userId: string, projectId: string) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level: 'write' });
+async function requireWrite(ctx: TrpcContext, projectId: string) {
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'write',
+ });
}
export const gscRouter = createTRPCRouter({
getConnection: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input: { projectId }, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, projectId);
+ await requireRead(ctx, projectId);
return ctx.services.gsc.getConnection(projectId);
}),
initiateOAuth: procedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input: { projectId }, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireWrite(userId, projectId);
+ await requireWrite(ctx, projectId);
const state = Arctic.generateState();
const codeVerifier = Arctic.generateCodeVerifier();
@@ -97,16 +93,14 @@ export const gscRouter = createTRPCRouter({
getSites: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input: { projectId }, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, projectId);
+ await requireRead(ctx, projectId);
return ctx.services.gsc.listSites(projectId);
}),
selectSite: procedure
.input(z.object({ projectId: z.string(), siteUrl: z.string() }))
.mutation(async ({ input: { projectId, siteUrl }, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireWrite(userId, projectId);
+ await requireWrite(ctx, projectId);
await ctx.services.gsc.selectSite(projectId, siteUrl);
return { ok: true };
@@ -115,16 +109,14 @@ export const gscRouter = createTRPCRouter({
disconnect: procedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input: { projectId }, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireWrite(userId, projectId);
+ await requireWrite(ctx, projectId);
await ctx.services.gsc.disconnect(projectId);
return { ok: true };
}),
getOverview: procedure.input(zGscDateInput).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
@@ -144,8 +136,7 @@ export const gscRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
@@ -161,8 +152,7 @@ export const gscRouter = createTRPCRouter({
getPageDetails: procedure
.input(zGscDateInput.extend({ page: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
@@ -178,8 +168,7 @@ export const gscRouter = createTRPCRouter({
getQueryDetails: procedure
.input(zGscDateInput.extend({ query: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
@@ -199,8 +188,7 @@ export const gscRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
@@ -216,8 +204,7 @@ export const gscRouter = createTRPCRouter({
getSearchEngines: procedure
.input(zGscDateInput)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
@@ -230,8 +217,7 @@ export const gscRouter = createTRPCRouter({
}),
getAiEngines: procedure.input(zGscDateInput).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
@@ -242,8 +228,7 @@ export const gscRouter = createTRPCRouter({
getPreviousOverview: procedure
.input(zGscDateInput)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
@@ -259,8 +244,7 @@ export const gscRouter = createTRPCRouter({
getCannibalization: procedure
.input(zGscDateInput)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireRead(userId, input.projectId);
+ await requireRead(ctx, input.projectId);
const { startDate, endDate } = await ctx.services.gsc.resolveDateRange(
input.projectId,
input
diff --git a/packages/core/src/modules/gsc/src/access.ts b/packages/core/src/modules/gsc/src/access.ts
deleted file mode 100644
index b82a18072..000000000
--- a/packages/core/src/modules/gsc/src/access.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/import/import.rpc.ts b/packages/core/src/modules/import/import.rpc.ts
index 80fab08a6..5a7d58cc5 100644
--- a/packages/core/src/modules/import/import.rpc.ts
+++ b/packages/core/src/modules/import/import.rpc.ts
@@ -12,9 +12,8 @@
// 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.
//
-// 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`.
import { z } from 'zod';
import { createTRPCRouter, procedure } from '../../rpc/base';
@@ -25,10 +24,6 @@ import {
} from '../../rpc/errors';
import { zCreateImport } from './import.constants';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function loadDb() {
return import('@openpanel/db/src/prisma-client').then((m) => m.db);
}
@@ -45,8 +40,7 @@ export const importRouter = createTRPCRouter({
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'read',
@@ -69,8 +63,7 @@ export const importRouter = createTRPCRouter({
include: { project: true },
});
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: importRecord.projectId,
level: 'read',
@@ -81,8 +74,7 @@ export const importRouter = createTRPCRouter({
create: procedure.input(zCreateImport).mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'write',
@@ -132,8 +124,7 @@ export const importRouter = createTRPCRouter({
where: { id: input.id },
});
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: importRecord.projectId,
level: 'write',
@@ -155,8 +146,7 @@ export const importRouter = createTRPCRouter({
where: { id: input.id },
});
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: importRecord.projectId,
level: 'write',
diff --git a/packages/core/src/modules/import/src/access.ts b/packages/core/src/modules/import/src/access.ts
deleted file mode 100644
index b82a18072..000000000
--- a/packages/core/src/modules/import/src/access.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/insight/insight.rpc.ts b/packages/core/src/modules/insight/insight.rpc.ts
index 5e25f7b98..26dd93025 100644
--- a/packages/core/src/modules/insight/insight.rpc.ts
+++ b/packages/core/src/modules/insight/insight.rpc.ts
@@ -9,23 +9,14 @@
// delegates its handler bodies to `ctx.services.insight` (DELEGATE PATTERN),
// so nothing here is a live regression.
//
-// 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 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 { TRPCAccessError } from '../../rpc/errors';
-// Lazy, deliberately: ./src/access reaches @openpanel/db's real lookups,
-// which (like insight.service.ts's db/ch access) construct a real pino
-// logger — with a transport worker thread — at import time. See
-// insight.service.ts's header for the full reasoning.
-function loadAccessChecks() {
- return import('./src/access');
-}
-
const DAY_MS = 24 * 60 * 60 * 1000;
const EXPLAIN_COLUMNS = [
'referrer_name',
@@ -51,8 +42,11 @@ export const insightRouter = createTRPCRouter({
)
.query(async ({ input: { projectId, limit }, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level: 'read' });
+ await ctx.services.auth.requireProjectAccess({
+ userId,
+ projectId,
+ level: 'read',
+ });
// Fetch more than needed to account for deduplication. AI
// relevanceScore leads (un-enriched insights sort last via
@@ -104,8 +98,11 @@ export const insightRouter = createTRPCRouter({
)
.query(async ({ input: { projectId, limit }, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level: 'read' });
+ await ctx.services.auth.requireProjectAccess({
+ userId,
+ projectId,
+ level: 'read',
+ });
return ctx.services.insight.listAllInsights({ projectId, limit });
}),
@@ -143,8 +140,7 @@ export const insightRouter = createTRPCRouter({
// Reads an existing insight and explains it. Nothing about the project
// changes, so a read-level member may do it.
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: insight.projectId,
level: 'read',
diff --git a/packages/core/src/modules/insight/src/access.ts b/packages/core/src/modules/insight/src/access.ts
deleted file mode 100644
index b82a18072..000000000
--- a/packages/core/src/modules/insight/src/access.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/integration/integration.service.ts b/packages/core/src/modules/integration/integration.service.ts
index e4d580a48..8bb94a469 100644
--- a/packages/core/src/modules/integration/integration.service.ts
+++ b/packages/core/src/modules/integration/integration.service.ts
@@ -8,8 +8,14 @@
// simple input-shape ladder checks project.rpc.ts/notification.rpc.ts do
// themselves, the access assertions travel WITH the business logic, ported
// verbatim from the router's own `assertProjectAccessAndGetOrg`/
-// `assertIntegrationAccess` helpers. `./src/access.ts` binds the shared
-// ladder to @openpanel/db, the same way every other module's does.
+// `assertIntegrationAccess` helpers. Every exported function here is still
+// called directly by `packages/trpc`'s LIVE V1 router with nothing but a
+// `userId` (DELEGATE PATTERN), so these can't take a `ctx`/`deps` the way a
+// core-only module's checks would; `requireProjectAccess` /
+// `requireOrganizationAdmin` come from auth.service.ts's single,
+// lazily-memoized `getAccessChecks()` (M10-002); `getOrganizationAccess` is a
+// raw lookup (no ladder involved), reached directly from the sibling
+// `shared/access-lookups.ts`.
//
// db access is LAZY (`loadDb` below), not a static top-level import — see
// organization.service.ts's header for the full reasoning (constructing
@@ -32,6 +38,8 @@ import {
slackInstaller,
} from '../../clients/integrations/slack';
import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';
+import { getOrganizationAccess } from '../../shared/access-lookups';
+import { getAccessChecks } from '../auth/auth.service';
import { BASE_INTEGRATIONS } from '../notification/notification.service';
import type { IIntegrationConfig, ISlackConfig } from './integration.constants';
import { zSlackAuthResponse } from './src/slack-contract';
@@ -40,10 +48,6 @@ function loadDb() {
return import('@openpanel/db/src/prisma-client').then((m) => m.db);
}
-function loadAccess() {
- return import('./src/access');
-}
-
// Credentials are write-only: they are encrypted at rest and never travel back
// to a client. `read` on a project is bare membership, so returning the stored
// ciphertext would hand every project member the org's object-store keys — and
@@ -75,7 +79,7 @@ async function assertProjectAccessAndGetOrg(
projectId: string,
level: 'read' | 'write'
) {
- const { requireProjectAccess } = await loadAccess();
+ const { requireProjectAccess } = await getAccessChecks();
await requireProjectAccess({ userId, projectId, level });
const db = await loadDb();
@@ -95,11 +99,8 @@ async function assertIntegrationAccess(
integration: { projectId: string | null; organizationId: string },
level: 'read' | 'write'
) {
- const {
- getOrganizationAccess,
- requireOrganizationAdmin,
- requireProjectAccess,
- } = await loadAccess();
+ const { requireProjectAccess, requireOrganizationAdmin } =
+ await getAccessChecks();
if (integration.projectId) {
await requireProjectAccess({
@@ -325,7 +326,7 @@ export async function testIntegrationConnection(
userId: string,
input: { projectId: string; config: IIntegrationConfig }
) {
- const { requireProjectAccess } = await loadAccess();
+ const { requireProjectAccess } = await getAccessChecks();
await requireProjectAccess({
userId,
projectId: input.projectId,
@@ -345,7 +346,7 @@ export async function testExportIntegrationConnection(
userId: string,
input: { projectId: string; config: IIntegrationConfig }
) {
- const { requireProjectAccess } = await loadAccess();
+ const { requireProjectAccess } = await getAccessChecks();
await requireProjectAccess({
userId,
projectId: input.projectId,
diff --git a/packages/core/src/modules/integration/src/access.ts b/packages/core/src/modules/integration/src/access.ts
deleted file mode 100644
index 2ff2c18f9..000000000
--- a/packages/core/src/modules/integration/src/access.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// ../../notification/src/access.ts (M6-005).
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
-export const requireOrganizationAdmin = checks.requireOrganizationAdmin;
-// `assertIntegrationAccess`'s read-branch on a legacy org-wide row needs bare
-// membership, not the admin gate — re-exported raw, same as
-// packages/trpc/src/access.ts does for V1's integration router.
-export { getOrganizationAccess } from '@openpanel/core';
diff --git a/packages/core/src/modules/notification/notification.rpc.ts b/packages/core/src/modules/notification/notification.rpc.ts
index 7ee60c4ab..ddf3a8991 100644
--- a/packages/core/src/modules/notification/notification.rpc.ts
+++ b/packages/core/src/modules/notification/notification.rpc.ts
@@ -14,9 +14,8 @@
// `deleteRule` and `createOrUpdateRule` re-check access against the
// *existing* rule's project, not just the input's).
//
-// 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 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';
@@ -31,10 +30,6 @@ import {
listNotifications,
} from './notification.service';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -65,8 +60,7 @@ export const notificationRouter = createTRPCRouter({
// Clear the cache for the project
await getNotificationRulesByProjectId.clear(input.projectId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'write',
@@ -74,7 +68,7 @@ export const notificationRouter = createTRPCRouter({
if (input.id) {
const existing = await getNotificationRuleByIdOrThrow(input.id);
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: existing.projectId,
level: 'write',
@@ -90,8 +84,7 @@ export const notificationRouter = createTRPCRouter({
const userId = requireLogin(ctx.session.userId);
const rule = await getNotificationRuleByIdOrThrow(input.id);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: rule.projectId,
level: 'write',
diff --git a/packages/core/src/modules/notification/src/access.ts b/packages/core/src/modules/notification/src/access.ts
deleted file mode 100644
index b82a18072..000000000
--- a/packages/core/src/modules/notification/src/access.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/organization/organization.rpc.ts b/packages/core/src/modules/organization/organization.rpc.ts
index 6bb263603..950eb268f 100644
--- a/packages/core/src/modules/organization/organization.rpc.ts
+++ b/packages/core/src/modules/organization/organization.rpc.ts
@@ -9,9 +9,8 @@
// delegates its handler bodies to `ctx.services.organization` (DELEGATE
// PATTERN), so nothing here is a live regression.
//
-// The organization-admin 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 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
@@ -23,17 +22,13 @@ import {
zUpdateMemberAccess,
} from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
import {
TRPCAccessError,
TRPCBadRequestError,
TRPCForbiddenError,
} from '../../rpc/errors';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -41,9 +36,11 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireOrgAdmin(userId: string, organizationId: string) {
- const { requireOrganizationAdmin } = await loadAccessChecks();
- await requireOrganizationAdmin({ userId, organizationId });
+async function requireOrgAdmin(ctx: TrpcContext, organizationId: string) {
+ await ctx.services.auth.requireOrganizationAdmin({
+ userId: requireLogin(ctx.session.userId),
+ organizationId,
+ });
}
export const organizationRouter = createTRPCRouter({
@@ -66,8 +63,7 @@ export const organizationRouter = createTRPCRouter({
.input(z.object({ organizationId: z.string() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { getOrganizationAccess } = await loadAccessChecks();
- const access = await getOrganizationAccess({
+ const access = await ctx.services.auth.getOrganizationAccess({
userId,
organizationId: input.organizationId,
});
@@ -80,16 +76,14 @@ export const organizationRouter = createTRPCRouter({
update: procedure
.input(zEditOrganization)
.mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireOrgAdmin(userId, input.id);
+ await requireOrgAdmin(ctx, input.id);
return ctx.services.organization.update(input);
}),
delete: procedure
.input(z.object({ organizationId: z.string() }))
.mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireOrgAdmin(userId, input.organizationId);
+ await requireOrgAdmin(ctx, input.organizationId);
await ctx.services.organization.scheduleDeletion(input.organizationId);
return true;
}),
@@ -97,15 +91,14 @@ export const organizationRouter = createTRPCRouter({
cancelDeletion: procedure
.input(z.object({ organizationId: z.string() }))
.mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireOrgAdmin(userId, input.organizationId);
+ await requireOrgAdmin(ctx, input.organizationId);
await ctx.services.organization.cancelDeletion(input.organizationId);
return true;
}),
inviteUser: procedure.input(zInviteUser).mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- await requireOrgAdmin(userId, input.organizationId);
+ await requireOrgAdmin(ctx, input.organizationId);
return ctx.services.organization.inviteUser({
organizationId: input.organizationId,
email: input.email,
@@ -118,11 +111,11 @@ export const organizationRouter = createTRPCRouter({
revokeInvite: procedure
.input(z.object({ inviteId: z.string() }))
.mutation(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
+ requireLogin(ctx.session.userId);
const invite = await ctx.services.organization.getInviteOrThrow(
input.inviteId
);
- await requireOrgAdmin(userId, invite.organizationId);
+ await requireOrgAdmin(ctx, invite.organizationId);
return ctx.services.organization.revokeInvite(input.inviteId);
}),
@@ -136,7 +129,7 @@ export const organizationRouter = createTRPCRouter({
)
.mutation(async ({ input, ctx }) => {
const requestedByUserId = requireLogin(ctx.session.userId);
- await requireOrgAdmin(requestedByUserId, input.organizationId);
+ await requireOrgAdmin(ctx, input.organizationId);
await ctx.services.organization.removeMember({
organizationId: input.organizationId,
memberId: input.id,
@@ -152,7 +145,7 @@ export const organizationRouter = createTRPCRouter({
if (input.userId === userId) {
throw new TRPCForbiddenError('You cannot update your own access');
}
- await requireOrgAdmin(userId, input.organizationId);
+ await requireOrgAdmin(ctx, input.organizationId);
return ctx.services.organization.updateMemberAccess({
organizationId: input.organizationId,
targetUserId: input.userId,
@@ -163,16 +156,14 @@ export const organizationRouter = createTRPCRouter({
members: procedure
.input(z.object({ organizationId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireOrgAdmin(userId, input.organizationId);
+ await requireOrgAdmin(ctx, input.organizationId);
return ctx.services.organization.members(input.organizationId);
}),
invitations: procedure
.input(z.object({ organizationId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireOrgAdmin(userId, input.organizationId);
+ await requireOrgAdmin(ctx, input.organizationId);
return ctx.services.organization.invitations(input.organizationId);
}),
diff --git a/packages/core/src/modules/organization/src/access.ts b/packages/core/src/modules/organization/src/access.ts
deleted file mode 100644
index 007a09b95..000000000
--- a/packages/core/src/modules/organization/src/access.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// conversation/src/access.ts and gsc/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-export { getOrganizationAccess } from '@openpanel/core';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireOrganizationAdmin = checks.requireOrganizationAdmin;
diff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.ts
index dcc1c8324..8d71e09c6 100644
--- a/packages/core/src/modules/overview/overview.rpc.ts
+++ b/packages/core/src/modules/overview/overview.rpc.ts
@@ -11,13 +11,6 @@
// router; they moved to `overviewService.getLiveData` (src/overview.sql.ts)
// so every query this module runs goes through the same `sql` tag (M7-005).
-import { format } from 'date-fns';
-import { getConversionEventNames } from '../event/event.service';
-import { getActiveVisitorCount } from '../realtime/realtime.service';
-import { getReferrerSpikes } from '../insight/insight.service';
-import { getOrganizationSubscriptionChartEndDate } from '../organization/organization.service';
-import { getSettingsForProject } from '../organization/organization.service';
-import { validateOverviewShareAccess } from '../share/share.service';
import {
getChartPrevStartEndDate,
getChartStartEndDate,
@@ -27,9 +20,18 @@ import {
pageContextSchema,
zRange,
} from '@openpanel/validation';
+import { format } from 'date-fns';
import { z } from 'zod';
import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
+import { getConversionEventNames } from '../event/event.service';
+import { getReferrerSpikes } from '../insight/insight.service';
+import {
+ getOrganizationSubscriptionChartEndDate,
+ getSettingsForProject,
+} from '../organization/organization.service';
+import { getActiveVisitorCount } from '../realtime/realtime.service';
+import { validateOverviewShareAccess } from '../share/share.service';
import {
overviewService,
zGetMapDataInput,
@@ -42,10 +44,6 @@ import {
zGetUserJourneyInput,
} from './overview.service';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
// Lazy, not a static import: the assistant module's chatApp chain reaches
// deep into @openpanel/db and @openpanel/queue (see index.ts's own
// `loadAssistant()` for the full story) — a static import here would pull
@@ -62,17 +60,12 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireAccess(
- userId: string,
- projectId: string,
- level: 'read' | 'write'
-) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level });
-}
-
async function requireReadAccess(ctx: TrpcContext, projectId: string) {
- await requireAccess(requireLogin(ctx.session.userId), projectId, 'read');
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'read',
+ });
}
/**
@@ -92,7 +85,9 @@ async function resolveOverviewAccess(
input.projectId,
{
cookies: ctx.cookies,
- session: ctx.session.userId ? { userId: ctx.session.userId } : undefined,
+ session: ctx.session.userId
+ ? { userId: ctx.session.userId }
+ : undefined,
}
);
if (!shareValidation.isValid) {
diff --git a/packages/core/src/modules/overview/src/access.ts b/packages/core/src/modules/overview/src/access.ts
deleted file mode 100644
index 25f45b905..000000000
--- a/packages/core/src/modules/overview/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// session/src/access.ts, event/src/access.ts and chart/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/profile/profile.rpc.ts b/packages/core/src/modules/profile/profile.rpc.ts
index df0e1da6d..02a31561a 100644
--- a/packages/core/src/modules/profile/profile.rpc.ts
+++ b/packages/core/src/modules/profile/profile.rpc.ts
@@ -10,7 +10,7 @@
import { zChartEventFilter } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
getPowerUsers,
@@ -28,10 +28,6 @@ const DEFAULT_LIST_TAKE = 50;
const zProfileRef = z.object({ profileId: z.string(), projectId: z.string() });
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -39,43 +35,41 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireReadAccess(userId: string, projectId: string) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level: 'read' });
+async function requireReadAccess(ctx: TrpcContext, projectId: string) {
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'read',
+ });
}
export const profileRouter = createTRPCRouter({
byId: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getProfileById(input.profileId, input.projectId);
}),
metrics: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getProfileMetrics(input.profileId, input.projectId);
}),
activity: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getProfileActivity(input.profileId, input.projectId);
}),
mostEvents: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getProfileMostEvents(input.profileId, input.projectId);
}),
popularRoutes: procedure.input(zProfileRef).query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getProfilePopularRoutes(input.profileId, input.projectId);
}),
@@ -83,8 +77,7 @@ export const profileRouter = createTRPCRouter({
properties: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getProfilePropertyNames(input.projectId);
}),
@@ -101,8 +94,7 @@ export const profileRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getProfileListPage(input);
}),
@@ -116,8 +108,7 @@ export const profileRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getPowerUsers(input);
}),
@@ -125,8 +116,7 @@ export const profileRouter = createTRPCRouter({
values: procedure
.input(z.object({ property: z.string(), projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getProfileValues(input);
}),
diff --git a/packages/core/src/modules/profile/src/access.ts b/packages/core/src/modules/profile/src/access.ts
deleted file mode 100644
index e3dff4359..000000000
--- a/packages/core/src/modules/profile/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// session/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/project/project.rpc.ts b/packages/core/src/modules/project/project.rpc.ts
index 6afd39599..38f6ded0f 100644
--- a/packages/core/src/modules/project/project.rpc.ts
+++ b/packages/core/src/modules/project/project.rpc.ts
@@ -10,11 +10,8 @@
// PATTERN) — this module has no queue/cron of its own, so there is no
// `ctx.services.project`, same as `user`/`conversation`.
//
-// The 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. It is dynamically imported
-// (`loadAccessChecks`), same as organization.rpc.ts, so a static import here
-// does not pull @openpanel/db's prisma client into every core test file.
+// 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';
@@ -31,10 +28,6 @@ import {
updateProjectForOrganization,
} from './project.service';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -47,8 +40,10 @@ export const projectRouter = createTRPCRouter({
.input(z.object({ projectId: z.string() }))
.query(async ({ input: { projectId }, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { getProjectAccess } = await loadAccessChecks();
- const access = await getProjectAccess({ userId, projectId });
+ const access = await ctx.services.auth.getProjectAccess({
+ userId,
+ projectId,
+ });
if (!access) {
throw new TRPCForbiddenError('You do not have access to this project');
}
@@ -61,8 +56,10 @@ export const projectRouter = createTRPCRouter({
.input(z.object({ projectId: z.string() }))
.query(async ({ input: { projectId }, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { getProjectAccess } = await loadAccessChecks();
- const access = await getProjectAccess({ userId, projectId });
+ const access = await ctx.services.auth.getProjectAccess({
+ userId,
+ projectId,
+ });
if (!access) {
throw new TRPCForbiddenError('You do not have access to this project');
}
@@ -82,8 +79,11 @@ export const projectRouter = createTRPCRouter({
update: procedure.input(zProjectUpdate).mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId: input.id, level: 'write' });
+ await ctx.services.auth.requireProjectAccess({
+ userId,
+ projectId: input.id,
+ level: 'write',
+ });
const project = await getProjectById(input.id);
if (!project) {
@@ -107,8 +107,7 @@ export const projectRouter = createTRPCRouter({
throw new TRPCForbiddenError('Organization is required');
}
- const { getOrganizationAccess } = await loadAccessChecks();
- const access = await getOrganizationAccess({
+ const access = await ctx.services.auth.getOrganizationAccess({
userId,
organizationId: input.organizationId,
});
@@ -137,9 +136,8 @@ export const projectRouter = createTRPCRouter({
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAdmin } = await loadAccessChecks();
// Destroying a project is admin-tier, matching project.create.
- await requireProjectAdmin({
+ await ctx.services.auth.requireProjectAdmin({
userId,
projectId: input.projectId,
message: 'Only organization admins can delete projects',
@@ -153,8 +151,7 @@ export const projectRouter = createTRPCRouter({
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAdmin } = await loadAccessChecks();
- await requireProjectAdmin({
+ await ctx.services.auth.requireProjectAdmin({
userId,
projectId: input.projectId,
message: 'Only organization admins can cancel a project deletion',
diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.ts
index f7391e74d..dbb62fa5c 100644
--- a/packages/core/src/modules/project/project.service.ts
+++ b/packages/core/src/modules/project/project.service.ts
@@ -2,9 +2,11 @@
// map: project owns "R,H,S,C"). packages/db keeps a re-export shim: its own
// access.service.ts and notification.service.ts still reach `getProjectById`
// / `getProjectByIdCached` through the same relative path, and
-// apps/api/src/utils/auth.ts + several other core modules' `src/access.ts`
-// reach them through @openpanel/db's barrel — same shape as
-// packages/db/src/services/organization.service.ts since M6-001.
+// apps/api/src/utils/auth.ts reaches them through @openpanel/db's barrel;
+// auth.service.ts's permission ladder (M10-002) reaches `getProjectById`
+// through a lazy dynamic import, same reasoning as this file's own `load*`
+// below — same shape as packages/db/src/services/organization.service.ts
+// since M6-001.
//
// The /manage REST CRUD bodies (apps/api/src/controllers/manage.controller.ts's
// listProjects/getProject/createProject/updateProject/deleteProject) move
diff --git a/packages/core/src/modules/project/src/access.ts b/packages/core/src/modules/project/src/access.ts
deleted file mode 100644
index 5cd8ce212..000000000
--- a/packages/core/src/modules/project/src/access.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// organization/src/access.ts and gsc/src/access.ts. `getProjectById` is
-// this module's own (../project.service), not the @openpanel/db deep path
-// other modules bind through.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-import { getProjectById } from '../project.service';
-
-export {
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
-export const requireProjectAdmin = checks.requireProjectAdmin;
diff --git a/packages/core/src/modules/realtime/realtime.routes.test.ts b/packages/core/src/modules/realtime/realtime.routes.test.ts
index b33d5cbf5..468f74b45 100644
--- a/packages/core/src/modules/realtime/realtime.routes.test.ts
+++ b/packages/core/src/modules/realtime/realtime.routes.test.ts
@@ -11,11 +11,13 @@
// listener, and a listener attached after the fact misses an event that
// already fired.
//
-// `./realtime.service` and `./src/access` are mocked (not a real Postgres/
-// ClickHouse/Redis), and `../../http/session` for the same reason
-// http/auth.test.ts mocks it: `resolveSession` is still a P6 stub. Every
-// mock is registered before the subject's first (dynamic, per-connection)
-// call — see AGENTS.md's `mock.module` idiom.
+// `./realtime.service` and `../../shared/access-lookups` (the real lookups
+// auth.service.ts's `createAuthService` binds `ctx.services.auth` to,
+// M10-002) are mocked (not a real Postgres/ClickHouse/Redis), and
+// `../../http/session` for the same reason http/auth.test.ts mocks it:
+// `resolveSession` is still a P6 stub. Every mock is registered before the
+// subject's first (dynamic, per-connection) call — see AGENTS.md's
+// `mock.module` idiom.
import {
afterAll,
@@ -78,11 +80,17 @@ afterAll(() => {
mock.module('./realtime.service', () => realService);
});
+// The real module, not `./src/access` (deleted, M10-002) — `ctx.services.auth`
+// binds these same lookups in auth.service.ts, so mocking them here is what
+// makes `ws.data.ctx.services.auth.getProjectAccess`/`getOrganizationAccess`
+// observable from the test.
+const actualAccessLookups = await import('../../shared/access-lookups');
let projectAccess: { level: string } | null = null;
let organizationAccess: { role: string } | null = null;
const getProjectAccess = mock(async () => projectAccess);
const getOrganizationAccess = mock(async () => organizationAccess);
-mock.module('./src/access', () => ({
+mock.module('../../shared/access-lookups', () => ({
+ ...actualAccessLookups,
getProjectAccess,
getOrganizationAccess,
}));
diff --git a/packages/core/src/modules/realtime/realtime.routes.ts b/packages/core/src/modules/realtime/realtime.routes.ts
index 69a2cff9b..e441a7e1a 100644
--- a/packages/core/src/modules/realtime/realtime.routes.ts
+++ b/packages/core/src/modules/realtime/realtime.routes.ts
@@ -36,17 +36,6 @@ import {
subscribeToVisitorActivity,
} from './realtime.service';
-// Dynamic, not a static top-level import: `./src/access` reaches
-// `@openpanel/core`, which re-exports from
-// `@openpanel/core`'s own barrel (`index.ts`) — and this file IS part of that
-// barrel's eager chain (`rest.routes.ts` -> `dashboardRoutes`). A static
-// import here closes the cycle mid-evaluation (a `getProjectAccess` TDZ
-// ReferenceError); every other H module's `src/access.ts` reach is already
-// dynamic for the same reason (mcp.routes.ts, assistant.routes.ts).
-function loadAccessChecks() {
- return import('./src/access');
-}
-
const NO_ACTIVE_SESSION_MESSAGE = 'No active session';
const NO_ACCESS_MESSAGE = 'No access';
@@ -116,8 +105,10 @@ export const realtimeRoutes = defineRoutes((app) =>
return;
}
- const { getProjectAccess } = await loadAccessChecks();
- const access = await getProjectAccess({ userId, projectId });
+ const access = await ws.data.ctx.services.auth.getProjectAccess({
+ userId,
+ projectId,
+ });
if (!access) {
rejectNoAccess(ws);
return;
@@ -145,8 +136,10 @@ export const realtimeRoutes = defineRoutes((app) =>
return;
}
- const { getProjectAccess } = await loadAccessChecks();
- const access = await getProjectAccess({ userId, projectId });
+ const access = await ws.data.ctx.services.auth.getProjectAccess({
+ userId,
+ projectId,
+ });
if (!access) {
rejectNoAccess(ws);
return;
@@ -174,8 +167,10 @@ export const realtimeRoutes = defineRoutes((app) =>
return;
}
- const { getOrganizationAccess } = await loadAccessChecks();
- const access = await getOrganizationAccess({ userId, organizationId });
+ const access = await ws.data.ctx.services.auth.getOrganizationAccess({
+ userId,
+ organizationId,
+ });
if (!access) {
rejectNoAccess(ws);
return;
diff --git a/packages/core/src/modules/realtime/realtime.rpc.ts b/packages/core/src/modules/realtime/realtime.rpc.ts
index d4bef28bd..2794974d4 100644
--- a/packages/core/src/modules/realtime/realtime.rpc.ts
+++ b/packages/core/src/modules/realtime/realtime.rpc.ts
@@ -13,12 +13,11 @@
// through two access-check paths until the ONE shared tRPC instance lands
// with auth (P6).
//
-// 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 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, procedure, type TrpcContext } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
getRealtimeActiveSessions,
@@ -46,10 +45,6 @@ const realtimeBadgeDetailScopeSchema = z.enum([
'merged',
]);
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -57,17 +52,19 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireReadAccess(userId: string, projectId: string) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level: 'read' });
+async function requireReadAccess(ctx: TrpcContext, projectId: string) {
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'read',
+ });
}
export const realtimeRouter = createTRPCRouter({
coordinates: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getRealtimeCoordinates(input.projectId);
}),
@@ -83,40 +80,35 @@ export const realtimeRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getRealtimeMapBadgeDetails(input);
}),
activeSessions: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getRealtimeActiveSessions(input.projectId);
}),
paths: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getRealtimePaths(input.projectId);
}),
referrals: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getRealtimeReferrals(input.projectId);
}),
geo: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getRealtimeGeo(input.projectId);
}),
diff --git a/packages/core/src/modules/realtime/src/access.ts b/packages/core/src/modules/realtime/src/access.ts
deleted file mode 100644
index 3a00981ac..000000000
--- a/packages/core/src/modules/realtime/src/access.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// organization/src/access.ts.
-//
-// The `/live` ws routes (realtime.routes.ts) want the RAW nullable lookups,
-// not the throwing `require*` wrappers: V1's controller (still live,
-// untouched) checks truthiness itself and sends a "No access" frame before
-// closing the socket, rather than throwing — porting that behaviour means
-// re-exporting `getProjectAccess`/`getOrganizationAccess` verbatim.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-export {
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/reference/reference.rpc.ts b/packages/core/src/modules/reference/reference.rpc.ts
index 0114293f1..7288a0c4f 100644
--- a/packages/core/src/modules/reference/reference.rpc.ts
+++ b/packages/core/src/modules/reference/reference.rpc.ts
@@ -10,10 +10,10 @@
// PATTERN) — this module has no queue/cron of its own, so there is no
// `ctx.services.reference`, same as `user`/`conversation`.
//
-// 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. `create` 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`. `create` has
+// no access check here either — same gap V1's router has (ported verbatim,
+// not fixed).
import { zCreateReference, zRange } from '@openpanel/validation';
import { z } from 'zod';
@@ -28,10 +28,6 @@ import {
updateReference,
} from './reference.service';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -44,8 +40,7 @@ export const referenceRouter = createTRPCRouter({
.input(z.object({ projectId: z.string(), cursor: z.number().optional() }))
.query(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { getProjectAccess } = await loadAccessChecks();
- const access = await getProjectAccess({
+ const access = await ctx.services.auth.getProjectAccess({
userId,
projectId: input.projectId,
});
@@ -72,8 +67,7 @@ export const referenceRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
const existing = await getReferenceByIdOrThrow(input.id);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: existing.projectId,
level: 'write',
@@ -86,8 +80,7 @@ export const referenceRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
const existing = await getReferenceByIdOrThrow(input.id);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: existing.projectId,
level: 'write',
diff --git a/packages/core/src/modules/reference/src/access.ts b/packages/core/src/modules/reference/src/access.ts
deleted file mode 100644
index 37255f63d..000000000
--- a/packages/core/src/modules/reference/src/access.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// conversation/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-export { getProjectAccess } from '@openpanel/core';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/report/report.rpc.ts b/packages/core/src/modules/report/report.rpc.ts
index 52fa073da..e64a7b512 100644
--- a/packages/core/src/modules/report/report.rpc.ts
+++ b/packages/core/src/modules/report/report.rpc.ts
@@ -2,7 +2,8 @@
//
// 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. The mutation bodies
+// 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
@@ -41,10 +42,6 @@ const zReportLayout = z.object({
maxH: z.number().optional(),
});
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -52,21 +49,20 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireAccess(
- userId: string,
- projectId: string,
- level: 'read' | 'write'
-) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level });
-}
-
async function requireReadAccess(ctx: TrpcContext, projectId: string) {
- await requireAccess(requireLogin(ctx.session.userId), projectId, 'read');
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'read',
+ });
}
async function requireWriteAccess(ctx: TrpcContext, projectId: string) {
- await requireAccess(requireLogin(ctx.session.userId), projectId, 'write');
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'write',
+ });
}
export const reportRouter = createTRPCRouter({
diff --git a/packages/core/src/modules/report/src/access.ts b/packages/core/src/modules/report/src/access.ts
deleted file mode 100644
index a080240fc..000000000
--- a/packages/core/src/modules/report/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// chart/src/access.ts and project/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/session/session.rpc.ts b/packages/core/src/modules/session/session.rpc.ts
index 5f8495ac9..ad081a956 100644
--- a/packages/core/src/modules/session/session.rpc.ts
+++ b/packages/core/src/modules/session/session.rpc.ts
@@ -13,7 +13,7 @@
import { zChartEventFilter } from '@openpanel/validation';
import { z } from 'zod';
-import { createTRPCRouter, procedure } from '../../rpc/base';
+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
import {
getSessionById,
@@ -25,10 +25,6 @@ import {
const DEFAULT_LIST_TAKE = 50;
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -36,9 +32,12 @@ function requireLogin(userId: string | null | undefined): string {
return userId;
}
-async function requireReadAccess(userId: string, projectId: string) {
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({ userId, projectId, level: 'read' });
+async function requireReadAccess(ctx: TrpcContext, projectId: string) {
+ await ctx.services.auth.requireProjectAccess({
+ userId: requireLogin(ctx.session.userId),
+ projectId,
+ level: 'read',
+ });
}
export const sessionRouter = createTRPCRouter({
@@ -56,8 +55,7 @@ export const sessionRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getSessionList({
...input,
@@ -73,8 +71,7 @@ export const sessionRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getSessionDistinctValues(input.projectId, input.field);
}),
@@ -82,8 +79,7 @@ export const sessionRouter = createTRPCRouter({
byId: procedure
.input(z.object({ sessionId: z.string(), projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getSessionById(input.sessionId, input.projectId);
}),
@@ -97,8 +93,7 @@ export const sessionRouter = createTRPCRouter({
})
)
.query(async ({ input, ctx }) => {
- const userId = requireLogin(ctx.session.userId);
- await requireReadAccess(userId, input.projectId);
+ await requireReadAccess(ctx, input.projectId);
return getSessionReplayChunksFrom(
input.sessionId,
diff --git a/packages/core/src/modules/session/src/access.ts b/packages/core/src/modules/session/src/access.ts
deleted file mode 100644
index b67cf8a8e..000000000
--- a/packages/core/src/modules/session/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// realtime/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/share/share.rpc.ts b/packages/core/src/modules/share/share.rpc.ts
index 24c48aa44..70b6cabcb 100644
--- a/packages/core/src/modules/share/share.rpc.ts
+++ b/packages/core/src/modules/share/share.rpc.ts
@@ -10,15 +10,18 @@
// PATTERN) — this module has no queue/cron of its own, so there is no
// `ctx.services.share`, same as `user`/`project`.
//
-// 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. `createOverview` has no access
+// 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).
import { z } from 'zod';
import { createTRPCRouter, procedure } from '../../rpc/base';
import { TRPCAccessError } from '../../rpc/errors';
-import { zShareDashboard, zShareOverview, zShareReport } from './share.constants';
+import {
+ zShareDashboard,
+ zShareOverview,
+ zShareReport,
+} from './share.constants';
import {
createShareDashboard,
createShareOverview,
@@ -32,10 +35,6 @@ import {
getShareReportSettings,
} from './share.service';
-function loadAccessChecks() {
- return import('./src/access');
-}
-
function requireLogin(userId: string | null | undefined): string {
if (!userId) {
throw new TRPCAccessError('Not authenticated');
@@ -55,12 +54,10 @@ export const shareRouter = createTRPCRouter({
return getShareOverviewSettings(input.projectId);
}),
- createOverview: procedure
- .input(zShareOverview)
- .mutation(({ input, ctx }) => {
- requireLogin(ctx.session.userId);
- return createShareOverview(input);
- }),
+ createOverview: procedure.input(zShareOverview).mutation(({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ return createShareOverview(input);
+ }),
dashboard: procedure
.input(z.object({ shareId: z.string() }))
@@ -77,8 +74,7 @@ export const shareRouter = createTRPCRouter({
.input(zShareDashboard)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'write',
@@ -107,8 +103,7 @@ export const shareRouter = createTRPCRouter({
.input(zShareReport)
.mutation(async ({ input, ctx }) => {
const userId = requireLogin(ctx.session.userId);
- const { requireProjectAccess } = await loadAccessChecks();
- await requireProjectAccess({
+ await ctx.services.auth.requireProjectAccess({
userId,
projectId: input.projectId,
level: 'write',
diff --git a/packages/core/src/modules/share/src/access.ts b/packages/core/src/modules/share/src/access.ts
deleted file mode 100644
index 4b5b53194..000000000
--- a/packages/core/src/modules/share/src/access.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// conversation/src/access.ts.
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/subscription/src/access.ts b/packages/core/src/modules/subscription/src/access.ts
deleted file mode 100644
index 5c5d9292d..000000000
--- a/packages/core/src/modules/subscription/src/access.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
-// this module's own router — the same binding packages/trpc/src/access.ts
-// does for V1, self-contained here because the general core -> db binding
-// itself moves with auth (P6), not this wave. Same shape as
-// ../../notification/src/access.ts (M6-005) / ../../integration/src/access.ts
-// (M6-006).
-
-import {
- canWriteProject,
- getOrganizationAccess,
- getProjectAccess,
-} from '@openpanel/core';
-import { getProjectById } from '@openpanel/core';
-import { createAccessChecks } from '../../../shared/access';
-
-const checks = createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
-});
-
-export const requireOrganizationAdmin = checks.requireOrganizationAdmin;
diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.ts
index 2c7ed9dc9..2f5d7cdab 100644
--- a/packages/core/src/modules/subscription/subscription.service.ts
+++ b/packages/core/src/modules/subscription/subscription.service.ts
@@ -8,27 +8,23 @@
// `requireOrganizationAdmin` travels with the business logic here rather than
// living in subscription.rpc.ts the way project.rpc.ts's simple ladder checks
// do: every mutating procedure in this module gates on it first, before
-// touching Polar — same call as `./src/access.ts`'s `requireOrganizationAdmin`,
-// kept close to the Polar call it guards.
+// touching Polar. Every exported function here is still called directly by
+// `packages/trpc`'s LIVE V1 router with nothing but a `userId` (DELEGATE
+// PATTERN), so these can't take a `ctx`/`deps`; `requireOrganizationAdmin`
+// comes from auth.service.ts's single, lazily-memoized `getAccessChecks()`
+// (M10-002) instead.
//
-// db access, `./src/access.ts` AND `getCache` are all LAZY
-// (`loadDb`/`loadAccess`/`loadCache` below), not a static top-level import —
-// see organization.service.ts's header for the db half (constructing
-// @openpanel/db's clients at import time would spawn a pino-pretty transport
-// worker thread per test file); `./src/access.ts` needs the same treatment
-// because it calls `createAccessChecks({ canWriteProject, ... })` at ITS OWN
-// top level; a static import here would reach into
-// @openpanel/core as soon as anything imports
-// @openpanel/core's barrel (this module is a static re-export there, not a
-// lazy one), which broke a vitest suite that partially mocks that module
-// (packages/trpc/src/routers/share.test.ts) with no `canWriteProject` export
-// at all. `getCache` hit the same barrel chain from the other direction: a
-// static `import { getCache } from '@openpanel/redis'` here broke every core
-// test that partially mocks `@openpanel/redis` (no `getCache` export) and
-// reaches this module through @openpanel/db's re-export shims
-// (project.service.ts / notification.service.ts -> @openpanel/core's barrel
-// -> here), e.g. organization.service.test.ts's `connectUserToOrganization`
-// path via access.service.ts.
+// db access and `getCache` are LAZY (`loadDb`/`loadCache` below), not a
+// static top-level import — see organization.service.ts's header for the db
+// half (constructing @openpanel/db's clients at import time would spawn a
+// pino-pretty transport worker thread per test file). `getCache` hit the same
+// barrel chain from the other direction: a static
+// `import { getCache } from '@openpanel/redis'` here broke every core test
+// that partially mocks `@openpanel/redis` (no `getCache` export) and reaches
+// this module through @openpanel/db's re-export shims (project.service.ts /
+// notification.service.ts -> @openpanel/core's barrel -> here), e.g.
+// organization.service.test.ts's `connectUserToOrganization` path via
+// access.service.ts.
import {
applySubscriptionDiscount,
@@ -48,6 +44,7 @@ import { addMonths, subDays } from 'date-fns';
import { z } from 'zod';
import type { Logger } from '../../logger';
import { TRPCBadRequestError } from '../../rpc/errors';
+import { getAccessChecks } from '../auth/auth.service';
import {
getOrganizationBillingEventsCountSerieCached,
getOrganizationById,
@@ -73,10 +70,6 @@ function loadPrisma() {
return import('@openpanel/db/src/prisma-client').then((m) => m.Prisma);
}
-function loadAccess() {
- return import('./src/access');
-}
-
function loadCache() {
return import('@openpanel/redis').then((m) => m.getCache);
}
@@ -96,7 +89,7 @@ export async function checkout(
input: ICheckout,
ipAddress: string | undefined
) {
- const { requireOrganizationAdmin } = await loadAccess();
+ const { requireOrganizationAdmin } = await getAccessChecks();
await requireOrganizationAdmin({
userId,
organizationId: input.organizationId,
@@ -210,7 +203,7 @@ export async function cancelSubscription(
userId: string,
input: ICancelSubscription
) {
- const { requireOrganizationAdmin } = await loadAccess();
+ const { requireOrganizationAdmin } = await getAccessChecks();
await requireOrganizationAdmin({
userId,
organizationId: input.organizationId,
@@ -250,7 +243,7 @@ export async function pauseSubscription(
userId: string,
input: IPauseSubscription
) {
- const { requireOrganizationAdmin } = await loadAccess();
+ const { requireOrganizationAdmin } = await getAccessChecks();
await requireOrganizationAdmin({
userId,
organizationId: input.organizationId,
@@ -292,7 +285,7 @@ export async function resumeSubscription(
userId: string,
organizationId: string
) {
- const { requireOrganizationAdmin } = await loadAccess();
+ const { requireOrganizationAdmin } = await getAccessChecks();
await requireOrganizationAdmin({ userId, organizationId });
const organization = await getOrganizationById(organizationId);
@@ -326,7 +319,7 @@ export async function applySaveDiscount(
userId: string,
organizationId: string
) {
- const { requireOrganizationAdmin } = await loadAccess();
+ const { requireOrganizationAdmin } = await getAccessChecks();
await requireOrganizationAdmin({ userId, organizationId });
const discountId = process.env.POLAR_SAVE_DISCOUNT_ID;
@@ -366,7 +359,7 @@ export async function applySaveDiscount(
}
export async function portal(userId: string, organizationId: string) {
- const { requireOrganizationAdmin } = await loadAccess();
+ const { requireOrganizationAdmin } = await getAccessChecks();
await requireOrganizationAdmin({ userId, organizationId });
const organization = await getOrganizationById(organizationId);
diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.ts
index 81e6bb3cb..a40e7e6ac 100644
--- a/packages/core/test/request-id-end-to-end.test.ts
+++ b/packages/core/test/request-id-end-to-end.test.ts
@@ -8,7 +8,7 @@
// property core's shape was chosen for: if this goes red the design is wrong,
// not this file.
-import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
+import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';
import { Elysia } from 'elysia';
import { z } from 'zod';
import type { AppDeps, Buffers } from '../src/context';
@@ -34,6 +34,13 @@ interface ProofServices {
ingest: { record(name: string): Promise<string> };
}
+// Snapshotted BEFORE `mock.module` below, not after — restoring by
+// re-`import`ing later would resolve the already-mocked registry entry, not
+// the real module (bare `bun test` shares one module registry across every
+// file, and this specifier and `src/context.test.ts`'s `'./services'`
+// resolve to the same file).
+const realServicesModule = { ...(await import('../src/services')) };
+
// `Services` grows with every module that lands, so this proof mocks the
// whole container with a shape of its own rather than the real one — but the
// mock is a real service: built from the SCOPED ctx, logging to that request's
@@ -52,6 +59,10 @@ const createServices = mock(
);
mock.module('../src/services', () => ({ createServices }));
+afterAll(() => {
+ mock.module('../src/services', () => realServicesModule);
+});
+
// mock.module is not hoisted (AGENTS.md), so everything that reaches
// `services` through `context.ts` is imported here rather than at the top.
let requestLogging: typeof import('../src/http/context').requestLogging;