From b51d335e97050a2cc0b1f5e3e4f0db40d8b7c96d Mon Sep 17 00:00:00 2001 From: facyndev Date: Thu, 15 Oct 2026 11:24:00 -0300 Subject: [PATCH 1/2] feat(server): add sessions REST endpoints (create/list/get) --- apps/api/src/collab/collab.module.ts | 8 +- apps/api/src/collab/dto.ts | 7 + apps/api/src/collab/session.service.ts | 69 +++++ .../collab/sessions.controller.int.spec.ts | 236 ++++++++++++++++++ apps/api/src/collab/sessions.controller.ts | 56 +++++ apps/api/src/collab/views.ts | 32 ++- odd/tasks/api-rest-crud.md | 3 +- 7 files changed, 406 insertions(+), 5 deletions(-) create mode 100644 apps/api/src/collab/session.service.ts create mode 100644 apps/api/src/collab/sessions.controller.int.spec.ts create mode 100644 apps/api/src/collab/sessions.controller.ts diff --git a/apps/api/src/collab/collab.module.ts b/apps/api/src/collab/collab.module.ts index bf4938f..158c585 100644 --- a/apps/api/src/collab/collab.module.ts +++ b/apps/api/src/collab/collab.module.ts @@ -2,13 +2,15 @@ import { Module } from '@nestjs/common'; import { AuthModule } from '../auth/auth.module'; import { PersistenceModule } from '../persistence/persistence.module'; +import { SessionService } from './session.service'; +import { SessionsController } from './sessions.controller'; import { WorkspacesController } from './workspaces.controller'; import { WorkspaceService } from './workspace.service'; @Module({ imports: [PersistenceModule, AuthModule], - controllers: [WorkspacesController], - providers: [WorkspaceService], - exports: [WorkspaceService], + controllers: [WorkspacesController, SessionsController], + providers: [WorkspaceService, SessionService], + exports: [WorkspaceService, SessionService], }) export class CollabModule {} diff --git a/apps/api/src/collab/dto.ts b/apps/api/src/collab/dto.ts index 5f92729..7da61df 100644 --- a/apps/api/src/collab/dto.ts +++ b/apps/api/src/collab/dto.ts @@ -6,3 +6,10 @@ export const createWorkspaceSchema = z .strict(); export type CreateWorkspaceBody = z.infer; + +// Session name follows the same rule as the workspace name (S4). +export const createSessionSchema = z + .object({ name: z.string().trim().min(1).max(100) }) + .strict(); + +export type CreateSessionBody = z.infer; diff --git a/apps/api/src/collab/session.service.ts b/apps/api/src/collab/session.service.ts new file mode 100644 index 0000000..3c78dd9 --- /dev/null +++ b/apps/api/src/collab/session.service.ts @@ -0,0 +1,69 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { Session, type SessionId, type UserId, type Workspace, type WorkspaceId } from '@opencollab/domain'; + +import { SessionRepository } from '../persistence/session.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { toSessionView, type SessionView } from './views'; + +// `not-found` covers both a missing workspace and a caller with no relation to +// it: sessions endpoints must not leak workspace existence (S4/S5). +export type SessionListResult = + | { kind: 'ok'; views: SessionView[] } + | { kind: 'not-found' }; + +export type SessionCreateResult = + | { kind: 'created'; view: SessionView } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +// S6: the session itself is either invisible (403 when it exists but the +// caller cannot view it) or missing (404). +export type SessionDetailResult = + | { kind: 'ok'; view: SessionView } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +@Injectable() +export class SessionService { + constructor( + @Inject(WorkspaceRepository) private readonly workspaces: WorkspaceRepository, + @Inject(SessionRepository) private readonly sessions: SessionRepository, + ) {} + + // Workspace classification for the nested routes: unknown or stranger is + // `not-found`, any member (owner or not) is `ok`. + private async access( + workspaceId: WorkspaceId, + actor: UserId, + ): Promise<{ kind: 'not-found' } | { kind: 'ok'; workspace: Workspace; owner: boolean }> { + const ws = await this.workspaces.find(workspaceId); + if (!ws || (!ws.isOwner(actor) && !ws.isMember(actor))) return { kind: 'not-found' }; + return { kind: 'ok', workspace: ws, owner: ws.isOwner(actor) }; + } + + async create(actor: UserId, workspaceId: WorkspaceId, name: string): Promise { + const acc = await this.access(workspaceId, actor); + if (acc.kind === 'not-found') return acc; + if (!acc.owner) return { kind: 'forbidden' }; + // `Session.create` re-checks ownership in the domain (ensureOwner). + const session = Session.create(acc.workspace, actor, name); + await this.sessions.save(session); + return { kind: 'created', view: toSessionView(session) }; + } + + async list(actor: UserId, workspaceId: WorkspaceId): Promise { + const acc = await this.access(workspaceId, actor); + if (acc.kind === 'not-found') return acc; + const list = await this.sessions.listByWorkspace(workspaceId); + return { kind: 'ok', views: list.map(toSessionView) }; + } + + async detail(id: SessionId, actor: UserId): Promise { + const session = await this.sessions.find(id); + if (!session) return { kind: 'not-found' }; + const ws = await this.workspaces.find(session.workspaceId); + if (!ws || !session.canView(ws, actor)) return { kind: 'forbidden' }; + return { kind: 'ok', view: toSessionView(session) }; + } +} diff --git a/apps/api/src/collab/sessions.controller.int.spec.ts b/apps/api/src/collab/sessions.controller.int.spec.ts new file mode 100644 index 0000000..b514b02 --- /dev/null +++ b/apps/api/src/collab/sessions.controller.int.spec.ts @@ -0,0 +1,236 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import type { InvitationId, SessionId, UserId, WorkspaceId } from '@opencollab/domain'; +import { SessionRepository } from '../persistence/session.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { truncateAll } from '../persistence/test-db'; +import { startCollabTestApp, type CollabTestApp } from './test-app'; + +let t: CollabTestApp; +let sessions: SessionRepository; +let workspaces: WorkspaceRepository; + +beforeAll(async () => { + t = await startCollabTestApp(); + sessions = new SessionRepository(t.prisma); + 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 }; +} + +async function createWorkspace(ownerToken: string, name = 'ws'): Promise<{ id: string }> { + const res = await post('/workspaces', { name }, ownerToken); + expect(res.status).toBe(201); + return res.body as { id: string }; +} + +// Seeds a member straight through the repository: invitations belong to T4. +async function seedMember(workspaceId: WorkspaceId, ownerId: UserId, memberId: UserId): Promise { + const ws = await workspaces.find(workspaceId); + expect(ws).toBeTruthy(); + ws!.addMember(ownerId, memberId); + await workspaces.save(ws!); +} + +type SessionBody = { + id: string; + name: string; + terminals: { id: string; name: string; command: string; args: string[]; cwd: string | null }[]; +}; + +describe('POST /workspaces/:workspaceId/sessions', () => { + it('creates a session with the caller as owner (201, empty terminals)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'Standup' }, owner.token); + expect(res.status).toBe(201); + const body = res.body as SessionBody; + expect(body.name).toBe('Standup'); + expect(body.id).toBeTruthy(); + expect(body.terminals).toEqual([]); + }); + + it('returns 403 for a member who is not the owner', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'x' }, member.token); + expect(res.status).toBe(403); + }); + + it('returns 404 for a stranger (no access) and for an unknown workspace', async () => { + const owner = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + + expect((await post(`/workspaces/${ws.id}/sessions`, { name: 'x' }, stranger.token)).status).toBe(404); + expect( + (await post('/workspaces/00000000-0000-0000-0000-000000000000/sessions', { name: 'x' }, owner.token)) + .status, + ).toBe(404); + }); + + it('requires auth and a valid strict body (S14)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + + expect((await post(`/workspaces/${ws.id}/sessions`, { name: 'x' })).status).toBe(401); + expect((await post(`/workspaces/${ws.id}/sessions`, { name: '' }, owner.token)).status).toBe(400); + expect((await post(`/workspaces/${ws.id}/sessions`, { name: ' ' }, owner.token)).status).toBe(400); + expect( + (await post(`/workspaces/${ws.id}/sessions`, { name: 'x', extra: true }, owner.token)).status, + ).toBe(400); + }); +}); + +describe('GET /workspaces/:workspaceId/sessions', () => { + it('lists the sessions of the workspace for owner and member, with terminals in position order', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + + const created = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'first' }, owner.token) + ).body as SessionBody; + await post(`/workspaces/${ws.id}/sessions`, { name: 'second' }, owner.token); + + // Seed terminals straight through the repository (endpoints belong to T3): + // two terminals whose stored order must survive the list projection. + const wsAggregate = await workspaces.find(ws.id as WorkspaceId); + const aggregate = await sessions.find(created.id as SessionId); + expect(aggregate).toBeTruthy(); + aggregate!.addTerminal(wsAggregate!, owner.id as UserId, { + name: 'a', + command: 'echo', + args: ['a'], + env: [], + }); + aggregate!.addTerminal(wsAggregate!, owner.id as UserId, { + name: 'b', + command: 'echo', + args: ['b'], + env: [], + cwd: '/tmp', + }); + await sessions.save(aggregate!); + + const forOwner = (await get(`/workspaces/${ws.id}/sessions`, owner.token)).body as SessionBody[]; + expect(forOwner.map((s) => s.name)).toEqual(['first', 'second']); + const withTerminals = forOwner.find((s) => s.id === created.id)!; + expect(withTerminals.terminals.map((tm) => tm.name)).toEqual(['a', 'b']); + expect(withTerminals.terminals[0]).toMatchObject({ command: 'echo', args: ['a'], cwd: null }); + expect(withTerminals.terminals[1]).toMatchObject({ command: 'echo', args: ['b'], cwd: '/tmp' }); + + const forMember = (await get(`/workspaces/${ws.id}/sessions`, member.token)).body as SessionBody[]; + expect(forMember.map((s) => s.name)).toEqual(['first', 'second']); + }); + + it('returns 404 for a stranger and for an unknown workspace', async () => { + const owner = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + await post(`/workspaces/${ws.id}/sessions`, { name: 'x' }, owner.token); + + expect((await get(`/workspaces/${ws.id}/sessions`, stranger.token)).status).toBe(404); + expect((await get('/workspaces/00000000-0000-0000-0000-000000000000/sessions', owner.token)).status).toBe( + 404, + ); + expect((await get(`/workspaces/${ws.id}/sessions`)).status).toBe(401); + }); +}); + +describe('GET /sessions/:id', () => { + it('returns the session detail with terminals for the owner', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'detail' }, owner.token) + ).body as SessionBody; + + const res = await get(`/sessions/${created.id}`, owner.token); + expect(res.status).toBe(200); + const body = res.body as SessionBody; + expect(body.id).toBe(created.id); + expect(body.name).toBe('detail'); + expect(body.terminals).toEqual([]); + }); + + it('allows a member and a guest to view, and rejects a stranger with 403', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const guest = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + const created = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'shared' }, owner.token) + ).body as SessionBody; + + // Guest seeding mirrors T1's approach: the domain invitation flow is T4, + // so the guest role is applied directly on the aggregate. + const aggregate = await sessions.find(created.id as SessionId); + const wsAggregate = await workspaces.find(ws.id as WorkspaceId); + aggregate!.acceptInvitation(wsAggregate!, { + id: '00000000-0000-0000-0000-000000000001' as InvitationId, + target: { kind: 'session', sessionId: aggregate!.id }, + invitee: guest.id as UserId, + invitedBy: owner.id as UserId, + }); + await sessions.save(aggregate!); + + expect((await get(`/sessions/${created.id}`, member.token)).status).toBe(200); + expect((await get(`/sessions/${created.id}`, guest.token)).status).toBe(200); + expect((await get(`/sessions/${created.id}`, stranger.token)).status).toBe(403); + expect((await get(`/sessions/${created.id}`)).status).toBe(401); + }); + + it('returns 404 for an unknown session', async () => { + const owner = await registerUser(); + expect((await get('/sessions/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); + }); +}); diff --git a/apps/api/src/collab/sessions.controller.ts b/apps/api/src/collab/sessions.controller.ts new file mode 100644 index 0000000..f08a2bb --- /dev/null +++ b/apps/api/src/collab/sessions.controller.ts @@ -0,0 +1,56 @@ +import { + Body, + Controller, + ForbiddenException, + Get, + HttpCode, + Inject, + NotFoundException, + Param, + Post, + UseGuards, +} from '@nestjs/common'; + +import type { SessionId, WorkspaceId } from '@opencollab/domain'; +import { AccessGuard, CurrentUser } from '../auth/access.guard'; +import { ZodPipe } from '../auth/dto'; +import type { UserRecord } from '../persistence/user.repository'; +import { createSessionSchema, type CreateSessionBody } from './dto'; +import { SessionService } from './session.service'; + +@Controller() +@UseGuards(AccessGuard) +export class SessionsController { + constructor(@Inject(SessionService) private readonly service: SessionService) {} + + // S4: owner creates; member 403; missing workspace or stranger 404. + @Post('workspaces/:workspaceId/sessions') + @HttpCode(201) + async create( + @CurrentUser() user: UserRecord, + @Param('workspaceId') workspaceId: string, + @Body(new ZodPipe(createSessionSchema)) body: CreateSessionBody, + ) { + const result = await this.service.create(user.id, workspaceId as WorkspaceId, body.name); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } + + // S5: owner or member list; missing workspace or stranger 404. + @Get('workspaces/:workspaceId/sessions') + async list(@CurrentUser() user: UserRecord, @Param('workspaceId') workspaceId: string) { + const result = await this.service.list(user.id, workspaceId as WorkspaceId); + if (result.kind === 'not-found') throw new NotFoundException(); + return result.views; + } + + // S6: any viewer (owner, member, guest); 403 without view access, 404 unknown. + @Get('sessions/:id') + async detail(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.detail(id as SessionId, user.id); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } +} diff --git a/apps/api/src/collab/views.ts b/apps/api/src/collab/views.ts index 4f48303..3165df3 100644 --- a/apps/api/src/collab/views.ts +++ b/apps/api/src/collab/views.ts @@ -1,5 +1,5 @@ import type { UserRecord } from '../persistence/user.repository'; -import type { UserId, Workspace, WorkspaceId } from '@opencollab/domain'; +import type { Session, SessionId, TerminalId, UserId, Workspace, WorkspaceId } from '@opencollab/domain'; export interface WorkspaceSummary { id: WorkspaceId; @@ -25,6 +25,36 @@ export function toWorkspaceSummary(ws: Workspace): WorkspaceSummary { return { id: ws.id, name: ws.name, owner: ws.owner, memberCount: ws.members.length }; } +export interface TerminalView { + id: TerminalId; + name: string; + command: string; + args: string[]; + cwd: string | null; +} + +export interface SessionView { + id: SessionId; + name: string; + terminals: TerminalView[]; +} + +// Terminals stay in the aggregate's position order (S5). `cwd` is nullable: +// a terminal without an explicit working directory persists as null. +export function toSessionView(session: Session): SessionView { + return { + id: session.id, + name: session.name, + terminals: session.terminals.map((t) => ({ + id: t.id, + name: t.profile.name, + command: t.profile.command, + args: t.profile.args, + cwd: t.profile.cwd ?? null, + })), + }; +} + // `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 { diff --git a/odd/tasks/api-rest-crud.md b/odd/tasks/api-rest-crud.md index 8e8c8b4..b299fba 100644 --- a/odd/tasks/api-rest-crud.md +++ b/odd/tasks/api-rest-crud.md @@ -28,7 +28,7 @@ Assumptions (marked as such, not user requirements): ## 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) +- 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). Review: tier high (463 lines), outcome granted/acknowledged (lineage review-78dd02cdbbd5c9c3, 0 blockers; advisory R3-001/R3-002 → L6) - 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 @@ -41,3 +41,4 @@ Assumptions (marked as such, not user requirements): - 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. +- L6 (2026-10-15, T1 review): RDD review of commit 2e3e113 (lineage review-78dd02cdbbd5c9c3, tier high, 463 changed lines, 3 lenses risk/readability/reliability) reached approved; authority burned, no corrections, 0 blocking findings. Advisory (non-blocking, candidates for T5 test hardening — not authorized scope by themselves): R3-001 `GET /workspaces/:id` casts the raw route param to WorkspaceId without a malformed-id failure-path assertion (400 vs 404 vs 500 unproved); R3-002 create-body upper boundary/shape handling and summary memberCount lack observable assertions (overlong name, non-string name, trimmed persistence, memberCount). From 3d2ae3395b53a2912ac5e08b8149505559aaa1c6 Mon Sep 17 00:00:00 2001 From: facyndev Date: Thu, 15 Oct 2026 11:31:09 -0300 Subject: [PATCH 2/2] feat(server): add terminals REST endpoints (add/remove) --- apps/api/src/collab/collab.module.ts | 3 +- apps/api/src/collab/dto.ts | 15 ++ apps/api/src/collab/session.service.ts | 74 +++++- .../collab/terminals.controller.int.spec.ts | 221 ++++++++++++++++++ apps/api/src/collab/terminals.controller.ts | 57 +++++ apps/api/src/collab/views.ts | 25 +- odd/tasks/api-rest-crud.md | 9 +- 7 files changed, 388 insertions(+), 16 deletions(-) create mode 100644 apps/api/src/collab/terminals.controller.int.spec.ts create mode 100644 apps/api/src/collab/terminals.controller.ts diff --git a/apps/api/src/collab/collab.module.ts b/apps/api/src/collab/collab.module.ts index 158c585..58a5091 100644 --- a/apps/api/src/collab/collab.module.ts +++ b/apps/api/src/collab/collab.module.ts @@ -4,12 +4,13 @@ import { AuthModule } from '../auth/auth.module'; import { PersistenceModule } from '../persistence/persistence.module'; import { SessionService } from './session.service'; import { SessionsController } from './sessions.controller'; +import { TerminalsController } from './terminals.controller'; import { WorkspacesController } from './workspaces.controller'; import { WorkspaceService } from './workspace.service'; @Module({ imports: [PersistenceModule, AuthModule], - controllers: [WorkspacesController, SessionsController], + controllers: [WorkspacesController, SessionsController, TerminalsController], providers: [WorkspaceService, SessionService], exports: [WorkspaceService, SessionService], }) diff --git a/apps/api/src/collab/dto.ts b/apps/api/src/collab/dto.ts index 7da61df..0e330b5 100644 --- a/apps/api/src/collab/dto.ts +++ b/apps/api/src/collab/dto.ts @@ -13,3 +13,18 @@ export const createSessionSchema = z .strict(); export type CreateSessionBody = z.infer; + +// S7 body. `env` is deliberately absent: the strict schema rejects it, so a +// client can never smuggle secrets into a terminal profile. `command` cannot +// be blank (domain EmptyCommand) but keeps the caller's exact spacing; the +// blank check does not echo the submitted value (S14). +export const addTerminalSchema = z + .object({ + name: z.string(), + command: z.string().refine((value) => value.trim() !== '', { message: 'command must not be blank' }), + args: z.array(z.string()).optional(), + cwd: z.string().nullable().optional(), + }) + .strict(); + +export type AddTerminalBody = z.infer; diff --git a/apps/api/src/collab/session.service.ts b/apps/api/src/collab/session.service.ts index 3c78dd9..c9868a6 100644 --- a/apps/api/src/collab/session.service.ts +++ b/apps/api/src/collab/session.service.ts @@ -1,10 +1,19 @@ import { Inject, Injectable } from '@nestjs/common'; -import { Session, type SessionId, type UserId, type Workspace, type WorkspaceId } from '@opencollab/domain'; +import { + newAgentProfile, + Session, + type SessionId, + type TerminalId, + type UserId, + type Workspace, + type WorkspaceId, +} from '@opencollab/domain'; import { SessionRepository } from '../persistence/session.repository'; import { WorkspaceRepository } from '../persistence/workspace.repository'; -import { toSessionView, type SessionView } from './views'; +import { toSessionView, toTerminalView, type SessionView, type TerminalView } from './views'; +import type { AddTerminalBody } from './dto'; // `not-found` covers both a missing workspace and a caller with no relation to // it: sessions endpoints must not leak workspace existence (S4/S5). @@ -24,6 +33,24 @@ export type SessionDetailResult = | { kind: 'not-found' } | { kind: 'forbidden' }; +// S7/S8: terminal mutations are owner-only; a non-owner never learns whether +// a terminal id exists (owner check runs before terminal existence). +export type TerminalCreateResult = + | { kind: 'created'; view: TerminalView } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +export type TerminalRemoveResult = + | { kind: 'removed' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +// The loaded session + its workspace, with the owner check already applied. +type OwnedSession = + | { kind: 'ok'; session: Session; workspace: Workspace } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + @Injectable() export class SessionService { constructor( @@ -66,4 +93,47 @@ export class SessionService { if (!ws || !session.canView(ws, actor)) return { kind: 'forbidden' }; return { kind: 'ok', view: toSessionView(session) }; } + + // Unknown session → 404; a caller without the workspace is `forbidden` (403), + // never leaking terminal existence. A vanished workspace is `not-found`: + // terminal mutations are meaningless without it (unreachable via cascade). + private async ownedSession(sessionId: SessionId, actor: UserId): Promise { + const session = await this.sessions.find(sessionId); + if (!session) return { kind: 'not-found' }; + const workspace = await this.workspaces.find(session.workspaceId); + if (!workspace) return { kind: 'not-found' }; + if (!workspace.isOwner(actor)) return { kind: 'forbidden' }; + return { kind: 'ok', session, workspace }; + } + + async addTerminal(actor: UserId, sessionId: SessionId, body: AddTerminalBody): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + // The domain factory copies args/env and enforces a non-blank command; + // env is always empty because the strict schema never accepts it (S7). + const profile = newAgentProfile(body.name, body.command, { + ...(body.args === undefined ? {} : { args: body.args }), + ...(body.cwd == null ? {} : { cwd: body.cwd }), + }); + // `addTerminal` re-checks ownership in the domain (ensureOwner). + const terminalId = acc.session.addTerminal(acc.workspace, actor, profile); + await this.sessions.save(acc.session); + const terminal = acc.session.terminal(terminalId); + if (!terminal) throw new Error('terminal vanished after addTerminal'); // unreachable + return { kind: 'created', view: toTerminalView(terminal) }; + } + + async removeTerminal( + actor: UserId, + sessionId: SessionId, + terminalId: TerminalId, + ): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + // TerminalNotInSession → 404 (the owner check already ran above). + if (!acc.session.terminal(terminalId)) return { kind: 'not-found' }; + acc.session.removeTerminal(acc.workspace, actor, terminalId); + await this.sessions.save(acc.session); + return { kind: 'removed' }; + } } diff --git a/apps/api/src/collab/terminals.controller.int.spec.ts b/apps/api/src/collab/terminals.controller.int.spec.ts new file mode 100644 index 0000000..1fc48e8 --- /dev/null +++ b/apps/api/src/collab/terminals.controller.int.spec.ts @@ -0,0 +1,221 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import type { SessionId, UserId, WorkspaceId } from '@opencollab/domain'; +import { SessionRepository } from '../persistence/session.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { truncateAll } from '../persistence/test-db'; +import { startCollabTestApp, type CollabTestApp } from './test-app'; + +let t: CollabTestApp; +let sessions: SessionRepository; +let workspaces: WorkspaceRepository; + +beforeAll(async () => { + t = await startCollabTestApp(); + sessions = new SessionRepository(t.prisma); + 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); +const del = (path: string, token?: string) => call('DELETE', path, undefined, 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 }; +} + +async function seedMember(workspaceId: WorkspaceId, ownerId: UserId, memberId: UserId): Promise { + const ws = await workspaces.find(workspaceId); + expect(ws).toBeTruthy(); + ws!.addMember(ownerId, memberId); + await workspaces.save(ws!); +} + +// Creates workspace + session through the endpoints added in T1/T2. +async function seedSession(ownerToken: string, name = 'sess'): Promise<{ wsId: string; sessionId: string }> { + const ws = (await post('/workspaces', { name: 'ws' }, ownerToken)).body as { id: string }; + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name }, ownerToken) + ).body as { id: string }; + return { wsId: ws.id, sessionId: session.id }; +} + +type TerminalBody = { id: string; name: string; command: string; args: string[]; cwd: string | null }; + +describe('POST /sessions/:id/terminals', () => { + it('appends a terminal for the owner and exposes it in the session detail (201)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'shell', command: 'pwsh', args: ['-NoLogo'], cwd: 'C:/tmp' }, + owner.token, + ); + expect(res.status).toBe(201); + const body = res.body as TerminalBody; + expect(body.name).toBe('shell'); + expect(body.command).toBe('pwsh'); + expect(body.args).toEqual(['-NoLogo']); + expect(body.cwd).toBe('C:/tmp'); + expect('env' in body).toBe(false); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals).toHaveLength(1); + expect(detail.terminals[0]?.id).toBe(body.id); + }); + + it('defaults args to [] and cwd to null when omitted', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'bash' }, owner.token); + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ args: [], cwd: null }); + }); + + it('returns 403 for a member and a stranger, 404 for an unknown session', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const { wsId, sessionId } = await seedSession(owner.token); + await seedMember(wsId as WorkspaceId, owner.id as UserId, member.id as UserId); + + expect( + (await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' }, member.token)).status, + ).toBe(403); + expect( + (await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' }, stranger.token)).status, + ).toBe(403); + expect( + (await post('/sessions/00000000-0000-0000-0000-000000000000/terminals', { name: 's', command: 'x' }, owner.token)) + .status, + ).toBe(404); + expect( + (await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' })).status, + ).toBe(401); + }); + + it('rejects invalid bodies with 400 and never accepts env (S7/S14)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const path = `/sessions/${sessionId}/terminals`; + + expect((await post(path, { name: 's' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: '' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: ' ' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', env: [['K', 'V']] }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', args: 'not-array' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', cwd: 42 }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', extra: true }, owner.token)).status).toBe(400); + }); + + it('never persists env even when the caller tries to send it (strict rejection)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const rejected = await post( + `/sessions/${sessionId}/terminals`, + { name: 's', command: 'x', env: [['SECRET', 'v']] }, + owner.token, + ); + expect(rejected.status).toBe(400); + + // The session stays empty and, on a valid create, the stored profile keeps env=[]. + const created = await post( + `/sessions/${sessionId}/terminals`, + { name: 's', command: 'x' }, + owner.token, + ); + expect(created.status).toBe(201); + const aggregate = await sessions.find(sessionId as SessionId); + expect(aggregate!.terminals[0]?.profile.env).toEqual([]); + }); +}); + +describe('DELETE /sessions/:id/terminals/:terminalId', () => { + it('removes the terminal for the owner (204) and it disappears from the detail', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' }, owner.token) + ).body as TerminalBody; + + const res = await del(`/sessions/${sessionId}/terminals/${created.id}`, owner.token); + expect(res.status).toBe(204); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals).toEqual([]); + }); + + it('returns 404 for an unknown terminal or session', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + expect( + (await del(`/sessions/${sessionId}/terminals/00000000-0000-0000-0000-000000000000`, owner.token)).status, + ).toBe(404); + expect( + (await del('/sessions/00000000-0000-0000-0000-000000000000/terminals/00000000-0000-0000-0000-000000000000', owner.token)) + .status, + ).toBe(404); + }); + + it('returns 403 for a member and a stranger before checking terminal existence', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const { wsId, sessionId } = await seedSession(owner.token); + await seedMember(wsId as WorkspaceId, owner.id as UserId, member.id as UserId); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' }, owner.token) + ).body as TerminalBody; + + expect((await del(`/sessions/${sessionId}/terminals/${created.id}`, member.token)).status).toBe(403); + // Non-owners must not learn whether a terminal id exists: a stranger probing + // an unknown id still gets 403, not 404. + expect( + (await del(`/sessions/${sessionId}/terminals/00000000-0000-0000-0000-000000000000`, stranger.token)).status, + ).toBe(403); + expect((await del(`/sessions/${sessionId}/terminals/${created.id}`)).status).toBe(401); + }); +}); diff --git a/apps/api/src/collab/terminals.controller.ts b/apps/api/src/collab/terminals.controller.ts new file mode 100644 index 0000000..921ec1d --- /dev/null +++ b/apps/api/src/collab/terminals.controller.ts @@ -0,0 +1,57 @@ +import { + Body, + Controller, + Delete, + ForbiddenException, + HttpCode, + Inject, + NotFoundException, + Param, + Post, + UseGuards, +} from '@nestjs/common'; + +import type { SessionId, TerminalId } from '@opencollab/domain'; +import { AccessGuard, CurrentUser } from '../auth/access.guard'; +import { ZodPipe } from '../auth/dto'; +import type { UserRecord } from '../persistence/user.repository'; +import { addTerminalSchema, type AddTerminalBody } from './dto'; +import { SessionService } from './session.service'; + +@Controller() +@UseGuards(AccessGuard) +export class TerminalsController { + constructor(@Inject(SessionService) private readonly service: SessionService) {} + + // S7: owner only; 403 for anyone else, 404 for an unknown session. + @Post('sessions/:id/terminals') + @HttpCode(201) + async create( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(addTerminalSchema)) body: AddTerminalBody, + ) { + const result = await this.service.addTerminal(user.id, id as SessionId, body); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } + + // S8: owner only; 204 on success, 404 for unknown session or terminal, + // 403 for anyone else (terminal existence stays hidden from non-owners). + @Delete('sessions/:id/terminals/:terminalId') + @HttpCode(204) + async remove( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Param('terminalId') terminalId: string, + ) { + const result = await this.service.removeTerminal( + user.id, + id as SessionId, + terminalId as TerminalId, + ); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + } +} diff --git a/apps/api/src/collab/views.ts b/apps/api/src/collab/views.ts index 3165df3..2992c18 100644 --- a/apps/api/src/collab/views.ts +++ b/apps/api/src/collab/views.ts @@ -1,5 +1,5 @@ import type { UserRecord } from '../persistence/user.repository'; -import type { Session, SessionId, TerminalId, UserId, Workspace, WorkspaceId } from '@opencollab/domain'; +import type { Session, SessionId, Terminal, TerminalId, UserId, Workspace, WorkspaceId } from '@opencollab/domain'; export interface WorkspaceSummary { id: WorkspaceId; @@ -39,19 +39,24 @@ export interface SessionView { terminals: TerminalView[]; } -// Terminals stay in the aggregate's position order (S5). `cwd` is nullable: -// a terminal without an explicit working directory persists as null. +// `cwd` is nullable: a terminal without an explicit working directory +// persists as null. `env` is never part of the projection (S7). +export function toTerminalView(terminal: Terminal): TerminalView { + return { + id: terminal.id, + name: terminal.profile.name, + command: terminal.profile.command, + args: terminal.profile.args, + cwd: terminal.profile.cwd ?? null, + }; +} + +// Terminals stay in the aggregate's position order (S5). export function toSessionView(session: Session): SessionView { return { id: session.id, name: session.name, - terminals: session.terminals.map((t) => ({ - id: t.id, - name: t.profile.name, - command: t.profile.command, - args: t.profile.args, - cwd: t.profile.cwd ?? null, - })), + terminals: session.terminals.map(toTerminalView), }; } diff --git a/odd/tasks/api-rest-crud.md b/odd/tasks/api-rest-crud.md index b299fba..e8263ca 100644 --- a/odd/tasks/api-rest-crud.md +++ b/odd/tasks/api-rest-crud.md @@ -1,7 +1,7 @@ # 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`) +Branch: feature/api-rest-crud | Delivery: PR chain to develop (strategy `feature-branch-chain`, decided L8; slices: PR1=T1, PR2=T2+T3, PR3=T4+T5) | Test runner: `pnpm --filter @opencollab/server test` (unit) + `pnpm --filter @opencollab/server test:integration` (needs Postgres via `DATABASE_URL`) ## Specs @@ -29,8 +29,8 @@ Assumptions (marked as such, not user requirements): ## 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). Review: tier high (463 lines), outcome granted/acknowledged (lineage review-78dd02cdbbd5c9c3, 0 blockers; advisory R3-001/R3-002 → L6) -- 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 +- T2 (S4-S6, S14-S15): SessionsController — create/list/get sessions + terminals in views; int tests RED→GREEN. route: inline — DONE (9 int tests, unit 166, int 116, typecheck 0, commit b51d335). Review assess: medium, under_budget (pending in slice) +- T3 (S7-S8, S14-S15): TerminalsController — add/remove terminal; int tests RED→GREEN. route: inline — DONE (8 int tests, unit 166, int 124, typecheck 0, commit TBD). Review assess: pending until commit - 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 @@ -42,3 +42,6 @@ Assumptions (marked as such, not user requirements): - 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. - L6 (2026-10-15, T1 review): RDD review of commit 2e3e113 (lineage review-78dd02cdbbd5c9c3, tier high, 463 changed lines, 3 lenses risk/readability/reliability) reached approved; authority burned, no corrections, 0 blocking findings. Advisory (non-blocking, candidates for T5 test hardening — not authorized scope by themselves): R3-001 `GET /workspaces/:id` casts the raw route param to WorkspaceId without a malformed-id failure-path assertion (400 vs 404 vs 500 unproved); R3-002 create-body upper boundary/shape handling and summary memberCount lack observable assertions (overlong name, non-string name, trimmed persistence, memberCount). +- L7 (2026-10-15, T2 done): SessionsController with full-route @Controller() (POST/GET `workspaces/:workspaceId/sessions`, GET `sessions/:id`) + `SessionService` access classification: missing workspace AND stranger both → 404 on nested routes (no existence leak, S4/S5); member non-owner → 403 on create; detail uses `session.canView(workspace, user)` (guests included) → 403 without view access, 404 unknown. New `SessionView`/`TerminalView` projections in views.ts (cwd nullable, position order from repository include); `createSessionSchema` strict (S14). Guest/member/terminal seeding in tests bypasses the T4/T3 endpoints via repositories (documented in-spec). Evidence: RED 7/9 failed → focused GREEN 9/9; unit 166/166, integration 116/116, typecheck exit 0; gitleaks clean; commit b51d335 (411 authored lines in slice → running count now >400, chain strategy question owed before next commit per delivery budget). Environment note: integration runs need Docker Desktop up + `docker compose up -d postgres` and `DATABASE_URL=postgresql://opencollab:opencollab@localhost:5432/opencollab` (CI default creds; root .env has no DATABASE_URL). +- L8 (2026-10-15, user decision): Delivery strategy asked once per ask-on-risk (running count >400 authored lines). User chose `feature-branch-chain`: PR chain from feature/api-rest-crud to develop, slices PR1=T1 (2e3e113), PR2=T2+T3 (b51d335..T3), PR3=T4+T5. Push/PR creation remain human decisions. +- L9 (2026-10-15, T3 done): TerminalsController (POST/DELETE `sessions/:id/terminals`) + `SessionService.addTerminal/removeTerminal` with `ownedSession` helper: unknown session → 404, non-owner (member/stranger/guest) → 403 BEFORE terminal-existence check (stranger probing unknown terminal id gets 403, not 404 — no existence leak), unknown terminal → 404. Profile built via domain `newAgentProfile` (copies args, blank command blocked); zod `addTerminalSchema` strict rejects `env` (never accepted/persisted) and rejects blank command with a non-echoing refine; `cwd: null` normalized to absent. `toTerminalView` extracted in views.ts (env never projected). Evidence: RED 7/8 failed → focused GREEN 8/8; unit 166/166, integration 124/124, typecheck exit 0.