// @vitest-environment node import { beforeEach, describe, expect, it, vi } from "vitest"; import { hashPassword, verifyPassword } from "better-auth/crypto"; import { bootstrapErrorMessage, bootstrapOwner, main } from "../../scripts/hf-bootstrap-owner.mjs"; const prisma = vi.hoisted(() => ({ create: vi.fn() })); vi.mock("../generated/prisma/index.js", () => ({ PrismaClient: prisma.create })); const env = { NODE_ENV: "production" as const, DATABASE_URL: "postgresql://test:test-only@localhost:5432/test", HF_ADMIN_EMAIL: "owner@example.com", HF_ADMIN_PASSWORD: "initial-test-password", }; type User = { id: string; email: string; name: string; is_admin: boolean }; type Account = { id: string; accountId: string; providerId: string; userId: string; password: string; createdAt: Date; updatedAt: Date; }; type Marker = { singleton: number; owner_id: string; email: string }; type State = { users: User[]; accounts: Account[]; markers: Marker[]; table: boolean }; function fakeDatabase(initial: Partial = {}) { const state: State = { users: [], accounts: [], markers: [], table: false, ...initial }; const operations: string[] = []; const tx = { $executeRaw: vi.fn(async (sql: TemplateStringsArray, ...values: string[]) => { expect(Array.isArray(sql.raw)).toBe(true); const text = sql.join("?").trim(); if (text.startsWith("CREATE TABLE IF NOT EXISTS public.hf_space_owner")) { operations.push("create-table"); expect(values).toEqual([]); expect(text).toContain("CHECK (singleton = 1)"); expect(text).toContain("REFERENCES public.users(id) ON DELETE RESTRICT"); state.table = true; } else if (text.startsWith("INSERT INTO public.hf_space_owner")) { operations.push("insert-marker"); expect(values).toHaveLength(2); if (state.markers.length) throw new Error("duplicate singleton"); state.markers.push({ singleton: 1, owner_id: values[0], email: values[1] }); } else { throw new Error("Unexpected SQL in test"); } return 1; }), $queryRaw: vi.fn(async (sql: TemplateStringsArray) => { operations.push("read-marker"); expect(sql.join("")).toContain("FROM public.hf_space_owner FOR UPDATE"); return structuredClone(state.markers); }), user: { findFirst: vi.fn(async ({ where }: { where: { email: { equals: string; mode: string } } }) => { operations.push("find-email"); expect(where.email.mode).toBe("insensitive"); return state.users.find((user) => user.email.toLowerCase() === where.email.equals) ?? null; }), findUnique: vi.fn(async ({ where }: { where: { id: string } }) => { operations.push("find-owner"); return state.users.find((user) => user.id === where.id) ?? null; }), create: vi.fn(async ({ data }: { data: Omit }) => { operations.push("create-user"); const user = { id: "created-owner", ...data }; state.users.push(user); return user; }), }, account: { create: vi.fn(async ({ data }: { data: Account }) => { operations.push("create-account"); state.accounts.push(data); return data; }), }, }; const db = { $connect: vi.fn(async () => {}), $disconnect: vi.fn(async () => {}), $transaction: vi.fn(async (callback: (transaction: typeof tx) => Promise) => { const snapshot = structuredClone(state); try { return await callback(tx); } catch (error) { Object.assign(state, snapshot); throw error; } }), }; return { db, tx, state, operations }; } const markedOwner: User = { id: "marked-owner", email: env.HF_ADMIN_EMAIL, name: "Owner", is_admin: true }; const marker: Marker = { singleton: 1, owner_id: markedOwner.id, email: markedOwner.email }; beforeEach(() => prisma.create.mockReset()); describe("HF deployment owner bootstrap", () => { it("creates the owner, Better Auth credential, and parameterized marker in one transaction", async () => { const { db, tx, state, operations } = fakeDatabase(); await expect(bootstrapOwner(db, { ...env, HF_ADMIN_EMAIL: " OWNER@Example.COM " })) .resolves.toEqual({ status: "created", ownerId: "created-owner" }); expect(db.$transaction).toHaveBeenCalledExactlyOnceWith(expect.any(Function), { isolationLevel: "Serializable", maxWait: 10000, timeout: 30000, }); expect(operations).toEqual(["create-table", "read-marker", "find-email", "create-user", "create-account", "insert-marker"]); expect(tx.user.create).toHaveBeenCalledWith({ data: { email: env.HF_ADMIN_EMAIL, name: "Space Owner", is_admin: true } }); expect(state.markers).toEqual([{ singleton: 1, owner_id: "created-owner", email: env.HF_ADMIN_EMAIL }]); expect(state.accounts).toHaveLength(1); const account = state.accounts[0]; expect(account).toMatchObject({ id: expect.any(String), userId: "created-owner", accountId: "created-owner", providerId: "credential", createdAt: expect.any(Date), updatedAt: expect.any(Date), }); expect(account.password).not.toBe(env.HF_ADMIN_PASSWORD); expect(await verifyPassword({ hash: account.password, password: env.HF_ADMIN_PASSWORD })).toBe(true); expect(await verifyPassword({ hash: account.password, password: "incorrect-password" })).toBe(false); expect(db.$connect).not.toHaveBeenCalled(); expect(db.$disconnect).not.toHaveBeenCalled(); }); it("never resets a credential after an in-app password change or HF secret change", async () => { const { db, tx, state } = fakeDatabase(); await bootstrapOwner(db, env); const originalHash = state.accounts[0].password; await bootstrapOwner(db, env); expect(state.accounts[0].password).toBe(originalHash); const changedPassword = "password-changed-in-app"; state.accounts[0].password = await hashPassword(changedPassword); const snapshot = structuredClone(state); await expect(bootstrapOwner(db, { ...env, HF_ADMIN_PASSWORD: "different-HF-secret" })) .resolves.toEqual({ status: "already-initialized", ownerId: "created-owner" }); expect(state).toEqual(snapshot); expect(tx.user.create).toHaveBeenCalledTimes(1); expect(tx.account.create).toHaveBeenCalledTimes(1); expect(tx.user.findFirst).toHaveBeenCalledTimes(1); expect(await verifyPassword({ hash: state.accounts[0].password, password: changedPassword })).toBe(true); expect(await verifyPassword({ hash: state.accounts[0].password, password: env.HF_ADMIN_PASSWORD })).toBe(false); }); it.each([false, true])("rejects any unmarked matching account, including existing admin=%s", async (isAdmin) => { const { db, state, tx } = fakeDatabase({ users: [{ ...markedOwner, email: "OWNER@EXAMPLE.COM", is_admin: isAdmin }] }); const snapshot = structuredClone(state); await expect(bootstrapOwner(db, env)).rejects.toThrow("unmarked account"); expect(state).toEqual(snapshot); expect(tx.user.create).not.toHaveBeenCalled(); expect(tx.account.create).not.toHaveBeenCalled(); }); it("rejects changing the configured owner even when the new email is unused", async () => { const { db, tx, state } = fakeDatabase({ users: [markedOwner], markers: [marker], table: true }); const snapshot = structuredClone(state); await expect(bootstrapOwner(db, { ...env, HF_ADMIN_EMAIL: "other@example.com" })).rejects.toThrow("differs from the initialized deployment owner"); expect(state).toEqual(snapshot); expect(tx.user.findFirst).not.toHaveBeenCalled(); expect(tx.user.create).not.toHaveBeenCalled(); }); it.each([ ["missing user", []], ["revoked admin", [{ ...markedOwner, is_admin: false }]], ["changed email", [{ ...markedOwner, email: "changed@example.com" }]], ["replaced ID", [{ ...markedOwner, id: "replacement-owner" }]], ] as const)("fails closed for a marked owner with %s", async (_label, users) => { const { db, state, tx } = fakeDatabase({ users: [...users], markers: [marker], table: true }); const snapshot = structuredClone(state); await expect(bootstrapOwner(db, env)).rejects.toThrow("refusing to repair privileges"); expect(state).toEqual(snapshot); expect(tx.account.create).not.toHaveBeenCalled(); }); it.each([ [{ ...marker, singleton: 2 }], [{ ...marker, owner_id: "" }], [marker, marker], ])("rejects a malformed deployment marker", async (...markers) => { const { db } = fakeDatabase({ markers, users: [markedOwner] }); await expect(bootstrapOwner(db, env)).rejects.toThrow("marker is invalid"); }); it.each([undefined, "", "plain-address", "a@@example.com", "a b@example.com", ".a@example.com", "a..b@example.com", "a@-example.com", "a@example..com", "a@example.com\nmalformed", "a#b@example.com", "a'@example.com"])("rejects malformed email without touching the database: %s", async (email) => { const { db } = fakeDatabase(); await expect(bootstrapOwner(db, { ...env, HF_ADMIN_EMAIL: email })).rejects.toThrow("HF_ADMIN_EMAIL must"); expect(db.$transaction).not.toHaveBeenCalled(); }); it.each([undefined, "", "12345678901", " ", "x".repeat(129)])("rejects missing/invalid password before database access", async (password) => { const { db } = fakeDatabase(); await expect(bootstrapOwner(db, { ...env, HF_ADMIN_PASSWORD: password })).rejects.toThrow("HF_ADMIN_PASSWORD must"); expect(db.$transaction).not.toHaveBeenCalled(); }); it("accepts a 12-character password without trimming it and binds apostrophes in email safely", async () => { const { db, tx, state } = fakeDatabase(); const password = " 1234567890 "; const email = "o'brien@example.com"; await bootstrapOwner(db, { ...env, HF_ADMIN_EMAIL: email, HF_ADMIN_PASSWORD: password }); expect(await verifyPassword({ hash: state.accounts[0].password, password })).toBe(true); const [sql, ...values] = tx.$executeRaw.mock.calls[1]; expect(sql.join("")).not.toContain(email); expect(values).toEqual(["created-owner", email]); }); it.each(["credential", "marker"])("rolls back all creation when %s insertion fails, with sanitized errors", async (failure) => { const { db, tx, state } = fakeDatabase(); const sensitiveError = new Error(`${env.DATABASE_URL} ${env.HF_ADMIN_PASSWORD}`); if (failure === "credential") tx.account.create.mockRejectedValueOnce(sensitiveError); else tx.$executeRaw.mockResolvedValueOnce(1).mockRejectedValueOnce(sensitiveError); await expect(bootstrapOwner(db, env)).rejects.toThrow("Details withheld"); expect(state).toEqual({ users: [], accounts: [], markers: [], table: false }); expect(bootstrapErrorMessage(sensitiveError)).not.toContain(env.DATABASE_URL); expect(bootstrapErrorMessage(sensitiveError)).not.toContain(env.HF_ADMIN_PASSWORD); }); }); describe("bootstrap main lifecycle", () => { it("loads Prisma only when main runs, connects, and always disconnects", async () => { const { db } = fakeDatabase({ users: [markedOwner], markers: [marker], table: true }); prisma.create.mockImplementation(function () { return db; }); expect(prisma.create).not.toHaveBeenCalled(); await expect(main(env)).resolves.toEqual({ status: "already-initialized", ownerId: markedOwner.id }); expect(prisma.create).toHaveBeenCalledWith({ datasourceUrl: env.DATABASE_URL, log: [] }); expect(db.$connect).toHaveBeenCalledOnce(); expect(db.$disconnect).toHaveBeenCalledOnce(); }); it.each(["connect", "transaction", "disconnect"])("sanitizes %s errors and disconnects", async (phase) => { const { db } = fakeDatabase({ users: [markedOwner], markers: [marker], table: true }); prisma.create.mockImplementation(function () { return db; }); db[`$${phase}` as "$connect" | "$transaction" | "$disconnect"].mockRejectedValueOnce(new Error(`${env.DATABASE_URL} ${env.HF_ADMIN_PASSWORD}`)); await expect(main(env)).rejects.toThrow(bootstrapErrorMessage(new Error())); expect(db.$disconnect).toHaveBeenCalledOnce(); }); it.each([undefined, "", "postgresql+asyncpg://test:test@localhost/db", "not-a-url", "postgresql://localhost", "https://localhost/db"])("rejects invalid database URLs before creating a client", async (url) => { await expect(main({ ...env, DATABASE_URL: url })).rejects.toThrow("DATABASE_URL must"); expect(prisma.create).not.toHaveBeenCalled(); }); it("requires explicit production mode", async () => { await expect(main({ ...env, NODE_ENV: "development" })).rejects.toThrow("NODE_ENV=production"); expect(prisma.create).not.toHaveBeenCalled(); }); }); it("the CLI catches unexpected errors without printing credentials and sets a failing exit code", async () => { const previousExitCode = process.exitCode; const errorLog = vi.spyOn(console, "error").mockImplementation(() => {}); vi.doMock("../../scripts/hf-bootstrap-owner.mjs", () => ({ main: vi.fn().mockRejectedValue(new Error(`${env.DATABASE_URL} ${env.HF_ADMIN_PASSWORD}`)), bootstrapErrorMessage, })); try { await import("../../scripts/hf-bootstrap-owner-cli.mjs"); await vi.waitFor(() => expect(errorLog).toHaveBeenCalledExactlyOnceWith(bootstrapErrorMessage(new Error()))); expect(process.exitCode).toBe(1); } finally { process.exitCode = previousExitCode; errorLog.mockRestore(); vi.doUnmock("../../scripts/hf-bootstrap-owner.mjs"); } });