-
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 6 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 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 |
|---|---|---|
| @@ -1,37 +1,72 @@ | ||
| # TASK: Issue #249 — Only show manageable servers for mod/admin | ||
| # TASK: Issue #123 — Dashboard audit log | ||
|
|
||
| ## Context | ||
| PR for VolvoxLLC/volvox-bot, branch `feat/issue-249` | ||
| Issue: https://github.com/VolvoxLLC/volvox-bot/issues/249 | ||
|
|
||
| ## Problem | ||
| Dashboard server list shows ALL servers the user is in. Should only show servers where user has mod/admin privileges as "manageable". Other servers should show a public link/CTA instead. | ||
| Branch: `feat/issue-123`, Repo: VolvoxLLC/volvox-bot | ||
| Work in: `/home/bill/worktrees/volvox-bot-123` | ||
|
|
||
| ## What to implement | ||
|
|
||
| ### Backend: Role check endpoint | ||
| - There's already a `GET /api/v1/guilds/:id/role` endpoint (check `src/api/routes/guilds.js`) | ||
| - Check `src/api/utils/dashboardRoles.js` for role hierarchy: viewer, moderator, admin, owner | ||
| - May need a batch endpoint or modify the guilds list endpoint to include role info | ||
|
|
||
| ### Frontend: Server selector filtering | ||
| - File: `web/src/components/layout/server-selector.tsx` — this is the guild picker | ||
| - File: `web/src/hooks/use-guild-role.ts` — hook for fetching user role per guild | ||
| - File: `web/src/lib/discord.ts` — Discord API utilities | ||
| - Modify the server list to categorize servers: | ||
| - **Manageable** (mod/admin/owner): show "Manage" button → opens dashboard | ||
| - **Member-only** (viewer): show "View Public Page" button → links to `/community/:guildId` | ||
| - Add visual distinction (badge, opacity, section divider) | ||
|
|
||
| ### Key files to check | ||
| - `web/src/components/layout/sidebar.tsx` — may have navigation filtering by role | ||
| - `web/src/hooks/use-guild-role.ts` — existing role hook | ||
| - `web/src/app/api/guilds/[guildId]/role/route.ts` — Next.js role proxy | ||
| ### 1. Database migration | ||
| - Create `migrations/013_audit_log.cjs` (next migration after 012 placeholder) | ||
| - Table: `audit_logs` with columns: | ||
| - `id SERIAL PRIMARY KEY` | ||
| - `guild_id VARCHAR(20) NOT NULL` | ||
| - `user_id VARCHAR(20) NOT NULL` — Discord user who took the action | ||
| - `user_tag VARCHAR(100)` — cached display name | ||
| - `action VARCHAR(100) NOT NULL` — e.g. 'config.update', 'member.xp.adjust', 'warning.create' | ||
| - `target_type VARCHAR(50)` — e.g. 'config', 'member', 'warning' | ||
| - `target_id VARCHAR(100)` — e.g. guild ID, user ID, warning ID | ||
| - `details JSONB` — before/after diff or action-specific data | ||
| - `ip_address VARCHAR(45)` — client IP (optional) | ||
| - `created_at TIMESTAMPTZ DEFAULT NOW()` | ||
| - Index: `(guild_id, created_at DESC)`, `(guild_id, user_id)` | ||
|
|
||
| ### 2. Backend: audit logger module | ||
| - Create `src/modules/auditLogger.js` | ||
| - `logAuditEvent(guildId, userId, userTag, action, details, options?)` — inserts to audit_logs | ||
| - Graceful: if DB unavailable, log warning but don't throw | ||
|
|
||
| ### 3. Express middleware | ||
| - Create `src/api/middleware/auditLog.js` | ||
| - Auto-logs all mutating requests (POST/PUT/PATCH/DELETE) that have authenticated sessions | ||
| - Captures: guild_id (from params), user_id + user_tag (from session), action (from method + path), IP | ||
| - Attach as middleware AFTER auth middleware on guild routes | ||
|
|
||
| ### 4. Instrument key actions manually | ||
| - Config update in `src/api/routes/config.js` → log before/after diff in `details` | ||
| - XP adjust in `src/api/routes/members.js` → log amount + reason | ||
| - Warning create/remove/clear in `src/api/routes/warnings.js` | ||
|
|
||
| ### 5. API route | ||
| - Create `src/api/routes/auditLog.js` | ||
| - `GET /api/v1/guilds/:guildId/audit-log` with: | ||
| - Pagination: `?page=1&limit=50` | ||
| - Filters: `?userId=`, `?action=`, `?from=`, `?to=` | ||
| - Register in `src/api/index.js` | ||
|
|
||
| ### 6. Dashboard page | ||
| - Create `web/src/app/dashboard/[guildId]/audit-log/page.tsx` | ||
| - Table with columns: Time, Admin, Action, Target, Details | ||
| - Expandable rows showing full `details` JSONB | ||
| - Filter controls: date range, action type, user search | ||
| - Use existing patterns from moderation cases page | ||
|
|
||
| ### 7. Next.js API proxy | ||
| - Create `web/src/app/api/guilds/[guildId]/audit-log/route.ts` | ||
| - Forward to bot API with auth | ||
|
|
||
| ### 8. Sidebar nav entry | ||
| - Add "Audit Log" to dashboard sidebar navigation | ||
| - Check `web/src/components/layout/sidebar.tsx` | ||
|
|
||
| ### 9. Tests | ||
| - Unit tests for `auditLogger.js` | ||
| - Integration tests for the API route | ||
|
|
||
| ## Rules | ||
| - **Everything in config.json must be configurable through the dashboard** | ||
| - Commit after EVERY file change with conventional commit format | ||
| - Run `pnpm --prefix web lint && pnpm --prefix web typecheck` before final commit | ||
| - Do NOT push — just commit locally | ||
| - Commit each section separately | ||
| - Run `pnpm format && pnpm lint && pnpm test` and `pnpm --prefix web lint && pnpm --prefix web typecheck` | ||
| - Everything configurable through dashboard (retention days setting) | ||
| - Do NOT push | ||
|
|
||
| Closes #249 | ||
| Closes #123 |
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.