mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
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:
1 parent
b431c121a2
commit
e0331b43bf
47 files changed
+2073
-156
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -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 "$@"
|
||||
`
|
||||
|
||||
@@ -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 } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user