Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,188 @@
/**
* Phase 10 Task #67 — Audit-event outbox handler.
*
* Subscribes to the `outbox.audit` BullMQ queue (populated by the
* outbox dispatcher in apps/worker/src/outbox/dispatcher.ts) and
* inserts the AuditEvent row into Postgres.
*
* The hash chain is computed inside a short Prisma transaction:
* - SELECT the most-recent eventHash for the tenant (FOR UPDATE
* equivalent via serializable isolation)
* - compute the new event's eventHash
* - INSERT the new row
*
* Running this under serializable isolation ensures concurrent persists
* for the same tenant either commit in some order with a coherent
* chain, or one of them retries on serialization-failure. The handler
* is therefore safe to invoke from N parallel BullMQ workers without
* corrupting the chain.
*
* Idempotency: the producer-side `publishAuditEventViaOutbox` writes
* one outbox row per business-write. The dispatcher delivers each row
* exactly once (claim+ack); on retry we may re-process the same
* payload but the audit insert is a plain CREATE — duplicates simply
* extend the chain by one extra row. The acceptable outcome here is
* "at-least-once": a duplicated audit row is harmless evidence.
*/
import { computeAuditHash, type AuditHashPayload } from "@toolctrl/db/audit-hash";
import {
buildAuditEventCreateData,
type AuditEventCreateData,
type AuditEventInput,
} from "@toolctrl/db/audit-events.server";
export const AUDIT_EVENT_OUTBOX_QUEUE = "outbox.audit" as const;
export interface AuditEventPersistLogger {
info?: (record: Record<string, unknown>, message?: string) => void;
warn?: (record: Record<string, unknown>, message?: string) => void;
error: (record: Record<string, unknown>, message?: string) => void;
}
export interface AuditEventPersistTxClient {
auditEvent: {
findFirst(args: {
where: { tenantId: string | null; eventHash: { not: null } };
orderBy: { createdAt: "desc" };
select: { eventHash: true };
}): Promise<{ eventHash: string | null } | null>;
create(args: {
data: AuditEventCreateData & { previousHash: string | null; eventHash: string };
}): Promise<{ id: string; eventHash: string }>;
};
}
export interface AuditEventPersistTransactionRunner {
/**
* Run `fn` inside a Prisma transaction. Production wiring passes
* `prisma.$transaction` with isolationLevel="Serializable" so that
* the prevHash lookup + insert form an atomic chain link.
*/
<T>(fn: (tx: AuditEventPersistTxClient) => Promise<T>): Promise<T>;
}
export interface AuditEventPersistDependencies {
readonly runInTransaction: AuditEventPersistTransactionRunner;
readonly logger?: AuditEventPersistLogger;
/**
* Override the hash-chain secret resolution for tests. Production
* leaves this undefined so the helper reads `process.env.AUDIT_CHAIN_SECRET`.
*/
readonly secret?: string | null;
}
export class AuditEventPersistJobError extends Error {
override readonly name = "AuditEventPersistJobError";
readonly code: "INVALID_PAYLOAD" | "INVALID_EVENT_TYPE" | "MISSING_ACTION";
constructor(message: string, code: AuditEventPersistJobError["code"]) {
super(message);
this.code = code;
}
}
export interface AuditEventPersistJobData {
readonly outboxEventId?: string;
readonly tenantId: string | null;
readonly eventType: string;
readonly payload: AuditEventCreateData;
}
export interface AuditEventPersistResult {
readonly persisted: true;
readonly auditEventId: string;
readonly eventHash: string;
}
export function parseAuditEventPersistJob(data: unknown): AuditEventPersistJobData {
if (!data || typeof data !== "object") {
throw new AuditEventPersistJobError("audit-event persist job missing data envelope", "INVALID_PAYLOAD");
}
const envelope = data as Record<string, unknown>;
const eventType = typeof envelope.eventType === "string" ? envelope.eventType : "";
if (eventType !== "audit.event.create") {
throw new AuditEventPersistJobError(
`audit-event persist job rejected eventType ${JSON.stringify(eventType)}`,
"INVALID_EVENT_TYPE"
);
}
const rawPayload = envelope.payload;
if (!rawPayload || typeof rawPayload !== "object") {
throw new AuditEventPersistJobError("audit-event persist job missing payload", "INVALID_PAYLOAD");
}
const inner = rawPayload as Record<string, unknown>;
const action = typeof inner.action === "string" ? inner.action.trim() : "";
if (action.length === 0) {
throw new AuditEventPersistJobError("audit-event persist job missing action", "MISSING_ACTION");
}
// Re-run normalization in case the producer emitted an older payload
// shape — defensive. `buildAuditEventCreateData` is idempotent.
const normalized = buildAuditEventCreateData(inner as unknown as AuditEventInput);
return {
outboxEventId: typeof envelope.outboxEventId === "string" ? envelope.outboxEventId : undefined,
tenantId: typeof envelope.tenantId === "string" ? envelope.tenantId : null,
eventType,
payload: normalized,
};
}
function toHashPayload(data: AuditEventCreateData): AuditHashPayload {
return {
id: "",
createdAt: "",
tenantId: data.tenantId,
actorType: data.actorType,
actorId: data.actorId,
actorEmail: data.actorEmail,
actorIp: data.actorIp,
actorUserAgent: data.actorUserAgent,
action: data.action,
targetType: data.targetType,
targetId: data.targetId,
requestId: data.requestId,
sourceModule: data.sourceModule,
outcome: data.outcome,
dataSensitivity: data.dataSensitivity,
regulatoryScope: data.regulatoryScope,
metadata: data.metadata,
};
}
export async function runAuditEventPersistJob(
data: unknown,
deps: AuditEventPersistDependencies
): Promise<AuditEventPersistResult> {
const job = parseAuditEventPersistJob(data);
const payload = job.payload;
const result = await deps.runInTransaction(async (tx) => {
const prior = await tx.auditEvent.findFirst({
where: { tenantId: payload.tenantId, eventHash: { not: null } },
orderBy: { createdAt: "desc" },
select: { eventHash: true },
});
const previousHash = prior?.eventHash ?? null;
const eventHash = computeAuditHash({
previousHash,
payload: toHashPayload(payload),
secret: deps.secret,
});
const inserted = await tx.auditEvent.create({
data: { ...payload, previousHash, eventHash },
});
return { auditEventId: inserted.id, eventHash };
});
deps.logger?.info?.(
{
component: "audit-event-persist",
tenantId: payload.tenantId,
action: payload.action,
auditEventId: result.auditEventId,
outboxEventId: job.outboxEventId,
},
"audit-event persisted via outbox"
);
return { persisted: true, auditEventId: result.auditEventId, eventHash: result.eventHash };
}