unit(D8): audit_log table + migration + audit-row builder (rule 12)

This commit is contained in:
Tiel Coder
2026-11-18 18:25:30 +00:00
parent 6982a8040d
commit b664de65f5
4 changed files with 150 additions and 0 deletions
+71
View File
@@ -0,0 +1,71 @@
import { auditLog } from "./schema";
import { uuidv7 } from "@/lib/uuid";
/**
* Audit-log helpers — unit D8 (BUILD-SPEC §7 rule 12: every admin mutation
* writes an audit row).
*
* `auditRow()` is pure: it builds the row object (uuidv7 id, JSON payloads,
* an injectable `now`) so it can be unit-tested without a database.
* `writeAudit()` takes the Drizzle client as a parameter (dependency
* injected) and inserts the row; the app never updates or deletes a row.
*/
export interface AuditRow {
id: string;
actorId: string;
actorIpHash: string | null;
action: string;
entityType: string;
entityId: string | null;
beforeJson: string;
afterJson: string;
createdAt: Date;
}
export interface AuditInput {
actorId: string;
action: string;
entityType: string;
entityId?: string | null;
actorIpHash?: string | null;
before?: Record<string, unknown>;
after?: Record<string, unknown>;
/** Injectable UTC instant (defaults to now) so tests are deterministic. */
now?: Date;
}
/** Build an append-only audit row. Pure — no database. */
export function auditRow(input: AuditInput): AuditRow {
return {
id: uuidv7(),
actorId: input.actorId,
actorIpHash: input.actorIpHash ?? null,
action: input.action,
entityType: input.entityType,
entityId: input.entityId ?? null,
beforeJson: input.before ? JSON.stringify(input.before) : "",
afterJson: input.after ? JSON.stringify(input.after) : "",
createdAt: input.now ?? new Date(),
};
}
/** Insert an audit row via the injected Drizzle client. */
export async function writeAudit(
db: typeof import("./db").db,
input: AuditInput,
): Promise<AuditRow> {
const row = auditRow(input);
await db.insert(auditLog).values({
id: row.id,
actorId: row.actorId,
actorIpHash: row.actorIpHash,
action: row.action,
entityType: row.entityType,
entityId: row.entityId,
beforeJson: row.beforeJson,
afterJson: row.afterJson,
createdAt: row.createdAt,
});
return row;
}