Skip to content
9 changes: 5 additions & 4 deletions packages/backend/src/routes/management.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
autoModService,
customCommandService,
serverLogService,
serializeServerLog,
type LogType,
} from '@lucky/shared/services'
import { setupEmbedRoutes } from './managementEmbeds'
Expand Down Expand Up @@ -258,13 +259,13 @@ export function setupManagementRoutes(app: Express): void {
guildId,
type as LogType,
)
res.json({ logs, total })
res.json({ logs: logs.map(serializeServerLog), total })
return
}

const logs = await serverLogService.getRecentLogs(guildId, limit)
const total = await serverLogService.countRecentLogs(guildId)
res.json({ logs, total })
res.json({ logs: logs.map(serializeServerLog), total })
}),
)

Expand All @@ -281,7 +282,7 @@ export function setupManagementRoutes(app: Express): void {
type: query.type as LogType | undefined,
userId: query.userId,
})
res.json({ logs })
res.json({ logs: logs.map(serializeServerLog) })
}),
)

Expand All @@ -294,7 +295,7 @@ export function setupManagementRoutes(app: Express): void {
const guildId = p(req.params.guildId)
const userId = p(req.params.userId)
const logs = await serverLogService.getUserLogs(guildId, userId)
res.json({ logs })
res.json({ logs: logs.map(serializeServerLog) })
}),
)

Expand Down
3 changes: 3 additions & 0 deletions packages/backend/tests/integration/routes/management.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ jest.mock('../../../src/services/GuildAccessService', () => ({
}))

jest.mock('@lucky/shared/services', () => ({
// Route-wiring test: pass logs through unchanged. The real serializer's
// behaviour is covered by ServerLogService.spec.ts.
serializeServerLog: (log: unknown) => log,
AutoModTemplateNotFoundError: class AutoModTemplateNotFoundError extends Error {
readonly code = 'ERR_AUTOMOD_TEMPLATE_NOT_FOUND'

Expand Down
114 changes: 114 additions & 0 deletions packages/shared/src/services/ServerLogService.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { describe, expect, it, jest } from '@jest/globals'

jest.mock('../utils/database/prismaClient', () => ({
getPrismaClient: () => ({ serverLog: {} }),
}))

import { serializeServerLog, LOG_LEVEL_BY_TYPE } from './ServerLogService'

describe('serializeServerLog', () => {
const createdAt = new Date('2026-07-02T16:00:00.000Z')

it('derives level from type and uses action as the message', () => {
const result = serializeServerLog({
id: 'log-1',
guildId: 'g1',
type: 'message_delete',
action: 'Message deleted',
userId: 'u1',
channelId: 'c1',
details: JSON.stringify({ messageId: 'm1', content: 'hi' }),
createdAt,
})

expect(result.level).toBe('moderation')
expect(result.message).toBe('Message deleted')
expect(result.type).toBe('message_delete')
expect(result.createdAt).toBe('2026-07-02T16:00:00.000Z')
expect(result.metadata).toEqual({ messageId: 'm1', content: 'hi' })
})

it('falls back to level "info" for unknown types', () => {
expect(
serializeServerLog({
id: 'x',
guildId: 'g',
type: 'totally_unknown_event',
action: 'Something',
createdAt,
}).level,
).toBe('info')
})

it('parses stringified details and surfaces details.username as userName', () => {
const result = serializeServerLog({
id: 'log-2',
guildId: 'g1',
type: 'member_join',
action: 'Member joined',
userId: 'u9',
details: JSON.stringify({ username: 'Alice' }),
createdAt,
})
expect(result.userName).toBe('Alice')
expect(result.level).toBe('info')
})

it('falls back to userId when details has no username so actor is never blank', () => {
const result = serializeServerLog({
id: 'log-3',
guildId: 'g1',
type: 'role_update',
action: 'Roles updated',
userId: 'u42',
details: JSON.stringify({ addedRoles: ['r1'], removedRoles: [] }),
createdAt,
})
expect(result.userName).toBe('u42')
expect(result.level).toBe('info')
expect(result.message).toBe('Roles updated')
})

it('treats an empty-string username as absent and falls back to userId', () => {
const result = serializeServerLog({
id: 'log-4',
guildId: 'g1',
type: 'role_update',
action: 'Roles updated',
userId: 'u77',
details: JSON.stringify({ username: '' }),
createdAt,
})
expect(result.userName).toBe('u77')
})

it('tolerates already-parsed object details and null details', () => {
expect(
serializeServerLog({
id: 'a',
guildId: 'g',
type: 'settings_change',
action: 'Settings changed',
details: { setting: 'x' },
createdAt,
}).metadata,
).toEqual({ setting: 'x' })

expect(
serializeServerLog({
id: 'b',
guildId: 'g',
type: 'settings_change',
action: null,
details: null,
createdAt,
}).message,
).toBe('')
})

it('maps known types to expected levels', () => {
expect(LOG_LEVEL_BY_TYPE.automod_trigger).toBe('automod')
expect(LOG_LEVEL_BY_TYPE.mod_action).toBe('moderation')
expect(LOG_LEVEL_BY_TYPE.custom_command).toBe('system')
})
})
108 changes: 108 additions & 0 deletions packages/shared/src/services/ServerLogService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,114 @@ export interface LogDetails {
[key: string]: unknown
}

/** Presentation severity/category bucket for a log, derived from its type. */
export type ServerLogLevel =
| 'info'
| 'warn'
| 'error'
| 'moderation'
| 'automod'
| 'system'

/** Maps a raw log `type` to the level bucket the dashboard groups/filters by. */
export const LOG_LEVEL_BY_TYPE: Record<string, ServerLogLevel> = {
message_delete: 'moderation',
message_edit: 'moderation',
member_join: 'info',
member_leave: 'info',
role_update: 'info',
channel_update: 'system',
voice_state: 'info',
mod_action: 'moderation',
mod_case_update: 'moderation',
automod_trigger: 'automod',
automod_settings: 'automod',
custom_command: 'system',
embed_template: 'system',
auto_message: 'system',
settings_change: 'system',
}

/** Shape the dashboard expects for each log row. */
export interface SerializedServerLog {
id: string
guildId: string
type: string
level: ServerLogLevel
message: string
userId?: string
userName?: string
channelId?: string
channelName?: string
metadata: Record<string, unknown>
createdAt: string
}

/** `details` is persisted as a JSON string; parse it back to an object safely. */
function parseLogDetails(details: unknown): Record<string, unknown> {
if (details == null) {
return {}
}
if (typeof details === 'string') {
try {
const parsed: unknown = JSON.parse(details)
return parsed && typeof parsed === 'object'
? (parsed as Record<string, unknown>)
: {}
} catch {
return {}
}
}
if (typeof details === 'object') {
return details as Record<string, unknown>
}
return {}
}

/**
* Maps a raw persisted log row to the dashboard contract: derives `level` from
* `type`, uses `action` as the human `message`, and surfaces user/channel names
* from `details` (falling back to the id so the actor is never blank).
*/
export function serializeServerLog(log: {
id: string
guildId: string
type: string
action?: string | null
userId?: string | null
channelId?: string | null
details?: unknown
createdAt: Date | string
}): SerializedServerLog {
const metadata = parseLogDetails(log.details)
// Treat empty strings as absent so the id fallback below still fires
// (keeps the actor/channel from rendering blank).
const userName =
typeof metadata.username === 'string' && metadata.username
? metadata.username
: undefined
const channelName =
typeof metadata.channelName === 'string' && metadata.channelName
? metadata.channelName
: undefined
return {
id: log.id,
guildId: log.guildId,
type: log.type,
level: LOG_LEVEL_BY_TYPE[log.type] ?? 'info',
message: log.action ?? '',
userId: log.userId ?? undefined,
userName: userName ?? log.userId ?? undefined,
channelId: log.channelId ?? undefined,
channelName: channelName ?? log.channelId ?? undefined,
metadata,
createdAt:
log.createdAt instanceof Date
? log.createdAt.toISOString()
: log.createdAt,
}
}
Comment thread
LucasSantana-Dev marked this conversation as resolved.
Resolved

/** Service for creating and querying server audit logs persisted in the database. */
export class ServerLogService {
/** Creates a new audit log entry for the given guild. */
Expand Down
Loading