Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/plugin-runtime/src/audit-chain.ts
T

204 lines
6.6 KiB
TypeScript

/**
* F-003 — Per-tenant hash chain over PluginCapabilityUse rows.
*
* Each row carries:
* - `prevHash` : the `rowHash` of the immediately preceding row in
* this tenant's chain (or NULL for the genesis row).
* - `rowHash` : SHA-256(prevHash || canonical(row)).
*
* The chain is per-tenant (not global) so a noisy tenant doesn't
* serialise every other tenant's insert path. The worker handler
* computes the chain inside `pluginCapabilityUseChain.stamp(...)` and
* persists both columns; the verifier in `verifyPluginCapabilityUseChain`
* walks an ordered slice and reports any break.
*
* Tampering detection is deterministic: any modification to a row
* changes its `rowHash`, which changes every subsequent `prevHash`,
* which changes every subsequent `rowHash` — the verifier sees a
* cascade of breaks starting at the modified row. A *deleted* row
* leaves the next row's `prevHash` referencing a hash that no longer
* exists in the chain head, which the verifier flags as `prev_mismatch`.
*
* The canonical form is a stable string built from a fixed field list
* (deterministic ordering). New columns added later must be appended to
* the field list, never inserted in the middle — that would invalidate
* every existing hash.
*/
import { createHash } from "node:crypto";
/**
* The fields included in the canonical form, in the EXACT order they
* are hashed. Appending new fields at the end is forward-compatible;
* reordering or inserting in the middle is a CHAIN-BREAKING change and
* must be paired with a re-stamping migration.
*/
export const CHAIN_FIELDS = [
"id",
"pluginInvocationId",
"tenantId",
"pluginId",
"capability",
"payloadHash",
"outcome",
"errorCode",
"durationMs",
"timestamp",
] as const;
export type PluginCapabilityUseChainRow = {
readonly id: string;
readonly pluginInvocationId: string;
readonly tenantId: string;
readonly pluginId: string;
readonly capability: string;
readonly payloadHash?: string | null;
readonly outcome: string;
readonly errorCode?: string | null;
readonly durationMs?: number | null;
/** ISO-8601 string at canonicalisation time. */
readonly timestamp: string;
};
const NULL_MARKER = ""; // disambiguates "" from null/undefined inside the canonical form
function canonicalField(value: unknown): string {
if (value === null || value === undefined) return NULL_MARKER;
if (typeof value === "number") {
if (!Number.isFinite(value)) return NULL_MARKER;
return String(value);
}
return String(value);
}
/**
* Build the canonical form of a row. Joins each CHAIN_FIELDS value with
* a U+001F (unit separator) so values like `foo|bar` and `foo` followed
* by `bar` cannot collide.
*/
export function canonicalisePluginCapabilityUseRow(
row: PluginCapabilityUseChainRow,
): string {
const indexable = row as unknown as Record<string, unknown>;
return CHAIN_FIELDS.map((key) => canonicalField(indexable[key])).join("");
}
/**
* Compute one row hash. `prevHash` may be null/undefined for the
* genesis row. SHA-256 hex digest, 64 chars.
*/
export function computeRowHash(
prevHash: string | null | undefined,
row: PluginCapabilityUseChainRow,
): string {
const h = createHash("sha256");
h.update(prevHash ?? "");
h.update(""); // record separator between prev and row
h.update(canonicalisePluginCapabilityUseRow(row));
return h.digest("hex");
}
/**
* Stamp a batch of rows with `prevHash` + `rowHash`, threading the
* `seedPrevHash` through the chain. Returns the stamped rows AND the
* new chain head (the last row's `rowHash`) so the worker can persist
* the head for the next batch.
*
* The function is pure — does not touch the DB. The worker calls it
* after reading the chain head from the DB and before insertMany.
*/
export type StampedRow = PluginCapabilityUseChainRow & {
readonly prevHash: string | null;
readonly rowHash: string;
};
export function stampPluginCapabilityUseChain(args: {
seedPrevHash: string | null;
rows: ReadonlyArray<PluginCapabilityUseChainRow>;
}): { stamped: ReadonlyArray<StampedRow>; chainHead: string | null } {
if (args.rows.length === 0) {
return { stamped: [], chainHead: args.seedPrevHash };
}
const stamped: StampedRow[] = [];
let prev = args.seedPrevHash;
for (const row of args.rows) {
const rowHash = computeRowHash(prev, row);
stamped.push({ ...row, prevHash: prev, rowHash });
prev = rowHash;
}
return { stamped, chainHead: prev };
}
/**
* Walk an ordered slice of rows and report the first break, if any.
* Rows MUST be ordered by `(tenantId, timestamp ASC, id ASC)`. Pre-F-003
* rows (both `prevHash` and `rowHash` are null) are skipped without
* being treated as breaks.
*
* Returns `{ ok: true, rowsVerified }` when the entire slice is
* consistent, or `{ ok: false, ... }` with details on the first break.
*/
export type ChainBreakReason =
| "row_hash_mismatch"
| "prev_mismatch"
| "missing_row_hash"
| "missing_prev_hash";
export type VerifyChainResult =
| { ok: true; rowsVerified: number }
| {
ok: false;
reason: ChainBreakReason;
brokenRowId: string;
brokenRowIndex: number;
expected?: string;
actual?: string;
};
export function verifyPluginCapabilityUseChain(
rows: ReadonlyArray<PluginCapabilityUseChainRow & { prevHash?: string | null; rowHash?: string | null }>,
): VerifyChainResult {
let prevHashTail: string | null = null;
let prevSeen = false;
let rowsVerified = 0;
for (let i = 0; i < rows.length; i++) {
const row = rows[i]!;
const hasHashes = row.rowHash !== null && row.rowHash !== undefined;
if (!hasHashes) {
// pre-F-003 row: skip, but if the next row carries a hash we have
// no valid prev to compare against — the verifier reports OK for
// the pre-chain prefix and starts verifying at the first hashed
// row by accepting whatever its prevHash claims.
prevSeen = false;
continue;
}
if (prevSeen && row.prevHash !== prevHashTail) {
return {
ok: false,
reason: "prev_mismatch",
brokenRowId: row.id,
brokenRowIndex: i,
expected: prevHashTail ?? "(null)",
actual: row.prevHash ?? "(null)",
};
}
const expectedHash = computeRowHash(row.prevHash ?? null, row);
if (expectedHash !== row.rowHash) {
return {
ok: false,
reason: "row_hash_mismatch",
brokenRowId: row.id,
brokenRowIndex: i,
expected: expectedHash,
actual: row.rowHash ?? "(null)",
};
}
prevHashTail = row.rowHash ?? null;
prevSeen = true;
rowsVerified += 1;
}
return { ok: true, rowsVerified };
}