UNPKG

@vigilbase/cli

Version:

Vigilbase CLI — security scanners, agent tools, and Vigilbase One from the terminal.

150 lines (149 loc) • 7.33 kB
import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID, sign } from 'node:crypto'; import { execFile } from 'node:child_process'; import { dirname, isAbsolute, join } from 'node:path'; import { rm } from 'node:fs/promises'; import { z } from 'zod'; import { platform } from '../lib/platform.js'; import { checkDirectory, checkExistingFile, identityCredentialsPath } from './store.js'; import { readPrivateFile, writePrivateFile } from './private-file.js'; const publicJwkSchema = z.object({ kty: z.literal('OKP'), crv: z.literal('Ed25519'), x: z.string().min(1) }); const privateJwkSchema = z.object({ kty: z.literal('OKP'), crv: z.literal('Ed25519'), x: z.string().min(1), d: z.string().min(1) }); const KEYCHAIN_SERVICE = 'com.vigilbase.cli.dpop'; const KEYCHAIN_LABEL = 'Vigilbase CLI sign-in key'; const ACCOUNT = /^[0-9a-f-]{36}$/; const BASE64URL = /^[A-Za-z0-9_-]+$/; export function dpopKeyPath(config, binding = 'software') { return join(dirname(identityCredentialsPath(config)), binding === 'keychain' ? 'identity-dpop-key.keychain' : 'identity-dpop-key.json'); } /** * Apple's /usr/bin/security, signed by Apple, so the CLI ships no native code. * `VIGILBASE_KEYCHAIN=off` forces a key file; `VIGILBASE_KEYCHAIN_TOOL` (an * absolute path) replaces the tool in tests. */ function keychainTool() { if (process.env.VIGILBASE_KEYCHAIN === 'off') return null; const override = process.env.VIGILBASE_KEYCHAIN_TOOL; // A bare name would be looked up on PATH, and a relative one in the working directory. if (override && !isAbsolute(override)) throw new Error('VIGILBASE_KEYCHAIN_TOOL must be an absolute path.'); if (override) return override; return platform() === 'darwin' ? '/usr/bin/security' : null; } /** No secret ever goes in argv: `security -i` reads the add command from stdin. */ function run(tool, args, stdin) { return new Promise((resolve, reject) => { const child = execFile(tool, args, { timeout: 10_000, maxBuffer: 65_536 }, (error, stdout) => { if (error) { reject(error); return; } resolve(stdout); }); child.stdin?.on('error', () => { }); child.stdin?.end(stdin ?? ''); }); } async function keychainRead(tool, account) { return (await run(tool, ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account, '-w'])).trim(); } async function keychainWrite(tool, account, secret) { if (!ACCOUNT.test(account) || !BASE64URL.test(secret)) throw new Error('Invalid Keychain item.'); await run(tool, ['-i'], `add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${account} -l "${KEYCHAIN_LABEL}" -w ${secret}\n`); // `security -i` does not report a failed command in its exit status; read it back. if (await keychainRead(tool, account) !== secret) throw new Error('The Keychain did not keep the sign-in key.'); } async function keychainDelete(tool, account) { await run(tool, ['delete-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account]).catch(() => { }); } function keyFromJwk(config, binding, jwk) { const privateKey = createPrivateKey({ key: jwk, format: 'jwk' }); const publicJwk = publicJwkSchema.parse(createPublicKey(privateKey).export({ format: 'jwk' })); return { binding, publicJwk, sign: async (input) => sign(null, Buffer.from(input), privateKey).toString('base64url'), delete: () => deleteDpopKey(config), }; } function encodeJwk(jwk) { return Buffer.from(JSON.stringify(jwk)).toString('base64url'); } function decodeJwk(secret) { return privateJwkSchema.parse(JSON.parse(Buffer.from(secret, 'base64url').toString('utf8'))); } async function keychainKey(config, marker) { const account = marker.trim(); if (!ACCOUNT.test(account)) throw new Error('The saved sign-in key is invalid. Run `vigilbase logout` then `vigilbase login`.'); const tool = keychainTool(); // Never silently replace the key of an existing bound grant with a key file. if (!tool) throw new Error('This sign-in keeps its key in the macOS Keychain, which is unavailable here. Run `vigilbase logout` then `vigilbase login`.'); let secret; try { secret = await keychainRead(tool, account); } catch (error) { throw new Error('Could not read your sign-in key from the macOS Keychain. Unlock your Mac (over SSH, run `security unlock-keychain`) and try again, or run `vigilbase logout` then `vigilbase login`.', { cause: error }); } try { return keyFromJwk(config, 'keychain', decodeJwk(secret)); } catch (error) { throw new Error('The sign-in key in your Keychain is invalid. Run `vigilbase logout` then `vigilbase login`.', { cause: error }); } } export async function loadDpopKey(config) { const marker = await readPrivateFile(dpopKeyPath(config, 'keychain')); if (marker !== null) return keychainKey(config, marker); const saved = await readPrivateFile(dpopKeyPath(config)); if (saved === null) throw new Error('The sign-in key is missing. Run `vigilbase login` again.'); try { return keyFromJwk(config, 'software', privateJwkSchema.parse(JSON.parse(saved))); } catch (error) { throw new Error('The saved sign-in key is invalid. Run `vigilbase logout` then `vigilbase login`.', { cause: error }); } } /** Idempotent, under the shared credentials lock: concurrent logins must use the same key. */ export async function createDpopKey(config) { const { withCredentialsLock } = await import('./refresh.js'); return withCredentialsLock(config, async () => { for (const binding of ['keychain', 'software']) { if (await checkExistingFile(dpopKeyPath(config, binding))) return loadDpopKey(config); } const { privateKey } = generateKeyPairSync('ed25519'); const jwk = privateKey.export({ format: 'jwk' }); const tool = keychainTool(); if (tool) { const account = randomUUID(); try { await keychainWrite(tool, account, encodeJwk(jwk)); await writePrivateFile(dpopKeyPath(config, 'keychain'), `${account}\n`); return keyFromJwk(config, 'keychain', jwk); } catch { // A locked or missing Keychain (SSH, CI) falls back to a key file at sign-in only. await keychainDelete(tool, account); } } await writePrivateFile(dpopKeyPath(config), `${JSON.stringify(jwk)}\n`); return keyFromJwk(config, 'software', jwk); }, true); } /** Call after revocation, while holding the credentials lock. */ export async function deleteDpopKey(config) { if (!await checkDirectory(dirname(identityCredentialsPath(config)))) return; const markerPath = dpopKeyPath(config, 'keychain'); if (await checkExistingFile(markerPath)) { const account = (await readPrivateFile(markerPath))?.trim() ?? ''; const tool = keychainTool(); if (tool && ACCOUNT.test(account)) await keychainDelete(tool, account); await rm(markerPath); } if (await checkExistingFile(dpopKeyPath(config))) await rm(dpopKeyPath(config)); }