Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/audit-hash.ts
T

215 lines
6.6 KiB
TypeScript

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 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`; when neither is set the helper falls
* back to plain SHA-256 (still tamper-evident for read-only attackers but
* not forgery-resistant).
*/
secret?: string | null;
};
/**
* 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<string, unknown>)
.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).
* - Otherwise falls back to plain SHA-256(previousHash || canonicalPayload).
*/
export function computeAuditHash(args: ComputeAuditHashArgs): string {
const canonical = canonicalizeAuditPayload(args.payload);
const input = `${args.previousHash ?? ""}\n${canonical}`;
const secret = resolveSecret(args.secret);
if (secret) {
return createHmac("sha256", secret).update(input, "utf8").digest("hex");
}
return createHash("sha256").update(input, "utf8").digest("hex");
}
function resolveSecret(explicit: string | null | undefined): string | null {
if (typeof explicit === "string" && explicit.length > 0) {
return explicit;
}
if (explicit === null) {
return null;
}
const fromEnv = process.env[AUDIT_CHAIN_SECRET_ENV];
if (typeof fromEnv === "string" && fromEnv.length > 0) {
return fromEnv;
}
return null;
}
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<AuditChainEvent>,
options: { secret?: string | null } = {}
): VerifyAuditChainResult {
let inspected = 0;
let lastHash: string | null = 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 recomputed = computeAuditHash({
previousHash: event.previousHash,
payload: stripChainFields(event),
secret: options.secret,
});
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 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,
};
}