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:
Chris ScottandCS authored and GitHub committed 2026-07-28 16:38:12 -04:00
1 parent 29f154a9c3
commit 6cc50a02ed
19 files changed
+1560 -117

No files matched your search

+7 -4
View File
@@ -76,7 +76,9 @@ ocm login https://your-manager-url
# paste your Manager internal token when prompted
```
The token is stored in the macOS Keychain under the manager URL. The manager URL is persisted to `~/.config/opencode-manager/state.json`.
The token is stored in a platform-specific token store: the macOS Keychain (service `opencode-manager`, account = manager URL) on macOS, or `~/.config/opencode-manager/credentials.json` at mode `0600` on Linux. On Linux the token is plaintext JSON protected only by file permissions. Run `ocm status` to see the active store. The manager URL itself is persisted to `~/.config/opencode-manager/state.json`.
Windows is not supported: the CLI falls back to the same file store, but the `0600` mode is not enforced there and hidden token entry requires `bash`.
Generate or rotate your internal token from **Settings → Manager Token** in the Manager web UI (Settings cog in the sidebar, then **Manager Token**).
@@ -88,7 +90,7 @@ Generate or rotate your internal token from **Settings → Manager Token** in th
ocm Attach to the Manager repo matching $PWD's git origin,
or fall back to the last selected repo
ocm login <url> [token] Save manager URL + token (token via stdin if omitted)
ocm logout Forget saved token (Keychain) and state
ocm logout Forget saved token and state
ocm status Show current manager URL, repo, and whether token is set
ocm list List ready repos from the manager
ocm use <repoId|name> Attach to a specific repo and remember it as last
@@ -141,14 +143,15 @@ When the TUI plugin entry is installed, `/ocm-move` is available in local OpenCo
## 4. Environment variables
Both can be used in place of `ocm login`:
The CLI's environment and token inputs:
| Variable | Description |
|---|---|
| `OPENCODE_MANAGER_URL` | Manager base URL (e.g., `https://manager.example.com`). Not currently consumed by the CLI — use `ocm login`. |
| `OCM_REMOTE_MANAGER_URL` | Internal child-process context set by `ocm attach`; controls the remote TUI indicator. Not a login setting. |
| `OCM_REMOTE_REPO_NAME` | Internal child-process context set by `ocm attach`; labels the remote TUI indicator. Not a login setting. |
| Keychain entry under `https://manager.example.com` | Token used for Bearer auth on Manager API calls and Basic auth on the OpenCode proxy. |
| `OCM_TOKEN` | Read-only override for the stored token; takes priority over the platform token store. `ocm login` never writes it, and `ocm logout` cannot remove it. Because the manager URL still comes from `state.json`, CI must run `ocm login` first, so this override does not yet avoid writing a token to disk. |
| Token store entry under `<manager url>` | Token used for Bearer auth on Manager API calls and Basic auth on the OpenCode proxy. macOS Keychain (service `opencode-manager`) or `~/.config/opencode-manager/credentials.json` (mode `0600`) on Linux. |
---
+20 -4
View File
@@ -22,10 +22,24 @@ also create a best-effort `~/.local/bin/ocm` symlink.
ocm login <manager-url> [token]
```
The token is stored in macOS Keychain under the `opencode-manager` service. CLI
state is stored at `~/.config/opencode-manager/state.json`.
The token is stored in a platform-specific token store:
If `[token]` is omitted, `ocm login` reads it from hidden TTY input or stdin.
| Platform | Store |
|---|---|
| macOS | Keychain, service `opencode-manager`, account = manager URL |
| Linux | `~/.config/opencode-manager/credentials.json`, mode `0600` |
On Linux the token is stored as plaintext JSON protected only by file
permissions. CLI state is stored at `~/.config/opencode-manager/state.json`.
Windows is unsupported: the same file store is used, but the `0600` mode is not
enforced there.
`OCM_TOKEN` overrides the token store for reads; `ocm login` always writes to
the platform store and `ocm logout` cannot remove the override. Run `ocm status`
to see the active store.
If `[token]` is omitted, `ocm login` reads it from hidden TTY input (requires
`bash`) or stdin.
## Commands
@@ -92,7 +106,9 @@ global installs); the plugin surface is TUI-only.
## Requirements
- macOS or Linux (Windows is unsupported)
- `opencode` available on `PATH`
- `git` and `tar` (with gzip support, i.e. the `-z` flag) available on `PATH`
- macOS `security` CLI for Keychain-backed token storage
- `bash`, used for hidden token entry and interactive confirmations
- macOS only: `/usr/bin/security`, used for Keychain-backed token storage (Linux uses a mode-`0600` file under the user config dir `~/.config/opencode-manager`)
- An OpenCode Manager URL and bearer token
+59 -19
View File
@@ -1,7 +1,7 @@
import { spawn, spawnSync } from 'child_process'
import { basename } from 'path'
import { readState, writeState, clearState, getStatePath, type OcmState } from '../src/state.js'
import { getToken, setToken, deleteToken, KeychainError } from '../src/keychain.js'
import { getToken, setToken, deleteToken, hasStoredToken, describeTokenStore, describeTokenWriteTarget, envToken, TOKEN_ENV, TokenStoreError } from '../src/internal-token-store.js'
import { ManagerApi, ManagerApiError } from '../src/manager-api.js'
import { mirrorUp, mirrorDown, mirrorUpFast, mirrorDownFast, prepareMirror, MirrorAbort, checkPushDivergence, checkPullDivergence } from '../src/mirror.js'
import type { RemoteRepoSummary, MirrorProgress, PushDivergence, PullDivergence } from '../src/mirror.js'
@@ -22,7 +22,7 @@ Usage:
fall back to the last selected repo, or launch local
opencode when no Manager target applies
ocm login <url> [token] Save manager URL + token (token via stdin if omitted)
ocm logout Forget saved token (Keychain) and state
ocm logout Forget saved token and state
ocm status Show current manager URL, repo, and whether token is set
ocm list List ready repos from the manager
ocm use <repoId|name> Attach to a specific repo and remember it as last
@@ -108,10 +108,17 @@ function requireState(): OcmState {
return state
}
function requireToken(state: OcmState): string {
const token = getToken(state.managerUrl)
async function requireToken(state: OcmState): Promise<string> {
const store = describeTokenStore()
let token: string | null
try {
token = await getToken(state.managerUrl)
} catch (err) {
if (!(err instanceof TokenStoreError)) throw err
die(`token store error (${store.kind}: ${store.location}): ${err.message}. Run \`ocm login ${state.managerUrl}\` after fixing the store.`)
}
if (!token) {
die(`no token in Keychain for ${state.managerUrl}. Run \`ocm login ${state.managerUrl}\`.`)
die(`no token stored for ${state.managerUrl} (${store.kind}: ${store.location}). Run \`ocm login ${state.managerUrl}\`.`)
}
return token
}
@@ -164,7 +171,7 @@ function findRepo(repos: ManagerRepo[], needle: string | number): ManagerRepo |
return repos.find((r) => r.name === needle) ?? repos.find((r) => r.name.toLowerCase() === needle.toLowerCase())
}
async function cmdLogin(args: string[]): Promise<void> {
export async function cmdLogin(args: string[]): Promise<void> {
const url = args[0]
if (!url) die('usage: ocm login <url> [token]')
const normalisedUrl = url.replace(/\/+$/, '')
@@ -190,9 +197,9 @@ async function cmdLogin(args: string[]): Promise<void> {
if (!token) die('no token provided')
try {
setToken(normalisedUrl, token)
await setToken(normalisedUrl, token)
} catch (err) {
if (err instanceof KeychainError) die(`Keychain error: ${err.message}`)
if (err instanceof TokenStoreError) die(`token store error: ${err.message}`)
throw err
}
@@ -202,32 +209,65 @@ async function cmdLogin(args: string[]): Promise<void> {
managerUrl: normalisedUrl,
})
info(`Saved token for ${normalisedUrl} in Keychain.`)
const store = describeTokenWriteTarget()
info(`Saved token for ${normalisedUrl} (${store.kind}: ${store.location}).`)
info(`State file: ${getStatePath()}`)
warnEnvTokenPrecedence()
}
async function cmdLogout(): Promise<void> {
export async function cmdLogout(): Promise<void> {
const state = readState()
if (!state || !state.managerUrl) {
info('Nothing to log out from.')
return
}
const deleted = deleteToken(state.managerUrl)
let deleted = false
let storeError: TokenStoreError | undefined
try {
deleted = await deleteToken(state.managerUrl)
} catch (err) {
if (!(err instanceof TokenStoreError)) throw err
storeError = err
}
clearState()
info(deleted ? `Removed Keychain entry for ${state.managerUrl}.` : `No Keychain entry found.`)
if (storeError) {
info('State cleared.')
die(`token store error: ${storeError.message}. The stored token may still exist.`)
}
info(deleted ? `Removed stored token for ${state.managerUrl}.` : 'No stored token found.')
info('State cleared.')
warnEnvTokenPrecedence()
}
async function cmdStatus(): Promise<void> {
function warnEnvTokenPrecedence(): void {
if (envToken()) {
info(`note: ${TOKEN_ENV} is set and takes precedence over the stored token; unset it to use the token store.`)
}
}
async function describeTokenPresence(account: string | undefined): Promise<string> {
try {
return (await hasStoredToken(account)) ? 'yes' : 'no'
} catch (err) {
if (!(err instanceof TokenStoreError)) throw err
return `unavailable (${err.message})`
}
}
export async function cmdStatus(): Promise<void> {
const store = describeTokenStore()
const state = readState()
if (!state) {
info(`version: ${VERSION}`)
info(`token store: ${store.kind} (${store.location})`)
info(`token: ${await describeTokenPresence(undefined)}`)
info('no state. run: ocm login <url>')
return
}
info(`version: ${VERSION}`)
info(`manager url: ${state.managerUrl}`)
info(`token in kc: ${getToken(state.managerUrl) ? 'yes' : 'no'}`)
info(`token: ${await describeTokenPresence(state.managerUrl)}`)
info(`token store: ${store.kind} (${store.location})`)
if (state.lastRepoId !== undefined) {
info(`last repo: ${state.lastRepoName} (id=${state.lastRepoId}, branch=${state.lastRepoBranch ?? 'n/a'})`)
info(`last repo dir: ${state.lastRepoDir}`)
@@ -239,7 +279,7 @@ async function cmdStatus(): Promise<void> {
async function cmdList(): Promise<void> {
const state = requireState()
const token = requireToken(state)
const token = await requireToken(state)
const repos = await fetchRepos(state.managerUrl, token)
if (repos.length === 0) {
info('No ready repos.')
@@ -259,7 +299,7 @@ async function cmdUse(args: string[]): Promise<void> {
const needle = args[0]
if (!needle) die('usage: ocm use <repoId|name>')
const state = requireState()
const token = requireToken(state)
const token = await requireToken(state)
const repos = await fetchRepos(state.managerUrl, token)
const repo = findRepo(repos, needle)
if (!repo) die(`repo not found: ${needle}`)
@@ -278,7 +318,7 @@ async function cmdUse(args: string[]): Promise<void> {
async function cmdDefault(): Promise<void> {
info(`ocm v${VERSION}`)
const state = requireState()
const token = requireToken(state)
const token = await requireToken(state)
const last = state.lastRepoId !== undefined && state.lastRepoDir
? {
@@ -361,7 +401,7 @@ export async function cmdPush(args: string[]): Promise<void> {
}
const state = requireState()
const token = requireToken(state)
const token = await requireToken(state)
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
@@ -439,7 +479,7 @@ async function cmdPull(args: string[]): Promise<void> {
}
const state = requireState()
const token = requireToken(state)
const token = await requireToken(state)
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/ocm-cli",
"version": "0.2.5",
"version": "0.2.6",
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
"license": "MIT",
"repository": {
+94
View File
@@ -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'
+66
View File
@@ -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
}
}
-51
View File
@@ -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
View File
@@ -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 {
+76
View File
@@ -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
})
},
}
}
+101
View File
@@ -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',
)
},
}
}
+24
View File
@@ -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)
}
+11 -3
View File
@@ -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
}
+196
View File
@@ -0,0 +1,196 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { OcmState } from '../src/state.js'
import {
MockTokenStoreError,
mockStateModule,
mockTokenStoreModule,
unmockTokenStoreModules,
type TokenStoreMockOptions,
} from './helpers/token-store-mocks.js'
type CliOverrides = TokenStoreMockOptions & {
state?: OcmState | null
}
async function loadCli(overrides: CliOverrides = {}) {
vi.resetModules()
const state = 'state' in overrides ? overrides.state : { managerUrl: 'https://manager.example.com' }
const { clearState } = mockStateModule(state ?? null)
const { getToken, setToken, deleteToken } = mockTokenStoreModule(overrides)
const written: string[] = []
const stderr: string[] = []
const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
written.push(String(chunk))
return true
})
const stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => {
stderr.push(String(chunk))
return true
})
const cli = await import('../bin/ocm')
return {
cli,
written,
stderr,
getToken,
setToken,
deleteToken,
clearState,
restore: () => {
stdoutSpy.mockRestore()
stderrSpy.mockRestore()
},
}
}
describe('cli auth commands', () => {
let originalArgv: string[]
beforeEach(() => {
originalArgv = process.argv.slice()
vi.restoreAllMocks()
})
afterEach(() => {
process.argv = originalArgv
unmockTokenStoreModules()
})
it('ocm status reports the store kind and location', async () => {
const { cli, written, restore } = await loadCli({ token: 'tok', store: { kind: 'file', location: '/tmp/credentials.json' } })
await cli.cmdStatus()
const out = written.join('')
expect(out).toContain('token store:')
expect(out).toContain('file (/tmp/credentials.json)')
restore()
})
it('ocm status reports token presence', async () => {
const present = await loadCli({ token: 'tok' })
await present.cli.cmdStatus()
expect(present.written.join('')).toMatch(/^token:\s+yes/m)
present.restore()
const absent = await loadCli({ token: null })
await absent.cli.cmdStatus()
expect(absent.written.join('')).toMatch(/^token:\s+no/m)
absent.restore()
})
it('ocm status reports the env store', async () => {
const { cli, written, restore } = await loadCli({ env: 'tok_env' })
await cli.cmdStatus()
const out = written.join('')
expect(out).toContain('env (OCM_TOKEN)')
restore()
})
it('ocm status reports the store in the no-state branch', async () => {
const { cli, written, restore } = await loadCli({ state: null, token: null })
await cli.cmdStatus()
const out = written.join('')
expect(out).toContain('token store:')
expect(out).toContain('file (/tmp/credentials.json)')
expect(out).toMatch(/^token:\s+no/m)
restore()
})
it('ocm status reports a token is present in the no-state branch when OCM_TOKEN is active', async () => {
const { cli, written, restore } = await loadCli({ state: null, env: 'tok_env' })
await cli.cmdStatus()
const out = written.join('')
expect(out).toContain('token store:')
expect(out).toContain('env (OCM_TOKEN)')
expect(out).toMatch(/^token:\s+yes/m)
restore()
})
it('ocm status reports an unavailable token store instead of exiting', async () => {
const { cli, written, restore } = await loadCli({
getTokenImpl: () => Promise.reject(new MockTokenStoreError('keychain locked', 'keychain')),
})
await cli.cmdStatus()
const out = written.join('')
expect(out).toMatch(/^token:\s+unavailable \(keychain locked\)/m)
expect(out).toContain('manager url:')
restore()
})
it('ocm login stores the token verbatim', async () => {
const { cli, setToken, restore } = await loadCli()
await cli.cmdLogin(['https://manager.example.com/', 'tok_xyz'])
expect(setToken).toHaveBeenCalledWith('https://manager.example.com', 'tok_xyz')
restore()
})
it('ocm login names the store on success', async () => {
const { cli, written, restore } = await loadCli({ store: { kind: 'file', location: '/tmp/credentials.json' } })
await cli.cmdLogin(['https://manager.example.com', 'tok_xyz'])
expect(written.join('')).toContain('Saved token for https://manager.example.com (file: /tmp/credentials.json).')
restore()
})
it('ocm login reports the persisted store and warns that OCM_TOKEN wins', async () => {
const { cli, written, restore } = await loadCli({
env: 'tok_env',
writeTarget: { kind: 'file', location: '/tmp/credentials.json' },
})
await cli.cmdLogin(['https://manager.example.com', 'tok_xyz'])
const out = written.join('')
expect(out).toContain('Saved token for https://manager.example.com (file: /tmp/credentials.json).')
expect(out).toContain('note: OCM_TOKEN is set and takes precedence over the stored token')
restore()
})
it('ocm login does not mention OCM_TOKEN when it is unset', async () => {
const { cli, written, restore } = await loadCli()
await cli.cmdLogin(['https://manager.example.com', 'tok_xyz'])
expect(written.join('')).not.toContain('OCM_TOKEN')
restore()
})
it('ocm login surfaces a store failure', async () => {
const { cli, stderr, restore } = await loadCli({
setTokenImpl: () => Promise.reject(new MockTokenStoreError('disk full')),
})
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit') })
await expect(cli.cmdLogin(['https://manager.example.com', 'tok_xyz'])).rejects.toThrow('exit')
expect(stderr.join('')).toContain('token store error: disk full')
expect(exitSpy).toHaveBeenCalledWith(1)
restore()
})
it('ocm logout reports removal', async () => {
const { cli, written, restore } = await loadCli({ deleteTokenImpl: () => Promise.resolve(true) })
await cli.cmdLogout()
expect(written.join('')).toContain('Removed stored token for')
restore()
})
it('ocm logout reports nothing stored', async () => {
const { cli, written, restore } = await loadCli({ deleteTokenImpl: () => Promise.resolve(false) })
await cli.cmdLogout()
expect(written.join('')).toContain('No stored token found.')
restore()
})
it('ocm logout clears state even when the store delete fails', async () => {
const { cli, written, stderr, clearState, restore } = await loadCli({
deleteTokenImpl: () => Promise.reject(new MockTokenStoreError('keychain locked', 'keychain')),
})
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit') })
await expect(cli.cmdLogout()).rejects.toThrow('exit')
expect(clearState).toHaveBeenCalledOnce()
expect(written.join('')).toContain('State cleared.')
expect(stderr.join('')).toContain('token store error: keychain locked')
expect(exitSpy).toHaveBeenCalledWith(1)
restore()
})
it('ocm logout warns that OCM_TOKEN still authenticates', async () => {
const { cli, written, restore } = await loadCli({ env: 'tok_env' })
await cli.cmdLogout()
expect(written.join('')).toContain('note: OCM_TOKEN is set and takes precedence over the stored token')
restore()
})
})
+69
View File
@@ -0,0 +1,69 @@
import { vi } from 'vitest'
import type { OcmState } from '../../src/state.js'
import type { TokenStoreDescription } from '../../src/token-store.js'
export class MockTokenStoreError extends Error {
constructor(message: string, public kind = 'file') {
super(message)
this.name = 'TokenStoreError'
}
}
const DEFAULT_STORE: TokenStoreDescription = { kind: 'file', location: '/tmp/credentials.json' }
export interface TokenStoreMockOptions {
token?: string | null
getTokenImpl?: (account: string) => Promise<string | null>
setTokenImpl?: (account: string, token: string) => Promise<void>
deleteTokenImpl?: (account: string) => Promise<boolean>
store?: TokenStoreDescription
writeTarget?: TokenStoreDescription
env?: string | null
}
export function mockStateModule(state: OcmState | null = { managerUrl: 'https://manager.example.com' }) {
const clearState = vi.fn()
vi.doMock('../../src/state.js', () => ({
readState: () => state,
writeState: () => {},
clearState,
getStatePath: () => '/tmp/state.json',
getConfigDir: () => '/tmp',
}))
return { clearState }
}
export function mockTokenStoreModule(options: TokenStoreMockOptions = {}) {
const envValue = options.env ?? null
const getToken = vi.fn<(account: string) => Promise<string | null>>(
options.getTokenImpl ?? (() => Promise.resolve(options.token ?? null)),
)
const setToken = vi.fn<(account: string, token: string) => Promise<void>>(
options.setTokenImpl ?? (() => Promise.resolve()),
)
const deleteToken = vi.fn<(account: string) => Promise<boolean>>(
options.deleteTokenImpl ?? (() => Promise.resolve(true)),
)
const store = options.store ?? DEFAULT_STORE
vi.doMock('../../src/internal-token-store.js', () => ({
TOKEN_ENV: 'OCM_TOKEN',
envToken: () => envValue,
getToken,
setToken,
deleteToken,
hasStoredToken: async (account: string | undefined) => {
if (envValue) return true
if (!account) return false
return (await getToken(account)) !== null
},
describeTokenStore: () => (envValue ? { kind: 'env', location: 'OCM_TOKEN' } : store),
describeTokenWriteTarget: () => options.writeTarget ?? store,
TokenStoreError: MockTokenStoreError,
}))
return { getToken, setToken, deleteToken }
}
export function unmockTokenStoreModules() {
vi.doUnmock('../../src/state.js')
vi.doUnmock('../../src/internal-token-store.js')
}
+193
View File
@@ -0,0 +1,193 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
TOKEN_ENV,
selectTokenStore,
getToken,
setToken,
deleteToken,
hasStoredToken,
envToken,
describeTokenStore,
describeTokenWriteTarget,
TokenStoreError,
} from '../src/internal-token-store.js'
import type { TokenStore } from '../src/token-store.js'
const TOKEN_ENV_NAME = TOKEN_ENV
function makeInMemoryStore(seed: Record<string, string> = {}): TokenStore & {
calls: { get: string[]; set: Array<{ account: string; token: string }>; delete: string[] }
} {
const tokens = { ...seed }
const calls = { get: [] as string[], set: [] as Array<{ account: string; token: string }>, delete: [] as string[] }
return {
describe: () => ({ kind: 'file', location: '<in-memory>' }),
async get(account: string) {
calls.get.push(account)
return tokens[account] ?? null
},
async set(account: string, token: string) {
calls.set.push({ account, token })
tokens[account] = token
},
async delete(account: string) {
calls.delete.push(account)
if (!(account in tokens)) return false
delete tokens[account]
return true
},
calls,
}
}
function makeFailingStore(err: TokenStoreError): TokenStore {
return {
describe: () => ({ kind: 'file', location: '<failing>' }),
get: () => Promise.reject(err),
set: () => Promise.reject(err),
delete: () => Promise.reject(err),
}
}
describe('internal token store facade', () => {
const savedToken = process.env[TOKEN_ENV_NAME]
beforeEach(() => {
delete process.env[TOKEN_ENV_NAME]
})
afterEach(() => {
if (savedToken === undefined) delete process.env[TOKEN_ENV_NAME]
else process.env[TOKEN_ENV_NAME] = savedToken
})
describe('selectTokenStore', () => {
it('uses the keychain store on darwin', () => {
expect(selectTokenStore('darwin').describe().kind).toBe('keychain')
})
it('uses the file store on linux', () => {
expect(selectTokenStore('linux').describe().kind).toBe('file')
})
it('uses the file store on win32', () => {
expect(selectTokenStore('win32').describe().kind).toBe('file')
})
})
it('getToken returns the stored token', async () => {
const store = makeInMemoryStore({ 'https://m': 'tok_stored' })
await expect(getToken('https://m', store)).resolves.toBe('tok_stored')
expect(store.calls.get).toEqual(['https://m'])
})
it('OCM_TOKEN wins over the store', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore({ 'https://m': 'tok_stored' })
await expect(getToken('https://m', store)).resolves.toBe('tok_env')
expect(store.calls.get).toEqual([])
})
it('OCM_TOKEN is used when the store is empty', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore()
await expect(getToken('https://m', store)).resolves.toBe('tok_env')
expect(store.calls.get).toEqual([])
})
it('blank OCM_TOKEN falls through to the store', async () => {
process.env[TOKEN_ENV_NAME] = ' '
const store = makeInMemoryStore({ 'https://m': 'tok_stored' })
await expect(getToken('https://m', store)).resolves.toBe('tok_stored')
expect(store.calls.get).toEqual(['https://m'])
})
it('envToken reports the trimmed override', () => {
process.env[TOKEN_ENV_NAME] = ' tok_env '
expect(envToken()).toBe('tok_env')
})
it('envToken reports null when the override is blank', () => {
process.env[TOKEN_ENV_NAME] = ' '
expect(envToken()).toBeNull()
})
it('setToken never writes the env', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore()
await setToken('https://m', 'tok_new', store)
expect(process.env[TOKEN_ENV_NAME]).toBe('tok_env')
expect(store.calls.set).toEqual([{ account: 'https://m', token: 'tok_new' }])
})
it('setToken trims the token before storing', async () => {
const store = makeInMemoryStore()
await setToken('https://m', ' tok ', store)
expect(store.calls.set).toEqual([{ account: 'https://m', token: 'tok' }])
})
it('setToken rejects an empty token without touching the store', async () => {
const store = makeInMemoryStore()
await expect(setToken('https://m', ' ', store)).rejects.toThrow(TokenStoreError)
expect(store.calls.set).toEqual([])
})
it('deleteToken delegates to the store', async () => {
const store = makeInMemoryStore({ 'https://m': 'tok' })
await expect(deleteToken('https://m', store)).resolves.toBe(true)
await expect(deleteToken('https://other', store)).resolves.toBe(false)
expect(store.calls.delete).toEqual(['https://m', 'https://other'])
})
it('hasStoredToken reports a stored token', async () => {
const store = makeInMemoryStore({ 'https://m': 'tok' })
await expect(hasStoredToken('https://m', store)).resolves.toBe(true)
await expect(hasStoredToken('https://other', store)).resolves.toBe(false)
})
it('hasStoredToken reports true from the env override without an account', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore()
await expect(hasStoredToken(undefined, store)).resolves.toBe(true)
expect(store.calls.get).toEqual([])
})
it('hasStoredToken reports false without an account and without the env override', async () => {
const store = makeInMemoryStore({ 'https://m': 'tok' })
await expect(hasStoredToken(undefined, store)).resolves.toBe(false)
expect(store.calls.get).toEqual([])
})
it('hasStoredToken propagates a store failure', async () => {
const store = makeFailingStore(new TokenStoreError('keychain locked', 'keychain'))
await expect(hasStoredToken('https://m', store)).rejects.toThrow(TokenStoreError)
})
it('hasStoredToken prefers the env override over a failing store', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeFailingStore(new TokenStoreError('keychain locked', 'keychain'))
await expect(hasStoredToken('https://m', store)).resolves.toBe(true)
})
it('describeTokenStore reports env when OCM_TOKEN is set', () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore()
expect(describeTokenStore(store)).toEqual({ kind: 'env', location: TOKEN_ENV_NAME })
})
it('describeTokenStore reports the store when OCM_TOKEN is unset', () => {
const store = makeInMemoryStore()
expect(describeTokenStore(store)).toEqual({ kind: 'file', location: '<in-memory>' })
})
it('describeTokenWriteTarget reports the store even when OCM_TOKEN is set', () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore()
expect(describeTokenWriteTarget(store)).toEqual({ kind: 'file', location: '<in-memory>' })
})
it('describeTokenWriteTarget reports the store when OCM_TOKEN is unset', () => {
const store = makeInMemoryStore()
expect(describeTokenWriteTarget(store)).toEqual({ kind: 'file', location: '<in-memory>' })
})
})
+3 -13
View File
@@ -7,6 +7,7 @@ import { spawnSync, execSync } from 'child_process'
import { prepareMirror, MirrorAbort, mirrorDown, mirrorUp, mirrorUpPatch, mirrorUpFast, checkPushDivergence, checkPullDivergence, type MirrorUpFastPhase } from '../src/mirror'
import { getBranchName } from '../src/local-repo'
import { gitRemoteProjectId } from '@opencode-manager/shared/project-id'
import { mockStateModule, mockTokenStoreModule } from './helpers/token-store-mocks.js'
const ME_REPO_ID = gitRemoteProjectId('https://github.com/me/repo.git')!
const OTHER_REPO_ID = gitRemoteProjectId('https://github.com/other/repo.git')!
@@ -127,19 +128,8 @@ describe('cmdPush', () => {
throw new Error(stderrOutput.trim())
})
const mockState = { managerUrl: 'http://localhost:5003' }
vi.doMock('../src/state.js', () => ({
readState: () => mockState,
writeState: () => {},
clearState: () => {},
getStatePath: () => '/tmp/state.json',
}))
vi.doMock('../src/keychain.js', () => ({
getToken: () => 'test-token',
setToken: () => {},
deleteToken: () => true,
KeychainError: class extends Error {},
}))
mockStateModule({ managerUrl: 'http://localhost:5003' })
mockTokenStoreModule({ token: 'test-token' })
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ workspaces: [] }),
+143
View File
@@ -0,0 +1,143 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
let home: string
let configDir: string
let savedHome: string | undefined
async function loadState() {
vi.resetModules()
return import('../src/state.js')
}
beforeEach(() => {
savedHome = process.env.HOME
home = mkdtempSync(join(tmpdir(), 'ocm-home-'))
process.env.HOME = home
configDir = join(home, '.config', 'opencode-manager')
})
afterEach(() => {
if (savedHome === undefined) delete process.env.HOME
else process.env.HOME = savedHome
rmSync(home, { recursive: true, force: true })
})
describe('cli state file', () => {
it('returns null when no state file exists', async () => {
const { readState } = await loadState()
expect(readState()).toBeNull()
})
it('round-trips the manager url and last repo', async () => {
const { readState, writeState } = await loadState()
writeState({ managerUrl: 'https://manager.example.com', lastRepoId: 7, lastRepoName: 'repo' })
const state = readState()
expect(state?.managerUrl).toBe('https://manager.example.com')
expect(state?.lastRepoId).toBe(7)
expect(state?.updatedAt).toBeTypeOf('number')
})
it('writes the state file with owner-only permissions', async () => {
if (process.platform === 'win32') return
const { writeState, getStatePath } = await loadState()
writeState({ managerUrl: 'https://manager.example.com' })
expect(statSync(getStatePath()).mode & 0o777).toBe(0o600)
expect(statSync(configDir).mode & 0o777).toBe(0o700)
})
it('repairs loose permissions on an existing state file', async () => {
if (process.platform === 'win32') return
const { writeState, getStatePath } = await loadState()
mkdirSync(configDir, { recursive: true })
writeFileSync(getStatePath(), '{}', { mode: 0o644 })
writeState({ managerUrl: 'https://manager.example.com' })
expect(statSync(getStatePath()).mode & 0o777).toBe(0o600)
})
it('leaves no temp file behind', async () => {
const { writeState } = await loadState()
writeState({ managerUrl: 'https://manager.example.com' })
expect(readdirSync(configDir).filter((entry) => entry.endsWith('.tmp'))).toEqual([])
})
it('treats a corrupt state file as absent', async () => {
const { readState, getStatePath } = await loadState()
mkdirSync(configDir, { recursive: true })
writeFileSync(getStatePath(), 'not json')
expect(readState()).toBeNull()
})
it('treats a state file without a manager url as absent', async () => {
const { readState, getStatePath } = await loadState()
mkdirSync(configDir, { recursive: true })
writeFileSync(getStatePath(), JSON.stringify({ lastRepoId: 1 }))
expect(readState()).toBeNull()
})
it('surfaces an unreadable state file instead of reporting no manager', async () => {
if (process.platform === 'win32' || process.getuid?.() === 0) return
const { readState, writeState, getStatePath } = await loadState()
writeState({ managerUrl: 'https://manager.example.com' })
chmodSync(getStatePath(), 0o000)
expect(() => readState()).toThrow(/EACCES|EPERM/)
})
it('clearState empties an existing state file without recreating a missing one', async () => {
const { readState, writeState, clearState, getStatePath } = await loadState()
clearState()
expect(existsSync(getStatePath())).toBe(false)
writeState({ managerUrl: 'https://manager.example.com' })
clearState()
expect(readState()).toBeNull()
expect(readFileSync(getStatePath(), 'utf-8')).toBe('{}')
})
it('reads an install notice once and then removes it', async () => {
const { readInstallNotice } = await loadState()
mkdirSync(configDir, { recursive: true })
const noticeFile = join(configDir, 'install-notice.json')
writeFileSync(noticeFile, JSON.stringify({ link: '~/.local/bin/ocm', binDir: '~/.local/bin', pathMissing: true }))
expect(readInstallNotice()).toEqual({ link: '~/.local/bin/ocm', binDir: '~/.local/bin', pathMissing: true })
expect(existsSync(noticeFile)).toBe(false)
expect(readInstallNotice()).toBeNull()
})
it('keeps an unreadable install notice instead of consuming it', async () => {
if (process.platform === 'win32' || process.getuid?.() === 0) return
const { readInstallNotice } = await loadState()
mkdirSync(configDir, { recursive: true })
const noticeFile = join(configDir, 'install-notice.json')
writeFileSync(noticeFile, JSON.stringify({ link: '~/.local/bin/ocm', binDir: '~/.local/bin', pathMissing: true }))
chmodSync(noticeFile, 0o000)
expect(readInstallNotice()).toBeNull()
expect(existsSync(noticeFile)).toBe(true)
})
it('ignores an incomplete install notice', async () => {
const { readInstallNotice } = await loadState()
mkdirSync(configDir, { recursive: true })
writeFileSync(join(configDir, 'install-notice.json'), JSON.stringify({ binDir: '~/.local/bin' }))
expect(readInstallNotice()).toBeNull()
})
})
+291
View File
@@ -0,0 +1,291 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { createFileTokenStore } from '../src/token-store-file.js'
import { TokenStoreError } from '../src/token-store.js'
let dir: string
let file: string
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'ocm-cred-'))
file = join(dir, 'credentials.json')
})
afterEach(() => {
rmSync(dir, { recursive: true, force: true })
})
async function expectFileStoreError(run: () => Promise<unknown>, messagePart?: string) {
const err = await run().then(() => null, (caught: unknown) => caught)
expect(err).toBeInstanceOf(TokenStoreError)
const storeError = err as TokenStoreError
expect(storeError.kind).toBe('file')
if (messagePart) expect(storeError.message).toContain(messagePart)
return storeError
}
describe('file token store', () => {
it('reads back a token that was stored for an account', async () => {
const store = createFileTokenStore(file)
await store.set('https://manager.example.com', 'tok_abc123')
await expect(store.get('https://manager.example.com')).resolves.toBe('tok_abc123')
})
it('keeps tokens isolated per account', async () => {
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_a')
await store.set('https://b', 'tok_b')
await expect(store.get('https://a')).resolves.toBe('tok_a')
await expect(store.get('https://b')).resolves.toBe('tok_b')
})
it('returns null for an unknown account', async () => {
const store = createFileTokenStore(file)
await expect(store.get('https://missing')).resolves.toBeNull()
})
it('returns null when the file does not exist', async () => {
const store = createFileTokenStore(join(dir, 'absent.json'))
await expect(store.get('https://a')).resolves.toBeNull()
})
it('overwrites an existing token for the same account', async () => {
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_old')
await store.set('https://a', 'tok_new')
await expect(store.get('https://a')).resolves.toBe('tok_new')
})
it('deletes only the requested account', async () => {
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_a')
await store.set('https://b', 'tok_b')
await expect(store.delete('https://a')).resolves.toBe(true)
await expect(store.get('https://a')).resolves.toBeNull()
await expect(store.get('https://b')).resolves.toBe('tok_b')
})
it('reports false when deleting an account that is not stored', async () => {
const store = createFileTokenStore(file)
await expect(store.delete('https://missing')).resolves.toBe(false)
})
it('writes the file with owner-only permissions', async () => {
if (process.platform === 'win32') return
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_a')
expect(statSync(file).mode & 0o777).toBe(0o600)
})
it('creates the parent directory with owner-only permissions', async () => {
if (process.platform === 'win32') return
const nested = join(dir, 'nested', 'credentials.json')
const store = createFileTokenStore(nested)
await store.set('https://a', 'tok_a')
expect(statSync(join(dir, 'nested')).mode & 0o777).toBe(0o700)
})
it('tightens a loose parent directory mode on write', async () => {
if (process.platform === 'win32') return
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_a')
expect(statSync(dir).mode & 0o777).toBe(0o700)
})
it('repairs loose permissions on an existing file', async () => {
if (process.platform === 'win32') return
writeFileSync(file, '{}', { mode: 0o644 })
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_a')
expect(statSync(file).mode & 0o777).toBe(0o600)
})
it('tolerates a corrupt file on read', async () => {
writeFileSync(file, 'not json', { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://a')).resolves.toBeNull()
})
it('recovers a corrupt file on write', async () => {
writeFileSync(file, 'not json', { mode: 0o600 })
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_a')
await expect(store.get('https://a')).resolves.toBe('tok_a')
})
it('does not leave a temp file behind after a write', async () => {
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_a')
expect(readdirSync(dir).filter((entry) => entry.endsWith('.tmp'))).toEqual([])
})
it('creates the parent directory when it does not exist', async () => {
const nested = join(dir, 'nested', 'credentials.json')
const store = createFileTokenStore(nested)
await store.set('https://a', 'tok_a')
await expect(store.get('https://a')).resolves.toBe('tok_a')
})
it('describes its file location', () => {
const store = createFileTokenStore(file)
expect(store.describe()).toEqual({ kind: 'file', location: file })
})
it('treats an array-valued tokens map as corrupt and recovers on write', async () => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: [] }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://a')).resolves.toBeNull()
await store.set('https://a', 'tok_a')
await expect(store.get('https://a')).resolves.toBe('tok_a')
})
it('refuses to read a document written by an unsupported future version', async () => {
writeFileSync(file, JSON.stringify({ version: 2, tokens: { 'https://a': 'tok_a' } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expectFileStoreError(() => store.get('https://a'), 'unsupported format version 2')
})
it('refuses to overwrite a document written by an unsupported future version', async () => {
const future = JSON.stringify({ version: 2, tokens: { 'https://a': 'tok_a' } })
writeFileSync(file, future, { mode: 0o600 })
const store = createFileTokenStore(file)
await expectFileStoreError(() => store.set('https://b', 'tok_b'), 'unsupported format version 2')
expect(readFileSync(file, 'utf-8')).toBe(future)
})
it('refuses to delete from a document written by an unsupported future version', async () => {
writeFileSync(file, JSON.stringify({ version: 2, tokens: { 'https://a': 'tok_a' } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expectFileStoreError(() => store.delete('https://a'), 'unsupported format version 2')
})
it('treats a versionless document as the current version', async () => {
writeFileSync(file, JSON.stringify({ tokens: { 'https://a': 'tok_a' } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://a')).resolves.toBe('tok_a')
})
it('preserves unknown top-level keys when writing', async () => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: {}, futureField: { keep: true } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await store.set('https://a', 'tok_a')
const written = JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>
expect(written.futureField).toEqual({ keep: true })
expect(written.version).toBe(1)
})
it('wraps read failures from set as a file TokenStoreError', async () => {
const store = createFileTokenStore(dir)
await expectFileStoreError(() => store.set('https://a', 'tok_a'))
})
it('wraps read failures from delete as a file TokenStoreError', async () => {
const store = createFileTokenStore(dir)
await expectFileStoreError(() => store.delete('https://a'))
})
it('throws a TokenStoreError naming the file and cause when the file is unreadable', async () => {
if (process.platform === 'win32') return
writeFileSync(file, '{}', { mode: 0o000 })
const store = createFileTokenStore(file)
const err = await expectFileStoreError(() => store.get('https://a'), 'failed to read token file')
expect(err.message).toContain(file)
})
it('does not treat an unreadable file as missing', async () => {
if (process.platform === 'win32') return
writeFileSync(file, '{"version":1,"tokens":{"https://a":"tok_a"}}', { mode: 0o000 })
const store = createFileTokenStore(file)
await expectFileStoreError(() => store.get('https://a'))
})
it('treats an object-valued token as missing without throwing', async () => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: { 'https://m': {} } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://m')).resolves.toBeNull()
})
it('treats a number-valued token as missing without throwing', async () => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: { 'https://m': 42 } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://m')).resolves.toBeNull()
})
it('treats a boolean-valued token as missing without throwing', async () => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: { 'https://m': true } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://m')).resolves.toBeNull()
})
it('preserves string siblings alongside malformed token values', async () => {
writeFileSync(
file,
JSON.stringify({ version: 1, tokens: { 'https://m': {}, 'https://ok': 'tok_ok' } }),
{ mode: 0o600 },
)
const store = createFileTokenStore(file)
await expect(store.get('https://m')).resolves.toBeNull()
await expect(store.get('https://ok')).resolves.toBe('tok_ok')
})
it('drops malformed token values when writing a new token over the document', async () => {
writeFileSync(
file,
JSON.stringify({ version: 1, tokens: { 'https://m': {} } }),
{ mode: 0o600 },
)
const store = createFileTokenStore(file)
await store.set('https://m', 'tok_real')
await expect(store.get('https://m')).resolves.toBe('tok_real')
const written = JSON.parse(readFileSync(file, 'utf-8')) as { tokens: Record<string, unknown> }
expect(typeof written.tokens['https://m']).toBe('string')
})
})
+191
View File
@@ -0,0 +1,191 @@
import { afterEach, describe, it, expect, vi } from 'vitest'
import { createKeychainTokenStore, formatSecurityCommand, KEYCHAIN_SERVICE } from '../src/token-store-keychain.js'
import type { SecurityResult } from '../src/token-store-keychain.js'
import { TokenStoreError } from '../src/token-store.js'
const ok = (stdout = ''): SecurityResult => ({ stdout, stderr: '', code: 0 })
const failed = (code: number | null, stderr = ''): SecurityResult => ({ stdout: '', stderr, code })
const unavailable = () => Promise.reject(
new TokenStoreError("cannot run the macOS 'security' CLI: spawn /usr/bin/security ENOENT", 'keychain'),
)
const ACCOUNT = 'https://manager.example.com'
async function expectStoreError(run: () => Promise<unknown>, expected: { message: string | RegExp }) {
const err = await run().then(() => null, (caught: unknown) => caught)
expect(err).toBeInstanceOf(TokenStoreError)
const storeError = err as TokenStoreError
expect(storeError.kind).toBe('keychain')
if (typeof expected.message === 'string') expect(storeError.message).toContain(expected.message)
else expect(storeError.message).toMatch(expected.message)
return storeError
}
describe('keychain token store', () => {
it('rejects with a diagnostic TokenStoreError when the security binary is missing on get', async () => {
const store = createKeychainTokenStore(unavailable)
await expectStoreError(() => store.get(ACCOUNT), { message: /security/ })
})
it('rejects with a diagnostic TokenStoreError when the security binary is missing on set', async () => {
const store = createKeychainTokenStore(unavailable)
await expectStoreError(() => store.set(ACCOUNT, 'tok'), { message: /security/ })
})
it('rejects with a diagnostic TokenStoreError when the security binary is missing on delete', async () => {
const store = createKeychainTokenStore(unavailable)
await expectStoreError(() => store.delete(ACCOUNT), { message: /security/ })
})
it('invokes security with the exact add-generic-password argv including -U upsert', async () => {
const run = vi.fn().mockResolvedValue(ok())
const store = createKeychainTokenStore(run)
await store.set('https://m', 'tok')
expect(run).toHaveBeenCalledOnce()
expect(run).toHaveBeenCalledWith(
['add-generic-password', '-s', KEYCHAIN_SERVICE, '-a', 'https://m', '-w', 'tok', '-U'],
)
})
it('rejects with a TokenStoreError containing stderr when set exits non-zero', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(1, 'boom')))
await expectStoreError(() => store.set(ACCOUNT, 'tok'), { message: 'boom' })
})
it('falls back to exit status in the set error when stderr is empty', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(1)))
await expectStoreError(() => store.set(ACCOUNT, 'tok'), { message: 'exit status 1' })
})
it('falls back to exit status in the get error when stderr is empty', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(36)))
await expectStoreError(() => store.get(ACCOUNT), { message: 'exit status 36' })
})
it('falls back to exit status in the delete error when stderr is empty', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(1)))
await expectStoreError(() => store.delete(ACCOUNT), { message: 'exit status 1' })
})
it('reports process termination when there is no stderr and no exit status', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(null)))
await expectStoreError(() => store.set(ACCOUNT, 'tok'), { message: 'terminated' })
})
it('invokes security with the exact find-generic-password -w argv on get', async () => {
const run = vi.fn().mockResolvedValue(ok('tok_abc\n'))
const store = createKeychainTokenStore(run)
await store.get('https://m')
expect(run).toHaveBeenCalledOnce()
expect(run).toHaveBeenCalledWith(
['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', 'https://m', '-w'],
)
})
it('trims a trailing newline from get stdout', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(ok('tok_abc\n')))
await expect(store.get(ACCOUNT)).resolves.toBe('tok_abc')
})
it('returns null for an item-not-found exit without throwing', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(44, 'could not be found')))
await expect(store.get(ACCOUNT)).resolves.toBeNull()
})
it('returns null when get stdout is empty after trimming', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(ok('\n')))
await expect(store.get(ACCOUNT)).resolves.toBeNull()
})
it('invokes security with the exact delete-generic-password argv and returns true on status 0', async () => {
const run = vi.fn().mockResolvedValue(ok())
const store = createKeychainTokenStore(run)
await expect(store.delete('https://m')).resolves.toBe(true)
expect(run).toHaveBeenCalledWith(
['delete-generic-password', '-s', KEYCHAIN_SERVICE, '-a', 'https://m'],
)
})
it('returns false when delete exits with the item-not-found code', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(44, 'could not be found')))
await expect(store.delete(ACCOUNT)).resolves.toBe(false)
})
it('rejects with a TokenStoreError on a non-44 get failure', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(36, 'user interaction is not allowed')))
await expectStoreError(() => store.get(ACCOUNT), { message: 'user interaction is not allowed' })
})
it('rejects with a TokenStoreError on a non-44 delete failure', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(1, 'keychain locked')))
await expectStoreError(() => store.delete(ACCOUNT), { message: 'keychain locked' })
})
it('quotes every security argument and escapes backslashes and quotes', () => {
expect(formatSecurityCommand(['add-generic-password', '-a', 'a"b\\c', '-w', 'tok en'])).toBe(
'"add-generic-password" "-a" "a\\"b\\\\c" "-w" "tok en"\n',
)
})
it('refuses arguments containing line breaks so they cannot inject extra security commands', () => {
expect(() => formatSecurityCommand(['add-generic-password', '-w', 'tok\ndelete-generic-password']))
.toThrow(TokenStoreError)
})
it('describes itself as a keychain store with the service name', () => {
const run = vi.fn()
const store = createKeychainTokenStore(run)
expect(store.describe()).toEqual({
kind: 'keychain',
location: `macOS Keychain (service ${KEYCHAIN_SERVICE})`,
})
expect(run).not.toHaveBeenCalled()
})
})
describe('keychain token store process arguments', () => {
afterEach(() => {
vi.doUnmock('child_process')
vi.resetModules()
})
it('sends the token on stdin and never puts it in the security argv', async () => {
const end = vi.fn()
const execFile = vi.fn((_bin: string, _args: string[], _opts: unknown, cb: (err: null, stdout: string, stderr: string) => void) => {
cb(null, '', '')
return { stdin: { on: vi.fn(), end } }
})
vi.doMock('child_process', () => ({ execFile }))
vi.resetModules()
const { createKeychainTokenStore: create } = await import('../src/token-store-keychain.js')
await create().set('https://m', 'sup3r-secret')
expect(execFile).toHaveBeenCalledOnce()
expect(execFile.mock.calls[0]![0]).toBe('/usr/bin/security')
expect(execFile.mock.calls[0]![1]).toEqual(['-i'])
expect(end).toHaveBeenCalledWith(
`"add-generic-password" "-s" "${KEYCHAIN_SERVICE}" "-a" "https://m" "-w" "sup3r-secret" "-U"\n`,
)
})
})