mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix(terminal-dev-loop): address branch review findings
Security: - Reject same-site and cross-site state-changing requests on cookie-authenticated routes unless the origin is trusted - Drop Manager and ocm_preview Set-Cookie headers from preview responses - Show and hash the full executable content of .ocm/project.json at trust time - Restrict action URLs to http(s) and refuse symlinked repo config paths - Keep the preview start redirect on the gateway origin Lifecycle: - Stop terminals in OpenCode workspace siblings when a repo is deleted - Report preview as unavailable instead of crashing when the gateway port cannot be bound Performance: - Skip branch lookups when validating terminal and project-config directories - Stop the /proc scan once all listening sockets are mapped and pause port polling while a preview is open - Close slow WebSocket clients with 1013 so they reconnect with replay - Lazy-load the xterm terminal view and skip unchanged resize requests - Request uncompressed responses from preview targets Cleanup: - Share one repo directory resolver, trusted-origins parser, cookie prefix, WebSocket frame forwarder, header filter, icon map and dialog-param helper - Remove unused props, options and exports Docs: update terminal, preview, project actions, sandboxing, internal API and environment pages
This commit is contained in:
1 parent
16b91ccf02
commit
c60a9b35f2
72 files changed
+2039
-596
No files matched your search
@@ -31,7 +31,13 @@ const { ENV } = vi.hoisted(() => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({ ENV }))
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV,
|
||||
getTrustedOrigins: () => ENV.AUTH.TRUSTED_ORIGINS
|
||||
.split(',')
|
||||
.map((origin: string) => origin.trim())
|
||||
.filter((origin: string) => origin.length > 0),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { createAuthMiddleware } from '../../src/auth/middleware'
|
||||
import type { AuthInstance, Session } from '../../src/auth'
|
||||
|
||||
const loggerMock = vi.hoisted(() => ({
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({ logger: loggerMock }))
|
||||
|
||||
const TRUSTED_ORIGIN = 'http://trusted.test'
|
||||
const UNTRUSTED_ORIGIN = 'http://untrusted.test'
|
||||
|
||||
function createSession(): Session {
|
||||
return {
|
||||
session: {
|
||||
id: 'session-1',
|
||||
userId: 'user-1',
|
||||
token: 'token-1',
|
||||
expiresAt: new Date(Date.now() + 1000),
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
user: {
|
||||
id: 'user-1',
|
||||
name: 'Test User',
|
||||
email: 'test@example.com',
|
||||
emailVerified: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
role: 'user',
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function createApp(
|
||||
getSession: (input: { headers: Headers }) => Promise<Session | null>,
|
||||
trustedOrigins: string[] = [TRUSTED_ORIGIN],
|
||||
) {
|
||||
const app = new Hono<{ Variables: { session: Session['session']; user: Session['user'] } }>()
|
||||
app.use('/*', createAuthMiddleware({ api: { getSession } } as unknown as AuthInstance, () => trustedOrigins))
|
||||
app.get('/', (c) => c.json({ userId: c.get('user').id }))
|
||||
app.post('/', (c) => c.json({ ok: true }))
|
||||
app.put('/', (c) => c.json({ ok: true }))
|
||||
app.patch('/', (c) => c.json({ ok: true }))
|
||||
app.delete('/', (c) => c.json({ ok: true }))
|
||||
return app
|
||||
}
|
||||
|
||||
describe('createAuthMiddleware same-site guard', () => {
|
||||
let getSession: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
getSession = vi.fn()
|
||||
getSession.mockResolvedValue(createSession())
|
||||
})
|
||||
|
||||
it('rejects an unsafe same-site request with an untrusted origin without looking up the session', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { 'sec-fetch-site': 'same-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(await res.json()).toEqual({ error: 'Cross-site request rejected' })
|
||||
expect(getSession).not.toHaveBeenCalled()
|
||||
expect(loggerMock.warn).toHaveBeenCalledWith(expect.stringContaining('/'))
|
||||
})
|
||||
|
||||
it('allows an unsafe same-site request from a trusted origin', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { 'sec-fetch-site': 'same-site', origin: TRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(getSession).toHaveBeenCalledTimes(1)
|
||||
expect(loggerMock.warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('allows a same-origin request', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { 'sec-fetch-site': 'same-origin', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(getSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('allows an unsafe request without a Sec-Fetch-Site header', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(getSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('allows a cross-site GET so WebSocket upgrades are unaffected', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'GET',
|
||||
headers: { 'sec-fetch-site': 'cross-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(getSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects a cross-site unsafe request with no origin', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'DELETE',
|
||||
headers: { 'sec-fetch-site': 'cross-site', cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(await res.json()).toEqual({ error: 'Cross-site request rejected' })
|
||||
expect(getSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a cross-site PUT with an untrusted origin', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'PUT',
|
||||
headers: { 'sec-fetch-site': 'cross-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(getSession).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getTrustedOrigins', () => {
|
||||
const originalTrustedOrigins = process.env.AUTH_TRUSTED_ORIGINS
|
||||
|
||||
afterEach(() => {
|
||||
if (originalTrustedOrigins === undefined) {
|
||||
delete process.env.AUTH_TRUSTED_ORIGINS
|
||||
} else {
|
||||
process.env.AUTH_TRUSTED_ORIGINS = originalTrustedOrigins
|
||||
}
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
async function loadTrustedOrigins(value?: string): Promise<string[]> {
|
||||
if (value === undefined) {
|
||||
delete process.env.AUTH_TRUSTED_ORIGINS
|
||||
} else {
|
||||
process.env.AUTH_TRUSTED_ORIGINS = value
|
||||
}
|
||||
vi.resetModules()
|
||||
const { getTrustedOrigins } = await import('@opencode-manager/shared/config/env')
|
||||
return getTrustedOrigins()
|
||||
}
|
||||
|
||||
it('splits, trims, and drops empty entries', async () => {
|
||||
await expect(loadTrustedOrigins(' http://a.test ,, http://b.test ')).resolves.toEqual(['http://a.test', 'http://b.test'])
|
||||
})
|
||||
|
||||
it('returns an empty list when configured empty', async () => {
|
||||
await expect(loadTrustedOrigins('')).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('falls back to the local development origins', async () => {
|
||||
await expect(loadTrustedOrigins(undefined)).resolves.toEqual(['http://localhost:5173', 'http://localhost:5003'])
|
||||
})
|
||||
})
|
||||
@@ -3,12 +3,47 @@ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promis
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const serveMock = vi.fn<(options: unknown) => { on: () => void }>(() => ({ on: vi.fn() }))
|
||||
interface MockServeServer {
|
||||
on: (event: string, handler: (...args: unknown[]) => void) => void
|
||||
emit: (event: string, ...args: unknown[]) => void
|
||||
}
|
||||
|
||||
const serveServers = vi.hoisted(() => [] as MockServeServer[])
|
||||
|
||||
const serveMock = vi.fn<(options: unknown) => MockServeServer>(() => {
|
||||
const handlers = new Map<string, Array<(...args: unknown[]) => void>>()
|
||||
const server: MockServeServer = {
|
||||
on: (event, handler) => {
|
||||
const registered = handlers.get(event) ?? []
|
||||
registered.push(handler)
|
||||
handlers.set(event, registered)
|
||||
},
|
||||
emit: (event, ...args) => {
|
||||
for (const handler of handlers.get(event) ?? []) handler(...args)
|
||||
},
|
||||
}
|
||||
serveServers.push(server)
|
||||
return server
|
||||
})
|
||||
|
||||
vi.mock('@hono/node-server', () => ({
|
||||
serve: serveMock,
|
||||
}))
|
||||
|
||||
const previewAvailabilityInstances = vi.hoisted(() => [] as Array<{ isEnabled: () => boolean }>)
|
||||
|
||||
vi.mock('../src/routes/preview', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/routes/preview')>()
|
||||
return {
|
||||
...actual,
|
||||
createPreviewAvailability: (initialEnabled: boolean) => {
|
||||
const availability = actual.createPreviewAvailability(initialEnabled)
|
||||
previewAvailabilityInstances.push(availability)
|
||||
return availability
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const supervisorMock = vi.hoisted(() => ({
|
||||
start: vi.fn().mockResolvedValue({ healthy: true, port: 5551, state: 'running' }),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -143,6 +178,8 @@ describe('backend entrypoint', () => {
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
serveServers.length = 0
|
||||
previewAvailabilityInstances.length = 0
|
||||
tempWorkspace = await mkdtemp(join(tmpdir(), 'ocm-entrypoint-'))
|
||||
previousWorkspace = process.env.WORKSPACE_PATH
|
||||
process.env.WORKSPACE_PATH = tempWorkspace
|
||||
@@ -175,6 +212,22 @@ describe('backend entrypoint', () => {
|
||||
expect(ipcServerMock.dispose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('marks the preview gateway unavailable instead of crashing when its port cannot be bound', async () => {
|
||||
await import('../src/index')
|
||||
|
||||
expect(serveServers).toHaveLength(2)
|
||||
const availability = previewAvailabilityInstances[0]
|
||||
expect(availability?.isEnabled()).toBe(false)
|
||||
|
||||
const previewServer = serveServers[1]!
|
||||
previewServer.emit('listening')
|
||||
expect(availability?.isEnabled()).toBe(true)
|
||||
|
||||
const error = Object.assign(new Error('bind failed'), { code: 'EADDRINUSE' })
|
||||
expect(() => previewServer.emit('error', error)).not.toThrow()
|
||||
expect(availability?.isEnabled()).toBe(false)
|
||||
})
|
||||
|
||||
it('imports home state without rewriting an existing valid config', async () => {
|
||||
const configDir = join(tempWorkspace, '.config', 'opencode')
|
||||
await mkdir(configDir, { recursive: true })
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { mkdtemp, mkdir, rm } from 'node:fs/promises'
|
||||
import { mkdtemp, mkdir, rm, symlink } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { createPreviewRoutes } from '../../src/routes/preview'
|
||||
import type { PreviewPort } from '@opencode-manager/shared/schemas'
|
||||
import { createPreviewRoutes, createPreviewAvailability } from '../../src/routes/preview'
|
||||
import { PreviewSessionStore } from '../../src/services/preview/gateway'
|
||||
import type { PreviewPortEntry } from '../../src/services/preview/ports'
|
||||
|
||||
@@ -30,7 +31,7 @@ describe('Preview Routes', () => {
|
||||
await mkdir(appDir)
|
||||
|
||||
const app = createPreviewRoutes({
|
||||
enabled: true,
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [
|
||||
entry({ port: 9000, cwd: '/somewhere/else' }),
|
||||
entry({ port: 5173, cwd: appDir }),
|
||||
@@ -47,7 +48,7 @@ describe('Preview Routes', () => {
|
||||
|
||||
it('sorts by port when no directory is given', async () => {
|
||||
const app = createPreviewRoutes({
|
||||
enabled: true,
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [entry({ port: 9000 }), entry({ port: 5173 })],
|
||||
})
|
||||
|
||||
@@ -57,8 +58,60 @@ describe('Preview Routes', () => {
|
||||
expect(body.ports.map((port) => port.port)).toEqual([5173, 9000])
|
||||
})
|
||||
|
||||
it('marks entries inside the directory and sorts them first', async () => {
|
||||
const root = await makeTempDir()
|
||||
const appDir = join(root, 'app')
|
||||
await mkdir(appDir)
|
||||
|
||||
const app = createPreviewRoutes({
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [
|
||||
entry({ port: 5173, cwd: '/somewhere/else' }),
|
||||
entry({ port: 9000, cwd: appDir }),
|
||||
],
|
||||
})
|
||||
|
||||
const res = await app.request(`/ports?directory=${encodeURIComponent(root)}`)
|
||||
const body = await res.json() as { ports: PreviewPort[] }
|
||||
|
||||
expect(body.ports.map((port) => ({ port: port.port, inDirectory: port.inDirectory }))).toEqual([
|
||||
{ port: 9000, inDirectory: true },
|
||||
{ port: 5173, inDirectory: false },
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves symlinked cwds before matching the directory', async () => {
|
||||
const root = await makeTempDir()
|
||||
const realDir = join(root, 'real')
|
||||
const linkDir = join(root, 'link')
|
||||
await mkdir(realDir)
|
||||
await symlink(realDir, linkDir)
|
||||
|
||||
const app = createPreviewRoutes({
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [entry({ port: 5173, cwd: linkDir })],
|
||||
})
|
||||
|
||||
const res = await app.request(`/ports?directory=${encodeURIComponent(realDir)}`)
|
||||
const body = await res.json() as { ports: PreviewPort[] }
|
||||
|
||||
expect(body.ports[0]?.inDirectory).toBe(true)
|
||||
})
|
||||
|
||||
it('marks every entry outside when no directory is given', async () => {
|
||||
const app = createPreviewRoutes({
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [entry({ port: 5173, cwd: '/repo' }), entry({ port: 9000, cwd: null })],
|
||||
})
|
||||
|
||||
const res = await app.request('/ports')
|
||||
const body = await res.json() as { ports: PreviewPort[] }
|
||||
|
||||
expect(body.ports.map((port) => port.inDirectory)).toEqual([false, false])
|
||||
})
|
||||
|
||||
it('reports preview as disabled when the port is zero', async () => {
|
||||
const app = createPreviewRoutes({ enabled: false, listPorts: async () => [] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => false, listPorts: async () => [] })
|
||||
|
||||
const res = await app.request('/ports')
|
||||
|
||||
@@ -67,7 +120,7 @@ describe('Preview Routes', () => {
|
||||
|
||||
it('issues a preview start token for a listening port', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: 5173 })], store })
|
||||
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: 5173 })], store })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -84,7 +137,7 @@ describe('Preview Routes', () => {
|
||||
})
|
||||
|
||||
it('rejects a reserved port with 400', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: ENV.PREVIEW.PORT })] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: ENV.PREVIEW.PORT })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -96,7 +149,7 @@ describe('Preview Routes', () => {
|
||||
})
|
||||
|
||||
it('returns 404 for a port that is not listening', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: 5173 })] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: 5173 })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -109,7 +162,7 @@ describe('Preview Routes', () => {
|
||||
})
|
||||
|
||||
it('returns 503 when preview is disabled', async () => {
|
||||
const app = createPreviewRoutes({ enabled: false, listPorts: async () => [entry({ port: 5173 })] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => false, listPorts: async () => [entry({ port: 5173 })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -121,7 +174,7 @@ describe('Preview Routes', () => {
|
||||
})
|
||||
|
||||
it('rejects an out-of-range port with 400', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -131,4 +184,40 @@ describe('Preview Routes', () => {
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('reads availability at request time', async () => {
|
||||
let enabled = true
|
||||
const app = createPreviewRoutes({ isEnabled: () => enabled, listPorts: async () => [entry({ port: 5173 })] })
|
||||
|
||||
const first = await app.request('/ports')
|
||||
expect((await first.json() as { enabled: boolean }).enabled).toBe(true)
|
||||
|
||||
enabled = false
|
||||
const second = await app.request('/ports')
|
||||
expect((await second.json() as { enabled: boolean }).enabled).toBe(false)
|
||||
|
||||
const disabledSession = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ port: 5173 }),
|
||||
})
|
||||
expect(disabledSession.status).toBe(503)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Preview availability', () => {
|
||||
it('starts in the provided state', () => {
|
||||
expect(createPreviewAvailability(true).isEnabled()).toBe(true)
|
||||
expect(createPreviewAvailability(false).isEnabled()).toBe(false)
|
||||
})
|
||||
|
||||
it('tracks availability transitions', () => {
|
||||
const availability = createPreviewAvailability(true)
|
||||
|
||||
availability.markUnavailable()
|
||||
expect(availability.isEnabled()).toBe(false)
|
||||
|
||||
availability.markAvailable()
|
||||
expect(availability.isEnabled()).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -89,6 +89,7 @@ describe('Repo Project Config Routes', () => {
|
||||
exists: false,
|
||||
trusted: false,
|
||||
hash: null,
|
||||
executable: null,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
@@ -100,6 +101,13 @@ describe('Repo Project Config Routes', () => {
|
||||
expect(await res.json()).toEqual({ error: 'Repo not found' })
|
||||
})
|
||||
|
||||
it('rejects the assistant repo id when assistant access is not allowed', async () => {
|
||||
const res = await app.request('/0/project-config')
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.json()).toEqual({ error: 'Repo not found' })
|
||||
})
|
||||
|
||||
it('returns 404 for a repo that is not ready', async () => {
|
||||
createRepo(db, { localPath: 'repo-cloning', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true })
|
||||
|
||||
@@ -214,6 +222,33 @@ describe('Repo Project Config Routes', () => {
|
||||
expect((await res.json() as { code: string }).code).toBe('REPO_CONFIG_CHANGED')
|
||||
})
|
||||
|
||||
it('returns the error code and details for an untrusted repository action', async () => {
|
||||
seedRepo(db)
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-route-untrusted-'))
|
||||
vi.mocked(resolveRepoWorkingDirectory).mockResolvedValue(directory)
|
||||
const repoFileDir = path.join(directory, '.ocm')
|
||||
fs.mkdirSync(repoFileDir, { recursive: true })
|
||||
fs.writeFileSync(
|
||||
path.join(repoFileDir, 'project.json'),
|
||||
JSON.stringify({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }),
|
||||
)
|
||||
|
||||
try {
|
||||
const res = await app.request('/1/project-config/actions/repo-serve/run', {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json() as { code: string; details: { hash: string } }
|
||||
expect(body.code).toBe('REPO_CONFIG_UNTRUSTED')
|
||||
expect(body.details.hash).toMatch(/^[a-f0-9]{64}$/)
|
||||
} finally {
|
||||
fs.rmSync(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('returns 400 for an invalid move request', async () => {
|
||||
seedRepo(db)
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ const gitAuthService = { getGitEnvironment: vi.fn(() => ({})) } as unknown as Gi
|
||||
const openCodeClient: OpenCodeClient = createStubOpenCodeClient()
|
||||
|
||||
const readyRepo = { id: 1, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo
|
||||
const assistantRepo = { id: 0, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo
|
||||
|
||||
const shellTerminal = {
|
||||
id: 'pty-1',
|
||||
@@ -54,7 +55,9 @@ const jsonHeaders = { 'Content-Type': 'application/json' }
|
||||
describe('Repo Terminal Routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(resolveRepoOrAssistant).mockImplementation((_db, id) => (id === 1 ? readyRepo : null))
|
||||
vi.mocked(resolveRepoOrAssistant).mockImplementation((_db, id) =>
|
||||
id === 1 ? readyRepo : id === 0 ? assistantRepo : null,
|
||||
)
|
||||
vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (_repo, directory) => {
|
||||
if (directory === undefined || directory === '/tmp/repo') return '/tmp/repo'
|
||||
return null
|
||||
@@ -78,6 +81,15 @@ describe('Repo Terminal Routes', () => {
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('resolves the assistant repo when assistant access is allowed', async () => {
|
||||
const terminals = [{ ...shellTerminal }]
|
||||
const list = vi.fn(async () => terminals)
|
||||
const res = await createApp(createService({ list })).request('/0/terminals')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(list).toHaveBeenCalledWith('/tmp/repo')
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown repo', async () => {
|
||||
vi.mocked(resolveRepoOrAssistant).mockReturnValue(null)
|
||||
const res = await createApp(createService()).request('/2/terminals')
|
||||
|
||||
@@ -871,6 +871,37 @@ describe('Repo Routes', () => {
|
||||
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
|
||||
})
|
||||
|
||||
it('removes terminals for OpenCode workspace siblings but not manager worktree repos', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
|
||||
vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined)
|
||||
vi.mocked(repoService.getSiblingRepos).mockResolvedValue([
|
||||
{ ...createMockRepo({ id: 2, fullPath: '/tmp/repos/manager-worktree', isWorktree: true }), currentBranch: undefined },
|
||||
{ ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeStrategy: 'git' },
|
||||
])
|
||||
|
||||
const app = createTestRoutes()
|
||||
const res = await app.request('/1', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/repos/test-repo')
|
||||
expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/plugin-workspace')
|
||||
expect(mockTerminalService.removeAll).not.toHaveBeenCalledWith('/tmp/repos/manager-worktree')
|
||||
expect(repoService.getSiblingRepos).toHaveBeenCalledWith(mockDb, 1, {}, expect.anything(), { includeBranch: false })
|
||||
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
|
||||
})
|
||||
|
||||
it('still deletes the repo when listing workspace siblings throws', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 }))
|
||||
vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined)
|
||||
vi.mocked(repoService.getSiblingRepos).mockRejectedValue(new Error('siblings failed'))
|
||||
|
||||
const app = createTestRoutes()
|
||||
const res = await app.request('/1', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
|
||||
})
|
||||
|
||||
it('should return 500 when removing the repo files throws', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 }))
|
||||
vi.mocked(repoService.deleteRepoFiles).mockRejectedValue(new Error('delete failed'))
|
||||
|
||||
@@ -31,6 +31,17 @@ upstreamApp.get('/cookies', () => {
|
||||
return new Response('ok', { status: 200, headers })
|
||||
})
|
||||
|
||||
upstreamApp.get('/manager-cookies', () => {
|
||||
const headers = new Headers()
|
||||
headers.append('set-cookie', 'app=keep; Path=/')
|
||||
headers.append('set-cookie', `${PREVIEW_COOKIE}=upstream; Path=/`)
|
||||
headers.append('set-cookie', 'opencode.session_token=secret; Path=/')
|
||||
headers.append('set-cookie', '__Secure-opencode.session_token=secure; Path=/')
|
||||
headers.append('set-cookie', '__Host-opencode.session_token=host; Path=/')
|
||||
headers.set('content-type', 'text/plain')
|
||||
return new Response('ok', { status: 200, headers })
|
||||
})
|
||||
|
||||
upstreamApp.all('/*', async (c) => {
|
||||
if (c.req.path === '/r') {
|
||||
return c.redirect(`http://localhost:${upstreamPort}/done`, 302)
|
||||
@@ -42,6 +53,7 @@ upstreamApp.all('/*', async (c) => {
|
||||
search: new URL(c.req.url).search,
|
||||
host: c.req.header('host') ?? null,
|
||||
cookie: c.req.header('cookie') ?? null,
|
||||
acceptEncoding: c.req.header('accept-encoding') ?? null,
|
||||
body,
|
||||
})
|
||||
})
|
||||
@@ -129,6 +141,36 @@ describe('Preview Gateway', () => {
|
||||
expect(res.headers.get('location')).toBe('/')
|
||||
})
|
||||
|
||||
it('rejects redirect paths that resolve off-origin', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
|
||||
for (const malicious of ['/\\evil.example', '//evil.example', 'https://evil.example']) {
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
const res = await app.request(
|
||||
`http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent(malicious)}`,
|
||||
{ redirect: 'manual' },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(302)
|
||||
expect(res.headers.get('location')).toBe('/')
|
||||
}
|
||||
})
|
||||
|
||||
it('redirects to an allowed same-origin path with query and hash', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
|
||||
const res = await app.request(
|
||||
`http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent('/ok?x=1#h')}`,
|
||||
{ redirect: 'manual' },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(302)
|
||||
expect(res.headers.get('location')).toBe('/ok?x=1#h')
|
||||
})
|
||||
|
||||
it('does not allow a start token to be reused', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
@@ -230,6 +272,31 @@ describe('Preview Gateway', () => {
|
||||
expect(cookies).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('drops Manager and preview Set-Cookie values from upstream responses', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const res = await app.request('http://localhost/manager-cookies', { headers: { cookie } })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.getSetCookie()).toEqual(['app=keep; Path=/'])
|
||||
})
|
||||
|
||||
it('requests identity encoding from the upstream', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const res = await app.request('http://localhost/echo', {
|
||||
headers: { cookie, 'accept-encoding': 'gzip, br' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { acceptEncoding: string | null }
|
||||
expect(body.acceptEncoding).toBe('identity')
|
||||
})
|
||||
|
||||
it('rewrites an absolute localhost location to its path', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
|
||||
@@ -140,6 +140,41 @@ describe('listListeningPorts', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('stops scanning process fd directories once every listening inode is mapped', async () => {
|
||||
const base = createDeps({
|
||||
files: {
|
||||
'/proc/net/tcp': [PROC_HEADER, procRow('00000000:1435', '00000000:0000', '0A', '11111')].join('\n'),
|
||||
'/proc/1234/comm': 'node\n',
|
||||
},
|
||||
links: {
|
||||
'/proc/1234/fd/3': 'socket:[11111]',
|
||||
'/proc/1234/cwd': '/home/user/project',
|
||||
'/proc/9999/fd/2': 'socket:[11111]',
|
||||
},
|
||||
dirs: {
|
||||
'/proc': ['1234', '9999'],
|
||||
'/proc/1234/fd': ['3'],
|
||||
'/proc/9999/fd': ['2'],
|
||||
},
|
||||
})
|
||||
const readdirCalls: string[] = []
|
||||
const deps: PortDiscoveryDeps = {
|
||||
...base,
|
||||
readdir: async (path) => {
|
||||
readdirCalls.push(path)
|
||||
return base.readdir(path)
|
||||
},
|
||||
}
|
||||
|
||||
const ports = await listListeningPorts(deps)
|
||||
|
||||
expect(ports).toEqual([
|
||||
{ port: 5173, host: '127.0.0.1', pid: 1234, command: 'node', cwd: '/home/user/project' },
|
||||
])
|
||||
expect(readdirCalls).toContain('/proc/1234/fd')
|
||||
expect(readdirCalls).not.toContain('/proc/9999/fd')
|
||||
})
|
||||
|
||||
it('reports an IPv6 loopback host only when the sole listener is IPv6 loopback', async () => {
|
||||
const deps = createDeps({
|
||||
files: {
|
||||
|
||||
@@ -95,6 +95,7 @@ describe('ProjectConfigService personal settings', () => {
|
||||
exists: false,
|
||||
trusted: false,
|
||||
hash: null,
|
||||
executable: null,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
@@ -288,17 +289,39 @@ describe('ProjectConfigService repository file', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps trust across a name-only edit and drops it on a command edit', async () => {
|
||||
it('drops trust when the name, command, or autoOpenUrl changes', async () => {
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
|
||||
const first = await service.getConfig(repo, directory)
|
||||
await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '')
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true)
|
||||
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] })
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true)
|
||||
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev --host' }] })
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false)
|
||||
|
||||
const renamed = await service.getConfig(repo, directory)
|
||||
await service.trustRepoFile(repo, directory, renamed.repoFile.hash ?? '')
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev', autoOpenUrl: true }],
|
||||
})
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false)
|
||||
})
|
||||
|
||||
it('changes the hash when only the name or autoOpenUrl changes', async () => {
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
|
||||
const base = await service.getConfig(repo, directory)
|
||||
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] })
|
||||
const renamed = await service.getConfig(repo, directory)
|
||||
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: true }],
|
||||
})
|
||||
const autoOpen = await service.getConfig(repo, directory)
|
||||
|
||||
expect(renamed.repoFile.hash).not.toBe(base.repoFile.hash)
|
||||
expect(autoOpen.repoFile.hash).not.toBe(base.repoFile.hash)
|
||||
})
|
||||
|
||||
it('reports invalid JSON with an error and no repository items', async () => {
|
||||
@@ -307,7 +330,7 @@ describe('ProjectConfigService repository file', () => {
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.exists).toBe(true)
|
||||
expect(config.repoFile.error).toBeTruthy()
|
||||
expect(config.repoFile.error).toBe('Invalid JSON')
|
||||
expect(config.repoFile.hash).toBeNull()
|
||||
expect(config.actions).toEqual([])
|
||||
})
|
||||
@@ -317,10 +340,72 @@ describe('ProjectConfigService repository file', () => {
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBeTruthy()
|
||||
expect(config.repoFile.error).toBe('Does not match the project file schema')
|
||||
expect(config.actions).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a repository action url that is not http(s)', async () => {
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: 'javascript:alert(1)' }],
|
||||
})
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBe('Does not match the project file schema')
|
||||
expect(config.repoFile.executable).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts an http url template', async () => {
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: 'http://localhost:3000/{branch}' }],
|
||||
})
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.executable?.actions[0]?.url).toBe('http://localhost:3000/{branch}')
|
||||
})
|
||||
|
||||
it('reports a symlinked .ocm directory as invalid on read', async () => {
|
||||
const realDir = path.join(directory, 'real-ocm')
|
||||
fs.mkdirSync(realDir, { recursive: true })
|
||||
fs.writeFileSync(path.join(realDir, 'project.json'), JSON.stringify({ version: 1 }))
|
||||
fs.symlinkSync(realDir, path.join(directory, '.ocm'), 'dir')
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBe('.ocm/project.json must not be a symbolic link')
|
||||
expect(config.repoFile.hash).toBeNull()
|
||||
expect(config.repoFile.executable).toBeNull()
|
||||
})
|
||||
|
||||
it('reports a symlinked project.json as invalid on read', async () => {
|
||||
const ocmDir = path.join(directory, '.ocm')
|
||||
fs.mkdirSync(ocmDir, { recursive: true })
|
||||
const target = path.join(directory, 'target.json')
|
||||
fs.writeFileSync(target, JSON.stringify({ version: 1 }))
|
||||
fs.symlinkSync(target, path.join(ocmDir, 'project.json'))
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBe('.ocm/project.json must not be a symbolic link')
|
||||
})
|
||||
|
||||
it('refuses to move an action into a symlinked repository config', async () => {
|
||||
service.setPersonalActions(repo, [createAction()])
|
||||
const realDir = path.join(directory, 'real-ocm')
|
||||
fs.mkdirSync(realDir, { recursive: true })
|
||||
fs.writeFileSync(path.join(realDir, 'project.json'), JSON.stringify({ version: 1 }))
|
||||
fs.symlinkSync(realDir, path.join(directory, '.ocm'), 'dir')
|
||||
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toMatchObject({
|
||||
status: 400,
|
||||
code: 'REPO_CONFIG_SYMLINK',
|
||||
})
|
||||
expect(service.getPersonalActions(repo)).toEqual([createAction()])
|
||||
})
|
||||
|
||||
it('moves an action personal to repo preserving unknown keys and marking it trusted', async () => {
|
||||
service.setPersonalActions(repo, [createAction()])
|
||||
writeRepoFile({ version: 1, customKey: 'keep-me' })
|
||||
@@ -416,6 +501,34 @@ describe('ProjectConfigService repository file', () => {
|
||||
expect(config.repoFile.warnings[0]).toContain('serve')
|
||||
})
|
||||
|
||||
it('lists every executable repository action including a shadowed one', async () => {
|
||||
service.setPersonalActions(repo, [
|
||||
createAction({ id: 'serve', name: 'Personal Serve', command: 'pnpm personal' }),
|
||||
])
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [
|
||||
{ id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev', url: 'https://example.com', autoOpenUrl: true },
|
||||
{ id: 'other', name: 'Other', command: 'pnpm other' },
|
||||
],
|
||||
setupWorktree: ['pnpm install'],
|
||||
})
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.executable).toEqual({
|
||||
actions: [
|
||||
{ id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev', url: 'https://example.com', autoOpenUrl: true },
|
||||
{ id: 'other', name: 'Other', command: 'pnpm other', url: null, autoOpenUrl: false },
|
||||
],
|
||||
setup: ['pnpm install'],
|
||||
})
|
||||
expect(config.actions).toEqual([
|
||||
{ id: 'serve', name: 'Personal Serve', command: 'pnpm personal', autoOpenUrl: false, source: 'personal' },
|
||||
{ id: 'other', name: 'Other', command: 'pnpm other', autoOpenUrl: false, source: 'repo' },
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects moving an unknown personal action', async () => {
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'missing', to: 'repo' })).rejects.toMatchObject({
|
||||
status: 404,
|
||||
@@ -487,12 +600,13 @@ describe('ProjectConfigService repository file', () => {
|
||||
|
||||
it('restores the repository file and personal settings when the file write fails', async () => {
|
||||
service.setPersonalActions(repo, [createAction()])
|
||||
const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
const writeSeam = service as unknown as { writeRepoFile(filePath: string, file: unknown): void }
|
||||
const writeSpy = vi.spyOn(writeSeam, 'writeRepoFile').mockImplementationOnce(() => {
|
||||
throw new Error('disk full')
|
||||
})
|
||||
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow('disk full')
|
||||
renameSpy.mockRestore()
|
||||
writeSpy.mockRestore()
|
||||
|
||||
expect(fs.existsSync(repoFilePath())).toBe(false)
|
||||
expect(service.getPersonalActions(repo)).toEqual([createAction()])
|
||||
@@ -531,14 +645,15 @@ describe('ProjectConfigService repository file', () => {
|
||||
],
|
||||
})
|
||||
const originalBytes = fs.readFileSync(repoFilePath(), 'utf8')
|
||||
const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
const writeSeam = service as unknown as { writeRepoFile(filePath: string, file: unknown): void }
|
||||
const writeSpy = vi.spyOn(writeSeam, 'writeRepoFile').mockImplementationOnce(() => {
|
||||
throw new Error('disk full')
|
||||
})
|
||||
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow(
|
||||
'disk full',
|
||||
)
|
||||
renameSpy.mockRestore()
|
||||
writeSpy.mockRestore()
|
||||
|
||||
expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes)
|
||||
expect(service.getPersonalActions(repo)).toEqual([])
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { findSiblingByDirectory, resolveRepoWorkingDirectory } from '../../src/services/repo'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { createRepo } from '../../src/db/queries'
|
||||
import { findSiblingByDirectory, getSiblingRepos, resolveRepoWorkingDirectory } from '../../src/services/repo'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
|
||||
const { executeCommand, resolveProjectId, getSettings } = vi.hoisted(() => ({
|
||||
executeCommand: vi.fn(),
|
||||
resolveProjectId: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/process', () => ({ executeCommand }))
|
||||
vi.mock('../../src/services/project-id-resolver', () => ({ resolveProjectId, isGitMainCheckout: vi.fn() }))
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => ({ getSettings })),
|
||||
}))
|
||||
|
||||
describe('resolveRepoWorkingDirectory', () => {
|
||||
let root: string
|
||||
let repoPath: string
|
||||
@@ -96,3 +112,50 @@ describe('findSiblingByDirectory', () => {
|
||||
expect(findSiblingByDirectory([sibling], path.join(root, 'missing'))).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSiblingRepos branch resolution', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
getSettings.mockReturnValue({ preferences: { repoOrder: [] }, updatedAt: Date.now() })
|
||||
resolveProjectId.mockResolvedValue('project-1')
|
||||
executeCommand.mockReset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
function seedRepo(): Repo {
|
||||
return createRepo(db, {
|
||||
localPath: 'repo-a',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
})
|
||||
}
|
||||
|
||||
it('skips branch resolution when includeBranch is false', async () => {
|
||||
const repo = seedRepo()
|
||||
|
||||
const siblings = await getSiblingRepos(db, repo.id, {}, undefined, { includeBranch: false })
|
||||
|
||||
expect(siblings).toHaveLength(1)
|
||||
expect(siblings[0]?.currentBranch).toBeUndefined()
|
||||
expect(executeCommand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves the branch when includeBranch is true', async () => {
|
||||
const repo = seedRepo()
|
||||
executeCommand.mockResolvedValue('feature-branch\n')
|
||||
|
||||
const siblings = await getSiblingRepos(db, repo.id, {})
|
||||
|
||||
expect(siblings).toHaveLength(1)
|
||||
expect(siblings[0]?.currentBranch).toBe('feature-branch')
|
||||
expect(executeCommand).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -65,6 +65,7 @@ interface FakePeer {
|
||||
closeCalls: Array<{ code?: number; reason?: string }>
|
||||
send(data: string | Uint8Array): void
|
||||
close(code?: number, reason?: string): void
|
||||
bufferedAmount(): number
|
||||
}
|
||||
|
||||
function createPeer(): FakePeer {
|
||||
@@ -79,6 +80,9 @@ function createPeer(): FakePeer {
|
||||
close(code, reason) {
|
||||
closeCalls.push({ code, reason })
|
||||
},
|
||||
bufferedAmount() {
|
||||
return 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/shared/utils'
|
||||
import { formatTerminalTitle, isRunningActionTerminal, parseTerminalTitle } from '@opencode-manager/shared/utils'
|
||||
|
||||
describe('terminal-title', () => {
|
||||
describe('formatTerminalTitle', () => {
|
||||
@@ -59,4 +59,22 @@ describe('terminal-title', () => {
|
||||
expect(parseTerminalTitle('ocm:action:dev')).toEqual({ kind: 'shell', title: 'ocm:action:dev' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('isRunningActionTerminal', () => {
|
||||
it('matches a running action terminal for the action id', () => {
|
||||
expect(isRunningActionTerminal({ kind: 'action', actionId: 'dev', status: 'running' }, 'dev')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a terminal for a different action id', () => {
|
||||
expect(isRunningActionTerminal({ kind: 'action', actionId: 'other', status: 'running' }, 'dev')).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a non-action terminal', () => {
|
||||
expect(isRunningActionTerminal({ kind: 'shell', status: 'running' }, 'dev')).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an exited action terminal', () => {
|
||||
expect(isRunningActionTerminal({ kind: 'action', actionId: 'dev', status: 'exited' }, 'dev')).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,8 @@
|
||||
import { mkdtemp, realpath, rm } from 'node:fs/promises'
|
||||
import { mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { canonicalPath, canonicalPathSync } from '../../src/utils/fs-safe'
|
||||
import { canonicalPath, canonicalPathSync, writeFileAtomicSync } from '../../src/utils/fs-safe'
|
||||
|
||||
describe('canonicalPath', () => {
|
||||
let workDir = ''
|
||||
@@ -29,3 +29,41 @@ describe('canonicalPath', () => {
|
||||
expect(canonicalPathSync(missing)).toBe(missing)
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeFileAtomicSync', () => {
|
||||
let workDir = ''
|
||||
|
||||
beforeEach(async () => {
|
||||
workDir = await mkdtemp(path.join(tmpdir(), 'fs-safe-atomic-'))
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(workDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('writes the content and creates missing parent directories', async () => {
|
||||
const target = path.join(workDir, 'nested', 'file.json')
|
||||
|
||||
writeFileAtomicSync(target, '{"ok":true}', { mode: 0o644 })
|
||||
|
||||
await expect(readFile(target, 'utf8')).resolves.toBe('{"ok":true}')
|
||||
expect((await stat(target)).mode & 0o777).toBe(0o644)
|
||||
})
|
||||
|
||||
it('overwrites an existing file', async () => {
|
||||
const target = path.join(workDir, 'file.txt')
|
||||
await writeFile(target, 'old')
|
||||
|
||||
writeFileAtomicSync(target, 'new')
|
||||
|
||||
await expect(readFile(target, 'utf8')).resolves.toBe('new')
|
||||
})
|
||||
|
||||
it('leaves no temp files behind', async () => {
|
||||
const target = path.join(workDir, 'file.txt')
|
||||
|
||||
writeFileAtomicSync(target, 'content')
|
||||
|
||||
await expect(readdir(workDir)).resolves.toEqual(['file.txt'])
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { bridgeWebSocket, type WebSocketPeer } from '../../src/utils/websocket-bridge'
|
||||
import {
|
||||
bridgeWebSocket,
|
||||
forwardPeerMessage,
|
||||
MAX_PEER_BUFFERED_BYTES,
|
||||
type WebSocketBridge,
|
||||
type WebSocketPeer,
|
||||
} from '../../src/utils/websocket-bridge'
|
||||
|
||||
type Listener = (event: unknown) => void
|
||||
|
||||
@@ -28,21 +34,25 @@ class FakeUpstream {
|
||||
interface FakePeer extends WebSocketPeer {
|
||||
sent: Array<string | Uint8Array>
|
||||
closeCalls: Array<{ code?: number; reason?: string }>
|
||||
buffered: number
|
||||
}
|
||||
|
||||
function createPeer(): FakePeer {
|
||||
const sent: Array<string | Uint8Array> = []
|
||||
const closeCalls: Array<{ code?: number; reason?: string }> = []
|
||||
return {
|
||||
sent,
|
||||
closeCalls,
|
||||
const peer: FakePeer = {
|
||||
sent: [],
|
||||
closeCalls: [],
|
||||
buffered: 0,
|
||||
send(data) {
|
||||
sent.push(data)
|
||||
peer.sent.push(data)
|
||||
},
|
||||
close(code, reason) {
|
||||
closeCalls.push({ code, reason })
|
||||
peer.closeCalls.push({ code, reason })
|
||||
},
|
||||
bufferedAmount() {
|
||||
return peer.buffered
|
||||
},
|
||||
}
|
||||
return peer
|
||||
}
|
||||
|
||||
function asUpstream(upstream: FakeUpstream): WebSocket {
|
||||
@@ -111,14 +121,32 @@ describe('bridgeWebSocket', () => {
|
||||
expect(peer.closeCalls).toEqual([{ code: 1011, reason: undefined }])
|
||||
})
|
||||
|
||||
it('applies a custom close-code mapper', () => {
|
||||
it('closes the upstream and peer with 1013 when the peer buffer overflows', () => {
|
||||
const upstream = new FakeUpstream()
|
||||
const peer = createPeer()
|
||||
bridgeWebSocket(asUpstream(upstream), peer, { mapCloseCode: () => 4000 })
|
||||
peer.buffered = MAX_PEER_BUFFERED_BYTES + 1
|
||||
|
||||
upstream.emit('close', { code: 1006 })
|
||||
bridgeWebSocket(asUpstream(upstream), peer)
|
||||
upstream.emit('message', { data: 'overflow' })
|
||||
|
||||
expect(peer.closeCalls).toEqual([{ code: 4000, reason: undefined }])
|
||||
expect(peer.closeCalls).toEqual([{ code: 1013, reason: 'Client too slow' }])
|
||||
expect(upstream.close).toHaveBeenCalledTimes(1)
|
||||
|
||||
upstream.emit('close', { code: 1000 })
|
||||
expect(peer.closeCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps bridging while the peer buffer stays within the limit', () => {
|
||||
const upstream = new FakeUpstream()
|
||||
const peer = createPeer()
|
||||
peer.buffered = MAX_PEER_BUFFERED_BYTES
|
||||
|
||||
bridgeWebSocket(asUpstream(upstream), peer)
|
||||
upstream.emit('message', { data: 'within limit' })
|
||||
|
||||
expect(peer.sent).toEqual(['within limit'])
|
||||
expect(peer.closeCalls).toEqual([])
|
||||
expect(upstream.close).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('closes the upstream only once and ignores later sends', () => {
|
||||
@@ -133,3 +161,27 @@ describe('bridgeWebSocket', () => {
|
||||
expect(upstream.sent).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('forwardPeerMessage', () => {
|
||||
function createBridge(sent: Array<string | ArrayBuffer | Uint8Array>): WebSocketBridge {
|
||||
return {
|
||||
send(data) {
|
||||
sent.push(data)
|
||||
},
|
||||
close() {},
|
||||
}
|
||||
}
|
||||
|
||||
it('forwards strings, ArrayBuffers and Blobs to the bridge', async () => {
|
||||
const sent: Array<string | ArrayBuffer | Uint8Array> = []
|
||||
const bridge = createBridge(sent)
|
||||
|
||||
await forwardPeerMessage(bridge, 'plain text')
|
||||
await forwardPeerMessage(bridge, new Uint8Array([1, 2]).buffer)
|
||||
await forwardPeerMessage(bridge, new Blob(['blob body']))
|
||||
|
||||
expect(sent[0]).toBe('plain text')
|
||||
expect(sent[1]).toEqual(new Uint8Array([1, 2]).buffer)
|
||||
expect(new TextDecoder().decode(sent[2] as ArrayBuffer)).toBe('blob body')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user