-
Notifications
You must be signed in to change notification settings - Fork 2
feat(dashboard): audit log — track all admin actions with attribution #260
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
670da04
feat(db): add audit_logs migration (#123)
9805b7b
feat(modules): add auditLogger module with logAuditEvent + purgeOldAu…
6ac4827
feat(maintenance): wire audit log retention purge into DB maintenance…
a848f0a
test(modules): unit tests for auditLogger module (#123)
2ecab60
feat(dashboard): add audit log retention config to bot config editor …
4e21887
fix: address all PR #260 review comments
5f00242
Delete TASK.md
BillChirico 6af57fd
fix: remove tracked node_modules symlinks; strip Card wrapper from Au…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| /home/bill/volvox-bot/node_modules | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.