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

+2 -7
View File
@@ -1,6 +1,7 @@
import { logger } from '../../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { createOpenCodeApi, type OpenCodeApi } from '@opencode-manager/shared/opencode'
import { filterProxyHeaders } from '../../utils/proxy-headers'
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from './upstream'
@@ -73,13 +74,7 @@ export class FetchOpenCodeClient implements OpenCodeClient {
body: req.body,
})
const filteredHeaders: Record<string, string> = {}
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
response.headers.forEach((value, key) => {
if (!skipHeaders.has(key.toLowerCase())) {
filteredHeaders[key] = value
}
})
const filteredHeaders = filterProxyHeaders(response.headers)
const noBodyStatuses = new Set([101, 204, 205, 304])
if (noBodyStatuses.has(response.status)) {
+58 -28
View File
@@ -2,17 +2,28 @@ import { randomBytes } from 'node:crypto'
import { Hono } from 'hono'
import type { Context, MiddlewareHandler } from 'hono'
import { createNodeWebSocket, type NodeWebSocket } from '@hono/node-ws'
import type { PreviewPort } from '@opencode-manager/shared/schemas'
import { AUTH_COOKIE_PREFIX } from '../../auth/cookies'
import { buildProxyResponseHeaders, filterProxyHeaders } from '../../utils/proxy-headers'
import { bridgeWebSocket, type WebSocketBridge } from '../../utils/websocket-bridge'
import {
bridgeWebSocket,
forwardPeerMessage,
peerBufferedAmount,
type WebSocketBridge,
} from '../../utils/websocket-bridge'
export const PREVIEW_COOKIE = 'ocm_preview'
const START_TOKEN_TTL_MS = 60_000
const SESSION_TTL_MS = 12 * 60 * 60 * 1000
const MANAGER_COOKIE_PREFIXES = ['opencode.', '__Secure-opencode.', '__Host-opencode.']
const MANAGER_COOKIE_PREFIXES = [
`${AUTH_COOKIE_PREFIX}.`,
`__Secure-${AUTH_COOKIE_PREFIX}.`,
`__Host-${AUTH_COOKIE_PREFIX}.`,
]
export type PreviewHost = '127.0.0.1' | '::1'
export type PreviewHost = PreviewPort['host']
export interface PreviewSession {
id: string
@@ -76,21 +87,32 @@ export class PreviewSessionStore {
}
}
export function stripManagerCookies(cookieHeader: string | undefined): string | undefined {
function readCookieName(cookie: string): string {
const separator = cookie.indexOf('=')
return (separator === -1 ? cookie : cookie.slice(0, separator)).trim()
}
function isManagerCookieName(name: string): boolean {
return name === PREVIEW_COOKIE || MANAGER_COOKIE_PREFIXES.some((prefix) => name.startsWith(prefix))
}
function stripManagerCookies(cookieHeader: string | undefined): string | undefined {
if (!cookieHeader) return undefined
const kept = cookieHeader
.split(';')
.map((part) => part.trim())
.filter((part) => {
if (!part) return false
const separator = part.indexOf('=')
const name = separator === -1 ? part : part.slice(0, separator)
if (name === PREVIEW_COOKIE) return false
return !MANAGER_COOKIE_PREFIXES.some((prefix) => name.startsWith(prefix))
})
.filter((part) => part.length > 0 && !isManagerCookieName(readCookieName(part)))
return kept.length > 0 ? kept.join('; ') : undefined
}
function stripPreviewSetCookies(headers: Headers): void {
const kept = headers.getSetCookie().filter((cookie) => !isManagerCookieName(readCookieName(cookie)))
headers.delete('set-cookie')
for (const cookie of kept) {
headers.append('set-cookie', cookie)
}
}
function readPreviewCookie(cookieHeader: string | undefined): string | null {
if (!cookieHeader) return null
for (const part of cookieHeader.split(';')) {
@@ -140,8 +162,24 @@ function isWebSocketUpgrade(c: Context): boolean {
}
function upstreamWebSocketUrl(session: PreviewSession, requestUrl: URL): string {
return `${previewUpstreamOrigin(session, 'ws')}${requestUrl.pathname}${requestUrl.search}`
}
function previewUpstreamOrigin(session: PreviewSession, protocol: 'http' | 'ws'): string {
const targetHost = session.host === '::1' ? '[::1]' : 'localhost'
return `ws://${targetHost}:${session.port}${requestUrl.pathname}${requestUrl.search}`
return `${protocol}://${targetHost}:${session.port}`
}
function resolveRedirectPath(requestUrl: URL, requestedPath: string): string {
if (!requestedPath) return '/'
let resolved: URL
try {
resolved = new URL(requestedPath, requestUrl)
} catch {
return '/'
}
if (resolved.origin !== requestUrl.origin) return '/'
return `${resolved.pathname}${resolved.search}${resolved.hash}`
}
function parseProtocols(header: string | undefined): string[] {
@@ -163,10 +201,11 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
}
const requestedPath = c.req.query('path') ?? ''
const location = requestedPath.startsWith('/') && !requestedPath.startsWith('//') ? requestedPath : '/'
const requestUrl = new URL(c.req.url)
const location = resolveRedirectPath(requestUrl, requestedPath)
const forwardedProto = c.req.header('x-forwarded-proto')?.toLowerCase()
const isSecure = forwardedProto === 'https' || new URL(c.req.url).protocol === 'https:'
const isSecure = forwardedProto === 'https' || requestUrl.protocol === 'https:'
const cookie = `${PREVIEW_COOKIE}=${sessionId}; HttpOnly; SameSite=Lax; Path=/${isSecure ? '; Secure' : ''}`
return new Response(null, { status: 302, headers: { location, 'set-cookie': cookie } })
@@ -212,22 +251,12 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
bridge = bridgeWebSocket(upstream, {
send: (data) => ws.send(data),
close: (code, reason) => ws.close(code, reason),
bufferedAmount: () => peerBufferedAmount(ws),
})
},
async onMessage(event) {
if (!bridge) return
const data = event.data
if (typeof data === 'string') {
bridge.send(data)
return
}
if (data instanceof Blob) {
bridge.send(await data.arrayBuffer())
return
}
if (data instanceof ArrayBuffer) {
bridge.send(data)
}
await forwardPeerMessage(bridge, event.data)
},
onClose() {
bridge?.close()
@@ -245,8 +274,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
}
const url = new URL(c.req.url)
const targetHost = session.host === '::1' ? '[::1]' : 'localhost'
const target = `http://${targetHost}:${session.port}${url.pathname}${url.search}`
const target = `${previewUpstreamOrigin(session, 'http')}${url.pathname}${url.search}`
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
@@ -256,6 +284,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
headers['content-encoding'] = contentEncoding
}
headers['host'] = `localhost:${session.port}`
headers['accept-encoding'] = 'identity'
const strippedCookies = stripManagerCookies(cookieHeader)
if (strippedCookies) {
headers['cookie'] = strippedCookies
@@ -275,6 +304,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
})
const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers)
stripPreviewSetCookies(responseHeaders)
const location = responseHeaders.get('location')
if (location) {
const rewritten = rewriteLocalLocation(location, session.port)
+12 -10
View File
@@ -1,14 +1,9 @@
import { readFile, readdir, readlink } from 'node:fs/promises'
import { ENV } from '@opencode-manager/shared/config/env'
import type { PreviewPort } from '@opencode-manager/shared/schemas'
import { executeCommand } from '../../utils/process'
export interface PreviewPortEntry {
port: number
host: '127.0.0.1' | '::1'
pid: number | null
command: string | null
cwd: string | null
}
export type PreviewPortEntry = Omit<PreviewPort, 'inDirectory'>
export interface ParsedProcNetSocket {
port: number
@@ -192,8 +187,9 @@ function dedupeByPort(entries: PreviewPortEntry[]): PreviewPortEntry[] {
return result
}
async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, number>> {
async function mapInodesToPids(deps: PortDiscoveryDeps, wantedInodes: ReadonlySet<string>): Promise<Map<string, number>> {
const map = new Map<string, number>()
if (wantedInodes.size === 0) return map
let entries: string[]
try {
entries = await deps.readdir('/proc')
@@ -201,6 +197,7 @@ async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, num
return map
}
for (const entry of entries) {
if (map.size >= wantedInodes.size) break
if (!/^\d+$/.test(entry)) continue
const fdDir = `/proc/${entry}/fd`
let fds: string[]
@@ -217,7 +214,8 @@ async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, num
continue
}
const match = /^socket:\[(\d+)\]$/.exec(target)
if (match?.[1]) map.set(match[1], Number.parseInt(entry, 10))
const inode = match?.[1]
if (inode && wantedInodes.has(inode)) map.set(inode, Number.parseInt(entry, 10))
}
}
return map
@@ -252,7 +250,11 @@ async function listLinuxPorts(deps: PortDiscoveryDeps): Promise<PreviewPortEntry
}
if (sockets.length === 0) return []
const inodeToPid = await mapInodesToPids(deps)
const wantedInodes = new Set<string>()
for (const socket of sockets) {
if (socket.inode) wantedInodes.add(socket.inode)
}
const inodeToPid = await mapInodesToPids(deps, wantedInodes)
const processMeta = new Map<number, { command: string | null; cwd: string | null }>()
const entries: PreviewPortEntry[] = []
for (const socket of sockets) {
+66 -36
View File
@@ -15,11 +15,12 @@ import {
type RunProjectActionResponse,
type WorktreeSetupResult,
} from '@opencode-manager/shared/schemas'
import { isRunningActionTerminal } from '@opencode-manager/shared/utils'
import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries'
import { executeCommand } from '../utils/process'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
import { canonicalPathSync } from '../utils/fs-safe'
import { canonicalPathSync, writeFileAtomicSync } from '../utils/fs-safe'
import type { GitService } from './git/GitService'
import type { GitAuthService } from './git-auth'
import type { TerminalService } from './terminal'
@@ -28,6 +29,7 @@ const PROJECT_ACTIONS_KEY = 'projectActions'
const WORKTREE_SETUP_KEY = 'worktreeSetupCommands'
const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash'
const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json')
const REPO_CONFIG_SYMLINK_MESSAGE = '.ocm/project.json must not be a symbolic link'
export interface RepoFileState {
exists: boolean
@@ -50,8 +52,8 @@ interface RepoFileSnapshot {
export class ProjectConfigError extends Error {
constructor(
public status: number,
message: string,
public status: number,
public code?: string,
public details?: unknown,
) {
@@ -85,7 +87,7 @@ export class ProjectConfigService {
const ids = new Set<string>()
for (const action of actions) {
if (ids.has(action.id)) {
throw new ProjectConfigError(400, 'Duplicate action id')
throw new ProjectConfigError('Duplicate action id', 400)
}
ids.add(action.id)
}
@@ -144,6 +146,7 @@ export class ProjectConfigService {
exists: repoFile.exists,
trusted,
hash: repoFile.hash,
executable: repoFile.file ? this.buildRepoFileExecutable(repoFile.file) : null,
...(repoFile.error ? { error: repoFile.error } : {}),
warnings,
},
@@ -178,11 +181,11 @@ export class ProjectConfigService {
const config = await this.getConfig(repo, directory)
const action = config.actions.find((item) => item.id === actionId)
if (!action) {
throw new ProjectConfigError(404, 'Action not found')
throw new ProjectConfigError('Action not found', 404)
}
if (action.source === 'repo' && !config.repoFile.trusted) {
throw new ProjectConfigError(409, 'Repository commands are not trusted', 'REPO_CONFIG_UNTRUSTED', {
throw new ProjectConfigError('Repository commands are not trusted', 409, 'REPO_CONFIG_UNTRUSTED', {
hash: config.repoFile.hash,
})
}
@@ -190,9 +193,7 @@ export class ProjectConfigService {
const key = this.actionRunKey(directory, actionId)
return this.enqueueActionRun(key, async () => {
const terminals = await terminalService.list(directory)
const running = terminals.find(
(terminal) => terminal.kind === 'action' && terminal.actionId === actionId && terminal.status === 'running',
)
const running = terminals.find((terminal) => isRunningActionTerminal(terminal, actionId))
const terminal =
running ??
(await terminalService.create(directory, {
@@ -288,34 +289,53 @@ export class ProjectConfigService {
readRepoFile(directory: string): RepoFileState {
const filePath = this.getRepoFilePath(directory)
if (!fs.existsSync(filePath)) {
return { exists: false, file: null, hash: null }
}
try {
const parsed = RepoProjectFileSchema.safeParse(JSON.parse(fs.readFileSync(filePath, 'utf8')))
if (this.isSymbolicLink(path.dirname(filePath)) || this.isSymbolicLink(filePath)) {
return { exists: true, file: null, hash: null, error: REPO_CONFIG_SYMLINK_MESSAGE }
}
if (!fs.existsSync(filePath)) {
return { exists: false, file: null, hash: null }
}
let parsedJson: unknown
try {
parsedJson = JSON.parse(fs.readFileSync(filePath, 'utf8'))
} catch {
return { exists: true, file: null, hash: null, error: 'Invalid JSON' }
}
const parsed = RepoProjectFileSchema.safeParse(parsedJson)
if (!parsed.success) {
return { exists: true, file: null, hash: null, error: 'Invalid repository config' }
return { exists: true, file: null, hash: null, error: 'Does not match the project file schema' }
}
return { exists: true, file: parsed.data, hash: this.hashRepoFile(parsed.data) }
} catch (error: unknown) {
return { exists: true, file: null, hash: null, error: getErrorMessage(error) }
} catch {
return { exists: fs.existsSync(filePath), file: null, hash: null, error: 'Invalid repository config' }
}
}
buildRepoFileExecutable(file: RepoProjectFile): NonNullable<ProjectConfigResponse['repoFile']['executable']> {
return {
actions: (file.projectActions ?? []).map((action) => ({
id: action.id,
name: action.name,
command: action.command,
url: action.url ?? null,
autoOpenUrl: action.autoOpenUrl,
})),
setup: file.setupWorktree ?? [],
}
}
hashRepoFile(file: RepoProjectFile): string {
const executable = {
actions: (file.projectActions ?? []).map(({ id, command, url }) => ({ id, command, url: url ?? null })),
setup: file.setupWorktree ?? [],
}
return createHash('sha256').update(JSON.stringify(executable)).digest('hex')
return createHash('sha256').update(JSON.stringify(this.buildRepoFileExecutable(file))).digest('hex')
}
async trustRepoFile(repo: Repo, directory: string, hash: string): Promise<void> {
const projectRepo = await this.resolveProjectRepo(repo)
const repoFile = this.readRepoFile(directory)
if (repoFile.hash === null || repoFile.hash !== hash) {
throw new ProjectConfigError(409, 'Repository config changed', 'REPO_CONFIG_CHANGED')
throw new ProjectConfigError('Repository config changed', 409, 'REPO_CONFIG_CHANGED')
}
this.setRepoTrust(projectRepo, repoFile.hash)
}
@@ -323,6 +343,7 @@ export class ProjectConfigService {
async moveItem(repo: Repo, directory: string, request: MoveProjectItemRequest): Promise<void> {
const projectRepo = await this.resolveProjectRepo(repo)
const filePath = this.getRepoFilePath(directory)
this.assertRepoFilePathNotSymlink(filePath)
const state = this.readRepoFile(directory)
const commit =
request.to === 'repo'
@@ -334,7 +355,7 @@ export class ProjectConfigService {
private planMoveToRepo(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit {
if (state.exists && !state.file) {
throw new ProjectConfigError(409, 'Repository config is invalid')
throw new ProjectConfigError('Repository config is invalid', 409)
}
const file: RepoProjectFile = state.file ? { ...state.file } : { version: 1 }
@@ -343,11 +364,11 @@ export class ProjectConfigService {
const personal = this.getPersonalActions(projectRepo)
const action = personal.find((item) => item.id === request.id)
if (!action) {
throw new ProjectConfigError(404, 'Action not found')
throw new ProjectConfigError('Action not found', 404)
}
const repoActions = file.projectActions ?? []
if (repoActions.some((existing) => existing.id === action.id)) {
throw new ProjectConfigError(409, 'Action already exists in repository config')
throw new ProjectConfigError('Action already exists in repository config', 409)
}
const nextFile: RepoProjectFile = { ...file, projectActions: [...repoActions, action] }
this.assertRepoFileValid(nextFile)
@@ -361,7 +382,7 @@ export class ProjectConfigService {
const personal = this.getPersonalSetup(projectRepo)
const index = personal.indexOf(request.command)
if (index === -1) {
throw new ProjectConfigError(404, 'Setup command not found')
throw new ProjectConfigError('Setup command not found', 404)
}
const nextFile: RepoProjectFile = {
...file,
@@ -380,14 +401,14 @@ export class ProjectConfigService {
private planMoveToPersonal(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit {
const file = state.file
if (!file) {
throw new ProjectConfigError(404, 'Item not found')
throw new ProjectConfigError('Item not found', 404)
}
if (request.kind === 'action') {
const repoActions = file.projectActions ?? []
const action = repoActions.find((item) => item.id === request.id)
if (!action) {
throw new ProjectConfigError(404, 'Action not found')
throw new ProjectConfigError('Action not found', 404)
}
const nextFile = this.pruneRepoFile({
...file,
@@ -406,7 +427,7 @@ export class ProjectConfigService {
const repoSetup = file.setupWorktree ?? []
const index = repoSetup.indexOf(request.command)
if (index === -1) {
throw new ProjectConfigError(404, 'Setup command not found')
throw new ProjectConfigError('Setup command not found', 404)
}
const nextFile = this.pruneRepoFile({
...file,
@@ -494,8 +515,8 @@ export class ProjectConfigService {
const result = RepoProjectFileSchema.safeParse(file)
if (!result.success) {
throw new ProjectConfigError(
409,
'Repository config limit exceeded',
409,
'PROJECT_CONFIG_LIMIT_EXCEEDED',
result.error.flatten(),
)
@@ -506,8 +527,8 @@ export class ProjectConfigService {
const result = WorktreeSetupCommandsSchema.safeParse(commands)
if (!result.success) {
throw new ProjectConfigError(
409,
'Personal setup command limit exceeded',
409,
'PROJECT_CONFIG_LIMIT_EXCEEDED',
result.error.flatten(),
)
@@ -523,17 +544,26 @@ export class ProjectConfigService {
}
private writeRepoFile(filePath: string, file: RepoProjectFile): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true })
const tmpPath = `${filePath}.tmp`
writeFileAtomicSync(filePath, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o644 })
}
private isSymbolicLink(target: string): boolean {
try {
fs.writeFileSync(tmpPath, `${JSON.stringify(file, null, 2)}\n`)
fs.renameSync(tmpPath, filePath)
return fs.lstatSync(target).isSymbolicLink()
} catch (error) {
fs.rmSync(tmpPath, { force: true })
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return false
}
throw error
}
}
private assertRepoFilePathNotSymlink(filePath: string): void {
if (this.isSymbolicLink(path.dirname(filePath)) || this.isSymbolicLink(filePath)) {
throw new ProjectConfigError(REPO_CONFIG_SYMLINK_MESSAGE, 400, 'REPO_CONFIG_SYMLINK')
}
}
private snapshotFile(filePath: string): RepoFileSnapshot {
try {
return { exists: true, content: fs.readFileSync(filePath) }
+3 -1
View File
@@ -1194,6 +1194,7 @@ export async function getSiblingRepos(
repoId: number,
gitEnv: Record<string, string>,
openCodeClient?: OpenCodeClient,
options: { includeBranch?: boolean } = {},
): Promise<Array<Repo & { currentBranch: string | undefined; worktreeStrategy?: string }>> {
const settingsService = new SettingsService(database)
const settings = settingsService.getSettings()
@@ -1217,10 +1218,11 @@ export async function getSiblingRepos(
.filter((entry) => entry.projectId === targetProjectId)
.map((entry) => entry.repo)
const includeBranch = options.includeBranch ?? true
const repoSiblings = await Promise.all(
matching.map(async (repo) => ({
...repo,
currentBranch: (await getCurrentBranch(repo, gitEnv)) ?? undefined,
currentBranch: includeBranch ? (await getCurrentBranch(repo, gitEnv)) ?? undefined : undefined,
})),
)