feat(secrets): repository secrets and variables injected into agent shells and terminals

Add a GitHub Actions-style store for secrets and variables so tests can read
credentials from the environment without .env files in the repo.

- secrets table keyed by kind, repo (NULL for global) and environment;
  secrets are encrypted with encryptSecret and write-only, variables are plain
  text. Names follow GitHub's rules and reject Manager-reserved names.
- Global (/api/secrets, /api/variables) and repo
  (/api/repos/:id/secrets|variables) routes.
- The trusted .ocm/project.json gains environment and env fields that map
  names to ${{ secrets.X }} / ${{ vars.X }} expressions. Both are part of the
  trust hash; files without them hash as before, so existing trust survives.
- RepoEnvService.resolveForDirectory resolves the repo and approved mapping
  for any directory, including worktrees outside the repo folder, with
  environment > repo > global precedence. It never throws.
- /api/internal/shell-env replaces /git-credentials/gh-env and feeds the
  ocm-gh-env plugin, the sandbox shell plan and TerminalService.create.
- The plugin masks injected secret values as *** in completed tool results.
- The sandbox shell plan is now the only source of the guest environment: the
  plugin pins OCM_SANDBOX_FORWARD_ENV and the shim forwards only those names.
This commit is contained in:
Chris Scott authored and Chris Scott committed 2026-10-23 22:59:57 -04:00
1 parent b431c121a2
commit e0331b43bf
47 files changed
+2073 -156

No files matched your search

@@ -0,0 +1,26 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
id: '202610181400-secrets',
up(db) {
db.run(`
CREATE TABLE IF NOT EXISTS secrets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL CHECK (kind IN ('secret','variable')),
repo_id INTEGER REFERENCES repos(id) ON DELETE CASCADE,
environment TEXT NOT NULL DEFAULT '',
name TEXT NOT NULL,
value TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_secrets_scope ON secrets(kind, COALESCE(repo_id, 0), environment, name)')
},
down(db) {
db.run('DROP TABLE IF EXISTS secrets')
},
}
export default migration
+2
View File
@@ -37,6 +37,7 @@ import migration202610181200 from './202610181200-opencode-servers'
import migration202610181300 from './202610181300-session-server-scope'
import migration202610181310 from './202610181310-multi-run-targets'
import migration202610181320 from './202610181320-remote-schedule-targets'
import migration202610181400 from './202610181400-secrets'
export const allMigrations: Migration[] = [
migration001,
@@ -77,4 +78,5 @@ export const allMigrations: Migration[] = [
migration202610181300,
migration202610181310,
migration202610181320,
migration202610181400,
]
+1
View File
@@ -351,6 +351,7 @@ export function deleteRepo(db: Database, id: number): void {
db.prepare('DELETE FROM multi_run_fusions WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
db.prepare('DELETE FROM multi_run_entries WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
db.prepare('DELETE FROM multi_runs WHERE repo_id = ?').run(id)
db.prepare('DELETE FROM secrets WHERE repo_id = ?').run(id)
for (const table of TABLES_WITH_REPO_ID) {
db.prepare(`DELETE FROM ${table} WHERE repo_id = ?`).run(id)
}
+13 -5
View File
@@ -46,6 +46,7 @@ import { createChangeWalkthroughRoutes } from './routes/change-walkthroughs'
import { getChangeWalkthroughByWalkthroughSession } from './db/change-walkthroughs'
import { createLogRoutes } from './routes/logs'
import { createPreviewRoutes, createPreviewAvailability } from './routes/preview'
import { createGlobalSecretRoutes } from './routes/secrets'
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
import { createInternalRoutes } from './routes/internal'
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
@@ -76,6 +77,8 @@ import { ScheduleRunner, ScheduleService } from './services/schedules'
import { CredentialProvider } from './services/credential-provider'
import { TerminalService } from './services/terminal'
import { ProjectConfigService } from './services/project-config'
import { SecretsService } from './services/secrets'
import { RepoEnvService } from './services/repo-env'
import { RepoWorkspaceService } from './services/repo-workspace'
import { createGitService } from './services/git/GitService'
import { ScheduleWorktreeManager } from './services/schedule-worktree'
@@ -141,6 +144,10 @@ import { DEFAULT_AGENTS_MD } from './constants'
let ipcServer: IPCServer | undefined
const gitAuthService = new GitAuthService()
const gitService = createGitService(gitAuthService)
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
const secretsService = new SecretsService(db)
const repoEnvService = new RepoEnvService(db, projectConfigService, secretsService)
let openCodeSupervisor: OpenCodeSupervisor | undefined
async function ensureOpenCodeConfigFileExists(): Promise<void> {
await withOpenCodeConfigLock(foldLegacyConfigJsonSource)
@@ -239,7 +246,7 @@ try {
opencodeServerManager.setDatabase(db)
detectSandboxCapability()
void new SandboxRuntimeService(db).prepareSandboxOnBoot().catch((error) => {
void new SandboxRuntimeService(db, repoEnvService).prepareSandboxOnBoot().catch((error) => {
logger.warn('Sandbox preparation failed:', error)
})
const openCodeStatus = await openCodeSupervisor.start()
@@ -260,6 +267,7 @@ const terminalService = new TerminalService(
includeLocalCredentials: true,
},
new CredentialProvider(db),
repoEnvService,
)
const resolveServerTerminalService = (serverId: string): TerminalService => {
const connection = opencodeServerRegistry.getConnection(serverId)
@@ -269,8 +277,6 @@ const resolveServerTerminalService = (serverId: string): TerminalService => {
includeLocalCredentials: false,
})
}
const gitService = createGitService(gitAuthService)
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager, opencodeServerRegistry)
scheduleService.setWorktreeRemovedHandler(async (directory) => {
@@ -385,14 +391,14 @@ app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService, changeWalkthroughService, sessionSandboxService))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService, changeWalkthroughService, sessionSandboxService, repoEnvService))
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService, upgradeWebSocket))
const protectedApi = new Hono()
protectedApi.use('/*', requireAuth)
protectedApi.route('/repos', createRepoTerminalSocketRoutes(db, gitAuthService, openCodeClient, terminalService, upgradeWebSocket))
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces))
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces, secretsService))
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor))
protectedApi.route('/files', createFileRoutes())
protectedApi.route('/filesystem', createFilesystemRoutes())
@@ -404,6 +410,8 @@ protectedApi.route('/sse', createSSERoutes())
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
protectedApi.route('/secrets', createGlobalSecretRoutes(secretsService, 'secret'))
protectedApi.route('/variables', createGlobalSecretRoutes(secretsService, 'variable'))
protectedApi.route('/session-pins', createSessionPinRoutes(db))
protectedApi.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService))
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalSocketRoutes(resolveServerTerminalService, upgradeWebSocket))
@@ -1,15 +0,0 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { CredentialProvider } from '../../services/credential-provider'
export function createInternalGitCredentialsRoutes(db: Database) {
const app = new Hono()
app.get('/gh-env', (c) => {
const provider = new CredentialProvider(db)
const cwd = c.req.query('cwd')
return c.json(provider.getGhCliEnv({ cwd }))
})
return app
}
+5 -3
View File
@@ -15,7 +15,7 @@ import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror'
import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces'
import { createInternalSessionRoutes } from './sessions'
import { createInternalAssistantRoutes } from './assistant'
import { createInternalGitCredentialsRoutes } from './git-credentials'
import { createInternalShellEnvRoutes } from './shell-env'
import { createInternalSandboxRoutes } from './sandbox'
import { createInternalSessionArtifactRoutes } from './session-artifacts'
import { createSessionGoalRoutes } from '../session-goals'
@@ -29,6 +29,7 @@ import type { GitAuthService } from '../../services/git-auth'
import type { SessionGoalService } from '../../services/session-goals'
import type { MultiRunService } from '../../services/multi-runs'
import type { ChangeWalkthroughService } from '../../services/change-walkthroughs'
import type { RepoEnvService } from '../../services/repo-env'
export function createInternalRoutes(
db: Database,
@@ -43,6 +44,7 @@ export function createInternalRoutes(
multiRuns: MultiRunService,
changeWalkthroughService: ChangeWalkthroughService,
sessionSandbox: SessionSandboxService,
repoEnvService: RepoEnvService,
) {
const app = new Hono()
app.use('/*', createInternalTokenMiddleware(db))
@@ -64,7 +66,7 @@ export function createInternalRoutes(
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
app.route('/walkthrough-sessions', createInternalWalkthroughSessionRoutes(changeWalkthroughService))
app.route('/session-artifacts', createInternalSessionArtifactRoutes(openCodeClient))
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
app.route('/sandbox', createInternalSandboxRoutes(db, sessionSandbox))
app.route('/shell-env', createInternalShellEnvRoutes(db, repoEnvService))
app.route('/sandbox', createInternalSandboxRoutes(db, sessionSandbox, repoEnvService))
return app
}
+7 -2
View File
@@ -3,6 +3,7 @@ import { z } from 'zod'
import type { Database } from 'bun:sqlite'
import { SandboxRuntimeService } from '../../services/sandbox/runtime'
import type { SessionSandboxService } from '../../services/session-sandbox'
import type { RepoEnvService } from '../../services/repo-env'
import { logger } from '../../utils/logger'
const SandboxShellRequestSchema = z.object({
@@ -12,7 +13,11 @@ const SandboxShellRequestSchema = z.object({
enforced: z.boolean().optional(),
})
export function createInternalSandboxRoutes(db: Database, sessionSandbox: SessionSandboxService) {
export function createInternalSandboxRoutes(
db: Database,
sessionSandbox: SessionSandboxService,
repoEnvService: RepoEnvService,
) {
const app = new Hono()
app.get('/sessions/:sessionId', async (c) => {
@@ -40,7 +45,7 @@ export function createInternalSandboxRoutes(db: Database, sessionSandbox: Sessio
try {
const target = await sessionSandbox.resolveShellTarget(parsed.data.sessionId)
return c.json(
await new SandboxRuntimeService(db).planShell(
await new SandboxRuntimeService(db, repoEnvService).planShell(
parsed.data.directory,
{ ...target, locationDirectory: parsed.data.locationDirectory },
parsed.data.enforced === true,
+22
View File
@@ -0,0 +1,22 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { CredentialProvider } from '../../services/credential-provider'
import type { RepoEnvService } from '../../services/repo-env'
export function createInternalShellEnvRoutes(db: Database, repoEnvService: RepoEnvService) {
const app = new Hono()
app.get('/', async (c) => {
const provider = new CredentialProvider(db)
const cwd = c.req.query('cwd')
const ghEnv = provider.getGhCliEnv({ cwd })
if (!cwd) {
return c.json({ env: ghEnv, mask: [] })
}
const repoEnv = await repoEnvService.resolveForDirectory(cwd)
return c.json({ env: { ...ghEnv, ...repoEnv.env }, mask: repoEnv.maskValues })
})
return app
}
+2 -1
View File
@@ -8,6 +8,7 @@ import { createRepo, getRepoById, setRepoSetting } from '../db/queries'
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
import { createGitService } from '../services/git/GitService'
import { ProjectConfigService } from '../services/project-config'
import type { SecretsService } from '../services/secrets'
import { RepoWorkspaceService } from '../services/repo-workspace'
import type { GitAuthService } from '../services/git-auth'
import type { TerminalService } from '../services/terminal'
@@ -68,7 +69,7 @@ function createTestApp(
} as any
const projectConfigService = new ProjectConfigService(db, createGitService(stubGitAuthService), stubGitAuthService)
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, stubGitAuthService, projectConfigService, terminalService, scheduleService)
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces))
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces, {} as unknown as SecretsService))
return app
}
+5
View File
@@ -18,10 +18,12 @@ import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/open
import { createRepoGitRoutes } from './repo-git'
import { createRepoTerminalRoutes } from './repo-terminals'
import { createRepoProjectConfigRoutes } from './repo-project-config'
import { createRepoSecretRoutes } from './secrets'
import { createScheduleRoutes } from './schedules'
import type { GitAuthService } from '../services/git-auth'
import type { TerminalService } from '../services/terminal'
import type { ProjectConfigService } from '../services/project-config'
import type { SecretsService } from '../services/secrets'
import type { RepoWorkspaceService } from '../services/repo-workspace'
import { createGitService } from '../services/git/GitService'
import { ScheduleService } from '../services/schedules'
@@ -47,6 +49,7 @@ export function createRepoRoutes(
terminalService: TerminalService,
projectConfigService: ProjectConfigService,
repoWorkspaces: RepoWorkspaceService,
secretsService: SecretsService,
) {
const app = new Hono()
const git = createGitService(gitAuthService)
@@ -55,6 +58,8 @@ export function createRepoRoutes(
app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, terminalService))
app.route('/', createRepoProjectConfigRoutes(database, gitAuthService, openCodeClient, projectConfigService, terminalService))
app.route('/:id/schedules', createScheduleRoutes(scheduleService))
app.route('/', createRepoSecretRoutes({ database, projectConfigService, secretsService }, 'secret'))
app.route('/', createRepoSecretRoutes({ database, projectConfigService, secretsService }, 'variable'))
app.post('/', async (c) => {
try {
+139
View File
@@ -0,0 +1,139 @@
import { Hono } from 'hono'
import type { Context } from 'hono'
import type { Database } from 'bun:sqlite'
import type { Repo } from '@opencode-manager/shared/types'
import { EnvironmentNameSchema, SecretNameSchema, SetSecretRequestSchema, type SecretKind } from '@opencode-manager/shared/schemas'
import { getRepoById } from '../db/queries'
import { SecretsService, SecretsServiceError } from '../services/secrets'
import type { ProjectConfigService } from '../services/project-config'
import { handleServiceError } from '../utils/route-helpers'
function readName(c: Context): { name: string } | Response {
const parsed = SecretNameSchema.safeParse(c.req.param('name'))
if (!parsed.success) {
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid name' }, 400)
}
return { name: parsed.data }
}
function readEnvironmentQuery(c: Context): { environment: string | null } | Response {
const value = c.req.query('environment')
if (value === undefined) {
return { environment: null }
}
const parsed = EnvironmentNameSchema.safeParse(value)
if (!parsed.success) {
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid environment' }, 400)
}
return { environment: parsed.data }
}
export function createGlobalSecretRoutes(secretsService: SecretsService, kind: SecretKind) {
const app = new Hono()
app.get('/', (c) => c.json({ items: secretsService.list(kind, null) }))
app.put('/:name', async (c) => {
const name = readName(c)
if (name instanceof Response) return name
const body = await c.req.json().catch(() => ({}))
const parsed = SetSecretRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid request' }, 400)
}
try {
secretsService.set(kind, null, parsed.data.environment ?? null, name.name, parsed.data.value)
return c.body(null, 204)
} catch (error: unknown) {
return handleServiceError(c, error, 'Failed to store secret', SecretsServiceError)
}
})
app.delete('/:name', (c) => {
const name = readName(c)
if (name instanceof Response) return name
const deleted = secretsService.delete(kind, null, null, name.name)
if (!deleted) {
return c.json({ error: 'Not found' }, 404)
}
return c.body(null, 204)
})
return app
}
export interface RepoSecretRouteDeps {
database: Database
projectConfigService: ProjectConfigService
secretsService: SecretsService
}
export function createRepoSecretRoutes(deps: RepoSecretRouteDeps, kind: SecretKind) {
const { database, projectConfigService, secretsService } = deps
const segment = kind === 'secret' ? 'secrets' : 'variables'
const app = new Hono()
const resolveProjectRepo = async (c: Context): Promise<Repo | Response> => {
const id = Number.parseInt(c.req.param('id') ?? '', 10)
if (Number.isNaN(id)) {
return c.json({ error: 'Invalid repo id' }, 400)
}
const repo = getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
return projectConfigService.resolveProjectRepo(repo)
}
app.get(`/:id/${segment}`, async (c) => {
const repo = await resolveProjectRepo(c)
if (repo instanceof Response) return repo
return c.json({ items: secretsService.list(kind, repo.id) })
})
app.put(`/:id/${segment}/:name`, async (c) => {
const name = readName(c)
if (name instanceof Response) return name
const body = await c.req.json().catch(() => ({}))
const parsed = SetSecretRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid request' }, 400)
}
const repo = await resolveProjectRepo(c)
if (repo instanceof Response) return repo
try {
secretsService.set(kind, repo.id, parsed.data.environment ?? null, name.name, parsed.data.value)
return c.body(null, 204)
} catch (error: unknown) {
return handleServiceError(c, error, 'Failed to store secret', SecretsServiceError)
}
})
app.delete(`/:id/${segment}/:name`, async (c) => {
const name = readName(c)
if (name instanceof Response) return name
const environment = readEnvironmentQuery(c)
if (environment instanceof Response) return environment
const repo = await resolveProjectRepo(c)
if (repo instanceof Response) return repo
const deleted = secretsService.delete(kind, repo.id, environment.environment, name.name)
if (!deleted) {
return c.json({ error: 'Not found' }, 404)
}
return c.body(null, 204)
})
return app
}
+85 -10
View File
@@ -1,36 +1,111 @@
export function buildGhEnvPluginSource(id: string): string {
return `const TTL_MS = 5000
let cache = new Map()
const maskValues = new Set()
async function fetchGhEnv(cwd) {
function rememberMasks(values) {
if (!Array.isArray(values)) return
for (const value of values) {
if (typeof value === 'string' && value.length > 0) maskValues.add(value)
}
}
function emptyBody() {
return { env: {}, mask: [] }
}
async function fetchShellEnv(cwd) {
const baseUrl = process.env.OCM_INTERNAL_API_URL
const token = process.env.OCM_INTERNAL_TOKEN
if (!baseUrl || !token) return {}
if (!baseUrl || !token) return emptyBody()
const now = Date.now()
const cacheKey = cwd || ''
const cached = cache.get(cacheKey)
if (cached && now < cached.expiry) return cached.env
if (cached && now < cached.expiry) return cached
try {
const url = new URL(baseUrl + '/git-credentials/gh-env')
const url = new URL(baseUrl + '/shell-env')
if (cwd) url.searchParams.set('cwd', cwd)
const res = await fetch(url, {
headers: { Authorization: 'Bearer ' + token },
})
if (!res.ok) return cached?.env || {}
const env = await res.json()
const next = { expiry: now + TTL_MS, env: env && typeof env === 'object' ? env : {} }
if (!res.ok) return cached || emptyBody()
const body = await res.json()
const env = body && typeof body.env === 'object' && body.env !== null ? body.env : {}
const mask = body && Array.isArray(body.mask) ? body.mask : []
const next = { expiry: now + TTL_MS, env, mask }
cache.set(cacheKey, next)
return next.env
return next
} catch {
return cached?.env || {}
return cached || emptyBody()
}
}
function isPlainObject(value) {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
const proto = Object.getPrototypeOf(value)
return proto === Object.prototype || proto === null
}
function containsMask(text) {
for (const value of maskValues) {
if (text.indexOf(value) !== -1) return true
}
return false
}
function applyMasks(text) {
let result = text
const ordered = Array.from(maskValues).sort(function (a, b) { return b.length - a.length })
for (const value of ordered) {
if (result.indexOf(value) !== -1) result = result.split(value).join('***')
}
return result
}
function maskValue(value) {
if (typeof value === 'string') {
return containsMask(value) ? applyMasks(value) : value
}
if (Array.isArray(value)) {
let copy = null
for (let index = 0; index < value.length; index += 1) {
const masked = maskValue(value[index])
if (masked !== value[index]) {
if (copy === null) copy = value.slice()
copy[index] = masked
}
}
return copy === null ? value : copy
}
if (isPlainObject(value)) {
let copy = null
for (const key of Object.keys(value)) {
const masked = maskValue(value[key])
if (masked !== value[key]) {
if (copy === null) copy = Object.assign({}, value)
copy[key] = masked
}
}
return copy === null ? value : copy
}
return value
}
export default {
id: '${id}',
async setup(ctx) {
await ctx.shell.hook('create.before', async (event) => {
Object.assign(event.env, await fetchGhEnv(event.cwd))
const body = await fetchShellEnv(event.cwd)
rememberMasks(body.mask)
Object.assign(event.env, body.env)
})
await ctx.tool.hook('execute.after', async (event) => {
if (event.status !== 'completed') return
if (maskValues.size === 0) return
if (event.result === null || typeof event.result !== 'object') return
const source = { ...event.result }
const masked = maskValue(source)
if (masked !== source) event.result = masked
})
},
}
@@ -1,6 +1,7 @@
import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
import {
SANDBOX_FORWARDED_ENV_NAMES,
SANDBOX_SHELL_ENV_FORWARD,
SANDBOX_SHELL_ENV_NAME,
SANDBOX_SHELL_ENV_WORKDIR,
} from './sandbox/shell-shim'
@@ -25,6 +26,7 @@ var SHELL_SHIM_PATH = ${JSON.stringify(shellShimPath)}
var ENV_WORKDIR = ${JSON.stringify(SANDBOX_SHELL_ENV_WORKDIR)}
var ENV_SANDBOX_NAME = ${JSON.stringify(SANDBOX_SHELL_ENV_NAME)}
var FORWARDED_ENV_NAMES = ${JSON.stringify(SANDBOX_FORWARDED_ENV_NAMES)}
var ENV_FORWARD = ${JSON.stringify(SANDBOX_SHELL_ENV_FORWARD)}
var SERVICE_SETTINGS_PATH = path.resolve(${JSON.stringify(serviceSettingsPath)})
var SERVICE_SETTINGS_DIRECTORY = path.dirname(SERVICE_SETTINGS_PATH)
var SERVICE_SETTINGS_DENIED = 'OpenCode Manager denies access to its service settings file (service.json), which holds the OpenCode server password.'
@@ -312,11 +314,15 @@ async function pinSandboxShell(event, sessionID, locationDirectory) {
throw unavailable('the sandbox shell shim is missing at ' + SHELL_SHIM_PATH)
}
var plan = await planSandboxShell(event.cwd, sessionID, locationDirectory)
var forwardNames = []
if (plan.env !== null && typeof plan.env === 'object') {
for (var name of FORWARDED_ENV_NAMES) {
if (typeof plan.env[name] === 'string') {
event.env[name] = plan.env[name]
}
for (var name of Object.keys(plan.env)) {
var value = plan.env[name]
if (typeof value !== 'string') continue
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue
if (name.startsWith('OCM_') || name.startsWith('MSB_')) continue
event.env[name] = value
forwardNames.push(name)
}
}
if (!lockAccessor(event, 'shell', SHELL_SHIM_PATH)) {
@@ -328,6 +334,9 @@ async function pinSandboxShell(event, sessionID, locationDirectory) {
if (!lockAccessor(event.env, ENV_SANDBOX_NAME, plan.name)) {
throw unavailable('sandbox enforcement could not pin the sandbox session name; aborting before the command runs on the host')
}
if (!lockAccessor(event.env, ENV_FORWARD, forwardNames.join(' '))) {
throw unavailable('sandbox enforcement could not pin the forwarded environment list; aborting before the command runs on the host')
}
}
async function wrapSandboxedShellTool(ctx) {
+22 -4
View File
@@ -31,6 +31,14 @@ const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash'
const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json')
const REPO_CONFIG_SYMLINK_MESSAGE = '.ocm/project.json must not be a symbolic link'
function describeZodIssue(issue: { path?: PropertyKey[]; message: string } | undefined): string {
if (!issue) {
return 'Invalid value'
}
const issuePath = (issue.path ?? []).map(String).join('.')
return issuePath ? `${issuePath}: ${issue.message}` : issue.message
}
export interface RepoFileState {
exists: boolean
file: RepoProjectFile | null
@@ -280,7 +288,7 @@ export class ProjectConfigService {
}
}
private isRepoFileTrusted(projectRepo: Repo, repoFile: RepoFileState): boolean {
isRepoFileTrusted(projectRepo: Repo, repoFile: RepoFileState): boolean {
return (
repoFile.hash !== null &&
repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY)
@@ -306,7 +314,7 @@ export class ProjectConfigService {
const parsed = RepoProjectFileSchema.safeParse(parsedJson)
if (!parsed.success) {
return { exists: true, file: null, hash: null, error: 'Does not match the project file schema' }
return { exists: true, file: null, hash: null, error: `Does not match the project file schema: ${describeZodIssue(parsed.error.issues[0])}` }
}
return { exists: true, file: parsed.data, hash: this.hashRepoFile(parsed.data) }
} catch {
@@ -315,7 +323,7 @@ export class ProjectConfigService {
}
buildRepoFileExecutable(file: RepoProjectFile): NonNullable<ProjectConfigResponse['repoFile']['executable']> {
return {
const executable: NonNullable<ProjectConfigResponse['repoFile']['executable']> = {
actions: (file.projectActions ?? []).map((action) => ({
id: action.id,
name: action.name,
@@ -325,6 +333,13 @@ export class ProjectConfigService {
})),
setup: file.setupWorktree ?? [],
}
if (file.environment !== undefined) {
executable.environment = file.environment
}
if (file.env && Object.keys(file.env).length > 0) {
executable.env = file.env
}
return executable
}
hashRepoFile(file: RepoProjectFile): string {
@@ -459,7 +474,10 @@ export class ProjectConfigService {
return false
}
const hasExecutable =
(state.file.projectActions?.length ?? 0) > 0 || (state.file.setupWorktree?.length ?? 0) > 0
(state.file.projectActions?.length ?? 0) > 0 ||
(state.file.setupWorktree?.length ?? 0) > 0 ||
(state.file.env !== undefined && Object.keys(state.file.env).length > 0) ||
state.file.environment !== undefined
return hasExecutable && !this.isRepoFileTrusted(projectRepo, state)
}
+116
View File
@@ -0,0 +1,116 @@
import type { Database } from 'bun:sqlite'
import type { Repo } from '@opencode-manager/shared/types'
import { interpolateEnvExpressions, type EnvExpressionReference } from '@opencode-manager/shared/utils'
import { getRepoByDirectory } from '../db/queries'
import { executeCommand } from '../utils/process'
import { logger } from '../utils/logger'
import { resolveMainCheckoutPath, resolveRepoForDirectory } from './repo'
import type { ProjectConfigService } from './project-config'
import type { SecretsService } from './secrets'
export interface ResolvedRepoEnv {
env: Record<string, string>
maskValues: string[]
missing: string[]
}
function emptyResult(): ResolvedRepoEnv {
return { env: {}, maskValues: [], missing: [] }
}
export class RepoEnvService {
constructor(
private readonly db: Database,
private readonly projectConfigService: ProjectConfigService,
private readonly secretsService: SecretsService,
) {}
/**
* Resolves the repository environment for a directory.
*
* Never rejects: any internal failure is logged as a warning naming the directory
* and resolves to an empty result.
*/
async resolveForDirectory(cwd: string): Promise<ResolvedRepoEnv> {
try {
const topLevel = await this.findTopLevel(cwd)
if (!topLevel) {
return emptyResult()
}
const repo = await this.findRepo(topLevel)
if (!repo) {
return emptyResult()
}
const projectRepo = await this.projectConfigService.resolveProjectRepo(repo)
const repoFile = this.projectConfigService.readRepoFile(topLevel)
if (!repoFile.file || !this.projectConfigService.isRepoFileTrusted(projectRepo, repoFile)) {
return emptyResult()
}
const mapping = repoFile.file.env
if (!mapping || Object.keys(mapping).length === 0) {
return emptyResult()
}
const resolved = this.secretsService.resolveValues(projectRepo.id, repoFile.file.environment ?? null)
const maskValues = new Set<string>()
const missing = new Set<string>()
const lookup = (reference: EnvExpressionReference): string | undefined => {
const values = reference.context === 'secrets' ? resolved.secrets : resolved.vars
const found = values[reference.name]
if (found === undefined) {
missing.add(`${reference.context}.${reference.name}`)
return undefined
}
if (reference.context === 'secrets') {
maskValues.add(found)
}
return found
}
const env: Record<string, string> = {}
for (const [name, template] of Object.entries(mapping)) {
env[name] = interpolateEnvExpressions(template, lookup).value
}
return {
env,
maskValues: [...maskValues].filter((value) => value.length >= 4).sort((a, b) => b.length - a.length),
missing: [...missing],
}
} catch (error) {
logger.warn(`Failed to resolve repository environment for ${cwd}`, error)
return emptyResult()
}
}
private async findTopLevel(cwd: string): Promise<string | null> {
try {
const output = await executeCommand(['git', '-C', cwd, 'rev-parse', '--show-toplevel'], { silent: true })
const topLevel = output.trim()
return topLevel.length > 0 ? topLevel : null
} catch {
return null
}
}
private async findRepo(topLevel: string): Promise<Repo | null> {
const direct = getRepoByDirectory(this.db, topLevel)
if (direct) {
return direct
}
const mainCheckout = await resolveMainCheckoutPath(topLevel)
if (mainCheckout) {
const mainRepo = getRepoByDirectory(this.db, mainCheckout)
if (mainRepo) {
return mainRepo
}
}
return resolveRepoForDirectory(this.db, topLevel)
}
}
+9 -1
View File
@@ -13,6 +13,7 @@ import { isPathWithinRoot, mkdirSafe } from '../../utils/fs-safe'
import { logger } from '../../utils/logger'
import { SettingsService } from '../settings'
import { CredentialProvider } from '../credential-provider'
import type { RepoEnvService } from '../repo-env'
import { getGitIdentityEnvForDirectory } from '../git-identity'
import { getProcessIdentityAttestationError } from '../opencode/process-identity'
import { detectSandboxCapability } from './capability'
@@ -1049,7 +1050,10 @@ function sandboxMaxRunningVms(db: Database): number {
}
export class SandboxRuntimeService {
constructor(private readonly db: Database) {}
constructor(
private readonly db: Database,
private readonly repoEnvService?: RepoEnvService,
) {}
async prepareSandboxOnBoot(): Promise<void> {
if (!this.isSandboxEnabled()) return
@@ -1119,6 +1123,10 @@ export class SandboxRuntimeService {
...new CredentialProvider(this.db).getSandboxGitEnv({ cwd: directory }),
...await getGitIdentityEnvForDirectory(directory, this.db),
}
if (this.repoEnvService) {
const repoEnv = await this.repoEnvService.resolveForDirectory(directory)
Object.assign(env, repoEnv.env)
}
return Object.keys(env).length > 0
? { mode: 'sandbox', name: spec.name, workdir: workDirectory, env }
: { mode: 'sandbox', name: spec.name, workdir: workDirectory }
+41 -20
View File
@@ -15,18 +15,25 @@ export const SANDBOX_SHELL_ENV_WORKDIR = 'OCM_SANDBOX_WORKDIR'
export const SANDBOX_SHELL_ENV_NAME = 'OCM_SANDBOX_NAME'
/**
* Upper bound on `http.<host>.extraheader` pairs forwarded into the microVM.
* The shim enumerates a fixed set of variable names rather than expanding
* `GIT_CONFIG_KEY_$i` indirectly, which would require `eval` on values holding
* credentials. Credentials are configured per host, so this bounds the number
* of distinct git hosts a sandboxed command can authenticate against.
* Space-separated allow-list of variable names the shim forwards from its own
* environment into the microVM with `msb exec -e`. The plugin pins it from the
* sandbox plan, so only names the plan approved reach a sandboxed command; the
* guest environment is otherwise empty.
*/
export const SANDBOX_SHELL_ENV_FORWARD = 'OCM_SANDBOX_FORWARD_ENV'
/**
* Upper bound on `http.<host>.extraheader` pairs the planner forwards into the
* microVM. Credentials are configured per host, so this bounds the number of
* distinct git hosts a sandboxed command can authenticate against.
*/
export const SANDBOX_MAX_FORWARDED_GIT_CONFIGS = 16
/**
* Variables the shim copies from its own environment into the microVM with
* `msb exec -e`. The guest environment is otherwise empty, so anything absent
* from this list never reaches a sandboxed command.
* Variables the shim always copies from its own environment into the microVM
* with `msb exec -e`, independent of the plan-approved allow-list. The guest
* environment is otherwise empty, so anything absent from this list and from
* the allow-list never reaches a sandboxed command.
*/
export const SANDBOX_FORWARDED_ENV_NAMES: readonly string[] = [
'GIT_TERMINAL_PROMPT',
@@ -44,9 +51,10 @@ export const SANDBOX_FORWARDED_ENV_NAMES: readonly string[] = [
]
/**
* Drops `http.<host>.extraheader` pairs the shim cannot forward, so the guest
* never sees a `GIT_CONFIG_COUNT` that overstates the pairs actually present.
* A count larger than the pairs in the environment makes git fail outright.
* Drops `http.<host>.extraheader` pairs beyond the forwarding cap, so the
* guest never sees a `GIT_CONFIG_COUNT` that overstates the pairs actually
* present. A count larger than the pairs in the environment makes git fail
* outright.
*/
export function limitForwardedGitConfigs(env: Record<string, string>): {
env: Record<string, string>
@@ -85,9 +93,22 @@ export function buildSandboxShellShimScript(): string {
'--timeout',
`${timeoutSeconds}s`,
].join(' ')
const forwardEnv = SANDBOX_FORWARDED_ENV_NAMES.map(
(name) => ` if [ -n "\${${name}+x}" ]; then set -- "$@" -e "${name}=$${name}"; fi`,
).join('\n')
const forwardEnv = [
...SANDBOX_FORWARDED_ENV_NAMES.map(
(name) => `if [ -n "\${${name}+x}" ]; then set -- "$@" -e "${name}=$${name}"; fi`,
),
'set -f',
`for OCM_SHIM_NAME in \${${SANDBOX_SHELL_ENV_FORWARD}}; do`,
` case "$OCM_SHIM_NAME" in`,
` ''|[0-9]*|*[!A-Za-z0-9_]*|OCM_*|MSB_*|${SANDBOX_FORWARDED_ENV_NAMES.join('|')}) continue ;;`,
' esac',
` eval "OCM_SHIM_SET=\\\${$OCM_SHIM_NAME+x}"`,
` [ -n "$OCM_SHIM_SET" ] || continue`,
` eval "OCM_SHIM_VALUE=\\\${$OCM_SHIM_NAME}"`,
` set -- "$@" -e "$OCM_SHIM_NAME=$OCM_SHIM_VALUE"`,
'done',
'set +f',
].join('\n')
return `#!/bin/sh
if [ -z "\${${SANDBOX_SHELL_ENV_WORKDIR}:-}" ]; then
echo 'ocm-sandbox-shell: sandbox working directory missing; refusing to run on the host' >&2
@@ -100,16 +121,16 @@ case "\${${SANDBOX_SHELL_ENV_NAME}:-}" in
exit 126
;;
esac
ocm_argc=$#
OCM_SHIM_ARGC=$#
set -- "$@" ${execArgs}
${forwardEnv}
set -- "$@" -- sh
ocm_i=0
while [ "$ocm_i" -lt "$ocm_argc" ]; do
ocm_arg=$1
OCM_SHIM_I=0
while [ "$OCM_SHIM_I" -lt "$OCM_SHIM_ARGC" ]; do
OCM_SHIM_ARG=$1
shift
set -- "$@" "$ocm_arg"
ocm_i=$((ocm_i + 1))
set -- "$@" "$OCM_SHIM_ARG"
OCM_SHIM_I=$((OCM_SHIM_I + 1))
done
exec "$@"
`
+123
View File
@@ -0,0 +1,123 @@
import type { Database } from 'bun:sqlite'
import type { SecretEntry, SecretKind } from '@opencode-manager/shared/schemas'
import { decryptSecret, encryptSecret } from '../utils/crypto'
import { logger } from '../utils/logger'
export class SecretsServiceError extends Error {
constructor(message: string, public statusCode: number = 500) {
super(message)
this.name = 'SecretsServiceError'
}
}
interface SecretRow {
kind: SecretKind
repo_id: number | null
environment: string
name: string
value: string
updated_at: number
}
interface SecretValueRow {
kind: SecretKind
repo_id: number | null
environment: string
name: string
value: string
}
export interface ResolvedSecretValues {
secrets: Record<string, string>
vars: Record<string, string>
}
export class SecretsService {
constructor(private readonly db: Database) {}
list(kind: SecretKind, repoId: number | null): SecretEntry[] {
return this.selectRows(kind, repoId).map((row) => this.toEntry(kind, row))
}
set(kind: SecretKind, repoId: number | null, environment: string | null, name: string, value: string): void {
const normalizedEnvironment = environment ?? ''
if (repoId === null && normalizedEnvironment !== '') {
throw new SecretsServiceError('Environments are only supported for repository secrets', 400)
}
const now = Date.now()
const storedValue = kind === 'secret' ? encryptSecret(value) : value
this.db
.prepare(
`INSERT INTO secrets (kind, repo_id, environment, name, value, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
)
.run(kind, repoId, normalizedEnvironment, name, storedValue, now, now)
}
delete(kind: SecretKind, repoId: number | null, environment: string | null, name: string): boolean {
const result = this.db
.prepare('DELETE FROM secrets WHERE kind = ? AND repo_id IS ? AND environment = ? AND name = ?')
.run(kind, repoId, environment ?? '', name)
return result.changes > 0
}
resolveValues(repoId: number, environment: string | null): ResolvedSecretValues {
const rows = this.db
.prepare(
`SELECT kind, repo_id, environment, name, value FROM secrets
WHERE repo_id IS NULL OR repo_id = ?
ORDER BY CASE WHEN repo_id IS NULL THEN 0 WHEN environment = '' THEN 1 ELSE 2 END`,
)
.all(repoId) as SecretValueRow[]
const secrets: Record<string, string> = {}
const vars: Record<string, string> = {}
for (const row of rows) {
if (row.repo_id !== null && row.environment !== '' && row.environment !== environment) {
continue
}
if (row.kind === 'secret') {
try {
secrets[row.name] = decryptSecret(row.value)
} catch {
logger.warn(`Skipping secret "${row.name}" because it could not be decrypted`)
}
} else {
vars[row.name] = row.value
}
}
return { secrets, vars }
}
private selectRows(kind: SecretKind, repoId: number | null): SecretRow[] {
if (repoId === null) {
return this.db
.prepare(
'SELECT kind, repo_id, environment, name, value, updated_at FROM secrets WHERE kind = ? AND repo_id IS NULL ORDER BY name',
)
.all(kind) as SecretRow[]
}
return this.db
.prepare(
'SELECT kind, repo_id, environment, name, value, updated_at FROM secrets WHERE kind = ? AND repo_id = ? ORDER BY name',
)
.all(kind, repoId) as SecretRow[]
}
private toEntry(kind: SecretKind, row: SecretRow): SecretEntry {
return {
name: row.name,
environment: row.environment === '' ? null : row.environment,
updatedAt: row.updated_at,
...(kind === 'variable' ? { value: row.value } : {}),
}
}
}
+12 -1
View File
@@ -3,6 +3,7 @@ import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/share
import type { TerminalInfo, TerminalKind } from '@opencode-manager/shared/types'
import type { OpenCodeClient } from './opencode/client'
import type { CredentialProvider } from './credential-provider'
import type { RepoEnvService } from './repo-env'
import { toWebSocketUrl } from './opencode/upstream'
import { bridgeWebSocket, type WebSocketBridge, type WebSocketPeer } from '../utils/websocket-bridge'
import { TerminalHub, TerminalHubRegistry } from './terminal-hub'
@@ -56,13 +57,21 @@ export class TerminalService {
constructor(
private readonly target: TerminalTarget,
private readonly credentialProvider: CredentialProvider,
private readonly repoEnvService: RepoEnvService,
private readonly openSocket: (url: string) => WebSocket = (url) => new WebSocket(url),
private readonly hubs: TerminalHubRegistry = new TerminalHubRegistry(),
private readonly deferredReleases: Map<string, DeferredRelease> = new Map(),
) {}
forTarget(target: TerminalTarget): TerminalService {
return new TerminalService(target, this.credentialProvider, this.openSocket, this.hubs, this.deferredReleases)
return new TerminalService(
target,
this.credentialProvider,
this.repoEnvService,
this.openSocket,
this.hubs,
this.deferredReleases,
)
}
async list(directory: string): Promise<TerminalInfo[]> {
@@ -75,6 +84,7 @@ export class TerminalService {
input.command !== undefined && DEFERRED_START_KINDS.has(input.kind) && process.platform !== 'win32'
? deferCommandStart(input.command, input.args ?? [])
: undefined
const repoEnv = (await this.repoEnvService.resolveForDirectory(directory)).env
const result = await this.target.client.api.pty.create({
location: { directory },
title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }),
@@ -86,6 +96,7 @@ export class TerminalService {
}),
env: {
...(this.target.includeLocalCredentials ? this.credentialProvider.getGhCliEnv({ cwd: directory }) : {}),
...repoEnv,
...input.env,
},
})