diff --git a/backend/src/lib/__tests__/tamperChain.test.ts b/backend/src/lib/__tests__/tamperChain.test.ts new file mode 100644 index 00000000..029f3a30 --- /dev/null +++ b/backend/src/lib/__tests__/tamperChain.test.ts @@ -0,0 +1,187 @@ +import { + GENESIS_HASH, + TamperChainError, + canonicalStringify, + computeEntryHash, + createTamperChain, + resealChain, + validateInput, + verifyChain, + type AuditEventInput, + type SealedAuditEntry, +} from '../tamperChain'; + +const EV = (over: Partial = {}): AuditEventInput => ({ + actor: 'admin:1', + action: 'role.grant', + resource: 'user:7', + timestamp: '2026-11-24T00:00:00.000Z', + metadata: { ip: '127.0.0.1' }, + ...over, +}); + +describe('tamperChain - canonicalStringify', () => { + it('sorts object keys recursively', () => { + expect(canonicalStringify({ b: 2, a: { d: 4, c: 3 } })).toBe('{"a":{"c":3,"d":4},"b":2}'); + }); + + it('omits undefined values but keeps arrays ordered', () => { + expect(canonicalStringify({ x: undefined, y: [2, 1] })).toBe('{"y":[2,1]}'); + }); + + it('is stable for logically identical entries regardless of key insertion order', () => { + expect(canonicalStringify({ a: 1, b: 2 })).toBe(canonicalStringify({ b: 2, a: 1 })); + }); +}); + +describe('tamperChain - validateInput', () => { + it('accepts a valid input', () => { + expect(() => validateInput(EV())).not.toThrow(); + }); + + it('rejects empty actor / action / timestamp', () => { + expect(() => validateInput(EV({ actor: '' }))).toThrow(TamperChainError); + expect(() => validateInput(EV({ action: '' }))).toThrow(TamperChainError); + expect(() => validateInput(EV({ timestamp: '' }))).toThrow(TamperChainError); + }); +}); + +describe('tamperChain - createTamperChain', () => { + it('starts at the genesis hash and is empty', () => { + const c = createTamperChain(); + expect(c.head()).toBe(GENESIS_HASH); + expect(c.length()).toBe(0); + expect(c.entries()).toEqual([]); + }); + + it('seals entries with monotonic seq and correct links', () => { + const c = createTamperChain(); + const e1 = c.append(EV()); + const e2 = c.append(EV({ action: 'key.rotate', actor: 'admin:2' })); + expect(e1.seq).toBe(1); + expect(e1.prevHash).toBe(GENESIS_HASH); + expect(e2.seq).toBe(2); + expect(e2.prevHash).toBe(e1.hash); + expect(c.head()).toBe(e2.hash); + expect(c.length()).toBe(2); + }); + + it('produces a verifiable chain', () => { + const c = createTamperChain(); + c.append(EV()); + c.append(EV({ action: 'key.rotate' })); + c.append(EV({ action: 'user.suspend' })); + const report = c.verify(); + expect(report.valid).toBe(true); + expect(report.entriesChecked).toBe(3); + expect(report.issues).toEqual([]); + expect(report.headHash).toBe(c.head()); + }); + + it('emits metrics and logger hooks', () => { + const increments: string[] = []; + const logs: string[] = []; + const c = createTamperChain(undefined, { + metrics: { increment: (n) => increments.push(n) }, + logger: { info: (m) => logs.push(m) }, + }); + c.append(EV()); + c.verify(); + expect(increments).toContain('audit.chain.append.total'); + expect(increments).toContain('audit.chain.verify.valid'); + expect(logs).toContain('audit.chain.appended'); + }); + + it('returns defensive copies from entries()', () => { + const c = createTamperChain(); + c.append(EV()); + const snap = c.entries() as SealedAuditEntry[]; + snap[0].hash = 'tampered'; + expect(c.entries()[0].hash).not.toBe('tampered'); + }); +}); + +describe('tamperChain - verifyChain (failure modes)', () => { + it('rejects an empty chain', () => { + const report = verifyChain([]); + expect(report.valid).toBe(false); + expect(report.issues[0].code).toBe('EMPTY_CHAIN'); + }); + + it('detects content modification of a middle entry', () => { + const c = createTamperChain(); + c.append(EV()); + c.append(EV({ action: 'key.rotate' })); + c.append(EV({ action: 'user.suspend' })); + const entries = c.entries() as SealedAuditEntry[]; + entries[1] = { ...entries[1], action: 'role.revoke' }; + const report = verifyChain(entries); + // Middle entry hash mismatch breaks this entry and the next link. + expect(report.valid).toBe(false); + expect(report.issues.some((i) => i.code === 'HASH_MISMATCH')).toBe(true); + }); + + it('detects a broken predecessor link', () => { + const c = createTamperChain(); + c.append(EV()); + c.append(EV({ action: 'key.rotate' })); + const entries = c.entries() as SealedAuditEntry[]; + entries[1] = { ...entries[1], prevHash: GENESIS_HASH }; + const report = verifyChain(entries); + expect(report.valid).toBe(false); + expect(report.issues.some((i) => i.code === 'BROKEN_LINK')).toBe(true); + }); + + it('detects a sequence gap', () => { + const c = createTamperChain(); + c.append(EV()); + c.append(EV({ action: 'key.rotate' })); + const entries = c.entries() as SealedAuditEntry[]; + entries[1] = { ...entries[1], seq: 5 }; + const report = verifyChain(entries); + expect(report.valid).toBe(false); + expect(report.issues.some((i) => i.code === 'INVALID_SEQUENCE')).toBe(true); + }); + + it('detects a malformed hash', () => { + const c = createTamperChain(); + c.append(EV()); + const entries = c.entries() as SealedAuditEntry[]; + entries[0] = { ...entries[0], hash: 'nope' }; + const report = verifyChain(entries); + expect(report.valid).toBe(false); + expect(report.issues.some((i) => i.code === 'INVALID_HASH')).toBe(true); + }); + + it('rejects a malformed genesis config', () => { + expect(() => createTamperChain({ genesisHash: 'xyz' })).toThrow(TamperChainError); + }); + + it('verifies a custom genesis chain', () => { + const g = 'a'.repeat(64); + const c = createTamperChain({ genesisHash: g }); + const e = c.append(EV()); + expect(e.prevHash).toBe(g); + expect(verifyChain(c.entries(), { genesisHash: g }).valid).toBe(true); + }); +}); + +describe('tamperChain - computeEntryHash / resealChain', () => { + it('computeEntryHash is deterministic', () => { + const a = computeEntryHash(EV(), 1, GENESIS_HASH); + const b = computeEntryHash(EV(), 1, GENESIS_HASH); + expect(a).toBe(b); + expect(a).toMatch(/^[0-9a-f]{64}$/); + }); + + it('resesals a tampered chain into a valid one', () => { + const c = createTamperChain(); + c.append(EV()); + c.append(EV({ action: 'key.rotate' })); + const entries = c.entries() as SealedAuditEntry[]; + entries[0] = { ...entries[0], action: 'tampered' }; + expect(verifyChain(entries).valid).toBe(false); + const resealed = resealChain(entries); + expect(verifyChain(resealed).valid).toBe(true); + }); +}); diff --git a/backend/src/lib/tamperChain.ts b/backend/src/lib/tamperChain.ts new file mode 100644 index 00000000..d5b7bcdd --- /dev/null +++ b/backend/src/lib/tamperChain.ts @@ -0,0 +1,305 @@ +/** + * backend/src/lib/tamperChain.ts + * + * Tamper-evident hash chaining for append-only audit records. This module is + * a zero-I/O, side-effect-free primitive: it knows nothing about stores, + * clocks, or networks. Callers feed it canonicalisable entries; it returns + * SHA-256 sealed entries whose `hash` binds both the entry content and the + * hash of its predecessor, forming an append-only chain. + * + * Design rules (issue #2273): + * - Pure functions only: no I/O, no clock reads, no random values. + * - Every rejection is a typed `TamperChainError` with a stable `code`. + * - Canonical serialisation is deterministic (sorted keys) so the same + * logical entry always produces the same hash across processes. + * - A sealed chain can be verified in full, detecting deletion, reordering, + * and content modification of any record. + * - Observability hooks for metrics and audit logging. + * + * Usage: + * import { createTamperChain, verifyChain } from '../lib/tamperChain'; + * const chain = createTamperChain(); + * const e1 = chain.append({ actor: 'admin:1', action: 'role.grant' }); + * const e2 = chain.append({ actor: 'admin:2', action: 'key.rotate' }); + * const report = chain.verify(); + * if (!report.valid) throw new Error('audit log tampered'); + */ + +import { createHash } from 'crypto'; + +// ?? Types ??????????????????????????????????????????????????????????????? + +export type TamperChainErrorCode = + | 'INVALID_SEQUENCE' + | 'INVALID_HASH' + | 'HASH_MISMATCH' + | 'BROKEN_LINK' + | 'EMPTY_CHAIN' + | 'INVALID_GENESIS' + | 'INVALID_CONFIG'; + +export class TamperChainError extends Error { + readonly code: TamperChainErrorCode; + readonly details: Readonly>; + + constructor( + code: TamperChainErrorCode, + message: string, + details: Readonly> = {} + ) { + super(message); + this.name = 'TamperChainError'; + this.code = code; + this.details = details; + } +} + +/** Payload supplied by the caller for a single audit event. */ +export interface AuditEventInput { + /** Stable actor identifier, e.g. `user:42` or `service:billing`. */ + actor: string; + /** Machine-readable action, e.g. `role.grant` or `key.rotate`. */ + action: string; + /** Optional resource the action was performed on. */ + resource?: string; + /** ISO-8601 timestamp. Callers supply it to keep this module clock-free. */ + timestamp: string; + /** Arbitrary structured metadata; must be JSON-serialisable. */ + metadata?: Readonly>; +} + +/** A sealed audit entry: the input plus chaining fields. */ +export interface SealedAuditEntry extends AuditEventInput { + /** Monotonic 1-based sequence number. */ + seq: number; + /** SHA-256 hash of the previous sealed entry (`GENESIS_HASH` for the first). */ + prevHash: string; + /** SHA-256 hash binding this entry's content and `prevHash`. */ + hash: string; +} + +export interface TamperChainConfig { + /** Expected hash of the chain genesis. Defaults to 64 zero characters. */ + genesisHash?: string; +} + +export interface ChainVerificationIssue { + seq: number; + code: TamperChainErrorCode; + message: string; +} + +export interface ChainVerificationReport { + valid: boolean; + entriesChecked: number; + issues: readonly ChainVerificationIssue[]; + /** Hash of the final entry, usable as the chain head / checkpoint anchor. */ + headHash: string | null; +} + +export interface ChainMetrics { + increment?(name: string, labels?: Record): void; + observe?(name: string, value: number, labels?: Record): void; +} + +export interface ChainLogger { + info?(message: string, fields?: Record): void; + warn?(message: string, fields?: Record): void; +} + +// ?? Configuration ????????????????????????????????????????????????????????? + +/** Sentinel used as the predecessor of the very first chain entry. */ +export const GENESIS_HASH = '0'.repeat(64); +const HEX_SHA256 = /^[0-9a-f]{64}$/; + +function resolveGenesis(config?: TamperChainConfig): string { + const g = config?.genesisHash ?? GENESIS_HASH; + if (!HEX_SHA256.test(g)) { + throw new TamperChainError('INVALID_GENESIS', 'genesisHash must be 64 lowercase hex chars'); + } + return g; +} + +/** + * Deterministic canonical JSON: object keys are sorted recursively so that + * logically identical entries hash identically regardless of key insertion + * order. `undefined` values are omitted; arrays preserve order. + */ +export function canonicalStringify(value: unknown): string { + if (value === null || typeof value !== 'object') { + return JSON.stringify(value) ?? 'null'; + } + if (Array.isArray(value)) { + return `[${value.map(canonicalStringify).join(',')}]`; + } + const obj = value as Record; + const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort(); + return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalStringify(obj[k])}`).join(',')}}`; +} + +/** Compute the SHA-256 hash binding an entry's content to its predecessor. */ +export function computeEntryHash(input: AuditEventInput, seq: number, prevHash: string): string { + const canonical = canonicalStringify({ + seq, + prevHash, + actor: input.actor, + action: input.action, + resource: input.resource, + timestamp: input.timestamp, + metadata: input.metadata ?? {}, + }); + return createHash('sha256').update(canonical).digest('hex'); +} + +/** Validate an input before sealing. */ +export function validateInput(input: AuditEventInput): void { + if (!input || typeof input.actor !== 'string' || input.actor.length === 0) { + throw new TamperChainError('INVALID_CONFIG', 'actor must be a non-empty string'); + } + if (typeof input.action !== 'string' || input.action.length === 0) { + throw new TamperChainError('INVALID_CONFIG', 'action must be a non-empty string'); + } + if (typeof input.timestamp !== 'string' || input.timestamp.length === 0) { + throw new TamperChainError('INVALID_CONFIG', 'timestamp must be a non-empty string'); + } +} + +// ?? Chain ????????????????????????????????????????????????????????????????? + +export interface TamperChain { + readonly genesisHash: string; + /** Append an input and return the sealed entry. Mutates chain head. */ + append(input: AuditEventInput): SealedAuditEntry; + /** Current head hash (genesis if empty). */ + head(): string; + /** Number of sealed entries. */ + length(): number; + /** Snapshot of all sealed entries (defensive copy). */ + entries(): readonly SealedAuditEntry[]; + /** Verify the whole in-memory chain. */ + verify(): ChainVerificationReport; +} + +/** + * Create an in-memory tamper-evident chain. A fresh chain starts at the + * genesis hash; each `append` seals a new entry onto the current head. + */ +export function createTamperChain( + config?: TamperChainConfig, + hooks?: { metrics?: ChainMetrics; logger?: ChainLogger } +): TamperChain { + const genesisHash = resolveGenesis(config); + const sealed: SealedAuditEntry[] = []; + const metrics = hooks?.metrics; + const logger = hooks?.logger; + + return { + genesisHash, + append(input: AuditEventInput): SealedAuditEntry { + validateInput(input); + const seq = sealed.length + 1; + const prevHash = sealed.length === 0 ? genesisHash : sealed[sealed.length - 1].hash; + const hash = computeEntryHash(input, seq, prevHash); + const entry: SealedAuditEntry = { ...input, seq, prevHash, hash }; + sealed.push(entry); + metrics?.increment?.('audit.chain.append.total'); + logger?.info?.('audit.chain.appended', { seq, actor: input.actor, action: input.action }); + return entry; + }, + head(): string { + return sealed.length === 0 ? genesisHash : sealed[sealed.length - 1].hash; + }, + length(): number { + return sealed.length; + }, + entries(): readonly SealedAuditEntry[] { + return sealed.map((e) => ({ ...e })); + }, + verify(): ChainVerificationReport { + return verifyChain(sealed, config, hooks); + }, + }; +} + +/** + * Verify an arbitrary list of sealed entries. Detects: empty chain, sequence + * gaps/duplicates, broken links, and content hashes that no longer match. + * Verification is pure and does not mutate `entries`. + */ +export function verifyChain( + entries: readonly SealedAuditEntry[], + config?: TamperChainConfig, + hooks?: { metrics?: ChainMetrics; logger?: ChainLogger } +): ChainVerificationReport { + const genesisHash = resolveGenesis(config); + const metrics = hooks?.metrics; + const logger = hooks?.logger; + const issues: ChainVerificationIssue[] = []; + + if (entries.length === 0) { + metrics?.increment?.('audit.chain.verify.empty'); + return { valid: false, entriesChecked: 0, issues: [ + { seq: 0, code: 'EMPTY_CHAIN', message: 'cannot verify an empty chain' }, + ], headHash: null }; + } + + for (let i = 0; i < entries.length; i++) { + const e = entries[i]; + const expectedSeq = i + 1; + + if (!Number.isInteger(e.seq) || e.seq !== expectedSeq) { + issues.push({ seq: e.seq, code: 'INVALID_SEQUENCE', + message: `expected seq ${expectedSeq}, got ${e.seq}` }); + } + + const expectedPrev = i === 0 ? genesisHash : entries[i - 1].hash; + if (typeof e.prevHash !== 'string' || e.prevHash !== expectedPrev) { + issues.push({ seq: e.seq, code: 'BROKEN_LINK', + message: `entry ${e.seq} does not link to predecessor` }); + } + + if (typeof e.hash !== 'string' || !HEX_SHA256.test(e.hash)) { + issues.push({ seq: e.seq, code: 'INVALID_HASH', + message: `entry ${e.seq} has a malformed hash` }); + continue; + } + + const expectedHash = computeEntryHash(e, e.seq, e.prevHash); + if (e.hash !== expectedHash) { + issues.push({ seq: e.seq, code: 'HASH_MISMATCH', + message: `entry ${e.seq} content was modified (hash mismatch)` }); + } + } + + const valid = issues.length === 0; + const headHash = entries[entries.length - 1].hash; + metrics?.increment?.(valid ? 'audit.chain.verify.valid' : 'audit.chain.verify.tampered'); + metrics?.observe?.('audit.chain.length', entries.length); + if (!valid) { + logger?.warn?.('audit.chain.tamper_detected', { issues: issues.length, headHash }); + } + return { valid, entriesChecked: entries.length, issues, headHash }; +} + +/** + * Recompute and re-seal a tampered chain from its payloads, preserving the + * original sequence. Useful for reconstructing a canonical chain after an + * operator repair; returns a brand-new sealed list without mutating input. + */ +export function resealChain( + entries: readonly SealedAuditEntry[], + config?: TamperChainConfig +): readonly SealedAuditEntry[] { + const chain = createTamperChain(config); + for (const e of entries) { + chain.append({ + actor: e.actor, + action: e.action, + resource: e.resource, + timestamp: e.timestamp, + metadata: e.metadata, + }); + } + return chain.entries(); +} diff --git a/backend/src/services/__tests__/audit.test.ts b/backend/src/services/__tests__/audit.test.ts new file mode 100644 index 00000000..282b23d2 --- /dev/null +++ b/backend/src/services/__tests__/audit.test.ts @@ -0,0 +1,100 @@ +import { + createAuditLogService, + createInMemoryAuditStore, + type AuditStore, +} from '../audit'; +import type { SealedAuditEntry } from '../../lib/tamperChain'; + +const EV = (over: Record = {}) => ({ + actor: 'admin:1', + action: 'role.grant', + resource: 'user:7', + timestamp: '2026-11-24T00:00:00.000Z', + metadata: { reason: 'onboarding' }, + ...over, +}); + +describe('audit - createAuditLogService', () => { + it('records entries and verifies an intact log', async () => { + const store = createInMemoryAuditStore(); + const audit = createAuditLogService({ store }); + const r1 = await audit.record(EV()); + const r2 = await audit.record(EV({ action: 'key.rotate', actor: 'admin:2' })); + expect(r1.persisted).toBe(true); + expect(r1.entry.seq).toBe(1); + expect(r2.entry.prevHash).toBe(r1.entry.hash); + const report = await audit.verifyIntegrity(); + expect(report.valid).toBe(true); + expect(report.entriesChecked).toBe(2); + expect(audit.sealedCount()).toBe(2); + expect(audit.head()).toBe(r2.entry.hash); + }); + + it('uses the typed kind when provided', async () => { + const store = createInMemoryAuditStore(); + const audit = createAuditLogService({ store }); + const r = await audit.record(EV({ kind: 'billing.override', action: 'free-form' })); + expect(r.entry.action).toBe('billing.override'); + }); + + it('rehydrates the head from persisted entries across restarts', async () => { + const store = createInMemoryAuditStore(); + const a1 = createAuditLogService({ store }); + const r = await a1.record(EV()); + const a2 = createAuditLogService({ store }); + await a2.record(EV({ action: 'user.suspend' })); + expect(a2.head()).not.toBe(r.entry.hash); + expect((await a2.verifyIntegrity()).valid).toBe(true); + }); + + it('detects tampering in the backing store', async () => { + const store = createInMemoryAuditStore(); + const audit = createAuditLogService({ store }); + await audit.record(EV()); + await audit.record(EV({ action: 'key.rotate' })); + // Mutate the stored copy directly (simulates an attacker with DB access). + const all = (await store.loadAll()) as SealedAuditEntry[]; + all[0] = { ...all[0], action: 'role.revoke' }; + const custom: AuditStore = { + append: (e) => store.append(e), + loadAll: async () => all, + }; + const audit2 = createAuditLogService({ store: custom }); + const report = await audit2.verifyIntegrity(); + expect(report.valid).toBe(false); + expect(report.issues.some((i) => i.code === 'HASH_MISMATCH')).toBe(true); + }); + + it('throws in strict mode on violation', async () => { + const store = createInMemoryAuditStore(); + const audit = createAuditLogService({ store }); + await audit.record(EV()); + const all = (await store.loadAll()) as SealedAuditEntry[]; + all[0] = { ...all[0], actor: 'attacker' }; + const custom: AuditStore = { + append: (e) => store.append(e), + loadAll: async () => all, + }; + const strict = createAuditLogService({ store: custom, strict: true }); + await expect(strict.verifyIntegrity()).rejects.toThrow(/tampering detected/); + }); + + it('emits metrics and logger hooks on record + verify', async () => { + const increments: string[] = []; + const logs: string[] = []; + const audit = createAuditLogService({ + store: createInMemoryAuditStore(), + metrics: { increment: (n) => increments.push(n) }, + logger: { + info: (m) => logs.push(m), + warn: (m) => logs.push(m), + }, + }); + await audit.record(EV()); + await audit.verifyIntegrity(); + expect(increments).toContain('audit.record.total'); + expect(increments).toContain('audit.chain.verify.valid'); + expect(logs).toContain('audit.record.sealed'); + expect(logs).toContain('audit.integrity.ok'); + }); +}); diff --git a/backend/src/services/audit.ts b/backend/src/services/audit.ts new file mode 100644 index 00000000..6f0f2900 --- /dev/null +++ b/backend/src/services/audit.ts @@ -0,0 +1,194 @@ +/** + * backend/src/services/audit.ts + * + * Append-only audit log service for admin-sensitive actions. Every admin + * mutation is sealed into a tamper-evident SHA-256 hash chain (see + * `../lib/tamperChain`) so that deletion, reordering, or content edits are + * detectable at verification time. + * + * Design rules (issue #2273): + * - The service owns the chain head; callers never supply hashes. + * - Callers supply the timestamp to keep persistence clock-generic; a + * default `Date.now()` provider is offered for convenience only. + * - Every decision (append / verify / violation) emits metrics + logs. + * - The backing store interface is minimal and adapter-agnostic. + * + * Usage: + * const audit = createAuditLogService({ store: myStore }); + * await audit.record({ + * actor: 'admin:42', action: 'role.grant', + * resource: 'user:7', timestamp: new Date().toISOString(), + * }); + * const report = await audit.verifyIntegrity(); + * if (!report.valid) alertSecurity(report.issues); + */ + +import { + type AuditEventInput, + type ChainVerificationReport, + type SealedAuditEntry, + type TamperChainConfig, + createTamperChain, + verifyChain, +} from '../lib/tamperChain.ts'; + +// ?? Types ??????????????????????????????????????????????????????????????? + +export type AuditAction = + | 'role.grant' + | 'role.revoke' + | 'key.rotate' + | 'user.suspend' + | 'user.delete' + | 'settings.update' + | 'permission.change' + | 'export.create' + | 'webhook.rotate' + | 'billing.override'; + +export interface AuditRecordInput extends AuditEventInput { + /** Strongly typed admin action. Falls back to the free-form `action` for unknown values. */ + kind?: AuditAction; +} + +/** Minimal persistence adapter. Implementations decide durability semantics. */ +export interface AuditStore { + /** Persist a sealed entry atomically. */ + append(entry: SealedAuditEntry): Promise; + /** Load all sealed entries in append order for verification. */ + loadAll(): Promise; + /** Load the last N sealed entries (for head checkpointing). Optional. */ + loadLast?(n: number): Promise; +} + +export interface AuditMetrics { + increment?(name: string, labels?: Record): void; + observe?(name: string, value: number, labels?: Record): void; +} + +export interface AuditLogger { + info?(message: string, fields?: Record): void; + warn?(message: string, fields?: Record): void; + error?(message: string, fields?: Record): void; +} + +export interface AuditServiceConfig { + store: AuditStore; + chain?: TamperChainConfig; + metrics?: AuditMetrics; + logger?: AuditLogger; + /** When true, `verifyIntegrity` throws on tampering instead of returning a report. */ + strict?: boolean; +} + +export interface RecordResult { + entry: SealedAuditEntry; + /** True when the store accepted the append. */ + persisted: boolean; +} + +export interface AuditLogService { + /** Seal and persist an admin action. */ + record(input: AuditRecordInput): Promise; + /** Verify the persisted log in full. */ + verifyIntegrity(): Promise; + /** Current in-memory head hash. */ + head(): string; + /** Number of entries sealed this session. */ + sealedCount(): number; +} + +// ?? Service ?????????????????????????????????????????????????????????????? + +/** + * Create an audit log service backed by a tamper-evident hash chain. + * The in-memory chain is rebuilt from the store on first use so the head + * remains correct across service restarts. + */ +export function createAuditLogService(config: AuditServiceConfig): AuditLogService { + const { store, strict = false } = config; + const metrics = config.metrics; + const logger = config.logger; + const chain = createTamperChain(config.chain, { metrics, logger }); + let hydrated = false; + + async function hydrate(): Promise { + if (hydrated) return; + const existing = await store.loadAll(); + // Re-seal loaded payloads to rebuild the head deterministically from the + // canonical chain, ignoring any (possibly tampered) stored hashes. + if (existing.length > 0) { + for (const e of existing) { + chain.append({ + actor: e.actor, + action: e.action, + resource: e.resource, + timestamp: e.timestamp, + metadata: e.metadata, + }); + } + } + hydrated = true; + } + + return { + async record(input: AuditRecordInput): Promise { + await hydrate(); + const effective: AuditEventInput = { + actor: input.actor, + action: input.kind ?? input.action, + resource: input.resource, + timestamp: input.timestamp, + metadata: input.metadata, + }; + const entry = chain.append(effective); + await store.append(entry); + metrics?.increment?.('audit.record.total', { action: entry.action }); + logger?.info?.('audit.record.sealed', { seq: entry.seq, actor: entry.actor, action: entry.action }); + return { entry, persisted: true }; + }, + + async verifyIntegrity(): Promise { + await hydrate(); + const persisted = await store.loadAll(); + const report = verifyChain(persisted, config.chain, { metrics, logger }); + metrics?.observe?.('audit.integrity.issues', report.issues.length); + if (!report.valid) { + logger?.warn?.('audit.integrity.violation', { + issues: report.issues.length, + headHash: report.headHash, + }); + if (strict) { + throw new Error(`audit log tampering detected: ${report.issues.length} issue(s)`); + } + } else { + logger?.info?.('audit.integrity.ok', { entries: report.entriesChecked }); + } + return report; + }, + + head(): string { + return chain.head(); + }, + + sealedCount(): number { + return chain.length(); + }, + }; +} + +/** Convenience: a no-op in-memory store for tests and local development. */ +export function createInMemoryAuditStore(seed: readonly SealedAuditEntry[] = []): AuditStore { + const rows: SealedAuditEntry[] = [...seed]; + return { + async append(entry: SealedAuditEntry): Promise { + rows.push({ ...entry }); + }, + async loadAll(): Promise { + return rows.map((e) => ({ ...e })); + }, + async loadLast(n: number): Promise { + return rows.slice(-n).map((e) => ({ ...e })); + }, + }; +}