示例工程 39-secrets-safestorage
39-secrets-safestorage/app/shared/vault.ts
import fs from "node:fs";
import path from "node:path";
import type { EncryptedValue } from "./crypto";
export type VaultSecret = {
id: string;
name: string;
createdAt: string;
updatedAt: string;
value: EncryptedValue;
};
export type VaultDoc = {
version: 1;
keyId: number;
wrappedKey: string;
secrets: VaultSecret[];
};
export function vaultFile(dir: string): string {
return path.join(dir, "vault.json");
}
export function isVaultDoc(value: unknown): value is VaultDoc {
if (typeof value !== "object" || value === null) return false;
const doc = value as {
version?: unknown;
keyId?: unknown;
wrappedKey?: unknown;
secrets?: unknown;
};
if (
doc.version !== 1 ||
typeof doc.keyId !== "number" ||
!Number.isInteger(doc.keyId) ||
doc.keyId < 1 ||
typeof doc.wrappedKey !== "string" ||
!Array.isArray(doc.secrets) ||
doc.secrets.length > 1000
) {
return false;
}
return doc.secrets.every((item) => {
if (typeof item !== "object" || item === null) return false;
const secret = item as Record<string, unknown>;
const value = secret.value as Record<string, unknown> | undefined;
return (
typeof secret.id === "string" &&
typeof secret.name === "string" &&
typeof secret.createdAt === "string" &&
typeof secret.updatedAt === "string" &&
typeof value === "object" &&
value !== null &&
typeof value.ciphertext === "string" &&
typeof value.iv === "string" &&
typeof value.tag === "string"
);
});
}
export function saveVault(dir: string, doc: VaultDoc): number {
fs.mkdirSync(dir, { recursive: true });
const file = vaultFile(dir);
const text = `${JSON.stringify(doc, null, 2)}\n`;
const tmp = path.join(dir, `.vault.json.tmp-${process.pid}-${Date.now()}`);
const fd = fs.openSync(tmp, "w", 0o600);
try {
fs.writeFileSync(fd, text, "utf8");
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
if (fs.existsSync(file)) fs.copyFileSync(file, `${file}.bak`);
fs.renameSync(tmp, file);
return Buffer.byteLength(text, "utf8");
}
export function loadVault(dir: string): {
doc: VaultDoc | null;
error: string;
bytes: number;
} {
const file = vaultFile(dir);
try {
const text = fs.readFileSync(file, "utf8");
const parsed: unknown = JSON.parse(text);
if (!isVaultDoc(parsed)) {
return { doc: null, error: "INVALID_VAULT_SHAPE", bytes: text.length };
}
return { doc: parsed, error: "", bytes: Buffer.byteLength(text) };
} catch (error) {
return {
doc: null,
error: error instanceof Error ? error.message : String(error),
bytes: 0,
};
}
}
export function vaultReadableText(dir: string): string {
try {
return fs.readFileSync(vaultFile(dir), "utf8");
} catch {
return "";
}
}