Repository Public
1import { mkdirSync, writeFileSync } from "node:fs";2import path from "node:path";3import "./_env";4import { sql } from "../src/lib/db";5import { env } from "../src/lib/env";6import { issueSetupToken, passkeyCount } from "../src/lib/auth";7import { storage } from "../src/server/storage";89/**10 * Idempotent first-run setup, run at every deployment.11 * - creates the owner account (administrator) from OWNER_EMAIL / OWNER_NAME — the only account ever created12 * outside the admin panel; there is no default password and no public sign-up;13 * - while the owner has no passkey, issues a one-time enrolment link (24 h) written to SETUP_URL_FILE (mode 0600),14 * never to the logs. Once a passkey exists this script issues nothing: setup mode is closed.15 */16async function main() {17 const st = await storage().health();18 if (!st.ok) throw new Error(`STORAGE_ROOT is not usable (${st.detail})`);19 let [u] = await sql<{ id: string }[]>`SELECT id FROM users WHERE is_owner`;20 if (!u) {21 const email = env.ownerEmail;22 if (!email) throw new Error("OWNER_EMAIL is required to create the owner account");23 [u] = await sql<{ id: string }[]>`INSERT INTO users (email, display_name, role, is_owner) VALUES (${email}, ${env.ownerName}, 'admin', true) RETURNING id`;24 console.log(" owner account created");25 }26 if ((await passkeyCount(u.id)) === 0) {27 const file = process.env.SETUP_URL_FILE;28 const token = await issueSetupToken(u.id, "setup", 24 * 60);29 const url = `${env.appUrl}/setup#${token}`;30 if (file) { mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); writeFileSync(file, url + "\n", { mode: 0o600 }); console.log(` owner has no passkey: one-time enrolment link written to ${file} (valid 24 h)`); }31 else if (process.stdout.isTTY) console.log(` owner has no passkey: one-time enrolment link (valid 24 h):\n ${url}`);32 else throw new Error("Owner has no passkey and SETUP_URL_FILE is not set: refusing to print the enrolment link to a log");33 } else console.log(" owner passkey present: setup mode closed");34 await sql.end();35}36main().catch((e) => { console.error(e.message); process.exit(1); });37