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
+13
View File
@@ -0,0 +1,13 @@
CREATE TABLE "audit_log" (
"id" text PRIMARY KEY NOT NULL,
"actor_id" text NOT NULL,
"actor_ip_hash" text,
"action" text NOT NULL,
"entity_type" text NOT NULL,
"entity_id" text,
"before_json" text DEFAULT '' NOT NULL,
"after_json" text DEFAULT '' NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE INDEX "audit_log_created_idx" ON "audit_log" USING btree ("created_at");
+41
View File
@@ -0,0 +1,41 @@
import { describe, test, expect } from "vitest";
import { auditRow } from "@/db/audit";
/** UUIDv7 (RFC 9562): version nibble is 7, variant nibble is 8/9/a/b. */
const V7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
describe("auditRow", () => {
test("builds an append-only audit row with a uuidv7 id and an injected createdAt", () => {
const now = new Date("2026-11-18T12:00:00.000Z");
const row = auditRow({
actorId: "admin-1",
action: "assignment.created",
entityType: "assignment",
entityId: "assign-abc",
before: { slotId: "slot-1" },
after: { slotId: "slot-1", userId: "user-2" },
now,
});
expect(row.id).toMatch(V7);
expect(row.actorId).toBe("admin-1");
expect(row.action).toBe("assignment.created");
expect(row.entityType).toBe("assignment");
expect(row.entityId).toBe("assign-abc");
expect(row.createdAt).toEqual(now);
expect(row.beforeJson).toBe(JSON.stringify({ slotId: "slot-1" }));
expect(row.afterJson).toBe(JSON.stringify({ slotId: "slot-1", userId: "user-2" }));
});
test("serializes omitted before/after as empty strings", () => {
const row = auditRow({
actorId: "admin-1",
action: "assignment.cleared",
entityType: "assignment",
entityId: "assign-abc",
});
expect(row.beforeJson).toBe("");
expect(row.afterJson).toBe("");
});
});
+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;
}
+25
View File
@@ -295,6 +295,30 @@ export const assignments = pgTable(
],
);
/* ----------------------------------------------------------- audit log (D8) */
/**
* Append-only audit trail (ARCHITECTURE §638, BUILD-SPEC §7 rule 12).
* Every admin mutation writes one row here; the app never updates or deletes
* a row. `before_json` / `after_json` capture the before/after of the change
* (empty string when there is none); `created_at` is a UTC instant.
*/
export const auditLog = pgTable("audit_log", {
id: text("id").primaryKey(),
actorId: text("actor_id").notNull(),
actorIpHash: text("actor_ip_hash"),
action: text("action").notNull(),
entityType: text("entity_type").notNull(),
entityId: text("entity_id"),
beforeJson: text("before_json").notNull().default(""),
afterJson: text("after_json").notNull().default(""),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [index("audit_log_created_idx").on(table.createdAt)],
);
/* ------------------------------------------------- unavailability (D4) */
/**
@@ -736,6 +760,7 @@ export const schema = {
serviceInstances,
slots,
assignments,
auditLog,
unavailability,
skillCategories,
vendors,