// Admin action log (Marty 2026-11-16, "a named, logged admin route"): who did what, to what, and when, for admin routes that // change a member's things on their behalf (first user: /api/admin/house-spins). One row per call, denied calls included. // With MySQL (production) the rows live in table admin_audit; without it (local copies, QA) in DATA_DIR/admin-audit.jsonl. // Never holds a secret: callers pass a short summary, and anything that looks like a key or password is masked here too. // record({ who, action, target, ok, detail, ip }) list(limit) -> newest first 'use strict'; const fs = require('fs'); const path = require('path'); const db = require('./db'); let DATA_DIR = null, made = false; function init(opts) { DATA_DIR = opts.dataDir; } const FILE = () => path.join(DATA_DIR, 'admin-audit.jsonl'); const clip = (s, n) => String(s == null ? '' : s).slice(0, n); // a value under a key like token/secret/password/key never lands in the log const scrub = o => JSON.parse(JSON.stringify(o == null ? null : o, (k, v) => (/pass|secret|token|apikey|api_key|authorization/i.test(k) ? '[masked]' : v))); async function table() { if (made) return; await db.q(`CREATE TABLE IF NOT EXISTS admin_audit ( id BIGINT AUTO_INCREMENT PRIMARY KEY, ts BIGINT NOT NULL, who VARCHAR(190) NOT NULL, action VARCHAR(80) NOT NULL, target VARCHAR(190) NOT NULL DEFAULT '', ok TINYINT NOT NULL DEFAULT 1, ip VARCHAR(64) NOT NULL DEFAULT '', detail MEDIUMTEXT, KEY ts (ts), KEY action (action)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); made = true; } async function record(e) { const row = { ts: Date.now(), who: clip(e.who || 'unknown', 190), action: clip(e.action, 80), target: clip(e.target, 190), ok: e.ok === false ? 0 : 1, ip: clip(e.ip, 64), detail: clip(JSON.stringify(scrub(e.detail)), 60000) }; try { if (db.enabled()) { await table(); await db.q('INSERT INTO admin_audit (ts, who, action, target, ok, ip, detail) VALUES (?, ?, ?, ?, ?, ?, ?)', [row.ts, row.who, row.action, row.target, row.ok, row.ip, row.detail]); } else fs.appendFileSync(FILE(), JSON.stringify(row) + '\n'); return true; } catch (er) { console.error('adminaudit', er.message); return false; } } async function list(limit) { const n = Math.max(1, Math.min(500, Number(limit) || 100)); const parse = r => Object.assign({}, r, { ts: Number(r.ts), ok: !!Number(r.ok), detail: (() => { try { return JSON.parse(r.detail); } catch (e) { return r.detail; } })() }); if (db.enabled()) { await table(); return (await db.q('SELECT id, ts, who, action, target, ok, ip, detail FROM admin_audit ORDER BY id DESC LIMIT ?', [n])).map(parse); } let lines = []; try { lines = fs.readFileSync(FILE(), 'utf8').split('\n').filter(Boolean); } catch (e) {} return lines.slice(-n).reverse().map(l => { try { return parse(JSON.parse(l)); } catch (e) { return null; } }).filter(Boolean); } module.exports = { init, record, list };