Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 0 additions & 37 deletions TASK.md

This file was deleted.

73 changes: 73 additions & 0 deletions migrations/013_audit_log.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* Migration 013 — Audit Log
*
* Creates the `audit_logs` table for recording all admin actions performed
* via the bot API (config changes, XP adjustments, warnings, etc.).
*
* Indexes:
* - (guild_id, created_at DESC) — primary query pattern for the dashboard
* - (guild_id, user_id) — filter by admin user within a guild
*/

/** @type {import('node-pg-migrate').MigrationBuilder} */
exports.up = (pgm) => {
pgm.createTable('audit_logs', {
id: {
type: 'SERIAL',
primaryKey: true,
},
guild_id: {
type: 'VARCHAR(20)',
notNull: true,
},
user_id: {
type: 'VARCHAR(20)',
notNull: true,
},
user_tag: {
type: 'VARCHAR(100)',
notNull: false,
},
action: {
type: 'VARCHAR(100)',
notNull: true,
},
target_type: {
type: 'VARCHAR(50)',
notNull: false,
},
target_id: {
type: 'VARCHAR(100)',
notNull: false,
},
details: {
type: 'JSONB',
notNull: false,
},
ip_address: {
type: 'VARCHAR(45)',
notNull: false,
},
created_at: {
type: 'TIMESTAMPTZ',
notNull: true,
default: pgm.func('NOW()'),
},
});

// Primary access pattern: guild's audit log ordered by recency
pgm.createIndex('audit_logs', ['guild_id', 'created_at'], {
name: 'idx_audit_logs_guild_created',
order: { created_at: 'DESC' },
});

// Filter by admin user within a guild
pgm.createIndex('audit_logs', ['guild_id', 'user_id'], {
name: 'idx_audit_logs_guild_user',
});
};

/** @type {import('node-pg-migrate').MigrationBuilder} */
exports.down = (pgm) => {
pgm.dropTable('audit_logs');
};
1 change: 1 addition & 0 deletions node_modules
11 changes: 7 additions & 4 deletions src/api/middleware/auditLog.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,17 @@ export function computeConfigDiff(before, after) {
* @param {Object} entry - Audit log entry
*/
function insertAuditEntry(pool, entry) {
const { guildId, userId, action, targetType, targetId, details, ipAddress } = entry;
const { guildId, userId, userTag, action, targetType, targetId, details, ipAddress } = entry;

try {
const result = pool.query(
`INSERT INTO audit_logs (guild_id, user_id, action, target_type, target_id, details, ip_address)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, guild_id, user_id, action, target_type, target_id, details, ip_address, created_at`,
`INSERT INTO audit_logs (guild_id, user_id, user_tag, action, target_type, target_id, details, ip_address)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, guild_id, user_id, user_tag, action, target_type, target_id, details, ip_address, created_at`,
[
guildId || 'global',
userId,
userTag || null,
action,
targetType || null,
targetId || null,
Expand Down Expand Up @@ -188,6 +189,7 @@ export function auditLogMiddleware() {
req._auditLogAttached = true;

const userId = req.user?.userId || req.authMethod || 'unknown';
const userTag = req.user?.tag || req.user?.username || null;
const action = deriveAction(req.method, cleanPath);
const ipAddress = req.ip || req.socket?.remoteAddress;

Expand Down Expand Up @@ -250,6 +252,7 @@ export function auditLogMiddleware() {
insertAuditEntry(pool, {
guildId,
userId,
userTag,
action,
targetType,
targetId,
Expand Down
149 changes: 149 additions & 0 deletions src/modules/auditLogger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* Audit Logger Module
*
* Provides a single `logAuditEvent` function for recording admin actions to
* the `audit_logs` table. Designed to be fire-and-forget — callers should not
* await the result unless they need confirmation of success.
*
* The middleware in `src/api/middleware/auditLog.js` handles *automatic*
* logging of all mutating HTTP requests. Use this module directly when you
* need richer, context-aware details (e.g. before/after diffs) that the
* generic middleware cannot infer from the request alone.
*
* @example
* import { logAuditEvent } from '../modules/auditLogger.js';
*
* // Log an XP adjustment with before/after values
* await logAuditEvent(pool, {
* guildId: guild.id,
* userId: req.user.userId,
* userTag: req.user.tag,
* action: 'member.xp_adjust',
* targetType: 'member',
* targetId: userId,
* details: { before: { xp: oldXp }, after: { xp: newXp }, reason },
* });
*/

import { info, error as logError, warn } from '../logger.js';

/**
* @typedef {Object} AuditEventOptions
* @property {string} guildId - Discord guild ID
* @property {string} userId - Discord user ID of the admin who took the action
* @property {string} [userTag] - Cached display name / tag of the admin
* @property {string} action - Dot-namespaced action identifier (e.g. 'config.update')
* @property {string} [targetType] - What kind of thing was affected (e.g. 'member', 'warning')
* @property {string} [targetId] - The ID of the affected entity
* @property {Object} [details] - Freeform JSONB payload (before/after diffs, reason, etc.)
* @property {string} [ipAddress] - Client IP address (optional)
*/

/**
* Insert an audit log event into the database.
*
* Non-blocking by design: if the DB is unavailable or the insert fails, the
* error is logged at WARN level but **never rethrown**. This ensures audit
* logging never interrupts the primary request flow.
*
* @param {import('pg').Pool|null} pool - Database connection pool (may be null — graceful skip)
* @param {AuditEventOptions} event - Audit event fields
* @returns {Promise<void>}
*/
export async function logAuditEvent(pool, event) {
if (!pool) {
warn('auditLogger: DB pool unavailable, skipping audit event', {
action: event?.action,
guildId: event?.guildId,
});
return;
}

const { guildId, userId, userTag, action, targetType, targetId, details, ipAddress } =
event ?? {};

if (!guildId || !userId || !action) {
warn('auditLogger: missing required fields (guildId, userId, action), skipping', {
guildId,
userId,
action,
});
return;
}

try {
await pool.query(
`INSERT INTO audit_logs
(guild_id, user_id, user_tag, action, target_type, target_id, details, ip_address)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[
guildId,
userId,
userTag ?? null,
action,
targetType ?? null,
targetId ?? null,
details != null ? JSON.stringify(details) : null,
ipAddress ?? null,
],
);
info('auditLogger: event recorded', { action, guildId, userId });
} catch (err) {
logError('auditLogger: failed to insert audit event', {
error: err.message,
action,
guildId,
userId,
});
// Intentionally not re-throwing — audit failures must never break callers
}
}

/**
* Purge audit log entries older than the configured retention period.
*
* Called periodically from the DB maintenance scheduler. Uses the
* `auditLog.retentionDays` config value (default: 90 days). Setting
* `retentionDays` to 0 disables purging.
*
* @param {import('pg').Pool} pool - Database connection pool
* @param {number} [retentionDays=90] - Days to keep audit log entries
* @returns {Promise<number>} - Number of rows deleted
*/
export async function purgeOldAuditLogs(pool, retentionDays = 90) {
if (!pool) return 0;
if (retentionDays <= 0) {
info('auditLogger: retention purge disabled (retentionDays <= 0)');
return 0;
}

try {
const result = await pool.query(
`DELETE FROM audit_logs
WHERE created_at < NOW() - make_interval(days => $1)`,
[retentionDays],
);
const count = result.rowCount ?? 0;
if (count > 0) {
info('auditLogger: purged old audit log entries', {
count,
retentionDays,
source: 'db_maintenance',
});
}
return count;
} catch (err) {
if (err.code === '42P01') {
// Table doesn't exist yet — migration hasn't run
warn('auditLogger: audit_logs table does not exist, skipping purge', {
source: 'db_maintenance',
});
return 0;
}
logError('auditLogger: failed to purge old audit log entries', {
error: err.message,
source: 'db_maintenance',
});
return 0;
}
}
8 changes: 8 additions & 0 deletions src/utils/dbMaintenance.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
*/

import { info, error as logError, warn } from '../logger.js';
import { getConfig } from '../modules/config.js';
import { purgeOldAuditLogs } from '../modules/auditLogger.js';

/** Track optional tables we've already warned about to avoid hourly log spam */
const warnedMissingOptionalTables = new Set();
Expand Down Expand Up @@ -138,11 +140,17 @@ async function purgeStaleRateLimits(pool) {
export async function runMaintenance(pool) {
info('DB maintenance: starting routine cleanup', { source: 'db_maintenance' });

// Audit log retention uses the global config default since purgeOldAuditLogs
// operates across all guilds in one query. Per-guild overrides are respected
// when guild-specific purge calls are made from guild config change handlers.
const auditRetentionDays = getConfig()?.auditLog?.retentionDays ?? 90;

try {
await Promise.all([
purgeOldTickets(pool),
purgeExpiredSessions(pool),
purgeStaleRateLimits(pool),
purgeOldAuditLogs(pool, auditRetentionDays),
]);
info('DB maintenance: cleanup complete', { source: 'db_maintenance' });
} catch (err) {
Expand Down
Loading
Loading