/** * The admin audit log, the per-person sign-in log and the access log. Logging never breaks the * action it records. */ import type { Request } from 'express'; import type { Ctx } from '../context.js'; export function clientIp(req: Request | undefined): string | null { return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null; } export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) { try { await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } }); } catch (e) { console.error('[audit]', (e as Error).message); } } export type LoginEventType = | 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off' | 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created'; export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) { try { await ctx.db.loginEvent.create({ data: { accountId, type, clientId: extra.clientId ?? null, ip: clientIp(req), userAgent: req?.get('user-agent')?.slice(0, 300) ?? null, detail: (extra.detail ?? undefined) as never, createdAt: ctx.now(), }, }); } catch (e) { console.error('[login-event]', (e as Error).message); } } export async function accessLog(ctx: Ctx, actorId: string, targetId: string, action: 'view' | 'export', req?: Request) { try { await ctx.db.accessLog.create({ data: { actorId, targetId, action, ip: clientIp(req), createdAt: ctx.now() } }); } catch (e) { console.error('[access-log]', (e as Error).message); } }