feat(backup,cli): add AES-256-GCM .gcoord.enc backup, verify, restore CLI and API

This commit is contained in:
tyuXX 2026-11-27 14:23:22 +00:00
parent 413053182b
commit fbc1eb94e0
7 changed files with 1155 additions and 19 deletions

View file

@ -12,7 +12,7 @@ import {
} from '../../shared/schemas/vault.schema.js';
import type { VaultState } from '../../shared/ws-protocol.js';
const VaultEnvelopeSchema = z.object({
export const VaultEnvelopeSchema = z.object({
version: z.literal(1),
alg: z.literal('aes-256-gcm'),
iv: z.string().min(1),
@ -21,7 +21,7 @@ const VaultEnvelopeSchema = z.object({
updatedAt: z.string(),
});
type VaultEnvelope = z.infer<typeof VaultEnvelopeSchema>;
export type VaultEnvelope = z.infer<typeof VaultEnvelopeSchema>;
export function parseMasterKey(raw: string): Buffer {
const trimmed = raw.trim();
@ -77,6 +77,37 @@ function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload {
}
}
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) {
@ -375,6 +406,40 @@ export class VaultService {
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();