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) <noreply@anthropic.com>
This commit is contained in:
3 files changed
+363
No files matched your search
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user