Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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: [
{
Expand Down
82 changes: 82 additions & 0 deletions apps/api/src/app.routes.int.spec.ts
Original file line number Diff line number Diff line change
@@ -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<number> {
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);
});
});
2 changes: 1 addition & 1 deletion apps/api/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,6 @@ function buildProviders(config: AuthConfig): OAuthProviders {
OAuthService,
AccessGuard,
],
exports: [SessionService, SessionRevocations],
exports: [SessionService, SessionRevocations, AuthService, AccessGuard],
})
export class AuthModule {}
19 changes: 19 additions & 0 deletions apps/api/src/collab/collab.module.ts
Original file line number Diff line number Diff line change
@@ -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 {}
26 changes: 26 additions & 0 deletions apps/api/src/collab/domain-errors.ts
Original file line number Diff line number Diff line change
@@ -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;
}
46 changes: 46 additions & 0 deletions apps/api/src/collab/dto.ts
Original file line number Diff line number Diff line change
@@ -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<typeof createWorkspaceSchema>;

// 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<typeof createSessionSchema>;

// 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<typeof addTerminalSchema>;

// 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<typeof inviteSchema>;

// 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);
}
Loading
Loading