import { Database } from "bun:sqlite"; import { mkdirSync } from "node:fs"; import { join } from "node:path"; // §19: only what the pages, the sync loop and issues use so far; later phases add their tables. const SCHEMA = ` CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS repos ( name TEXT PRIMARY KEY, public INTEGER NOT NULL DEFAULT 0, category TEXT NOT NULL DEFAULT '', homepage TEXT NOT NULL DEFAULT '', languages TEXT NOT NULL DEFAULT '', issues_paused INTEGER NOT NULL DEFAULT 0, hidden_paths TEXT NOT NULL DEFAULT '', last_sync_at INTEGER, last_sync_error TEXT ); -- §24: the admin console hides a version or replaces its notes; NULL notes keep the record's. CREATE TABLE IF NOT EXISTS release_settings ( repo TEXT NOT NULL, version TEXT NOT NULL, hidden INTEGER NOT NULL DEFAULT 0, notes TEXT, PRIMARY KEY (repo, version) ); -- §22.2: one count per release file; installs are Nix tarball fetches, per repo. CREATE TABLE IF NOT EXISTS downloads ( repo TEXT NOT NULL, version TEXT NOT NULL, platform TEXT NOT NULL, count INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (repo, version, platform) ); CREATE TABLE IF NOT EXISTS installs ( repo TEXT PRIMARY KEY, count INTEGER NOT NULL DEFAULT 0 ); -- §23. Numbers are per repo and set explicitly, so Kepr 2's carry over on import. The contact -- email is the operator's alone; token_hash is the follow-up link's SHA-256 (NULL for imports). CREATE TABLE IF NOT EXISTS issues ( id INTEGER PRIMARY KEY, repo TEXT NOT NULL, number INTEGER NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, type TEXT NOT NULL CHECK (type IN ('bug', 'idea', 'question')), version TEXT NOT NULL DEFAULT '', reporter_name TEXT NOT NULL DEFAULT '', contact_email TEXT NOT NULL DEFAULT '', filed_at INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')), closed_at INTEGER, fixed_in TEXT NOT NULL DEFAULT '', hidden INTEGER NOT NULL DEFAULT 0, ip_hash TEXT NOT NULL DEFAULT '', token_hash TEXT, UNIQUE (repo, number) ); CREATE INDEX IF NOT EXISTS issues_ip ON issues (ip_hash, filed_at); -- The thread after the first post: the reporter's follow-ups and the operator's replies. CREATE TABLE IF NOT EXISTS issue_entries ( id INTEGER PRIMARY KEY, issue_id INTEGER NOT NULL REFERENCES issues (id), author TEXT NOT NULL CHECK (author IN ('reporter', 'operator')), body TEXT NOT NULL, created_at INTEGER NOT NULL, hidden INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS issue_entries_issue ON issue_entries (issue_id, id); -- §24: admin sessions, revocable; only the SHA-256 of the cookie's token is kept. CREATE TABLE IF NOT EXISTS sessions ( token_hash TEXT PRIMARY KEY, expires_at INTEGER NOT NULL ); -- June's own words for a repo, edited on its page when signed in; '' falls back to the README. CREATE TABLE IF NOT EXISTS repo_text ( repo TEXT PRIMARY KEY, description TEXT NOT NULL DEFAULT '', details TEXT NOT NULL DEFAULT '' ); CREATE TABLE IF NOT EXISTS connect_codes ( code_hash TEXT PRIMARY KEY, machine TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, used_at INTEGER ); -- §24: what Kepr tells the operator in the console, newest 200 kept. CREATE TABLE IF NOT EXISTS notifications ( id INTEGER PRIMARY KEY, kind TEXT NOT NULL, text TEXT NOT NULL, href TEXT NOT NULL, created_at INTEGER NOT NULL, read INTEGER NOT NULL DEFAULT 0 ); -- §24: notifications on their way to the operator's inbox; the address is kepr.toml's. CREATE TABLE IF NOT EXISTS email_queue ( id INTEGER PRIMARY KEY, subject TEXT NOT NULL, href TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'waiting' CHECK (status IN ('waiting', 'sent', 'failed')), attempts INTEGER NOT NULL DEFAULT 0, next_at INTEGER NOT NULL, last_error TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, sent_at INTEGER ); `; /** What raises a notification (§24); each can be switched off. */ export const NOTIFICATION_KINDS = [ "issue_filed", "issue_followup", "sync_failed", "backup_failed", ] as const; export type NotificationKind = (typeof NOTIFICATION_KINDS)[number]; const NOTIFICATIONS_KEPT = 200; // Columns added after the first kepr.db was made; SQLite has no ADD COLUMN IF NOT EXISTS. const ADDED_COLUMNS: [table: string, column: string, definition: string][] = [ ["repos", "languages", "TEXT NOT NULL DEFAULT ''"], ["repos", "issues_paused", "INTEGER NOT NULL DEFAULT 0"], ["issue_entries", "hidden", "INTEGER NOT NULL DEFAULT 0"], ["repos", "hidden_paths", "TEXT NOT NULL DEFAULT ''"], ]; // Columns an older kepr.db still has; card order and install lines were removed (June, 2026-09-30). const DROPPED_COLUMNS: [table: string, column: string][] = [ ["repos", "sort_order"], ["repos", "install1"], ["repos", "install2"], ["repos", "install3"], ]; /** `description` and `details` are the operator's Markdown, or '' for the README's. */ export type RepoSettings = { name: string; category: string; homepage: string; /** The operator's shown languages (§24), or none for the detected one. */ languages: string[]; /** Filing is paused (§23); the list, threads and follow-ups carry on. */ issuesPaused: boolean; description: string; details: string; }; export type RepoText = "description" | "details"; type RepoRow = { name: string; category: string; homepage: string; languages: string; issues_paused: number; description: string | null; details: string | null; }; export function openKeprDb(dataDir: string): Database { mkdirSync(dataDir, { recursive: true }); const db = new Database(join(dataDir, "kepr.db"), { strict: true }); db.run("PRAGMA journal_mode = WAL"); db.run("PRAGMA busy_timeout = 5000"); db.run(SCHEMA); // Every name below comes from the two lists above, never from input. const has = (table: string, column: string) => db .query<{ name: string }, []>(`PRAGMA table_info(${table})`) .all() .some((existing) => existing.name === column); for (const [table, column, definition] of ADDED_COLUMNS) { if (!has(table, column)) db.run(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`); } for (const [table, column] of DROPPED_COLUMNS) { if (has(table, column)) db.run(`ALTER TABLE ${table} DROP COLUMN ${column}`); } return db; } export function setting(db: Database, key: string): string | null { const row = db .query<{ value: string }, [string]>("SELECT value FROM settings WHERE key = ?") .get(key); return row?.value ?? null; } /** Every repo starts private (§20); registering a known repo changes nothing. */ export function registerRepo(db: Database, name: string): void { db.query("INSERT OR IGNORE INTO repos (name) VALUES (?)").run(name); } /** * Tells the operator, unless that kind is switched off, and queues an email when that kind is * emailed. The newest 200 of each are kept. */ export function notify(db: Database, kind: NotificationKind, text: string, href: string): void { const now = Math.floor(Date.now() / 1000); db.transaction(() => { if (!setting(db, `notify_off_${kind}`)) { db.query("INSERT INTO notifications (kind, text, href, created_at) VALUES (?, ?, ?, ?)").run( kind, text, href, now, ); } if (setting(db, `email_on_${kind}`)) { db.query( "INSERT INTO email_queue (subject, href, next_at, created_at) VALUES (?, ?, ?, ?)", ).run(text, href, now, now); } for (const table of ["notifications", "email_queue"]) { // `table` is one of the two names above, never input. db.query( `DELETE FROM ${table} WHERE id NOT IN (SELECT id FROM ${table} ORDER BY id DESC LIMIT ?)`, ).run(NOTIFICATIONS_KEPT); } })(); } /** Records a sync's outcome; a repo that starts failing tells the operator, once. */ export function recordSync(db: Database, name: string, at: number, error: string | null): void { const before = db .query<{ last_sync_error: string | null }, [string]>( "SELECT last_sync_error FROM repos WHERE name = ?", ) .get(name); if (error && !before?.last_sync_error) { notify(db, "sync_failed", `Sync failed for ${name}: ${error}`, `/admin/repos?repo=${name}`); } db.query("UPDATE repos SET last_sync_at = ?, last_sync_error = ? WHERE name = ?").run( at, error, name, ); } export function publicRepoNames(db: Database): string[] { return db .query<{ name: string }, []>("SELECT name FROM repos WHERE public = 1 ORDER BY name") .all() .map((row) => row.name); } /** The settings of a public repo, or null when it is private or unknown: both must look missing. */ export function publicRepo(db: Database, name: string): RepoSettings | null { const row = db .query( `SELECT name, category, homepage, languages, issues_paused, description, details FROM repos LEFT JOIN repo_text ON repo_text.repo = repos.name WHERE name = ? AND public = 1`, ) .get(name); if (!row) return null; return { name: row.name, category: row.category, homepage: row.homepage, languages: row.languages === "" ? [] : row.languages.split(", "), issuesPaused: row.issues_paused === 1, description: row.description ?? "", details: row.details ?? "", }; } /** The paths the operator hid from a repo (June, 2026-09-30), one per line in kepr.db. */ export function hiddenPaths(db: Database, repo: string): string[] { const row = db .query<{ hidden_paths: string }, [string]>("SELECT hidden_paths FROM repos WHERE name = ?") .get(repo); return row?.hidden_paths ? row.hidden_paths.split("\n") : []; } /** A repo's own texts, public or not; '' where the README speaks. */ export function repoText(db: Database, repo: string): Record { return ( db .query, [string]>( "SELECT description, details FROM repo_text WHERE repo = ?", ) .get(repo) ?? { description: "", details: "" } ); } /** Sets one of a repo's texts; '' hands it back to the README. */ export function setRepoText(db: Database, repo: string, field: RepoText, value: string): void { db.query("INSERT OR IGNORE INTO repo_text (repo) VALUES (?)").run(repo); // `field` is one of two column names, never input. db.query(`UPDATE repo_text SET ${field} = ? WHERE repo = ?`).run(value, repo); }