Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
93 changes: 64 additions & 29 deletions TASK.md
Original file line number Diff line number Diff line change
@@ -1,37 +1,72 @@
# TASK: Issue #249Only show manageable servers for mod/admin
# TASK: Issue #123Dashboard 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
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