feat(security): implement AES-256-GCM vault, Panic Lock, Argon2id+TOTP auth, guards, and rotate-key CLI

This commit is contained in:
tyuXX 2026-11-26 18:21:09 +00:00
parent 2c60483a90
commit 3b9e084916
5 changed files with 1249 additions and 0 deletions

View file

@ -0,0 +1,418 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
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);
}
}
function buildSshEd25519PublicAndFingerprint(spkiDer: Buffer, comment?: string): {
publicKey: string;
fingerprint: string;
} {
// Ed25519 SPKI DER is 44 bytes: 12-byte ASN.1 header + 32-byte raw public key
if (spkiDer.length !== 44) {
throw new Error(`Unexpected Ed25519 SPKI DER length: ${spkiDer.length}`);
}
const rawPub = spkiDer.subarray(12);
const algBuf = Buffer.from('ssh-ed25519', 'ascii');
const wire = Buffer.allocUnsafe(4 + algBuf.length + 4 + rawPub.length);
wire.writeUInt32BE(algBuf.length, 0);
algBuf.copy(wire, 4);
wire.writeUInt32BE(rawPub.length, 4 + algBuf.length);
rawPub.copy(wire, 8 + algBuf.length);
const publicB64 = wire.toString('base64');
const fingerprintHash = crypto
.createHash('sha256')
.update(wire)
.digest('base64')
.replace(/=+$/, '');
const publicKey = comment ? `ssh-ed25519 ${publicB64} ${comment}` : `ssh-ed25519 ${publicB64}`;
return {
publicKey,
fingerprint: `SHA256:${fingerprintHash}`,
};
}
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) {}
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;
}
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.wasPanicLocked) {
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.wasPanicLocked = 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.wasPanicLocked = false;
} catch (err) {
keyBuf.fill(0);
throw err;
}
}
panicLock(): void {
this.zeroizeMasterKey();
this.credentials.clear();
this.wasPanicLocked = 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;
}
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 privateKeyEncoding = options.passphrase
? ({
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: options.passphrase,
} as const)
: ({
type: 'pkcs8',
format: 'pem',
} as const);
const { publicKey: spkiDer, privateKey: privatePem } = crypto.generateKeyPairSync(
'ed25519',
{
publicKeyEncoding: { type: 'spki', format: 'der' },
privateKeyEncoding,
},
);
const { publicKey, fingerprint } = buildSshEd25519PublicAndFingerprint(
spkiDer,
options.comment ?? options.id,
);
return this.upsertCredential({
id: options.id,
name: options.name,
type: 'ssh-key',
privateKey: privatePem,
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;
}
}
}