diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 32c22bc..88121ea 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -1,6 +1,7 @@ import { Module } from '@nestjs/common'; import { AuthModule } from './auth/auth.module'; +import { CollabModule } from './collab/collab.module'; import { CollabGateway } from './collab.gateway'; import { HealthController } from './health.controller'; import { SESSION_STORE, SessionHub, type SessionStore } from './hub'; @@ -10,7 +11,7 @@ import { SessionRepository } from './persistence/session.repository'; import { WorkspaceRepository } from './persistence/workspace.repository'; @Module({ - imports: [AuthModule, PersistenceModule], + imports: [AuthModule, CollabModule, PersistenceModule], controllers: [HealthController], providers: [ { diff --git a/apps/api/src/app.routes.int.spec.ts b/apps/api/src/app.routes.int.spec.ts new file mode 100644 index 0000000..e96ca76 --- /dev/null +++ b/apps/api/src/app.routes.int.spec.ts @@ -0,0 +1,82 @@ +import type { INestApplication } from '@nestjs/common'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { Test } from '@nestjs/testing'; +import { WsAdapter } from '@nestjs/platform-ws'; + +import { AUTH_CONFIG, type AuthConfig } from './auth/config'; +import { applyHttpConfig } from './auth/http-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 type { PrismaClient } from './generated/prisma/client'; +import { AppModule } from './app.module'; + +// Boots the REAL AppModule (not the CollabModule-only test app) to prove the +// collab REST surface is wired into the production module graph and that its +// routes stay behind AccessGuard (S14: unauthenticated -> 401, not 404). +describe('AppModule collab route wiring (int)', () => { + let app: INestApplication; + let prisma: PrismaClient; + let baseUrl: string; + + beforeAll(async () => { + prisma = openTestClient(); + const config: AuthConfig = { + jwtSecret: 'test-secret-test-secret-test-secret-test', + databaseUrl: 'unused', + publicBaseUrl: 'http://api.test', + webOrigin: 'http://web.test', + oauth: {}, + rateLimitEnabled: false, + trustProxy: false, + }; + const moduleRef = await Test.createTestingModule({ imports: [AppModule] }) + .overrideProvider(PRISMA) + .useValue(prisma) + .overrideProvider(AUTH_CONFIG) + .useValue(config) + .overrideProvider(OAUTH_PROVIDERS) + .useValue({}) + .overrideProvider(CLOCK) + .useValue(new TestClock()) + .compile(); + app = moduleRef.createNestApplication(); + applyHttpConfig(app, config); + app.useWebSocketAdapter(new WsAdapter(app)); + await app.listen(0, '127.0.0.1'); + baseUrl = await app.getUrl(); + }); + + afterAll(async () => { + await app.close(); + await prisma.$disconnect(); + }); + + async function statusOf(method: string, path: string): Promise { + const res = await fetch(`${baseUrl}${path}`, { method }); + return res.status; + } + + it('still serves the existing health route', async () => { + expect(await statusOf('GET', '/health')).toBe(200); + }); + + it('registers workspaces routes behind the access guard (S14)', async () => { + expect(await statusOf('GET', '/workspaces')).toBe(401); + }); + + it('registers nested sessions routes behind the access guard (S14)', async () => { + expect(await statusOf('GET', '/workspaces/00000000-0000-0000-0000-000000000000/sessions')).toBe(401); + }); + + it('registers terminals routes behind the access guard (S14)', async () => { + expect(await statusOf('POST', '/sessions/00000000-0000-0000-0000-000000000000/terminals')).toBe(401); + }); + + it('registers invitations routes behind the access guard (S14)', async () => { + expect(await statusOf('GET', '/invitations')).toBe(401); + expect(await statusOf('POST', '/invitations/00000000-0000-0000-0000-000000000000/accept')).toBe(401); + }); +}); 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..92d906e --- /dev/null +++ b/apps/api/src/collab/collab.module.ts @@ -0,0 +1,19 @@ +import { Module } from '@nestjs/common'; + +import { AuthModule } from '../auth/auth.module'; +import { PersistenceModule } from '../persistence/persistence.module'; +import { InvitationsController } from './invitations.controller'; +import { InvitationsService } from './invitations.service'; +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, TerminalsController, InvitationsController], + providers: [WorkspaceService, SessionService, InvitationsService], + exports: [WorkspaceService, SessionService, InvitationsService], +}) +export class CollabModule {} diff --git a/apps/api/src/collab/domain-errors.ts b/apps/api/src/collab/domain-errors.ts new file mode 100644 index 0000000..5b44252 --- /dev/null +++ b/apps/api/src/collab/domain-errors.ts @@ -0,0 +1,26 @@ +import { DomainError } from '@opencollab/domain'; + +// S15: maps a caught domain error to the HTTP-equivalent result kind. The +// controller turns each kind into its Nest exception; anything that is not a +// DomainError is rethrown unchanged and becomes a 500. +export type DomainViolation = 'forbidden' | 'conflict' | 'not-found' | 'bad-request'; + +export function domainViolation(error: unknown): DomainViolation { + if (error instanceof DomainError) { + switch (error.code) { + case 'NotOwner': + case 'NotAParticipant': + return 'forbidden'; + case 'AlreadyHasAccess': + case 'InvitationTargetMismatch': + case 'CannotChangeOwnerAccess': + return 'conflict'; + case 'TerminalNotInSession': + case 'WorkspaceMismatch': + return 'not-found'; + case 'EmptyCommand': + return 'bad-request'; + } + } + throw error; +} diff --git a/apps/api/src/collab/dto.ts b/apps/api/src/collab/dto.ts new file mode 100644 index 0000000..7bee89b --- /dev/null +++ b/apps/api/src/collab/dto.ts @@ -0,0 +1,46 @@ +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; + +// 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; + +// 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; + +// S9/S10 body. The uuid message names the rule, never the submitted value +// (S14: ZodPipe only emits field paths and messages). +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export const inviteSchema = z + .object({ inviteeId: z.string().regex(UUID, { message: 'must be a uuid' }) }) + .strict(); + +export type InviteBody = z.infer; + +// Malformed invitation ids answer 404, never 500: Postgres uuid columns throw +// on non-uuid input, so the format is pre-checked before Prisma sees it. +export function isUuid(value: string): boolean { + return UUID.test(value); +} diff --git a/apps/api/src/collab/invitations.controller.int.spec.ts b/apps/api/src/collab/invitations.controller.int.spec.ts new file mode 100644 index 0000000..1afb654 --- /dev/null +++ b/apps/api/src/collab/invitations.controller.int.spec.ts @@ -0,0 +1,554 @@ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import type { InvitationId, UserId, WorkspaceId } from '@opencollab/domain'; +import { InvitationRepository } from '../persistence/invitation.repository'; +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; +let invitations: InvitationRepository; + +beforeAll(async () => { + t = await startCollabTestApp(); + workspaces = new WorkspaceRepository(t.prisma); + invitations = new InvitationRepository(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 postEmpty = (path: string, token?: string) => call('POST', path, undefined, token); + +let counter = 0; +async function registerUser(prefix = 'user'): Promise<{ id: string; token: string; username: 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, username }; +} + +async function seedWorkspace(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 }; +} + +async function seedSession(ownerToken: string, wsId: string, name = 'sess'): Promise<{ id: string }> { + const res = await post(`/workspaces/${wsId}/sessions`, { name }, ownerToken); + expect(res.status).toBe(201); + return res.body as { id: string }; +} + +// Seeds a member straight through the repository: no endpoint exists for it. +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!); +} + +// Seeds an already-expired invitation straight through the repository: the API +// never creates expiring invitations, so expiry can only be set up this way. +async function seedExpiredWorkspaceInvitation( + workspaceId: WorkspaceId, + ownerId: UserId, + inviteeId: UserId, +): Promise { + const ws = await workspaces.find(workspaceId); + expect(ws).toBeTruthy(); + const invitation = ws!.inviteMember(ownerId, inviteeId); + await invitations.save(invitation, new Date(Date.now() - 60_000)); + return invitation.id; +} + +type InvitationBody = { + id: string; + target: + | { kind: 'workspace'; workspaceId: string; name: string } + | { kind: 'session'; sessionId: string; name: string }; + invitedBy: { userId: string; username: string; displayName: string }; +}; + +const UNKNOWN_ID = '00000000-0000-0000-0000-000000000000'; + +describe('POST /workspaces/:id/invitations (S9)', () => { + it('invites a user as member and returns the invitation view (201)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token, 'team'); + + const res = await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token); + expect(res.status).toBe(201); + const body = res.body as InvitationBody; + expect(Object.keys(body).sort()).toEqual(['id', 'invitedBy', 'target']); + expect(body.target).toEqual({ kind: 'workspace', workspaceId: ws.id, name: 'team' }); + expect(body.invitedBy).toEqual({ + userId: owner.id, + username: owner.username, + displayName: 'owner', + }); + + // The invitation is stored as pending. + const stored = await invitations.find(body.id as InvitationId); + expect(stored?.status).toBe('pending'); + expect(stored?.invitation.invitee).toBe(invitee.id); + }); + + it('returns 404 for an unknown workspace, 403 for member and stranger, 401 without token', async () => { + const owner = await registerUser('owner'); + const member = await registerUser('member'); + const stranger = await registerUser('stranger'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + + expect( + (await post(`/workspaces/${UNKNOWN_ID}/invitations`, { inviteeId: invitee.id }, owner.token)).status, + ).toBe(404); + expect( + (await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, member.token)).status, + ).toBe(403); + expect( + (await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, stranger.token)).status, + ).toBe(403); + expect((await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id })).status).toBe(401); + expect((await post(`/workspaces/${UNKNOWN_ID}/invitations`, { inviteeId: invitee.id })).status).toBe( + 401, + ); + }); + + it('returns 409 when the invitee is already the owner or a member', async () => { + const owner = await registerUser('owner'); + const member = await registerUser('member'); + const ws = await seedWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + + expect( + (await post(`/workspaces/${ws.id}/invitations`, { inviteeId: owner.id }, owner.token)).status, + ).toBe(409); + expect( + (await post(`/workspaces/${ws.id}/invitations`, { inviteeId: member.id }, owner.token)).status, + ).toBe(409); + }); + + it('returns 404 for a ghost invitee (well-formed UUID of a nonexistent user) and stores nothing', async () => { + const owner = await registerUser('owner'); + const ws = await seedWorkspace(owner.token); + const ghost = randomUUID(); + + const res = await post(`/workspaces/${ws.id}/invitations`, { inviteeId: ghost }, owner.token); + expect(res.status).toBe(404); + + // Nothing was stored: the ghost has no pending invitation. + expect(await invitations.listPendingFor(ghost as UserId)).toEqual([]); + }); + + it('rejects invalid bodies with 400 without echoing submitted values (S14)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const path = `/workspaces/${ws.id}/invitations`; + + expect((await post(path, {}, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: 42 }, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: null }, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: 'not-a-uuid' }, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: invitee.id, extra: true }, owner.token)).status).toBe(400); + + // Field path only: the submitted value must never appear in the response. + const leaked = 'definitely-not-a-user-zzz'; + const res = await post(path, { inviteeId: leaked }, owner.token); + expect(res.status).toBe(400); + expect(JSON.stringify(res.body)).not.toContain(leaked); + expect(JSON.stringify(res.body)).toContain('inviteeId'); + }); +}); + +describe('POST /sessions/:id/invitations (S10)', () => { + it('invites a user as guest and returns the session-target view (201)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token, 'team'); + const session = await seedSession(owner.token, ws.id, 'standup'); + + const res = await post(`/sessions/${session.id}/invitations`, { inviteeId: invitee.id }, owner.token); + expect(res.status).toBe(201); + const body = res.body as InvitationBody; + expect(Object.keys(body).sort()).toEqual(['id', 'invitedBy', 'target']); + expect(body.target).toEqual({ kind: 'session', sessionId: session.id, name: 'standup' }); + expect(body.invitedBy.userId).toBe(owner.id); + }); + + it('returns 404 for an unknown session or a vanished workspace; 403 for member, stranger and guest; 401 without token', async () => { + const owner = await registerUser('owner'); + const member = await registerUser('member'); + const stranger = await registerUser('stranger'); + const guest = await registerUser('guest'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const session = await seedSession(owner.token, ws.id); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + // Guest role via the invitations flow itself. + const guestInvite = await post( + `/sessions/${session.id}/invitations`, + { inviteeId: guest.id }, + owner.token, + ); + expect(guestInvite.status).toBe(201); + expect( + (await postEmpty(`/invitations/${(guestInvite.body as InvitationBody).id}/accept`, guest.token)).status, + ).toBe(204); + + const path = `/sessions/${session.id}/invitations`; + expect((await post(path, { inviteeId: invitee.id }, member.token)).status).toBe(403); + expect((await post(path, { inviteeId: invitee.id }, stranger.token)).status).toBe(403); + expect((await post(path, { inviteeId: invitee.id }, guest.token)).status).toBe(403); + expect((await post(`/sessions/${UNKNOWN_ID}/invitations`, { inviteeId: invitee.id }, owner.token)).status).toBe( + 404, + ); + // A ghost invitee (unknown user id) is 404 on the session path too. + expect((await post(path, { inviteeId: randomUUID() }, owner.token)).status).toBe(404); + expect((await post(path, { inviteeId: invitee.id })).status).toBe(401); + + // A session whose workspace is gone is 404 (workspaces cascade to sessions). + await t.prisma.workspace.delete({ where: { id: ws.id } }); + expect((await post(path, { inviteeId: invitee.id }, owner.token)).status).toBe(404); + }); + + it('returns 409 when the invitee already has a role (owner, member, guest)', async () => { + const owner = await registerUser('owner'); + const member = await registerUser('member'); + const guest = await registerUser('guest'); + const ws = await seedWorkspace(owner.token); + const session = await seedSession(owner.token, ws.id); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + const path = `/sessions/${session.id}/invitations`; + + expect((await post(path, { inviteeId: owner.id }, owner.token)).status).toBe(409); + expect((await post(path, { inviteeId: member.id }, owner.token)).status).toBe(409); + + const created = (await post(path, { inviteeId: guest.id }, owner.token)).body as InvitationBody; + expect((await postEmpty(`/invitations/${created.id}/accept`, guest.token)).status).toBe(204); + expect((await post(path, { inviteeId: guest.id }, owner.token)).status).toBe(409); + }); + + it('rejects invalid bodies with 400 without echoing submitted values (S14)', async () => { + const owner = await registerUser('owner'); + const ws = await seedWorkspace(owner.token); + const session = await seedSession(owner.token, ws.id); + const path = `/sessions/${session.id}/invitations`; + + expect((await post(path, {}, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: 'not-a-uuid' }, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: randomUUID(), extra: 1 }, owner.token)).status).toBe(400); + + const leaked = 'definitely-not-a-user-zzz'; + const res = await post(path, { inviteeId: leaked }, owner.token); + expect(res.status).toBe(400); + expect(JSON.stringify(res.body)).not.toContain(leaked); + expect(JSON.stringify(res.body)).toContain('inviteeId'); + }); +}); + +describe('GET /invitations (S11)', () => { + it('lists the caller pending invitations with target and inviter (200)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token, 'team'); + const session = await seedSession(owner.token, ws.id, 'standup'); + + const wsInvite = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + const sessionInvite = ( + await post(`/sessions/${session.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + const res = await get('/invitations', invitee.token); + expect(res.status).toBe(200); + const list = res.body as InvitationBody[]; + expect(list).toHaveLength(2); + const byId = new Map(list.map((entry) => [entry.id, entry])); + expect(byId.get(wsInvite.id)?.target).toEqual({ + kind: 'workspace', + workspaceId: ws.id, + name: 'team', + }); + expect(byId.get(sessionInvite.id)?.target).toEqual({ + kind: 'session', + sessionId: session.id, + name: 'standup', + }); + for (const entry of list) { + expect(entry.invitedBy).toEqual({ + userId: owner.id, + username: owner.username, + displayName: 'owner', + }); + } + + // Another user sees none of them. + expect(((await get('/invitations', owner.token)).body as unknown[])).toEqual([]); + }); + + it('excludes declined, accepted and expired invitations from the list', async () => { + const owner = await registerUser('owner'); + const declined = await registerUser('declined'); + const accepted = await registerUser('accepted'); + const expired = await registerUser('expired'); + const ws = await seedWorkspace(owner.token); + + const declinedId = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: declined.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${declinedId.id}/decline`, declined.token)).status).toBe(204); + + const acceptedId = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: accepted.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${acceptedId.id}/accept`, accepted.token)).status).toBe(204); + + await seedExpiredWorkspaceInvitation(ws.id as WorkspaceId, owner.id as UserId, expired.id as UserId); + + expect(((await get('/invitations', declined.token)).body as unknown[])).toEqual([]); + expect(((await get('/invitations', accepted.token)).body as unknown[])).toEqual([]); + expect(((await get('/invitations', expired.token)).body as unknown[])).toEqual([]); + }); + + it('hides entries whose target aggregate no longer exists', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token); + expect(((await get('/invitations', invitee.token)).body as unknown[])).toHaveLength(1); + + // Workspaces cascade to their invitations, so the entry disappears with it. + await t.prisma.workspace.delete({ where: { id: ws.id } }); + expect(((await get('/invitations', invitee.token)).body as unknown[])).toEqual([]); + }); + + it('requires auth (401)', async () => { + expect((await get('/invitations')).status).toBe(401); + }); +}); + +describe('POST /invitations/:id/accept (S12)', () => { + it('workspace invitee accepts (204), becomes a member, invitation marked accepted', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + const res = await postEmpty(`/invitations/${created.id}/accept`, invitee.token); + expect(res.status).toBe(204); + expect(res.body).toBeUndefined(); + + // Membership applied: the invitee now sees the workspace detail as a member. + const detail = (await get(`/workspaces/${ws.id}`, invitee.token)).body as { + members: { userId: string }[]; + }; + expect(detail.members.map((m) => m.userId)).toContain(invitee.id); + + // Invitation marked accepted (S15: aggregate change and status stay together). + expect((await invitations.find(created.id as InvitationId))?.status).toBe('accepted'); + }); + + it('session invitee accepts (204) and can then view the session', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const stranger = await registerUser('stranger'); + const ws = await seedWorkspace(owner.token); + const session = await seedSession(owner.token, ws.id); + expect((await get(`/sessions/${session.id}`, invitee.token)).status).toBe(403); + + const created = ( + await post(`/sessions/${session.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(204); + expect((await get(`/sessions/${session.id}`, invitee.token)).status).toBe(200); + expect((await get(`/sessions/${session.id}`, stranger.token)).status).toBe(403); + }); + + it('returns 404 for unknown and malformed ids (never 500)', async () => { + const user = await registerUser('user'); + expect((await postEmpty(`/invitations/${UNKNOWN_ID}/accept`, user.token)).status).toBe(404); + expect((await postEmpty('/invitations/not-a-uuid/accept', user.token)).status).toBe(404); + }); + + it('returns 403 for non-invitees before any status signal (no leak)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const stranger = await registerUser('stranger'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + // Pending invitation, stranger probes: 403, not 404/409. + expect((await postEmpty(`/invitations/${created.id}/accept`, stranger.token)).status).toBe(403); + expect((await postEmpty(`/invitations/${created.id}/decline`, stranger.token)).status).toBe(403); + + // After the invitee accepts, the stranger still gets 403 (no status leak). + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(204); + expect((await postEmpty(`/invitations/${created.id}/accept`, stranger.token)).status).toBe(403); + expect((await postEmpty(`/invitations/${created.id}/accept`, owner.token)).status).toBe(403); + }); + + it('returns 409 for already-responded and expired invitations without changing them', async () => { + const owner = await registerUser('owner'); + const twice = await registerUser('twice'); + const declined = await registerUser('declined'); + const expired = await registerUser('expired'); + const ws = await seedWorkspace(owner.token); + + const twiceId = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: twice.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${twiceId.id}/accept`, twice.token)).status).toBe(204); + expect((await postEmpty(`/invitations/${twiceId.id}/accept`, twice.token)).status).toBe(409); + expect((await invitations.find(twiceId.id as InvitationId))?.status).toBe('accepted'); + + const declinedId = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: declined.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${declinedId.id}/decline`, declined.token)).status).toBe(204); + expect((await postEmpty(`/invitations/${declinedId.id}/accept`, declined.token)).status).toBe(409); + expect((await invitations.find(declinedId.id as InvitationId))?.status).toBe('declined'); + + const expiredId = await seedExpiredWorkspaceInvitation( + ws.id as WorkspaceId, + owner.id as UserId, + expired.id as UserId, + ); + expect((await postEmpty(`/invitations/${expiredId}/accept`, expired.token)).status).toBe(409); + expect((await invitations.find(expiredId as InvitationId))?.status).toBe('pending'); + }); + + it('returns 409 and leaves the invitation pending when the invitee is already a member (failed accept never applies)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + // The invitee gains membership through another path before accepting. + await seedMember(ws.id as WorkspaceId, owner.id as UserId, invitee.id as UserId); + + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(409); + // A failed accept never marks the invitation accepted (S15). + expect((await invitations.find(created.id as InvitationId))?.status).toBe('pending'); + }); + + it('returns 404 when the target aggregate is gone', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + await t.prisma.workspace.delete({ where: { id: ws.id } }); + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(404); + }); + + it('requires auth (401)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + expect((await postEmpty(`/invitations/${created.id}/accept`)).status).toBe(401); + expect((await postEmpty('/invitations/not-a-uuid/accept')).status).toBe(401); + }); +}); + +describe('POST /invitations/:id/decline (S13)', () => { + it('invitee declines (204): invitation marked declined and hidden from the list', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + expect(((await get('/invitations', invitee.token)).body as unknown[])).toHaveLength(1); + + const res = await postEmpty(`/invitations/${created.id}/decline`, invitee.token); + expect(res.status).toBe(204); + expect(res.body).toBeUndefined(); + expect((await invitations.find(created.id as InvitationId))?.status).toBe('declined'); + expect(((await get('/invitations', invitee.token)).body as unknown[])).toEqual([]); + + // Declining grants nothing: the invitee still cannot see the workspace. + expect((await get(`/workspaces/${ws.id}`, invitee.token)).status).toBe(403); + }); + + it('returns 409 on double decline and on accept-after-decline', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + expect((await postEmpty(`/invitations/${created.id}/decline`, invitee.token)).status).toBe(204); + expect((await postEmpty(`/invitations/${created.id}/decline`, invitee.token)).status).toBe(409); + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(409); + expect((await invitations.find(created.id as InvitationId))?.status).toBe('declined'); + }); + + it('returns 403 for non-invitees, 404 for unknown/malformed ids, 401 without token', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const stranger = await registerUser('stranger'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + expect((await postEmpty(`/invitations/${created.id}/decline`, stranger.token)).status).toBe(403); + expect((await postEmpty(`/invitations/${UNKNOWN_ID}/decline`, invitee.token)).status).toBe(404); + expect((await postEmpty('/invitations/not-a-uuid/decline', invitee.token)).status).toBe(404); + expect((await postEmpty(`/invitations/${created.id}/decline`)).status).toBe(401); + expect((await get('/invitations')).status).toBe(401); + expect((await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id })).status).toBe(401); + }); +}); diff --git a/apps/api/src/collab/invitations.controller.ts b/apps/api/src/collab/invitations.controller.ts new file mode 100644 index 0000000..cfce725 --- /dev/null +++ b/apps/api/src/collab/invitations.controller.ts @@ -0,0 +1,90 @@ +import { + Body, + ConflictException, + Controller, + ForbiddenException, + Get, + HttpCode, + Inject, + NotFoundException, + Param, + Post, + UseGuards, +} from '@nestjs/common'; + +import type { SessionId, UserId, WorkspaceId } from '@opencollab/domain'; +import { AccessGuard, CurrentUser } from '../auth/access.guard'; +import { ZodPipe } from '../auth/dto'; +import type { UserRecord } from '../persistence/user.repository'; +import { inviteSchema, type InviteBody } from './dto'; +import { InvitationsService } from './invitations.service'; + +@Controller() +@UseGuards(AccessGuard) +export class InvitationsController { + constructor(@Inject(InvitationsService) private readonly service: InvitationsService) {} + + // S9: owner invites a workspace member; 201 with the invitation view. + @Post('workspaces/:id/invitations') + @HttpCode(201) + async inviteToWorkspace( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(inviteSchema)) body: InviteBody, + ) { + const result = await this.service.inviteToWorkspace( + user.id, + id as WorkspaceId, + body.inviteeId as UserId, + ); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + return result.view; + } + + // S10: owner invites a session guest; 201 with the invitation view. + @Post('sessions/:id/invitations') + @HttpCode(201) + async inviteToSession( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(inviteSchema)) body: InviteBody, + ) { + const result = await this.service.inviteToSession( + user.id, + id as SessionId, + body.inviteeId as UserId, + ); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + return result.view; + } + + // S11: the caller's pending, non-expired invitations. + @Get('invitations') + async list(@CurrentUser() user: UserRecord) { + return this.service.list(user.id); + } + + // S12: only the invitee may accept; 204 with no body. + @Post('invitations/:id/accept') + @HttpCode(204) + async accept(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.accept(user.id, id); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + } + + // S13: only the invitee may decline; 204 with no body. + @Post('invitations/:id/decline') + @HttpCode(204) + async decline(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.decline(user.id, id); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + } +} diff --git a/apps/api/src/collab/invitations.service.ts b/apps/api/src/collab/invitations.service.ts new file mode 100644 index 0000000..f54a61a --- /dev/null +++ b/apps/api/src/collab/invitations.service.ts @@ -0,0 +1,243 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import type { + Invitation, + InvitationId, + SessionId, + UserId, + WorkspaceId, +} from '@opencollab/domain'; +import { InvitationRepository, type StoredInvitation } from '../persistence/invitation.repository'; +import { SessionRepository } from '../persistence/session.repository'; +import { UserRepository } from '../persistence/user.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { domainViolation } from './domain-errors'; +import { isUuid } from './dto'; +import type { InvitationView } from './views'; + +export type InvitationCreateResult = + | { kind: 'created'; view: InvitationView } + | { kind: 'not-found' } + | { kind: 'forbidden' } + | { kind: 'conflict' }; + +export type InvitationRespondResult = + | { kind: 'ok' } + | { kind: 'not-found' } + | { kind: 'forbidden' } + | { kind: 'conflict' }; + +type ResponseLookup = + | { kind: 'ok'; stored: StoredInvitation } + | { kind: 'not-found' } + | { kind: 'forbidden' } + | { kind: 'conflict' }; + +@Injectable() +export class InvitationsService { + constructor( + @Inject(WorkspaceRepository) private readonly workspaces: WorkspaceRepository, + @Inject(SessionRepository) private readonly sessions: SessionRepository, + @Inject(UserRepository) private readonly users: UserRepository, + @Inject(InvitationRepository) private readonly invitations: InvitationRepository, + ) {} + + // S9: unknown workspace 404; any non-owner (member or stranger) 403 — the + // workspace existence is intentionally visible here, unlike the nested + // session routes. A ghost invitee (unknown user id) is stored as-is. + async inviteToWorkspace( + actor: UserId, + workspaceId: WorkspaceId, + inviteeId: UserId, + ): Promise { + const ws = await this.workspaces.find(workspaceId); + if (!ws) return { kind: 'not-found' }; + if (!ws.isOwner(actor)) return { kind: 'forbidden' }; + // Unknown users cannot be invited: the invitation row holds a required FK + // to User, so the check runs up front (after the owner check, so strangers + // still get 403 without learning whether the user id exists). + if (!(await this.users.findById(inviteeId))) return { kind: 'not-found' }; + let invitation: Invitation; + try { + invitation = ws.inviteMember(actor, inviteeId); + } catch (error) { + // Only AlreadyHasAccess is reachable (ownership was pre-checked). + return { kind: this.inviteViolation(error) }; + } + // Created invitations never expire. + await this.invitations.save(invitation, null); + const inviter = await this.users.findById(actor); + if (!inviter) throw new Error('authenticated user vanished'); // unreachable + return { + kind: 'created', + view: { + id: invitation.id, + target: { kind: 'workspace', workspaceId: ws.id, name: ws.name }, + invitedBy: { userId: inviter.id, username: inviter.username, displayName: inviter.displayName }, + }, + }; + } + + // S10: unknown session (or a session whose workspace is gone) 404; any + // non-owner — member, stranger, or guest — 403. + async inviteToSession( + actor: UserId, + sessionId: SessionId, + inviteeId: UserId, + ): Promise { + const session = await this.sessions.find(sessionId); + if (!session) return { kind: 'not-found' }; + const ws = await this.workspaces.find(session.workspaceId); + if (!ws) return { kind: 'not-found' }; + if (!ws.isOwner(actor)) return { kind: 'forbidden' }; + // Unknown users cannot be invited: the invitation row holds a required FK + // to User, so the check runs up front (after the owner check, so strangers + // still get 403 without learning whether the user id exists). + if (!(await this.users.findById(inviteeId))) return { kind: 'not-found' }; + let invitation: Invitation; + try { + invitation = session.inviteGuest(ws, actor, inviteeId); + } catch (error) { + // Only AlreadyHasAccess is reachable (ownership was pre-checked). + return { kind: this.inviteViolation(error) }; + } + // Created invitations never expire. + await this.invitations.save(invitation, null); + const inviter = await this.users.findById(actor); + if (!inviter) throw new Error('authenticated user vanished'); // unreachable + return { + kind: 'created', + view: { + id: invitation.id, + target: { kind: 'session', sessionId: session.id, name: session.name }, + invitedBy: { userId: inviter.id, username: inviter.username, displayName: inviter.displayName }, + }, + }; + } + + // S11: the caller's pending, non-expired invitations, oldest first. + async list(actor: UserId): Promise { + const pending = await this.invitations.listPendingFor(actor); + const inviterIds = [...new Set(pending.map((s) => s.invitation.invitedBy))]; + const inviters = new Map((await this.users.findByIds(inviterIds)).map((u) => [u.id, u] as const)); + const views: InvitationView[] = []; + for (const stored of pending) { + const inviter = inviters.get(stored.invitation.invitedBy); + if (!inviter) continue; // inviter deleted: nothing to attribute the entry to + const { target } = stored.invitation; + if (target.kind === 'workspace') { + // A target that no longer loads is skipped, never listed as an orphan: + // the entry would name something the caller can no longer accept. + const ws = await this.workspaces.find(target.workspaceId); + if (!ws) continue; + views.push({ + id: stored.invitation.id, + target: { kind: 'workspace', workspaceId: ws.id, name: ws.name }, + invitedBy: { userId: inviter.id, username: inviter.username, displayName: inviter.displayName }, + }); + } else { + const session = await this.sessions.find(target.sessionId); + if (!session) continue; + views.push({ + id: stored.invitation.id, + target: { kind: 'session', sessionId: session.id, name: session.name }, + invitedBy: { userId: inviter.id, username: inviter.username, displayName: inviter.displayName }, + }); + } + } + return views; + } + + // S12: applies the domain accept, persists the aggregate, then marks the + // invitation accepted — in that order, so a failed accept never leaves a + // half-applied aggregate plus an accepted invitation (S15). + async accept(actor: UserId, id: string): Promise { + const loaded = await this.loadForResponse(id, actor); + if (loaded.kind !== 'ok') return loaded; + const { invitation } = loaded.stored; + if (invitation.target.kind === 'workspace') { + const ws = await this.workspaces.find(invitation.target.workspaceId); + if (!ws) return { kind: 'not-found' }; + try { + ws.acceptInvitation(invitation); + } catch (error) { + // The aggregate is untouched and the invitation stays pending. + return { kind: this.respondViolation(error) }; + } + // The aggregate save is already one batch transaction; only once it is + // fully applied may the invitation be marked accepted — never the + // reverse, so a crash between the two cannot accept without applying. + await this.workspaces.save(ws); + try { + await this.invitations.setStatus(invitation.id, 'accepted'); + } catch { + // Count 0 after our pending check means a raced response slipped in. + return { kind: 'conflict' }; + } + return { kind: 'ok' }; + } + const session = await this.sessions.find(invitation.target.sessionId); + if (!session) return { kind: 'not-found' }; + const ws = await this.workspaces.find(session.workspaceId); + if (!ws) return { kind: 'not-found' }; + try { + session.acceptInvitation(ws, invitation); + } catch (error) { + // The aggregate is untouched and the invitation stays pending. + return { kind: this.respondViolation(error) }; + } + await this.sessions.save(session); + try { + await this.invitations.setStatus(invitation.id, 'accepted'); + } catch { + // Count 0 after our pending check means a raced response slipped in. + return { kind: 'conflict' }; + } + return { kind: 'ok' }; + } + + // S13: declining only flips the invitation row; it never touches aggregates. + async decline(actor: UserId, id: string): Promise { + const loaded = await this.loadForResponse(id, actor); + if (loaded.kind !== 'ok') return loaded; + try { + await this.invitations.setStatus(loaded.stored.invitation.id, 'declined'); + } catch { + // Count 0 after our pending check means a raced response slipped in. + return { kind: 'conflict' }; + } + return { kind: 'ok' }; + } + + // Shared S12/S13 gate, strictly ordered: (1) unknown or malformed id 404 — + // malformed is pre-checked because Postgres uuid columns throw on it; + // (2) caller is not the invitee 403, before any status signal (no leak); + // (3) expired or no longer pending 409. + private async loadForResponse(id: string, actor: UserId): Promise { + if (!isUuid(id)) return { kind: 'not-found' }; + const stored = await this.invitations.find(id as InvitationId); + if (!stored) return { kind: 'not-found' }; + if (stored.invitation.invitee !== actor) return { kind: 'forbidden' }; + if (stored.status !== 'pending' || (stored.expiresAt !== null && stored.expiresAt <= new Date())) { + return { kind: 'conflict' }; + } + return { kind: 'ok', stored }; + } + + // Invites only ever raise AlreadyHasAccess past the ownership pre-check; + // anything else is an invariant break and must surface, not map. + private inviteViolation(error: unknown): 'forbidden' | 'conflict' { + const violation = domainViolation(error); + if (violation === 'forbidden' || violation === 'conflict') return violation; + throw error; + } + + // Accepts only ever raise AlreadyHasAccess (invitee already has the role), + // InvitationTargetMismatch, or NotOwner (inviter lost ownership); anything + // else is an invariant break and must surface, not map. + private respondViolation(error: unknown): 'forbidden' | 'conflict' { + const violation = domainViolation(error); + if (violation === 'forbidden' || violation === 'conflict') return violation; + throw error; + } +} diff --git a/apps/api/src/collab/session.service.ts b/apps/api/src/collab/session.service.ts new file mode 100644 index 0000000..c9868a6 --- /dev/null +++ b/apps/api/src/collab/session.service.ts @@ -0,0 +1,139 @@ +import { Inject, Injectable } from '@nestjs/common'; + +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, 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). +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' }; + +// 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( + @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) }; + } + + // 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/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/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/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..eff6a73 --- /dev/null +++ b/apps/api/src/collab/views.ts @@ -0,0 +1,87 @@ +import type { UserRecord } from '../persistence/user.repository'; +import type { Session, SessionId, Terminal, TerminalId, 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 }; +} + +export interface TerminalView { + id: TerminalId; + name: string; + command: string; + args: string[]; + cwd: string | null; +} + +export interface SessionView { + id: SessionId; + name: string; + terminals: TerminalView[]; +} + +// `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(toTerminalView), + }; +} + +// `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 }; +} + +export type InvitationTargetView = + | { kind: 'workspace'; workspaceId: WorkspaceId; name: string } + | { kind: 'session'; sessionId: SessionId; name: string }; + +// S9-S11: what an invitation looks like over the wire. Lifecycle fields +// (status, expiresAt) are deliberately absent: they are server bookkeeping, +// and S12/S13 signal them through status codes instead. +export interface InvitationView { + id: string; + target: InvitationTargetView; + invitedBy: { userId: UserId; username: string; displayName: string }; +} 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/persistence.module.ts b/apps/api/src/persistence/persistence.module.ts index b9e2373..f4e0d90 100644 --- a/apps/api/src/persistence/persistence.module.ts +++ b/apps/api/src/persistence/persistence.module.ts @@ -3,6 +3,7 @@ import { Inject, Module, type OnApplicationShutdown } from '@nestjs/common'; import type { PrismaClient } from '../generated/prisma/client'; import { AuthRepository } from './auth.repository'; import { createPrismaClient } from './prisma'; +import { InvitationRepository } from './invitation.repository'; import { SessionRepository } from './session.repository'; import { UserRepository } from './user.repository'; import { WorkspaceRepository } from './workspace.repository'; @@ -22,9 +23,10 @@ export const PRISMA = Symbol('PRISMA'); { provide: UserRepository, useFactory: (p: PrismaClient) => new UserRepository(p), inject: [PRISMA] }, { provide: AuthRepository, useFactory: (p: PrismaClient) => new AuthRepository(p), inject: [PRISMA] }, { provide: SessionRepository, useFactory: (p: PrismaClient) => new SessionRepository(p), inject: [PRISMA] }, + { provide: InvitationRepository, useFactory: (p: PrismaClient) => new InvitationRepository(p), inject: [PRISMA] }, { provide: WorkspaceRepository, useFactory: (p: PrismaClient) => new WorkspaceRepository(p), inject: [PRISMA] }, ], - exports: [PRISMA, UserRepository, AuthRepository, SessionRepository, WorkspaceRepository], + exports: [PRISMA, UserRepository, AuthRepository, SessionRepository, InvitationRepository, WorkspaceRepository], }) export class PersistenceModule implements OnApplicationShutdown { constructor(@Inject(PRISMA) private readonly prisma: PrismaClient) {} 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..5289bf2 --- /dev/null +++ b/odd/tasks/api-rest-crud.md @@ -0,0 +1,51 @@ +# 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 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 + +- 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). 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 — 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 3d2ae33). Review assess: medium, under_budget (pending in slice) +- T4 (S9-S13, S15): InvitationsController + accept/decline orchestration service; int tests RED→GREEN. route: delegated (writer, context backstop) — DONE (24 int tests, unit 166, int 148, typecheck 0, commit b70b272; ghost-invitee → 404 per L10). Review assess: medium, under_budget (pending in slice). Independent verify: not required — assess tier medium (no named high-risk item; writer self-verification + parent spot-check stand) +- T5 (S1-S15): AppModule wiring, full unit + integration suite green, typecheck + build. route: inline — DONE (RED 4/5 → GREEN 5/5 wiring spec; unit 166, int 153, typecheck 0, build 0; commit 44068f1). Review assess: medium (executable_change app.module.ts), under_budget over 2e3e113..HEAD — stays pending in slice, no review due + +## 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. +- 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. +- L10 (2026-10-15, T4 done + user decision): Invitations endpoints implemented by delegated writer (5 routes, 24 int tests): POST `workspaces/:id/invitations`, POST `sessions/:id/invitations`, GET `invitations`, POST `invitations/:id/accept`, POST `invitations/:id/decline`; `InvitationRepository` registered+exported in PersistenceModule (A3); `domain-errors.ts` S15 mapping; accept order = aggregate save → `setStatus('accepted')` LAST so a failed accept provably leaves the row pending (test: seeded-member accept → 409 + row still PENDING). USER DECISION (supersedes the parent's draft decision 5 "ghost → 201"): the schema enforces FK `Invitation.inviteeId/invitedById → User` (schema.prisma FKs, empirically P2003/23503 on ghost insert → 500), so ghost invitees (well-formed UUID, nonexistent user) are rejected with 404 via a `UserRepository.findById` precheck placed AFTER the owner check (no user-enumeration leak to unauthorized callers), and no invitation row is stored (asserted). Malformed (non-UUID) invitation `:id` params → 404 before Prisma (Postgres uuid columns throw → would be 500; closes R3-001-class for invitations). Invitation expiry at create: `expiresAt = null` (never expires). Evidence: RED 22/24 failed → GREEN 24/24; unit 166/166; integration 148/148; typecheck 0; parent spot-check re-ran focused suite (24/24, exit 0); gitleaks clean; commit b70b272 (954 lines). +- L11 (2026-10-15, T5 done): AppModule now imports CollabModule (production module graph exposes the collab REST surface; main.ts unchanged). New `src/app.routes.int.spec.ts` boots the REAL AppModule (overrides PRISMA/AUTH_CONFIG/OAUTH_PROVIDERS/CLOCK, WsAdapter like main.ts, `listen(0)`) and pins S14 wiring per controller: unauthenticated hits on `/workspaces`, nested sessions, terminals and invitations routes → 401, and `/health` stays 200. Evidence: RED 4/5 (404 — routes absent from AppModule) → focused GREEN 5/5; unit 166/166; integration 153/153; typecheck exit 0; build exit 0. Independent verify on T4 corrected: assess tier medium → no separate verifier per the verification gate (writer self-verification + parent spot-check stand). Commit 44068f1. +- L12 (2026-10-15, feature closure): All tasks T1–T5 DONE. Final assess of the accumulated range 2e3e113..44068f1 (16 paths, 1828 changed lines): risk medium (reason `executable_change` apps/api/src/app.module.ts), review_due false, reason under_budget — T2..T5 remain pending-in-slice, no native review required; untracked `.gga` excluded via explicit inventory declaration (not part of this change). Advisories R3-001/R3-002 (L6) remain open follow-ups, not authorized scope. Delivery per L8: PR chain feature/api-rest-crud → develop (PR1=T1 2e3e113, PR2=T2+T3 b51d335..3d2ae33, PR3=T4+T5 b70b272..44068f1); push/PR creation remain human decisions. Next feature (separate branch, per L3/L4): desktop dual storage mode (local appdata vs cloud API). +- L13 (2026-10-15, delivery, user: "Dale crealo"): PR chain created (feature-branch-chain, per L8): #13 workspaces (T1, 463 lines, base develop) ← #14 sessions+terminals (T2+T3, 789, base -01-workspaces) ← #15 invitations+wiring (T4+T5, 1048, base -02-sessions-terminals); #16 tracker PR DRAFT (feature/api-rest-crud → develop, 2272 lines, merges the whole feature last). Slice branches at 2e3e113 and 3d2ae33 pushed alongside feature/api-rest-crud; diffs verified clean per slice (no polluted diffs). Review order #13→#14→#15; nothing lands on develop until the tracker merges. `size:exception` disclosed in each PR body (#13 single reviewed unit; #14/#15 user-decided slices per L8). Note: git pushes hung on GCM credential prompts; fixed with `gh auth setup-git` (gh as credential helper for github.com). CI runs on all pushed branches.