72 lines
2.8 KiB
TypeScript
72 lines
2.8 KiB
TypeScript
import "server-only";
|
|
import { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
// Tresor für Geheimnisse in der Datenbank (Muster Rocket, tresor.key):
|
|
// AES-256-GCM, der Schlüssel liegt als Datei unter /app/data und überlebt so
|
|
// eine Deinstallation. **Abzug und tresor.key gehören zusammen** — wer nur
|
|
// die Sicherung hat, hat die Geheimnisse nicht.
|
|
|
|
const VERSION = 1;
|
|
let cached: Buffer | null = null;
|
|
|
|
function keyPath(): string {
|
|
return path.join(process.env.APP_DATA_DIR ?? path.join(process.cwd(), ".data"), "tresor.key");
|
|
}
|
|
|
|
async function key(): Promise<Buffer> {
|
|
if (cached) return cached;
|
|
const file = keyPath();
|
|
try {
|
|
const k = await readFile(file);
|
|
if (k.length !== 32) throw new Error("tresor.key hat nicht 32 Byte");
|
|
cached = k;
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
await mkdir(path.dirname(file), { recursive: true });
|
|
const k = randomBytes(32);
|
|
await writeFile(file, k, { mode: 0o600, flag: "wx" }).catch(async (e) => {
|
|
if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
|
|
});
|
|
await chmod(file, 0o600).catch(() => {});
|
|
cached = await readFile(file);
|
|
}
|
|
return cached!;
|
|
}
|
|
|
|
/** Text verschlüsseln: Version (1) · Nonce (12) · Tag (16) · Geheimtext. */
|
|
export async function seal(text: string): Promise<Buffer> {
|
|
const nonce = randomBytes(12);
|
|
const cipher = createCipheriv("aes-256-gcm", await key(), nonce);
|
|
const body = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]);
|
|
return Buffer.concat([Buffer.from([VERSION]), nonce, cipher.getAuthTag(), body]);
|
|
}
|
|
|
|
/** Entschlüsseln; wirft bei falschem Schlüssel oder veränderten Daten. */
|
|
export async function unseal(data: Buffer): Promise<string> {
|
|
if (data[0] !== VERSION || data.length < 29) throw new Error("vault: unknown format");
|
|
const decipher = createDecipheriv("aes-256-gcm", await key(), data.subarray(1, 13));
|
|
decipher.setAuthTag(data.subarray(13, 29));
|
|
return Buffer.concat([decipher.update(data.subarray(29)), decipher.final()]).toString("utf8");
|
|
}
|
|
|
|
/**
|
|
* Prüfsumme über einen Text mit dem Tresor-Schlüssel (26.11.53): für Links, die
|
|
* dauerhaft gelten und nichts speichern müssen, etwa „Mails abbestellen“.
|
|
*/
|
|
export async function mac(text: string): Promise<string> {
|
|
return createHmac("sha256", await key()).update(text, "utf8").digest("base64url");
|
|
}
|
|
|
|
export async function macOk(text: string, given: string): Promise<boolean> {
|
|
const want = Buffer.from(await mac(text));
|
|
const got = Buffer.from(given);
|
|
return want.length === got.length && timingSafeEqual(want, got);
|
|
}
|
|
|
|
/** Nur für Tests: Schlüssel neu lesen. */
|
|
export function forgetKeyForTests() {
|
|
cached = null;
|
|
}
|