mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
Before-merge items: 1. HTTPS enforced on every remote endpoint (RFC 8252 §8.3): baseUrl, issuer, authorization/token/revocation endpoints, and the traces endpoint all reject non-https, with a loopback (127.0.0.1/::1/ localhost) exception for offline tests and local dev. Enforcement is central (assertHttps) — the browser-open guard is no longer the only check whose failure was swallowed. 2. Credential store test isolation: CODEBURN_SYNC_TOKEN_STORE=file forces the file store (honors HOME) so the offline suite never touches the real macOS login keychain. Set in the e2e suite. 3. Golden pins for deriveSpanId/deriveTraceId/deriveDeviceId with fixed inputs and expected hex — the idempotency contract depends on these encodings being stable across releases; a green-tests encoding change would silently double-count history on span-ID-keyed backends. getDeviceId refactored over a pure deriveDeviceId(host, user). Smaller review items: - Callback server: ready promise resolves the actually-bound port from the listening event (kills the 100ms-sleep race after port fallback); Connection: close on all responses + closeAllConnections() on shutdown (pooled keep-alive sockets from a closed server could swallow requests aimed at a later server on the same port); error handler guarded so a post-bind error can never rebind to a different port than advertised; optional ports param ([0] = ephemeral) removes fixed-port contention between parallel test workers. - fetchOidcConfig verifies the issuer claim matches the fetch origin (OIDC Discovery §4.3 mix-up defense). - partialSuccess.rejectedSpans wrapped in Number() — proto3 int64 JSON mapping sends strings from strict protojson servers; += would concatenate. - Ledger writes are atomic (temp + rename); corrupt-ledger recovery and no-tmp-left-behind tests added; XDG_CACHE_HOME honored (ledger is reconstructible state, not config). - Mock IdP now implements /oauth2/authorize (registers PKCE challenge, 302s to redirect_uri) and verifies S256 code_verifier + single-use codes at the token endpoint. The e2e drives the real redirect flow and asserts wrong-verifier and code-reuse are rejected — PKCE binding is now exercised end to end. - sync reset calls clearLedger() instead of reimplementing the path. - push sets exit code 1 on rate-limited/server-error outcomes so cron and script callers can detect incomplete pushes. Deferred (noted for fast-follow): macOS 'security -i' stdin mode (untestable on this Linux box), ai.cost_estimated as a real ParsedApiCall flag (touches core parser types). Sync suite: 81 passing (5x stable), 5 developer-only. AI-Origin: human
218 lines
6.5 KiB
TypeScript
218 lines
6.5 KiB
TypeScript
/**
|
|
* codeburn sync — OS credential storage.
|
|
*
|
|
* Stores refresh tokens in the OS keychain.
|
|
* Falls back to a 0600 file when no keychain is available.
|
|
*/
|
|
|
|
import { execFileSync } from 'child_process'
|
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, chmodSync } from 'fs'
|
|
import { join } from 'path'
|
|
import { homedir } from 'os'
|
|
|
|
const SERVICE_NAME = 'codeburn-sync'
|
|
const ACCOUNT_NAME = 'refresh-token'
|
|
|
|
export type StorageMethod = 'keychain' | 'secret-tool' | 'dpapi' | 'file'
|
|
|
|
export interface CredentialStore {
|
|
store(token: string): void
|
|
retrieve(): string | null
|
|
delete(): void
|
|
method(): StorageMethod
|
|
}
|
|
|
|
// --- macOS Keychain ---
|
|
|
|
class KeychainStore implements CredentialStore {
|
|
store(token: string): void {
|
|
// Delete existing first (add-generic-password fails if entry exists)
|
|
try {
|
|
execFileSync('security', ['delete-generic-password', '-s', SERVICE_NAME, '-a', ACCOUNT_NAME], { stdio: 'pipe' })
|
|
} catch { /* may not exist */ }
|
|
|
|
// Token passed as arg to execFileSync (no shell interpolation).
|
|
// Note: still briefly visible in process args on macOS; `security` has no
|
|
// stdin mode for -w with non-interactive use, so this is the best available.
|
|
execFileSync('security', ['add-generic-password', '-s', SERVICE_NAME, '-a', ACCOUNT_NAME, '-w', token], { stdio: 'pipe' })
|
|
}
|
|
|
|
retrieve(): string | null {
|
|
try {
|
|
const result = execFileSync(
|
|
'security',
|
|
['find-generic-password', '-s', SERVICE_NAME, '-a', ACCOUNT_NAME, '-w'],
|
|
{ encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }
|
|
)
|
|
return result.trim() || null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
delete(): void {
|
|
try {
|
|
execFileSync('security', ['delete-generic-password', '-s', SERVICE_NAME, '-a', ACCOUNT_NAME], { stdio: 'pipe' })
|
|
} catch { /* may not exist */ }
|
|
}
|
|
|
|
method(): StorageMethod { return 'keychain' }
|
|
}
|
|
|
|
// --- Linux libsecret ---
|
|
|
|
class SecretToolStore implements CredentialStore {
|
|
store(token: string): void {
|
|
// Token passed via stdin — never appears in argv or shell string
|
|
execFileSync(
|
|
'secret-tool',
|
|
['store', `--label=${SERVICE_NAME}`, 'service', SERVICE_NAME, 'account', ACCOUNT_NAME],
|
|
{ input: token, stdio: ['pipe', 'pipe', 'pipe'] }
|
|
)
|
|
}
|
|
|
|
retrieve(): string | null {
|
|
try {
|
|
const result = execFileSync(
|
|
'secret-tool',
|
|
['lookup', 'service', SERVICE_NAME, 'account', ACCOUNT_NAME],
|
|
{ encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }
|
|
)
|
|
return result.trim() || null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
delete(): void {
|
|
try {
|
|
execFileSync('secret-tool', ['clear', 'service', SERVICE_NAME, 'account', ACCOUNT_NAME], { stdio: 'pipe' })
|
|
} catch { /* may not exist */ }
|
|
}
|
|
|
|
method(): StorageMethod { return 'secret-tool' }
|
|
}
|
|
|
|
// --- Windows DPAPI ---
|
|
|
|
class DpapiStore implements CredentialStore {
|
|
private filePath: string
|
|
|
|
constructor() {
|
|
this.filePath = join(homedir(), '.config', 'codeburn', '.sync-token-dpapi')
|
|
}
|
|
|
|
store(token: string): void {
|
|
// Token passed via environment variable — never in argv or command string
|
|
const ps = `$s = ConvertTo-SecureString $env:CODEBURN_SYNC_TOKEN -AsPlainText -Force; ConvertFrom-SecureString $s`
|
|
const encrypted = execFileSync('powershell', ['-NoProfile', '-Command', ps], {
|
|
encoding: 'utf-8',
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
env: { ...process.env, CODEBURN_SYNC_TOKEN: token },
|
|
}).trim()
|
|
|
|
const dir = join(homedir(), '.config', 'codeburn')
|
|
mkdirSync(dir, { recursive: true })
|
|
writeFileSync(this.filePath, encrypted, { mode: 0o600 })
|
|
}
|
|
|
|
retrieve(): string | null {
|
|
if (!existsSync(this.filePath)) return null
|
|
try {
|
|
const encrypted = readFileSync(this.filePath, 'utf-8').trim()
|
|
const ps = `$s = ConvertTo-SecureString $env:CODEBURN_SYNC_BLOB; [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($s))`
|
|
const result = execFileSync('powershell', ['-NoProfile', '-Command', ps], {
|
|
encoding: 'utf-8',
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
env: { ...process.env, CODEBURN_SYNC_BLOB: encrypted },
|
|
})
|
|
return result.trim() || null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
delete(): void {
|
|
try { unlinkSync(this.filePath) } catch { /* may not exist */ }
|
|
}
|
|
|
|
method(): StorageMethod { return 'dpapi' }
|
|
}
|
|
|
|
// --- File Fallback ---
|
|
|
|
class FileStore implements CredentialStore {
|
|
private filePath: string
|
|
|
|
constructor() {
|
|
this.filePath = join(homedir(), '.config', 'codeburn', '.sync-token')
|
|
}
|
|
|
|
store(token: string): void {
|
|
const dir = join(homedir(), '.config', 'codeburn')
|
|
mkdirSync(dir, { recursive: true })
|
|
writeFileSync(this.filePath, token, { mode: 0o600 })
|
|
// Ensure permissions (writeFile mode doesn't always work on existing files)
|
|
try { chmodSync(this.filePath, 0o600) } catch {}
|
|
}
|
|
|
|
retrieve(): string | null {
|
|
if (!existsSync(this.filePath)) return null
|
|
try {
|
|
return readFileSync(this.filePath, 'utf-8').trim() || null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
delete(): void {
|
|
try { unlinkSync(this.filePath) } catch { /* may not exist */ }
|
|
}
|
|
|
|
method(): StorageMethod { return 'file' }
|
|
}
|
|
|
|
// --- Factory ---
|
|
|
|
function isCommandAvailable(cmd: string): boolean {
|
|
try {
|
|
const probe = process.platform === 'win32' ? 'where' : 'which'
|
|
execFileSync(probe, [cmd], { stdio: 'pipe' })
|
|
return true
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
export function createCredentialStore(): CredentialStore {
|
|
// Test/CI escape hatch: force the file store (respects $HOME, so tests
|
|
// can fully isolate with a temp HOME). Without this, darwin machines
|
|
// would hit the real login keychain during the offline test suite.
|
|
if (process.env.CODEBURN_SYNC_TOKEN_STORE === 'file') {
|
|
return new FileStore()
|
|
}
|
|
|
|
if (process.platform === 'darwin') {
|
|
return new KeychainStore()
|
|
}
|
|
|
|
if (process.platform === 'win32') {
|
|
return new DpapiStore()
|
|
}
|
|
|
|
// Linux: try secret-tool, fall back to file
|
|
if (isCommandAvailable('secret-tool')) {
|
|
// Also verify the keyring daemon is running
|
|
try {
|
|
execFileSync('secret-tool', ['lookup', 'service', '__codeburn_probe__', 'account', '__probe__'], { stdio: 'pipe' })
|
|
return new SecretToolStore()
|
|
} catch (err) {
|
|
// Exit code 1 = not found (keyring works). Other errors = keyring not running.
|
|
if ((err as { status?: number }).status === 1) {
|
|
return new SecretToolStore()
|
|
}
|
|
}
|
|
}
|
|
|
|
return new FileStore()
|
|
}
|