-
-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add AuditLogManager for dashboard settings audit logging #188
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| CREATE TABLE "audit_log" ( | ||
| "id" SERIAL NOT NULL, | ||
| "guild_id" VARCHAR(19) NOT NULL, | ||
| "user_id" VARCHAR(19) NOT NULL, | ||
| "action" VARCHAR(64) NOT NULL, | ||
| "section" VARCHAR(64) NOT NULL, | ||
| "changes" JSON NOT NULL DEFAULT '[]', | ||
| "created_at" TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
| CONSTRAINT "audit_log_pkey" PRIMARY KEY ("id") | ||
| ); | ||
| CREATE INDEX "IDX_audit_log_guild_created" ON "audit_log"("guild_id", "created_at" DESC); | ||
| ALTER TABLE "audit_log" ADD CONSTRAINT "audit_log_guild_id_fkey" FOREIGN KEY ("guild_id") REFERENCES "guilds"("id") ON DELETE CASCADE ON UPDATE CASCADE; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import type { AuditLogChange, ReadonlyGuildData } from '#lib/database/settings/types'; | ||
| import { container } from '@sapphire/framework'; | ||
|
|
||
| export class AuditLogManager { | ||
| #guildId: string; | ||
| #settings: ReadonlyGuildData; | ||
|
|
||
| public constructor(settings: ReadonlyGuildData) { | ||
| this.#guildId = settings.id; | ||
| this.#settings = settings; | ||
| } | ||
|
|
||
| public onPatch(settings: ReadonlyGuildData): void { | ||
| this.#guildId = settings.id; | ||
| this.#settings = settings; | ||
| } | ||
|
|
||
| public update(userId: string, newData: Record<string, unknown>): Promise<void> { | ||
| const changedKeys = Object.keys(newData); | ||
| const changes = this.#buildChanges(newData); | ||
|
|
||
| return this.write(userId, { | ||
| action: 'settings.update', | ||
| section: AuditLogManager.deriveSection(changedKeys), | ||
| changes | ||
| }); | ||
| } | ||
|
|
||
| public add(userId: string, key: string, value: unknown): Promise<void> { | ||
| return this.write(userId, { | ||
| action: 'settings.add', | ||
| section: AuditLogManager.deriveSection([key]), | ||
| changes: [{ key, newValue: AuditLogManager.serializeValue(value) }] | ||
| }); | ||
| } | ||
|
|
||
| public remove(userId: string, key: string, value: unknown): Promise<void> { | ||
| return this.write(userId, { | ||
| action: 'settings.remove', | ||
| section: AuditLogManager.deriveSection([key]), | ||
| changes: [{ key, oldValue: AuditLogManager.serializeValue(value) }] | ||
| }); | ||
| } | ||
|
|
||
| public async write(userId: string, params: { action: string; section: string; changes: AuditLogChange[] }): Promise<void> { | ||
| await container.prisma.auditLog.create({ | ||
| data: { | ||
| guildId: this.#guildId, | ||
| userId, | ||
| action: params.action, | ||
| section: params.section, | ||
| changes: JSON.parse(JSON.stringify(params.changes)) | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| #buildChanges(newData: Record<string, unknown>): AuditLogChange[] { | ||
| return Object.keys(newData).map((key) => ({ | ||
| key, | ||
| oldValue: AuditLogManager.serializeValue((this.#settings as Record<string, unknown>)[key]), | ||
| newValue: AuditLogManager.serializeValue(newData[key]) | ||
| })); | ||
| } | ||
|
|
||
| private static deriveSection(keys: string[]): string { | ||
| const counts = new Map<string, number>(); | ||
| for (const key of keys) { | ||
| const section = AuditLogManager.classifyKey(key); | ||
| counts.set(section, (counts.get(section) ?? 0) + 1); | ||
| } | ||
|
|
||
| if (counts.size === 0) return 'general'; | ||
| if (counts.size === 1) return counts.keys().next().value!; | ||
|
|
||
| let best = 'general'; | ||
| let max = 0; | ||
| for (const [section, count] of counts) { | ||
| if (count > max) { | ||
| max = count; | ||
| best = section; | ||
| } | ||
| } | ||
| return best; | ||
| } | ||
|
|
||
| private static classifyKey(key: string): string { | ||
| if (key.startsWith('permissions')) return 'permissions'; | ||
| if (key.startsWith('selfmod') || key.startsWith('noMentionSpam')) return 'moderation'; | ||
| if (key.startsWith('channels')) return 'channels'; | ||
| if (key.startsWith('roles')) return 'roles'; | ||
| if (key.startsWith('events')) return 'events'; | ||
| if (key.startsWith('messages')) return 'messages'; | ||
| if (key.startsWith('disabled')) return 'commands'; | ||
| return 'general'; | ||
| } | ||
|
|
||
| private static serializeValue(value: unknown): unknown { | ||
| if (typeof value === 'bigint') return Number(value); | ||
| return value; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import { authenticated, canManage, ratelimit } from '#lib/api/utils'; | ||
| import { seconds } from '#utils/common'; | ||
| import { container } from '@sapphire/framework'; | ||
| import { HttpCodes, Route } from '@sapphire/plugin-api'; | ||
|
Comment on lines
+1
to
+4
|
||
|
|
||
| export class UserRoute extends Route { | ||
| @authenticated() | ||
| @ratelimit(seconds(10), 5, true) | ||
| public async run(request: Route.Request, response: Route.Response) { | ||
| const guildId = request.params.guild; | ||
|
|
||
| const guild = container.client.guilds.cache.get(guildId); | ||
| if (!guild) return response.error(HttpCodes.BadRequest); | ||
|
|
||
| const member = await guild.members.fetch(request.auth!.id).catch(() => null); | ||
| if (!member) return response.error(HttpCodes.BadRequest); | ||
|
|
||
| if (!(await canManage(guild, member))) return response.error(HttpCodes.Forbidden); | ||
|
|
||
| const take = Math.min(Number(request.query.take) || 50, 100); | ||
| const skip = Math.max(Number(request.query.skip) || 0, 0); | ||
|
|
||
| const [results, total] = await Promise.all([ | ||
| container.prisma.auditLog.findMany({ | ||
| where: { guildId }, | ||
| orderBy: { createdAt: 'desc' }, | ||
| take, | ||
| skip | ||
| }), | ||
| container.prisma.auditLog.count({ | ||
| where: { guildId } | ||
| }) | ||
| ]); | ||
|
|
||
| return response.status(HttpCodes.OK).json({ entries: results, total }); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,6 +2,7 @@ import { authenticated, canManage, ratelimit } from '#lib/api/utils'; | |
| import { | ||
| getConfigurableKeys, | ||
| isSchemaKey, | ||
| readSettingsAuditLog, | ||
| serializeSettings, | ||
| writeSettingsTransaction, | ||
| type GuildDataValue, | ||
|
|
@@ -37,7 +38,15 @@ export class UserRoute extends Route { | |
| try { | ||
| using trx = await writeSettingsTransaction(guild); | ||
| const data = await this.validateAll(trx.settings, guild, entries); | ||
| await trx.write(Object.fromEntries(data)).submit(); | ||
| const settingsData = Object.fromEntries(data); | ||
|
|
||
| // Capture current settings for audit log before mutation | ||
| const auditLog = readSettingsAuditLog(structuredClone(trx.settings)); | ||
|
|
||
| await trx.write(settingsData).submit(); | ||
|
|
||
| // Fire-and-forget audit log write | ||
| auditLog.update(request.auth!.id, settingsData).catch(() => null); | ||
|
Comment on lines
+43
to
+49
|
||
|
|
||
| return this.sendSettings(response, trx.settings); | ||
| } catch (errors) { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
readSettingsAuditLog()returns the cachedSettingsContext.auditLoginstance keyed bysettings.id. This makes it unsuitable for callers that expect a snapshot-based manager (e.g., passing a cloned settings object), because it will still return the shared per-guild instance whose internal#settingsreference is updated on every settings patch. Consider returning a newAuditLogManager(settings)here (or adding a separate helper likecreateSettingsAuditLogSnapshotfor non-cached instances) so audit logs can reliably compare against the provided settings object.