mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(sandbox): add KVM-backed agent sandboxing via microsandbox
This commit is contained in:
1 parent
1d477bdee4
commit
aa3fb48a62
80 files changed
+17304
-204
No files matched your search
+14
-16
@@ -39,6 +39,7 @@ import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from './routes/opencode-auth-proxy'
|
||||
import { sseAggregator } from './services/sse-aggregator'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
|
||||
import { SettingsService } from './services/settings'
|
||||
@@ -50,6 +51,7 @@ import { CredentialProvider } from './services/credential-provider'
|
||||
import { ScheduleWorktreeManager } from './services/schedule-worktree'
|
||||
import { migrateGlobalSkills } from './services/skills'
|
||||
import { installAssistantWorkspace } from './services/assistant-mode'
|
||||
import { stopWorkspaceSandboxOnShutdown } from './services/sandbox/runtime'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
import { OpenCodeRestartCoordinator } from './services/opencode-restart-coordinator'
|
||||
@@ -104,7 +106,10 @@ app.use('/*', cors({
|
||||
const db = initializeDatabase(DB_PATH)
|
||||
const auth = createAuth(db)
|
||||
const requireAuth = createAuthMiddleware(auth)
|
||||
const openCodeClient = createOpenCodeClient(() => new SettingsService(db).getOpenCodeServerPassword())
|
||||
const openCodeClient = createOpenCodeClient(
|
||||
() => new SettingsService(db).getOpenCodeServerPassword(),
|
||||
() => opencodeServerManager.getEffectiveServerHost(),
|
||||
)
|
||||
|
||||
import { DEFAULT_AGENTS_MD } from './constants'
|
||||
|
||||
@@ -293,6 +298,7 @@ try {
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
opencodeServerManager.setLifecycleInitialized(openCodeStatus.healthy)
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
} else {
|
||||
@@ -373,21 +379,7 @@ protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
|
||||
app.route('/api', protectedApi)
|
||||
|
||||
app.post('/api/opencode/mcp/:name/auth', requireAuth, async (c) => {
|
||||
const serverName = c.req.param('name')
|
||||
const directory = c.req.query('directory')
|
||||
return openCodeClient.startMcpAuth(serverName, directory)
|
||||
})
|
||||
|
||||
app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => {
|
||||
const serverName = c.req.param('name')
|
||||
const directory = c.req.query('directory')
|
||||
return openCodeClient.authenticateMcp(serverName, directory)
|
||||
})
|
||||
|
||||
app.all('/api/opencode/*', requireAuth, async (c) => {
|
||||
return openCodeClient.forwardRaw(c.req.raw)
|
||||
})
|
||||
app.route('/api/opencode', createAuthenticatedOpenCodeProxyRoutes(openCodeClient, requireAuth))
|
||||
|
||||
const isProduction = ENV.SERVER.NODE_ENV === 'production'
|
||||
|
||||
@@ -483,6 +475,12 @@ const shutdown = async (signal: string) => {
|
||||
} catch (error) {
|
||||
logger.error('Error during shutdown:', error)
|
||||
}
|
||||
try {
|
||||
await stopWorkspaceSandboxOnShutdown(db)
|
||||
logger.info('Workspace sandbox stopped')
|
||||
} catch (error) {
|
||||
logger.error('Error stopping workspace sandbox:', error)
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { compareVersions } from '../utils/version-utils'
|
||||
import { githubFetch } from '../utils/github'
|
||||
import { logger } from '../utils/logger'
|
||||
import { SandboxRuntimeService } from '../services/sandbox/runtime'
|
||||
|
||||
const GITHUB_REPO_OWNER = 'chriswritescode-dev'
|
||||
const GITHUB_REPO_NAME = 'opencode-manager'
|
||||
@@ -94,6 +96,22 @@ export function createHealthRoutes(db: Database, openCodeSupervisor?: OpenCodeSu
|
||||
opencodeRestartPending: opencodeServerManager.isRestartPending(),
|
||||
}
|
||||
|
||||
try {
|
||||
const runtimeStatus = new SandboxRuntimeService(db).getStatus()
|
||||
response.sandbox = {
|
||||
...runtimeStatus,
|
||||
enforced: opencodeServerManager.isSandboxEnforced(),
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to collect sandbox status', error)
|
||||
response.sandbox = {
|
||||
available: false,
|
||||
enabled: false,
|
||||
enforced: opencodeServerManager.isSandboxEnforced(),
|
||||
reason: error instanceof Error ? error.message : 'sandbox status unavailable',
|
||||
}
|
||||
}
|
||||
|
||||
if (lifecycle) {
|
||||
response.opencodeLifecycle = lifecycle
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror'
|
||||
import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces'
|
||||
import { createInternalAssistantRoutes } from './assistant'
|
||||
import { createInternalGitCredentialsRoutes } from './git-credentials'
|
||||
import { createInternalSandboxRoutes } from './sandbox'
|
||||
|
||||
export function createInternalRoutes(
|
||||
db: Database,
|
||||
@@ -36,5 +37,6 @@ export function createInternalRoutes(
|
||||
app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db))
|
||||
app.route('/assistant', createInternalAssistantRoutes(openCodeClient))
|
||||
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
|
||||
app.route('/sandbox', createInternalSandboxRoutes(db))
|
||||
return app
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { existsSync, mkdtempSync, readdirSync, statSync } from 'fs'
|
||||
import * as fsp from 'fs/promises'
|
||||
import { createReadStream } from 'fs'
|
||||
import { dirname, join } from 'path'
|
||||
import { Readable } from 'stream'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
@@ -94,11 +95,23 @@ export interface ExtractResult {
|
||||
staging: string
|
||||
}
|
||||
|
||||
function isStdinClosedError(error: unknown): boolean {
|
||||
if (typeof error !== 'object' || error === null) return false
|
||||
const code = (error as { code?: unknown }).code
|
||||
return code === 'ERR_STREAM_PREMATURE_CLOSE' || code === 'EPIPE'
|
||||
}
|
||||
|
||||
export async function extractPartsToStaging(uploadId: string, totalParts: number, gzip: boolean): Promise<ExtractResult> {
|
||||
if (!isValidTotalParts(totalParts)) {
|
||||
throw new Error(TOTAL_PARTS_INVALID_MESSAGE)
|
||||
}
|
||||
|
||||
for (let i = 0; i < totalParts; i++) {
|
||||
if (!existsSync(getPartPath(uploadId, i))) {
|
||||
throw new Error(`missing part ${i} for upload ${uploadId}`)
|
||||
}
|
||||
}
|
||||
|
||||
const stagingParent = getStagingRoot()
|
||||
mkdirSyncSafe(stagingParent)
|
||||
const staging = mkdtempSync(join(stagingParent, 'recv-'))
|
||||
@@ -110,30 +123,40 @@ export async function extractPartsToStaging(uploadId: string, totalParts: number
|
||||
const stderrChunks: Buffer[] = []
|
||||
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
|
||||
|
||||
const tarDone = new Promise<void>((resolve, reject) => {
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) resolve()
|
||||
else {
|
||||
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
|
||||
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ''}`))
|
||||
}
|
||||
})
|
||||
const tarDone = new Promise<number | null>((resolve, reject) => {
|
||||
child.on('close', (code) => resolve(code))
|
||||
child.on('error', reject)
|
||||
})
|
||||
tarDone.catch(() => {})
|
||||
|
||||
try {
|
||||
for (let i = 0; i < totalParts; i++) {
|
||||
const partPath = getPartPath(uploadId, i)
|
||||
if (!existsSync(partPath)) {
|
||||
throw new Error(`missing part ${i} for upload ${uploadId}`)
|
||||
let writeError: unknown = null
|
||||
const partStreams = Readable.from(
|
||||
(async function* () {
|
||||
for (let i = 0; i < totalParts; i++) {
|
||||
for await (const chunk of createReadStream(getPartPath(uploadId, i))) {
|
||||
yield chunk
|
||||
}
|
||||
}
|
||||
await pipeline(createReadStream(partPath), child.stdin, { end: i === totalParts - 1 })
|
||||
}
|
||||
await tarDone
|
||||
})(),
|
||||
)
|
||||
try {
|
||||
await pipeline(partStreams, child.stdin, { end: true })
|
||||
} catch (err) {
|
||||
writeError = err
|
||||
}
|
||||
|
||||
if (writeError && !isStdinClosedError(writeError)) {
|
||||
if (!child.killed) child.kill('SIGKILL')
|
||||
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
|
||||
throw err
|
||||
throw writeError
|
||||
}
|
||||
|
||||
const exitCode = await tarDone
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
|
||||
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
|
||||
throw new Error(`tar exited with code ${exitCode}${stderr ? `: ${stderr}` : ''}`)
|
||||
}
|
||||
|
||||
let extractedRoot = staging
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SandboxRuntimeService } from '../../services/sandbox/runtime'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
const SandboxCommandRequestSchema = z.object({
|
||||
directory: z.string().min(1),
|
||||
command: z.string().min(1),
|
||||
enforced: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export function createInternalSandboxRoutes(db: Database) {
|
||||
const app = new Hono()
|
||||
|
||||
app.post('/command', async (c) => {
|
||||
let body: unknown
|
||||
try {
|
||||
body = await c.req.json()
|
||||
} catch {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
const parsed = SandboxCommandRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
return c.json(
|
||||
await new SandboxRuntimeService(db).planCommand(parsed.data.directory, parsed.data.command, parsed.data.enforced === true),
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error('Failed to plan sandbox command', error)
|
||||
return c.json({ mode: 'blocked', reason: error instanceof Error ? error.message : String(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import {
|
||||
decideSandboxMutationBody,
|
||||
decideSandboxProxyBlock,
|
||||
isSandboxAuthWrite,
|
||||
isSandboxConfigMutation,
|
||||
isSandboxMcpAdd,
|
||||
} from '../services/opencode/proxy-policy'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
|
||||
export function createAuthenticatedOpenCodeProxyRoutes(
|
||||
openCodeClient: OpenCodeClient,
|
||||
requireAuth: MiddlewareHandler,
|
||||
): Hono {
|
||||
const app = new Hono()
|
||||
|
||||
app.all('/*', requireAuth, async (c) => {
|
||||
if (!opencodeServerManager.isLifecycleInitialized()) {
|
||||
return c.json({ error: 'OpenCode lifecycle initialization is incomplete; refusing to proxy to an unmanaged server' }, 503)
|
||||
}
|
||||
|
||||
const enforced = opencodeServerManager.isSandboxEnforced()
|
||||
const pathSuffix = new URL(c.req.url).pathname.replace(/^\/api\/opencode/, '') || '/'
|
||||
const decision = decideSandboxProxyBlock(enforced, c.req.method, pathSuffix)
|
||||
if (decision.blocked) {
|
||||
return c.json({ error: decision.reason }, 403)
|
||||
}
|
||||
if (isSandboxConfigMutation(enforced, c.req.method, pathSuffix) || isSandboxMcpAdd(enforced, c.req.method, pathSuffix) || isSandboxAuthWrite(enforced, c.req.method, pathSuffix)) {
|
||||
const rawBody = await c.req.text()
|
||||
const bodyDecision = decideSandboxMutationBody(enforced, c.req.method, pathSuffix, rawBody)
|
||||
if (bodyDecision.kind === 'reject') {
|
||||
return c.json({ error: bodyDecision.reason }, 403)
|
||||
}
|
||||
const headers = new Headers(c.req.raw.headers)
|
||||
headers.delete('content-length')
|
||||
return openCodeClient.forwardRaw(new Request(c.req.url, {
|
||||
method: c.req.method,
|
||||
headers,
|
||||
body: bodyDecision.kind === 'sanitized' ? bodyDecision.body : rawBody,
|
||||
}))
|
||||
}
|
||||
return openCodeClient.forwardRaw(c.req.raw)
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -3,6 +3,14 @@ import type { Database } from 'bun:sqlite'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { createInternalTokenMiddleware } from '../auth/internal-token-middleware'
|
||||
import type { SettingsService } from '../services/settings'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import {
|
||||
decideSandboxMutationBody,
|
||||
decideSandboxProxyBlock,
|
||||
isSandboxAuthWrite,
|
||||
isSandboxConfigMutation,
|
||||
isSandboxMcpAdd,
|
||||
} from '../services/opencode/proxy-policy'
|
||||
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
@@ -25,6 +33,10 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
app.use('/*', createInternalTokenMiddleware(db))
|
||||
|
||||
app.all('/*', async (c) => {
|
||||
if (!opencodeServerManager.isLifecycleInitialized()) {
|
||||
return c.json({ error: 'OpenCode lifecycle initialization is incomplete; refusing to proxy to an unmanaged server' }, 503)
|
||||
}
|
||||
|
||||
const connectionHeader = c.req.header('connection')?.toLowerCase() ?? ''
|
||||
const upgradeHeader = c.req.header('upgrade')?.toLowerCase() ?? ''
|
||||
if (connectionHeader.includes('upgrade') && upgradeHeader === 'websocket') {
|
||||
@@ -33,6 +45,11 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
|
||||
const url = new URL(c.req.url)
|
||||
const pathSuffix = url.pathname.replace(/^\/api\/opencode-proxy/, '') || '/'
|
||||
const enforced = opencodeServerManager.isSandboxEnforced()
|
||||
const decision = decideSandboxProxyBlock(enforced, c.req.method, pathSuffix)
|
||||
if (decision.blocked) {
|
||||
return c.json({ error: decision.reason }, 403)
|
||||
}
|
||||
const upstreamUrl = `http://127.0.0.1:${ENV.OPENCODE.PORT}${pathSuffix}${url.search}`
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
@@ -49,7 +66,16 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
|
||||
let requestBody: RequestInit['body'] = undefined
|
||||
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
|
||||
requestBody = c.req.raw.body
|
||||
if (isSandboxConfigMutation(enforced, c.req.method, pathSuffix) || isSandboxMcpAdd(enforced, c.req.method, pathSuffix) || isSandboxAuthWrite(enforced, c.req.method, pathSuffix)) {
|
||||
const rawBody = await c.req.text()
|
||||
const bodyDecision = decideSandboxMutationBody(enforced, c.req.method, pathSuffix, rawBody)
|
||||
if (bodyDecision.kind === 'reject') {
|
||||
return c.json({ error: bodyDecision.reason }, 403)
|
||||
}
|
||||
requestBody = bodyDecision.kind === 'sanitized' ? bodyDecision.body : rawBody
|
||||
} else {
|
||||
requestBody = c.req.raw.body
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -20,6 +20,8 @@ import { createScheduleRoutes } from './schedules'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { ScheduleService } from '../services/schedules'
|
||||
import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { resolveSandboxWorkDirectory } from '../services/sandbox/command'
|
||||
import path from 'path'
|
||||
|
||||
function resolveRepo(database: Database, id: number): Repo | null {
|
||||
@@ -314,7 +316,33 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: body || 'Failed to create workspace' }, response.status as ContentfulStatusCode)
|
||||
}
|
||||
|
||||
return c.json(body ? JSON.parse(body) : { success: true })
|
||||
let workspace: unknown
|
||||
try {
|
||||
workspace = body ? JSON.parse(body) : { success: true }
|
||||
} catch {
|
||||
return c.json({ error: 'Failed to create workspace' }, 500)
|
||||
}
|
||||
|
||||
const workspaceRecord = workspace as { id?: unknown; directory?: unknown } | null
|
||||
if (
|
||||
workspaceRecord &&
|
||||
typeof workspaceRecord.directory === 'string' &&
|
||||
opencodeServerManager.isSandboxEnforced() &&
|
||||
(await resolveSandboxWorkDirectory(workspaceRecord.directory)) === null
|
||||
) {
|
||||
if (typeof workspaceRecord.id === 'string' && workspaceRecord.id.length > 0) {
|
||||
await openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(workspaceRecord.id)}`,
|
||||
directory: repo.fullPath,
|
||||
}).catch(() => {})
|
||||
}
|
||||
return c.json({
|
||||
error: 'OpenCode worktrees are not available while sandboxing is enabled because they are created outside the sandboxed project roots',
|
||||
}, 400)
|
||||
}
|
||||
|
||||
return c.json(workspace)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create workspace:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
|
||||
+152
-28
@@ -13,6 +13,7 @@ import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/sh
|
||||
import {
|
||||
UserPreferencesSchema,
|
||||
OpenCodeConfigSchema,
|
||||
type SandboxPreferences,
|
||||
} from '../types/settings'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
import {
|
||||
@@ -27,7 +28,9 @@ import { logger } from '../utils/logger'
|
||||
import {
|
||||
discoverModelsCached,
|
||||
} from '../utils/discovery-cache'
|
||||
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
|
||||
import { opencodeServerManager, ConfigReloadError, isSandboxVerifiedOpenCodeVersion, getSandboxVerifiedOpenCodeVersions } from '../services/opencode-single-server'
|
||||
import { sanitizeConfigForEnforcementResult, type EnforcementRemovedSections } from '../services/opencode/enforcement-config'
|
||||
import { isSandboxEnforcementActive } from '../services/sandbox/enforcement'
|
||||
import { getOrCreateInternalToken, rotateInternalToken } from '../services/internal-token'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
@@ -83,14 +86,16 @@ function getOpenCodeInstallMethod(): string {
|
||||
|
||||
function getOpenCodeConfigContentToWrite(
|
||||
rawContent: string,
|
||||
sourceConfig: Record<string, unknown>,
|
||||
appliedConfig?: Record<string, unknown>,
|
||||
removedFields?: string[]
|
||||
removedFields?: string[],
|
||||
enforcementRemoved = false,
|
||||
): string {
|
||||
if (!appliedConfig || !removedFields || removedFields.length === 0) {
|
||||
return rawContent
|
||||
if ((removedFields && removedFields.length > 0) || enforcementRemoved) {
|
||||
return JSON.stringify(appliedConfig ?? sourceConfig, null, 2)
|
||||
}
|
||||
|
||||
return JSON.stringify(appliedConfig, null, 2)
|
||||
return rawContent
|
||||
}
|
||||
|
||||
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
|
||||
@@ -215,6 +220,14 @@ function needsOpenCodeRestart(
|
||||
return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field))
|
||||
}
|
||||
|
||||
function sandboxPreferenceChanged(
|
||||
previous: SandboxPreferences | undefined,
|
||||
next: SandboxPreferences | undefined,
|
||||
): boolean {
|
||||
if (next === undefined) return false
|
||||
return JSON.stringify(previous ?? {}) !== JSON.stringify(next)
|
||||
}
|
||||
|
||||
function parseOptionalRepoId(value: string | undefined): number | undefined {
|
||||
if (value === undefined) return undefined
|
||||
const parsed = parseInt(value, 10)
|
||||
@@ -236,6 +249,28 @@ function hasConfiguredPlugins(config: Record<string, unknown> | undefined): bool
|
||||
return Array.isArray(config?.plugin) && config.plugin.length > 0
|
||||
}
|
||||
|
||||
type EnforcementSanitization = {
|
||||
patchTarget: Record<string, unknown>
|
||||
removed: EnforcementRemovedSections
|
||||
}
|
||||
|
||||
function sanitizeConfigPatchForEnforcement(config: Record<string, unknown>): EnforcementSanitization {
|
||||
const { sanitized, removed } = sanitizeConfigForEnforcementResult(config, opencodeServerManager.isSandboxEnforced())
|
||||
return { patchTarget: sanitized, removed }
|
||||
}
|
||||
|
||||
function contentForEnforcedDefaultWrite(
|
||||
rawContent: string,
|
||||
config: Record<string, unknown>,
|
||||
): { content: string; enforcementRemoved: boolean } {
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(config)
|
||||
const enforcementRemoved = Object.keys(sanitization.removed).length > 0
|
||||
if (!enforcementRemoved) {
|
||||
return { content: rawContent, enforcementRemoved }
|
||||
}
|
||||
return { content: JSON.stringify(sanitization.patchTarget, null, 2), enforcementRemoved }
|
||||
}
|
||||
|
||||
function execWithTimeout(
|
||||
command: string | [executable: string, ...args: string[]],
|
||||
timeoutMs: number,
|
||||
@@ -400,6 +435,13 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const currentSettings = settingsService.getSettings(userId)
|
||||
const settings = settingsService.updateSettings(validated.preferences, userId)
|
||||
|
||||
const sandboxChanged = sandboxPreferenceChanged(currentSettings.preferences.sandbox, validated.preferences.sandbox)
|
||||
|
||||
if (sandboxChanged) {
|
||||
logger.info('Sandbox preference changed, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
}
|
||||
|
||||
let serverRestarted = false
|
||||
|
||||
const credentialsChanged = validated.preferences.gitCredentials !== undefined &&
|
||||
@@ -437,7 +479,14 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
app.delete('/', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const currentSettings = settingsService.getSettings(userId)
|
||||
const settings = settingsService.resetSettings(userId)
|
||||
|
||||
if (sandboxPreferenceChanged(currentSettings.preferences.sandbox, settings.preferences.sandbox)) {
|
||||
logger.info('Sandbox preference changed, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
}
|
||||
|
||||
return c.json(settings)
|
||||
} catch (error) {
|
||||
logger.error('Failed to reset settings:', error)
|
||||
@@ -473,8 +522,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
)
|
||||
|
||||
if (hasConfiguredPlugins(provisionalConfig.content)) {
|
||||
const { content: contentToWrite } = contentForEnforcedDefaultWrite(provisionalConfig.rawContent, provisionalConfig.content)
|
||||
const config = settingsService.updateOpenCodeConfig(provisionalConfig.name, {
|
||||
content: provisionalConfig.rawContent,
|
||||
content: contentToWrite,
|
||||
isDefault: true,
|
||||
}, userId)
|
||||
|
||||
@@ -483,7 +533,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, provisionalConfig.rawContent)
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
@@ -491,7 +541,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json(config)
|
||||
}
|
||||
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, provisionalConfig.content)
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(provisionalConfig.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, sanitization.patchTarget)
|
||||
if (!patchResult.success) {
|
||||
settingsService.deleteOpenCodeConfig(provisionalConfig.name, userId)
|
||||
return c.json({
|
||||
@@ -504,8 +555,10 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
provisionalConfig.rawContent,
|
||||
sanitization.patchTarget,
|
||||
patchResult.appliedConfig,
|
||||
patchResult.removedFields
|
||||
patchResult.removedFields,
|
||||
Object.keys(sanitization.removed).length > 0,
|
||||
)
|
||||
const config = settingsService.updateOpenCodeConfig(provisionalConfig.name, {
|
||||
content: contentToWrite,
|
||||
@@ -552,7 +605,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const existingConfig = settingsService.getOpenCodeConfigByName(configName, userId)
|
||||
const previousContent = existingConfig?.content
|
||||
|
||||
const config = settingsService.updateOpenCodeConfig(configName, validated, userId)
|
||||
let config = settingsService.updateOpenCodeConfig(configName, validated, userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
@@ -562,13 +615,22 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
|
||||
if (restartRequired) {
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
const { content: contentToWrite, enforcementRemoved } = contentForEnforcedDefaultWrite(config.rawContent, config.content)
|
||||
if (enforcementRemoved) {
|
||||
const persisted = settingsService.updateOpenCodeConfig(configName, { content: contentToWrite }, userId)
|
||||
if (!persisted) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
config = persisted
|
||||
}
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
logger.info('OpenCode configuration change requires a server restart; deferring until requested')
|
||||
opencodeServerManager.markRestartPending()
|
||||
return c.json({ ...config, restartRequired: true })
|
||||
} else {
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, config.content)
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(config.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, sanitization.patchTarget)
|
||||
if (!patchResult.success) {
|
||||
return c.json({
|
||||
error: 'Config saved but failed to apply',
|
||||
@@ -579,9 +641,14 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
const removedFields = patchResult.removedFields ?? []
|
||||
const contentToWrite = removedFields.length > 0
|
||||
? JSON.stringify(patchResult.appliedConfig ?? config.content, null, 2)
|
||||
: config.rawContent
|
||||
const enforcementRemoved = Object.keys(sanitization.removed).length > 0
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
config.rawContent,
|
||||
sanitization.patchTarget,
|
||||
patchResult.appliedConfig,
|
||||
removedFields,
|
||||
enforcementRemoved,
|
||||
)
|
||||
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
@@ -596,6 +663,17 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
return c.json({ ...persisted, removedFields })
|
||||
}
|
||||
|
||||
if (enforcementRemoved) {
|
||||
logger.info('Config applied with host-execution sections removed by sandbox enforcement')
|
||||
const persisted = settingsService.updateOpenCodeConfig(configName, { content: contentToWrite }, userId)
|
||||
if (!persisted) {
|
||||
return c.json({
|
||||
error: 'OpenCode config was removed while applying sandbox enforcement',
|
||||
}, 409)
|
||||
}
|
||||
return c.json(persisted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,13 +717,20 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
if (hasConfiguredPlugins(existingConfig.content)) {
|
||||
const { content: contentToWrite, enforcementRemoved } = contentForEnforcedDefaultWrite(existingConfig.rawContent, existingConfig.content)
|
||||
if (enforcementRemoved) {
|
||||
const updated = settingsService.updateOpenCodeConfig(configName, { content: contentToWrite }, userId)
|
||||
if (!updated) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
}
|
||||
const config = settingsService.setDefaultOpenCodeConfig(configName, userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, existingConfig.rawContent)
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
@@ -653,7 +738,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json(config)
|
||||
}
|
||||
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, existingConfig.content)
|
||||
const sanitization = sanitizeConfigPatchForEnforcement(existingConfig.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, sanitization.patchTarget)
|
||||
if (!patchResult.success) {
|
||||
return c.json({
|
||||
error: 'Config validation failed',
|
||||
@@ -665,8 +751,10 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
existingConfig.rawContent,
|
||||
sanitization.patchTarget,
|
||||
patchResult.appliedConfig,
|
||||
patchResult.removedFields
|
||||
patchResult.removedFields,
|
||||
Object.keys(sanitization.removed).length > 0,
|
||||
)
|
||||
const updatedConfig = settingsService.updateOpenCodeConfig(configName, {
|
||||
content: contentToWrite,
|
||||
@@ -849,7 +937,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json({ error: 'Failed to get default config after rollback' }, 500)
|
||||
}
|
||||
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
const { content: contentToWrite, enforcementRemoved } = contentForEnforcedDefaultWrite(config.rawContent, config.content)
|
||||
if (enforcementRemoved) {
|
||||
settingsService.updateOpenCodeConfig(config.name, { content: contentToWrite }, userId)
|
||||
}
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Rolled back to config '${rollbackConfig}'`)
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
@@ -896,6 +988,19 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
logger.info(`Current OpenCode version: ${oldVersion}`)
|
||||
|
||||
try {
|
||||
if (isSandboxEnforcementActive(db)) {
|
||||
const verified = getSandboxVerifiedOpenCodeVersions()
|
||||
logger.warn('OpenCode upgrade blocked while sandbox enforcement is active')
|
||||
return c.json({
|
||||
success: false,
|
||||
error: 'OpenCode upgrade is disabled while sandbox enforcement is active',
|
||||
details: `Sandbox enforcement only accepts verified OpenCode builds (${verified.join(', ')}). Disable Agent Sandboxing in Settings and restart the OpenCode server before upgrading.`,
|
||||
oldVersion,
|
||||
newVersion: oldVersion,
|
||||
upgraded: false,
|
||||
}, 409)
|
||||
}
|
||||
|
||||
const installMethod = getOpenCodeInstallMethod()
|
||||
logger.info(`Running opencode upgrade --method ${installMethod} with 90s timeout...`)
|
||||
const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade --method ${installMethod} 2>&1`, 90000)
|
||||
@@ -1003,15 +1108,20 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
published_at: string
|
||||
prerelease: boolean
|
||||
}>
|
||||
|
||||
|
||||
const enforcementActive = isSandboxEnforcementActive(db)
|
||||
const versions = releases
|
||||
.filter(r => !r.prerelease)
|
||||
.map(r => ({
|
||||
version: r.tag_name.replace(/^v/, ''),
|
||||
tag: r.tag_name,
|
||||
name: r.name,
|
||||
publishedAt: r.published_at
|
||||
}))
|
||||
.map(r => {
|
||||
const version = r.tag_name.replace(/^v/, '')
|
||||
return {
|
||||
version,
|
||||
tag: r.tag_name,
|
||||
name: r.name,
|
||||
publishedAt: r.published_at,
|
||||
installable: !enforcementActive || isSandboxVerifiedOpenCodeVersion(version),
|
||||
}
|
||||
})
|
||||
|
||||
const currentVersion = opencodeServerManager.getVersion()
|
||||
|
||||
@@ -1041,6 +1151,18 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
throw new Error('Invalid version format. Must be in MAJOR.MINOR.PATCH format (e.g., 1.2.27)')
|
||||
}
|
||||
|
||||
if (isSandboxEnforcementActive(db) && !isSandboxVerifiedOpenCodeVersion(versionWithoutPrefix)) {
|
||||
const verified = getSandboxVerifiedOpenCodeVersions()
|
||||
logger.warn(`OpenCode v${versionWithoutPrefix} install blocked while sandbox enforcement is active`)
|
||||
return c.json({
|
||||
success: false,
|
||||
error: `OpenCode v${versionWithoutPrefix} is not verified for sandbox enforcement`,
|
||||
details: `Sandbox enforcement only accepts verified OpenCode builds (${verified.join(', ')}).`,
|
||||
oldVersion,
|
||||
newVersion: oldVersion,
|
||||
}, 409)
|
||||
}
|
||||
|
||||
logger.info(`Installing OpenCode version: ${version}`)
|
||||
const versionArg = version.startsWith('v') ? version : `v${version}`
|
||||
const installMethod = getOpenCodeInstallMethod()
|
||||
@@ -1819,11 +1941,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
try {
|
||||
await opencodeServerManager.restart()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
} catch (restartError) {
|
||||
try {
|
||||
settingsService.restoreOpenCodeServerPasswordState(previousPasswordState)
|
||||
await opencodeServerManager.restart()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
sseAggregator.reconnect()
|
||||
} catch (restoreError) {
|
||||
logger.error('Failed to restore OpenCode server auth runtime after restart failure:', restoreError)
|
||||
@@ -1859,6 +1981,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
app.post('/manager-token/rotate', async (c) => {
|
||||
try {
|
||||
const token = rotateInternalToken(db)
|
||||
logger.info('Manager token rotated, marking OpenCode server restart as pending')
|
||||
opencodeServerManager.markRestartPending()
|
||||
return c.json({ token })
|
||||
} catch (error) {
|
||||
logger.error('Failed to rotate manager token:', error)
|
||||
|
||||
@@ -13,8 +13,8 @@ import {
|
||||
ensureDirectoryExists,
|
||||
} from './file-operations'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH } from '@opencode-manager/shared/utils'
|
||||
import { getReposPath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantModePath, getReposPath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { ensureAssistantRepo } from '../db/queries'
|
||||
@@ -24,7 +24,7 @@ const ASSISTANT_MODE_DIR = ASSISTANT_REPO_PATH
|
||||
const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
|
||||
const ASSISTANT_AGENTS_MD_FILENAME = 'AGENTS.md'
|
||||
const ASSISTANT_OPENCODE_CONFIG_FILENAME = 'opencode.json'
|
||||
const ASSISTANT_OPENCODE_DIR = '.opencode'
|
||||
const ASSISTANT_OPENCODE_DIR = ASSISTANT_OPENCODE_DIR_NAME
|
||||
const ASSISTANT_INTERNAL_TOKEN_FILENAME = 'internal-token'
|
||||
const ASSISTANT_SKILLS_DIR = 'skills'
|
||||
const ASSISTANT_SCHEDULES_SKILL_DIR = 'schedule-management'
|
||||
@@ -37,9 +37,8 @@ const ASSISTANT_DEFAULT_AGENT_NAME = 'assistant'
|
||||
const ASSISTANT_DEFAULT_AGENT_FILENAME = `${ASSISTANT_DEFAULT_AGENT_NAME}.md`
|
||||
|
||||
export function getAssistantModeDirectory(): string {
|
||||
const reposPath = getReposPath()
|
||||
const assistantDir = path.join(reposPath, ASSISTANT_MODE_DIR)
|
||||
const resolvedReposRoot = path.resolve(reposPath)
|
||||
const assistantDir = getAssistantModePath()
|
||||
const resolvedReposRoot = path.resolve(getReposPath())
|
||||
const resolvedAssistantDir = path.resolve(assistantDir)
|
||||
|
||||
if (!resolvedAssistantDir.startsWith(resolvedReposRoot)) {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSafe } from '../utils/fs-safe'
|
||||
import { writeFileAtomic } from '../utils/fs-safe'
|
||||
|
||||
const PLUGIN_FILENAME = 'ocm-gh-env.js'
|
||||
|
||||
@@ -47,11 +45,5 @@ export function getGhEnvPluginDir(configHome: string): string {
|
||||
}
|
||||
|
||||
export async function installGhEnvPlugin(configHome: string): Promise<void> {
|
||||
try {
|
||||
const dir = getGhEnvPluginDir(configHome)
|
||||
await mkdirSafe(dir)
|
||||
await fs.writeFile(path.join(dir, PLUGIN_FILENAME), PLUGIN_SOURCE, 'utf-8')
|
||||
} catch (error) {
|
||||
logger.warn('Failed to install gh-env OpenCode plugin:', error)
|
||||
}
|
||||
await writeFileAtomic(path.join(getGhEnvPluginDir(configHome), PLUGIN_FILENAME), PLUGIN_SOURCE)
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import { lstat, realpath } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
import {
|
||||
isRecord,
|
||||
restoreEnforcementSections,
|
||||
sanitizeEnforcementSections,
|
||||
type EnforcementRemovedSections,
|
||||
} from './opencode/enforcement-config'
|
||||
|
||||
export const TRUSTED_OPENCODE_PLUGIN_FILENAMES = ['ocm-sandbox.js', 'ocm-gh-env.js'] as const
|
||||
const TRUSTED_TOOL_FILENAMES: readonly string[] = []
|
||||
const PLUGIN_CONFIG_BACKUP_SUFFIX = '.ocm-sandbox-backup'
|
||||
const QUARANTINE_CONFLICT_SUFFIX = '.ocm-conflict'
|
||||
const QUARANTINE_MANIFEST_FILENAME = '.ocm-quarantine-manifest.json'
|
||||
|
||||
export function getOpenCodePluginDiscoveryHome(): string {
|
||||
return process.env.HOME ?? '/home/node'
|
||||
}
|
||||
|
||||
type PluginConfigBackup = {
|
||||
originalPlugins?: unknown
|
||||
sanitizedConfig?: Record<string, unknown>
|
||||
plugin?: unknown
|
||||
removedSections?: EnforcementRemovedSections
|
||||
}
|
||||
|
||||
type QuarantineManifestEntry = {
|
||||
original: string
|
||||
order: number
|
||||
}
|
||||
|
||||
type QuarantineManifest = {
|
||||
version: 1
|
||||
entries: Record<string, QuarantineManifestEntry>
|
||||
}
|
||||
|
||||
function deepEqual(left: unknown, right: unknown): boolean {
|
||||
if (left === right) return true
|
||||
if (Array.isArray(left) && Array.isArray(right)) {
|
||||
if (left.length !== right.length) return false
|
||||
return left.every((value, index) => deepEqual(value, right[index]))
|
||||
}
|
||||
if (left !== null && right !== null && typeof left === 'object' && typeof right === 'object') {
|
||||
const leftRecord = left as Record<string, unknown>
|
||||
const rightRecord = right as Record<string, unknown>
|
||||
const leftKeys = Object.keys(leftRecord).sort()
|
||||
const rightKeys = Object.keys(rightRecord).sort()
|
||||
if (leftKeys.length !== rightKeys.length) return false
|
||||
return leftKeys.every((key, index) => key === rightKeys[index] && deepEqual(leftRecord[key], rightRecord[key]))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function getPluginDirs(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'plugin'),
|
||||
path.join(configHome, 'opencode', 'plugins'),
|
||||
path.join(home, '.opencode', 'plugin'),
|
||||
path.join(home, '.opencode', 'plugins'),
|
||||
]
|
||||
}
|
||||
|
||||
function getToolDirs(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'tool'),
|
||||
path.join(configHome, 'opencode', 'tools'),
|
||||
path.join(home, '.opencode', 'tool'),
|
||||
path.join(home, '.opencode', 'tools'),
|
||||
]
|
||||
}
|
||||
|
||||
function getNativeOpenCodeConfigPaths(configHome: string): string[] {
|
||||
const home = getOpenCodePluginDiscoveryHome()
|
||||
return [
|
||||
path.join(configHome, 'opencode', 'opencode.json'),
|
||||
path.join(configHome, 'opencode', 'opencode.jsonc'),
|
||||
path.join(configHome, 'opencode', 'config.json'),
|
||||
path.join(home, '.opencode', 'opencode.json'),
|
||||
path.join(home, '.opencode', 'opencode.jsonc'),
|
||||
]
|
||||
}
|
||||
|
||||
function getSystemManagedConfigDir(): string {
|
||||
switch (process.platform) {
|
||||
case 'darwin':
|
||||
return '/Library/Application Support/opencode'
|
||||
case 'win32':
|
||||
return path.join(process.env.ProgramData || 'C:\\ProgramData', 'opencode')
|
||||
default:
|
||||
return '/etc/opencode'
|
||||
}
|
||||
}
|
||||
|
||||
function getManagedConfigPaths(): string[] {
|
||||
const dirs = [getSystemManagedConfigDir()]
|
||||
const override = process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR
|
||||
if (override !== undefined && override.trim() !== '') {
|
||||
dirs.push(override)
|
||||
}
|
||||
return [...new Set(dirs)].flatMap((dir) =>
|
||||
['opencode.json', 'opencode.jsonc'].map((file) => path.join(dir, file)),
|
||||
)
|
||||
}
|
||||
|
||||
function getEnforcementConfigPaths(configHome: string, configPath: string): string[] {
|
||||
return [...new Set([configPath, ...getNativeOpenCodeConfigPaths(configHome), ...getManagedConfigPaths()])]
|
||||
}
|
||||
|
||||
function getAuthFilePath(configHome: string): string {
|
||||
return path.join(path.dirname(configHome), '.opencode', 'state', 'opencode', 'auth.json')
|
||||
}
|
||||
|
||||
async function assertNoWellKnownAuthEntries(configHome: string): Promise<void> {
|
||||
const authPath = getAuthFilePath(configHome)
|
||||
let content: string
|
||||
try {
|
||||
content = await fs.readFile(authPath, 'utf-8')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return
|
||||
throw new Error(
|
||||
`cannot inspect OpenCode auth file ${authPath}: ${error instanceof Error ? error.message : String(error)}; refusing to start an enforced server with an uninspectable auth file`,
|
||||
)
|
||||
}
|
||||
let auth: unknown
|
||||
try {
|
||||
auth = JSON.parse(content)
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`cannot parse OpenCode auth file ${authPath}: ${error instanceof Error ? error.message : String(error)}; refusing to start an enforced server with an uninspectable auth file`,
|
||||
)
|
||||
}
|
||||
if (!isRecord(auth)) {
|
||||
throw new Error(
|
||||
`OpenCode auth file ${authPath} has an unexpected top-level shape; refusing to start an enforced server with an uninspectable auth file`,
|
||||
)
|
||||
}
|
||||
for (const [providerId, entry] of Object.entries(auth)) {
|
||||
if (!isRecord(entry)) {
|
||||
throw new Error(
|
||||
`OpenCode auth entry ${providerId} in ${authPath} cannot be inspected; refusing to start an enforced server with an uninspectable auth file`,
|
||||
)
|
||||
}
|
||||
if (entry.type === 'wellknown') {
|
||||
throw new Error(
|
||||
`refusing to start an enforced OpenCode server: provider ${providerId} authenticates through well-known remote configuration (.well-known/opencode) that the Manager cannot sanitize; remove the provider authentication or disable sandboxing`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function pathExists(target: string): Promise<boolean> {
|
||||
try {
|
||||
await fs.access(target)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function requireRealDirectory(dir: string, purpose: string): Promise<boolean> {
|
||||
let stat
|
||||
try {
|
||||
stat = await lstat(dir)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return false
|
||||
throw new Error(`cannot inspect ${purpose} ${dir}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
if (stat.isSymbolicLink()) {
|
||||
throw new Error(`${purpose} ${dir} is a symbolic link; refusing to quarantine or restore through a redirected directory`)
|
||||
}
|
||||
if (!stat.isDirectory()) {
|
||||
throw new Error(`${purpose} ${dir} is not a directory; refusing to quarantine or restore through it`)
|
||||
}
|
||||
const resolved = path.resolve(dir)
|
||||
const canonical = await realpath(dir)
|
||||
if (canonical !== resolved) {
|
||||
throw new Error(`${purpose} ${dir} resolves to ${canonical} instead of ${resolved}; refusing to quarantine or restore through a redirected directory`)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function quarantineConflictSuffixMatch(name: string): string | null {
|
||||
const separatorIndex = name.lastIndexOf(QUARANTINE_CONFLICT_SUFFIX)
|
||||
if (separatorIndex === -1) return null
|
||||
const suffix = name.slice(separatorIndex + QUARANTINE_CONFLICT_SUFFIX.length)
|
||||
if (!/^\d+$/.test(suffix)) return null
|
||||
return name.slice(0, separatorIndex)
|
||||
}
|
||||
|
||||
function isSingleBasenameComponent(name: string): boolean {
|
||||
return (
|
||||
name !== '' &&
|
||||
name !== '.' &&
|
||||
name !== '..' &&
|
||||
!name.includes('/') &&
|
||||
!name.includes('\\') &&
|
||||
path.basename(name) === name
|
||||
)
|
||||
}
|
||||
|
||||
function assertPathContainedWithin(parent: string, child: string, purpose: string): string {
|
||||
const relative = path.relative(parent, child)
|
||||
if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
|
||||
throw new Error(`${purpose} path ${child} escapes ${parent}; refusing to restore outside the plugin directory`)
|
||||
}
|
||||
return path.join(parent, relative)
|
||||
}
|
||||
|
||||
async function resolveQuarantineTarget(quarantineDir: string, name: string): Promise<string> {
|
||||
const stored = name === QUARANTINE_MANIFEST_FILENAME
|
||||
? `${name}${QUARANTINE_CONFLICT_SUFFIX}1`
|
||||
: name
|
||||
const original = path.join(quarantineDir, stored)
|
||||
if (!(await pathExists(original))) return original
|
||||
for (let index = 1; ; index++) {
|
||||
const candidate = path.join(quarantineDir, `${stored}${QUARANTINE_CONFLICT_SUFFIX}${index}`)
|
||||
if (!(await pathExists(candidate))) return candidate
|
||||
}
|
||||
}
|
||||
|
||||
async function readQuarantineManifest(quarantineDir: string): Promise<QuarantineManifest> {
|
||||
try {
|
||||
const parsed = JSON.parse(await fs.readFile(path.join(quarantineDir, QUARANTINE_MANIFEST_FILENAME), 'utf-8')) as unknown
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
const record = parsed as { version?: unknown; entries?: unknown }
|
||||
if (record.version === 1 && record.entries && typeof record.entries === 'object' && !Array.isArray(record.entries)) {
|
||||
return { version: 1, entries: record.entries as Record<string, QuarantineManifestEntry> }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// no manifest yet
|
||||
}
|
||||
return { version: 1, entries: {} }
|
||||
}
|
||||
|
||||
async function writeQuarantineManifest(quarantineDir: string, manifest: QuarantineManifest): Promise<void> {
|
||||
await writeFileAtomic(path.join(quarantineDir, QUARANTINE_MANIFEST_FILENAME), JSON.stringify(manifest, null, 2))
|
||||
}
|
||||
|
||||
async function recordQuarantinedEntry(
|
||||
manifest: QuarantineManifest,
|
||||
storedName: string,
|
||||
originalName: string,
|
||||
): Promise<void> {
|
||||
const existingOrders = Object.values(manifest.entries)
|
||||
.filter((record) => record.original === originalName)
|
||||
.map((record) => record.order)
|
||||
const order = storedName === originalName ? 1 : (existingOrders.length > 0 ? Math.max(...existingOrders) + 1 : 1)
|
||||
manifest.entries[storedName] = { original: originalName, order }
|
||||
}
|
||||
|
||||
async function moveUntrustedPluginEntries(
|
||||
dir: string,
|
||||
trustedNames: readonly string[],
|
||||
purpose = 'plugin directory',
|
||||
): Promise<void> {
|
||||
if (!(await requireRealDirectory(dir, purpose))) return
|
||||
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await fs.readdir(dir)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return
|
||||
throw new Error(`cannot inspect plugin directory ${dir}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
|
||||
const untrusted = entries.filter((name) => !trustedNames.includes(name))
|
||||
if (untrusted.length === 0) return
|
||||
|
||||
const quarantineDir = `${dir}.ocm-quarantine`
|
||||
await mkdirSafe(quarantineDir)
|
||||
if (!(await requireRealDirectory(quarantineDir, 'quarantine directory'))) {
|
||||
throw new Error(`cannot create quarantine directory ${quarantineDir}`)
|
||||
}
|
||||
const manifest = await readQuarantineManifest(quarantineDir)
|
||||
for (const name of untrusted) {
|
||||
const source = path.join(dir, name)
|
||||
const target = await resolveQuarantineTarget(quarantineDir, name)
|
||||
await fs.rename(source, target)
|
||||
await recordQuarantinedEntry(manifest, path.basename(target), name)
|
||||
}
|
||||
await writeQuarantineManifest(quarantineDir, manifest)
|
||||
logger.warn(`Quarantined ${untrusted.length} untrusted OpenCode plugin file(s) from ${dir}`)
|
||||
}
|
||||
|
||||
async function restorePluginEntries(dir: string): Promise<void> {
|
||||
const quarantineDir = `${dir}.ocm-quarantine`
|
||||
if (!(await requireRealDirectory(quarantineDir, 'quarantine directory'))) return
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await fs.readdir(quarantineDir)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return
|
||||
throw error
|
||||
}
|
||||
|
||||
await mkdirSafe(dir)
|
||||
if (!(await requireRealDirectory(dir, 'plugin directory'))) {
|
||||
throw new Error(`cannot create plugin directory ${dir}`)
|
||||
}
|
||||
|
||||
const manifest = await readQuarantineManifest(quarantineDir)
|
||||
const storedNames = entries.filter((name) => name !== QUARANTINE_MANIFEST_FILENAME)
|
||||
|
||||
const byOriginal = new Map<string, Array<{ stored: string; order: number }>>()
|
||||
const manifestless: string[] = []
|
||||
for (const stored of storedNames) {
|
||||
const record = manifest.entries[stored]
|
||||
if (
|
||||
record &&
|
||||
isSingleBasenameComponent(stored) &&
|
||||
typeof record.original === 'string' &&
|
||||
isSingleBasenameComponent(record.original) &&
|
||||
typeof record.order === 'number' &&
|
||||
Number.isFinite(record.order)
|
||||
) {
|
||||
const list = byOriginal.get(record.original) ?? []
|
||||
list.push({ stored, order: record.order })
|
||||
byOriginal.set(record.original, list)
|
||||
} else {
|
||||
manifestless.push(stored)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [original, copies] of byOriginal) {
|
||||
copies.sort((left, right) => left.order - right.order)
|
||||
const primary = copies[0]!
|
||||
const target = assertPathContainedWithin(dir, path.join(dir, original), 'restore target')
|
||||
if (await pathExists(target)) continue
|
||||
const source = assertPathContainedWithin(quarantineDir, path.join(quarantineDir, primary.stored), 'restore source')
|
||||
await fs.rename(source, target)
|
||||
}
|
||||
|
||||
for (const name of manifestless) {
|
||||
const base = quarantineConflictSuffixMatch(name)
|
||||
if (base !== null) {
|
||||
const baseIsOriginal = manifest.entries[base] !== undefined || storedNames.includes(base)
|
||||
if (baseIsOriginal) continue
|
||||
}
|
||||
const target = assertPathContainedWithin(dir, path.join(dir, name), 'restore target')
|
||||
if (await pathExists(target)) continue
|
||||
const source = assertPathContainedWithin(quarantineDir, path.join(quarantineDir, name), 'restore source')
|
||||
await fs.rename(source, target)
|
||||
}
|
||||
|
||||
await fs.rm(path.join(quarantineDir, QUARANTINE_MANIFEST_FILENAME), { force: true })
|
||||
|
||||
const remaining = (await fs.readdir(quarantineDir)).filter((name) => name !== QUARANTINE_MANIFEST_FILENAME)
|
||||
if (remaining.length > 0) {
|
||||
logger.warn(
|
||||
`Left ${remaining.length} conflicted quarantined OpenCode plugin copy/copies recoverable in ${quarantineDir}: ${remaining.join(', ')}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function readPluginConfigBackup(backupPath: string): Promise<PluginConfigBackup | null> {
|
||||
try {
|
||||
const parsed = parseJsonc(await fs.readFile(backupPath, 'utf-8')) as unknown
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as PluginConfigBackup
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function backupRemovedSections(backup: PluginConfigBackup | null): EnforcementRemovedSections {
|
||||
if (backup !== null && backup.removedSections !== undefined && isRecord(backup.removedSections)) {
|
||||
return backup.removedSections as EnforcementRemovedSections
|
||||
}
|
||||
const legacyPlugins = backup !== null && Array.isArray(backup.originalPlugins)
|
||||
? backup.originalPlugins
|
||||
: backup?.plugin
|
||||
return Array.isArray(legacyPlugins) ? { plugin: legacyPlugins } : {}
|
||||
}
|
||||
|
||||
async function existingFileMode(filePath: string): Promise<number | undefined> {
|
||||
try {
|
||||
return (await fs.stat(filePath)).mode & 0o777
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function describeRemovedSections(removed: EnforcementRemovedSections): string {
|
||||
const parts: string[] = []
|
||||
if (Array.isArray(removed.plugin) && removed.plugin.length > 0) {
|
||||
parts.push(`${removed.plugin.length} configured OpenCode plugin(s)`)
|
||||
}
|
||||
if (isRecord(removed.mcp) && Object.keys(removed.mcp).length > 0) {
|
||||
parts.push(`${Object.keys(removed.mcp).length} local MCP server(s)`)
|
||||
}
|
||||
if (isRecord(removed.provider) && Object.keys(removed.provider).length > 0) {
|
||||
parts.push(`${Object.keys(removed.provider).length} custom provider module(s)`)
|
||||
}
|
||||
if (removed.formatter !== undefined) {
|
||||
parts.push('the formatter configuration')
|
||||
}
|
||||
if (removed.shell !== undefined) {
|
||||
parts.push('the shell configuration')
|
||||
}
|
||||
if (removed.lsp !== undefined) {
|
||||
parts.push('the LSP server configuration')
|
||||
}
|
||||
if (removed.experimentalHook !== undefined) {
|
||||
parts.push('experimental hook commands')
|
||||
}
|
||||
return parts.length > 0 ? parts.join(', ') : 'all host-execution config sections'
|
||||
}
|
||||
|
||||
function reconcileRemovedSections(
|
||||
prior: EnforcementRemovedSections,
|
||||
current: EnforcementRemovedSections,
|
||||
): EnforcementRemovedSections {
|
||||
const merged: EnforcementRemovedSections = {}
|
||||
|
||||
if (current.plugin !== undefined) {
|
||||
merged.plugin = current.plugin
|
||||
} else if (Array.isArray(prior.plugin) && prior.plugin.length > 0) {
|
||||
merged.plugin = prior.plugin
|
||||
}
|
||||
|
||||
const priorMcp = isRecord(prior.mcp) ? prior.mcp : {}
|
||||
const currentMcp = isRecord(current.mcp) ? current.mcp : {}
|
||||
const mergedMcp: Record<string, unknown> = {}
|
||||
for (const [name, entry] of Object.entries(priorMcp)) {
|
||||
if (!(name in currentMcp)) {
|
||||
mergedMcp[name] = entry
|
||||
}
|
||||
}
|
||||
for (const [name, entry] of Object.entries(currentMcp)) {
|
||||
mergedMcp[name] = entry
|
||||
}
|
||||
if (Object.keys(mergedMcp).length > 0) {
|
||||
merged.mcp = mergedMcp
|
||||
}
|
||||
|
||||
const priorProvider = isRecord(prior.provider) ? prior.provider : {}
|
||||
const currentProvider = isRecord(current.provider) ? current.provider : {}
|
||||
const mergedProvider: Record<string, unknown> = {}
|
||||
for (const [name, entry] of Object.entries(priorProvider)) {
|
||||
if (!(name in currentProvider)) {
|
||||
mergedProvider[name] = entry
|
||||
}
|
||||
}
|
||||
for (const [name, entry] of Object.entries(currentProvider)) {
|
||||
mergedProvider[name] = entry
|
||||
}
|
||||
if (Object.keys(mergedProvider).length > 0) {
|
||||
merged.provider = mergedProvider
|
||||
}
|
||||
|
||||
for (const key of ['formatter', 'shell', 'lsp', 'experimentalHook'] as const) {
|
||||
if (current[key] !== undefined) {
|
||||
merged[key] = current[key]
|
||||
} else if (prior[key] !== undefined) {
|
||||
merged[key] = prior[key]
|
||||
}
|
||||
}
|
||||
|
||||
return merged
|
||||
}
|
||||
|
||||
async function sanitizeEnforcementConfigSections(configPath: string): Promise<void> {
|
||||
let content: string
|
||||
try {
|
||||
content = await fs.readFile(configPath, 'utf-8')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ENOENT') return
|
||||
throw error
|
||||
}
|
||||
|
||||
let config: Record<string, unknown>
|
||||
try {
|
||||
config = parseJsonc(content) as Record<string, unknown>
|
||||
} catch (error) {
|
||||
throw new Error(`cannot parse OpenCode config ${configPath} for enforcement sanitization: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
const backupPath = `${configPath}${PLUGIN_CONFIG_BACKUP_SUFFIX}`
|
||||
const hasBackup = await pathExists(backupPath)
|
||||
const pluginArray = Array.isArray(config.plugin) ? config.plugin : []
|
||||
const { sanitized, removed } = sanitizeEnforcementSections(config)
|
||||
if (
|
||||
!hasBackup &&
|
||||
pluginArray.length === 0 &&
|
||||
removed.mcp === undefined &&
|
||||
removed.formatter === undefined &&
|
||||
removed.shell === undefined &&
|
||||
removed.lsp === undefined &&
|
||||
removed.experimentalHook === undefined &&
|
||||
removed.provider === undefined
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
let effectiveRemoved = removed
|
||||
if (hasBackup) {
|
||||
const backup = await readPluginConfigBackup(backupPath)
|
||||
if (backup !== null) {
|
||||
const priorRemoved = backupRemovedSections(backup)
|
||||
if (backup.sanitizedConfig !== undefined && deepEqual(backup.sanitizedConfig, config)) {
|
||||
effectiveRemoved = priorRemoved
|
||||
} else {
|
||||
effectiveRemoved = reconcileRemovedSections(priorRemoved, removed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const backupContent = JSON.stringify(
|
||||
{
|
||||
originalPlugins: effectiveRemoved.plugin,
|
||||
sanitizedConfig: sanitized,
|
||||
removedSections: effectiveRemoved,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)
|
||||
await writeFileAtomic(backupPath, backupContent, { mode: await existingFileMode(backupPath) })
|
||||
await writeFileAtomic(configPath, JSON.stringify(sanitized, null, 2), { mode: await existingFileMode(configPath) })
|
||||
logger.warn(`Removed ${describeRemovedSections(effectiveRemoved)} from ${configPath} while sandbox enforcement is active`)
|
||||
}
|
||||
|
||||
async function restoreEnforcementConfigSections(configPath: string): Promise<void> {
|
||||
const backupPath = `${configPath}${PLUGIN_CONFIG_BACKUP_SUFFIX}`
|
||||
if (!(await pathExists(backupPath))) return
|
||||
|
||||
let backupContent: string
|
||||
let currentContent: string
|
||||
try {
|
||||
backupContent = await fs.readFile(backupPath, 'utf-8')
|
||||
currentContent = await fs.readFile(configPath, 'utf-8')
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
let removed: EnforcementRemovedSections
|
||||
let currentConfig: Record<string, unknown>
|
||||
try {
|
||||
const backupRecord = parseJsonc(backupContent) as Record<string, unknown>
|
||||
removed = isRecord(backupRecord.removedSections)
|
||||
? backupRecord.removedSections
|
||||
: {
|
||||
plugin: Array.isArray(backupRecord.originalPlugins)
|
||||
? backupRecord.originalPlugins
|
||||
: Array.isArray(backupRecord.plugin) ? backupRecord.plugin : [],
|
||||
}
|
||||
currentConfig = parseJsonc(currentContent) as Record<string, unknown>
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
const restored = restoreEnforcementSections(currentConfig, removed)
|
||||
const restoredContent = JSON.stringify(restored, null, 2)
|
||||
if (restoredContent !== currentContent) {
|
||||
await writeFileAtomic(configPath, restoredContent, { mode: await existingFileMode(configPath) })
|
||||
}
|
||||
await fs.rm(backupPath, { force: true })
|
||||
}
|
||||
|
||||
export async function quarantineOpenCodePlugins(configHome: string, configPath: string): Promise<void> {
|
||||
await assertNoWellKnownAuthEntries(configHome)
|
||||
const managerPluginDir = path.join(configHome, 'opencode', 'plugin')
|
||||
for (const dir of getPluginDirs(configHome)) {
|
||||
await moveUntrustedPluginEntries(dir, dir === managerPluginDir ? TRUSTED_OPENCODE_PLUGIN_FILENAMES : [])
|
||||
}
|
||||
for (const dir of getToolDirs(configHome)) {
|
||||
await moveUntrustedPluginEntries(dir, TRUSTED_TOOL_FILENAMES, 'custom tool directory')
|
||||
}
|
||||
for (const nativeConfigPath of getEnforcementConfigPaths(configHome, configPath)) {
|
||||
await sanitizeEnforcementConfigSections(nativeConfigPath)
|
||||
}
|
||||
}
|
||||
|
||||
export async function restoreQuarantinedOpenCodePlugins(configHome: string, configPath: string): Promise<void> {
|
||||
for (const dir of getPluginDirs(configHome)) {
|
||||
await restorePluginEntries(dir)
|
||||
}
|
||||
for (const dir of getToolDirs(configHome)) {
|
||||
await restorePluginEntries(dir)
|
||||
}
|
||||
for (const nativeConfigPath of getEnforcementConfigPaths(configHome, configPath)) {
|
||||
await restoreEnforcementConfigSections(nativeConfigPath)
|
||||
}
|
||||
}
|
||||
@@ -17,13 +17,22 @@ export function getOpenCodeRestartCoordinator(): OpenCodeRestartCoordinator | nu
|
||||
return restartCoordinator
|
||||
}
|
||||
|
||||
function restartFailureError(): Error {
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
return new Error(startupError ?? 'OpenCode server restart did not complete successfully')
|
||||
}
|
||||
|
||||
async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean> {
|
||||
if (supervisor) {
|
||||
return (await supervisor.restart('settings_restart')).healthy
|
||||
}
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
return opencodeServerManager.checkHealth()
|
||||
const healthy = await opencodeServerManager.checkHealth()
|
||||
if (!healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
return healthy
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,13 +46,23 @@ async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean>
|
||||
export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<{ resumedSessionIDs: string[] }> {
|
||||
if (restartCoordinator) {
|
||||
const result = await restartCoordinator.runWithResume(() => performRestart(supervisor))
|
||||
if (!result.healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
return { resumedSessionIDs: result.resumedSessionIDs }
|
||||
}
|
||||
if (supervisor) {
|
||||
await supervisor.restart('settings_restart')
|
||||
const status = await supervisor.restart('settings_restart')
|
||||
if (!status.healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
} else {
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
const healthy = await opencodeServerManager.checkHealth()
|
||||
if (!healthy) {
|
||||
throw restartFailureError()
|
||||
}
|
||||
}
|
||||
return { resumedSessionIDs: [] }
|
||||
}
|
||||
@@ -55,7 +74,11 @@ export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<
|
||||
*/
|
||||
export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Promise<void> {
|
||||
if (supervisor) {
|
||||
await supervisor.reloadConfig('settings_reload')
|
||||
const status = await supervisor.reloadConfig('settings_reload')
|
||||
if (!status.healthy) {
|
||||
const startupError = opencodeServerManager.getLastStartupError()
|
||||
throw new Error(startupError ?? 'OpenCode server reload did not complete successfully')
|
||||
}
|
||||
return
|
||||
}
|
||||
await opencodeServerManager.reloadConfig()
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import path from 'path'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
|
||||
import { writeFileAtomic } from '../utils/fs-safe'
|
||||
|
||||
const PLUGIN_FILENAME = 'ocm-sandbox.js'
|
||||
|
||||
const SANDBOX_PLAN_REQUEST_MARGIN_MS = 30000
|
||||
|
||||
export const SANDBOX_PLAN_TIMEOUT_MS = ENV.SANDBOX.START_TIMEOUT_MS + SANDBOX_PLAN_REQUEST_MARGIN_MS
|
||||
|
||||
const PLUGIN_SOURCE = `var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
|
||||
var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}
|
||||
|
||||
function guardCommand(reason) {
|
||||
var safe = String(SANDBOX_UNAVAILABLE_PREFIX + reason).replace(/'/g, "'\\\\''")
|
||||
return "printf '%s\\\\n' '" + safe + "' >&2; exit 1"
|
||||
}
|
||||
|
||||
function lockArgsReference(output, args) {
|
||||
try {
|
||||
Object.defineProperty(output, 'args', {
|
||||
get: function () { return args },
|
||||
set: function () {},
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
})
|
||||
} catch (error) {
|
||||
return false
|
||||
}
|
||||
var descriptor = Object.getOwnPropertyDescriptor(output, 'args')
|
||||
return !!descriptor && descriptor.configurable === false && typeof descriptor.get === 'function'
|
||||
}
|
||||
|
||||
function lockCommand(args, command) {
|
||||
var current = null
|
||||
try {
|
||||
Object.defineProperty(args, 'command', {
|
||||
get: function () { return command },
|
||||
set: function () {},
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
})
|
||||
current = args.command
|
||||
} catch (error) {
|
||||
try {
|
||||
args.command = command
|
||||
current = args.command
|
||||
} catch (ignored) {
|
||||
current = null
|
||||
}
|
||||
}
|
||||
return current === command
|
||||
}
|
||||
|
||||
var wrappedCommands = new Map()
|
||||
var bypassed = false
|
||||
|
||||
function replaceCommand(output, command, callID) {
|
||||
if (!lockArgsReference(output, output.args)) {
|
||||
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
|
||||
}
|
||||
if (!lockCommand(output.args, command)) {
|
||||
throw new Error('sandbox enforcement could not replace the bash command; aborting tool execution before it runs on the host')
|
||||
}
|
||||
wrappedCommands.set(callID, command)
|
||||
}
|
||||
|
||||
export default async function ({ directory, worktree }) {
|
||||
return {
|
||||
'tool.execute.before': async (input, output) => {
|
||||
if (input.tool !== 'bash') return
|
||||
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
|
||||
if (typeof output.args?.command !== 'string') {
|
||||
if (!lockArgsReference(output, output.args)) {
|
||||
throw new Error('sandbox enforcement could not lock the bash arguments; aborting tool execution before it runs on the host')
|
||||
}
|
||||
return
|
||||
}
|
||||
if (bypassed) {
|
||||
replaceCommand(output, guardCommand('sandbox enforcement was bypassed by another plugin; all sandboxed commands are now blocked'), input.callID)
|
||||
return
|
||||
}
|
||||
var baseUrl = process.env.OCM_INTERNAL_API_URL
|
||||
var token = process.env.OCM_INTERNAL_TOKEN
|
||||
if (!baseUrl || !token) {
|
||||
replaceCommand(output, guardCommand('sandbox plan lookup unavailable: internal API is not configured'), input.callID)
|
||||
return
|
||||
}
|
||||
var replacement = null
|
||||
var sessionDir = worktree || directory
|
||||
var effectiveDirectory = sessionDir
|
||||
var requestedWorkdir = output.args.workdir
|
||||
if (typeof requestedWorkdir === 'string' && requestedWorkdir.length > 0) {
|
||||
if (requestedWorkdir.charAt(0) === '/') {
|
||||
effectiveDirectory = requestedWorkdir
|
||||
} else {
|
||||
effectiveDirectory = sessionDir.replace(/\\/+$/, '') + '/' + requestedWorkdir
|
||||
}
|
||||
}
|
||||
var controller = new AbortController()
|
||||
var planTimedOut = false
|
||||
var planTimer = setTimeout(function () {
|
||||
planTimedOut = true
|
||||
controller.abort()
|
||||
}, PLAN_TIMEOUT_MS)
|
||||
try {
|
||||
var res = await fetch(baseUrl + '/sandbox/command', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
Authorization: 'Bearer ' + token,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
directory: effectiveDirectory,
|
||||
command: output.args.command,
|
||||
enforced: true,
|
||||
}),
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (!res.ok) {
|
||||
replacement = guardCommand('sandbox plan request failed with status ' + res.status)
|
||||
} else {
|
||||
var plan = await res.json()
|
||||
if (plan && typeof plan === 'object' && plan.mode === 'sandbox' && typeof plan.command === 'string' && plan.command.length > 0) {
|
||||
replacement = plan.command
|
||||
} else {
|
||||
replacement = guardCommand(plan && typeof plan === 'object' && typeof plan.reason === 'string' ? plan.reason : 'sandbox plan request returned an invalid response')
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
replacement = guardCommand(planTimedOut ? 'sandbox plan lookup timed out' : (error instanceof Error ? error.message : String(error)))
|
||||
} finally {
|
||||
clearTimeout(planTimer)
|
||||
}
|
||||
if (replacement !== null) {
|
||||
replaceCommand(output, replacement, input.callID)
|
||||
}
|
||||
},
|
||||
'tool.execute.after': async (input, output) => {
|
||||
if (input.tool !== 'bash') return
|
||||
if (process.env.OCM_SANDBOX_ENFORCED !== 'true') return
|
||||
var wrapped = wrappedCommands.get(input.callID)
|
||||
if (wrapped === undefined) return
|
||||
wrappedCommands.delete(input.callID)
|
||||
if (!bypassed && input.args && input.args.command !== wrapped) {
|
||||
bypassed = true
|
||||
console.error('OpenCode Manager: sandbox enforcement bypass detected for bash call ' + input.callID + '; blocking all further sandboxed commands')
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export function getSandboxPluginDir(configHome: string): string {
|
||||
return path.join(configHome, 'opencode', 'plugin')
|
||||
}
|
||||
|
||||
export async function installSandboxPlugin(configHome: string): Promise<void> {
|
||||
await writeFileAtomic(path.join(getSandboxPluginDir(configHome), PLUGIN_FILENAME), PLUGIN_SOURCE)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -65,6 +65,7 @@ export class OpenCodeSupervisor {
|
||||
private attemptedRecoveryActions: OpenCodeRecoveryAction[] = []
|
||||
private consecutiveFailures = 0
|
||||
private operationInProgress = false
|
||||
private operationTail: Promise<void> = Promise.resolve()
|
||||
private updatedAt = new Date().toISOString()
|
||||
|
||||
constructor(
|
||||
@@ -89,6 +90,7 @@ export class OpenCodeSupervisor {
|
||||
async start(): Promise<OpenCodeLifecycleStatus> {
|
||||
await this.runLifecycleOperation(async () => {
|
||||
this.setState('starting')
|
||||
this.closeLifecycleGate()
|
||||
|
||||
try {
|
||||
await this.openCodeServerManager.start()
|
||||
@@ -113,6 +115,7 @@ export class OpenCodeSupervisor {
|
||||
async restart(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
|
||||
return this.runLifecycleOperation(async () => {
|
||||
this.setState('starting')
|
||||
this.closeLifecycleGate()
|
||||
|
||||
try {
|
||||
this.openCodeServerManager.clearStartupError()
|
||||
@@ -128,6 +131,7 @@ export class OpenCodeSupervisor {
|
||||
async reloadConfig(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
|
||||
return this.runLifecycleOperation(async () => {
|
||||
this.setState('starting')
|
||||
this.closeLifecycleGate()
|
||||
|
||||
try {
|
||||
this.openCodeServerManager.clearStartupError()
|
||||
@@ -160,6 +164,7 @@ export class OpenCodeSupervisor {
|
||||
|
||||
await this.runLifecycleOperation(async () => {
|
||||
this.setState('stopping')
|
||||
this.closeLifecycleGate()
|
||||
await this.openCodeServerManager.stop()
|
||||
this.setState('stopped')
|
||||
return this.getStatus()
|
||||
@@ -191,16 +196,20 @@ export class OpenCodeSupervisor {
|
||||
}
|
||||
|
||||
private async runLifecycleOperation(operation: () => Promise<OpenCodeLifecycleStatus>): Promise<OpenCodeLifecycleStatus> {
|
||||
if (this.operationInProgress) {
|
||||
return this.getStatus()
|
||||
}
|
||||
const previousTail = this.operationTail
|
||||
let releaseTail!: () => void
|
||||
this.operationTail = new Promise<void>((resolve) => {
|
||||
releaseTail = resolve
|
||||
})
|
||||
|
||||
await previousTail
|
||||
this.operationInProgress = true
|
||||
try {
|
||||
return await operation()
|
||||
} finally {
|
||||
this.operationInProgress = false
|
||||
this.touch()
|
||||
releaseTail()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,6 +222,7 @@ export class OpenCodeSupervisor {
|
||||
|
||||
this.consecutiveFailures += 1
|
||||
this.setState('unhealthy')
|
||||
this.closeLifecycleGate()
|
||||
this.lastError = this.openCodeServerManager.getLastStartupError() ?? 'OpenCode health check failed'
|
||||
|
||||
if (respectThreshold && this.consecutiveFailures < this.failureThreshold) {
|
||||
@@ -223,10 +233,20 @@ export class OpenCodeSupervisor {
|
||||
}
|
||||
|
||||
private async recover(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
|
||||
this.closeLifecycleGate()
|
||||
|
||||
if (this.openCodeServerManager.isLastStartupErrorNonRecoverable()) {
|
||||
return this.failWithoutRecovery()
|
||||
}
|
||||
|
||||
this.setState('recovering')
|
||||
logger.warn(`OpenCode unhealthy during ${reason}, entering recovery`)
|
||||
|
||||
for (const action of OPENCODE_RECOVERY_ACTIONS) {
|
||||
if (this.openCodeServerManager.isLastStartupErrorNonRecoverable()) {
|
||||
return this.failWithoutRecovery()
|
||||
}
|
||||
|
||||
this.activeRecoveryAction = action
|
||||
this.attemptedRecoveryActions.push(action)
|
||||
this.touch()
|
||||
@@ -249,6 +269,17 @@ export class OpenCodeSupervisor {
|
||||
|
||||
this.activeRecoveryAction = null
|
||||
this.setState('failed')
|
||||
this.openCodeServerManager.setLifecycleInitialized(false)
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
private failWithoutRecovery(): OpenCodeLifecycleStatus {
|
||||
const message = this.lastError ?? this.openCodeServerManager.getLastStartupError() ?? 'OpenCode failed with a non-recoverable startup error'
|
||||
logger.error(`OpenCode failed with a non-recoverable startup error; skipping configuration recovery: ${message}`)
|
||||
this.activeRecoveryAction = null
|
||||
this.attemptedRecoveryActions = []
|
||||
this.setState('failed')
|
||||
this.openCodeServerManager.setLifecycleInitialized(false)
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
@@ -349,12 +380,17 @@ export class OpenCodeSupervisor {
|
||||
logger.info(`Started OpenCode supervisor health polling (${this.pollIntervalMs}ms)`)
|
||||
}
|
||||
|
||||
private closeLifecycleGate(): void {
|
||||
this.openCodeServerManager.setLifecycleInitialized(false)
|
||||
}
|
||||
|
||||
private markHealthy(): void {
|
||||
this.state = 'healthy'
|
||||
this.lastError = null
|
||||
this.activeRecoveryAction = null
|
||||
this.attemptedRecoveryActions = []
|
||||
this.consecutiveFailures = 0
|
||||
this.openCodeServerManager.setLifecycleInitialized(true)
|
||||
this.touch()
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,10 @@ export interface OpenCodeClient {
|
||||
authenticateMcp(serverName: string, directory?: string): Promise<Response>
|
||||
}
|
||||
|
||||
export type OpenCodeClientHost = string | (() => string)
|
||||
|
||||
export interface FetchOpenCodeClientConfig {
|
||||
baseUrl: string
|
||||
baseUrl: OpenCodeClientHost
|
||||
basicAuth: string | null
|
||||
passwordResolver?: OpenCodePasswordResolver
|
||||
fetchFn?: typeof fetch
|
||||
@@ -53,6 +55,10 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
return this.config.fetchFn ?? fetch
|
||||
}
|
||||
|
||||
private resolveBaseUrl(): string {
|
||||
return typeof this.config.baseUrl === 'function' ? this.config.baseUrl() : this.config.baseUrl
|
||||
}
|
||||
|
||||
private async getBasicAuth(): Promise<string> {
|
||||
if (!this.config.passwordResolver) {
|
||||
return this.config.basicAuth ?? ''
|
||||
@@ -62,7 +68,7 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
}
|
||||
|
||||
private async request(req: ForwardRequest): Promise<Response> {
|
||||
const url = new URL(this.config.baseUrl + req.path)
|
||||
const url = new URL(this.resolveBaseUrl() + req.path)
|
||||
|
||||
if (req.directory) {
|
||||
url.searchParams.set('directory', req.directory)
|
||||
@@ -248,9 +254,20 @@ export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(passwordOverride?: string | OpenCodePasswordResolver): OpenCodeClient {
|
||||
const host = ENV.OPENCODE.HOST === '0.0.0.0' ? '127.0.0.1' : ENV.OPENCODE.HOST
|
||||
const baseUrl = `http://${host}:${ENV.OPENCODE.PORT}`
|
||||
function formatOpenCodeHostForUrl(host: string): string {
|
||||
return host.includes(':') ? `[${host}]` : host
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(
|
||||
passwordOverride?: string | OpenCodePasswordResolver,
|
||||
host?: OpenCodeClientHost,
|
||||
): OpenCodeClient {
|
||||
const resolveConfiguredHost = typeof host === 'function' ? host : () => (host ?? ENV.OPENCODE.HOST)
|
||||
const baseUrl: OpenCodeClientHost = () => {
|
||||
const configuredHost = resolveConfiguredHost()
|
||||
const normalized = configuredHost === '0.0.0.0' ? '127.0.0.1' : configuredHost
|
||||
return `http://${formatOpenCodeHostForUrl(normalized)}:${ENV.OPENCODE.PORT}`
|
||||
}
|
||||
const passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
|
||||
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
|
||||
const basicAuth = getOpenCodeBasicAuthHeader(password)
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
export type EnforcementRemovedSections = Record<string, unknown>
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export function sanitizeConfigForEnforcement(
|
||||
config: Record<string, unknown>,
|
||||
enforced: boolean,
|
||||
): Record<string, unknown> {
|
||||
return sanitizeConfigForEnforcementResult(config, enforced).sanitized
|
||||
}
|
||||
|
||||
export function sanitizeConfigForEnforcementResult(
|
||||
config: Record<string, unknown>,
|
||||
enforced: boolean,
|
||||
): { sanitized: Record<string, unknown>; removed: EnforcementRemovedSections } {
|
||||
if (!enforced) {
|
||||
return { sanitized: config, removed: {} }
|
||||
}
|
||||
const { sanitized, removed } = sanitizeEnforcementSections(config)
|
||||
if (Object.keys(removed).length === 0) {
|
||||
return { sanitized: config, removed: {} }
|
||||
}
|
||||
if (Array.isArray(removed.plugin)) {
|
||||
logger.warn(`Stripped ${removed.plugin.length} configured OpenCode plugin(s) from the live config while sandbox enforcement is active`)
|
||||
}
|
||||
if (isRecord(removed.mcp)) {
|
||||
logger.warn(`Disabled ${Object.keys(removed.mcp).length} local MCP server(s) from the live config while sandbox enforcement is active`)
|
||||
}
|
||||
if (isRecord(removed.provider)) {
|
||||
logger.warn(`Disabled ${Object.keys(removed.provider).length} custom provider module(s) from the live config while sandbox enforcement is active`)
|
||||
}
|
||||
if (removed.formatter !== undefined) {
|
||||
logger.warn('Disabled formatter execution from the live config while sandbox enforcement is active')
|
||||
}
|
||||
if (removed.shell !== undefined) {
|
||||
logger.warn('Disabled the shell configuration from the live config while sandbox enforcement is active')
|
||||
}
|
||||
if (removed.lsp !== undefined) {
|
||||
logger.warn('Disabled LSP server configuration from the live config while sandbox enforcement is active')
|
||||
}
|
||||
if (removed.experimentalHook !== undefined) {
|
||||
logger.warn('Disabled experimental hook commands from the live config while sandbox enforcement is active')
|
||||
}
|
||||
return { sanitized, removed }
|
||||
}
|
||||
|
||||
export function isLocalMcpServerEntry(entry: unknown): boolean {
|
||||
if (!isRecord(entry)) return false
|
||||
return entry.type === 'local' || Array.isArray(entry.command)
|
||||
}
|
||||
|
||||
export function isCustomProviderEntry(entry: unknown): boolean {
|
||||
return isRecord(entry) && typeof entry.npm === 'string'
|
||||
}
|
||||
|
||||
export function sanitizeEnforcementSections(config: Record<string, unknown>): {
|
||||
sanitized: Record<string, unknown>
|
||||
removed: EnforcementRemovedSections
|
||||
} {
|
||||
const sanitized: Record<string, unknown> = { ...config }
|
||||
const removed: EnforcementRemovedSections = {}
|
||||
|
||||
if (Array.isArray(config.plugin) && config.plugin.length > 0) {
|
||||
delete sanitized.plugin
|
||||
removed.plugin = config.plugin
|
||||
}
|
||||
|
||||
if (config.formatter !== undefined) {
|
||||
delete sanitized.formatter
|
||||
removed.formatter = config.formatter
|
||||
}
|
||||
|
||||
if (config.shell !== undefined) {
|
||||
delete sanitized.shell
|
||||
removed.shell = config.shell
|
||||
}
|
||||
|
||||
const mcp = config.mcp
|
||||
if (isRecord(mcp)) {
|
||||
const retained: Record<string, unknown> = {}
|
||||
const removedMcp: Record<string, unknown> = {}
|
||||
for (const [name, entry] of Object.entries(mcp)) {
|
||||
if (isLocalMcpServerEntry(entry)) {
|
||||
removedMcp[name] = entry
|
||||
} else {
|
||||
retained[name] = entry
|
||||
}
|
||||
}
|
||||
if (Object.keys(removedMcp).length > 0) {
|
||||
removed.mcp = removedMcp
|
||||
if (Object.keys(retained).length > 0) {
|
||||
sanitized.mcp = retained
|
||||
} else {
|
||||
delete sanitized.mcp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const provider = config.provider
|
||||
if (isRecord(provider)) {
|
||||
const retainedProvider: Record<string, unknown> = {}
|
||||
const removedProvider: Record<string, unknown> = {}
|
||||
for (const [name, entry] of Object.entries(provider)) {
|
||||
if (isCustomProviderEntry(entry)) {
|
||||
removedProvider[name] = entry
|
||||
} else {
|
||||
retainedProvider[name] = entry
|
||||
}
|
||||
}
|
||||
if (Object.keys(removedProvider).length > 0) {
|
||||
removed.provider = removedProvider
|
||||
if (Object.keys(retainedProvider).length > 0) {
|
||||
sanitized.provider = retainedProvider
|
||||
} else {
|
||||
delete sanitized.provider
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const lsp = config.lsp
|
||||
if (lsp !== undefined && lsp !== false) {
|
||||
delete sanitized.lsp
|
||||
removed.lsp = lsp
|
||||
}
|
||||
|
||||
const experimental = config.experimental
|
||||
if (isRecord(experimental) && experimental.hook !== undefined) {
|
||||
const retainedExperimental: Record<string, unknown> = { ...experimental }
|
||||
delete retainedExperimental.hook
|
||||
removed.experimentalHook = experimental.hook
|
||||
if (Object.keys(retainedExperimental).length > 0) {
|
||||
sanitized.experimental = retainedExperimental
|
||||
} else {
|
||||
delete sanitized.experimental
|
||||
}
|
||||
}
|
||||
|
||||
return { sanitized, removed }
|
||||
}
|
||||
|
||||
export function restoreEnforcementSections(
|
||||
config: Record<string, unknown>,
|
||||
removed: EnforcementRemovedSections,
|
||||
): Record<string, unknown> {
|
||||
const restored: Record<string, unknown> = { ...config }
|
||||
|
||||
for (const [key, value] of Object.entries(removed)) {
|
||||
if (key === 'plugin') {
|
||||
if (Array.isArray(value) && value.length > 0 && restored.plugin === undefined) {
|
||||
restored.plugin = value
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (key === 'mcp' && isRecord(value)) {
|
||||
const currentMcp = isRecord(restored.mcp) ? { ...(restored.mcp as Record<string, unknown>) } : {}
|
||||
for (const [name, entry] of Object.entries(value)) {
|
||||
if (currentMcp[name] === undefined) {
|
||||
currentMcp[name] = entry
|
||||
}
|
||||
}
|
||||
restored.mcp = currentMcp
|
||||
continue
|
||||
}
|
||||
if (key === 'provider' && isRecord(value)) {
|
||||
const currentProvider = isRecord(restored.provider) ? { ...(restored.provider as Record<string, unknown>) } : {}
|
||||
for (const [name, entry] of Object.entries(value)) {
|
||||
if (currentProvider[name] === undefined) {
|
||||
currentProvider[name] = entry
|
||||
}
|
||||
}
|
||||
restored.provider = currentProvider
|
||||
continue
|
||||
}
|
||||
if (key === 'experimentalHook') {
|
||||
const experimental = isRecord(restored.experimental)
|
||||
? { ...(restored.experimental as Record<string, unknown>) }
|
||||
: {}
|
||||
if (experimental.hook === undefined) {
|
||||
experimental.hook = value
|
||||
restored.experimental = experimental
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (restored[key] === undefined) {
|
||||
restored[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
return restored
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { readFileSync, readdirSync } from 'fs'
|
||||
|
||||
export type ProcessStat = {
|
||||
pgrp: number
|
||||
startToken: string
|
||||
}
|
||||
|
||||
export type ProcessGroupMember = {
|
||||
pid: number
|
||||
startToken: string
|
||||
}
|
||||
|
||||
export type ProcessIdentityProvider = {
|
||||
attested: boolean
|
||||
readProcessStat(pid: number): ProcessStat | null
|
||||
readProcessGroupMembers(pgid: number): ProcessGroupMember[]
|
||||
}
|
||||
|
||||
function parseProcessStat(stat: string): ProcessStat | null {
|
||||
const commEnd = stat.lastIndexOf(')')
|
||||
if (commEnd === -1) return null
|
||||
const fields = stat.slice(commEnd + 2).split(' ')
|
||||
const pgrp = Number(fields[2])
|
||||
const startToken = fields[19]
|
||||
if (!Number.isInteger(pgrp) || pgrp <= 0) return null
|
||||
if (startToken === undefined || startToken === '') return null
|
||||
return { pgrp, startToken }
|
||||
}
|
||||
|
||||
const LINUX_PROCESS_IDENTITY_PROVIDER: ProcessIdentityProvider = {
|
||||
attested: true,
|
||||
readProcessStat(pid) {
|
||||
try {
|
||||
return parseProcessStat(readFileSync(`/proc/${pid}/stat`, 'utf-8'))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
readProcessGroupMembers(pgid) {
|
||||
const members: ProcessGroupMember[] = []
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = readdirSync('/proc')
|
||||
} catch {
|
||||
return members
|
||||
}
|
||||
if (!Array.isArray(entries)) return members
|
||||
for (const entry of entries) {
|
||||
if (!/^\d+$/.test(entry)) continue
|
||||
const pid = Number(entry)
|
||||
const stat = this.readProcessStat(pid)
|
||||
if (stat !== null && stat.pgrp === pgid) {
|
||||
members.push({ pid, startToken: stat.startToken })
|
||||
}
|
||||
}
|
||||
return members
|
||||
},
|
||||
}
|
||||
|
||||
const DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER: ProcessIdentityProvider = {
|
||||
attested: false,
|
||||
readProcessStat() {
|
||||
return null
|
||||
},
|
||||
readProcessGroupMembers() {
|
||||
return []
|
||||
},
|
||||
}
|
||||
|
||||
let cachedProvider: ProcessIdentityProvider | null = null
|
||||
let forcedProvider: ProcessIdentityProvider | null = null
|
||||
|
||||
export function resolveProcessIdentityProvider(): ProcessIdentityProvider {
|
||||
if (cachedProvider !== null) return cachedProvider
|
||||
cachedProvider = forcedProvider ??
|
||||
(process.platform === 'linux' ? LINUX_PROCESS_IDENTITY_PROVIDER : DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER)
|
||||
return cachedProvider
|
||||
}
|
||||
|
||||
export function resetProcessIdentityProvider(): void {
|
||||
cachedProvider = null
|
||||
}
|
||||
|
||||
export function forceProcessAttestation(attested: boolean | null): void {
|
||||
forcedProvider = attested === null ? null : attested ? LINUX_PROCESS_IDENTITY_PROVIDER : DIRECT_CHILD_PROCESS_IDENTITY_PROVIDER
|
||||
cachedProvider = null
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { isRecord, sanitizeConfigForEnforcement } from './enforcement-config'
|
||||
|
||||
export type SandboxProxyDecision = { blocked: true; reason: string } | { blocked: false }
|
||||
|
||||
export const SANDBOX_BLOCKED_REASON_PREFIX = 'Sandbox enforcement is on; host-process shell execution is disabled: '
|
||||
|
||||
export const SANDBOX_CONFIG_MUTATION_REASON_PREFIX =
|
||||
'Sandbox enforcement is on; config mutations that could re-enable host-process execution are disabled: '
|
||||
|
||||
const ENCODED_PATH_HAZARD =
|
||||
/%(?:2f|5c|25|00|01|02|03|04|05|06|07|08|09|0a|0b|0c|0d|0e|0f|10|11|12|13|14|15|16|17|18|19|1a|1b|1c|1d|1e|1f|7f)/i
|
||||
|
||||
function stripSandboxProxyApiPrefix(pathname: string): string {
|
||||
if (pathname === '/api' || pathname.startsWith('/api/')) {
|
||||
return pathname.slice(4) || '/'
|
||||
}
|
||||
return pathname
|
||||
}
|
||||
|
||||
function canonicalizeSandboxProxyPath(pathname: string): string | null {
|
||||
if (!pathname.includes('%')) return stripSandboxProxyApiPrefix(pathname)
|
||||
if (ENCODED_PATH_HAZARD.test(pathname)) return null
|
||||
try {
|
||||
return stripSandboxProxyApiPrefix(decodeURIComponent(pathname))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const BLOCKED_ENFORCED_ROUTES: ReadonlyArray<{
|
||||
methods: readonly string[]
|
||||
pathPattern: RegExp
|
||||
reason: string
|
||||
}> = [
|
||||
{
|
||||
methods: ['POST'],
|
||||
pathPattern: /^\/session\/[^/]+\/shell$/,
|
||||
reason: 'the session shell endpoint (`!command`) runs in the OpenCode host process',
|
||||
},
|
||||
{
|
||||
methods: ['POST'],
|
||||
pathPattern: /^\/session\/[^/]+\/command$/,
|
||||
reason: 'custom slash commands can run shell templates in the OpenCode host process',
|
||||
},
|
||||
{
|
||||
methods: ['POST'],
|
||||
pathPattern: /^\/pty$/,
|
||||
reason: 'PTY creation runs commands in the OpenCode host process',
|
||||
},
|
||||
{
|
||||
methods: ['GET', 'POST'],
|
||||
pathPattern: /^\/pty\/[^/]+\/connect$/,
|
||||
reason: 'PTY connections drive processes in the OpenCode host process',
|
||||
},
|
||||
]
|
||||
|
||||
export function decideSandboxProxyBlock(enforced: boolean, method: string, pathname: string): SandboxProxyDecision {
|
||||
if (!enforced) {
|
||||
return { blocked: false }
|
||||
}
|
||||
const normalizedMethod = method.toUpperCase()
|
||||
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
|
||||
if (canonicalPath === null) {
|
||||
return {
|
||||
blocked: true,
|
||||
reason: `${SANDBOX_BLOCKED_REASON_PREFIX}the request path could not be safely canonicalized`,
|
||||
}
|
||||
}
|
||||
for (const route of BLOCKED_ENFORCED_ROUTES) {
|
||||
if (route.methods.includes(normalizedMethod) && route.pathPattern.test(canonicalPath)) {
|
||||
return { blocked: true, reason: `${SANDBOX_BLOCKED_REASON_PREFIX}${route.reason}` }
|
||||
}
|
||||
}
|
||||
return { blocked: false }
|
||||
}
|
||||
|
||||
export function isSandboxConfigMutation(enforced: boolean, method: string, pathname: string): boolean {
|
||||
if (!enforced) {
|
||||
return false
|
||||
}
|
||||
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
|
||||
if (canonicalPath === null) {
|
||||
return false
|
||||
}
|
||||
return method.toUpperCase() === 'PATCH' && canonicalPath === '/config'
|
||||
}
|
||||
|
||||
export function isSandboxMcpAdd(enforced: boolean, method: string, pathname: string): boolean {
|
||||
if (!enforced) {
|
||||
return false
|
||||
}
|
||||
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
|
||||
if (canonicalPath === null) {
|
||||
return false
|
||||
}
|
||||
return method.toUpperCase() === 'POST' && canonicalPath === '/mcp'
|
||||
}
|
||||
|
||||
export function isSandboxAuthWrite(enforced: boolean, method: string, pathname: string): boolean {
|
||||
if (!enforced) {
|
||||
return false
|
||||
}
|
||||
const canonicalPath = canonicalizeSandboxProxyPath(pathname)
|
||||
if (canonicalPath === null) {
|
||||
return false
|
||||
}
|
||||
return method.toUpperCase() === 'PUT' && /^\/auth\/[^/]+$/.test(canonicalPath)
|
||||
}
|
||||
|
||||
export type SandboxConfigBodyDecision =
|
||||
| { kind: 'passthrough' }
|
||||
| { kind: 'sanitized'; body: string }
|
||||
| { kind: 'reject'; reason: string }
|
||||
|
||||
export function decideSandboxConfigBody(
|
||||
enforced: boolean,
|
||||
method: string,
|
||||
pathname: string,
|
||||
rawBody: string,
|
||||
): SandboxConfigBodyDecision {
|
||||
if (!isSandboxConfigMutation(enforced, method, pathname)) {
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(rawBody)
|
||||
} catch {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the config mutation body is not valid JSON`,
|
||||
}
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the config mutation body must be a JSON object`,
|
||||
}
|
||||
}
|
||||
return { kind: 'sanitized', body: JSON.stringify(sanitizeConfigForEnforcement(parsed, true)) }
|
||||
}
|
||||
|
||||
export function decideSandboxMcpAddBody(
|
||||
enforced: boolean,
|
||||
method: string,
|
||||
pathname: string,
|
||||
rawBody: string,
|
||||
): SandboxConfigBodyDecision {
|
||||
if (!isSandboxMcpAdd(enforced, method, pathname)) {
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(rawBody)
|
||||
} catch {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the MCP server body is not valid JSON`,
|
||||
}
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the MCP server body must be a JSON object`,
|
||||
}
|
||||
}
|
||||
const config = parsed.config
|
||||
if (
|
||||
!isRecord(config) ||
|
||||
config.type !== 'remote' ||
|
||||
typeof config.url !== 'string' ||
|
||||
config.command !== undefined ||
|
||||
config.environment !== undefined
|
||||
) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}only remote MCP servers can be added while enforcement is active`,
|
||||
}
|
||||
}
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
|
||||
export function decideSandboxAuthBody(
|
||||
enforced: boolean,
|
||||
method: string,
|
||||
pathname: string,
|
||||
rawBody: string,
|
||||
): SandboxConfigBodyDecision {
|
||||
if (!isSandboxAuthWrite(enforced, method, pathname)) {
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(rawBody)
|
||||
} catch {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the auth body is not valid JSON`,
|
||||
}
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}the auth body must be a JSON object`,
|
||||
}
|
||||
}
|
||||
if (parsed.type === 'wellknown') {
|
||||
return {
|
||||
kind: 'reject',
|
||||
reason: `${SANDBOX_CONFIG_MUTATION_REASON_PREFIX}well-known provider authentication loads remote host-executed code and cannot be added while enforcement is active`,
|
||||
}
|
||||
}
|
||||
return { kind: 'passthrough' }
|
||||
}
|
||||
|
||||
export function decideSandboxMutationBody(
|
||||
enforced: boolean,
|
||||
method: string,
|
||||
pathname: string,
|
||||
rawBody: string,
|
||||
): SandboxConfigBodyDecision {
|
||||
if (isSandboxMcpAdd(enforced, method, pathname)) {
|
||||
return decideSandboxMcpAddBody(enforced, method, pathname, rawBody)
|
||||
}
|
||||
if (isSandboxAuthWrite(enforced, method, pathname)) {
|
||||
return decideSandboxAuthBody(enforced, method, pathname, rawBody)
|
||||
}
|
||||
return decideSandboxConfigBody(enforced, method, pathname, rawBody)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { accessSync, constants } from 'fs'
|
||||
import { spawnSync } from 'child_process'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { buildSandboxVersionArgs, resolveSandboxExecutable, resetSandboxExecutableCache, resolveSandboxExecUserUid } from './command'
|
||||
|
||||
export type SandboxCapability = {
|
||||
available: boolean
|
||||
reason?: string
|
||||
msbVersion?: string
|
||||
}
|
||||
|
||||
let cachedCapability: SandboxCapability | null = null
|
||||
|
||||
export function detectSandboxCapability(): SandboxCapability {
|
||||
if (cachedCapability) {
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
try {
|
||||
accessSync('/dev/kvm', constants.R_OK | constants.W_OK)
|
||||
} catch {
|
||||
const reason = '/dev/kvm is not available or not writable; pass --device /dev/kvm and run on a KVM-capable Linux host'
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
const execUserUid = resolveSandboxExecUserUid()
|
||||
if (
|
||||
execUserUid !== null &&
|
||||
typeof process.getuid === 'function' &&
|
||||
typeof process.getgid === 'function' &&
|
||||
execUserUid !== process.getuid()
|
||||
) {
|
||||
const reason = `SANDBOX_EXEC_USER resolves to uid ${execUserUid}, which does not match the Manager workspace owner uid ${process.getuid()}; sandboxed commands could not write to the mounted project roots. Set SANDBOX_EXEC_USER=${process.getuid()}:${process.getgid()} or leave it unset`
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
const executable = resolveSandboxExecutable()
|
||||
if (executable === null) {
|
||||
const reason = 'msb CLI not found or not executable'
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
const result = spawnSync(executable, buildSandboxVersionArgs(), { encoding: 'utf8', timeout: 10000 })
|
||||
if (result.status !== 0 || result.error) {
|
||||
const reason = 'msb CLI not found or not executable'
|
||||
cachedCapability = { available: false, reason }
|
||||
logger.info(reason)
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
cachedCapability = {
|
||||
available: true,
|
||||
msbVersion: result.stdout.trim(),
|
||||
}
|
||||
return cachedCapability
|
||||
}
|
||||
|
||||
export function resetSandboxCapabilityCache(): void {
|
||||
cachedCapability = null
|
||||
resetSandboxExecutableCache()
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
import path from 'path'
|
||||
import { accessSync, constants, realpathSync, statSync } from 'fs'
|
||||
import { realpath } from 'fs/promises'
|
||||
import { ENV, getAssistantOpenCodeDir, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
|
||||
export const WORKSPACE_SANDBOX_NAME = 'ocm-workspace'
|
||||
|
||||
export const SANDBOX_UNAVAILABLE_PREFIX = 'Sandbox enforcement is on but the sandbox is unavailable: '
|
||||
|
||||
let cachedExecutablePath: string | null | undefined
|
||||
let executableTrustValidator: ((candidate: string) => boolean) | null = null
|
||||
|
||||
export function overrideSandboxExecutableTrustValidator(validator: ((candidate: string) => boolean) | null): void {
|
||||
executableTrustValidator = validator
|
||||
resetSandboxExecutableCache()
|
||||
}
|
||||
|
||||
function isPathWithinRoot(root: string, target: string): boolean {
|
||||
const relative = path.relative(path.resolve(root), path.resolve(target))
|
||||
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
function isWritableByManager(stat: { uid: number; gid: number; mode: number }): boolean {
|
||||
if (typeof process.getuid === 'function' && typeof process.getgid === 'function') {
|
||||
if (stat.uid === process.getuid() && (stat.mode & 0o200) !== 0) return true
|
||||
if (stat.gid === process.getgid() && (stat.mode & 0o020) !== 0) return true
|
||||
}
|
||||
return (stat.mode & 0o002) !== 0
|
||||
}
|
||||
|
||||
function pathPrefixes(target: string): string[] {
|
||||
const resolved = path.resolve(target)
|
||||
const parts = resolved.split(path.sep).filter((part) => part !== '')
|
||||
const prefixes: string[] = []
|
||||
let current = path.parse(resolved).root
|
||||
for (const part of parts) {
|
||||
current = path.join(current, part)
|
||||
prefixes.push(current)
|
||||
}
|
||||
return prefixes
|
||||
}
|
||||
|
||||
function isTrustedExecutablePath(candidate: string): boolean {
|
||||
if (executableTrustValidator !== null) {
|
||||
return executableTrustValidator(candidate)
|
||||
}
|
||||
let canonical: string
|
||||
try {
|
||||
canonical = realpathSync(candidate)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
const roots = sandboxMountRoots()
|
||||
for (const target of [candidate, canonical]) {
|
||||
if (roots.some((root) => isPathWithinRoot(root, target))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for (const target of new Set([candidate, canonical])) {
|
||||
for (const prefix of pathPrefixes(target)) {
|
||||
try {
|
||||
if (isWritableByManager(statSync(prefix))) {
|
||||
return false
|
||||
}
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function computeSandboxExecutablePath(): string | null {
|
||||
const configured = ENV.SANDBOX.MSB_PATH.trim()
|
||||
const candidates: string[] = []
|
||||
if (path.isAbsolute(configured)) {
|
||||
candidates.push(configured)
|
||||
} else {
|
||||
for (const directory of (process.env.PATH ?? '').split(path.delimiter)) {
|
||||
if (directory === '') continue
|
||||
candidates.push(path.join(directory, configured))
|
||||
}
|
||||
}
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
accessSync(candidate, constants.X_OK)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (isTrustedExecutablePath(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function resolveSandboxExecutable(): string | null {
|
||||
if (cachedExecutablePath !== undefined) return cachedExecutablePath
|
||||
cachedExecutablePath = computeSandboxExecutablePath()
|
||||
return cachedExecutablePath
|
||||
}
|
||||
|
||||
export function sandboxExecutablePath(): string {
|
||||
return resolveSandboxExecutable() ?? ENV.SANDBOX.MSB_PATH
|
||||
}
|
||||
|
||||
export function resetSandboxExecutableCache(): void {
|
||||
cachedExecutablePath = undefined
|
||||
}
|
||||
|
||||
export function buildSandboxVersionArgs(): string[] {
|
||||
return ['--version']
|
||||
}
|
||||
|
||||
export function sandboxMountRoots(): string[] {
|
||||
return [getReposPath(), getScheduleWorktreesPath()]
|
||||
}
|
||||
|
||||
export function sandboxSecretMaskPath(): string {
|
||||
return getAssistantOpenCodeDir()
|
||||
}
|
||||
|
||||
export function quoteForShell(value: string): string {
|
||||
return `'${value.replace(/'/g, `'\\''`)}'`
|
||||
}
|
||||
|
||||
export function buildSandboxCreateArgs(): string[] {
|
||||
return [
|
||||
'run',
|
||||
'-d',
|
||||
'--name',
|
||||
WORKSPACE_SANDBOX_NAME,
|
||||
'--label',
|
||||
'ocm.managed=true',
|
||||
'--label',
|
||||
`ocm.net=${ENV.SANDBOX.NET}`,
|
||||
'-m',
|
||||
ENV.SANDBOX.MEMORY,
|
||||
'-c',
|
||||
String(ENV.SANDBOX.CPUS),
|
||||
'--net',
|
||||
ENV.SANDBOX.NET,
|
||||
'-u',
|
||||
resolveSandboxExecUser(),
|
||||
...sandboxMountRoots().flatMap((root) => ['--mount-dir', `${root}:${root}`]),
|
||||
'--tmpfs',
|
||||
sandboxSecretMaskPath(),
|
||||
'-w',
|
||||
getReposPath(),
|
||||
ENV.SANDBOX.IMAGE,
|
||||
'--',
|
||||
'sleep',
|
||||
'infinity',
|
||||
]
|
||||
}
|
||||
|
||||
export function buildSandboxInspectArgs(): string[] {
|
||||
return ['inspect', WORKSPACE_SANDBOX_NAME, '--format', 'json']
|
||||
}
|
||||
|
||||
export function buildSandboxRemoveArgs(): string[] {
|
||||
return ['rm', '--force', WORKSPACE_SANDBOX_NAME]
|
||||
}
|
||||
|
||||
export function buildSandboxListArgs(): string[] {
|
||||
return ['ls', '--format', 'json']
|
||||
}
|
||||
|
||||
export function buildSandboxStartArgs(): string[] {
|
||||
return ['start', WORKSPACE_SANDBOX_NAME]
|
||||
}
|
||||
|
||||
export function buildSandboxStopManagedArgs(): string[] {
|
||||
return ['stop', '--label', 'ocm.managed=true']
|
||||
}
|
||||
|
||||
export type SandboxNetworkPolicyRule = {
|
||||
direction: string
|
||||
destination: Record<string, unknown> | string
|
||||
protocols: unknown[]
|
||||
ports: unknown[]
|
||||
action: string
|
||||
}
|
||||
|
||||
export type SandboxNetworkPolicy = {
|
||||
default_egress: string
|
||||
default_ingress: string
|
||||
rules: SandboxNetworkPolicyRule[]
|
||||
}
|
||||
|
||||
const SUPPORTED_SANDBOX_NETWORK_PROFILES = ['public', 'private', 'host'] as const
|
||||
const TERMINAL_SANDBOX_NETWORK_PROFILES = new Set(['all', 'none'])
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function stableJson(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map((item) => stableJson(item)).join(',')}]`
|
||||
}
|
||||
if (isPlainRecord(value)) {
|
||||
return `{${Object.keys(value)
|
||||
.sort()
|
||||
.map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`)
|
||||
.join(',')}}`
|
||||
}
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
|
||||
export function resolveExpectedSandboxNetworkPolicy(netProfile: string): SandboxNetworkPolicy | null {
|
||||
const tokens = netProfile.split(',').map((token) => token.trim()).filter((token) => token !== '')
|
||||
if (tokens.length === 0) {
|
||||
return null
|
||||
}
|
||||
const groups: string[] = []
|
||||
for (const token of tokens) {
|
||||
if (TERMINAL_SANDBOX_NETWORK_PROFILES.has(token)) {
|
||||
return null
|
||||
}
|
||||
if (!(SUPPORTED_SANDBOX_NETWORK_PROFILES as readonly string[]).includes(token)) {
|
||||
return null
|
||||
}
|
||||
if (!groups.includes(token)) {
|
||||
groups.push(token)
|
||||
}
|
||||
}
|
||||
return {
|
||||
default_egress: 'deny',
|
||||
default_ingress: 'allow',
|
||||
rules: [
|
||||
{ direction: 'egress', destination: { group: 'dns' }, protocols: [], ports: [], action: 'allow' },
|
||||
...groups.map((group) => ({ direction: 'egress', destination: { group }, protocols: [], ports: [], action: 'allow' })),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function canonicalSandboxNetworkRuleKey(rule: unknown): string | null {
|
||||
if (!isPlainRecord(rule)) return null
|
||||
if (typeof rule.direction !== 'string' || typeof rule.action !== 'string') return null
|
||||
if (!Array.isArray(rule.protocols) || !Array.isArray(rule.ports)) return null
|
||||
const protocols = [...rule.protocols].map(String).sort().join(',')
|
||||
const ports = [...rule.ports].map(String).sort().join(',')
|
||||
return `${rule.direction}|${stableJson(rule.destination)}|${protocols}|${ports}|${rule.action}`
|
||||
}
|
||||
|
||||
export function sandboxNetworkPolicyMismatch(inspected: unknown, expected: SandboxNetworkPolicy): string | null {
|
||||
if (!isPlainRecord(inspected) || typeof inspected.default_egress !== 'string' || typeof inspected.default_ingress !== 'string') {
|
||||
return 'sandbox network policy is missing or malformed'
|
||||
}
|
||||
if (inspected.default_egress !== expected.default_egress) {
|
||||
return `sandbox network default_egress ${inspected.default_egress} does not match the deny policy required by the configured network profile; unrestricted egress is not allowed`
|
||||
}
|
||||
if (inspected.default_ingress !== expected.default_ingress) {
|
||||
return `sandbox network default_ingress ${inspected.default_ingress} does not match the configured network profile`
|
||||
}
|
||||
if (!Array.isArray(inspected.rules)) {
|
||||
return 'sandbox network policy is missing or malformed'
|
||||
}
|
||||
const inspectedKeys: string[] = []
|
||||
for (const rule of inspected.rules) {
|
||||
const key = canonicalSandboxNetworkRuleKey(rule)
|
||||
if (key === null) {
|
||||
return 'sandbox network policy contains a rule that does not match the configured network profile'
|
||||
}
|
||||
inspectedKeys.push(key)
|
||||
}
|
||||
const expectedKeys = expected.rules.map((rule) => {
|
||||
const key = canonicalSandboxNetworkRuleKey(rule)
|
||||
return key === null ? `unexpected:${stableJson(rule)}` : key
|
||||
})
|
||||
if (inspectedKeys.length !== expectedKeys.length) {
|
||||
return `sandbox network policy rules do not match the configured network profile (expected ${expectedKeys.length}, found ${inspectedKeys.length})`
|
||||
}
|
||||
const sortedInspected = [...inspectedKeys].sort()
|
||||
const sortedExpected = [...expectedKeys].sort()
|
||||
for (let index = 0; index < sortedExpected.length; index++) {
|
||||
if (sortedInspected[index] !== sortedExpected[index]) {
|
||||
return 'sandbox network policy contains a rule that does not match the configured network profile'
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function parseMemoryMib(value: string): number | null {
|
||||
const match = /^(\d+(?:\.\d+)?)([gGmM])?$/.exec(value.trim())
|
||||
if (match === null) return null
|
||||
const number = Number(match[1])
|
||||
if (!Number.isFinite(number) || number < 0) return null
|
||||
const unit = match[2]
|
||||
if (unit === undefined || unit === 'M' || unit === 'm') return Math.floor(number)
|
||||
return Math.floor(number * 1024)
|
||||
}
|
||||
|
||||
function parseSandboxCreateArgs(args: string[]): {
|
||||
name: string
|
||||
labels: Record<string, string>
|
||||
memory: string
|
||||
cpus: number
|
||||
user: string
|
||||
mountDirs: string[]
|
||||
tmpfs: string | null
|
||||
workdir: string
|
||||
image: string
|
||||
cmd: string[]
|
||||
} {
|
||||
const labels: Record<string, string> = {}
|
||||
const mountDirs: string[] = []
|
||||
let name = ''
|
||||
let memory = ''
|
||||
let cpus = 0
|
||||
let user = ''
|
||||
let tmpfs: string | null = null
|
||||
let workdir = ''
|
||||
let image = ''
|
||||
let cmd: string[] = []
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
const token = args[i]!
|
||||
if (token === '--') {
|
||||
cmd = args.slice(i + 1)
|
||||
break
|
||||
}
|
||||
const value = args[i + 1]
|
||||
switch (token) {
|
||||
case '--name': name = value ?? ''; i += 1; break
|
||||
case '--label': {
|
||||
if (value !== undefined) {
|
||||
const separator = value.indexOf('=')
|
||||
if (separator >= 0) labels[value.slice(0, separator)] = value.slice(separator + 1)
|
||||
}
|
||||
i += 1
|
||||
break
|
||||
}
|
||||
case '-m': memory = value ?? ''; i += 1; break
|
||||
case '-c': cpus = Number(value); i += 1; break
|
||||
case '--net': i += 1; break
|
||||
case '-u': user = value ?? ''; i += 1; break
|
||||
case '--mount-dir': if (value !== undefined) mountDirs.push(value); i += 1; break
|
||||
case '--tmpfs': tmpfs = value ?? null; i += 1; break
|
||||
case '-w': workdir = value ?? ''; i += 1; break
|
||||
case '-d': break
|
||||
default:
|
||||
if (image === '' && !token.startsWith('-')) image = token
|
||||
}
|
||||
}
|
||||
return { name, labels, memory, cpus, user, mountDirs, tmpfs, workdir, image, cmd }
|
||||
}
|
||||
|
||||
export function buildCanonicalSandboxSpec(): Record<string, unknown> {
|
||||
const args = parseSandboxCreateArgs(buildSandboxCreateArgs())
|
||||
const memoryMib = parseMemoryMib(args.memory)
|
||||
const bindMounts = args.mountDirs.map((spec) => {
|
||||
const separator = spec.indexOf(':')
|
||||
const host = separator >= 0 ? spec.slice(0, separator) : spec
|
||||
const guest = separator >= 0 ? spec.slice(separator + 1) : spec
|
||||
return {
|
||||
type: 'Bind',
|
||||
host,
|
||||
guest,
|
||||
options: { readonly: false, noexec: false, nosuid: false, nodev: false },
|
||||
stat_virtualization: 'strict',
|
||||
host_permissions: 'private',
|
||||
follow_root_symlinks: false,
|
||||
quota_mib: null,
|
||||
}
|
||||
})
|
||||
return {
|
||||
name: args.name,
|
||||
image: {
|
||||
Oci: {
|
||||
reference: args.image,
|
||||
},
|
||||
},
|
||||
resources: {
|
||||
cpus: args.cpus,
|
||||
memory_mib: memoryMib,
|
||||
max_cpus: args.cpus,
|
||||
max_memory_mib: memoryMib,
|
||||
},
|
||||
runtime: {
|
||||
workdir: args.workdir,
|
||||
shell: null,
|
||||
scripts: {},
|
||||
entrypoint: null,
|
||||
cmd: args.cmd,
|
||||
hostname: null,
|
||||
user: args.user,
|
||||
log_level: null,
|
||||
metrics_sample_interval_ms: null,
|
||||
disable_metrics_sample: false,
|
||||
},
|
||||
env: [],
|
||||
labels: args.labels,
|
||||
rlimits: [],
|
||||
mounts: [
|
||||
...bindMounts,
|
||||
...(args.tmpfs !== null
|
||||
? [{ type: 'Tmpfs', guest: args.tmpfs, size_mib: null, options: { readonly: false, noexec: false, nosuid: false, nodev: false } }]
|
||||
: []),
|
||||
],
|
||||
patches: [],
|
||||
network: { enabled: true, ports: [] },
|
||||
init: null,
|
||||
pull_policy: 'IfMissing',
|
||||
security_profile: 'default',
|
||||
lifecycle: { ephemeral: false, max_duration_secs: null, idle_timeout_secs: null },
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveSandboxWorkDirectory(directory: string): Promise<string | null> {
|
||||
let resolvedDirectory: string
|
||||
try {
|
||||
resolvedDirectory = await realpath(directory)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
for (const root of sandboxMountRoots()) {
|
||||
let resolvedRoot: string
|
||||
try {
|
||||
resolvedRoot = await realpath(root)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const relative = path.relative(resolvedRoot, resolvedDirectory)
|
||||
if (relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))) {
|
||||
return path.join(root, relative)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function resolveSandboxExecUser(): string {
|
||||
const configured = ENV.SANDBOX.EXEC_USER.trim()
|
||||
if (/^\d+$/.test(configured)) {
|
||||
return typeof process.getgid === 'function' ? `${configured}:${process.getgid()}` : configured
|
||||
}
|
||||
if (/^\d+:\d+$/.test(configured)) {
|
||||
return configured
|
||||
}
|
||||
if (typeof process.getuid === 'function' && typeof process.getgid === 'function') {
|
||||
return `${process.getuid()}:${process.getgid()}`
|
||||
}
|
||||
return configured
|
||||
}
|
||||
|
||||
export function resolveSandboxExecUserUid(): number | null {
|
||||
const uid = resolveSandboxExecUser().split(':')[0]
|
||||
if (uid === undefined || !/^\d+$/.test(uid)) return null
|
||||
return Number(uid)
|
||||
}
|
||||
|
||||
export function buildSandboxExecCommandString(directory: string, command: string): string {
|
||||
const timeoutSeconds = Math.floor(ENV.SANDBOX.EXEC_TIMEOUT_MS / 1000)
|
||||
return `${quoteForShell(sandboxExecutablePath())} exec ${WORKSPACE_SANDBOX_NAME} --no-tty -q -u ${quoteForShell(resolveSandboxExecUser())} -w ${quoteForShell(directory)} --timeout ${timeoutSeconds}s -- sh -c ${quoteForShell(command)}`
|
||||
}
|
||||
|
||||
export function buildBlockedCommand(reason: string): string {
|
||||
const message = `${SANDBOX_UNAVAILABLE_PREFIX}${reason}`
|
||||
return `printf '%s\n' ${quoteForShell(message)} >&2; exit 1`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { SandboxRuntimeService } from './runtime'
|
||||
import { opencodeServerManager } from '../opencode-single-server'
|
||||
|
||||
export function isSandboxEnforcementActive(db: Database): boolean {
|
||||
let preferenceEnabled = false
|
||||
try {
|
||||
preferenceEnabled = new SandboxRuntimeService(db).isEnabled()
|
||||
} catch (error) {
|
||||
logger.warn('Failed to read the sandbox preference; treating sandbox enforcement as active:', error)
|
||||
return true
|
||||
}
|
||||
return preferenceEnabled || opencodeServerManager.isSandboxEnforced()
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import path from 'path'
|
||||
import { lstat, realpath } from 'fs/promises'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { executeCommand } from '../../utils/process'
|
||||
import { mkdirSafe } from '../../utils/fs-safe'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { SettingsService } from '../settings'
|
||||
import { detectSandboxCapability } from './capability'
|
||||
import {
|
||||
WORKSPACE_SANDBOX_NAME,
|
||||
buildCanonicalSandboxSpec,
|
||||
buildSandboxCreateArgs,
|
||||
buildSandboxExecCommandString,
|
||||
buildSandboxInspectArgs,
|
||||
buildSandboxListArgs,
|
||||
buildSandboxRemoveArgs,
|
||||
buildSandboxStartArgs,
|
||||
buildSandboxStopManagedArgs,
|
||||
resolveExpectedSandboxNetworkPolicy,
|
||||
resolveSandboxWorkDirectory,
|
||||
sandboxExecutablePath,
|
||||
sandboxMountRoots,
|
||||
sandboxNetworkPolicyMismatch,
|
||||
} from './command'
|
||||
|
||||
const SANDBOX_LS_CACHE_MS = 5000
|
||||
const SANDBOX_LS_TIMEOUT_MS = 15000
|
||||
const SANDBOX_STOP_TIMEOUT_MS = 30000
|
||||
|
||||
export type SandboxPlan =
|
||||
| { mode: 'host' }
|
||||
| { mode: 'sandbox'; command: string }
|
||||
| { mode: 'blocked'; reason: string }
|
||||
|
||||
export type SandboxStatus = {
|
||||
available: boolean
|
||||
enabled: boolean
|
||||
reason?: string
|
||||
msbVersion?: string
|
||||
}
|
||||
|
||||
let inFlightBoot: Promise<void> | null = null
|
||||
let lastKnownRunningAt: number | null = null
|
||||
let shutdownRequested = false
|
||||
|
||||
export function resetSandboxRuntimeState(): void {
|
||||
inFlightBoot = null
|
||||
lastKnownRunningAt = null
|
||||
shutdownRequested = false
|
||||
}
|
||||
|
||||
async function validateSandboxMountRoots(): Promise<void> {
|
||||
for (const root of sandboxMountRoots()) {
|
||||
const resolvedRoot = path.resolve(root)
|
||||
let stat
|
||||
try {
|
||||
stat = await lstat(root)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode !== 'ENOENT') {
|
||||
throw new Error(`cannot inspect sandbox mount root ${root}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
await mkdirSafe(root)
|
||||
stat = await lstat(root)
|
||||
}
|
||||
if (stat.isSymbolicLink()) {
|
||||
throw new Error(`sandbox mount root ${root} is a symbolic link; refusing to mount a redirected project root`)
|
||||
}
|
||||
const canonical = await realpath(root)
|
||||
if (canonical !== resolvedRoot) {
|
||||
throw new Error(`sandbox mount root ${root} resolves to ${canonical} instead of ${resolvedRoot}; refusing to mount a redirected project root`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function ensureWorkspaceSandbox(): Promise<void> {
|
||||
if (inFlightBoot) {
|
||||
return inFlightBoot
|
||||
}
|
||||
inFlightBoot = (async () => {
|
||||
await validateSandboxMountRoots()
|
||||
if (shutdownRequested) {
|
||||
throw new Error('sandbox shutdown is in progress; refusing to boot the workspace sandbox')
|
||||
}
|
||||
if (lastKnownRunningAt !== null && Date.now() - lastKnownRunningAt < SANDBOX_LS_CACHE_MS) {
|
||||
return
|
||||
}
|
||||
await bootWorkspaceSandbox()
|
||||
})().finally(() => {
|
||||
inFlightBoot = null
|
||||
})
|
||||
return inFlightBoot
|
||||
}
|
||||
|
||||
async function bootWorkspaceSandbox(): Promise<void> {
|
||||
try {
|
||||
const entry = findWorkspaceSandboxEntry(await listSandboxes())
|
||||
|
||||
if (!entry) {
|
||||
await createWorkspaceSandbox()
|
||||
} else {
|
||||
const attestation = await attestWorkspaceSandbox(entry.running)
|
||||
if (!attestation.trusted) {
|
||||
logger.warn(`Recreating unverifiable sandbox ${WORKSPACE_SANDBOX_NAME}: ${attestation.reason}`)
|
||||
await removeWorkspaceSandbox()
|
||||
await createWorkspaceSandbox()
|
||||
} else if (!entry.running) {
|
||||
await startWorkspaceSandbox()
|
||||
const runningAttestation = await attestWorkspaceSandbox(true)
|
||||
if (!runningAttestation.trusted) {
|
||||
logger.warn(
|
||||
`Recreating sandbox ${WORKSPACE_SANDBOX_NAME} that failed running attestation: ${runningAttestation.reason}`,
|
||||
)
|
||||
await removeWorkspaceSandbox()
|
||||
await createWorkspaceSandbox()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lastKnownRunningAt = Date.now()
|
||||
} catch (error) {
|
||||
lastKnownRunningAt = null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
type SandboxAttestation = { trusted: true } | { trusted: false; reason: string }
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function resolveInspectSpec(config: unknown): Record<string, unknown> | null {
|
||||
if (!isRecord(config)) return null
|
||||
const wrapped = config.spec
|
||||
if (isRecord(wrapped) && (isRecord(wrapped.image) || Array.isArray(wrapped.mounts) || isRecord(wrapped.labels) || isRecord(wrapped.network))) {
|
||||
return wrapped
|
||||
}
|
||||
if (isRecord(config.image) || Array.isArray(config.mounts) || isRecord(config.labels) || isRecord(config.network)) {
|
||||
return config
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function inspectImageReference(image: unknown): string | null {
|
||||
if (!isRecord(image)) return null
|
||||
const oci = image.Oci
|
||||
if (!isRecord(oci) || typeof oci.reference !== 'string') return null
|
||||
return oci.reference
|
||||
}
|
||||
|
||||
function sameStringArray(left: unknown, right: unknown): boolean {
|
||||
if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false
|
||||
return left.every((value, index) => value === right[index])
|
||||
}
|
||||
|
||||
function emptyArrayMismatch(value: unknown, path: string): string | null {
|
||||
if (!Array.isArray(value) || value.length > 0) {
|
||||
return `sandbox configuration ${path} must be empty`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
type ParsedSandboxMount =
|
||||
| { kind: 'bind'; host: string; guest: string; readonly: boolean }
|
||||
| { kind: 'tmpfs'; guest: string; readonly: boolean }
|
||||
| { kind: 'other' }
|
||||
|
||||
function parseInspectMount(mount: unknown): ParsedSandboxMount | null {
|
||||
if (!isRecord(mount) || typeof mount.type !== 'string') return null
|
||||
const readonly = (isRecord(mount.options) && mount.options.readonly === true) || mount.readonly === true
|
||||
if (mount.type === 'Bind') {
|
||||
if (typeof mount.host !== 'string' || typeof mount.guest !== 'string') return null
|
||||
return { kind: 'bind', host: mount.host, guest: mount.guest, readonly }
|
||||
}
|
||||
if (mount.type === 'Tmpfs') {
|
||||
if (typeof mount.guest !== 'string') return null
|
||||
return { kind: 'tmpfs', guest: mount.guest, readonly }
|
||||
}
|
||||
return { kind: 'other' }
|
||||
}
|
||||
|
||||
async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAttestation> {
|
||||
const spec = resolveInspectSpec(config)
|
||||
if (spec === null) {
|
||||
return { trusted: false, reason: 'msb inspect returned an unexpected config shape' }
|
||||
}
|
||||
|
||||
const canonical = buildCanonicalSandboxSpec()
|
||||
|
||||
const labels = isRecord(spec.labels) ? spec.labels : {}
|
||||
const canonicalLabels = isRecord(canonical.labels) ? canonical.labels : {}
|
||||
if (labels['ocm.managed'] !== 'true') {
|
||||
return { trusted: false, reason: 'sandbox is not labelled ocm.managed=true' }
|
||||
}
|
||||
if (labels['ocm.net'] !== canonicalLabels['ocm.net']) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox network profile ${String(labels['ocm.net'])} does not match ${canonicalLabels['ocm.net']}`,
|
||||
}
|
||||
}
|
||||
|
||||
const imageReference = inspectImageReference(spec.image)
|
||||
const canonicalImageReference = inspectImageReference(canonical.image)
|
||||
if (imageReference === null) {
|
||||
return { trusted: false, reason: 'sandbox image is not an OCI reference' }
|
||||
}
|
||||
if (canonicalImageReference !== null && imageReference !== canonicalImageReference) {
|
||||
return { trusted: false, reason: `sandbox image ${imageReference} does not match ${canonicalImageReference}` }
|
||||
}
|
||||
const image = isRecord(spec.image) ? spec.image : {}
|
||||
const oci = isRecord(image.Oci) ? image.Oci : null
|
||||
const rootDisk = oci !== null && isRecord(oci.root_disk) ? oci.root_disk : null
|
||||
if (rootDisk !== null && rootDisk.kind === 'disk-image') {
|
||||
return { trusted: false, reason: 'sandbox image must not attach a host disk image' }
|
||||
}
|
||||
|
||||
const canonicalMounts = Array.isArray(canonical.mounts) ? canonical.mounts : []
|
||||
const expectedRoots = new Set<string>()
|
||||
const expectedRealRoots = new Set<string>()
|
||||
let maskGuest: string | null = null
|
||||
for (const rawMount of canonicalMounts) {
|
||||
const mount = parseInspectMount(rawMount)
|
||||
if (mount?.kind === 'bind') {
|
||||
const resolvedRoot = path.resolve(mount.host)
|
||||
expectedRoots.add(resolvedRoot)
|
||||
try {
|
||||
expectedRealRoots.add(await realpath(resolvedRoot))
|
||||
} catch {
|
||||
return { trusted: false, reason: `cannot resolve the canonical bind mount root ${resolvedRoot}` }
|
||||
}
|
||||
} else if (mount?.kind === 'tmpfs') {
|
||||
maskGuest = path.resolve(mount.guest)
|
||||
}
|
||||
}
|
||||
|
||||
const mounts = Array.isArray(spec.mounts) ? spec.mounts : []
|
||||
const bindRoots = new Set<string>()
|
||||
let maskSeen = false
|
||||
for (let mountIndex = 0; mountIndex < mounts.length; mountIndex++) {
|
||||
const rawMount = mounts[mountIndex]
|
||||
const mount = parseInspectMount(rawMount)
|
||||
if (mount === null) {
|
||||
return { trusted: false, reason: 'sandbox has an unrecognized mount entry' }
|
||||
}
|
||||
if (mount.kind === 'bind') {
|
||||
const hostPath = path.resolve(mount.host)
|
||||
if (mount.readonly) {
|
||||
return { trusted: false, reason: 'sandbox has a read-only project bind mount' }
|
||||
}
|
||||
const mountOptions = isRecord(rawMount) && isRecord(rawMount.options) ? rawMount.options : {}
|
||||
for (const flag of ['noexec', 'nosuid', 'nodev'] as const) {
|
||||
if (mountOptions[flag] === true) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].options.${flag} does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rawMount.stat_virtualization !== 'strict') {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].stat_virtualization does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
if (rawMount.host_permissions !== 'private') {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].host_permissions does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
if (rawMount.follow_root_symlinks !== false) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].follow_root_symlinks does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
if (rawMount.quota_mib !== null) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].quota_mib does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
if (hostPath !== path.resolve(mount.guest) || !expectedRoots.has(hostPath)) {
|
||||
return { trusted: false, reason: 'sandbox has an unexpected bind mount' }
|
||||
}
|
||||
let realHost: string
|
||||
try {
|
||||
realHost = await realpath(mount.host)
|
||||
} catch {
|
||||
return { trusted: false, reason: `sandbox bind mount host ${mount.host} does not exist on the host` }
|
||||
}
|
||||
if (!expectedRealRoots.has(realHost)) {
|
||||
return { trusted: false, reason: 'sandbox bind mount resolves outside the expected project roots' }
|
||||
}
|
||||
bindRoots.add(hostPath)
|
||||
} else if (mount.kind === 'tmpfs') {
|
||||
if (maskGuest === null || path.resolve(mount.guest) !== maskGuest) {
|
||||
return { trusted: false, reason: `sandbox has an unexpected tmpfs mount at ${mount.guest}` }
|
||||
}
|
||||
if (maskSeen) {
|
||||
return { trusted: false, reason: 'sandbox has a duplicate assistant mask mount' }
|
||||
}
|
||||
maskSeen = true
|
||||
const tmpfsMountOptions = isRecord(rawMount) && isRecord(rawMount.options) ? rawMount.options : {}
|
||||
for (const flag of ['readonly', 'noexec', 'nosuid', 'nodev'] as const) {
|
||||
if (tmpfsMountOptions[flag] === true) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].options.${flag} does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rawMount.size_mib !== null) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox configuration mounts[${mountIndex}].size_mib does not match the canonical specification`,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return { trusted: false, reason: 'sandbox has an unexpected mount type' }
|
||||
}
|
||||
}
|
||||
if (bindRoots.size !== expectedRoots.size || [...expectedRoots].some((root) => !bindRoots.has(root))) {
|
||||
return { trusted: false, reason: 'sandbox is missing one of the project bind mounts' }
|
||||
}
|
||||
if (!maskSeen) {
|
||||
return { trusted: false, reason: `sandbox is missing the assistant .opencode mask at ${maskGuest}` }
|
||||
}
|
||||
|
||||
const resources = isRecord(spec.resources) ? spec.resources : {}
|
||||
const canonicalResources = isRecord(canonical.resources) ? canonical.resources : {}
|
||||
if (resources.cpus !== canonicalResources.cpus) {
|
||||
return { trusted: false, reason: `sandbox cpus ${String(resources.cpus)} does not match ${String(canonicalResources.cpus)}` }
|
||||
}
|
||||
if (resources.memory_mib !== canonicalResources.memory_mib) {
|
||||
return { trusted: false, reason: `sandbox memory does not match ${String(canonicalResources.memory_mib)}` }
|
||||
}
|
||||
if (resources.max_cpus !== canonicalResources.max_cpus) {
|
||||
return { trusted: false, reason: `sandbox max cpus ${String(resources.max_cpus)} does not match ${String(canonicalResources.max_cpus)}` }
|
||||
}
|
||||
if (resources.max_memory_mib !== canonicalResources.max_memory_mib) {
|
||||
return { trusted: false, reason: `sandbox max memory does not match ${String(canonicalResources.max_memory_mib)}` }
|
||||
}
|
||||
|
||||
const runtime = isRecord(spec.runtime) ? spec.runtime : {}
|
||||
const canonicalRuntime = isRecord(canonical.runtime) ? canonical.runtime : {}
|
||||
if (runtime.workdir !== canonicalRuntime.workdir) {
|
||||
return { trusted: false, reason: `sandbox workdir ${String(runtime.workdir)} does not match ${String(canonicalRuntime.workdir)}` }
|
||||
}
|
||||
if (runtime.user !== canonicalRuntime.user) {
|
||||
return { trusted: false, reason: `sandbox user ${String(runtime.user)} does not match ${String(canonicalRuntime.user)}` }
|
||||
}
|
||||
if (!sameStringArray(runtime.cmd, canonicalRuntime.cmd)) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.cmd does not match the canonical specification' }
|
||||
}
|
||||
if (runtime.entrypoint !== null) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.entrypoint must be empty' }
|
||||
}
|
||||
if (runtime.shell !== canonicalRuntime.shell) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.shell does not match the canonical specification' }
|
||||
}
|
||||
if (!isRecord(runtime.scripts) || Object.keys(runtime.scripts).length > 0) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.scripts must be empty' }
|
||||
}
|
||||
if (runtime.hostname !== canonicalRuntime.hostname) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.hostname does not match the canonical specification' }
|
||||
}
|
||||
if (runtime.metrics_sample_interval_ms !== canonicalRuntime.metrics_sample_interval_ms) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.metrics_sample_interval_ms does not match the canonical specification' }
|
||||
}
|
||||
if (runtime.disable_metrics_sample !== canonicalRuntime.disable_metrics_sample) {
|
||||
return { trusted: false, reason: 'sandbox configuration runtime.disable_metrics_sample does not match the canonical specification' }
|
||||
}
|
||||
|
||||
const network = isRecord(spec.network) ? spec.network : {}
|
||||
if (network.enabled !== true) {
|
||||
return { trusted: false, reason: 'sandbox networking is disabled' }
|
||||
}
|
||||
if (!Array.isArray(network.ports) || network.ports.length > 0) {
|
||||
return { trusted: false, reason: 'sandbox configuration network.ports must be empty' }
|
||||
}
|
||||
const expectedPolicy = resolveExpectedSandboxNetworkPolicy(ENV.SANDBOX.NET)
|
||||
if (expectedPolicy === null) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `sandbox network profile ${ENV.SANDBOX.NET} cannot be attested; supported profiles are public, private, host`,
|
||||
}
|
||||
}
|
||||
const policyMismatch = sandboxNetworkPolicyMismatch(network.policy, expectedPolicy)
|
||||
if (policyMismatch !== null) {
|
||||
return { trusted: false, reason: policyMismatch }
|
||||
}
|
||||
|
||||
const secretsConfig = network.secrets
|
||||
if (secretsConfig !== undefined && secretsConfig !== null) {
|
||||
if (!isRecord(secretsConfig) || !Array.isArray(secretsConfig.secrets)) {
|
||||
return { trusted: false, reason: 'sandbox configuration network.secrets is malformed' }
|
||||
}
|
||||
if (secretsConfig.secrets.length > 0) {
|
||||
return { trusted: false, reason: 'sandbox configuration network.secrets must be empty' }
|
||||
}
|
||||
}
|
||||
|
||||
const emptyMismatch = emptyArrayMismatch(spec.patches, 'patches')
|
||||
if (emptyMismatch !== null) return { trusted: false, reason: emptyMismatch }
|
||||
const rlimitsMismatch = emptyArrayMismatch(spec.rlimits, 'rlimits')
|
||||
if (rlimitsMismatch !== null) return { trusted: false, reason: rlimitsMismatch }
|
||||
|
||||
if (spec.init !== null) {
|
||||
return { trusted: false, reason: 'sandbox configuration init must be empty' }
|
||||
}
|
||||
if (spec.pull_policy !== 'IfMissing') {
|
||||
return { trusted: false, reason: `sandbox pull policy ${String(spec.pull_policy)} must be IfMissing` }
|
||||
}
|
||||
if (spec.security_profile !== 'default') {
|
||||
return { trusted: false, reason: 'sandbox configuration security_profile must be default' }
|
||||
}
|
||||
const lifecycle = isRecord(spec.lifecycle) ? spec.lifecycle : {}
|
||||
if (lifecycle.ephemeral !== false) {
|
||||
return { trusted: false, reason: 'sandbox configuration lifecycle.ephemeral must be false' }
|
||||
}
|
||||
if (lifecycle.max_duration_secs !== null) {
|
||||
return { trusted: false, reason: 'sandbox configuration lifecycle.max_duration_secs must be empty' }
|
||||
}
|
||||
if (lifecycle.idle_timeout_secs !== null) {
|
||||
return { trusted: false, reason: 'sandbox configuration lifecycle.idle_timeout_secs must be empty' }
|
||||
}
|
||||
if (spec.manifest_digest !== undefined && spec.manifest_digest !== null) {
|
||||
if (typeof spec.manifest_digest !== 'string' || spec.manifest_digest === '') {
|
||||
return { trusted: false, reason: 'sandbox manifest digest is malformed' }
|
||||
}
|
||||
}
|
||||
|
||||
return { trusted: true }
|
||||
}
|
||||
|
||||
async function attestWorkspaceSandbox(running: boolean): Promise<SandboxAttestation> {
|
||||
let result: string | { exitCode: number; stdout: string; stderr: string }
|
||||
try {
|
||||
result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxInspectArgs()], {
|
||||
ignoreExitCode: true,
|
||||
silent: true,
|
||||
timeout: SANDBOX_LS_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
} catch (error) {
|
||||
return { trusted: false, reason: `msb inspect failed: ${error instanceof Error ? error.message : String(error)}` }
|
||||
}
|
||||
const listing = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
|
||||
if (listing.exitCode !== 0) {
|
||||
return {
|
||||
trusted: false,
|
||||
reason: `msb inspect failed with code ${listing.exitCode}: ${listing.stderr || listing.stdout}`,
|
||||
}
|
||||
}
|
||||
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(listing.stdout)
|
||||
} catch {
|
||||
return { trusted: false, reason: 'msb inspect returned malformed JSON' }
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
return { trusted: false, reason: 'msb inspect returned an unexpected JSON shape' }
|
||||
}
|
||||
if (running) {
|
||||
if (parsed.active_config === undefined || parsed.active_config === null) {
|
||||
return { trusted: false, reason: 'msb inspect returned no active configuration for the running sandbox' }
|
||||
}
|
||||
return await attestWorkspaceSandboxConfig(parsed.active_config)
|
||||
}
|
||||
return await attestWorkspaceSandboxConfig(parsed.config)
|
||||
}
|
||||
|
||||
async function createWorkspaceSandbox(): Promise<void> {
|
||||
await executeCommand([sandboxExecutablePath(), ...buildSandboxCreateArgs()], {
|
||||
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
|
||||
})
|
||||
const attestation = await attestWorkspaceSandbox(true)
|
||||
if (!attestation.trusted) {
|
||||
throw new Error(`newly created sandbox ${WORKSPACE_SANDBOX_NAME} failed attestation: ${attestation.reason}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeWorkspaceSandbox(): Promise<void> {
|
||||
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxRemoveArgs()], {
|
||||
ignoreExitCode: true,
|
||||
timeout: SANDBOX_LS_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
const removal = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
if (removal.exitCode !== 0) {
|
||||
throw new Error(`msb rm failed with code ${removal.exitCode}: ${removal.stderr || removal.stdout}`)
|
||||
}
|
||||
}
|
||||
|
||||
type SandboxLsEntry = {
|
||||
name?: unknown
|
||||
status?: unknown
|
||||
state?: unknown
|
||||
}
|
||||
|
||||
async function listSandboxes(): Promise<SandboxLsEntry[]> {
|
||||
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxListArgs()], {
|
||||
ignoreExitCode: true,
|
||||
silent: true,
|
||||
timeout: SANDBOX_LS_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
const listing = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
|
||||
if (listing.exitCode !== 0) {
|
||||
throw new Error(`msb ls failed with code ${listing.exitCode}: ${listing.stderr || listing.stdout}`)
|
||||
}
|
||||
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(listing.stdout)
|
||||
} catch {
|
||||
throw new Error(`msb ls returned malformed JSON (${listing.stdout.slice(0, 200)})`)
|
||||
}
|
||||
if (!Array.isArray(parsed)) {
|
||||
throw new Error('msb ls returned an unexpected JSON shape (expected a top-level array)')
|
||||
}
|
||||
return parsed as SandboxLsEntry[]
|
||||
}
|
||||
|
||||
function findWorkspaceSandboxEntry(entries: SandboxLsEntry[]): { running: boolean } | null {
|
||||
for (const value of entries) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
|
||||
const entry = value as SandboxLsEntry
|
||||
if (entry.name !== WORKSPACE_SANDBOX_NAME) continue
|
||||
const status = entry.status ?? entry.state
|
||||
return { running: String(status).toLowerCase() === 'running' }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function startWorkspaceSandbox(): Promise<void> {
|
||||
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStartArgs()], {
|
||||
ignoreExitCode: true,
|
||||
timeout: ENV.SANDBOX.START_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
if (typeof result === 'string' || result.exitCode === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const entry = findWorkspaceSandboxEntry(await listSandboxes())
|
||||
if (entry?.running) {
|
||||
return
|
||||
}
|
||||
throw new Error(`msb start failed with code ${result.exitCode}: ${result.stderr || result.stdout}`)
|
||||
}
|
||||
|
||||
export class SandboxRuntimeService {
|
||||
constructor(private readonly db: Database) {}
|
||||
|
||||
isEnabled(): boolean {
|
||||
return this.isSandboxEnabled()
|
||||
}
|
||||
|
||||
getStatus(): SandboxStatus {
|
||||
const capability = detectSandboxCapability()
|
||||
return {
|
||||
available: capability.available,
|
||||
enabled: this.isEnabled(),
|
||||
...(capability.reason !== undefined ? { reason: capability.reason } : {}),
|
||||
...(capability.msbVersion !== undefined ? { msbVersion: capability.msbVersion } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
async planCommand(directory: string, command: string, enforced = false): Promise<SandboxPlan> {
|
||||
if (!enforced && !this.isEnabled()) {
|
||||
return { mode: 'host' }
|
||||
}
|
||||
const capability = detectSandboxCapability()
|
||||
if (!capability.available) {
|
||||
return { mode: 'blocked', reason: capability.reason ?? 'Sandbox capability is unavailable' }
|
||||
}
|
||||
const workDirectory = await resolveSandboxWorkDirectory(directory)
|
||||
if (workDirectory === null) {
|
||||
return {
|
||||
mode: 'blocked',
|
||||
reason: `working directory is outside the sandboxed project roots (${sandboxMountRoots().join(', ')})`,
|
||||
}
|
||||
}
|
||||
try {
|
||||
await ensureWorkspaceSandbox()
|
||||
return { mode: 'sandbox', command: buildSandboxExecCommandString(workDirectory, command) }
|
||||
} catch (error) {
|
||||
logger.error('Failed to prepare the workspace sandbox', error)
|
||||
return { mode: 'blocked', reason: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
async stopWorkspaceSandbox(): Promise<void> {
|
||||
shutdownRequested = true
|
||||
await this.stopManagedSandbox()
|
||||
}
|
||||
|
||||
async stopWorkspaceSandboxForToggle(): Promise<void> {
|
||||
await this.stopManagedSandbox()
|
||||
}
|
||||
|
||||
private async stopManagedSandbox(): Promise<void> {
|
||||
while (inFlightBoot) {
|
||||
try {
|
||||
await inFlightBoot
|
||||
} catch {
|
||||
// a settled boot is done; keep waiting for any other admitted boot
|
||||
}
|
||||
}
|
||||
lastKnownRunningAt = null
|
||||
const result = (await executeCommand([sandboxExecutablePath(), ...buildSandboxStopManagedArgs()], {
|
||||
ignoreExitCode: true,
|
||||
timeout: SANDBOX_STOP_TIMEOUT_MS,
|
||||
})) as string | { exitCode: number; stdout: string; stderr: string }
|
||||
const stopResult = typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
|
||||
if (stopResult.exitCode !== 0) {
|
||||
try {
|
||||
await confirmManagedSandboxStopped()
|
||||
logger.warn(`msb stop failed with code ${stopResult.exitCode} but the workspace sandbox is confirmed stopped: ${stopResult.stderr || stopResult.stdout}`)
|
||||
} catch (error) {
|
||||
logger.error('Failed to confirm the workspace sandbox stopped:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private isSandboxEnabled(): boolean {
|
||||
return new SettingsService(this.db).getSettings('default').preferences.sandbox?.enabled === true
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmManagedSandboxStopped(): Promise<void> {
|
||||
const entry = findWorkspaceSandboxEntry(await listSandboxes())
|
||||
if (entry !== null && entry.running) {
|
||||
throw new Error('msb stop failed to stop the workspace sandbox; the managed microVM is still running')
|
||||
}
|
||||
}
|
||||
|
||||
export async function stopWorkspaceSandboxOnShutdown(db: Database): Promise<void> {
|
||||
await new SandboxRuntimeService(db).stopWorkspaceSandbox()
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import { executeCommand } from '../utils/process'
|
||||
import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSyncSafe } from '../utils/fs-safe'
|
||||
import { resolveSandboxWorkDirectory } from './sandbox/command'
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
|
||||
export interface ScheduleWorktreeContext {
|
||||
directory: string
|
||||
@@ -89,16 +91,18 @@ export class ScheduleWorktreeManager {
|
||||
{ directory: repo.fullPath },
|
||||
)
|
||||
|
||||
// Re-point the workspace to our run branch and base
|
||||
await executeCommand(['git', '-C', createdWorkspace.directory, 'checkout', '-B', runBranch, baseRef], { env })
|
||||
const workspaceDirectory = await this.resolveWorkspaceDirectory(createdWorkspace.directory)
|
||||
|
||||
if (!existsSync(createdWorkspace.directory)) {
|
||||
throw new Error(`OpenCode workspace directory was not created at: ${createdWorkspace.directory}`)
|
||||
// Re-point the workspace to our run branch and base
|
||||
await executeCommand(['git', '-C', workspaceDirectory, 'checkout', '-B', runBranch, baseRef], { env })
|
||||
|
||||
if (!existsSync(workspaceDirectory)) {
|
||||
throw new Error(`OpenCode workspace directory was not created at: ${workspaceDirectory}`)
|
||||
}
|
||||
|
||||
return {
|
||||
directory: createdWorkspace.directory,
|
||||
worktreePath: createdWorkspace.directory,
|
||||
directory: workspaceDirectory,
|
||||
worktreePath: workspaceDirectory,
|
||||
runBranch,
|
||||
workspaceId: createdWorkspace.id,
|
||||
}
|
||||
@@ -289,6 +293,17 @@ export class ScheduleWorktreeManager {
|
||||
return null
|
||||
}
|
||||
|
||||
private async resolveWorkspaceDirectory(directory: string): Promise<string> {
|
||||
if (!opencodeServerManager.isSandboxEnforced()) {
|
||||
return directory
|
||||
}
|
||||
const workDirectory = await resolveSandboxWorkDirectory(directory)
|
||||
if (workDirectory === null) {
|
||||
throw new Error(`OpenCode workspace directory is outside the sandboxed project roots: ${directory}`)
|
||||
}
|
||||
return workDirectory
|
||||
}
|
||||
|
||||
private async buildGitEnv(repo: Repo, sshSetup: boolean, silent: boolean): Promise<Record<string, string>> {
|
||||
const baseEnv = this.gitAuthService.getGitEnvironment(silent)
|
||||
const sshEnv = sshSetup ? this.gitAuthService.getSSHEnvironment() : {}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import path from 'path'
|
||||
import { promises as fs, mkdirSync, accessSync, constants } from 'node:fs'
|
||||
|
||||
interface MkdirSafeOptions {
|
||||
@@ -9,6 +10,19 @@ function isPermissionError(error: unknown): boolean {
|
||||
return code === 'EACCES' || code === 'EPERM'
|
||||
}
|
||||
|
||||
export async function writeFileAtomic(filePath: string, content: string, options: { mode?: number } = {}): Promise<void> {
|
||||
const dir = path.dirname(filePath)
|
||||
await mkdirSafe(dir)
|
||||
const tempPath = path.join(dir, `.${path.basename(filePath)}.ocm-tmp-${process.pid}-${Date.now()}`)
|
||||
try {
|
||||
await fs.writeFile(tempPath, content, { encoding: 'utf-8', mode: options.mode ?? 0o600 })
|
||||
await fs.rename(tempPath, filePath)
|
||||
} catch (error) {
|
||||
await fs.rm(tempPath, { force: true }).catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function mkdirSafe(dirPath: string, options: MkdirSafeOptions = {}): Promise<void> {
|
||||
try {
|
||||
await fs.mkdir(dirPath, { ...options, recursive: true })
|
||||
|
||||
@@ -77,18 +77,26 @@ export async function executeCommand(
|
||||
}
|
||||
})
|
||||
|
||||
proc.on('close', (code: number | null) => {
|
||||
proc.on('close', (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (isResolved) return
|
||||
|
||||
isResolved = true
|
||||
if (timeoutId) clearTimeout(timeoutId)
|
||||
|
||||
|
||||
const terminatedBySignal = code === null && signal !== null
|
||||
const exitCode = code === null ? 1 : code
|
||||
const failureDetail = terminatedBySignal ? `signal ${signal}` : `code ${code}`
|
||||
|
||||
if (options.ignoreExitCode) {
|
||||
resolve({ exitCode: code || 0, stdout, stderr })
|
||||
resolve({
|
||||
exitCode,
|
||||
stdout,
|
||||
stderr: terminatedBySignal ? `${stderr}Command terminated by signal ${signal}` : stderr,
|
||||
})
|
||||
} else if (code === 0) {
|
||||
resolve(stdout)
|
||||
} else {
|
||||
const error = new Error(`Command failed with code ${code}: ${stderr || stdout}`)
|
||||
const error = new Error(`Command failed with ${failureDetail}: ${stderr || stdout}`)
|
||||
if (!options.silent) {
|
||||
logger.error(`Command failed: ${args.join(' ')}`, error)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user