Files
opencode-manager/ocm-cli/src/token-store-keychain.ts
T
Chris ScottandCS 6cc50a02ed feat(ocm-cli): add file and keychain credential backends with auth commands (#327)
* feat(ocm-cli): add file and keychain credential backends with auth commands

* feat(ocm-cli): refactor credentials into async TokenStore architecture

Replace the credential-backend module with a TokenStore interface and
file/keychain implementations behind an internal facade. Convert token
get/set/delete to async, add env-token precedence warnings on login and
logout, and surface store availability in status. Add token-store tests
and helpers; remove the old credential modules and tests. Bump to 0.2.6.

* fix(ocm-cli): keep tokens out of security argv and stop masking config read errors

Route every macOS Keychain call through `security -i`, sending the quoted
command on stdin so the token is never visible in process arguments. Reject
arguments containing line breaks, which would otherwise inject additional
security commands.

Let unexpected state file read failures propagate so a broken config dir is
reported instead of being reduced to "no manager configured", and stop
consuming the install notice when reading it fails unexpectedly.

---------

Co-authored-by: CS <chris@chriswritescode.dev>
2026-07-28 16:38:12 -04:00

102 lines
3.3 KiB
TypeScript

import { execFile } from 'child_process'
import type { TokenStore, TokenStoreDescription } from './token-store.js'
import { TokenStoreError } from './token-store.js'
export const KEYCHAIN_SERVICE = 'opencode-manager'
const SECURITY_BIN = '/usr/bin/security'
const ITEM_NOT_FOUND = 44
export interface SecurityResult {
stdout: string
stderr: string
code: number | null
}
export type SecurityRunner = (args: string[]) => Promise<SecurityResult>
type ExecFileFailure = Error & { code?: number | string }
export function formatSecurityCommand(args: string[]): string {
const quoted = args.map((arg) => {
if (/[\r\n]/.test(arg)) {
throw new TokenStoreError('keychain service, account and token values cannot contain line breaks', 'keychain')
}
return `"${arg.replace(/[\\"]/g, '\\$&')}"`
})
return `${quoted.join(' ')}\n`
}
function runSecurity(args: string[]): Promise<SecurityResult> {
return new Promise<SecurityResult>((resolve, reject) => {
const command = formatSecurityCommand(args)
const child = execFile(SECURITY_BIN, ['-i'], { encoding: 'utf-8' }, (err, stdout, stderr) => {
const exitCode = (err as ExecFileFailure | null)?.code ?? (err ? null : 0)
if (typeof exitCode !== 'number') {
reject(new TokenStoreError(`cannot run the macOS 'security' CLI: ${(err as Error).message}`, 'keychain'))
return
}
resolve({ stdout: stdout ?? '', stderr: stderr ?? '', code: exitCode })
})
child.stdin?.on('error', () => undefined)
child.stdin?.end(command)
})
}
function describeFailure(res: SecurityResult): string {
const stderr = res.stderr.trim()
if (stderr) return stderr
if (res.code !== null) return `exit status ${res.code}`
return 'process terminated without an exit status'
}
export function createKeychainTokenStore(run: SecurityRunner = runSecurity): TokenStore {
return {
describe(): TokenStoreDescription {
return { kind: 'keychain', location: `macOS Keychain (service ${KEYCHAIN_SERVICE})` }
},
async get(account: string): Promise<string | null> {
const res = await run([
'find-generic-password',
'-s', KEYCHAIN_SERVICE,
'-a', account,
'-w',
])
if (res.code === 0) return res.stdout.trim() || null
if (res.code === ITEM_NOT_FOUND) return null
throw new TokenStoreError(
`failed to read token from the macOS Keychain: ${describeFailure(res)}`,
'keychain',
)
},
async set(account: string, token: string): Promise<void> {
const res = await run([
'add-generic-password',
'-s', KEYCHAIN_SERVICE,
'-a', account,
'-w', token,
'-U',
])
if (res.code !== 0) {
throw new TokenStoreError(
`failed to store token in the macOS Keychain: ${describeFailure(res)}`,
'keychain',
)
}
},
async delete(account: string): Promise<boolean> {
const res = await run([
'delete-generic-password',
'-s', KEYCHAIN_SERVICE,
'-a', account,
])
if (res.code === 0) return true
if (res.code === ITEM_NOT_FOUND) return false
throw new TokenStoreError(
`failed to delete token from the macOS Keychain: ${describeFailure(res)}`,
'keychain',
)
},
}
}