import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { canEncrypt, decryptSecret, encryptSecret } from "../lib/settings-crypto"; import { validateIntegrationSection } from "../lib/integration-settings"; const ORIGINAL = process.env.SETTINGS_ENCRYPTION_KEY; beforeEach(() => { process.env.SETTINGS_ENCRYPTION_KEY = "test-schluessel-mindestens-32-zeichen-lang!"; }); afterEach(() => { if (ORIGINAL === undefined) delete process.env.SETTINGS_ENCRYPTION_KEY; else process.env.SETTINGS_ENCRYPTION_KEY = ORIGINAL; }); describe("settings-crypto", () => { it("roundtrip: entschlüsseln liefert Klartext", () => { const enc = encryptSecret("smtp-geheim"); expect(enc.startsWith("gcm1:")).toBe(true); expect(decryptSecret(enc)).toBe("smtp-geheim"); }); it("gleicher Klartext ergibt verschiedene Chiffre (Zufalls-IV)", () => { expect(encryptSecret("x")).not.toBe(encryptSecret("x")); }); it("manipulierter Wert wird abgelehnt", () => { const enc = encryptSecret("wichtig"); const tampered = enc.slice(0, -2) + (enc.endsWith("AA") ? "BB" : "AA"); expect(() => decryptSecret(tampered)).toThrow(); expect(() => decryptSecret("klartext")).toThrow(); }); it("ohne/zu kurzem Key kein Verschlüsseln", () => { delete process.env.SETTINGS_ENCRYPTION_KEY; expect(canEncrypt()).toBe(false); expect(() => encryptSecret("x")).toThrow("SETTINGS_ENCRYPTION_KEY"); process.env.SETTINGS_ENCRYPTION_KEY = "kurz"; expect(canEncrypt()).toBe(false); }); }); describe("validateIntegrationSection", () => { it("unbekannte Bereiche ablehnen", () => { expect(validateIntegrationSection("login", {})).toEqual(["section"]); }); it("gültige SMTP-Werte bestehen", () => { expect(validateIntegrationSection("smtp", { smtp_host: "mail.de", smtp_port: "587", smtp_pass: "" })).toEqual([]); }); it("ungültiger Port und Typen ablehnen", () => { expect(validateIntegrationSection("smtp", { smtp_port: "abc" })).toEqual(["smtp_port"]); expect(validateIntegrationSection("smtp", { smtp_host: 5 })).toEqual(["smtp_host"]); }); it("leeres Geheimnis-Feld ist ok (behält bestehenden Wert)", () => { expect(validateIntegrationSection("telegram", { telegram_bot_token: "" })).toEqual([]); expect(validateIntegrationSection("logo", { logo_dev_secret_key: "sk_x", logo_dev_publishable_key: "pk_x" })).toEqual([]); }); });