import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import ssh2 from 'ssh2'; import { z } from 'zod'; import { VaultCredentialSchema, VaultPayloadSchema, type VaultCredential, type VaultCredentialMeta, type VaultPayload, } from '../../shared/schemas/vault.schema.js'; import type { VaultState } from '../../shared/ws-protocol.js'; export const VaultEnvelopeSchema = z.object({ version: z.literal(1), alg: z.literal('aes-256-gcm'), iv: z.string().min(1), tag: z.string().min(1), ciphertext: z.string().min(1), updatedAt: z.string(), }); export type VaultEnvelope = z.infer; export function parseMasterKey(raw: string): Buffer { const trimmed = raw.trim(); if (/^[0-9a-fA-F]{64}$/.test(trimmed)) { return Buffer.from(trimmed, 'hex'); } if (/^[A-Za-z0-9+/=]{43,44}$/.test(trimmed)) { const buf = Buffer.from(trimmed, 'base64'); if (buf.length === 32) return buf; } throw new Error('Master key must be a 32-byte key encoded as 64 hex chars or base64'); } export function generateMasterKeyBuffer(): Buffer { return crypto.randomBytes(32); } function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); const plaintext = Buffer.from(JSON.stringify(payload), 'utf8'); const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]); const tag = cipher.getAuthTag(); plaintext.fill(0); return { version: 1, alg: 'aes-256-gcm', iv: iv.toString('base64'), tag: tag.toString('base64'), ciphertext: ciphertext.toString('base64'), updatedAt: new Date().toISOString(), }; } function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload { const iv = Buffer.from(envelope.iv, 'base64'); const tag = Buffer.from(envelope.tag, 'base64'); const ciphertext = Buffer.from(envelope.ciphertext, 'base64'); if (iv.length !== 12 || tag.length !== 16) { throw new Error('Invalid AES-256-GCM envelope parameters'); } const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); decipher.setAuthTag(tag); const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]); try { const parsed = JSON.parse(plaintext.toString('utf8')); return VaultPayloadSchema.parse(parsed); } finally { plaintext.fill(0); } } export function verifyVaultEnvelopeText( rawText: string, masterKeyInput?: string, ): { envelopeValid: boolean; decrypted: boolean; credentialCount?: number; updatedAt: string; } { const envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText)); if (!masterKeyInput || !masterKeyInput.trim()) { return { envelopeValid: true, decrypted: false, updatedAt: envelope.updatedAt, }; } const keyBuf = parseMasterKey(masterKeyInput); try { const payload = decryptEnvelope(envelope, keyBuf); return { envelopeValid: true, decrypted: true, credentialCount: Object.keys(payload.credentials).length, updatedAt: envelope.updatedAt, }; } finally { keyBuf.fill(0); } } export function computeOpenSshFingerprint(publicKeyLine: string): string { const parsed = ssh2.utils.parseKey(publicKeyLine.trim()); if (parsed instanceof Error) { throw parsed; } const key = Array.isArray(parsed) ? parsed[0]! : parsed; const hash = crypto .createHash('sha256') .update(key.getPublicSSH()) .digest('base64') .replace(/=+$/, ''); return `SHA256:${hash}`; } /** * Generates an OpenSSH Ed25519 keypair, retrying around ssh2's BitString * leading-zero stripping bug when a generated public key starts with 0x00. */ export function generateValidEd25519KeyPair(opts: { comment: string; passphrase?: string; }): { privateKey: string; publicKey: string; fingerprint: string } { let lastErr: unknown; for (let attempt = 0; attempt < 16; attempt++) { const kp = opts.passphrase ? ssh2.utils.generateKeyPairSync('ed25519', { comment: opts.comment, passphrase: opts.passphrase, cipher: 'aes256-ctr', rounds: 16, }) : ssh2.utils.generateKeyPairSync('ed25519', { comment: opts.comment, }); const publicKey = kp.public.trim(); try { const fingerprint = computeOpenSshFingerprint(publicKey); return { privateKey: kp.private, publicKey, fingerprint }; } catch (err) { lastErr = err; } } throw lastErr instanceof Error ? lastErr : new Error('Failed to generate valid Ed25519 keypair'); } type DistributiveOmit = T extends unknown ? Omit : never; export type VaultCredentialInput = DistributiveOmit< VaultCredential, 'createdAt' | 'updatedAt' > & { createdAt?: string; updatedAt?: string; }; export interface VaultServiceOptions { keyFilePath?: string; } export class VaultService { private masterKey: Buffer | null = null; private credentials = new Map(); private writeUnlocked = false; private autoInitializedEmpty = false; private wasPanicLocked = false; private readonly keyFilePath: string | null; private readonly panicListeners = new Set<() => void>(); constructor( private readonly vaultFilePath: string, options: VaultServiceOptions = {}, ) { this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null; this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath()); } private panicLockMarkerPath(): string { return `${this.vaultFilePath}.panic-locked`; } private setPanicLockMarker(active: boolean): void { this.wasPanicLocked = active; const markerPath = this.panicLockMarkerPath(); if (active) { fs.mkdirSync(path.dirname(markerPath), { recursive: true }); fs.writeFileSync(markerPath, `${Date.now()}\n`, { mode: 0o600 }); } else { fs.rmSync(markerPath, { force: true }); } } get filePath(): string { return this.vaultFilePath; } get isRuntimeReady(): boolean { return this.masterKey !== null; } get state(): VaultState { if (this.masterKey !== null && this.writeUnlocked) return 'unlocked'; return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized'; } get isPanicLocked(): boolean { return this.wasPanicLocked || fs.existsSync(this.panicLockMarkerPath()); } onPanicLock(listener: () => void): () => void { this.panicListeners.add(listener); return () => { this.panicListeners.delete(listener); }; } initRuntime(options: { secretFilePath?: string; envKey?: string; backupKey?: string; autoCreateIfMissing?: boolean; }): { runtimeReady: boolean; initialized?: boolean; reason?: string } { // Security invariant: never silently re-read disk secrets after Emergency Panic Lock if (this.isPanicLocked) { return { runtimeReady: false, reason: 'panic_locked' }; } const candidates: string[] = []; if (options.secretFilePath && fs.existsSync(options.secretFilePath)) { const val = fs.readFileSync(options.secretFilePath, 'utf8').trim(); if (val) candidates.push(val); } if (options.envKey && options.envKey.trim().length > 0) { candidates.push(options.envKey.trim()); } if (this.keyFilePath && fs.existsSync(this.keyFilePath)) { const val = fs.readFileSync(this.keyFilePath, 'utf8').trim(); if (val) candidates.push(val); } if (options.backupKey && options.backupKey.trim().length > 0) { candidates.push(options.backupKey.trim()); } if (fs.existsSync(this.vaultFilePath)) { if (candidates.length === 0) { return { runtimeReady: false, reason: 'no_key' }; } let envelope: VaultEnvelope; try { const rawText = fs.readFileSync(this.vaultFilePath, 'utf8'); envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText)); } catch (err) { return { runtimeReady: false, reason: err instanceof Error ? err.message : 'decrypt_failed', }; } for (const candidate of candidates) { let keyBuf: Buffer | null = null; try { keyBuf = parseMasterKey(candidate); const payload = decryptEnvelope(envelope, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = false; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); this.persistKeyFileIfConfigured(keyBuf); return { runtimeReady: true }; } catch { keyBuf?.fill(0); } } return { runtimeReady: false, reason: 'decrypt_failed' }; } if (!options.autoCreateIfMissing && candidates.length === 0) { return { runtimeReady: false, reason: 'no_key' }; } let keyBuf: Buffer | null = null; try { keyBuf = candidates[0] ? parseMasterKey(candidates[0]) : generateMasterKeyBuffer(); const emptyPayload: VaultPayload = { version: 1, credentials: {} }; this.writeVerifiedVaultAtomic(emptyPayload, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; this.credentials.clear(); this.writeUnlocked = false; this.autoInitializedEmpty = true; this.setPanicLockMarker(false); this.persistKeyFileIfConfigured(keyBuf); return { runtimeReady: true, initialized: true }; } catch (err) { keyBuf?.fill(0); return { runtimeReady: false, reason: err instanceof Error ? err.message : 'init_failed', }; } } tryAutoUnlockFromEnvOrSecret(options: { secretFilePath?: string; envKey?: string; }): { unlocked: boolean; initialized?: boolean; reason?: string } { // Security invariant: never silently re-read disk secrets after Emergency Panic Lock if (this.isPanicLocked) { return { unlocked: false, reason: 'panic_locked' }; } let rawKey: string | undefined; if (options.secretFilePath && fs.existsSync(options.secretFilePath)) { rawKey = fs.readFileSync(options.secretFilePath, 'utf8').trim(); } else if (options.envKey && options.envKey.trim().length > 0) { rawKey = options.envKey.trim(); } if (!rawKey) { return { unlocked: false, reason: 'no_key' }; } try { if (!fs.existsSync(this.vaultFilePath)) { this.initializeNewVault(rawKey); return { unlocked: true, initialized: true }; } this.unlock(rawKey); return { unlocked: true }; } catch (err) { return { unlocked: false, reason: err instanceof Error ? err.message : 'decrypt_failed', }; } } initializeNewVault(masterKeyInput?: string): { generatedKeyHex?: string } { const allowOverwriteAutoEmpty = this.autoInitializedEmpty && this.credentials.size === 0; if (fs.existsSync(this.vaultFilePath) && !allowOverwriteAutoEmpty) { throw new Error('Vault file already exists; unlock it instead of initializing'); } const keyBuf = masterKeyInput ? parseMasterKey(masterKeyInput) : generateMasterKeyBuffer(); const emptyPayload: VaultPayload = { version: 1, credentials: {} }; this.writeVerifiedVaultAtomic(emptyPayload, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; this.credentials.clear(); this.writeUnlocked = true; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); this.persistKeyFileIfConfigured(keyBuf); return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') }; } unlock(masterKeyInput: string): void { if (!fs.existsSync(this.vaultFilePath)) { throw new Error('Vault is not initialized yet'); } const keyBuf = parseMasterKey(masterKeyInput); try { const rawText = fs.readFileSync(this.vaultFilePath, 'utf8'); const envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText)); const payload = decryptEnvelope(envelope, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = true; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); this.persistKeyFileIfConfigured(keyBuf); } catch (err) { keyBuf.fill(0); throw err; } } unlockForModifications(): void { if (this.masterKey === null || this.isPanicLocked) { throw new Error('Master key is required to unseal vault'); } this.writeUnlocked = true; } lockForModifications(): void { this.writeUnlocked = false; } reloadFromDisk(masterKeyInput?: string): boolean { if (!fs.existsSync(this.vaultFilePath)) { this.credentials.clear(); return false; } let candidateKey: Buffer | null = null; if (masterKeyInput && masterKeyInput.trim().length > 0) { candidateKey = parseMasterKey(masterKeyInput); } else if (this.masterKey !== null) { candidateKey = Buffer.from(this.masterKey); } else { return false; } try { const rawText = fs.readFileSync(this.vaultFilePath, 'utf8'); const envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText)); const payload = decryptEnvelope(envelope, candidateKey); const wasUnlocked = this.writeUnlocked; this.zeroizeMasterKey(); this.masterKey = candidateKey; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = wasUnlocked; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); this.persistKeyFileIfConfigured(candidateKey); return true; } catch (err) { candidateKey.fill(0); throw err; } } panicLock(): void { this.zeroizeMasterKey(); this.credentials.clear(); this.writeUnlocked = false; this.autoInitializedEmpty = false; this.setPanicLockMarker(true); for (const listener of this.panicListeners) { try { listener(); } catch { // Panic lock cleanup must continue across all listeners } } } rotateMasterKey(newMasterKeyInput?: string): { generatedKeyHex?: string } { this.assertWriteUnlocked(); const nextKey = newMasterKeyInput ? parseMasterKey(newMasterKeyInput) : generateMasterKeyBuffer(); const payload: VaultPayload = { version: 1, credentials: Object.fromEntries(this.credentials.entries()), }; try { this.writeVerifiedVaultAtomic(payload, nextKey); this.zeroizeMasterKey(); this.masterKey = nextKey; this.writeUnlocked = true; this.persistKeyFileIfConfigured(nextKey); return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') }; } catch (err) { nextKey.fill(0); throw err; } } listMetadata(): VaultCredentialMeta[] { this.assertRuntimeReady(); return [...this.credentials.values()].map((cred) => { const meta: VaultCredentialMeta = { id: cred.id, name: cred.name, type: cred.type, createdAt: cred.createdAt, updatedAt: cred.updatedAt, }; if (cred.type === 'ssh-key') { meta.fingerprint = cred.fingerprint; meta.publicKey = cred.publicKey; meta.hasPassphrase = Boolean(cred.passphrase); } return meta; }); } hasCredential(id: string): boolean { if (this.masterKey === null) return false; return this.credentials.has(id); } getRuntimeSecret(id: string): VaultCredential | undefined { this.assertRuntimeReady(); const cred = this.credentials.get(id); return cred ? structuredClone(cred) : undefined; } getSecret(id: string): VaultCredential | undefined { this.assertWriteUnlocked(); const cred = this.credentials.get(id); return cred ? structuredClone(cred) : undefined; } exportMasterKeyHex(): string | null { return this.masterKey ? this.masterKey.toString('hex') : null; } exportAllCredentials(): Record { this.assertRuntimeReady(); const out: Record = {}; for (const [id, cred] of this.credentials.entries()) { out[id] = structuredClone(cred); } return out; } upsertCredential(input: VaultCredentialInput): VaultCredentialMeta { this.assertWriteUnlocked(); this.autoInitializedEmpty = false; const now = new Date().toISOString(); const existing = this.credentials.get(input.id); const candidate = VaultCredentialSchema.parse({ ...input, createdAt: existing?.createdAt ?? input.createdAt ?? now, updatedAt: now, }); const nextMap = new Map(this.credentials); nextMap.set(candidate.id, candidate); const payload: VaultPayload = { version: 1, credentials: Object.fromEntries(nextMap.entries()), }; this.writeVerifiedVaultAtomic(payload, this.masterKey!); this.credentials = nextMap; const meta = this.listMetadata().find((m) => m.id === candidate.id)!; return meta; } deleteCredential(id: string): boolean { this.assertWriteUnlocked(); if (!this.credentials.has(id)) return false; const nextMap = new Map(this.credentials); nextMap.delete(id); const payload: VaultPayload = { version: 1, credentials: Object.fromEntries(nextMap.entries()), }; this.writeVerifiedVaultAtomic(payload, this.masterKey!); this.credentials = nextMap; return true; } generateEd25519Credential(options: { id: string; name: string; comment?: string; passphrase?: string; }): VaultCredentialMeta { this.assertWriteUnlocked(); this.autoInitializedEmpty = false; const { privateKey, publicKey, fingerprint } = generateValidEd25519KeyPair({ comment: options.comment ?? options.id, passphrase: options.passphrase, }); return this.upsertCredential({ id: options.id, name: options.name, type: 'ssh-key', privateKey, publicKey, passphrase: options.passphrase || undefined, fingerprint, }); } private assertRuntimeReady(): void { if (this.masterKey === null) { throw new Error('Vault is locked'); } } private assertWriteUnlocked(): void { if (this.masterKey === null || !this.writeUnlocked) { throw new Error('Vault is locked'); } } private persistKeyFileIfConfigured(key: Buffer): void { const siblingKeyFile = path.join(path.dirname(this.vaultFilePath), 'vault.key'); const targetPath = this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null); if (!targetPath) return; fs.mkdirSync(path.dirname(targetPath), { recursive: true }); const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); } fs.renameSync(tmpPath, targetPath); fs.chmodSync(targetPath, 0o600); } private zeroizeMasterKey(): void { if (this.masterKey !== null) { this.masterKey.fill(0); this.masterKey = null; } } private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void { const dir = path.dirname(this.vaultFilePath); fs.mkdirSync(dir, { recursive: true }); const envelope = encryptPayload(payload, key); const serialized = JSON.stringify(envelope, null, 2); const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${Date.now()}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, serialized, 'utf8'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); } // Verify round-trip read + GCM tag before replacing live vault.enc try { const readBack = VaultEnvelopeSchema.parse( JSON.parse(fs.readFileSync(tmpPath, 'utf8')), ); decryptEnvelope(readBack, key); fs.renameSync(tmpPath, this.vaultFilePath); fs.chmodSync(this.vaultFilePath, 0o600); } catch (err) { try { fs.unlinkSync(tmpPath); } catch { // Ignore cleanup errors } throw err; } } }