feat(opencode-config): redact secrets and add MCP listing to the internal config API (#366)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-28 23:52:41 -04:00
1 parent 68b13c8e35
commit a1b7f58aae
31 files changed
+1238 -181

No files matched your search

+1 -1
View File
@@ -29,7 +29,7 @@ export function createInternalRoutes(
app.route('/schedules', createScheduleRoutes(scheduleService))
app.route('/notifications', createInternalNotificationRoutes(notificationService))
app.route('/settings', createInternalSettingsRoutes(settingsService))
app.route('/opencode-config', createOpenCodeConfigRoutes(settingsService, openCodeClient))
app.route('/opencode-config', createOpenCodeConfigRoutes(settingsService, openCodeClient, { redactSecrets: true }))
const repos = new Hono()
repos.route('/', createInternalRepoRoutes(db, settingsService))
repos.route('/:id/schedules', createScheduleRoutes(scheduleService))
+147 -37
View File
@@ -1,21 +1,63 @@
import { Hono } from 'hono'
import { Hono, type Context } from 'hono'
import { z } from 'zod'
import { UpdateOpenCodeConfigRequestSchema } from '@opencode-manager/shared/schemas'
import {
UpdateOpenCodeConfigPatchRequestSchema,
UpdateOpenCodeConfigRequestSchema,
} from '@opencode-manager/shared/schemas'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
import { ClientError, openCodeLocation } from '@opencode-manager/shared/opencode'
import {
ClientError,
mcpServerViewsFromConfig,
mcpStatusByName,
openCodeLocation,
type McpServerView,
type McpStatusMap,
} from '@opencode-manager/shared/opencode'
import type { SettingsService } from '../services/settings'
import type { OpenCodeClient } from '../services/opencode/client'
import {
OpenCodeConfigConflictError,
OpenCodeConfigRedactedValueError,
OpenCodeConfigShadowedRemovalError,
OpenCodeConfigSourceInvalidError,
readOpenCodeConfigFile,
withOpenCodeConfigLock,
} from '../services/opencode-config-file'
import { applyOpenCodeConfigUpdate, toOpenCodeConfigApplyResponse } from '../services/opencode-config-apply'
import { redactOpenCodeConfigContent, redactOpenCodeConfigFile } from '../services/opencode-config-redact'
import { logger } from '../utils/logger'
export function createOpenCodeConfigRoutes(settingsService: SettingsService, openCodeClient: OpenCodeClient) {
interface OpenCodeConfigRoutesOptions {
redactSecrets?: boolean
}
async function readMcpStatus(openCodeClient: OpenCodeClient): Promise<McpStatusMap> {
try {
const servers = await openCodeClient.api.mcp.list(openCodeLocation(getWorkspacePath()))
return mcpStatusByName(servers.data)
} catch (error) {
logger.warn('Failed to read live MCP server status:', error)
return {}
}
}
function mergeMcpServerStatus(views: McpServerView[], status: McpStatusMap) {
return views.map((view) => {
const live = status[view.name]
if (!live) return view
return {
...view,
status: live.status,
...('error' in live && live.error ? { error: live.error } : {}),
}
})
}
export function createOpenCodeConfigRoutes(
settingsService: SettingsService,
openCodeClient: OpenCodeClient,
options: OpenCodeConfigRoutesOptions = {},
) {
const app = new Hono()
app.get('/', async (c) => {
@@ -24,7 +66,7 @@ export function createOpenCodeConfigRoutes(settingsService: SettingsService, ope
if (!config) {
return c.json({ error: 'No OpenCode config file found' }, 404)
}
return c.json(config)
return c.json(options.redactSecrets ? redactOpenCodeConfigFile(config) : config)
} catch (error) {
logger.error('Failed to get OpenCode config:', error)
return c.json({ error: 'Failed to get OpenCode config' }, 500)
@@ -34,7 +76,18 @@ export function createOpenCodeConfigRoutes(settingsService: SettingsService, ope
app.get('/effective', async (c) => {
try {
const entries = await openCodeClient.api.config.get(openCodeLocation(getWorkspacePath()))
return c.json({ entries })
return c.json({
entries: options.redactSecrets
? entries.map((entry) =>
entry.type === 'document'
? {
...entry,
info: redactOpenCodeConfigContent(entry.info).content as typeof entry.info,
}
: entry,
)
: entries,
})
} catch (error) {
logger.error('Failed to get effective OpenCode config:', error)
if (error instanceof ClientError) {
@@ -47,6 +100,23 @@ export function createOpenCodeConfigRoutes(settingsService: SettingsService, ope
}
})
app.get('/mcp', async (c) => {
try {
const [config, status] = await Promise.all([
withOpenCodeConfigLock(readOpenCodeConfigFile),
readMcpStatus(openCodeClient),
])
const views = mcpServerViewsFromConfig(config?.content.mcp)
return c.json({
revision: config?.revision ?? null,
servers: mergeMcpServerStatus(views, status),
})
} catch (error) {
logger.error('Failed to get OpenCode MCP servers:', error)
return c.json({ error: 'Failed to get OpenCode MCP servers' }, 500)
}
})
app.put('/', async (c) => {
let body: unknown
try {
@@ -60,40 +130,80 @@ export function createOpenCodeConfigRoutes(settingsService: SettingsService, ope
return c.json({ error: 'Invalid config data', details: parsed.error.issues }, 400)
}
return applyUpdate(c, {
content: parsed.data.content,
source: parsed.data.source,
expectedRevision: parsed.data.expectedRevision,
settingsService,
openCodeClient,
}, options.redactSecrets)
})
app.patch('/', async (c) => {
let body: unknown
try {
const result = await applyOpenCodeConfigUpdate({
content: parsed.data.content,
source: parsed.data.source,
expectedRevision: parsed.data.expectedRevision,
settingsService,
openCodeClient,
})
const { status, body: responseBody } = toOpenCodeConfigApplyResponse(result)
return c.json(responseBody, status)
} catch (error) {
logger.error('Failed to update OpenCode config:', error)
if (error instanceof OpenCodeConfigConflictError) {
return c.json({
error: error.message,
expectedRevision: error.expectedRevision,
actualRevision: error.actualRevision,
}, 409)
}
if (error instanceof OpenCodeConfigSourceInvalidError) {
return c.json({ error: error.message, sources: error.sources }, 400)
}
if (error instanceof OpenCodeConfigShadowedRemovalError) {
return c.json({ error: error.message, paths: error.paths, sources: error.sources }, 409)
}
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
}
if (error instanceof SyntaxError) {
return c.json({ error: 'Invalid config data', details: error.message }, 400)
}
return c.json({ error: 'Failed to update OpenCode config' }, 500)
body = await c.req.json()
} catch {
return c.json({ error: 'Invalid JSON' }, 400)
}
const parsed = UpdateOpenCodeConfigPatchRequestSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: 'Invalid config data', details: parsed.error.issues }, 400)
}
return applyUpdate(c, {
content: parsed.data.patch,
source: parsed.data.source,
expectedRevision: parsed.data.expectedRevision,
mode: 'merge',
settingsService,
openCodeClient,
}, options.redactSecrets)
})
return app
}
async function applyUpdate(
c: Context,
input: Parameters<typeof applyOpenCodeConfigUpdate>[0],
redactSecrets = false,
) {
try {
const result = await applyOpenCodeConfigUpdate(input)
const response = toOpenCodeConfigApplyResponse(result)
if (!redactSecrets) {
return c.json(response.body, response.status)
}
return c.json({
...redactOpenCodeConfigFile(result.config),
...(result.status === 'restart_pending' ? { restartRequired: true } : {}),
}, response.status)
} catch (error) {
logger.error('Failed to update OpenCode config:', error)
if (error instanceof OpenCodeConfigConflictError) {
return c.json({
error: error.message,
expectedRevision: error.expectedRevision,
actualRevision: error.actualRevision,
}, 409)
}
if (error instanceof OpenCodeConfigSourceInvalidError) {
return c.json({ error: error.message, sources: error.sources }, 400)
}
if (error instanceof OpenCodeConfigShadowedRemovalError) {
return c.json({ error: error.message, paths: error.paths, sources: error.sources }, 409)
}
if (error instanceof OpenCodeConfigRedactedValueError) {
return c.json({ error: error.message, paths: error.paths }, 400)
}
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
}
if (error instanceof SyntaxError) {
return c.json({ error: 'Invalid config data', details: error.message }, 400)
}
return c.json({ error: 'Failed to update OpenCode config' }, 500)
}
}
+45 -18
View File
@@ -721,19 +721,19 @@ The global configuration files on disk are the source of truth. Use the \`ocm\`
### GET /opencode-config
Read the merged persisted global configuration and its source files. Returns \`404\` when no source exists. This is not the running instance configuration: project overrides and expanded environment values are not included. \`GET /opencode-config/effective\` reads the running server's configuration separately as \`entries\`: the configuration documents and discovery directories in precedence order, lowest first, each shaped as \`{ type: 'document', path, info }\` or \`{ type: 'directory', path }\`. Its \`info\` values are expanded for the running server; never copy this response into a save.
Read the merged persisted global configuration and its source files. Returns \`404\` when no source exists. Secret values are replaced with \`<redacted>\` and the raw source text is omitted, so a read never returns credentials; \`redactedPaths\` lists the hidden paths. This is not the running instance configuration: project overrides and expanded environment values are not included. \`GET /opencode-config/effective\` reads the running server's configuration separately as \`entries\`: the configuration documents and discovery directories in precedence order, lowest first, each shaped as \`{ type: 'document', path, info }\` or \`{ type: 'directory', path }\`. Its \`info\` values are expanded for the running server, with secrets redacted; never copy this response into a save.
**Response (\`OpenCodeConfigFile\`):**
**Response:**
\`\`\`ts
{
path: string
content: object
rawContent: string
sources: Array<{ name: string, path: string, rawContent: string, content: object, isValid: boolean }>
revision: string
content: object // secrets replaced with "<redacted>"
isValid: boolean
validationIssues?: Array<{ path: string, message: string }>
updatedAt: number
sources: Array<{ name: string, path: string, content: object, isValid: boolean, validationIssues?: Array<{ path: string, message: string }>, updatedAt: number }>
revision: string
redactedPaths: string[]
}
\`\`\`
@@ -748,28 +748,31 @@ Read the merged persisted global configuration and its source files. Returns \`4
}
\`\`\`
### PUT /opencode-config
### PATCH /opencode-config
Read the merged persisted configuration first, change only the keys the user asked for, and send the complete object back with its revision. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved. Removing a field removes only its override in the write target; a lower-priority value can reappear.
Change only the paths the user asked for. Send a nested \`patch\` object naming those paths and the values to set; every path you do not name is left untouched, and a \`null\` value removes a path. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved.
For a raw edit, send a string with the exact source name from \`sources\`. Never send merged JSON as raw source text. A \`409\` means the source files changed: read again and reconcile rather than retrying stale content.
Send \`expectedRevision\` from a read. A \`409\` means the source files changed: read again and reconcile rather than retrying stale content.
**Request Body:**
\`\`\`ts
{ content: object | string, expectedRevision: string, source?: "opencode.json" | "opencode.jsonc" }
{ patch: object, expectedRevision?: string, source?: "opencode.json" | "opencode.jsonc" }
\`\`\`
**Example:**
**Example** — change one MCP server's bearer token without reading the file:
\`\`\`json
{
"action": "request",
"params": {
"method": "PUT",
"method": "PATCH",
"path": "/opencode-config",
"body": {
"expectedRevision": "revision-from-get",
"content": {
"theme": "dark"
"patch": {
"mcp": {
"servers": {
"linear": { "headers": { "Authorization": "Bearer <token>" } }
}
}
}
}
}
@@ -777,11 +780,34 @@ For a raw edit, send a string with the exact source name from \`sources\`. Never
\`\`\`
**Response:**
Returns the refreshed merged configuration and source files. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. Changes limited to \`mcp\` are saved without a reload; to make an MCP change take effect immediately, tell the user to reconnect the server from Settings → MCP. Comment-only changes do nothing. Saving never silently drops unsupported fields.
Returns the refreshed merged configuration and source files, with secrets redacted. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. An \`mcp\` change is applied the same way, and only the servers whose configuration changed reconnect. Comment-only changes do nothing. Saving never silently drops unsupported fields.
The response adds \`restartRequired: true\` only when the automatic reload failed, for example because the OpenCode server is unavailable.
Returns \`400\` for invalid configuration and \`409\` for a stale revision.
Returns \`400\` for invalid configuration or a \`<redacted>\` value (\`paths\` lists them), and \`409\` for a stale revision.
### GET /opencode-config/mcp
List the configured MCP servers with their stored shape, enabled state, and live connection status. Use this to answer questions about MCP servers instead of reading the whole configuration. Header and environment values are never returned.
\`type\` is \`local\` or \`remote\`, and \`command\` or \`url\` is included for the matching type. \`enabled\` reflects the stored flag. \`shape\` is \`servers\` for a native \`mcp.servers.<name>\` entry or \`legacy\` for a flat \`mcp.<name>\` entry, so you can address the entry by the path it actually uses. \`status\` is the live OpenCode status (\`connected\`, \`pending\`, \`disabled\`, \`failed\`, or \`needs_auth\`) when the server is reachable, and \`error\` carries the failure reason.
**Response:**
\`\`\`ts
{
revision: string | null
servers: Array<{
name: string
type: 'local' | 'remote'
command?: string[]
url?: string
enabled: boolean
shape: 'servers' | 'legacy'
status?: 'connected' | 'pending' | 'disabled' | 'failed' | 'needs_auth'
error?: string
}>
}
\`\`\`
When the response contains \`restartRequired: true\`, tell the user to restart the OpenCode server from Settings. Never attempt the restart yourself: it would terminate your own session.
@@ -790,7 +816,8 @@ Only changes to how the OpenCode process is launched need a user restart from Se
## Safety
- The settings PATCH endpoint rejects any attempt to modify credentials, API keys, or other sensitive settings; guide the user to the full UI for Git, TTS, and STT credentials
- PUT /opencode-config patches changed global settings, including \`plugin\`, \`mcp\`, and \`provider\` entries; change only the keys the user explicitly asked for and never add plugins, MCP servers, or provider credentials the user did not request
- PATCH /opencode-config patches only the paths you name, including \`plugin\`, \`mcp\`, and \`provider\` entries; change only the keys the user explicitly asked for and never add plugins, MCP servers, or provider credentials the user did not request
- GET /opencode-config redacts secrets; never reconstruct a secret you did not read, and never send a \`<redacted>\` value back
- The settings PATCH endpoint does NOT trigger an OpenCode reload or restart
`
}
@@ -10,6 +10,7 @@ import {
restoreOpenCodeConfigSnapshot,
serializeOpenCodeConfigSnapshot,
updateOpenCodeConfigFile,
type OpenCodeConfigUpdateMode,
withOpenCodeConfigLock,
} from './opencode-config-file'
import { opencodeServerManager } from './opencode-single-server'
@@ -29,12 +30,11 @@ export interface ApplyOpenCodeConfigInput {
content: Record<string, unknown> | string
source?: OpenCodeConfigSourceName
expectedRevision?: string
mode?: OpenCodeConfigUpdateMode
settingsService: SettingsService
openCodeClient: OpenCodeClient
}
const MCP_CONFIG_KEY = 'mcp'
export async function captureLastKnownGoodOpenCodeConfig(settingsService: SettingsService): Promise<OpenCodeConfigFile | null> {
const previous = await readOpenCodeConfigFile()
if (previous?.isValid) {
@@ -95,19 +95,19 @@ function requiresOpenCodeReload(previous: OpenCodeConfigFile | null, next: OpenC
if (previous?.isValid !== next.isValid) {
return true
}
return listChangedTopLevelKeys(previous?.content ?? {}, next.content).some((key) => key !== MCP_CONFIG_KEY)
return listChangedTopLevelKeys(previous?.content ?? {}, next.content).length > 0
}
export async function applyOpenCodeConfigUpdate(
input: ApplyOpenCodeConfigInput,
): Promise<ApplyOpenCodeConfigResult> {
const { reloadRequired, config } = await withOpenCodeConfigLock(async () => {
const { content, source, expectedRevision, settingsService } = input
const { content, source, expectedRevision, mode, settingsService } = input
const snapshot = await readOpenCodeConfigSnapshot()
const previous = await readOpenCodeConfigFile(snapshot)
const next = await updateOpenCodeConfigFile(content, { source, expectedRevision, snapshot })
const next = await updateOpenCodeConfigFile(content, { source, expectedRevision, snapshot, mode })
if (previous?.isValid) {
const snapshot = serializeOpenCodeConfigSnapshot(previous)
+96 -20
View File
@@ -41,10 +41,13 @@ const OPENCODE_CONFIG_SNAPSHOT_MARKER = 'opencode-config-snapshot'
const OPENCODE_CONFIG_SNAPSHOT_ARTIFACT_PREFIX = 'opencode-config-broken'
export type OpenCodeConfigUpdateMode = 'replace' | 'merge'
export interface UpdateOpenCodeConfigOptions {
source?: OpenCodeConfigSourceName
expectedRevision?: string
snapshot?: OpenCodeConfigSnapshot
mode?: OpenCodeConfigUpdateMode
}
export class OpenCodeConfigConflictError extends Error {
@@ -88,6 +91,18 @@ export class OpenCodeConfigShadowedRemovalError extends Error {
}
}
export const OPENCODE_CONFIG_REDACTED_VALUE = '<redacted>'
export class OpenCodeConfigRedactedValueError extends Error {
readonly paths: string[]
constructor(paths: string[]) {
super('Configuration contains redacted placeholder values')
this.name = 'OpenCodeConfigRedactedValueError'
this.paths = paths
}
}
interface OpenCodeConfigParseResult {
content: Record<string, unknown>
isValid: boolean
@@ -177,9 +192,45 @@ function defineOwnConfigValue(target: Record<string, unknown>, key: string, valu
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
}
function stripNullOpenCodeConfigValues(value: unknown): unknown {
if (!isPlainObject(value)) return value
const output: Record<string, unknown> = {}
for (const key of Object.keys(value)) {
const entry = value[key]
if (entry === null) continue
defineOwnConfigValue(output, key, stripNullOpenCodeConfigValues(entry))
}
return output
}
function collectOpenCodeConfigRedactedPaths(value: unknown, basePath: string[] = []): string[] {
const paths: string[] = []
if (typeof value === 'string') {
if (value === OPENCODE_CONFIG_REDACTED_VALUE) paths.push(basePath.join('.'))
return paths
}
if (Array.isArray(value)) {
value.forEach((entry, index) => {
paths.push(...collectOpenCodeConfigRedactedPaths(entry, [...basePath, String(index)]))
})
return paths
}
if (isPlainObject(value)) {
for (const key of Object.keys(value)) {
paths.push(...collectOpenCodeConfigRedactedPaths(value[key], [...basePath, key]))
}
}
return paths
}
interface MergeOpenCodeConfigValuesOptions {
deleteNullValues?: boolean
}
function mergeOpenCodeConfigValues(
target: Record<string, unknown>,
source: Record<string, unknown>,
options: MergeOpenCodeConfigValuesOptions = {},
): Record<string, unknown> {
const output: Record<string, unknown> = {}
for (const key of Object.keys(target)) {
@@ -187,14 +238,20 @@ function mergeOpenCodeConfigValues(
}
for (const key of Object.keys(source)) {
const sourceValue = source[key]
if (options.deleteNullValues && sourceValue === null) {
delete output[key]
continue
}
const targetValue = hasOwn(output, key) ? output[key] : undefined
defineOwnConfigValue(
output,
key,
isPlainObject(targetValue) && isPlainObject(sourceValue)
? mergeOpenCodeConfigValues(targetValue, sourceValue)
: sourceValue,
)
let nextValue: unknown
if (isPlainObject(targetValue) && isPlainObject(sourceValue)) {
nextValue = mergeOpenCodeConfigValues(targetValue, sourceValue, options)
} else if (options.deleteNullValues) {
nextValue = stripNullOpenCodeConfigValues(sourceValue)
} else {
nextValue = sourceValue
}
defineOwnConfigValue(output, key, nextValue)
}
return output
}
@@ -348,27 +405,37 @@ export async function writeOpenCodeConfigFile(
}
function collectOpenCodeConfigPathOperations(
requested: Record<string, unknown>,
next: Record<string, unknown>,
current: Record<string, unknown>,
mode: OpenCodeConfigUpdateMode,
basePath: JSONPath = [],
): OpenCodeConfigPathOperation[] {
const operations: OpenCodeConfigPathOperation[] = []
for (const key of Object.keys(requested)) {
const requestedValue = requested[key]
for (const key of Object.keys(next)) {
const nextValue = next[key]
const hasCurrent = hasOwn(current, key)
const currentValue = hasCurrent ? current[key] : undefined
const nextPath = [...basePath, key]
if (isPlainObject(requestedValue) && isPlainObject(currentValue)) {
operations.push(...collectOpenCodeConfigPathOperations(requestedValue, currentValue, nextPath))
} else if (!hasCurrent || !isDeepStrictEqual(requestedValue, currentValue)) {
operations.push({ path: nextPath, value: requestedValue })
if (mode === 'merge' && nextValue === null) {
if (hasCurrent) operations.push({ path: nextPath, value: undefined })
continue
}
if (isPlainObject(nextValue) && isPlainObject(currentValue)) {
operations.push(...collectOpenCodeConfigPathOperations(nextValue, currentValue, mode, nextPath))
continue
}
const appliedValue = mode === 'merge' ? stripNullOpenCodeConfigValues(nextValue) : nextValue
if (!hasCurrent || !isDeepStrictEqual(appliedValue, currentValue)) {
operations.push({ path: nextPath, value: appliedValue })
}
}
for (const key of Object.keys(current)) {
if (hasOwn(requested, key)) continue
operations.push({ path: [...basePath, key], value: undefined })
if (mode === 'replace') {
for (const key of Object.keys(current)) {
if (hasOwn(next, key)) continue
operations.push({ path: [...basePath, key], value: undefined })
}
}
return operations
@@ -437,15 +504,24 @@ export async function updateOpenCodeConfigFile(
return writeOpenCodeConfigFile(content, targetName, snapshot)
}
const redactedPaths = collectOpenCodeConfigRedactedPaths(content)
if (redactedPaths.length > 0) {
throw new OpenCodeConfigRedactedValueError(redactedPaths)
}
const invalidSources = snapshot.sources.filter((source) => !source.isValid).map((source) => source.name)
if (invalidSources.length > 0) {
throw new OpenCodeConfigSourceInvalidError(invalidSources)
}
OpenCodeConfigSchema.parse(content)
const mode = options.mode ?? 'replace'
const operations = collectOpenCodeConfigPathOperations(content, snapshot.content, mode)
OpenCodeConfigSchema.parse(
mode === 'merge' ? mergeOpenCodeConfigValues(snapshot.content, content, { deleteNullValues: true }) : content,
)
const originalText = targetSource?.rawContent ?? '{}\n'
const operations = collectOpenCodeConfigPathOperations(content, snapshot.content)
assertNoShadowedOpenCodeConfigRemovals(operations, targetSource, snapshot.sources, targetName)
const updatedText = applyOpenCodeConfigPathOperations(originalText, operations)
@@ -666,7 +742,7 @@ export async function foldLegacyConfigJsonSource(): Promise<boolean> {
return true
}
const operations = collectOpenCodeConfigPathOperations(legacyContent, lowestPrecedenceSource.content)
const operations = collectOpenCodeConfigPathOperations(legacyContent, lowestPrecedenceSource.content, 'replace')
.filter((operation) => operation.value !== undefined && !hasOpenCodeConfigPath(lowestPrecedenceSource.content, operation.path))
if (operations.length > 0) {
const updatedText = applyOpenCodeConfigPathOperations(lowestPrecedenceSource.rawContent, operations)
@@ -0,0 +1,152 @@
import type { OpenCodeConfigFile } from '../types/settings'
import { isRecord } from './opencode/enforcement-config'
import { OPENCODE_CONFIG_REDACTED_VALUE } from './opencode-config-file'
const SECRET_KEYS = new Set([
'apikey',
'token',
'accesstoken',
'refreshtoken',
'idtoken',
'bearertoken',
'authtoken',
'clientsecret',
'secret',
'password',
'passphrase',
'authorization',
'credential',
'credentials',
'privatekey',
])
const OPAQUE_VALUE_KEYS = new Set(['headers', 'environment'])
export interface RedactedOpenCodeConfigContent {
content: Record<string, unknown>
redactedPaths: string[]
}
export interface RedactedOpenCodeConfigFile {
path: string
content: Record<string, unknown>
isValid: boolean
validationIssues?: OpenCodeConfigFile['validationIssues']
updatedAt: number
sources: Array<{
name: OpenCodeConfigFile['sources'][number]['name']
path: string
content: Record<string, unknown>
isValid: boolean
validationIssues?: OpenCodeConfigFile['validationIssues']
updatedAt: number
}>
revision: string
redactedPaths: string[]
}
function normalizeSecretKey(key: string): string {
return key.toLowerCase().replace(/[-_]/g, '')
}
function isSecretKey(key: string): boolean {
return SECRET_KEYS.has(normalizeSecretKey(key))
}
function keysAreNames(path: string[]): boolean {
const [head] = path
if (head === 'provider') {
return path.length === 1 || (path.length === 3 && path[2] === 'models')
}
if (head === 'agent') {
return path.length === 1
}
if (head === 'mcp') {
return path.length === 1 || (path.length === 2 && path[1] === 'servers')
}
return false
}
function isNameMapException(key: string): boolean {
return key === 'servers' || key === 'timeout'
}
function redactOpaqueValue(value: unknown, path: string[], redactedPaths: string[]): unknown {
if (Array.isArray(value)) {
return value.map((item, index) => redactOpaqueValue(item, [...path, String(index)], redactedPaths))
}
if (!isRecord(value)) {
if (typeof value !== 'string') return value
redactedPaths.push(path.join('.'))
return OPENCODE_CONFIG_REDACTED_VALUE
}
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [key, redactOpaqueValue(child, [...path, key], redactedPaths)]),
)
}
function redactValue(value: unknown, path: string[], redactedPaths: string[]): unknown {
if (Array.isArray(value)) {
return value.map((item, index) => redactValue(item, [...path, String(index)], redactedPaths))
}
if (!isRecord(value)) return value
const names = keysAreNames(path)
return Object.fromEntries(
Object.entries(value).map(([key, child]) => {
const childPath = [...path, key]
if (names && !isNameMapException(key)) {
return [key, redactValue(child, childPath, redactedPaths)]
}
if (OPAQUE_VALUE_KEYS.has(key)) {
return [key, redactOpaqueValue(child, childPath, redactedPaths)]
}
if (isSecretKey(key)) {
if (typeof child === 'string') {
redactedPaths.push(childPath.join('.'))
return [key, OPENCODE_CONFIG_REDACTED_VALUE]
}
if (isRecord(child) || Array.isArray(child)) {
return [key, redactOpaqueValue(child, childPath, redactedPaths)]
}
return [key, child]
}
return [key, redactValue(child, childPath, redactedPaths)]
}),
)
}
function uniqueSortedPaths(paths: string[]): string[] {
return [...new Set(paths)].toSorted()
}
export function redactOpenCodeConfigContent(
content: Record<string, unknown>,
): RedactedOpenCodeConfigContent {
const redactedPaths: string[] = []
return {
content: redactValue(content, [], redactedPaths) as Record<string, unknown>,
redactedPaths: uniqueSortedPaths(redactedPaths),
}
}
export function redactOpenCodeConfigFile(config: OpenCodeConfigFile): RedactedOpenCodeConfigFile {
const redacted = redactOpenCodeConfigContent(config.content)
return {
path: config.path,
content: redacted.content,
isValid: config.isValid,
...(config.validationIssues ? { validationIssues: config.validationIssues } : {}),
updatedAt: config.updatedAt,
sources: config.sources.map((source) => ({
name: source.name,
path: source.path,
content: redactOpenCodeConfigContent(source.content).content,
isValid: source.isValid,
...(source.validationIssues ? { validationIssues: source.validationIssues } : {}),
updatedAt: source.updatedAt,
})),
revision: config.revision,
redactedPaths: redacted.redactedPaths,
}
}
@@ -10,7 +10,8 @@ export const MANAGER_TOOL_ALLOWED_ROUTES = [
'PATCH /settings',
'GET /opencode-config',
'GET /opencode-config/effective',
'PUT /opencode-config',
'GET /opencode-config/mcp',
'PATCH /opencode-config',
'POST /assistant/reload',
'GET /repos',
'GET /repos/*/git-info',