chore: consolidate new foundation and archive v1 (#1495)
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import type { Brain } from '@mosaicstack/brain';
|
||||
import { BRAIN } from '../brain/brain.tokens.js';
|
||||
import { PluginService } from '../plugin/plugin.service.js';
|
||||
import { WorkspaceService } from './workspace.service.js';
|
||||
|
||||
export interface BootstrapProjectParams {
|
||||
name: string;
|
||||
description?: string;
|
||||
userId: string;
|
||||
teamId?: string;
|
||||
repoUrl?: string;
|
||||
}
|
||||
|
||||
export interface BootstrapProjectResult {
|
||||
projectId: string;
|
||||
workspacePath: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ProjectBootstrapService {
|
||||
private readonly logger = new Logger(ProjectBootstrapService.name);
|
||||
|
||||
constructor(
|
||||
@Inject(BRAIN) private readonly brain: Brain,
|
||||
private readonly workspace: WorkspaceService,
|
||||
private readonly pluginService: PluginService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Bootstrap a new project: create DB record + workspace directory.
|
||||
* Returns the created project with its workspace path.
|
||||
*/
|
||||
async bootstrap(params: BootstrapProjectParams): Promise<BootstrapProjectResult> {
|
||||
const ownerType: 'user' | 'team' = params.teamId ? 'team' : 'user';
|
||||
|
||||
this.logger.log(
|
||||
`Bootstrapping project "${params.name}" for ${ownerType} ${params.teamId ?? params.userId}`,
|
||||
);
|
||||
|
||||
// 1. Create DB record
|
||||
const project = await this.brain.projects.create({
|
||||
name: params.name,
|
||||
description: params.description,
|
||||
ownerId: params.userId,
|
||||
teamId: params.teamId ?? null,
|
||||
ownerType,
|
||||
});
|
||||
|
||||
// 2. Create workspace directory (includes docs structure)
|
||||
const workspacePath = await this.workspace.create(
|
||||
{
|
||||
id: project.id,
|
||||
ownerType,
|
||||
userId: params.userId,
|
||||
teamId: params.teamId ?? null,
|
||||
},
|
||||
params.repoUrl,
|
||||
);
|
||||
|
||||
// 3. Create default agent config for the project
|
||||
await this.brain.agents.create({
|
||||
name: 'default',
|
||||
provider: '',
|
||||
model: '',
|
||||
projectId: project.id,
|
||||
ownerId: params.userId,
|
||||
isSystem: false,
|
||||
status: 'active',
|
||||
});
|
||||
|
||||
// 4. Notify plugins so they can set up project-specific resources (e.g. Discord channel)
|
||||
try {
|
||||
for (const plugin of this.pluginService.getPlugins()) {
|
||||
if (plugin.onProjectCreated) {
|
||||
const result = await plugin.onProjectCreated({
|
||||
id: project.id,
|
||||
name: params.name,
|
||||
description: params.description,
|
||||
});
|
||||
if (result?.channelId) {
|
||||
await this.brain.projects.update(project.id, {
|
||||
metadata: { discordChannelId: result.channelId },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Plugin project notification failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.logger.log(`Project ${project.id} bootstrapped at ${workspacePath}`);
|
||||
|
||||
return { projectId: project.id, workspacePath };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'reflect-metadata';
|
||||
import { type CanActivate, type ExecutionContext, type INestApplication } from '@nestjs/common';
|
||||
import { FastifyAdapter, type NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { TeamsController } from './teams.controller.js';
|
||||
import { TeamsService } from './teams.service.js';
|
||||
|
||||
const teamAlpha = { id: 'team-alpha', name: 'Alpha' };
|
||||
const teamBeta = { id: 'team-beta', name: 'Beta' };
|
||||
|
||||
// user-1 is a member of team-alpha only; admin-1 has role admin.
|
||||
let currentUser: { id: string; role?: string } = { id: 'user-1' };
|
||||
|
||||
const teamsServiceMock = {
|
||||
findAll: vi.fn(() => Promise.resolve([teamAlpha, teamBeta])),
|
||||
findAllForUser: vi.fn((userId: string) =>
|
||||
Promise.resolve(userId === 'user-1' ? [teamAlpha] : []),
|
||||
),
|
||||
findById: vi.fn((id: string) => Promise.resolve([teamAlpha, teamBeta].find((t) => t.id === id))),
|
||||
listMembers: vi.fn(() => Promise.resolve([{ teamId: 'team-alpha', userId: 'user-1' }])),
|
||||
isMember: vi.fn((teamId: string, userId: string) =>
|
||||
Promise.resolve(teamId === 'team-alpha' && userId === 'user-1'),
|
||||
),
|
||||
};
|
||||
|
||||
const authGuard: CanActivate = {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requestContext = context
|
||||
.switchToHttp()
|
||||
.getRequest<{ user?: { id: string; role?: string } }>();
|
||||
requestContext.user = currentUser;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
describe('teams endpoints are scoped to membership', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
controllers: [TeamsController],
|
||||
providers: [{ provide: TeamsService, useValue: teamsServiceMock }],
|
||||
})
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue(authGuard)
|
||||
.compile();
|
||||
|
||||
app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter());
|
||||
await app.init();
|
||||
await app.getHttpAdapter().getInstance().ready();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
currentUser = { id: 'user-1' };
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('GET /api/teams returns only the teams the user belongs to', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/teams');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual([teamAlpha]);
|
||||
expect(teamsServiceMock.findAll).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('GET /api/teams returns every team for an admin', async () => {
|
||||
currentUser = { id: 'admin-1', role: 'admin' };
|
||||
const response = await request(app.getHttpServer()).get('/api/teams');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual([teamAlpha, teamBeta]);
|
||||
expect(teamsServiceMock.findAllForUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('GET /api/teams/:teamId returns 403 for a non-member', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/teams/team-beta');
|
||||
expect(response.status).toBe(403);
|
||||
});
|
||||
|
||||
it('GET /api/teams/:teamId returns 404 for a missing team', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/teams/team-missing');
|
||||
expect(response.status).toBe(404);
|
||||
});
|
||||
|
||||
it('GET /api/teams/:teamId returns the team for a member', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/teams/team-alpha');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual(teamAlpha);
|
||||
});
|
||||
|
||||
it('GET /api/teams/:teamId/members returns 403 for a non-member and members for a member', async () => {
|
||||
const denied = await request(app.getHttpServer()).get('/api/teams/team-beta/members');
|
||||
expect(denied.status).toBe(403);
|
||||
expect(teamsServiceMock.listMembers).not.toHaveBeenCalled();
|
||||
|
||||
const allowed = await request(app.getHttpServer()).get('/api/teams/team-alpha/members');
|
||||
expect(allowed.status).toBe(200);
|
||||
expect(allowed.body).toEqual([{ teamId: 'team-alpha', userId: 'user-1' }]);
|
||||
});
|
||||
|
||||
it('GET /api/teams/:teamId/members/:userId allows a self-lookup on any team', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/teams/team-beta/members/user-1');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ isMember: false });
|
||||
});
|
||||
|
||||
it('GET /api/teams/:teamId/members/:userId denies looking up another user on a foreign team', async () => {
|
||||
const response = await request(app.getHttpServer()).get('/api/teams/team-beta/members/user-2');
|
||||
expect(response.status).toBe(403);
|
||||
});
|
||||
|
||||
it('an admin can look up any membership', async () => {
|
||||
currentUser = { id: 'admin-1', role: 'admin' };
|
||||
const response = await request(app.getHttpServer()).get('/api/teams/team-alpha/members/user-1');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({ isMember: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import {
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
NotFoundException,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import { TeamsService } from './teams.service.js';
|
||||
|
||||
type RequestUser = { id: string; role?: string };
|
||||
|
||||
@Controller('api/teams')
|
||||
@UseGuards(AuthGuard)
|
||||
export class TeamsController {
|
||||
constructor(private readonly teams: TeamsService) {}
|
||||
|
||||
@Get()
|
||||
async list(@CurrentUser() user: RequestUser) {
|
||||
if (user.role === 'admin') {
|
||||
return this.teams.findAll();
|
||||
}
|
||||
return this.teams.findAllForUser(user.id);
|
||||
}
|
||||
|
||||
@Get(':teamId')
|
||||
async findOne(@Param('teamId') teamId: string, @CurrentUser() user: RequestUser) {
|
||||
return this.getAccessibleTeam(teamId, user);
|
||||
}
|
||||
|
||||
@Get(':teamId/members')
|
||||
async listMembers(@Param('teamId') teamId: string, @CurrentUser() user: RequestUser) {
|
||||
await this.getAccessibleTeam(teamId, user);
|
||||
return this.teams.listMembers(teamId);
|
||||
}
|
||||
|
||||
@Get(':teamId/members/:userId')
|
||||
async checkMembership(
|
||||
@Param('teamId') teamId: string,
|
||||
@Param('userId') userId: string,
|
||||
@CurrentUser() user: RequestUser,
|
||||
) {
|
||||
// A user may always ask about their own membership; anything else is
|
||||
// team-scoped like the other routes.
|
||||
if (userId !== user.id) {
|
||||
await this.getAccessibleTeam(teamId, user);
|
||||
}
|
||||
const isMember = await this.teams.isMember(teamId, userId);
|
||||
return { isMember };
|
||||
}
|
||||
|
||||
/**
|
||||
* Team-scoped access: admins see any team; everyone else only teams they
|
||||
* are a member of. NotFoundException when the team does not exist and
|
||||
* ForbiddenException when the user lacks access (same convention as the
|
||||
* projects controller).
|
||||
*/
|
||||
private async getAccessibleTeam(teamId: string, user: RequestUser) {
|
||||
const team = await this.teams.findById(teamId);
|
||||
if (!team) throw new NotFoundException('Team not found');
|
||||
if (user.role === 'admin') return team;
|
||||
const isMember = await this.teams.isMember(teamId, user.id);
|
||||
if (!isMember) throw new ForbiddenException('Not a member of this team');
|
||||
return team;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import { eq, and, inArray, type Db, teams, teamMembers, projects } from '@mosaicstack/db';
|
||||
import { DB } from '../database/database.module.js';
|
||||
|
||||
@Injectable()
|
||||
export class TeamsService {
|
||||
private readonly logger = new Logger(TeamsService.name);
|
||||
|
||||
constructor(@Inject(DB) private readonly db: Db) {}
|
||||
|
||||
/**
|
||||
* Check if a user is a member of a team.
|
||||
*/
|
||||
async isMember(teamId: string, userId: string): Promise<boolean> {
|
||||
const rows = await this.db
|
||||
.select({ id: teamMembers.id })
|
||||
.from(teamMembers)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)));
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check project access for a user.
|
||||
* - ownerType === 'user': project.ownerId must equal userId
|
||||
* - ownerType === 'team': userId must be a member of project.teamId
|
||||
*/
|
||||
async canAccessProject(userId: string, projectId: string): Promise<boolean> {
|
||||
const rows = await this.db
|
||||
.select({
|
||||
id: projects.id,
|
||||
ownerType: projects.ownerType,
|
||||
ownerId: projects.ownerId,
|
||||
teamId: projects.teamId,
|
||||
})
|
||||
.from(projects)
|
||||
.where(eq(projects.id, projectId));
|
||||
|
||||
const project = rows[0];
|
||||
if (!project) return false;
|
||||
|
||||
if (project.ownerType === 'user') {
|
||||
return project.ownerId === userId;
|
||||
}
|
||||
|
||||
if (project.ownerType === 'team' && project.teamId) {
|
||||
return this.isMember(project.teamId, userId);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all teams (for admin/listing endpoints).
|
||||
*/
|
||||
async findAll() {
|
||||
return this.db.select().from(teams);
|
||||
}
|
||||
|
||||
/**
|
||||
* List only the teams the user is a member of.
|
||||
*/
|
||||
async findAllForUser(userId: string) {
|
||||
const memberRows = await this.db
|
||||
.select({ teamId: teamMembers.teamId })
|
||||
.from(teamMembers)
|
||||
.where(eq(teamMembers.userId, userId));
|
||||
|
||||
const teamIds = memberRows.map((r) => r.teamId);
|
||||
if (teamIds.length === 0) return [];
|
||||
|
||||
return this.db.select().from(teams).where(inArray(teams.id, teamIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a team by ID.
|
||||
*/
|
||||
async findById(id: string) {
|
||||
const rows = await this.db.select().from(teams).where(eq(teams.id, id));
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* List members of a team.
|
||||
*/
|
||||
async listMembers(teamId: string) {
|
||||
return this.db.select().from(teamMembers).where(eq(teamMembers.teamId, teamId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import 'reflect-metadata';
|
||||
import {
|
||||
type CanActivate,
|
||||
type ExecutionContext,
|
||||
type INestApplication,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyAdapter, type NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { ProjectBootstrapService } from './project-bootstrap.service.js';
|
||||
import { WorkspaceController } from './workspace.controller.js';
|
||||
|
||||
const bootstrapMock = vi.fn(() =>
|
||||
Promise.resolve({
|
||||
projectId: 'project-1',
|
||||
workspacePath: '/opt/mosaic/.workspaces/users/user-1/project-1',
|
||||
}),
|
||||
);
|
||||
|
||||
const authGuard: CanActivate = {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requestContext = context.switchToHttp().getRequest<{ user?: { id: string } }>();
|
||||
requestContext.user = { id: 'user-1' };
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
describe('POST /api/workspaces repoUrl validation', () => {
|
||||
let app: INestApplication;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
controllers: [WorkspaceController],
|
||||
providers: [
|
||||
{
|
||||
provide: ProjectBootstrapService,
|
||||
useValue: { bootstrap: bootstrapMock },
|
||||
},
|
||||
],
|
||||
})
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue(authGuard)
|
||||
.compile();
|
||||
|
||||
app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter());
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
await app.init();
|
||||
await app.getHttpAdapter().getInstance().ready();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
bootstrapMock.mockClear();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a leading-dash value', '--upload-pack=sh -c id'],
|
||||
['an ext remote helper', 'ext::sh -c id'],
|
||||
['a file URL', 'file:///tmp/repository'],
|
||||
['an unparseable value', 'not a url'],
|
||||
['an SSH shorthand', '[email protected]:acme/repository.git'],
|
||||
['a scheme without //', 'https:example.com/acme/repository.git'],
|
||||
['a hostless git URL', 'git:///tmp/repository'],
|
||||
])('returns 400 for %s', async (_description, repoUrl) => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/api/workspaces')
|
||||
.send({ name: 'Example', repoUrl })
|
||||
.set('Content-Type', 'application/json');
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(bootstrapMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a plain HTTPS repository URL', 'https://example.com/acme/repository.git'],
|
||||
['a git protocol repository URL', 'git://example.com/acme/repository.git'],
|
||||
])('accepts %s', async (_description, repoUrl) => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/api/workspaces')
|
||||
.send({ name: 'Example', repoUrl })
|
||||
.set('Content-Type', 'application/json');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(bootstrapMock).toHaveBeenCalledWith({
|
||||
name: 'Example',
|
||||
description: undefined,
|
||||
userId: 'user-1',
|
||||
teamId: undefined,
|
||||
repoUrl,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Body, Controller, Post, UseGuards } from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard.js';
|
||||
import { CurrentUser } from '../auth/current-user.decorator.js';
|
||||
import {
|
||||
ProjectBootstrapService,
|
||||
type BootstrapProjectResult,
|
||||
} from './project-bootstrap.service.js';
|
||||
import { CreateWorkspaceDto } from './workspace.dto.js';
|
||||
|
||||
@Controller('api/workspaces')
|
||||
@UseGuards(AuthGuard)
|
||||
export class WorkspaceController {
|
||||
constructor(private readonly bootstrap: ProjectBootstrapService) {}
|
||||
|
||||
@Post()
|
||||
async create(
|
||||
@CurrentUser() user: { id: string },
|
||||
@Body() dto: CreateWorkspaceDto,
|
||||
): Promise<BootstrapProjectResult> {
|
||||
return this.bootstrap.bootstrap({
|
||||
name: dto.name,
|
||||
description: dto.description,
|
||||
userId: user.id,
|
||||
teamId: dto.teamId,
|
||||
repoUrl: dto.repoUrl,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { IsOptional, IsString, IsUrl, Matches, MaxLength } from 'class-validator';
|
||||
|
||||
export class CreateWorkspaceDto {
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
name!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(10_000)
|
||||
description?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
teamId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(/^(?:https|git):\/\//i, {
|
||||
message: 'repoUrl must be a valid https:// or git:// URL',
|
||||
})
|
||||
@IsUrl(
|
||||
{
|
||||
protocols: ['https', 'git'],
|
||||
require_host: true,
|
||||
require_protocol: true,
|
||||
require_tld: false,
|
||||
require_valid_protocol: true,
|
||||
},
|
||||
{ message: 'repoUrl must be a valid https:// or git:// URL' },
|
||||
)
|
||||
repoUrl?: string;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { WorkspaceService } from './workspace.service.js';
|
||||
import { ProjectBootstrapService } from './project-bootstrap.service.js';
|
||||
import { TeamsService } from './teams.service.js';
|
||||
import { WorkspaceController } from './workspace.controller.js';
|
||||
import { TeamsController } from './teams.controller.js';
|
||||
|
||||
@Module({
|
||||
controllers: [WorkspaceController, TeamsController],
|
||||
providers: [WorkspaceService, ProjectBootstrapService, TeamsService],
|
||||
exports: [WorkspaceService, ProjectBootstrapService, TeamsService],
|
||||
})
|
||||
export class WorkspaceModule {}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { WorkspaceService } from './workspace.service.js';
|
||||
|
||||
type ExecFileMock = (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: { cwd: string },
|
||||
callback: (error: Error | null, stdout: string, stderr: string) => void,
|
||||
) => void;
|
||||
|
||||
const { execFileMock } = vi.hoisted(() => ({
|
||||
execFileMock: vi.fn<ExecFileMock>(),
|
||||
}));
|
||||
|
||||
vi.mock('node:child_process', () => ({
|
||||
execFile: execFileMock,
|
||||
}));
|
||||
|
||||
describe('WorkspaceService', () => {
|
||||
let service: WorkspaceService;
|
||||
|
||||
beforeEach(() => {
|
||||
execFileMock.mockReset();
|
||||
execFileMock.mockImplementation((_command, _args, _options, callback) => {
|
||||
callback(null, '', '');
|
||||
});
|
||||
service = new WorkspaceService();
|
||||
});
|
||||
|
||||
describe('resolvePath', () => {
|
||||
it('resolves user workspace path', () => {
|
||||
const result = service.resolvePath({
|
||||
id: 'proj1',
|
||||
ownerType: 'user',
|
||||
userId: 'user1',
|
||||
teamId: null,
|
||||
});
|
||||
expect(result).toContain(path.join('users', 'user1', 'proj1'));
|
||||
});
|
||||
|
||||
it('resolves team workspace path', () => {
|
||||
const result = service.resolvePath({
|
||||
id: 'proj1',
|
||||
ownerType: 'team',
|
||||
userId: 'user1',
|
||||
teamId: 'team1',
|
||||
});
|
||||
expect(result).toContain(path.join('teams', 'team1', 'proj1'));
|
||||
});
|
||||
|
||||
it('falls back to user path when ownerType is team but teamId is null', () => {
|
||||
const result = service.resolvePath({
|
||||
id: 'proj1',
|
||||
ownerType: 'team',
|
||||
userId: 'user1',
|
||||
teamId: null,
|
||||
});
|
||||
expect(result).toContain(path.join('users', 'user1', 'proj1'));
|
||||
});
|
||||
|
||||
it('uses MOSAIC_ROOT env var as the base path', () => {
|
||||
const originalRoot = process.env['MOSAIC_ROOT'];
|
||||
process.env['MOSAIC_ROOT'] = '/custom/root';
|
||||
const customService = new WorkspaceService();
|
||||
const result = customService.resolvePath({
|
||||
id: 'proj1',
|
||||
ownerType: 'user',
|
||||
userId: 'user1',
|
||||
teamId: null,
|
||||
});
|
||||
expect(result).toMatch(/^\/custom\/root/);
|
||||
// Restore
|
||||
if (originalRoot === undefined) {
|
||||
delete process.env['MOSAIC_ROOT'];
|
||||
} else {
|
||||
process.env['MOSAIC_ROOT'] = originalRoot;
|
||||
}
|
||||
});
|
||||
|
||||
it('defaults to /opt/mosaic when MOSAIC_ROOT is unset', () => {
|
||||
const originalRoot = process.env['MOSAIC_ROOT'];
|
||||
delete process.env['MOSAIC_ROOT'];
|
||||
const defaultService = new WorkspaceService();
|
||||
const result = defaultService.resolvePath({
|
||||
id: 'proj2',
|
||||
ownerType: 'user',
|
||||
userId: 'user2',
|
||||
teamId: null,
|
||||
});
|
||||
expect(result).toMatch(/^\/opt\/mosaic/);
|
||||
// Restore
|
||||
if (originalRoot !== undefined) {
|
||||
process.env['MOSAIC_ROOT'] = originalRoot;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
const project = {
|
||||
id: 'project-1',
|
||||
ownerType: 'user',
|
||||
userId: 'user-1',
|
||||
teamId: null,
|
||||
} as const;
|
||||
|
||||
let originalRoot: string | undefined;
|
||||
let temporaryRoot: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
originalRoot = process.env['MOSAIC_ROOT'];
|
||||
temporaryRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'mosaic-workspace-'));
|
||||
process.env['MOSAIC_ROOT'] = temporaryRoot;
|
||||
service = new WorkspaceService();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (originalRoot === undefined) {
|
||||
delete process.env['MOSAIC_ROOT'];
|
||||
} else {
|
||||
process.env['MOSAIC_ROOT'] = originalRoot;
|
||||
}
|
||||
await fs.rm(temporaryRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a leading-dash URL', '--upload-pack=sh -c id'],
|
||||
['an ext remote helper', 'ext::sh -c id'],
|
||||
['a file URL', 'file:///tmp/repository'],
|
||||
['an unparseable value', 'not a url'],
|
||||
['an SSH shorthand', '[email protected]:acme/repository.git'],
|
||||
['a scheme without //', 'https:example.com/acme/repository.git'],
|
||||
['a hostless git URL', 'git:///tmp/repository'],
|
||||
])('rejects %s before invoking git', async (_description, repoUrl) => {
|
||||
await expect(service.create(project, repoUrl)).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(execFileMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an HTTPS URL', 'https://example.com/acme/repository.git'],
|
||||
['a git protocol URL', 'git://example.com/acme/repository.git'],
|
||||
])('accepts %s and invokes hardened git clone arguments', async (_description, repoUrl) => {
|
||||
const workspacePath = await service.create(project, repoUrl);
|
||||
|
||||
expect(execFileMock).toHaveBeenCalledOnce();
|
||||
expect(execFileMock).toHaveBeenCalledWith(
|
||||
'git',
|
||||
[
|
||||
'-c',
|
||||
'protocol.ext.allow=never',
|
||||
'-c',
|
||||
'protocol.file.allow=never',
|
||||
'clone',
|
||||
'--',
|
||||
repoUrl,
|
||||
'.',
|
||||
],
|
||||
{ cwd: workspacePath },
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const allowedRepositoryProtocols = new Set(['https:', 'git:']);
|
||||
const repositoryUrlPrefixPattern = /^(?:https|git):\/\//i;
|
||||
const repositoryUrlError = 'repoUrl must be a valid https:// or git:// URL';
|
||||
|
||||
function assertAllowedRepositoryUrl(repoUrl: string): void {
|
||||
if (repoUrl.startsWith('-') || !repositoryUrlPrefixPattern.test(repoUrl)) {
|
||||
throw new BadRequestException(repositoryUrlError);
|
||||
}
|
||||
|
||||
let parsedUrl: URL;
|
||||
try {
|
||||
parsedUrl = new URL(repoUrl);
|
||||
} catch {
|
||||
throw new BadRequestException(repositoryUrlError);
|
||||
}
|
||||
|
||||
if (!allowedRepositoryProtocols.has(parsedUrl.protocol) || parsedUrl.hostname.length === 0) {
|
||||
throw new BadRequestException(repositoryUrlError);
|
||||
}
|
||||
}
|
||||
|
||||
export interface WorkspaceProject {
|
||||
id: string;
|
||||
ownerType: 'user' | 'team';
|
||||
userId: string;
|
||||
teamId: string | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class WorkspaceService {
|
||||
private readonly logger = new Logger(WorkspaceService.name);
|
||||
private readonly mosaicRoot: string;
|
||||
|
||||
constructor() {
|
||||
this.mosaicRoot = process.env['MOSAIC_ROOT'] ?? '/opt/mosaic';
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the workspace path for a project.
|
||||
* Solo: $MOSAIC_ROOT/.workspaces/users/<userId>/<projectId>/
|
||||
* Team: $MOSAIC_ROOT/.workspaces/teams/<teamId>/<projectId>/
|
||||
*/
|
||||
resolvePath(project: WorkspaceProject): string {
|
||||
if (project.ownerType === 'team' && project.teamId) {
|
||||
return path.join(this.mosaicRoot, '.workspaces', 'teams', project.teamId, project.id);
|
||||
}
|
||||
return path.join(this.mosaicRoot, '.workspaces', 'users', project.userId, project.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a workspace directory and initialize it as a git repo.
|
||||
* If repoUrl is provided, clone instead of init.
|
||||
*/
|
||||
async create(project: WorkspaceProject, repoUrl?: string): Promise<string> {
|
||||
if (repoUrl !== undefined) {
|
||||
assertAllowedRepositoryUrl(repoUrl);
|
||||
}
|
||||
|
||||
const workspacePath = this.resolvePath(project);
|
||||
|
||||
// Create directory
|
||||
await fs.mkdir(workspacePath, { recursive: true });
|
||||
|
||||
if (repoUrl !== undefined) {
|
||||
// Clone existing repo. Defense in depth keeps dangerous local helpers
|
||||
// disabled and terminates option parsing before positional arguments.
|
||||
await execFileAsync(
|
||||
'git',
|
||||
[
|
||||
'-c',
|
||||
'protocol.ext.allow=never',
|
||||
'-c',
|
||||
'protocol.file.allow=never',
|
||||
'clone',
|
||||
'--',
|
||||
repoUrl,
|
||||
'.',
|
||||
],
|
||||
{ cwd: workspacePath },
|
||||
);
|
||||
this.logger.log(`Cloned ${repoUrl} into workspace ${workspacePath}`);
|
||||
} else {
|
||||
// Init new git repo
|
||||
await execFileAsync('git', ['init'], { cwd: workspacePath });
|
||||
await execFileAsync('git', ['commit', '--allow-empty', '-m', 'Initial workspace commit'], {
|
||||
cwd: workspacePath,
|
||||
env: {
|
||||
...process.env,
|
||||
GIT_AUTHOR_NAME: 'Mosaic',
|
||||
GIT_AUTHOR_EMAIL: 'mosaic@localhost',
|
||||
GIT_COMMITTER_NAME: 'Mosaic',
|
||||
GIT_COMMITTER_EMAIL: 'mosaic@localhost',
|
||||
},
|
||||
});
|
||||
this.logger.log(`Initialized git workspace at ${workspacePath}`);
|
||||
}
|
||||
|
||||
// Create standard docs structure
|
||||
await fs.mkdir(path.join(workspacePath, 'docs', 'plans'), { recursive: true });
|
||||
await fs.mkdir(path.join(workspacePath, 'docs', 'reports'), { recursive: true });
|
||||
this.logger.log(`Created docs structure at ${workspacePath}`);
|
||||
|
||||
return workspacePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a workspace directory recursively.
|
||||
*/
|
||||
async delete(project: WorkspaceProject): Promise<void> {
|
||||
const workspacePath = this.resolvePath(project);
|
||||
try {
|
||||
await fs.rm(workspacePath, { recursive: true, force: true });
|
||||
this.logger.log(`Deleted workspace at ${workspacePath}`);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Failed to delete workspace at ${workspacePath}: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the workspace directory exists.
|
||||
*/
|
||||
async exists(project: WorkspaceProject): Promise<boolean> {
|
||||
const workspacePath = this.resolvePath(project);
|
||||
try {
|
||||
await fs.access(workspacePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the base user workspace directory (call on user registration).
|
||||
*/
|
||||
async createUserRoot(userId: string): Promise<void> {
|
||||
const userRoot = path.join(this.mosaicRoot, '.workspaces', 'users', userId);
|
||||
await fs.mkdir(userRoot, { recursive: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the base team workspace directory (call on team creation).
|
||||
*/
|
||||
async createTeamRoot(teamId: string): Promise<void> {
|
||||
const teamRoot = path.join(this.mosaicRoot, '.workspaces', 'teams', teamId);
|
||||
await fs.mkdir(teamRoot, { recursive: true });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user