mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
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>
This commit is contained in:
1 parent
29f154a9c3
commit
6cc50a02ed
19 files changed
+1560
-117
No files matched your search
@@ -0,0 +1,94 @@
|
||||
import type { TokenStore, TokenStoreDescription } from './token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
import { createFileTokenStore } from './token-store-file.js'
|
||||
import { createKeychainTokenStore } from './token-store-keychain.js'
|
||||
|
||||
export const TOKEN_ENV = 'OCM_TOKEN'
|
||||
|
||||
export function selectTokenStore(platform: NodeJS.Platform = process.platform): TokenStore {
|
||||
return platform === 'darwin'
|
||||
? createKeychainTokenStore()
|
||||
: createFileTokenStore()
|
||||
}
|
||||
|
||||
function memoizeReads(store: TokenStore): TokenStore {
|
||||
const cache = new Map<string, string>()
|
||||
return {
|
||||
describe: () => store.describe(),
|
||||
async get(account: string): Promise<string | null> {
|
||||
const cached = cache.get(account)
|
||||
if (cached) return cached
|
||||
const token = await store.get(account)
|
||||
if (token) cache.set(account, token)
|
||||
return token
|
||||
},
|
||||
async set(account: string, token: string): Promise<void> {
|
||||
await store.set(account, token)
|
||||
cache.set(account, token)
|
||||
},
|
||||
async delete(account: string): Promise<boolean> {
|
||||
cache.delete(account)
|
||||
return store.delete(account)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let active: TokenStore | undefined
|
||||
function defaultStore(): TokenStore {
|
||||
active ??= memoizeReads(selectTokenStore())
|
||||
return active
|
||||
}
|
||||
|
||||
export function envToken(): string | null {
|
||||
const raw = process.env[TOKEN_ENV]?.trim()
|
||||
return raw ? raw : null
|
||||
}
|
||||
|
||||
export async function getToken(
|
||||
account: string,
|
||||
store: TokenStore = defaultStore(),
|
||||
): Promise<string | null> {
|
||||
return envToken() ?? (await store.get(account))
|
||||
}
|
||||
|
||||
export async function setToken(
|
||||
account: string,
|
||||
token: string,
|
||||
store: TokenStore = defaultStore(),
|
||||
): Promise<void> {
|
||||
const normalised = token.trim()
|
||||
if (!normalised) {
|
||||
throw new TokenStoreError('refusing to store an empty token', store.describe().kind)
|
||||
}
|
||||
await store.set(account, normalised)
|
||||
}
|
||||
|
||||
export async function deleteToken(
|
||||
account: string,
|
||||
store: TokenStore = defaultStore(),
|
||||
): Promise<boolean> {
|
||||
return store.delete(account)
|
||||
}
|
||||
|
||||
export async function hasStoredToken(
|
||||
account: string | undefined,
|
||||
store: TokenStore = defaultStore(),
|
||||
): Promise<boolean> {
|
||||
if (envToken()) return true
|
||||
if (!account) return false
|
||||
return (await store.get(account)) !== null
|
||||
}
|
||||
|
||||
export function describeTokenStore(
|
||||
store: TokenStore = defaultStore(),
|
||||
): TokenStoreDescription {
|
||||
return envToken() ? { kind: 'env', location: TOKEN_ENV } : store.describe()
|
||||
}
|
||||
|
||||
export function describeTokenWriteTarget(
|
||||
store: TokenStore = defaultStore(),
|
||||
): TokenStoreDescription {
|
||||
return store.describe()
|
||||
}
|
||||
|
||||
export { TokenStoreError } from './token-store.js'
|
||||
@@ -0,0 +1,66 @@
|
||||
import { accessSync, chmodSync, constants, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'fs'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { dirname } from 'path'
|
||||
|
||||
const DIR_MODE = 0o700
|
||||
const FILE_MODE = 0o600
|
||||
|
||||
function isPermissionError(err: unknown): boolean {
|
||||
const code = (err as NodeJS.ErrnoException).code
|
||||
return code === 'EACCES' || code === 'EPERM'
|
||||
}
|
||||
|
||||
function removeQuietly(filePath: string): void {
|
||||
try {
|
||||
unlinkSync(filePath)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export function ensurePrivateDir(dir: string): void {
|
||||
try {
|
||||
mkdirSync(dir, { recursive: true, mode: DIR_MODE })
|
||||
} catch (err) {
|
||||
if (!isPermissionError(err)) throw err
|
||||
try {
|
||||
accessSync(dir, constants.X_OK)
|
||||
} catch {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
try {
|
||||
chmodSync(dir, DIR_MODE)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export function readJsonFile<T>(filePath: string): T | null {
|
||||
let contents: string
|
||||
try {
|
||||
contents = readFileSync(filePath, 'utf-8')
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null
|
||||
throw err
|
||||
}
|
||||
if (contents.trim() === '') return null
|
||||
try {
|
||||
return JSON.parse(contents) as T
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function writeJsonFileAtomic(filePath: string, data: unknown): void {
|
||||
ensurePrivateDir(dirname(filePath))
|
||||
const tmp = `${filePath}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
|
||||
try {
|
||||
writeFileSync(tmp, JSON.stringify(data, null, 2), { encoding: 'utf-8', mode: FILE_MODE, flag: 'wx' })
|
||||
chmodSync(tmp, FILE_MODE)
|
||||
renameSync(tmp, filePath)
|
||||
} catch (err) {
|
||||
removeQuietly(tmp)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { spawnSync } from 'child_process'
|
||||
|
||||
const SERVICE = 'opencode-manager'
|
||||
|
||||
export class KeychainError extends Error {
|
||||
constructor(message: string, public exitCode: number | null) {
|
||||
super(message)
|
||||
this.name = 'KeychainError'
|
||||
}
|
||||
}
|
||||
|
||||
function runSecurity(args: string[], input?: string): { stdout: string; stderr: string; code: number | null } {
|
||||
const res = spawnSync('security', args, {
|
||||
input,
|
||||
encoding: 'utf-8',
|
||||
})
|
||||
return { stdout: res.stdout ?? '', stderr: res.stderr ?? '', code: res.status }
|
||||
}
|
||||
|
||||
export function setToken(account: string, token: string): void {
|
||||
const res = runSecurity([
|
||||
'add-generic-password',
|
||||
'-s', SERVICE,
|
||||
'-a', account,
|
||||
'-w', token,
|
||||
'-U',
|
||||
])
|
||||
if (res.code !== 0) {
|
||||
throw new KeychainError(`Failed to store token in Keychain: ${res.stderr.trim()}`, res.code)
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(account: string): string | null {
|
||||
const res = runSecurity([
|
||||
'find-generic-password',
|
||||
'-s', SERVICE,
|
||||
'-a', account,
|
||||
'-w',
|
||||
])
|
||||
if (res.code !== 0) return null
|
||||
return res.stdout.trim() || null
|
||||
}
|
||||
|
||||
export function deleteToken(account: string): boolean {
|
||||
const res = runSecurity([
|
||||
'delete-generic-password',
|
||||
'-s', SERVICE,
|
||||
'-a', account,
|
||||
])
|
||||
return res.code === 0
|
||||
}
|
||||
+15
-22
@@ -1,6 +1,7 @@
|
||||
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs'
|
||||
import { existsSync, unlinkSync } from 'fs'
|
||||
import { homedir } from 'os'
|
||||
import { dirname, join } from 'path'
|
||||
import { join } from 'path'
|
||||
import { readJsonFile, writeJsonFileAtomic } from './json-store.js'
|
||||
|
||||
export interface OcmState {
|
||||
managerUrl: string
|
||||
@@ -21,46 +22,38 @@ const STATE_DIR = join(homedir(), '.config', 'opencode-manager')
|
||||
const STATE_FILE = join(STATE_DIR, 'state.json')
|
||||
const INSTALL_NOTICE_FILE = join(STATE_DIR, 'install-notice.json')
|
||||
|
||||
export function getConfigDir(): string {
|
||||
return STATE_DIR
|
||||
}
|
||||
|
||||
export function getStatePath(): string {
|
||||
return STATE_FILE
|
||||
}
|
||||
|
||||
export function readState(): OcmState | null {
|
||||
if (!existsSync(STATE_FILE)) return null
|
||||
try {
|
||||
const raw = readFileSync(STATE_FILE, 'utf-8')
|
||||
const parsed = JSON.parse(raw) as OcmState
|
||||
if (!parsed.managerUrl) return null
|
||||
return parsed
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const parsed = readJsonFile<OcmState>(STATE_FILE)
|
||||
return parsed?.managerUrl ? parsed : null
|
||||
}
|
||||
|
||||
export function writeState(state: OcmState): void {
|
||||
mkdirSync(dirname(STATE_FILE), { recursive: true })
|
||||
const next: OcmState = { ...state, updatedAt: Date.now() }
|
||||
writeFileSync(STATE_FILE, JSON.stringify(next, null, 2), { mode: 0o600 })
|
||||
writeJsonFileAtomic(STATE_FILE, { ...state, updatedAt: Date.now() })
|
||||
}
|
||||
|
||||
export function clearState(): void {
|
||||
if (existsSync(STATE_FILE)) {
|
||||
writeFileSync(STATE_FILE, '{}', { mode: 0o600 })
|
||||
writeJsonFileAtomic(STATE_FILE, {})
|
||||
}
|
||||
}
|
||||
|
||||
export function readInstallNotice(): InstallNotice | null {
|
||||
if (!existsSync(INSTALL_NOTICE_FILE)) return null
|
||||
let parsed: InstallNotice | null
|
||||
try {
|
||||
const raw = readFileSync(INSTALL_NOTICE_FILE, 'utf-8')
|
||||
const parsed = JSON.parse(raw) as InstallNotice
|
||||
if (!parsed.link || !parsed.binDir) return null
|
||||
return parsed
|
||||
parsed = readJsonFile<InstallNotice>(INSTALL_NOTICE_FILE)
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
deleteInstallNotice()
|
||||
}
|
||||
deleteInstallNotice()
|
||||
return parsed?.link && parsed.binDir ? parsed : null
|
||||
}
|
||||
|
||||
function deleteInstallNotice(): void {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { join } from 'path'
|
||||
import { getConfigDir } from './state.js'
|
||||
import { readJsonFile, writeJsonFileAtomic } from './json-store.js'
|
||||
import type { TokenStore, TokenStoreDescription } from './token-store.js'
|
||||
import { TokenStoreError, describeCause } from './token-store.js'
|
||||
|
||||
const DOCUMENT_VERSION = 1
|
||||
|
||||
type TokenDocument = Record<string, unknown> & {
|
||||
version: number
|
||||
tokens: Record<string, string>
|
||||
}
|
||||
|
||||
function tokenFilePath(): string {
|
||||
return join(getConfigDir(), 'credentials.json')
|
||||
}
|
||||
|
||||
function readDocument(filePath: string): TokenDocument {
|
||||
let raw: Record<string, unknown> | null
|
||||
try {
|
||||
raw = readJsonFile<Record<string, unknown>>(filePath)
|
||||
} catch (err) {
|
||||
throw new TokenStoreError(`failed to read token file ${filePath}: ${describeCause(err)}`, 'file')
|
||||
}
|
||||
const empty: TokenDocument = { version: DOCUMENT_VERSION, tokens: {} }
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return empty
|
||||
if (raw.version !== undefined && raw.version !== DOCUMENT_VERSION) {
|
||||
throw new TokenStoreError(
|
||||
`token file ${filePath} uses unsupported format version ${JSON.stringify(raw.version)}; upgrade ocm or remove the file`,
|
||||
'file',
|
||||
)
|
||||
}
|
||||
const tokens: Record<string, string> = {}
|
||||
if (raw.tokens && typeof raw.tokens === 'object' && !Array.isArray(raw.tokens)) {
|
||||
for (const [account, token] of Object.entries(raw.tokens as Record<string, unknown>)) {
|
||||
if (typeof token === 'string') tokens[account] = token
|
||||
}
|
||||
}
|
||||
return { ...raw, version: DOCUMENT_VERSION, tokens }
|
||||
}
|
||||
|
||||
function mutateDocument(filePath: string, mutate: (tokens: Record<string, string>) => boolean): boolean {
|
||||
try {
|
||||
const doc = readDocument(filePath)
|
||||
if (!mutate(doc.tokens)) return false
|
||||
writeJsonFileAtomic(filePath, doc)
|
||||
return true
|
||||
} catch (err) {
|
||||
if (err instanceof TokenStoreError) throw err
|
||||
throw new TokenStoreError(`failed to write token file ${filePath}: ${describeCause(err)}`, 'file')
|
||||
}
|
||||
}
|
||||
|
||||
export function createFileTokenStore(filePath: string = tokenFilePath()): TokenStore {
|
||||
return {
|
||||
describe(): TokenStoreDescription {
|
||||
return { kind: 'file', location: filePath }
|
||||
},
|
||||
async get(account: string): Promise<string | null> {
|
||||
return readDocument(filePath).tokens[account] ?? null
|
||||
},
|
||||
async set(account: string, token: string): Promise<void> {
|
||||
mutateDocument(filePath, (tokens) => {
|
||||
tokens[account] = token
|
||||
return true
|
||||
})
|
||||
},
|
||||
async delete(account: string): Promise<boolean> {
|
||||
return mutateDocument(filePath, (tokens) => {
|
||||
if (!(account in tokens)) return false
|
||||
delete tokens[account]
|
||||
return true
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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',
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
export type TokenStoreKind = 'env' | 'keychain' | 'file'
|
||||
|
||||
export interface TokenStoreDescription {
|
||||
kind: TokenStoreKind
|
||||
location: string
|
||||
}
|
||||
|
||||
export interface TokenStore {
|
||||
describe(): TokenStoreDescription
|
||||
get(account: string): Promise<string | null>
|
||||
set(account: string, token: string): Promise<void>
|
||||
delete(account: string): Promise<boolean>
|
||||
}
|
||||
|
||||
export class TokenStoreError extends Error {
|
||||
constructor(message: string, public kind: TokenStoreKind) {
|
||||
super(message)
|
||||
this.name = 'TokenStoreError'
|
||||
}
|
||||
}
|
||||
|
||||
export function describeCause(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { TuiPluginApi } from './tui-types.js'
|
||||
import { readInstallNotice, readState } from './state.js'
|
||||
import { getToken } from './keychain.js'
|
||||
import { getToken } from './internal-token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
|
||||
import { ManagerApi, ManagerApiError } from './manager-api.js'
|
||||
import { prepareMirror, checkPushDivergence, mirrorUpFast } from './mirror.js'
|
||||
@@ -90,9 +91,16 @@ async function runSessionMove(api: TuiPluginApi): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
const token = getToken(state.managerUrl)
|
||||
let token: string | null
|
||||
try {
|
||||
token = await getToken(state.managerUrl)
|
||||
} catch (err) {
|
||||
const reason = err instanceof TokenStoreError ? err.message : String(err)
|
||||
api.ui.toast({ variant: 'error', message: `Token store unavailable: ${reason}` })
|
||||
return
|
||||
}
|
||||
if (!token) {
|
||||
api.ui.toast({ variant: 'error', message: `No token in Keychain. Run \`ocm login ${state.managerUrl}\`.` })
|
||||
api.ui.toast({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user