diff --git a/backend/src/routes/repo-terminal-socket.ts b/backend/src/routes/repo-terminal-socket.ts index 99059f8a..635784b2 100644 --- a/backend/src/routes/repo-terminal-socket.ts +++ b/backend/src/routes/repo-terminal-socket.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono' import type { MiddlewareHandler } from 'hono' import type { Database } from 'bun:sqlite' import type { UpgradeWebSocket } from 'hono/ws' +import { ENV } from '@opencode-manager/shared/config/env' import type { GitAuthService } from '../services/git-auth' import type { OpenCodeClient } from '../services/opencode/client' import type { TerminalService } from '../services/terminal' @@ -16,6 +17,19 @@ export interface RepoTerminalSocketVariables { const MAX_CLOSE_REASON_BYTES = 120 +const DEFAULT_TRUSTED_ORIGINS = ENV.AUTH.TRUSTED_ORIGINS.split(',') + .map((origin) => origin.trim()) + .filter(Boolean) + +function isAllowedUpgradeOrigin( + origin: string | undefined, + trustedOrigins: readonly string[], +): boolean { + if (origin === undefined) return true + if (origin === 'null') return false + return trustedOrigins.includes(origin) +} + function parseCursor(raw: string | undefined): number | undefined | null { if (raw === undefined) return undefined if (!/^-?\d+$/.test(raw)) return null @@ -36,11 +50,16 @@ export function createRepoTerminalSocketRoutes( openCodeClient: OpenCodeClient, terminalService: TerminalService, upgradeWebSocket: UpgradeWebSocket, + trustedOrigins: readonly string[] = DEFAULT_TRUSTED_ORIGINS, ) { const app = new Hono<{ Variables: RepoTerminalSocketVariables }>() const deps = { database, gitAuthService, openCodeClient } const validate: MiddlewareHandler<{ Variables: RepoTerminalSocketVariables }> = async (c, next) => { + if (!isAllowedUpgradeOrigin(c.req.header('origin'), trustedOrigins)) { + return c.json({ error: 'Origin not allowed' }, 403) + } + const cursor = parseCursor(c.req.query('cursor')) if (cursor === null) { return c.json({ error: 'Invalid cursor' }, 400) diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 84acb670..937904b3 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -94,13 +94,10 @@ export function createRepoRoutes( } if (repo.isWorktree) { - const projectRepo = await projectConfigService.resolveProjectRepo(repo) - if (projectRepo.id !== repo.id) { - return c.json({ - ...repo, - worktreeSetup: await projectConfigService.runWorktreeSetup(projectRepo, repo.fullPath, terminalService), - }) - } + return c.json({ + ...repo, + worktreeSetup: await projectConfigService.runWorktreeSetupForRepo(repo, repo.fullPath, terminalService), + }) } return c.json(repo) @@ -332,7 +329,7 @@ app.get('/', async (c) => { const worktree = await openCodeClient.api.worktree.create({ projectID }) return c.json({ ...worktree, - worktreeSetup: await projectConfigService.runWorktreeSetup(repo, worktree.directory, terminalService), + worktreeSetup: await projectConfigService.runWorktreeSetupForRepo(repo, worktree.directory, terminalService), }) } catch (error: unknown) { if (isWorktreeError(error)) { diff --git a/backend/src/services/project-config.ts b/backend/src/services/project-config.ts index fa76c5d0..61c490f5 100644 --- a/backend/src/services/project-config.ts +++ b/backend/src/services/project-config.ts @@ -265,6 +265,20 @@ export class ProjectConfigService { } } + async runWorktreeSetupForRepo( + repo: Repo, + worktreeDirectory: string, + terminalService: TerminalService, + ): Promise { + try { + const projectRepo = await this.resolveProjectRepo(repo) + return await this.runWorktreeSetup(projectRepo, worktreeDirectory, terminalService) + } catch (error: unknown) { + logger.warn(`Failed to prepare worktree setup for ${worktreeDirectory}:`, error) + return { status: 'failed', error: getErrorMessage(error) } + } + } + private isRepoFileTrusted(projectRepo: Repo, repoFile: RepoFileState): boolean { return ( repoFile.hash !== null && @@ -340,7 +354,7 @@ export class ProjectConfigService { return { repoFile: nextFile, personalActions: personal.filter((item) => item.id !== action.id), - trustHash: this.hashRepoFile(nextFile), + trustHash: this.resolveTrustAfterMove(projectRepo, state, this.hashRepoFile(nextFile)), } } @@ -356,7 +370,11 @@ export class ProjectConfigService { const nextPersonal = personal.filter((_, itemIndex) => itemIndex !== index) this.assertRepoFileValid(nextFile) this.assertPersonalSetupValid(nextPersonal) - return { repoFile: nextFile, personalSetup: nextPersonal, trustHash: this.hashRepoFile(nextFile) } + return { + repoFile: nextFile, + personalSetup: nextPersonal, + trustHash: this.resolveTrustAfterMove(projectRepo, state, this.hashRepoFile(nextFile)), + } } private planMoveToPersonal(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit { @@ -377,7 +395,11 @@ export class ProjectConfigService { }) const personalActions = [...this.getPersonalActions(projectRepo), action] return nextFile - ? { repoFile: nextFile, personalActions, trustHash: this.hashRepoFile(nextFile) } + ? { + repoFile: nextFile, + personalActions, + trustHash: this.resolveTrustAfterMove(projectRepo, state, this.hashRepoFile(nextFile)), + } : { repoFile: null, personalActions, trustHash: null } } @@ -393,10 +415,33 @@ export class ProjectConfigService { const personalSetup = [...this.getPersonalSetup(projectRepo), request.command] this.assertPersonalSetupValid(personalSetup) return nextFile - ? { repoFile: nextFile, personalSetup, trustHash: this.hashRepoFile(nextFile) } + ? { + repoFile: nextFile, + personalSetup, + trustHash: this.resolveTrustAfterMove(projectRepo, state, this.hashRepoFile(nextFile)), + } : { repoFile: null, personalSetup, trustHash: null } } + private resolveTrustAfterMove(projectRepo: Repo, state: RepoFileState, nextHash: string | null): string | null { + if (nextHash === null) { + return null + } + if (this.hasUntrustedExecutableContent(projectRepo, state)) { + return getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY) + } + return nextHash + } + + private hasUntrustedExecutableContent(projectRepo: Repo, state: RepoFileState): boolean { + if (!state.exists || !state.file) { + return false + } + const hasExecutable = + (state.file.projectActions?.length ?? 0) > 0 || (state.file.setupWorktree?.length ?? 0) > 0 + return hasExecutable && !this.isRepoFileTrusted(projectRepo, state) + } + private pruneRepoFile(file: RepoProjectFile): RepoProjectFile | null { const next: RepoProjectFile = { ...file } if (next.projectActions && next.projectActions.length === 0) { diff --git a/backend/test/routes/repo-terminal-socket.test.ts b/backend/test/routes/repo-terminal-socket.test.ts index 9f713dee..0efcea88 100644 --- a/backend/test/routes/repo-terminal-socket.test.ts +++ b/backend/test/routes/repo-terminal-socket.test.ts @@ -1,5 +1,8 @@ import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest' +import { randomBytes } from 'node:crypto' +import { request as httpRequest } from 'node:http' import { Hono } from 'hono' +import { cors } from 'hono/cors' import { serve } from '@hono/node-server' import { createNodeWebSocket } from '@hono/node-ws' import type { Server } from 'node:http' @@ -91,6 +94,67 @@ managerApp.route( ), ) +const TRUSTED_ORIGIN = 'http://localhost:5003' +const authenticatedApp = new Hono() +const authenticatedWs = createNodeWebSocket({ app: authenticatedApp }) +authenticatedApp.use('/*', cors()) +authenticatedApp.use('/*', async (c, next) => { + const cookie = c.req.header('cookie') ?? '' + if (!cookie.includes('session=valid')) { + return c.json({ error: 'Unauthorized' }, 401) + } + await next() +}) +authenticatedApp.route( + '/', + createRepoTerminalSocketRoutes( + database, + gitAuthService, + openCodeClient, + terminalService, + authenticatedWs.upgradeWebSocket, + [TRUSTED_ORIGIN], + ), +) + +let authenticatedServer: Server +let authenticatedPort = 0 + +interface RawHandshakeResult { + upgraded: boolean + status?: number +} + +function rawHandshake(options: { port: number; path: string; origin?: string; cookie?: string }): Promise { + return new Promise((resolve, reject) => { + const headers: Record = { + Connection: 'Upgrade', + Upgrade: 'websocket', + 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), + 'Sec-WebSocket-Version': '13', + } + if (options.origin !== undefined) headers.Origin = options.origin + if (options.cookie) headers.Cookie = options.cookie + + const request = httpRequest({ host: '127.0.0.1', port: options.port, path: options.path, method: 'GET', headers }) + let settled = false + request.on('upgrade', (_res, socket) => { + settled = true + socket.destroy() + resolve({ upgraded: true }) + }) + request.on('response', (res) => { + settled = true + res.resume() + resolve({ upgraded: false, status: res.statusCode }) + }) + request.on('error', (error) => { + if (!settled) reject(error) + }) + request.end() + }) +} + function listen(server: Server): Promise { return new Promise((resolve) => { if (server.listening) { @@ -154,6 +218,10 @@ beforeAll(async () => { managerWs.injectWebSocket(managerServer) managerPort = await listen(managerServer) + authenticatedServer = serve({ fetch: authenticatedApp.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server + authenticatedWs.injectWebSocket(authenticatedServer) + authenticatedPort = await listen(authenticatedServer) + vi.mocked(resolveRepoOrAssistant).mockImplementation((_db, id) => (id === 1 ? readyRepo : null)) vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (_repo, directory) => { if (directory === undefined || directory === '/tmp/repo') return '/tmp/repo' @@ -165,8 +233,10 @@ beforeAll(async () => { afterAll(async () => { upstreamWs.wss.close() managerWs.wss.close() + authenticatedWs.wss.close() await closeServer(upstreamServer) await closeServer(managerServer) + await closeServer(authenticatedServer) }) describe('Repo Terminal Socket Route', () => { @@ -217,3 +287,52 @@ describe('Repo Terminal Socket Route', () => { expect(closeEvent.code).toBe(4404) }) }) + +describe('Repo Terminal Socket Origin validation', () => { + const path = `/1/terminals/pty-1/connect?directory=${encodeURIComponent('/tmp/repo')}` + + it('accepts a trusted Origin with a valid session cookie', async () => { + const outcome = await rawHandshake({ + port: authenticatedPort, + path, + origin: TRUSTED_ORIGIN, + cookie: 'session=valid', + }) + + expect(outcome).toEqual({ upgraded: true }) + }) + + it('allows a non-browser client without an Origin header', async () => { + const outcome = await rawHandshake({ port: authenticatedPort, path, cookie: 'session=valid' }) + + expect(outcome).toEqual({ upgraded: true }) + }) + + it('rejects an untrusted same-site Origin before the upgrade', async () => { + const outcome = await rawHandshake({ + port: authenticatedPort, + path, + origin: 'http://localhost:5004', + cookie: 'session=valid', + }) + + expect(outcome).toEqual({ upgraded: false, status: 403 }) + }) + + it('rejects a null Origin before the upgrade', async () => { + const outcome = await rawHandshake({ + port: authenticatedPort, + path, + origin: 'null', + cookie: 'session=valid', + }) + + expect(outcome).toEqual({ upgraded: false, status: 403 }) + }) + + it('rejects the upgrade without a session cookie', async () => { + const outcome = await rawHandshake({ port: authenticatedPort, path, origin: TRUSTED_ORIGIN }) + + expect(outcome).toEqual({ upgraded: false, status: 401 }) + }) +}) diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index 313242f1..afa4bdbe 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -1,4 +1,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' import type { Database } from 'bun:sqlite' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' @@ -79,6 +82,7 @@ import * as repoService from '../../src/services/repo' import * as archiveService from '../../src/services/archive' import { createRepoRoutes } from '../../src/routes/repos' import { opencodeServerManager } from '../../src/services/opencode-single-server' +import { ProjectConfigService } from '../../src/services/project-config' import type { GitAuthService } from '../../src/services/git-auth' import type { ScheduleService } from '../../src/services/schedules' import type { TerminalService } from '../../src/services/terminal' @@ -513,6 +517,78 @@ describe('Repo Routes', () => { worktreeSetup: { status: 'failed', error: 'spawn failed' }, }) }) + + it('runs the main project setup when a linked worktree row creates a workspace', async () => { + const worktreeDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-workspace-')) + const repoFile = { version: 1 as const, setupWorktree: ['pnpm repo-setup'] } + fs.mkdirSync(path.join(worktreeDirectory, '.ocm'), { recursive: true }) + fs.writeFileSync(path.join(worktreeDirectory, '.ocm', 'project.json'), JSON.stringify(repoFile)) + const hash = new ProjectConfigService(mockDb, {} as never, mockGitAuthService).hashRepoFile(repoFile) + + vi.mocked(db.getRepoById).mockReturnValue( + createMockRepo({ id: 2, fullPath: '/tmp/repos/worktree', isWorktree: true }), + ) + vi.mocked(db.getRepoSetting).mockImplementation((_database, repoId, key) => { + if (repoId !== 1) return null + if (key === 'worktreeSetupCommands') return JSON.stringify(['pnpm install']) + if (key === 'repoConfigTrustHash') return hash + return null + }) + const mainRepo = createMockRepo({ id: 1, fullPath: '/tmp/repos/main' }) + const resolveSpy = vi + .spyOn(ProjectConfigService.prototype, 'resolveProjectRepo') + .mockResolvedValue(mainRepo) + const client = createStubOpenCodeClient() + client.api.worktree.create = vi.fn(async () => ({ directory: worktreeDirectory })) as never + vi.mocked(mockTerminalService.create).mockResolvedValue({ + id: 'pty-setup', + title: 'Worktree setup', + kind: 'setup', + cwd: worktreeDirectory, + status: 'running', + }) + + try { + const app = createTestRoutes(client) + const res = await app.request('/2/workspaces', { method: 'POST' }) + + expect(res.status).toBe(200) + const body = (await res.json()) as { worktreeSetup: { status: string; repoCommandsSkipped: boolean } } + expect(body.worktreeSetup).toMatchObject({ status: 'started', repoCommandsSkipped: false }) + expect(vi.mocked(mockTerminalService.create)).toHaveBeenCalledWith(worktreeDirectory, { + kind: 'setup', + name: 'Worktree setup', + command: '/bin/sh', + args: ['-c', 'set -e\npnpm install\npnpm repo-setup'], + env: { ROOT_PROJECT_PATH: '/tmp/repos/main' }, + }) + } finally { + resolveSpy.mockRestore() + fs.rmSync(worktreeDirectory, { recursive: true, force: true }) + } + }) + + it('returns 200 with a failed setup when resolving the main project fails', async () => { + vi.mocked(db.getRepoById).mockReturnValue( + createMockRepo({ id: 2, fullPath: '/tmp/repos/worktree', isWorktree: true }), + ) + const resolveSpy = vi + .spyOn(ProjectConfigService.prototype, 'resolveProjectRepo') + .mockRejectedValue(new Error('git unavailable')) + + try { + const app = createTestRoutes() + const res = await app.request('/2/workspaces', { method: 'POST' }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ + directory: '/tmp/wrk-test', + worktreeSetup: { status: 'failed', error: 'git unavailable' }, + }) + } finally { + resolveSpy.mockRestore() + } + }) }) describe('POST /discover', () => { it('should return 400 for an invalid body', async () => { diff --git a/backend/test/services/project-config.test.ts b/backend/test/services/project-config.test.ts index 7ee2957c..69e9b0b8 100644 --- a/backend/test/services/project-config.test.ts +++ b/backend/test/services/project-config.test.ts @@ -347,6 +347,50 @@ describe('ProjectConfigService repository file', () => { expect(service.getPersonalActions(repo)).toEqual([createAction()]) }) + it('keeps unrelated repository setup untrusted when moving an action to personal', async () => { + writeRepoFile({ + version: 1, + projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }], + setupWorktree: ['echo unrelated'], + }) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + + const config = await service.getConfig(repo, directory) + expect(config.repoFile.trusted).toBe(false) + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + + const { service: terminalService, create } = createStatefulTerminalService(null) + const result = await service.runWorktreeSetup(repo, directory, terminalService) + expect(result).toEqual({ status: 'skipped', reason: 'untrusted' }) + expect(create).not.toHaveBeenCalled() + }) + + it('keeps unrelated repository actions untrusted when moving an action into the file', async () => { + service.setPersonalActions(repo, [ + createAction({ id: 'personal-serve', name: 'Personal Serve', command: 'pnpm personal' }), + ]) + writeRepoFile({ + version: 1, + projectActions: [{ id: 'repo-other', name: 'Other', command: 'pnpm other' }], + }) + + await service.moveItem(repo, directory, { kind: 'action', id: 'personal-serve', to: 'repo' }) + + const config = await service.getConfig(repo, directory) + expect(config.repoFile.trusted).toBe(false) + expect(config.actions).toEqual([ + { id: 'repo-other', name: 'Other', command: 'pnpm other', autoOpenUrl: false, source: 'repo' }, + { id: 'personal-serve', name: 'Personal Serve', command: 'pnpm personal', autoOpenUrl: false, source: 'repo' }, + ]) + + const { service: terminalService } = createStatefulTerminalService(null) + await expect(service.runAction(repo, directory, 'repo-other', terminalService)).rejects.toMatchObject({ + status: 409, + code: 'REPO_CONFIG_UNTRUSTED', + }) + }) + it('moves a setup command personal to repo and back', async () => { service.setPersonalSetup(repo, ['pnpm install']) diff --git a/frontend/src/components/repo/RepoActionsDialog.test.tsx b/frontend/src/components/repo/RepoActionsDialog.test.tsx index 450e2588..97d53a15 100644 --- a/frontend/src/components/repo/RepoActionsDialog.test.tsx +++ b/frontend/src/components/repo/RepoActionsDialog.test.tsx @@ -74,6 +74,28 @@ describe('RepoActionsDialog', () => { expect(payload[1]).toMatchObject({ name: 'Dev server', command: 'pnpm dev' }) }) + it('adds an action when crypto.randomUUID is unavailable', async () => { + vi.stubGlobal('crypto', { randomUUID: undefined }) + try { + mockConfig(baseConfig()) + const user = userEvent.setup() + renderDialog() + + await user.click(screen.getByRole('button', { name: /add action/i })) + await user.type(screen.getByLabelText('Name'), 'Dev server') + await user.type(screen.getByLabelText('Command'), 'pnpm dev') + await user.click(screen.getByRole('button', { name: /^save$/i })) + + await waitFor(() => expect(mocks.updateActionsMutate).toHaveBeenCalledTimes(1)) + const payload = mocks.updateActionsMutate.mock.calls[0][0] + expect(payload).toHaveLength(1) + expect(payload[0].id).toMatch(/^[A-Za-z0-9_-]{1,64}$/) + expect(payload[0]).toMatchObject({ name: 'Dev server', command: 'pnpm dev' }) + } finally { + vi.unstubAllGlobals() + } + }) + it('offers no edit button for repo items but allows moving them to personal settings', () => { mockConfig( baseConfig({ diff --git a/frontend/src/components/repo/RepoActionsDialog.tsx b/frontend/src/components/repo/RepoActionsDialog.tsx index 53ddd4f2..cfdbec2a 100644 --- a/frontend/src/components/repo/RepoActionsDialog.tsx +++ b/frontend/src/components/repo/RepoActionsDialog.tsx @@ -32,6 +32,7 @@ import { useUpdateWorktreeSetup, } from '@/api/projectConfig' import { showToast } from '@/lib/toast' +import { randomId } from '@/lib/utils' import type { ProjectAction, ProjectActionIcon, ProjectItemSource } from '@opencode-manager/shared/types' const ACTION_ICON_OPTIONS: { value: ProjectActionIcon; label: string; Icon: LucideIcon }[] = [ @@ -59,7 +60,7 @@ interface ActionDraft { } function emptyActionDraft(): ActionDraft { - return { id: crypto.randomUUID(), name: '', command: '', icon: 'play', url: '', autoOpenUrl: false } + return { id: randomId(), name: '', command: '', icon: 'play', url: '', autoOpenUrl: false } } function actionToDraft(action: ProjectAction): ActionDraft {