import { eq, sql } from 'drizzle-orm'; import { authDb } from './auth-transaction.ts'; import { DATABASE_FILE, MIGRATIONS_FOLDER, db, tables } from './db/index.ts'; import { readDbState, type DbState } from '../../../scripts/db-state.mjs'; import { BUILD } from './version.ts'; export type InstanceSettings = { name: string; signupOpen: boolean; preserveOriginals: boolean; /** Days of recovery history kept. Zero keeps everything. */ historyRetentionDays: number; }; /** * Reads the one settings row, creating it on first boot: every request goes * through here, so the row exists by the time anything asks. */ export function getInstance(): InstanceSettings { const existing = db .select() .from(tables.instanceSetting) .where(eq(tables.instanceSetting.id, 1)) .get(); if (existing) { return { name: existing.name, signupOpen: existing.signupOpen, preserveOriginals: existing.preserveOriginals, historyRetentionDays: existing.historyRetentionDays }; } const created = db.insert(tables.instanceSetting).values({ id: 1 }).returning().get(); return { name: created.name, signupOpen: created.signupOpen, preserveOriginals: created.preserveOriginals, historyRetentionDays: created.historyRetentionDays }; } export function updateInstance( patch: Partial< Pick > ) { db.transaction((tx) => { tx.insert(tables.instanceSetting).values({ id: 1 }).onConflictDoNothing().run(); tx.update(tables.instanceSetting) .set({ ...patch, updatedAt: new Date() }) .where(eq(tables.instanceSetting.id, 1)) .run(); }); return getInstance(); } export function countAccounts(): number { const row = authDb .select({ n: sql`count(*)` }) .from(tables.user) .get(); return row?.n ?? 0; } /** * True while no account exists: the first account to sign up becomes the admin, * which makes a fresh instance claimable by whoever installs it. */ export function isFirstAccount(): boolean { return countAccounts() === 0; } export function signupAllowed(): boolean { return isFirstAccount() || getInstance().signupOpen; } /** * Records the build that opened the database, so a rollback can name the build * that wrote the shape it reads. It runs at boot, before anything has created the * instance row, hence the insert first. */ export function stampOpenedVersion(): void { db.transaction((tx) => { tx.insert(tables.instanceSetting).values({ id: 1 }).onConflictDoNothing().run(); tx.update(tables.instanceSetting) .set({ lastVersion: BUILD.version, lastOpenedAt: new Date() }) .where(eq(tables.instanceSetting.id, 1)) .run(); }); } /** * The migration level and the build that last opened the database. The admin page * reports it, and `server.js` refuses to start a build older than the database, * reading the same module. */ export function readDatabaseState(): DbState { return readDbState({ databasePath: DATABASE_FILE, migrationsFolder: MIGRATIONS_FOLDER }); }