SPB Git

Repository Public

bootstrap.ts 4.1 KB 81 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Sheet8 * File             : scripts/bootstrap.ts9 * Module           : scripts10 * Repository       : https://git.spboucher.ai/sheet11 * Project Website  : https://sheet.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { mkdirSync, writeFileSync } from "node:fs";44import path from "node:path";45import "./_env";46import { sql } from "../src/lib/db";47import { env } from "../src/lib/env";48import { issueSetupToken, passkeyCount } from "../src/lib/auth";49import { storage } from "../src/server/storage";5051/**52 * Idempotent first-run setup, run at every deployment.53 *  - creates the single administrator from ADMIN_EMAIL / ADMIN_NAME (no password exists anywhere; no sign-up route);54 *  - while the administrator has no passkey, issues a one-time enrolment link (24 h) written to SETUP_URL_FILE55 *    (mode 0600) — never to a log. Once a passkey exists this script issues nothing: bootstrap is closed for good,56 *    and only `scripts/setup-token.ts` run by someone with shell access can open a recovery.57 */58async function main() {59  const st = await storage().health();60  if (!st.ok) throw new Error(`STORAGE_ROOT is not usable (${st.detail})`);61  let [u] = await sql<{ id: string }[]>`SELECT id FROM users ORDER BY created_at LIMIT 1`;62  if (!u) {63    const email = env.adminEmail;64    if (!email) throw new Error("ADMIN_EMAIL is required to create the administrator");65    [u] = await sql<{ id: string }[]>`INSERT INTO users (email, display_name) VALUES (${email}, ${env.adminName}) RETURNING id`;66    console.log("  administrator created");67  }68  if ((await passkeyCount(u.id)) === 0) {69    const [pending] = await sql`SELECT 1 FROM setup_tokens WHERE user_id = ${u.id} AND used_at IS NULL AND expires_at > now() + interval '1 hour'`;70    if (pending && !process.argv.includes("--renew")) { console.log("  administrator has no passkey: an enrolment link is already waiting (SETUP_URL_FILE); --renew issues a new one"); await sql.end(); return; }71    const file = process.env.SETUP_URL_FILE;72    const token = await issueSetupToken(u.id, "setup", 24 * 60);73    const url = `${env.appUrl}/admin/setup#${token}`;74    if (file) { mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); writeFileSync(file, url + "\n", { mode: 0o600 }); console.log(`  administrator has no passkey: one-time enrolment link written to ${file} (valid 24 h)`); }75    else if (process.stdout.isTTY) console.log(`  administrator has no passkey: one-time enrolment link (valid 24 h):\n  ${url}`);76    else throw new Error("The administrator has no passkey and SETUP_URL_FILE is not set: refusing to print the enrolment link to a log");77  } else console.log("  administrator passkey present: bootstrap closed");78  await sql.end();79}80main().catch((e) => { console.error(e.message); process.exit(1); });81
Files main
Menu

Theme