Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/database/db.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *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: support@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 { DatabaseSync } from "node:sqlite";44import { mkdirSync } from "node:fs";45import { join } from "node:path";46import { env } from "../env";4748/**49 * One SQLite file (WAL) under ORIX_DATA_DIR. The catalog is small and read-mostly: synchronous queries from50 * node:sqlite answer in microseconds and need no connection pool, no ORM and no native add-on.51 */52const MIGRATIONS: string[] = [53 `CREATE TABLE apps (54 slug TEXT PRIMARY KEY, publish TEXT NOT NULL DEFAULT 'draft' CHECK (publish IN ('draft','published','archived')),55 data TEXT NOT NULL, draft TEXT, sort INTEGER NOT NULL DEFAULT 0,56 updated_at TEXT NOT NULL, published_at TEXT);57 CREATE TABLE releases (58 id INTEGER PRIMARY KEY, slug TEXT NOT NULL, source TEXT NOT NULL DEFAULT 'spbgit', repo TEXT, tag TEXT NOT NULL,59 version TEXT, prerelease INTEGER NOT NULL DEFAULT 0, tag_date TEXT, subject TEXT,60 asset_name TEXT NOT NULL DEFAULT '', asset_size INTEGER, sha256_declared TEXT, sha256_computed TEXT, source_url TEXT,61 state TEXT NOT NULL CHECK (state IN ('note','discovered','validated','invalid','held','published','withdrawn')),62 reason TEXT, signature TEXT, artifact TEXT, notes TEXT,63 discovered_at TEXT NOT NULL, checked_at TEXT, approved_at TEXT, approved_by TEXT, published_at TEXT,64 UNIQUE (slug, tag, asset_name));65 CREATE TABLE repo_meta (slug TEXT PRIMARY KEY, json TEXT NOT NULL, fetched_at TEXT NOT NULL);66 CREATE TABLE sync_runs (id INTEGER PRIMARY KEY, started_at TEXT NOT NULL, finished_at TEXT, trigger TEXT NOT NULL, ok INTEGER, summary TEXT, error TEXT);67 CREATE TABLE announcements (68 id INTEGER PRIMARY KEY, kind TEXT NOT NULL, app_slug TEXT, date TEXT NOT NULL,69 publish TEXT NOT NULL DEFAULT 'draft' CHECK (publish IN ('draft','published','archived')),70 title_en TEXT NOT NULL, title_fr TEXT NOT NULL, body_en TEXT NOT NULL, body_fr TEXT NOT NULL,71 created_at TEXT NOT NULL, updated_at TEXT NOT NULL);72 CREATE TABLE admins (id TEXT PRIMARY KEY, name TEXT NOT NULL, created_at TEXT NOT NULL);73 CREATE TABLE credentials (74 id TEXT PRIMARY KEY, admin_id TEXT NOT NULL REFERENCES admins(id), public_key BLOB NOT NULL, counter INTEGER NOT NULL,75 transports TEXT NOT NULL, name TEXT NOT NULL, device_type TEXT, backed_up INTEGER, created_at TEXT NOT NULL, last_used_at TEXT);76 CREATE TABLE sessions (77 token_hash TEXT PRIMARY KEY, admin_id TEXT NOT NULL REFERENCES admins(id), csrf TEXT NOT NULL,78 created_at TEXT NOT NULL, expires_at TEXT NOT NULL, last_seen_at TEXT NOT NULL, ip TEXT, ua TEXT);79 CREATE TABLE enroll_tokens (token_hash TEXT PRIMARY KEY, purpose TEXT NOT NULL, created_at TEXT NOT NULL, expires_at TEXT NOT NULL, used_at TEXT);80 CREATE TABLE challenges (id TEXT PRIMARY KEY, challenge TEXT NOT NULL, kind TEXT NOT NULL, binding TEXT NOT NULL, expires_at TEXT NOT NULL);81 CREATE TABLE audit (id INTEGER PRIMARY KEY, at TEXT NOT NULL, actor TEXT NOT NULL, action TEXT NOT NULL, detail TEXT, ip TEXT);82 CREATE INDEX audit_action ON audit (action, at);83 CREATE TABLE downloads (day TEXT NOT NULL, slug TEXT NOT NULL, version TEXT NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('click','request','completed')), n INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day, slug, version, kind));84 CREATE TABLE webhook_nonces (nonce TEXT PRIMARY KEY, at TEXT NOT NULL);85 CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);`,86];8788type G = typeof globalThis & { __orixDb?: { path: string; db: DatabaseSync } };8990function open(path: string): DatabaseSync {91 const db = new DatabaseSync(path);92 db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000; PRAGMA synchronous = NORMAL;");93 db.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER NOT NULL)");94 const cur = (db.prepare("SELECT max(v) AS v FROM schema_version").get() as { v: number | null }).v ?? 0;95 for (let i = cur; i < MIGRATIONS.length; i++) {96 db.exec("BEGIN");97 try { db.exec(MIGRATIONS[i]); db.prepare("INSERT INTO schema_version (v) VALUES (?)").run(i + 1); db.exec("COMMIT"); }98 catch (err) { db.exec("ROLLBACK"); throw err; }99 }100 return db;101}102103/** The process-wide handle (re-opened if ORIX_DATA_DIR changes, which only tests do). */104export function db(): DatabaseSync {105 const g = globalThis as G;106 const path = env.dataDir === ":memory:" ? ":memory:" : join(env.dataDir, "orix.db");107 if (g.__orixDb?.path !== path || path === ":memory:" && !g.__orixDb) {108 if (path !== ":memory:") mkdirSync(env.dataDir, { recursive: true, mode: 0o700 });109 g.__orixDb = { path, db: open(path) };110 }111 return g.__orixDb!.db;112}113114export function closeDb(): void {115 const g = globalThis as G;116 g.__orixDb?.db.close();117 g.__orixDb = undefined;118}119120export const now = () => new Date().toISOString();121122export function tx<T>(fn: () => T): T {123 const d = db();124 d.exec("BEGIN IMMEDIATE");125 try { const r = fn(); d.exec("COMMIT"); return r; }126 catch (e) { d.exec("ROLLBACK"); throw e; }127}128129export function getSetting(key: string): string | null {130 return (db().prepare("SELECT value FROM settings WHERE key = ?").get(key) as { value: string } | undefined)?.value ?? null;131}132export function setSetting(key: string, value: string): void {133 db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(key, value);134}135