diff --git a/apps/api/src/auth/auth.module.ts b/apps/api/src/auth/auth.module.ts index 885530f..238e9fd 100644 --- a/apps/api/src/auth/auth.module.ts +++ b/apps/api/src/auth/auth.module.ts @@ -47,6 +47,6 @@ function buildProviders(config: AuthConfig): OAuthProviders { OAuthService, AccessGuard, ], - exports: [SessionService, SessionRevocations], + exports: [SessionService, SessionRevocations, AuthService, AccessGuard], }) export class AuthModule {} diff --git a/apps/api/src/collab/collab.module.ts b/apps/api/src/collab/collab.module.ts new file mode 100644 index 0000000..bf4938f --- /dev/null +++ b/apps/api/src/collab/collab.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; + +import { AuthModule } from '../auth/auth.module'; +import { PersistenceModule } from '../persistence/persistence.module'; +import { WorkspacesController } from './workspaces.controller'; +import { WorkspaceService } from './workspace.service'; + +@Module({ + imports: [PersistenceModule, AuthModule], + controllers: [WorkspacesController], + providers: [WorkspaceService], + exports: [WorkspaceService], +}) +export class CollabModule {} diff --git a/apps/api/src/collab/dto.ts b/apps/api/src/collab/dto.ts new file mode 100644 index 0000000..5f92729 --- /dev/null +++ b/apps/api/src/collab/dto.ts @@ -0,0 +1,8 @@ +import { z } from 'zod'; + +// `.strict()` everywhere: unknown fields are rejected, not silently dropped. +export const createWorkspaceSchema = z + .object({ name: z.string().trim().min(1).max(100) }) + .strict(); + +export type CreateWorkspaceBody = z.infer; diff --git a/apps/api/src/collab/test-app.ts b/apps/api/src/collab/test-app.ts new file mode 100644 index 0000000..3453db1 --- /dev/null +++ b/apps/api/src/collab/test-app.ts @@ -0,0 +1,60 @@ +import type { INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; + +import type { PrismaClient } from '../generated/prisma/client'; +import { AuthModule } from '../auth/auth.module'; +import { applyHttpConfig } from '../auth/http-config'; +import { AUTH_CONFIG, type AuthConfig } from '../auth/config'; +import { CLOCK } from '../auth/clock'; +import { OAUTH_PROVIDERS } from '../auth/oauth-provider'; +import { TestClock } from '../auth/test-app'; +import { PRISMA } from '../persistence/persistence.module'; +import { openTestClient } from '../persistence/test-db'; +import { CollabModule } from './collab.module'; + +export const TEST_SECRET = 'test-secret-test-secret-test-secret-test'; + +export interface CollabTestApp { + app: INestApplication; + prisma: PrismaClient; + clock: TestClock; + baseUrl: string; + close(): Promise; +} + +export async function startCollabTestApp(): Promise { + const prisma = openTestClient(); + const clock = new TestClock(); + const config: AuthConfig = { + jwtSecret: TEST_SECRET, + databaseUrl: 'unused', + publicBaseUrl: 'http://api.test', + webOrigin: 'http://web.test', + oauth: {}, + rateLimitEnabled: false, + trustProxy: false, + }; + const moduleRef = await Test.createTestingModule({ imports: [AuthModule, CollabModule] }) + .overrideProvider(PRISMA) + .useValue(prisma) + .overrideProvider(AUTH_CONFIG) + .useValue(config) + .overrideProvider(OAUTH_PROVIDERS) + .useValue({}) + .overrideProvider(CLOCK) + .useValue(clock) + .compile(); + const app = moduleRef.createNestApplication(); + applyHttpConfig(app, config); + await app.listen(0, '127.0.0.1'); + return { + app, + prisma, + clock, + baseUrl: await app.getUrl(), + close: async () => { + await app.close(); + await prisma.$disconnect(); + }, + }; +} diff --git a/apps/api/src/collab/views.ts b/apps/api/src/collab/views.ts new file mode 100644 index 0000000..4f48303 --- /dev/null +++ b/apps/api/src/collab/views.ts @@ -0,0 +1,39 @@ +import type { UserRecord } from '../persistence/user.repository'; +import type { UserId, Workspace, WorkspaceId } from '@opencollab/domain'; + +export interface WorkspaceSummary { + id: WorkspaceId; + name: string; + owner: UserId; + memberCount: number; +} + +export interface MemberView { + userId: UserId; + username: string; + displayName: string; +} + +export interface WorkspaceDetail { + id: WorkspaceId; + name: string; + owner: UserId; + members: MemberView[]; +} + +export function toWorkspaceSummary(ws: Workspace): WorkspaceSummary { + return { id: ws.id, name: ws.name, owner: ws.owner, memberCount: ws.members.length }; +} + +// `usersById` supplies the display fields for the member ids; ids missing from +// the map (deleted users) are dropped from the view. +export function toWorkspaceDetail(ws: Workspace, usersById: Map): WorkspaceDetail { + const members: MemberView[] = []; + for (const m of ws.members) { + const user = usersById.get(m.userId); + if (user) { + members.push({ userId: user.id, username: user.username, displayName: user.displayName }); + } + } + return { id: ws.id, name: ws.name, owner: ws.owner, members }; +} diff --git a/apps/api/src/collab/workspace.service.ts b/apps/api/src/collab/workspace.service.ts new file mode 100644 index 0000000..4885111 --- /dev/null +++ b/apps/api/src/collab/workspace.service.ts @@ -0,0 +1,46 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { Workspace, type UserId, type WorkspaceId } from '@opencollab/domain'; + +import { UserRepository } from '../persistence/user.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { toWorkspaceDetail, toWorkspaceSummary, type WorkspaceDetail, type WorkspaceSummary } from './views'; + +export type WorkspaceLookup = + | { kind: 'ok'; workspace: Workspace } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +@Injectable() +export class WorkspaceService { + constructor( + @Inject(WorkspaceRepository) private readonly workspaces: WorkspaceRepository, + @Inject(UserRepository) private readonly users: UserRepository, + ) {} + + async create(actor: UserId, name: string): Promise { + const ws = new Workspace(actor, name); + await this.workspaces.save(ws); + return this.detail(ws); + } + + async listFor(actor: UserId): Promise { + const list = await this.workspaces.listForUser(actor); + return list.map(toWorkspaceSummary); + } + + // Loads a workspace and classifies the caller's access so the controller can + // answer 404 vs 403 without leaking existence to strangers. + async lookup(id: WorkspaceId, actor: UserId): Promise { + const ws = await this.workspaces.find(id); + if (!ws) return { kind: 'not-found' }; + if (!ws.isOwner(actor) && !ws.isMember(actor)) return { kind: 'forbidden' }; + return { kind: 'ok', workspace: ws }; + } + + async detail(ws: Workspace): Promise { + const ids = [ws.owner, ...ws.members.map((m) => m.userId)]; + const users = await this.users.findByIds(ids); + return toWorkspaceDetail(ws, new Map(users.map((u) => [u.id, u]))); + } +} diff --git a/apps/api/src/collab/workspaces.controller.int.spec.ts b/apps/api/src/collab/workspaces.controller.int.spec.ts new file mode 100644 index 0000000..194a2dd --- /dev/null +++ b/apps/api/src/collab/workspaces.controller.int.spec.ts @@ -0,0 +1,153 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { Workspace } from '@opencollab/domain'; +import type { UserId, WorkspaceId } from '@opencollab/domain'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { truncateAll } from '../persistence/test-db'; +import { startCollabTestApp, type CollabTestApp } from './test-app'; + +let t: CollabTestApp; +let workspaces: WorkspaceRepository; + +beforeAll(async () => { + t = await startCollabTestApp(); + workspaces = new WorkspaceRepository(t.prisma); +}); +afterAll(() => t.close()); +beforeEach(() => truncateAll(t.prisma)); + +interface Res { + status: number; + body: unknown; +} + +async function call(method: string, path: string, body?: unknown, token?: string): Promise { + const res = await fetch(`${t.baseUrl}${path}`, { + method, + headers: { + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + const text = await res.text(); + let parsed: unknown = undefined; + try { + parsed = text ? JSON.parse(text) : undefined; + } catch { + parsed = text; + } + return { status: res.status, body: parsed }; +} + +const get = (path: string, token?: string) => call('GET', path, undefined, token); +const post = (path: string, body?: unknown, token?: string) => call('POST', path, body ?? {}, token); + +let counter = 0; +async function registerUser(prefix = 'user'): Promise<{ id: string; token: string }> { + counter += 1; + const username = `${prefix}${counter}`; + const res = await post('/auth/register', { + username, + password: 'correct horse battery', + displayName: prefix, + }); + expect(res.status).toBe(201); + const body = res.body as { accessToken: string; user: { id: string } }; + return { id: body.user.id, token: body.accessToken }; +} + +// Seeds a workspace with a member straight through the repository: the +// invitation endpoints belong to a later task, so this setup stays independent. +async function seedWorkspaceWithMember(ownerId: UserId, memberId: UserId, name: string): Promise { + const ws = new Workspace(ownerId, name); + ws.addMember(ownerId, memberId); + await workspaces.save(ws); + return ws.id; +} + +describe('POST /workspaces', () => { + it('creates a workspace with the caller as owner', async () => { + const { id, token } = await registerUser(); + const res = await post('/workspaces', { name: 'Proyecto X' }, token); + expect(res.status).toBe(201); + const body = res.body as { id: string; name: string; owner: string; members: unknown[] }; + expect(body.name).toBe('Proyecto X'); + expect(body.owner).toBe(id); + expect(body.members).toEqual([]); + }); + + it('rejects an unauthenticated request with 401', async () => { + const res = await post('/workspaces', { name: 'x' }); + expect(res.status).toBe(401); + }); + + it('rejects an empty or blank name with 400', async () => { + const { token } = await registerUser(); + expect((await post('/workspaces', { name: '' }, token)).status).toBe(400); + expect((await post('/workspaces', { name: ' ' }, token)).status).toBe(400); + }); + + it('rejects unknown fields with 400', async () => { + const { token } = await registerUser(); + const res = await post('/workspaces', { name: 'x', extra: true }, token); + expect(res.status).toBe(400); + }); +}); + +describe('GET /workspaces', () => { + it('lists only workspaces where the caller is owner or member', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + + const mine = (await post('/workspaces', { name: 'mine' }, owner.token)).body as { id: string }; + await post('/workspaces', { name: 'owned-by-member' }, member.token); + await seedWorkspaceWithMember(owner.id as UserId, member.id as UserId, 'shared'); + + const forOwner = (await get('/workspaces', owner.token)).body as { id: string; name: string }[]; + expect(forOwner.map((w) => w.name).sort()).toEqual(['mine', 'shared']); + + // Member owns 'owned-by-member' and belongs to 'shared' (seeded); they have + // no relation to 'mine', so it must not appear in their list. + const forMember = (await get('/workspaces', member.token)).body as { name: string }[]; + expect(forMember.map((w) => w.name).sort()).toEqual(['owned-by-member', 'shared']); + + const forStranger = (await get('/workspaces', stranger.token)).body as { name: string }[]; + expect(forStranger).toEqual([]); + expect(mine.id).toBeTruthy(); + }); +}); + +describe('GET /workspaces/:id', () => { + it('returns the detail with members for the owner', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const wsId = await seedWorkspaceWithMember(owner.id as UserId, member.id as UserId, 'detail'); + + const res = await get(`/workspaces/${wsId}`, owner.token); + expect(res.status).toBe(200); + const body = res.body as { + id: string; + name: string; + owner: string; + members: { userId: string; username: string; displayName: string }[]; + }; + expect(body.id).toBe(wsId); + expect(body.name).toBe('detail'); + expect(body.owner).toBe(owner.id); + expect(body.members).toHaveLength(1); + expect(body.members[0]?.userId).toBe(member.id); + expect(body.members[0]?.username).toBeTruthy(); + expect(body.members[0]?.displayName).toBeTruthy(); + }); + + it('returns 404 for an unknown workspace and 403 for a stranger', async () => { + const owner = await registerUser(); + const stranger = await registerUser(); + const ws = (await post('/workspaces', { name: 'private' }, owner.token)).body as { id: string }; + + expect((await get('/workspaces/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); + expect((await get(`/workspaces/${ws.id}`, stranger.token)).status).toBe(403); + }); +}); diff --git a/apps/api/src/collab/workspaces.controller.ts b/apps/api/src/collab/workspaces.controller.ts new file mode 100644 index 0000000..d6c9186 --- /dev/null +++ b/apps/api/src/collab/workspaces.controller.ts @@ -0,0 +1,47 @@ +import { + Body, + Controller, + ForbiddenException, + Get, + HttpCode, + Inject, + NotFoundException, + Param, + Post, + UseGuards, +} from '@nestjs/common'; + +import type { WorkspaceId } from '@opencollab/domain'; +import { AccessGuard, CurrentUser } from '../auth/access.guard'; +import { ZodPipe } from '../auth/dto'; +import type { UserRecord } from '../persistence/user.repository'; +import { createWorkspaceSchema, type CreateWorkspaceBody } from './dto'; +import { WorkspaceService } from './workspace.service'; + +@Controller('workspaces') +@UseGuards(AccessGuard) +export class WorkspacesController { + constructor(@Inject(WorkspaceService) private readonly service: WorkspaceService) {} + + @Post() + @HttpCode(201) + create( + @CurrentUser() user: UserRecord, + @Body(new ZodPipe(createWorkspaceSchema)) body: CreateWorkspaceBody, + ) { + return this.service.create(user.id, body.name); + } + + @Get() + list(@CurrentUser() user: UserRecord) { + return this.service.listFor(user.id); + } + + @Get(':id') + async get(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.lookup(id as WorkspaceId, user.id); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return this.service.detail(result.workspace); + } +} diff --git a/apps/api/src/persistence/user.repository.ts b/apps/api/src/persistence/user.repository.ts index 2a41027..0f0a5f8 100644 --- a/apps/api/src/persistence/user.repository.ts +++ b/apps/api/src/persistence/user.repository.ts @@ -54,6 +54,13 @@ export class UserRepository { return row ? toUserRecord(row) : undefined; } + // Batch lookup (member lists, invitation enrichment). Unknown ids are skipped. + async findByIds(ids: readonly UserId[]): Promise { + if (ids.length === 0) return []; + const rows = await this.prisma.user.findMany({ where: { id: { in: [...ids] } } }); + return rows.map(toUserRecord); + } + // An identifier containing `@` is an email, anything else a username. The // two namespaces never overlap, so a login is never ambiguous. async findByUsernameOrEmail(identifier: string): Promise { diff --git a/apps/api/src/persistence/workspace.repository.int.spec.ts b/apps/api/src/persistence/workspace.repository.int.spec.ts index 8a45ef5..7b4ea3e 100644 --- a/apps/api/src/persistence/workspace.repository.int.spec.ts +++ b/apps/api/src/persistence/workspace.repository.int.spec.ts @@ -67,6 +67,33 @@ describe('WorkspaceRepository', () => { expect((await workspaces.find(ws.id))?.members).toHaveLength(1); }); + it('listForUser returns workspaces where the user is owner or member, and not others', async () => { + const owner = await seedUser(users); + const member = await seedUser(users); + const stranger = await seedUser(users); + const otherOwner = await seedUser(users); + + const mine = new Workspace(owner, 'mine'); + mine.addMember(owner, member); + await workspaces.save(mine); + + const shared = new Workspace(member, 'shared'); + await workspaces.save(shared); + + const foreign = new Workspace(otherOwner, 'foreign'); + await workspaces.save(foreign); + + // `mine` is owned by owner with member added; `shared` is owned by member only. + const forOwner = await workspaces.listForUser(owner); + expect(forOwner.map((w) => w.id)).toEqual([mine.id]); + + const forMember = await workspaces.listForUser(member); + expect(forMember.map((w) => w.id).sort()).toEqual([mine.id, shared.id].sort()); + + const forStranger = await workspaces.listForUser(stranger); + expect(forStranger).toEqual([]); + }); + it('deleting a workspace cascades to members, sessions and their children', async () => { const owner = await seedUser(users); const member = await seedUser(users); diff --git a/apps/api/src/persistence/workspace.repository.ts b/apps/api/src/persistence/workspace.repository.ts index 9545c90..881b7b1 100644 --- a/apps/api/src/persistence/workspace.repository.ts +++ b/apps/api/src/persistence/workspace.repository.ts @@ -19,6 +19,23 @@ export class WorkspaceRepository { }); } + // Every workspace where the user is owner or member, oldest first. + async listForUser(userId: UserId): Promise { + const rows = await this.prisma.workspace.findMany({ + where: { OR: [{ ownerId: userId }, { members: { some: { userId } } }] }, + include: { members: { orderBy: [{ joinedAt: 'asc' }, { userId: 'asc' }] } }, + orderBy: { createdAt: 'asc' }, + }); + return rows.map((row) => + Workspace.restore({ + id: row.id as WorkspaceId, + owner: row.ownerId as UserId, + name: row.name, + members: row.members.map((m) => m.userId as UserId), + }), + ); + } + // Upserts the workspace and makes the member rows match the aggregate. // Existing members keep their joinedAt. async save(workspace: Workspace): Promise { diff --git a/odd/tasks/api-rest-crud.md b/odd/tasks/api-rest-crud.md new file mode 100644 index 0000000..8e8c8b4 --- /dev/null +++ b/odd/tasks/api-rest-crud.md @@ -0,0 +1,43 @@ +# API REST CRUD — workspaces, sessions, terminals, invitations + +Objective: expose the existing domain + persistence (Workspace/Session/Terminal/Invitation) as authenticated REST endpoints so the desktop (Feature 2: dual storage mode) has a cloud CRUD surface to call. +Branch: feature/api-rest-crud | Delivery: PR a develop | Test runner: `pnpm --filter @opencollab/server test` (unit) + `pnpm --filter @opencollab/server test:integration` (needs Postgres via `DATABASE_URL`) + +## Specs + +- S1: `POST /workspaces` — any authenticated user creates a workspace; the caller becomes owner. Body: `{ "name": string }` (trimmed, 1..100 chars). Returns the created workspace view (201). +- S2: `GET /workspaces` — lists every workspace where the caller is owner or member, each with its member count. Returns an array (200). +- S3: `GET /workspaces/:id` — workspace detail (name, owner, members with username/displayName). Owner or member only; 404 if not found, 403 if the caller has no access. +- S4: `POST /workspaces/:workspaceId/sessions` — creates a session in the workspace. Owner only (matches domain `Session.create` which requires `workspace.ensureOwner(actor)`). Body: `{ "name": string }` (trimmed, 1..100). Returns the session view (201). 403 for non-owner members, 404 if the workspace does not exist or the caller has no access. +- S5: `GET /workspaces/:workspaceId/sessions` — lists the sessions of the workspace (owner or member), each with its terminals in position order. Returns an array (200). +- S6: `GET /sessions/:id` — session detail with terminals (id, name, command, args, cwd). Viewable by anyone who can view the session (owner, member, or guest — matches `session.canView(workspace, user)`). 404 if not found, 403 if no view access. +- S7: `POST /sessions/:id/terminals` — appends a terminal to the session. Owner only (domain `addTerminal` is owner-only). Body: `{ "name": string, "command": string, "args"?: string[], "cwd"?: string | null }`. Returns the terminal view (201). Env is never accepted nor persisted (domain rule: env may hold secrets). +- S8: `DELETE /sessions/:id/terminals/:terminalId` — removes the terminal. Owner only. 204 on success; 404 if session or terminal not found; 403 if not owner. +- S9: `POST /workspaces/:id/invitations` — invites a user to the workspace as member. Owner only (domain `inviteMember`). Body: `{ "inviteeId": string }` (a UserId). Creates the invitation as pending. Returns the invitation view (201). 403 for non-owners; 409 if the invitee is already owner or member (`AlreadyHasAccess`). +- S10: `POST /sessions/:id/invitations` — invites a user to the session as guest. Owner only (domain `inviteGuest`). Body: `{ "inviteeId": string }`. Returns the invitation view (201). 403 for non-owners; 409 if the invitee already has a role (`AlreadyHasAccess`). +- S11: `GET /invitations` — lists the caller's pending, non-expired invitations (uses `InvitationRepository.listPendingFor`). Each entry carries the target (workspace or session) and who invited. Returns an array (200). +- S12: `POST /invitations/:id/accept` — accepts an invitation. Only the invitee may accept (403 otherwise). Applies the domain accept (`Workspace.acceptInvitation` or `Session.acceptInvitation`), persists the workspace/session, and marks the invitation accepted. 204 on success; 404 if not found; 409 if already responded/revoked/expired. +- S13: `POST /invitations/:id/decline` — declines an invitation. Only the invitee (403 otherwise). Marks it declined. 204; 404 if not found; 409 if already responded/revoked/expired. +- S14: All endpoints require `Authorization: Bearer ` (reuse `AccessGuard` + `CurrentUser`); missing/invalid token → 401. Bodies are validated with zod + `ZodPipe` (strict: unknown fields rejected); invalid body → 400 with field paths only, never echoing submitted values. +- S15: Domain errors map to HTTP: `NotOwner` → 403, `AlreadyHasAccess` → 409, `NotAParticipant` → 403, `TerminalNotInSession` → 404, invitation already responded → 409. Persistence changes are transactional: a failed accept never leaves a half-applied workspace/session plus an accepted invitation. + +Assumptions (marked as such, not user requirements): +- A1: "terminales" as an API resource means the persisted terminal profile (name/command/args/cwd), not live PTY streaming — live I/O already goes through the WebSocket gateway (`collab.gateway.ts`). +- A2: Renaming workspaces/sessions, removing members, and changing session access via REST are out of scope for this feature (access changes already exist as the `access_changed` WS frame). +- A3: `WorkspaceRepository` gains a `listForUser` method (it currently only has find/save); `InvitationRepository` is added to `PersistenceModule` exports (currently missing). + +## Tasks + +- T1 (S1-S3, S14): WorkspacesController — list/create/get + `WorkspaceRepository.listForUser` + module wiring; int tests RED→GREEN. route: inline — DONE (13 int tests, unit 166, int 107, typecheck ok) +- T2 (S4-S6, S14-S15): SessionsController — create/list/get sessions + terminals in views; int tests RED→GREEN. route: inline +- T3 (S7-S8, S14-S15): TerminalsController — add/remove terminal; int tests RED→GREEN. route: inline +- T4 (S9-S13, S15): InvitationsController + accept/decline orchestration service; int tests RED→GREEN. route: inline +- T5 (S1-S15): AppModule wiring, full unit + integration suite green, typecheck + build. route: inline + +## Log + +- L1 (2026-10-14, user verbatim): "En la API ya se encuentran los endpoints para la creación de workspaces - sesiones - terminales e invitaciones. Lo ideal es que el usuario tenga 2 opciones al usar la aplicación, almacenar todo local (podria ser en appdata) o guardar todo en "cloud" que seria que se interactue con la API." +- L2 (2026-10-14, verification): Checked the premise against develop HEAD 6a45795: the API has NO REST endpoints for workspaces/sessions/terminals/invitations — only `/auth/*`, `/health`, the WS gateway, and internal repositories. User confirmed the scope split. +- L3 (2026-10-14, user decision): Dual-mode product decisions (for Feature 2, recorded here for continuity): mode selection = "Onboarding + Settings"; collaboration in local mode = "Visibles pero inactivas"; switching local→cloud = "Migrar local → cloud". +- L4 (2026-10-14, user decision): Scope = "Dos features secuenciales": this feature builds the API REST CRUD first; Feature 2 (desktop dual storage mode) follows in a separate feature branch. +- L5 (2026-10-14, T1 done): WorkspacesController (POST/GET /workspaces, GET /workspaces/:id) implemented with `WorkspaceRepository.listForUser`, `UserRepository.findByIds`, zod `ZodPipe` validation, `AccessGuard`. New `CollabModule` imports PersistenceModule + AuthModule; AuthModule now exports `AuthService` and `AccessGuard` (previously only SessionService/SessionRevocations). Added `collab/test-app.ts` (bootstraps AuthModule+CollabModule against the `_test` database). Verified: unit 166/166, integration 107/107, typecheck clean.