GCoordinator/src/server/security/vault.ts

422 lines
12 KiB
TypeScript

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';
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(),
});
type VaultEnvelope = z.infer<typeof VaultEnvelopeSchema>;
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 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}`;
}
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
export type VaultCredentialInput = DistributiveOmit<
VaultCredential,
'createdAt' | 'updatedAt'
> & {
createdAt?: string;
updatedAt?: string;
};
export class VaultService {
private masterKey: Buffer | null = null;
private credentials = new Map<string, VaultCredential>();
private wasPanicLocked = false;
private readonly panicListeners = new Set<() => void>();
constructor(private readonly vaultFilePath: string) {
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 state(): VaultState {
if (this.masterKey !== null) 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);
};
}
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 } {
if (fs.existsSync(this.vaultFilePath)) {
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.setPanicLockMarker(false);
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.setPanicLockMarker(false);
} catch (err) {
keyBuf.fill(0);
throw err;
}
}
panicLock(): void {
this.zeroizeMasterKey();
this.credentials.clear();
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.assertUnlocked();
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;
return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') };
} catch (err) {
nextKey.fill(0);
throw err;
}
}
listMetadata(): VaultCredentialMeta[] {
this.assertUnlocked();
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);
}
getSecret(id: string): VaultCredential | undefined {
this.assertUnlocked();
const cred = this.credentials.get(id);
return cred ? structuredClone(cred) : undefined;
}
exportMasterKeyHex(): string | null {
return this.masterKey ? this.masterKey.toString('hex') : null;
}
exportAllCredentials(): Record<string, VaultCredential> {
this.assertUnlocked();
const out: Record<string, VaultCredential> = {};
for (const [id, cred] of this.credentials.entries()) {
out[id] = structuredClone(cred);
}
return out;
}
upsertCredential(input: VaultCredentialInput): VaultCredentialMeta {
this.assertUnlocked();
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.assertUnlocked();
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.assertUnlocked();
const keyPair = options.passphrase
? ssh2.utils.generateKeyPairSync('ed25519', {
comment: options.comment ?? options.id,
passphrase: options.passphrase,
cipher: 'aes256-ctr',
rounds: 16,
})
: ssh2.utils.generateKeyPairSync('ed25519', {
comment: options.comment ?? options.id,
});
const publicKey = keyPair.public.trim();
const fingerprint = computeOpenSshFingerprint(publicKey);
return this.upsertCredential({
id: options.id,
name: options.name,
type: 'ssh-key',
privateKey: keyPair.private,
publicKey,
passphrase: options.passphrase || undefined,
fingerprint,
});
}
private assertUnlocked(): void {
if (this.masterKey === null) {
throw new Error('Vault is locked');
}
}
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;
}
}
}