feat(vault): keep established secrets active at runtime and require unlock only for modifications

This commit is contained in:
tyuXX 2026-11-26 22:25:55 +00:00
parent c5a5835ae6
commit 10a28bb316
14 changed files with 445 additions and 85 deletions

View file

@ -101,13 +101,24 @@ export type VaultCredentialInput = DistributiveOmit<
updatedAt?: string;
};
export interface VaultServiceOptions {
keyFilePath?: string;
}
export class VaultService {
private masterKey: Buffer | null = null;
private credentials = new Map<string, VaultCredential>();
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) {
constructor(
private readonly vaultFilePath: string,
options: VaultServiceOptions = {},
) {
this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null;
this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath());
}
@ -130,8 +141,12 @@ export class VaultService {
return this.vaultFilePath;
}
get isRuntimeReady(): boolean {
return this.masterKey !== null;
}
get state(): VaultState {
if (this.masterKey !== null) return 'unlocked';
if (this.masterKey !== null && this.writeUnlocked) return 'unlocked';
return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized';
}
@ -146,6 +161,95 @@ export class VaultService {
};
}
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;
@ -182,7 +286,9 @@ export class VaultService {
}
initializeNewVault(masterKeyInput?: string): { generatedKeyHex?: string } {
if (fs.existsSync(this.vaultFilePath)) {
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');
}
@ -195,7 +301,10 @@ export class VaultService {
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') };
}
@ -214,16 +323,32 @@ export class VaultService {
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;
}
panicLock(): void {
this.zeroizeMasterKey();
this.credentials.clear();
this.writeUnlocked = false;
this.autoInitializedEmpty = false;
this.setPanicLockMarker(true);
for (const listener of this.panicListeners) {
@ -236,7 +361,7 @@ export class VaultService {
}
rotateMasterKey(newMasterKeyInput?: string): { generatedKeyHex?: string } {
this.assertUnlocked();
this.assertWriteUnlocked();
const nextKey = newMasterKeyInput
? parseMasterKey(newMasterKeyInput)
: generateMasterKeyBuffer();
@ -250,6 +375,8 @@ export class VaultService {
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);
@ -258,7 +385,7 @@ export class VaultService {
}
listMetadata(): VaultCredentialMeta[] {
this.assertUnlocked();
this.assertRuntimeReady();
return [...this.credentials.values()].map((cred) => {
const meta: VaultCredentialMeta = {
id: cred.id,
@ -281,8 +408,14 @@ export class VaultService {
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.assertUnlocked();
this.assertWriteUnlocked();
const cred = this.credentials.get(id);
return cred ? structuredClone(cred) : undefined;
}
@ -292,7 +425,7 @@ export class VaultService {
}
exportAllCredentials(): Record<string, VaultCredential> {
this.assertUnlocked();
this.assertRuntimeReady();
const out: Record<string, VaultCredential> = {};
for (const [id, cred] of this.credentials.entries()) {
out[id] = structuredClone(cred);
@ -301,7 +434,8 @@ export class VaultService {
}
upsertCredential(input: VaultCredentialInput): VaultCredentialMeta {
this.assertUnlocked();
this.assertWriteUnlocked();
this.autoInitializedEmpty = false;
const now = new Date().toISOString();
const existing = this.credentials.get(input.id);
const candidate = VaultCredentialSchema.parse({
@ -325,7 +459,7 @@ export class VaultService {
}
deleteCredential(id: string): boolean {
this.assertUnlocked();
this.assertWriteUnlocked();
if (!this.credentials.has(id)) return false;
const nextMap = new Map(this.credentials);
@ -346,7 +480,8 @@ export class VaultService {
comment?: string;
passphrase?: string;
}): VaultCredentialMeta {
this.assertUnlocked();
this.assertWriteUnlocked();
this.autoInitializedEmpty = false;
const keyPair = options.passphrase
? ssh2.utils.generateKeyPairSync('ed25519', {
@ -373,12 +508,37 @@ export class VaultService {
});
}
private assertUnlocked(): void {
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);