import { randomUUID } from "node:crypto"; import { hashPassword } from "better-auth/crypto"; class OwnerBootstrapError extends Error {} export function bootstrapErrorMessage(error) { // Never expose Prisma diagnostics, connection strings, or supplied credentials. return error instanceof OwnerBootstrapError ? error.message : "Owner bootstrap failed; check database availability and schema. Details withheld."; } function ownerCredentials(env) { const email = typeof env.HF_ADMIN_EMAIL === "string" ? env.HF_ADMIN_EMAIL.trim().toLowerCase() : ""; const [local, domain, extra] = email.split("@"); if ( !local || !domain || extra !== undefined || email.length > 254 || local.length > 64 || !/^[a-z0-9.'+_-]+$/.test(local) || !/[a-z0-9_+-]$/.test(local) || local.startsWith(".") || local.endsWith(".") || local.includes("..") || !domain.includes(".") || !domain.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) || !/^[a-z]{2,63}$/.test(domain.split(".").at(-1)) ) { throw new OwnerBootstrapError("HF_ADMIN_EMAIL must be a valid email address."); } const password = env.HF_ADMIN_PASSWORD; // Better Auth's default maximum is 128. Preserve whitespace in valid passwords. if (typeof password !== "string" || password.length < 12 || password.length > 128 || !password.trim()) { throw new OwnerBootstrapError("HF_ADMIN_PASSWORD must contain 12 to 128 characters and cannot be blank."); } return { email, password }; } export async function bootstrapOwner(db, env) { const { email, password } = ownerCredentials(env); try { return await db.$transaction(async (tx) => { // Deployment-only state, deliberately outside the application's Prisma schema. await tx.$executeRaw` CREATE TABLE IF NOT EXISTS public.hf_space_owner ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), owner_id TEXT NOT NULL UNIQUE REFERENCES public.users(id) ON DELETE RESTRICT, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP ) `; const markers = await tx.$queryRaw` SELECT singleton, owner_id, email FROM public.hf_space_owner FOR UPDATE `; if (markers.length) { const marker = markers[0]; if (markers.length !== 1 || marker.singleton !== 1 || !marker.owner_id || !marker.email) { throw new OwnerBootstrapError("The deployment owner marker is invalid; refusing to change accounts."); } if (marker.email !== email) { throw new OwnerBootstrapError("HF_ADMIN_EMAIL differs from the initialized deployment owner; refusing to change owners."); } const owner = await tx.user.findUnique({ where: { id: marker.owner_id }, select: { id: true, email: true, is_admin: true }, }); if (!owner || owner.id !== marker.owner_id || owner.email !== marker.email || owner.is_admin !== true) { throw new OwnerBootstrapError("The marked owner is missing, has changed identity, or is not an admin; refusing to repair privileges."); } // The secret is initialization-only: in-app password changes survive restarts. return { status: "already-initialized", ownerId: owner.id }; } const existing = await tx.user.findFirst({ where: { email: { equals: email, mode: "insensitive" } }, select: { id: true }, }); if (existing) { throw new OwnerBootstrapError("HF_ADMIN_EMAIL already belongs to an unmarked account; refusing to promote or reset it."); } const passwordHash = await hashPassword(password); const owner = await tx.user.create({ data: { email, name: "Space Owner", is_admin: true }, }); const now = new Date(); await tx.account.create({ data: { id: randomUUID(), accountId: owner.id, providerId: "credential", userId: owner.id, password: passwordHash, createdAt: now, updatedAt: now, }, }); await tx.$executeRaw` INSERT INTO public.hf_space_owner (singleton, owner_id, email) VALUES (1, ${owner.id}, ${email}) `; return { status: "created", ownerId: owner.id }; }, { isolationLevel: "Serializable", maxWait: 10000, timeout: 30000 }); } catch (error) { throw new OwnerBootstrapError(bootstrapErrorMessage(error)); } } export async function main(env = process.env) { try { ownerCredentials(env); if (env.NODE_ENV !== "production") { throw new OwnerBootstrapError("Owner bootstrap requires NODE_ENV=production."); } let url; try { url = new URL(env.DATABASE_URL); } catch { // URL parser errors may include the original connection string. } if (!url || url.protocol !== "postgresql:" || !url.hostname || url.pathname.length < 2 || url.hash) { throw new OwnerBootstrapError("DATABASE_URL must be a standard postgresql:// connection URL with a database name."); } // Keep this relative import external when bundling the CLI into scripts/*.cjs. const { PrismaClient } = await import("../src/generated/prisma/index.js"); const db = new PrismaClient({ datasourceUrl: env.DATABASE_URL, log: [] }); try { await db.$connect(); return await bootstrapOwner(db, env); } finally { await db.$disconnect(); } } catch (error) { throw new OwnerBootstrapError(bootstrapErrorMessage(error)); } }