Files
crosscode-platform/apps/accounts/backend/src/lib/audit.ts
T
joshuaandClaude Opus 5.5 069b66fd30 Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and
back-channel logout; clients are the linked products (Connect). Sign-in
steps (password, sign-up, email check, 2FA and its setup, privacy notice,
news question, password reset) survive to the product. Account page and
admin API, church profile, export and deletion fan-out, Hub v2 client,
jobs. End-to-end tests with a test product on openid-client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:33:49 +02:00

49 lines
1.9 KiB
TypeScript

/**
* 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);
}
}