From 5abe713279c55257793c5d8b5ec9168eb6b8b94e Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 19:55:15 +0200 Subject: [PATCH] feat(database): store dashboard sessions, deploy targets and deployments Sessions and API tokens keep only a hash of the value handed to the client, so a database dump cannot be replayed. A deployment denormalises its target name so the history survives the deletion of that target. Co-Authored-By: Claude Opus 5 (1M context) --- src/database/migrations/006-web-dashboard.sql | 80 ++++++++ .../repositories/deploy-repository.js | 176 ++++++++++++++++++ .../repositories/web-session-repository.js | 107 +++++++++++ 3 files changed, 363 insertions(+) create mode 100644 src/database/migrations/006-web-dashboard.sql create mode 100644 src/database/repositories/deploy-repository.js create mode 100644 src/database/repositories/web-session-repository.js diff --git a/src/database/migrations/006-web-dashboard.sql b/src/database/migrations/006-web-dashboard.sql new file mode 100644 index 0000000..53ff029 --- /dev/null +++ b/src/database/migrations/006-web-dashboard.sql @@ -0,0 +1,80 @@ +-- Web dashboard: sessions, machine tokens, deploy targets and deployments (M16) + +-- Browser sessions created by the Discord OAuth2 login (M16-T02). +-- Only the hash of the cookie value is stored, so a database dump cannot be replayed. +CREATE TABLE IF NOT EXISTS web_sessions ( + id TEXT PRIMARY KEY, + token_hash TEXT NOT NULL UNIQUE, + user_id TEXT, + username TEXT, + display_name TEXT, + avatar TEXT, + access_level INTEGER NOT NULL DEFAULT 0, + source TEXT NOT NULL DEFAULT 'discord' CHECK (source IN ('discord', 'setup', 'token')), + ip TEXT, + user_agent TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + last_seen_at TEXT NOT NULL DEFAULT (datetime('now')), + expires_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_web_sessions_expires ON web_sessions (expires_at); +CREATE INDEX IF NOT EXISTS idx_web_sessions_user ON web_sessions (user_id); + +-- Long lived tokens for scripts and CI calling the dashboard API (M16-T03). +CREATE TABLE IF NOT EXISTS web_api_tokens ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + prefix TEXT NOT NULL, + access_level INTEGER NOT NULL DEFAULT 1, + created_by TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + last_used_at TEXT, + expires_at TEXT, + revoked_at TEXT +); + +-- Where a release can be deployed: a signed webhook, a local command or a Gitea Action (M16-T06). +CREATE TABLE IF NOT EXISTS deploy_targets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + name TEXT NOT NULL, + repository TEXT NOT NULL, + environment TEXT NOT NULL DEFAULT 'production', + kind TEXT NOT NULL CHECK (kind IN ('webhook', 'command', 'gitea-action')), + config TEXT NOT NULL DEFAULT '{}', + auto_deploy INTEGER NOT NULL DEFAULT 0, + enabled INTEGER NOT NULL DEFAULT 1, + created_by TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_deploy_targets_name ON deploy_targets (guild_id, name); +CREATE INDEX IF NOT EXISTS idx_deploy_targets_repo ON deploy_targets (guild_id, repository); + +-- One row per deployment attempt. `target_name` is denormalised so the history +-- survives the deletion of its target (M16-T07). +CREATE TABLE IF NOT EXISTS deployments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + target_id INTEGER REFERENCES deploy_targets (id) ON DELETE SET NULL, + target_name TEXT NOT NULL, + repository TEXT NOT NULL, + environment TEXT NOT NULL, + ref TEXT, + release_tag TEXT, + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'running', 'success', 'failed', 'cancelled')), + source TEXT NOT NULL DEFAULT 'web', + triggered_by TEXT, + log TEXT, + error TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + started_at TEXT, + finished_at TEXT +); + +CREATE INDEX IF NOT EXISTS idx_deployments_target ON deployments (guild_id, target_id, id DESC); +CREATE INDEX IF NOT EXISTS idx_deployments_status ON deployments (status, id DESC); diff --git a/src/database/repositories/deploy-repository.js b/src/database/repositories/deploy-repository.js new file mode 100644 index 0000000..40b0fcf --- /dev/null +++ b/src/database/repositories/deploy-repository.js @@ -0,0 +1,176 @@ +import { getDatabase } from '../index.js'; + +/** Deploy targets and deployment history of the release pipeline (M16-T06 / M16-T07). */ + +const parseTarget = (row) => + row + ? { + ...row, + config: JSON.parse(row.config), + auto_deploy: Boolean(row.auto_deploy), + enabled: Boolean(row.enabled), + } + : null; + +export function createTarget({ + guildId, + name, + repository, + environment = 'production', + kind, + config = {}, + autoDeploy = false, + enabled = true, + createdBy = null, +}) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO deploy_targets + (guild_id, name, repository, environment, kind, config, auto_deploy, enabled, created_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + guildId, + name, + repository, + environment, + kind, + JSON.stringify(config), + autoDeploy ? 1 : 0, + enabled ? 1 : 0, + createdBy, + ); + return getTarget(Number(lastInsertRowid)); +} + +export function getTarget(id) { + return parseTarget(getDatabase().prepare('SELECT * FROM deploy_targets WHERE id = ?').get(id) ?? null); +} + +export function listTargets({ guildId, repository = null } = {}) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (repository) { + clauses.push('repository = ?'); + params.push(repository); + } + return getDatabase() + .prepare(`SELECT * FROM deploy_targets WHERE ${clauses.join(' AND ')} ORDER BY environment, name`) + .all(...params) + .map(parseTarget); +} + +/** Targets eligible for an automatic deployment when a release is published (M16-T08). */ +export function listAutoTargets({ guildId, repository }) { + return getDatabase() + .prepare( + `SELECT * FROM deploy_targets + WHERE guild_id = ? AND repository = ? AND auto_deploy = 1 AND enabled = 1 + ORDER BY environment, name`, + ) + .all(guildId, repository) + .map(parseTarget); +} + +const UPDATABLE = Object.freeze({ + name: (value) => value, + repository: (value) => value, + environment: (value) => value, + kind: (value) => value, + config: (value) => JSON.stringify(value), + auto_deploy: (value) => (value ? 1 : 0), + enabled: (value) => (value ? 1 : 0), +}); + +export function updateTarget(id, patch) { + const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE); + if (entries.length === 0) return getTarget(id); + + const assignments = entries.map(([key]) => `${key} = ?`).join(', '); + const values = entries.map(([key, value]) => UPDATABLE[key](value)); + getDatabase() + .prepare(`UPDATE deploy_targets SET ${assignments}, updated_at = datetime('now') WHERE id = ?`) + .run(...values, id); + return getTarget(id); +} + +export function removeTarget(id) { + return getDatabase().prepare('DELETE FROM deploy_targets WHERE id = ?').run(id).changes; +} + +export function createDeployment({ + guildId, + targetId = null, + targetName, + repository, + environment, + ref = null, + releaseTag = null, + source = 'web', + triggeredBy = null, +}) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO deployments + (guild_id, target_id, target_name, repository, environment, ref, release_tag, source, triggered_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run(guildId, targetId, targetName, repository, environment, ref, releaseTag, source, triggeredBy); + return getDeployment(Number(lastInsertRowid)); +} + +export function getDeployment(id) { + return getDatabase().prepare('SELECT * FROM deployments WHERE id = ?').get(id) ?? null; +} + +export function listDeployments({ guildId, targetId = null, repository = null, status = null, limit = 30 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (targetId) { + clauses.push('target_id = ?'); + params.push(targetId); + } + if (repository) { + clauses.push('repository = ?'); + params.push(repository); + } + if (status) { + clauses.push('status = ?'); + params.push(status); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM deployments WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +export function markRunning(id) { + return getDatabase() + .prepare("UPDATE deployments SET status = 'running', started_at = datetime('now') WHERE id = ?") + .run(id).changes; +} + +export function finishDeployment(id, { status, log = null, error = null }) { + return getDatabase() + .prepare( + `UPDATE deployments SET status = ?, log = ?, error = ?, finished_at = datetime('now') WHERE id = ?`, + ) + .run(status, log, error, id).changes; +} + +/** Counts per status, used by the dashboard tiles. */ +export function countByStatus(guildId) { + return getDatabase() + .prepare('SELECT status, COUNT(*) AS count FROM deployments WHERE guild_id = ? GROUP BY status') + .all(guildId); +} + +export function lastDeploymentPerEnvironment(guildId) { + return getDatabase() + .prepare( + `SELECT environment, repository, status, release_tag, finished_at, MAX(id) AS id + FROM deployments WHERE guild_id = ? GROUP BY environment, repository ORDER BY environment`, + ) + .all(guildId); +} diff --git a/src/database/repositories/web-session-repository.js b/src/database/repositories/web-session-repository.js new file mode 100644 index 0000000..c0dcc89 --- /dev/null +++ b/src/database/repositories/web-session-repository.js @@ -0,0 +1,107 @@ +import { getDatabase } from '../index.js'; + +/** Browser sessions and machine tokens of the web dashboard (M16-T02 / M16-T03). */ + +export function createSession({ + id, + tokenHash, + userId = null, + username = null, + displayName = null, + avatar = null, + accessLevel = 0, + source = 'discord', + ip = null, + userAgent = null, + expiresAt, +}) { + getDatabase() + .prepare( + `INSERT INTO web_sessions + (id, token_hash, user_id, username, display_name, avatar, access_level, source, ip, user_agent, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run(id, tokenHash, userId, username, displayName, avatar, accessLevel, source, ip, userAgent, expiresAt); + return getSession(id); +} + +export function getSession(id) { + return getDatabase().prepare('SELECT * FROM web_sessions WHERE id = ?').get(id) ?? null; +} + +/** Only returns sessions that have not expired, so callers never have to check. */ +export function getLiveSessionByHash(tokenHash) { + return ( + getDatabase() + .prepare("SELECT * FROM web_sessions WHERE token_hash = ? AND expires_at > datetime('now')") + .get(tokenHash) ?? null + ); +} + +export function touchSession(id) { + return getDatabase().prepare("UPDATE web_sessions SET last_seen_at = datetime('now') WHERE id = ?").run(id) + .changes; +} + +export function deleteSession(id) { + return getDatabase().prepare('DELETE FROM web_sessions WHERE id = ?').run(id).changes; +} + +export function deleteSessionsOfUser(userId) { + return getDatabase().prepare('DELETE FROM web_sessions WHERE user_id = ?').run(userId).changes; +} + +export function listSessions(limit = 50) { + return getDatabase() + .prepare( + `SELECT id, user_id, username, display_name, avatar, access_level, source, ip, user_agent, + created_at, last_seen_at, expires_at + FROM web_sessions WHERE expires_at > datetime('now') ORDER BY last_seen_at DESC LIMIT ?`, + ) + .all(limit); +} + +export function purgeExpiredSessions() { + return getDatabase().prepare("DELETE FROM web_sessions WHERE expires_at <= datetime('now')").run().changes; +} + +export function createApiToken({ name, tokenHash, prefix, accessLevel, createdBy = null, expiresAt = null }) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO web_api_tokens (name, token_hash, prefix, access_level, created_by, expires_at) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run(name, tokenHash, prefix, accessLevel, createdBy, expiresAt); + return Number(lastInsertRowid); +} + +export function getLiveApiTokenByHash(tokenHash) { + return ( + getDatabase() + .prepare( + `SELECT * FROM web_api_tokens + WHERE token_hash = ? AND revoked_at IS NULL + AND (expires_at IS NULL OR expires_at > datetime('now'))`, + ) + .get(tokenHash) ?? null + ); +} + +export function touchApiToken(id) { + getDatabase().prepare("UPDATE web_api_tokens SET last_used_at = datetime('now') WHERE id = ?").run(id); +} + +export function listApiTokens() { + return getDatabase() + .prepare( + `SELECT id, name, prefix, access_level, created_by, created_at, last_used_at, expires_at, revoked_at + FROM web_api_tokens ORDER BY id DESC`, + ) + .all(); +} + +export function revokeApiToken(id) { + return getDatabase() + .prepare("UPDATE web_api_tokens SET revoked_at = datetime('now') WHERE id = ? AND revoked_at IS NULL") + .run(id).changes; +}