|
| 1 | +import type { Database } from "@openpims/db/client"; |
| 2 | +import { auditLog } from "@openpims/db"; |
| 3 | + |
| 4 | +/** |
| 5 | + * Audit logging for mutations. The pure helpers (path parsing, secret |
| 6 | + * redaction, entity-id extraction) are unit-tested; recordAuditLog performs the |
| 7 | + * best-effort insert and must never throw into the request path. |
| 8 | + */ |
| 9 | + |
| 10 | +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; |
| 11 | +const SECRET_KEY_RE = /pass(word)?|secret|token|keyhash|^key$|apikey/i; |
| 12 | + |
| 13 | +/** "clients.create" -> { entityType: "clients", action: "create" }. */ |
| 14 | +export function parseAuditPath(path: string): { entityType: string; action: string } { |
| 15 | + const dot = path.indexOf("."); |
| 16 | + const entityType = (dot === -1 ? path : path.slice(0, dot)).slice(0, 64); |
| 17 | + const action = (dot === -1 ? "" : path.slice(dot + 1)).slice(0, 64); |
| 18 | + return { entityType, action }; |
| 19 | +} |
| 20 | + |
| 21 | +/** Shallow-redact secret-ish fields so they never land in the audit trail. */ |
| 22 | +export function redactSecrets(input: unknown): Record<string, unknown> | null { |
| 23 | + if (!input || typeof input !== "object" || Array.isArray(input)) { |
| 24 | + return input == null ? null : { value: "[redacted-nonobject]" }; |
| 25 | + } |
| 26 | + const out: Record<string, unknown> = {}; |
| 27 | + for (const [k, v] of Object.entries(input as Record<string, unknown>)) { |
| 28 | + out[k] = SECRET_KEY_RE.test(k) ? "[redacted]" : v; |
| 29 | + } |
| 30 | + return out; |
| 31 | +} |
| 32 | + |
| 33 | +/** Best-effort entity id: prefer the created/updated row's id, else input.id. */ |
| 34 | +export function extractEntityId(rawInput: unknown, resultData: unknown): string | null { |
| 35 | + const fromResult = (resultData as { id?: unknown } | null)?.id; |
| 36 | + if (typeof fromResult === "string" && UUID_RE.test(fromResult)) return fromResult; |
| 37 | + const fromInput = (rawInput as { id?: unknown } | null)?.id; |
| 38 | + if (typeof fromInput === "string" && UUID_RE.test(fromInput)) return fromInput; |
| 39 | + return null; |
| 40 | +} |
| 41 | + |
| 42 | +export async function recordAuditLog( |
| 43 | + db: Database, |
| 44 | + opts: { |
| 45 | + practiceId: string; |
| 46 | + userId: string; |
| 47 | + ip?: string | null; |
| 48 | + path: string; |
| 49 | + rawInput: unknown; |
| 50 | + resultData: unknown; |
| 51 | + } |
| 52 | +): Promise<void> { |
| 53 | + try { |
| 54 | + const { entityType, action } = parseAuditPath(opts.path); |
| 55 | + await db.insert(auditLog).values({ |
| 56 | + practiceId: opts.practiceId, |
| 57 | + userId: opts.userId, |
| 58 | + action, |
| 59 | + entityType, |
| 60 | + entityId: extractEntityId(opts.rawInput, opts.resultData), |
| 61 | + changes: redactSecrets(opts.rawInput), |
| 62 | + ipAddress: opts.ip ?? null, |
| 63 | + }); |
| 64 | + } catch (err) { |
| 65 | + // Auditing must never break the request it's recording. |
| 66 | + console.error("[audit] failed to record:", err); |
| 67 | + } |
| 68 | +} |
0 commit comments