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:
Chris Scott committed 2026-10-03 10:00:33 -04:00
1 parent 16b91ccf02
commit c60a9b35f2
72 files changed
+2039 -596

No files matched your search

@@ -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: {
+125 -10
View File
@@ -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()
})
})
+4
View File
@@ -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
},
}
}