import 'dotenv/config'; import path from 'node:path'; import fs from 'node:fs'; import Database from 'better-sqlite3'; import { encrypt, decrypt } from './secret-store.js'; const dbPath = process.env.DB_PATH || './data/disjecta.db'; fs.mkdirSync(path.dirname(dbPath), { recursive: true }); export const db = new Database(dbPath); db.pragma('journal_mode = WAL'); db.pragma('foreign_keys = ON'); function ensureColumn(table, column, definition) { const cols = db.prepare(`PRAGMA table_info(${table})`).all(); if (cols.length > 0 && !cols.some(c => c.name === column)) { db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`); } } db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, discord_id TEXT UNIQUE NOT NULL, stripe_customer_id TEXT, active INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now')) ); CREATE TABLE IF NOT EXISTS jobs ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, did TEXT NOT NULL, did_handle TEXT, did_avatar TEXT, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), UNIQUE (user_id, did) ); CREATE TABLE IF NOT EXISTS rules ( id INTEGER PRIMARY KEY, job_id INTEGER NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, guild_id TEXT, channel_id TEXT, author_id TEXT, mode TEXT NOT NULL DEFAULT 'urls', match_kind TEXT, match_value TEXT, destination_kind TEXT NOT NULL DEFAULT 'stdout', destination_config TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')) ); CREATE INDEX IF NOT EXISTS rules_lookup ON rules(enabled, guild_id); CREATE TABLE IF NOT EXISTS write_counters ( job_id INTEGER NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, period TEXT NOT NULL, count INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (job_id, period) ); CREATE TABLE IF NOT EXISTS oauth_state ( key TEXT PRIMARY KEY, value TEXT NOT NULL, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')) ); CREATE TABLE IF NOT EXISTS oauth_session ( sub TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now')) ); CREATE TABLE IF NOT EXISTS webhook_events ( event_id TEXT PRIMARY KEY, received_at INTEGER NOT NULL DEFAULT (strftime('%s','now')) ); CREATE TABLE IF NOT EXISTS backfill_jobs ( id INTEGER PRIMARY KEY, rule_id INTEGER NOT NULL REFERENCES rules(id) ON DELETE CASCADE, channel_id TEXT NOT NULL, since_ts INTEGER NOT NULL, until_ts INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', cursor_message_id TEXT, cursor_ts INTEGER, scanned INTEGER NOT NULL DEFAULT 0, dispatched INTEGER NOT NULL DEFAULT 0, records_written INTEGER NOT NULL DEFAULT 0, error_count INTEGER NOT NULL DEFAULT 0, error_samples TEXT, error TEXT, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), started_at INTEGER, finished_at INTEGER ); CREATE INDEX IF NOT EXISTS backfill_jobs_status ON backfill_jobs(status); CREATE INDEX IF NOT EXISTS backfill_jobs_rule ON backfill_jobs(rule_id); `); // Migrations for existing databases predating columns above. ensureColumn('rules', 'mode', `TEXT NOT NULL DEFAULT 'urls'`); ensureColumn('rules', 'match_kind', `TEXT`); ensureColumn('rules', 'match_value', `TEXT`); ensureColumn('backfill_jobs', 'records_written', `INTEGER NOT NULL DEFAULT 0`); ensureColumn('backfill_jobs', 'error_count', `INTEGER NOT NULL DEFAULT 0`); ensureColumn('backfill_jobs', 'error_samples', `TEXT`); // One-shot migration from the pre-jobs schema (where users held the DID // directly and rules.user_id pointed at users). Detect by presence of the // old user_id column on rules; once the column is gone, this block is a no-op. // The full procedure uses SQLite's recommended table-rebuild dance: // FKs off → BEGIN → CREATE _new → copy → DROP → RENAME → COMMIT → FKs on → // PRAGMA foreign_key_check. if (db.prepare(`PRAGMA table_info(rules)`).all().some(c => c.name === 'user_id')) { console.log('db: migrating to jobs model'); const beforeRules = db.prepare(`SELECT COUNT(*) AS c FROM rules`).get().c; db.exec('PRAGMA foreign_keys = OFF'); try { db.exec('BEGIN'); // 1) Seed jobs from users with a DID. Skip orphan users (no DID). db.exec(` INSERT OR IGNORE INTO jobs (user_id, did, did_handle, did_avatar) SELECT id, did, did_handle, did_avatar FROM users WHERE did IS NOT NULL `); // 2) Rebuild rules with job_id. Rules whose user has no DID are dropped // (they were never going to dispatch and we no longer have a job to // pin them to). db.exec(` CREATE TABLE rules_new ( id INTEGER PRIMARY KEY, job_id INTEGER NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, guild_id TEXT, channel_id TEXT, author_id TEXT, mode TEXT NOT NULL DEFAULT 'urls', match_kind TEXT, match_value TEXT, destination_kind TEXT NOT NULL DEFAULT 'stdout', destination_config TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')) ) `); db.exec(` INSERT INTO rules_new (id, job_id, guild_id, channel_id, author_id, mode, match_kind, match_value, destination_kind, destination_config, enabled, created_at) SELECT r.id, j.id, r.guild_id, r.channel_id, r.author_id, r.mode, r.match_kind, r.match_value, r.destination_kind, r.destination_config, r.enabled, r.created_at FROM rules r JOIN jobs j ON j.user_id = r.user_id `); const afterRules = db.prepare(`SELECT COUNT(*) AS c FROM rules_new`).get().c; if (afterRules < beforeRules) { console.warn(`db: migration dropped ${beforeRules - afterRules} rule(s) belonging to users with no linked DID`); } db.exec(`DROP TABLE rules`); db.exec(`ALTER TABLE rules_new RENAME TO rules`); db.exec(`CREATE INDEX IF NOT EXISTS rules_lookup ON rules(enabled, guild_id)`); // 3) Rebuild write_counters with job_id. Counters for users with no DID // are dropped (orphaned). db.exec(` CREATE TABLE write_counters_new ( job_id INTEGER NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, period TEXT NOT NULL, count INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (job_id, period) ) `); db.exec(` INSERT INTO write_counters_new (job_id, period, count) SELECT j.id, wc.period, wc.count FROM write_counters wc JOIN jobs j ON j.user_id = wc.user_id `); db.exec(`DROP TABLE write_counters`); db.exec(`ALTER TABLE write_counters_new RENAME TO write_counters`); // 4) Drop did / did_handle / did_avatar from users. db.exec(` CREATE TABLE users_new ( id INTEGER PRIMARY KEY, discord_id TEXT UNIQUE NOT NULL, stripe_customer_id TEXT, active INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now')) ) `); db.exec(` INSERT INTO users_new (id, discord_id, stripe_customer_id, active, created_at, updated_at) SELECT id, discord_id, stripe_customer_id, active, created_at, updated_at FROM users `); db.exec(`DROP TABLE users`); db.exec(`ALTER TABLE users_new RENAME TO users`); db.exec('COMMIT'); } catch (e) { try { db.exec('ROLLBACK'); } catch {} db.exec('PRAGMA foreign_keys = ON'); throw e; } db.exec('PRAGMA foreign_keys = ON'); const fkCheck = db.prepare('PRAGMA foreign_key_check').all(); if (fkCheck.length > 0) { console.error('db: post-migration FK check failed', fkCheck); throw new Error('post-migration foreign_key_check failed'); } console.log('db: migration to jobs model complete'); } // Whether a user.active=1 row is allowed to dispatch right now. Evaluated // at module load against env, then embedded into prepared statements so we // don't pay the cost per-message. // // Open ────── BILLING_DISABLED=1 (test period / loopback): everyone fires. // Paid only ─ BILLING_DISABLED=0 and no grace window: must have a customer id. // Grace ──── BILLING_DISABLED=0 with GRACE_UNTIL set: customer id OR within the // grace window. const _isLoopback = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i.test(process.env.PUBLIC_URL ?? ''); const _billingDisabled = _isLoopback || process.env.BILLING_DISABLED === '1'; const _graceUntilEpoch = (() => { const raw = process.env.GRACE_UNTIL; if (!raw) return null; const t = Date.parse(raw); if (!Number.isFinite(t)) { console.warn(`db: GRACE_UNTIL="${raw}" is not a parseable date; ignoring.`); return null; } return Math.floor(t / 1000); })(); const dispatchGateClause = _billingDisabled ? '1=1' : _graceUntilEpoch != null ? `(u.stripe_customer_id IS NOT NULL OR strftime('%s','now') < ${_graceUntilEpoch})` : `u.stripe_customer_id IS NOT NULL`; export const graceUntilEpoch = _graceUntilEpoch; export function isWithinGrace() { return _graceUntilEpoch != null && Math.floor(Date.now() / 1000) < _graceUntilEpoch; } // Find rules that match a (guild, channel, author) tuple. NULL = wildcard. // 'self' on author_id resolves to the rule-owner's discord_id. // Content matching (match_kind/match_value) happens in JS after this call. export const findMatchingRules = db.prepare(` SELECT r.id AS rule_id, r.mode, r.match_kind, r.match_value, r.destination_kind, r.destination_config, j.id AS job_id, u.id AS user_id, u.discord_id AS owner_discord_id, j.did AS owner_did FROM rules r JOIN jobs j ON j.id = r.job_id JOIN users u ON u.id = j.user_id WHERE u.active = 1 AND r.enabled = 1 AND ${dispatchGateClause} AND (r.guild_id IS NULL OR r.guild_id = @guild_id) AND (r.channel_id IS NULL OR r.channel_id = @channel_id) AND (r.author_id IS NULL OR r.author_id = @author_id OR (r.author_id = 'self' AND u.discord_id = @author_id)) `); // Same gate, reused by active-guilds.js (which inlines its own statement but // needs the identical predicate to stay consistent). export const _dispatchGateClause = dispatchGateClause; const bumpStmt = db.prepare(` INSERT INTO write_counters (job_id, period, count) VALUES (?, ?, ?) ON CONFLICT(job_id, period) DO UPDATE SET count = count + excluded.count `); export function bumpCounter(jobId, n = 1) { const period = new Date().toISOString().slice(0, 7); // YYYY-MM bumpStmt.run(jobId, period, n); } const counterGet = db.prepare( `SELECT count FROM write_counters WHERE job_id = ? AND period = ?` ); export function getCounter(jobId, period = new Date().toISOString().slice(0, 7)) { return counterGet.get(jobId, period)?.count ?? 0; } const countersForJob = db.prepare( `SELECT period, count FROM write_counters WHERE job_id = ? ORDER BY period DESC LIMIT ?` ); export function listCounters(jobId, n = 6) { return countersForJob.all(jobId, n); } const upsertByDiscordStmt = db.prepare(` INSERT INTO users (discord_id) VALUES (?) ON CONFLICT(discord_id) DO UPDATE SET updated_at = strftime('%s','now') RETURNING * `); export function upsertUserByDiscord({ discordId }) { return upsertByDiscordStmt.get(discordId); } export const getUserByDiscord = db.prepare(`SELECT * FROM users WHERE discord_id = ?`); // ───── jobs ─────────────────────────────────────────────────────────────── // A job is the (user, did) pair — the unit that owns rules and counters. // Multiple jobs per user is fine; a single user can drive several atproto // identities. UNIQUE(user_id, did) means upserting an existing pair is a // no-op that returns the existing row. const insertJobStmt = db.prepare(` INSERT INTO jobs (user_id, did) VALUES (?, ?) ON CONFLICT(user_id, did) DO NOTHING `); const getJobByUserAndDidStmt = db.prepare( `SELECT * FROM jobs WHERE user_id = ? AND did = ?` ); export function upsertJob({ userId, did }) { insertJobStmt.run(userId, did); return getJobByUserAndDidStmt.get(userId, did); } export function getJobByUserAndDid(userId, did) { return getJobByUserAndDidStmt.get(userId, did); } export const getJobById = db.prepare(`SELECT * FROM jobs WHERE id = ?`); export const listJobsForUser = db.prepare( `SELECT * FROM jobs WHERE user_id = ? ORDER BY id ASC` ); const setJobProfileStmt = db.prepare( `UPDATE jobs SET did_handle = ?, did_avatar = ? WHERE id = ?` ); export function setJobProfile(jobId, handle, avatar) { setJobProfileStmt.run(handle ?? null, avatar ?? null, jobId); } // Deleting a job cascades to its rules and write_counters via ON DELETE // CASCADE. The caller is responsible for revoking the atproto OAuth session // for the DID (web.js does this before invoking deleteJob). const deleteJobStmt = db.prepare(`DELETE FROM jobs WHERE id = ? AND user_id = ?`); export function deleteJob(jobId, userId) { return deleteJobStmt.run(jobId, userId).changes === 1; } // ───── rules ────────────────────────────────────────────────────────────── export const listRulesForJob = db.prepare( `SELECT * FROM rules WHERE job_id = ? ORDER BY id DESC` ); export const getRuleForJob = db.prepare( `SELECT * FROM rules WHERE id = ? AND job_id = ?` ); const insertRuleStmt = db.prepare(` INSERT INTO rules (job_id, guild_id, channel_id, author_id, mode, match_kind, match_value, destination_kind, destination_config, enabled) VALUES (@job_id, @guild_id, @channel_id, @author_id, @mode, @match_kind, @match_value, @destination_kind, @destination_config, @enabled) RETURNING * `); export function insertRule(row) { return insertRuleStmt.get({ job_id: row.job_id, guild_id: row.guild_id ?? null, channel_id: row.channel_id ?? null, author_id: row.author_id ?? null, mode: row.mode ?? 'urls', match_kind: row.match_kind ?? null, match_value: row.match_value ?? null, destination_kind: row.destination_kind ?? 'stdout', destination_config: row.destination_config ?? null, enabled: row.enabled ?? 1, }); } export const deleteRuleForJob = db.prepare( `DELETE FROM rules WHERE id = ? AND job_id = ?` ); export const toggleRuleForJob = db.prepare( `UPDATE rules SET enabled = 1 - enabled WHERE id = ? AND job_id = ?` ); // Edit-in-place. Doesn't touch enabled/created_at — Toggle handles enabled, // and we preserve the original creation time so the rule's backfill history // (FK'd on rule.id) stays meaningful. const updateRuleStmt = db.prepare(` UPDATE rules SET guild_id = @guild_id, channel_id = @channel_id, author_id = @author_id, mode = @mode, match_kind = @match_kind, match_value = @match_value, destination_kind = @destination_kind, destination_config = @destination_config WHERE id = @id AND job_id = @job_id `); export function updateRuleForJob(row) { return updateRuleStmt.run({ id: row.id, job_id: row.job_id, guild_id: row.guild_id ?? null, channel_id: row.channel_id ?? null, author_id: row.author_id ?? null, mode: row.mode ?? 'urls', match_kind: row.match_kind ?? null, match_value: row.match_value ?? null, destination_kind: row.destination_kind ?? 'stdout', destination_config: row.destination_config ?? null, }).changes === 1; } const setSubStmt = db.prepare(` UPDATE users SET stripe_customer_id = COALESCE(?, stripe_customer_id), active = ?, updated_at = strftime('%s','now') WHERE id = ? `); export function setUserSubscription(userId, customerId, active) { setSubStmt.run(customerId ?? null, active ? 1 : 0, userId); } const getUserByCustomerStmt = db.prepare( `SELECT * FROM users WHERE stripe_customer_id = ?` ); export function getUserByCustomer(customerId) { return getUserByCustomerStmt.get(customerId); } const setActiveByCustomerStmt = db.prepare(` UPDATE users SET active = ?, updated_at = strftime('%s','now') WHERE stripe_customer_id = ? `); export function setActiveByCustomer(customerId, active) { setActiveByCustomerStmt.run(active ? 1 : 0, customerId); } // Disable every rule belonging to any job owned by this user. const disableAllRulesForUserStmt = db.prepare( `UPDATE rules SET enabled = 0 WHERE job_id IN (SELECT id FROM jobs WHERE user_id = ?)` ); export function disableAllRulesForUser(userId) { disableAllRulesForUserStmt.run(userId); } // Subscription lapse: flip active=0 and disable every rule across every job // the user owns. Re-subscribing later flips active=1 but leaves rules // disabled (user opts back in via the UI). Wrapped in a transaction so the // user is never seen active=1 with disabled rules mid-flight. export const deactivateUserAndDisableRules = db.transaction((userId) => { db.prepare(`UPDATE users SET active = 0, updated_at = strftime('%s','now') WHERE id = ?`).run(userId); disableAllRulesForUserStmt.run(userId); }); const clearStripeCustomerStmt = db.prepare( `UPDATE users SET stripe_customer_id = NULL, updated_at = strftime('%s','now') WHERE id = ?` ); export function clearStripeCustomer(userId) { clearStripeCustomerStmt.run(userId); } const setActiveByDiscordStmt = db.prepare(` UPDATE users SET active = ?, updated_at = strftime('%s','now') WHERE discord_id = ? `); export function setActiveByDiscord(discordId, active) { setActiveByDiscordStmt.run(active ? 1 : 0, discordId); } // Webhook idempotency: returns true if we've never seen this event_id, false // if it's a Stripe retry of an already-processed event. const insertWebhookEventStmt = db.prepare( `INSERT OR IGNORE INTO webhook_events (event_id) VALUES (?)` ); export function tryRecordWebhookEvent(eventId) { return insertWebhookEventStmt.run(eventId).changes === 1; } // ───── backfill jobs ─────────────────────────────────────────────────────── // Worker model: one job at a time, claimed by the worker loop. A rule may // have at most one non-terminal (pending|running) job; the API enforces this. const insertBackfillJobStmt = db.prepare(` INSERT INTO backfill_jobs (rule_id, channel_id, since_ts, until_ts, status) VALUES (@rule_id, @channel_id, @since_ts, @until_ts, 'pending') RETURNING * `); export function insertBackfillJob(row) { return insertBackfillJobStmt.get(row); } export const getActiveBackfillJobForRule = db.prepare(` SELECT * FROM backfill_jobs WHERE rule_id = ? AND status IN ('pending', 'running') ORDER BY id DESC LIMIT 1 `); export const getLatestBackfillJobForRule = db.prepare(` SELECT * FROM backfill_jobs WHERE rule_id = ? ORDER BY id DESC LIMIT 1 `); // All jobs for a rule, newest first. Used by the status page to render a // channel-centric view of a "backfill every channel" fan-out. export const listBackfillJobsForRule = db.prepare(` SELECT * FROM backfill_jobs WHERE rule_id = ? ORDER BY id DESC `); // Per-channel active check, so a fan-out skips channels that already have a // non-terminal job instead of enqueuing duplicate work. export const getActiveBackfillJobForRuleChannel = db.prepare(` SELECT * FROM backfill_jobs WHERE rule_id = ? AND channel_id = ? AND status IN ('pending', 'running') ORDER BY id DESC LIMIT 1 `); export const nextPendingBackfillJob = db.prepare(` SELECT * FROM backfill_jobs WHERE status = 'pending' ORDER BY id ASC LIMIT 1 `); const markRunningStmt = db.prepare(` UPDATE backfill_jobs SET status = 'running', started_at = strftime('%s','now') WHERE id = ? `); export function markBackfillRunning(id) { markRunningStmt.run(id); } const updateProgressStmt = db.prepare(` UPDATE backfill_jobs SET cursor_message_id = @cursor_message_id, cursor_ts = @cursor_ts, scanned = scanned + @scanned_delta, dispatched = dispatched + @dispatched_delta, records_written = records_written + @records_written_delta WHERE id = @id `); export function updateBackfillProgress(args) { updateProgressStmt.run({ id: args.id, cursor_message_id: args.cursor_message_id ?? null, cursor_ts: args.cursor_ts ?? null, scanned_delta: args.scanned_delta ?? 0, dispatched_delta: args.dispatched_delta ?? 0, records_written_delta: args.records_written_delta ?? 0, }); } export const getBackfillJobById = db.prepare( `SELECT * FROM backfill_jobs WHERE id = ?` ); // Cancellation: only meaningful while pending or running. Once flipped, the // worker will notice on its next page-boundary status re-read and exit // without overwriting status='cancelled' with status='done'. const cancelStmt = db.prepare(` UPDATE backfill_jobs SET status = 'cancelled', finished_at = COALESCE(finished_at, strftime('%s','now')) WHERE id = ? AND status IN ('pending', 'running') `); export function cancelBackfillJob(id) { return cancelStmt.run(id).changes === 1; } // Called on worker startup. Any job left in 'running' from a previous // container that died mid-page is orphaned — no worker will pick it up // because nextPendingBackfillJob only sees 'pending'. Push it back so the // new worker resumes at the saved cursor. We clear started_at so the next // claim records a fresh start; cursor_message_id / scanned / records_written // are preserved. const requeueOrphansStmt = db.prepare(` UPDATE backfill_jobs SET status = 'pending', started_at = NULL WHERE status = 'running' `); export function requeueOrphanedBackfillJobs() { return requeueOrphansStmt.run().changes; } // Diagnostic: record per-write errors against a backfill job so we can see the // PDS's verbatim rejection without relying on Railway's windowed log buffer. // Keeps the first N distinct samples (keyed by a short "fingerprint" — status // + error name — so repeated identical failures don't dominate). const MAX_ERROR_SAMPLES = 10; const readSamplesStmt = db.prepare( `SELECT error_samples FROM backfill_jobs WHERE id = ?` ); const writeSamplesStmt = db.prepare( `UPDATE backfill_jobs SET error_count = error_count + @count_delta, error_samples = @samples_json WHERE id = @id` ); export function recordBackfillErrors(jobId, newErrors) { if (!Array.isArray(newErrors) || newErrors.length === 0) return; const row = readSamplesStmt.get(jobId); let samples = []; if (row?.error_samples) { try { samples = JSON.parse(row.error_samples) ?? []; } catch { samples = []; } } const seen = new Set(samples.map(s => s.fingerprint)); for (const e of newErrors) { const fingerprint = `${e.status ?? '?'}:${e.error ?? ''}`; if (seen.has(fingerprint)) continue; seen.add(fingerprint); samples.push({ fingerprint, ...e }); if (samples.length >= MAX_ERROR_SAMPLES) break; } writeSamplesStmt.run({ id: jobId, count_delta: newErrors.length, samples_json: JSON.stringify(samples), }); } // Only transition out of pending/running — once a job is cancelled or // already terminal, leave it alone so worker code doesn't accidentally // stomp a user's cancel. const finishStmt = db.prepare(` UPDATE backfill_jobs SET status = @status, error = @error, finished_at = strftime('%s','now') WHERE id = @id AND status IN ('pending', 'running') `); export function finishBackfillJob(id, status, error = null) { finishStmt.run({ id, status, error }); } // Used by the worker to load the rule shape it needs to call dispatch(). export const getRuleForDispatch = db.prepare(` SELECT r.id AS rule_id, j.id AS job_id, u.id AS user_id, r.guild_id, r.channel_id, r.author_id, r.mode, r.match_kind, r.match_value, r.destination_kind, r.destination_config, r.enabled, u.discord_id AS owner_discord_id, j.did AS owner_did, u.active AS owner_active, u.stripe_customer_id AS owner_stripe_customer_id FROM rules r JOIN jobs j ON j.id = r.job_id JOIN users u ON u.id = j.user_id WHERE r.id = ? `); const oauthStateSet = db.prepare(`INSERT OR REPLACE INTO oauth_state (key, value) VALUES (?, ?)`); const oauthStateGet = db.prepare(`SELECT value FROM oauth_state WHERE key = ?`); const oauthStateDel = db.prepare(`DELETE FROM oauth_state WHERE key = ?`); const oauthSessionSet = db.prepare( `INSERT OR REPLACE INTO oauth_session (sub, value, updated_at) VALUES (?, ?, strftime('%s','now'))` ); const oauthSessionGet = db.prepare(`SELECT value FROM oauth_session WHERE sub = ?`); const oauthSessionDel = db.prepare(`DELETE FROM oauth_session WHERE sub = ?`); export const oauthStores = { state: { async set(key, value) { oauthStateSet.run(key, encrypt(JSON.stringify(value))); }, async get(key) { const row = oauthStateGet.get(key); return row ? JSON.parse(decrypt(row.value)) : undefined; }, async del(key) { oauthStateDel.run(key); }, }, session: { async set(sub, value) { oauthSessionSet.run(sub, encrypt(JSON.stringify(value))); }, async get(sub) { const row = oauthSessionGet.get(sub); return row ? JSON.parse(decrypt(row.value)) : undefined; }, async del(sub) { oauthSessionDel.run(sub); }, }, }; console.log(`db at ${dbPath}`);