import { createHash, createHmac } from "node:crypto"; /** * Tamper-evident hash chain for AuditEvent rows. * * Each event's `eventHash` is derived from the previous event's `eventHash` * plus a canonical JSON encoding of the event payload. A platform-level * secret (`AUDIT_CHAIN_SECRET`) is HMAC-mixed in so a DB-only attacker * cannot forge a continuation of the chain without also stealing the * secret — see docs/compliance/audit-trails.md. * * The canonical encoding sorts object keys recursively and stringifies * with no whitespace so two semantically-equivalent payloads always hash * to the same digest regardless of insertion order. */ export const AUDIT_CHAIN_SECRET_ENV = "AUDIT_CHAIN_SECRET"; export const AUDIT_CHAIN_SECRET_MIN_BYTES = 32; export const AUDIT_HASH_V2_PREFIX = "v2:"; export type AuditHashVersion = "legacy-v1" | "hmac-v2"; export class AuditChainSecretError extends Error { override readonly name = "AuditChainSecretError"; constructor() { super(`${AUDIT_CHAIN_SECRET_ENV} must contain at least ${AUDIT_CHAIN_SECRET_MIN_BYTES} UTF-8 bytes in production.`); } } export type AuditHashPayload = { /** Stable identifier of the event (`AuditEvent.id`). */ id: string; /** ISO-8601 createdAt of the event. */ createdAt: string; /** Tenant scope (null = platform-level). */ tenantId: string | null; /** Actor type (user | admin | api_key | system | plugin). */ actorType: string; /** Actor identifier (null for system). */ actorId: string | null; actorEmail: string | null; actorIp: string | null; actorUserAgent: string | null; action: string; targetType: string | null; targetId: string | null; requestId: string | null; sourceModule: string | null; outcome: string; dataSensitivity: string; regulatoryScope: string[]; metadata: unknown; }; export type ComputeAuditHashArgs = { previousHash: string | null; payload: AuditHashPayload; /** * Optional explicit secret. When omitted the helper reads * `process.env.AUDIT_CHAIN_SECRET`. Production requires at least 32 bytes; * only development and tests may fall back to plain SHA-256. */ secret?: string | null; /** New persisted events use hmac-v2; legacy-v1 remains verifier-only compatibility. */ version?: AuditHashVersion; }; /** * Canonical JSON encoding: sort keys recursively, no whitespace, strict * UTF-8 output. Arrays preserve order (chain payloads only contain * deterministic arrays). */ export function canonicalizeAuditPayload(payload: unknown): string { return JSON.stringify(sortValue(payload)); } function sortValue(value: unknown): unknown { if (value === null || value === undefined) { return null; } if (Array.isArray(value)) { return value.map(sortValue); } if (typeof value === "object") { const entries = Object.entries(value as Record) .filter(([, v]) => v !== undefined) .map(([k, v]) => [k, sortValue(v)] as const) .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); return Object.fromEntries(entries); } return value; } /** * Compute the eventHash for a single event given its predecessor's hash. * * - When `AUDIT_CHAIN_SECRET` is set (env or explicit), uses * HMAC-SHA-256(secret, previousHash || canonicalPayload). * - Outside production only, otherwise falls back to plain SHA-256. */ export function computeAuditHash(args: ComputeAuditHashArgs): string { const canonical = canonicalizeAuditPayload(args.payload); const input = `${args.previousHash ?? ""}\n${canonical}`; const secret = resolveAuditChainSecret(args.secret); const version = args.version ?? "legacy-v1"; let digest: string; if (secret) { digest = createHmac("sha256", secret).update(input, "utf8").digest("hex"); } else { digest = createHash("sha256").update(input, "utf8").digest("hex"); } return version === "hmac-v2" ? `${AUDIT_HASH_V2_PREFIX}${digest}` : digest; } export function resolveAuditChainSecret( explicit: string | null | undefined, env: Readonly> = process.env, ): string | null { const candidate = explicit === undefined ? env[AUDIT_CHAIN_SECRET_ENV] : explicit; const secret = typeof candidate === "string" && candidate.length > 0 ? candidate : null; if (env.NODE_ENV === "production" && (!secret || Buffer.byteLength(secret, "utf8") < AUDIT_CHAIN_SECRET_MIN_BYTES)) { throw new AuditChainSecretError(); } return secret; } export function isAuditProductionRuntime( env: Readonly> = process.env, ): boolean { return env.NODE_ENV === "production"; } /** Checkpoints are always HMAC-authenticated, including in development and tests. */ export function requireAuditChainSecret( explicit: string | null | undefined, env: Readonly> = process.env, ): string { const secret = resolveAuditChainSecret(explicit, env); if (!secret || Buffer.byteLength(secret, "utf8") < AUDIT_CHAIN_SECRET_MIN_BYTES) { throw new AuditChainSecretError(); } return secret; } export type AuditChainEvent = AuditHashPayload & { previousHash: string | null; eventHash: string | null; }; export type AuditChainBreak = { eventId: string; expectedHash: string; actualHash: string | null; expectedPreviousHash: string | null; actualPreviousHash: string | null; reason: "hash-mismatch" | "previous-hash-mismatch" | "missing-hash"; }; export type VerifyAuditChainResult = { ok: boolean; inspected: number; firstBreak: AuditChainBreak | null; }; /** * Re-compute hashes for an ordered sequence of audit events (oldest → * newest) and report the first break in the chain. * * Events without `eventHash` set are treated as pre-migration history and * skipped silently — they predate the chain. The first event with a hash * anchors the chain (its `previousHash` is compared against the prior * event's `eventHash`, or `null` if it is the chain root). */ export function verifyAuditChain( events: ReadonlyArray, options: { secret?: string | null; initialPreviousHash?: string | null } = {} ): VerifyAuditChainResult { let inspected = 0; let lastHash: string | null = options.initialPreviousHash ?? null; for (const event of events) { if (event.eventHash === null) { // Pre-chain history: still update lastHash to null sentinel. lastHash = null; continue; } inspected += 1; if (event.previousHash !== lastHash) { return { ok: false, inspected, firstBreak: { eventId: event.id, expectedHash: event.eventHash, actualHash: event.eventHash, expectedPreviousHash: lastHash, actualPreviousHash: event.previousHash, reason: "previous-hash-mismatch", }, }; } const isV2 = event.eventHash.startsWith(AUDIT_HASH_V2_PREFIX); let recomputed = computeAuditHash({ previousHash: event.previousHash, payload: isV2 ? stripChainFields(event) : toLegacyHashPayload(event), secret: options.secret, version: isV2 ? "hmac-v2" : "legacy-v1", }); // Two unversioned formats existed before v2: production writers used // id/createdAt sentinels, while an early verifier/test contract hashed the // stored values. Accept both for historical rows; all new writes are v2. if (!isV2 && recomputed !== event.eventHash) { const legacyStoredFieldsHash = computeAuditHash({ previousHash: event.previousHash, payload: stripChainFields(event), secret: options.secret, version: "legacy-v1", }); if (legacyStoredFieldsHash === event.eventHash) recomputed = legacyStoredFieldsHash; } if (recomputed !== event.eventHash) { return { ok: false, inspected, firstBreak: { eventId: event.id, expectedHash: recomputed, actualHash: event.eventHash, expectedPreviousHash: event.previousHash, actualPreviousHash: event.previousHash, reason: "hash-mismatch", }, }; } lastHash = event.eventHash; } return { ok: true, inspected, firstBreak: null }; } function toLegacyHashPayload(event: AuditChainEvent): AuditHashPayload { return { ...stripChainFields(event), id: "", createdAt: "" }; } function stripChainFields(event: AuditChainEvent): AuditHashPayload { // `previousHash` and `eventHash` are NOT part of the payload digest. return { id: event.id, createdAt: event.createdAt, tenantId: event.tenantId, actorType: event.actorType, actorId: event.actorId, actorEmail: event.actorEmail, actorIp: event.actorIp, actorUserAgent: event.actorUserAgent, action: event.action, targetType: event.targetType, targetId: event.targetId, requestId: event.requestId, sourceModule: event.sourceModule, outcome: event.outcome, dataSensitivity: event.dataSensitivity, regulatoryScope: event.regulatoryScope, metadata: event.metadata, }; }