import { mkdtempSync, readFileSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("server-only", () => ({})); describe("setup code", () => { let dir: string; beforeEach(() => { dir = mkdtempSync(path.join(tmpdir(), "lunch-")); process.env.APP_DATA_DIR = dir; }); it("is written once, readable only by the app, and matches however it is typed", async () => { const { ensureSetupCode, setupCodeMatches, removeSetupCode, SETUP_FILE } = await import("@/lib/auth/codes"); await ensureSetupCode(); const file = path.join(dir, SETUP_FILE); const first = readFileSync(file, "utf8"); await ensureSetupCode(); expect(readFileSync(file, "utf8")).toBe(first); expect(statSync(file).mode & 0o777).toBe(0o600); const code = first.split("\n").find((l) => /^[A-Z2-9]{4}(-[A-Z2-9]{4}){3}$/.test(l))!; expect(await setupCodeMatches(code)).toBe(true); expect(await setupCodeMatches(code.toLowerCase().replace(/-/g, " "))).toBe(true); expect(await setupCodeMatches(code.slice(0, -1) + (code.endsWith("A") ? "B" : "A"))).toBe(false); expect(await setupCodeMatches("")).toBe(false); await removeSetupCode(); expect(await setupCodeMatches(code)).toBe(false); }); });