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
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 {}
14 changes: 14 additions & 0 deletions apps/api/src/collab/collab.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';

import { AuthModule } from '../auth/auth.module';
import { PersistenceModule } from '../persistence/persistence.module';
import { WorkspacesController } from './workspaces.controller';
import { WorkspaceService } from './workspace.service';

@Module({
imports: [PersistenceModule, AuthModule],
controllers: [WorkspacesController],
providers: [WorkspaceService],
exports: [WorkspaceService],
})
export class CollabModule {}
8 changes: 8 additions & 0 deletions apps/api/src/collab/dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { z } from 'zod';

// `.strict()` everywhere: unknown fields are rejected, not silently dropped.
export const createWorkspaceSchema = z
.object({ name: z.string().trim().min(1).max(100) })
.strict();

export type CreateWorkspaceBody = z.infer<typeof createWorkspaceSchema>;
60 changes: 60 additions & 0 deletions apps/api/src/collab/test-app.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
}

export async function startCollabTestApp(): Promise<CollabTestApp> {
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();
},
};
}
39 changes: 39 additions & 0 deletions apps/api/src/collab/views.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { UserRecord } from '../persistence/user.repository';
import type { UserId, Workspace, WorkspaceId } from '@opencollab/domain';

export interface WorkspaceSummary {
id: WorkspaceId;
name: string;
owner: UserId;
memberCount: number;
}

export interface MemberView {
userId: UserId;
username: string;
displayName: string;
}

export interface WorkspaceDetail {
id: WorkspaceId;
name: string;
owner: UserId;
members: MemberView[];
}

export function toWorkspaceSummary(ws: Workspace): WorkspaceSummary {
return { id: ws.id, name: ws.name, owner: ws.owner, memberCount: ws.members.length };
}

// `usersById` supplies the display fields for the member ids; ids missing from
// the map (deleted users) are dropped from the view.
export function toWorkspaceDetail(ws: Workspace, usersById: Map<UserId, UserRecord>): 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 };
}
46 changes: 46 additions & 0 deletions apps/api/src/collab/workspace.service.ts
Original file line number Diff line number Diff line change
@@ -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<WorkspaceDetail> {
const ws = new Workspace(actor, name);
await this.workspaces.save(ws);
return this.detail(ws);
}

async listFor(actor: UserId): Promise<WorkspaceSummary[]> {
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<WorkspaceLookup> {
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<WorkspaceDetail> {
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])));
}
}
153 changes: 153 additions & 0 deletions apps/api/src/collab/workspaces.controller.int.spec.ts
Original file line number Diff line number Diff line change
@@ -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<Res> {
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<WorkspaceId> {
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);
});
});
47 changes: 47 additions & 0 deletions apps/api/src/collab/workspaces.controller.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}
7 changes: 7 additions & 0 deletions apps/api/src/persistence/user.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<UserRecord[]> {
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<UserRecord | undefined> {
Expand Down
Loading
Loading