hierarchical-approval 4.2.0 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/{ApprovalEngine-DxVvZWi2.d.ts → ApprovalEngine-BtfTSo_J.d.ts} +1 -1
  3. package/dist/{ApprovalEngine-CQEBchcl.d.cts → ApprovalEngine-C8Jg5Td7.d.cts} +1 -1
  4. package/dist/{IOperationMiddleware-Cg37YFoc.d.cts → IOperationMiddleware-hyUwOuee.d.cts} +1 -0
  5. package/dist/{IOperationMiddleware-DGnAbRDI.d.ts → IOperationMiddleware-ko_8XDeV.d.ts} +1 -0
  6. package/dist/adapters/MemoryAdapter.cjs +5 -1
  7. package/dist/adapters/MemoryAdapter.cjs.map +1 -1
  8. package/dist/adapters/MemoryAdapter.js +5 -1
  9. package/dist/adapters/MemoryAdapter.js.map +1 -1
  10. package/dist/adapters/PostgresAdapter.cjs +5 -1
  11. package/dist/adapters/PostgresAdapter.cjs.map +1 -1
  12. package/dist/adapters/PostgresAdapter.js +5 -1
  13. package/dist/adapters/PostgresAdapter.js.map +1 -1
  14. package/dist/index.cjs +5 -1
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +2 -2
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +5 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/nestjs.cjs +5 -1
  21. package/dist/nestjs.cjs.map +1 -1
  22. package/dist/nestjs.d.cts +1 -1
  23. package/dist/nestjs.d.ts +1 -1
  24. package/dist/nestjs.js +5 -1
  25. package/dist/nestjs.js.map +1 -1
  26. package/dist/plugins/audit.cjs +5 -1
  27. package/dist/plugins/audit.cjs.map +1 -1
  28. package/dist/plugins/audit.js +5 -1
  29. package/dist/plugins/audit.js.map +1 -1
  30. package/dist/plugins/notify.cjs +5 -1
  31. package/dist/plugins/notify.cjs.map +1 -1
  32. package/dist/plugins/notify.js +5 -1
  33. package/dist/plugins/notify.js.map +1 -1
  34. package/dist/plugins/resilience.cjs +5 -1
  35. package/dist/plugins/resilience.cjs.map +1 -1
  36. package/dist/plugins/resilience.js +5 -1
  37. package/dist/plugins/resilience.js.map +1 -1
  38. package/dist/plugins/scheduler.cjs +5 -1
  39. package/dist/plugins/scheduler.cjs.map +1 -1
  40. package/dist/plugins/scheduler.js +5 -1
  41. package/dist/plugins/scheduler.js.map +1 -1
  42. package/dist/plugins/webhook.cjs +5 -1
  43. package/dist/plugins/webhook.cjs.map +1 -1
  44. package/dist/plugins/webhook.js +5 -1
  45. package/dist/plugins/webhook.js.map +1 -1
  46. package/dist/testing.cjs +5 -1
  47. package/dist/testing.cjs.map +1 -1
  48. package/dist/testing.d.cts +1 -1
  49. package/dist/testing.d.ts +1 -1
  50. package/dist/testing.js +5 -1
  51. package/dist/testing.js.map +1 -1
  52. package/package.json +6 -6
@@ -70,13 +70,17 @@ var ApprovalError = class extends Error {
70
70
  toJSON() {
71
71
  return { code: this.code, message: this.message, name: this.name };
72
72
  }
73
+ /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */
73
74
  toHttpStatus() {
74
75
  const map = {
75
76
  NOT_FOUND: 404,
76
77
  CONFLICT: 409,
78
+ CANNOT_CANCEL: 409,
77
79
  FORBIDDEN: 403,
78
80
  VALIDATION: 422,
79
- TEMPLATE_NOT_FOUND: 404
81
+ TEMPLATE_NOT_FOUND: 404,
82
+ // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.
83
+ SCHEDULER_SHUTDOWN: 503
80
84
  };
81
85
  return map[this.code] ?? 500;
82
86
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/audit/canonicalize.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/audit/HashChainAuditAdapter.ts","../../src/plugins/audit/RedactingAuditAdapter.ts","../../src/plugins/audit/CompositeAuditAdapter.ts"],"names":["createHash"],"mappings":";;;;;AAiBO,IAAM,sBAAA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AA,GAAS,QAAQ,CAAC,CAAA;AACxB,MAAA,IAAI,MAAA,CAAO,WAAW,UAAA,EAAY;AAChC,QAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,QAAA,CAAS,CAAC,CAAA;AAC7B,QAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,UACV,CAAA,8BAAA,EAAiC,MAAM,EAAE,CAAA,kBAAA,CAAA;AAAA,UACzC,MAAA,CAAO,MAAA;AAAA,UACP,EAAE,QAAA,EAAU,UAAA,EAAY,SAAS,KAAA,CAAM,EAAA,EAAI,YAAY,CAAA;AAAE,SAC3D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF","file":"audit.cjs","sourcesContent":["/**\n * Deterministic canonical JSON serialization for hashing.\n *\n * Guarantees a stable, reproducible string for the same logical value regardless\n * of key insertion order, so the same record always produces the same hash:\n * - Object keys are emitted in lexicographic order (recursively).\n * - `Date` values are serialized to their ISO-8601 string.\n * - `undefined` properties (and `undefined` array elements) are encoded as `null`\n * so that presence/position is preserved deterministically.\n * - `bigint` is encoded as its decimal string; functions/symbols are encoded as `null`.\n * - Circular references are detected and rejected (the caller decides how to react),\n * rather than throwing the native, unstable `TypeError` deep inside JSON.stringify.\n *\n * This module performs no I/O and has no dependencies; it is pure and unit-testable.\n */\n\n/** Thrown by {@link canonicalize} when a circular reference is encountered. */\nexport class CircularReferenceError extends Error {\n constructor(path: string) {\n super(`Circular reference detected during canonicalization at path \"${path}\".`);\n this.name = 'CircularReferenceError';\n }\n}\n\n/**\n * Produce a deterministic JSON string for `value`.\n *\n * @param value - Any JavaScript value. Plain objects, arrays, strings, numbers,\n * booleans, `null`, `undefined`, `Date`, and `bigint` are supported.\n * @returns A stable string suitable for hashing.\n * @throws {CircularReferenceError} If the value graph contains a cycle.\n */\nexport function canonicalize(value: unknown): string {\n const seen = new Set<object>();\n\n const encode = (v: unknown, path: string): string => {\n if (v === null || v === undefined) return 'null';\n\n const t = typeof v;\n if (t === 'number') return Number.isFinite(v as number) ? String(v) : 'null';\n if (t === 'boolean') return (v as boolean) ? 'true' : 'false';\n if (t === 'bigint') return JSON.stringify((v as bigint).toString());\n if (t === 'string') return JSON.stringify(v);\n if (t === 'function' || t === 'symbol') return 'null';\n\n if (v instanceof Date) return JSON.stringify(v.toISOString());\n\n if (Array.isArray(v)) {\n if (seen.has(v)) throw new CircularReferenceError(path);\n seen.add(v);\n const parts = v.map((item, i) => encode(item, `${path}[${i}]`));\n seen.delete(v);\n return `[${parts.join(',')}]`;\n }\n\n if (t === 'object') {\n const obj = v as Record<string, unknown>;\n if (seen.has(obj)) throw new CircularReferenceError(path);\n seen.add(obj);\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const key of keys) {\n const child = obj[key];\n // Mirror JSON.stringify: skip keys whose value is undefined inside objects.\n if (child === undefined) continue;\n parts.push(`${JSON.stringify(key)}:${encode(child, `${path}.${key}`)}`);\n }\n seen.delete(obj);\n return `{${parts.join(',')}}`;\n }\n\n return 'null';\n };\n\n return encode(value, '$');\n}\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport { canonicalize, CircularReferenceError } from './canonicalize.js';\nimport { ApprovalValidationError } from '../../errors.js';\n\n/** The fixed sentinel used as the previous-hash of the genesis (first) entry. */\nexport const GENESIS_PREV_HASH = '0'.repeat(64);\n\n/** A single persisted record in a hash chain. The shape is intentionally exact. */\nexport interface ChainRecord {\n /** The original audit entry, captured verbatim. */\n readonly entry: AuditEntry;\n /** SHA-256 (hex) over the canonical serialization of `{ seq, prevHash, entry }`. */\n readonly hash: string;\n /** The `hash` of the preceding record, or {@link GENESIS_PREV_HASH} for the first. */\n readonly prevHash: string;\n /** Monotonic sequence number within this (tenant, instance) chain. */\n readonly seq: number;\n}\n\n/**\n * Persists a single chain record. Implementations may target any durable sink\n * (Kafka, S3 WORM bucket, append-only table, …). The record's `(tenantId, instanceId)`\n * is supplied alongside it so the sink can partition without inferring identity from\n * the entry. The adapter awaits this writer but tolerates rejection: a failed write\n * is logged and swallowed.\n */\nexport type ChainRecordWriter = (\n tenantId: string,\n instanceId: string,\n record: ChainRecord,\n) => Promise<void>;\n\n/** Reads back the ordered chain for a (tenant, instance). */\nexport type ChainRecordReader = (\n tenantId: string,\n instanceId: string,\n) => Promise<readonly ChainRecord[]>;\n\n/** Result of {@link HashChainAuditAdapter.verify}. */\nexport interface VerifyResult {\n /** True when every record's hash and linkage recompute correctly. */\n ok: boolean;\n /**\n * The lowest `seq` whose stored hash or `prevHash` linkage failed, or — for a\n * tail truncation — the first missing `seq` (the gap point at the end of the\n * chain). Present only when `ok` is false.\n */\n brokenAt?: number;\n}\n\n/** Constructor options for {@link HashChainAuditAdapter}. */\nexport interface HashChainAuditAdapterOptions {\n /**\n * Async sink for each persisted record. Defaults to an internal in-memory store.\n * If you supply a custom `writer`, also supply a matching {@link reader} so the\n * adapter can recompute the chain during {@link HashChainAuditAdapter.verify}.\n */\n writer?: ChainRecordWriter;\n /** Reads back the ordered chain for verification. Required when a custom `writer` is supplied. */\n reader?: ChainRecordReader;\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\n/** The composite chain key (tenant + instance) never collides across tenants or instances. */\nfunction chainKey(tenantId: string, instanceId: string): string {\n // Length-prefix the tenant id so that (\"a\", \"b:c\") and (\"a:b\", \"c\") cannot collide.\n return `${tenantId.length}:${tenantId}:${instanceId}`;\n}\n\n/**\n * Tamper-evident {@link IAuditAdapter}. Every appended entry is wrapped in a\n * {@link ChainRecord} whose `hash` is a SHA-256 over a canonical serialization of\n * `{ seq, prevHash, entry }`, with `prevHash` linking to the previous record's hash.\n * Any later mutation, deletion, or reordering of a record breaks the recomputed\n * chain, which {@link verify} detects and pinpoints.\n *\n * Chains are partitioned by `(tenantId, instanceId)`: separate instances or tenants\n * never share a sequence counter or hash linkage. Appends to the same chain are\n * serialized so concurrent calls cannot interleave `seq`/`prevHash`.\n *\n * **Tail-truncation detection.** A pure re-hash of the stored chain cannot, on its\n * own, detect that the *last* record(s) were dropped: a truncated prefix still\n * re-hashes and re-links perfectly. To close this gap the adapter records an\n * in-process **high-water mark** per `(tenantId, instanceId)` — the highest `seq`\n * it has ever appended (advanced before the writer is awaited). {@link verify}\n * compares the stored chain's last `seq` against this high-water mark and reports\n * `{ ok: false, brokenAt: <first missing seq> }` when the tail is short. Callers\n * who hold an external anchor (e.g. a durably persisted length) may also pass\n * `expectedLength` to {@link verify} to assert truncation **across process\n * restarts**, when the in-process high-water mark has been lost.\n *\n * *Limit:* with neither an in-process high-water mark (e.g. a fresh process that\n * never appended to this chain) nor an `expectedLength` argument, truncation of\n * the tail is undetectable — there is no record of how long the chain *should* be.\n *\n * `append` never throws: writer rejections and canonicalization failures are logged\n * and swallowed, honoring the {@link IAuditAdapter} must-not-throw contract.\n *\n * @example\n * ```ts\n * const audit = new HashChainAuditAdapter();\n * // ...wire as ApprovalEngineOptions.auditAdapter...\n * const result = await audit.verify(tenantId, instanceId); // { ok: true }\n * ```\n */\nexport class HashChainAuditAdapter implements IAuditAdapter {\n private readonly writer: ChainRecordWriter;\n private readonly reader: ChainRecordReader;\n private readonly logger: Logger;\n\n /** In-memory default store, keyed by composite chain key. Used only when no custom writer/reader. */\n private readonly store = new Map<string, ChainRecord[]>();\n /**\n * Last hash + seq per chain key, tracked in-process so the next append links\n * without re-reading the sink. The `seq` field doubles as the per-chain\n * **high-water mark**: the highest `seq` ever appended in this process, which\n * {@link verify} uses to detect a truncated tail.\n */\n private readonly heads = new Map<string, { prevHash: string; seq: number }>();\n /** Per-chain promise tail used to serialize appends to the same (tenant, instance). */\n private readonly locks = new Map<string, Promise<void>>();\n\n constructor(options: HashChainAuditAdapterOptions = {}) {\n this.logger = options.logger ?? noopLogger;\n\n if (options.writer && !options.reader) {\n // A custom sink with no reader cannot be verified; fail fast at construction\n // rather than silently producing a chain that verify() cannot inspect.\n throw new ApprovalValidationError(\n 'HashChainAuditAdapter: a custom `writer` requires a matching `reader` for verification.',\n );\n }\n\n this.writer =\n options.writer ??\n (async (tenantId, instanceId, record) => {\n const key = chainKey(tenantId, instanceId);\n const chain = this.store.get(key);\n if (chain) {\n chain.push(record);\n } else {\n this.store.set(key, [record]);\n }\n });\n\n this.reader =\n options.reader ??\n (async (tenantId, instanceId) => this.store.get(chainKey(tenantId, instanceId)) ?? []);\n }\n\n /**\n * Append an entry to the (tenant, instance) chain. Computes the next `seq` and\n * `prevHash`, hashes the canonical record, and persists via the injected writer.\n * Never throws.\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n _instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n const key = chainKey(tenantId, instanceId);\n\n // Serialize per-chain: chain the work onto the existing tail so two concurrent\n // appends to the same (tenant, instance) cannot read the same head.\n const prior = this.locks.get(key) ?? Promise.resolve();\n const work = prior.then(() => this.appendLocked(key, tenantId, instanceId, entry));\n // The lock tail must never reject (it would poison every subsequent append).\n this.locks.set(\n key,\n work.then(\n () => undefined,\n () => undefined,\n ),\n );\n await work;\n }\n\n private async appendLocked(\n key: string,\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n ): Promise<void> {\n try {\n const head = this.heads.get(key);\n const seq = head ? head.seq + 1 : 0;\n const prevHash = head ? head.prevHash : GENESIS_PREV_HASH;\n\n const hash = this.computeHash(seq, prevHash, entry);\n const record: ChainRecord = Object.freeze({ entry, hash, prevHash, seq });\n\n // Advance the in-process head BEFORE awaiting the writer so a slow or failing\n // writer cannot cause the next append to reuse this seq/prevHash. The chain's\n // logical integrity is independent of whether the sink durably accepted it.\n this.heads.set(key, { prevHash: hash, seq });\n\n try {\n await this.writer(tenantId, instanceId, record);\n } catch (err) {\n // Writer failure (including on the genesis entry) is logged and swallowed.\n // The in-process head already advanced, so subsequent appends stay linked;\n // if the sink dropped this record, verify() will surface the gap deterministically.\n this.logger.error(\n 'HashChainAuditAdapter: writer rejected; entry not durably persisted',\n err,\n { tenantId, instanceId, seq },\n );\n }\n } catch (err) {\n // Canonicalization/hashing failure (e.g. circular reference). Swallow per contract.\n if (err instanceof CircularReferenceError) {\n this.logger.error('HashChainAuditAdapter: entry could not be canonicalized', err, {\n tenantId,\n instanceId,\n });\n } else {\n this.logger.error('HashChainAuditAdapter: unexpected error during append', err, {\n tenantId,\n instanceId,\n });\n }\n }\n }\n\n /** Compute the SHA-256 (hex) hash for a record's `{ seq, prevHash, entry }`. */\n private computeHash(seq: number, prevHash: string, entry: AuditEntry): string {\n const canonical = canonicalize({ seq, prevHash, entry });\n return createHash('sha256').update(canonical, 'utf8').digest('hex');\n }\n\n /**\n * Recompute the entire chain for `(tenantId, instanceId)` from genesis and,\n * additionally, detect a truncated tail.\n *\n * Per-record integrity (tamper, deletion, reorder, broken linkage) is found by\n * re-hashing and re-linking from genesis. Tail truncation — dropping the last\n * record(s) — leaves a perfectly self-consistent prefix, so it is detected by\n * comparing the chain's last `seq` against an **expected high-water mark**:\n *\n * - `expectedLength`, when supplied, is the authoritative expected record count\n * (so the expected high-water `seq` is `expectedLength - 1`). Use this with an\n * external anchor to assert truncation even across process restarts.\n * - otherwise the in-process high-water mark recorded by {@link append} is used.\n *\n * When the stored chain is shorter than expected, `brokenAt` is the first\n * missing `seq` (the gap point at the tail). With neither an `expectedLength`\n * argument nor an in-process high-water mark, a truncated tail is undetectable.\n *\n * @param tenantId - Tenant partition.\n * @param instanceId - Instance partition.\n * @param expectedLength - Optional external anchor: the number of records the\n * chain is expected to contain. When provided it overrides the in-process\n * high-water mark for the truncation check.\n * @returns `{ ok: true }` for an untouched chain (and an empty chain when no\n * high-water mark/`expectedLength` says otherwise), otherwise\n * `{ ok: false, brokenAt }`.\n */\n async verify(\n tenantId: string,\n instanceId: string,\n expectedLength?: number,\n ): Promise<VerifyResult> {\n const key = chainKey(tenantId, instanceId);\n const chain = await this.reader(tenantId, instanceId);\n\n // Resolve the expected number of records: the explicit anchor wins; otherwise\n // fall back to the in-process high-water mark (highest appended seq + 1).\n let expectedCount: number | undefined;\n if (expectedLength !== undefined) {\n expectedCount = expectedLength;\n } else {\n const head = this.heads.get(key);\n if (head !== undefined) expectedCount = head.seq + 1;\n }\n\n // Empty chain: only \"ok\" if nothing was expected. If an anchor/high-water\n // mark says records should exist, the entire tail was truncated.\n if (chain.length === 0) {\n if (expectedCount !== undefined && expectedCount > 0) {\n return { ok: false, brokenAt: 0 };\n }\n return { ok: true };\n }\n\n let expectedPrev = GENESIS_PREV_HASH;\n for (let i = 0; i < chain.length; i++) {\n const record = chain[i]!;\n\n // Sequence must start at 0 and increment by exactly 1 (detects deletion/reorder/gap).\n if (record.seq !== i) return { ok: false, brokenAt: Math.min(record.seq, i) };\n\n // Linkage to the previous record's hash must hold.\n if (record.prevHash !== expectedPrev) return { ok: false, brokenAt: record.seq };\n\n // The stored hash must equal the recomputed hash of its content (detects tamper).\n let recomputed: string;\n try {\n recomputed = this.computeHash(record.seq, record.prevHash, record.entry);\n } catch {\n return { ok: false, brokenAt: record.seq };\n }\n if (recomputed !== record.hash) return { ok: false, brokenAt: record.seq };\n\n expectedPrev = record.hash;\n }\n\n // Tail-truncation check: the per-record loop above cannot see records that are\n // simply absent from the end. Compare the actual length against the expected\n // high-water mark; a short chain means the tail was dropped.\n if (expectedCount !== undefined && chain.length < expectedCount) {\n return { ok: false, brokenAt: chain.length };\n }\n\n return { ok: true };\n }\n\n /**\n * Read the ordered chain for `(tenantId, instanceId)`. Returns whatever the\n * configured reader yields (the default in-memory reader returns the live array;\n * callers should treat it as read-only).\n */\n async getChain(tenantId: string, instanceId: string): Promise<readonly ChainRecord[]> {\n return this.reader(tenantId, instanceId);\n }\n}\n","import type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** Default token substituted in place of redacted values. */\nexport const DEFAULT_REDACTION_MASK = '[REDACTED]';\n\n/** Constructor options for {@link RedactingAuditAdapter}. */\nexport interface RedactingAuditAdapterOptions {\n /**\n * The wrapped adapter that receives the redacted entry.\n */\n inner: IAuditAdapter;\n\n /**\n * Dot-delimited field paths to redact, scoped to the bag they live in.\n *\n * Paths target the structured value bags (`oldValue`, `newValue`) of an\n * {@link AuditEntry}. Prefix a path with `oldValue.` or `newValue.` to scope it,\n * or supply an unscoped path (e.g. `applicant.ssn`) to apply it to BOTH bags.\n *\n * A trailing `.*` wildcard redacts every direct child of the matched object\n * (e.g. `card.*` masks every field under `card`). A path that does not resolve\n * to an existing value is a no-op.\n *\n * @example ['newValue.applicant.ssn', 'card.*', 'oldValue.bankAccount']\n */\n fieldPaths?: string[];\n\n /**\n * Free-text top-level entry fields to redact wholesale (value replaced by the mask).\n * Defaults to `[]`. Common choices: `['comment', 'reason']`.\n */\n freeTextFields?: Array<'comment' | 'reason'>;\n\n /** Token used to replace redacted values. Defaults to {@link DEFAULT_REDACTION_MASK}. */\n mask?: string;\n\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\n/** Deep-clone a value, preserving `Date` instances and dropping functions/symbols. */\nfunction deepClone<T>(value: T): T {\n return cloneValue(value) as T;\n}\n\nfunction cloneValue(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n if (value instanceof Date) return new Date(value.getTime());\n if (Array.isArray(value)) return value.map((v) => cloneValue(v));\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = cloneValue(v);\n }\n return out;\n}\n\n/** A field path scoped to one or both structured bags. */\ninterface ParsedPath {\n bag: 'oldValue' | 'newValue' | 'both';\n /** Remaining segments after the optional bag prefix. */\n segments: string[];\n /** True when the final segment is the `*` wildcard. */\n wildcard: boolean;\n}\n\nfunction parsePath(raw: string): ParsedPath | null {\n const parts = raw.split('.').filter((p) => p.length > 0);\n if (parts.length === 0) return null;\n\n let bag: ParsedPath['bag'] = 'both';\n let segments = parts;\n if (parts[0] === 'oldValue' || parts[0] === 'newValue') {\n bag = parts[0];\n segments = parts.slice(1);\n }\n\n let wildcard = false;\n if (segments[segments.length - 1] === '*') {\n wildcard = true;\n segments = segments.slice(0, -1);\n }\n\n // A bare `oldValue.*` / `newValue.*` (wildcard with no remaining segments) masks\n // every direct child of that whole bag.\n if (segments.length === 0 && !wildcard) return null;\n return { bag, segments, wildcard };\n}\n\n/**\n * Apply one parsed path to a single bag object, masking in place. The bag has\n * already been deep-cloned by the caller, so mutation here is safe.\n */\nfunction redactInBag(bag: Record<string, unknown>, path: ParsedPath, mask: string): void {\n // Walk to the parent of the target. Any non-object along the way means the path\n // does not resolve — leave the structure untouched.\n let cursor: unknown = bag;\n for (let i = 0; i < path.segments.length - (path.wildcard ? 0 : 1); i++) {\n const seg = path.segments[i]!;\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n cursor = (cursor as Record<string, unknown>)[seg];\n }\n\n if (path.wildcard) {\n // After walking all segments, `cursor` is the object whose children we mask.\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n const target = cursor as Record<string, unknown>;\n for (const key of Object.keys(target)) {\n target[key] = mask;\n }\n return;\n }\n\n // Non-wildcard: `cursor` is the parent; mask the final key if it exists.\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n const parent = cursor as Record<string, unknown>;\n const finalKey = path.segments[path.segments.length - 1]!;\n if (Object.prototype.hasOwnProperty.call(parent, finalKey)) {\n parent[finalKey] = mask;\n }\n}\n\n/**\n * An {@link IAuditAdapter} decorator that strips configured PII from each entry\n * before forwarding to a wrapped adapter. The caller's original `entry` and\n * `instance` are never mutated — redaction operates on a deep clone.\n *\n * Redaction targets the structured bags (`oldValue`, `newValue`) by dot-path,\n * supports a trailing `.*` wildcard to mask every child of an object, and can\n * blank out free-text fields (`comment`, `reason`). Paths that do not resolve,\n * or that point at `null`/array/primitive values, are no-ops that leave the\n * entry structurally intact.\n *\n * @example\n * ```ts\n * const audit = new RedactingAuditAdapter({\n * inner: new HashChainAuditAdapter(),\n * fieldPaths: ['newValue.applicant.ssn', 'card.*'],\n * freeTextFields: ['comment', 'reason'],\n * });\n * ```\n */\nexport class RedactingAuditAdapter implements IAuditAdapter {\n private readonly inner: IAuditAdapter;\n private readonly parsedPaths: ParsedPath[];\n private readonly freeTextFields: ReadonlyArray<'comment' | 'reason'>;\n private readonly mask: string;\n private readonly logger: Logger;\n\n constructor(options: RedactingAuditAdapterOptions) {\n this.inner = options.inner;\n this.mask = options.mask ?? DEFAULT_REDACTION_MASK;\n this.freeTextFields = options.freeTextFields ?? [];\n this.logger = options.logger ?? noopLogger;\n this.parsedPaths = (options.fieldPaths ?? [])\n .map(parsePath)\n .filter((p): p is ParsedPath => p !== null);\n }\n\n /**\n * Deep-clone the entry, redact configured fields on the clone, then forward to\n * the wrapped adapter. The caller's `entry` reference and contents are unchanged.\n * Never throws (delegates the must-not-throw guarantee to the wrapped adapter and\n * swallows any unexpected local error).\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n let redacted: AuditEntry;\n try {\n redacted = this.redactEntry(entry);\n } catch (err) {\n // Redaction must never break the audit path. On the unexpected event that\n // cloning/redaction fails, log and forward the original entry unmodified so\n // the audit record is not silently dropped.\n this.logger.error('RedactingAuditAdapter: redaction failed; forwarding original entry', err, {\n tenantId,\n instanceId,\n });\n redacted = entry;\n }\n await this.inner.append(tenantId, instanceId, redacted, instance);\n }\n\n /** Produce a redacted deep clone of `entry` without touching the original. */\n private redactEntry(entry: AuditEntry): AuditEntry {\n const clone = deepClone(entry);\n\n // Free-text fields: blank the value wholesale if present and non-empty/defined.\n for (const field of this.freeTextFields) {\n if (clone[field] !== undefined) {\n clone[field] = this.mask;\n }\n }\n\n // Structured bags.\n for (const path of this.parsedPaths) {\n if ((path.bag === 'oldValue' || path.bag === 'both') && clone.oldValue) {\n redactInBag(clone.oldValue, path, this.mask);\n }\n if ((path.bag === 'newValue' || path.bag === 'both') && clone.newValue) {\n redactInBag(clone.newValue, path, this.mask);\n }\n }\n\n return clone;\n }\n}\n","import type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** A child adapter, optionally tagged with a stable identity for diagnostics. */\nexport interface CompositeChild {\n /** Human-readable identity used in logs when this child rejects (defaults to its index). */\n readonly id?: string;\n readonly adapter: IAuditAdapter;\n}\n\n/** Constructor options for {@link CompositeAuditAdapter}. */\nexport interface CompositeAuditAdapterOptions {\n /**\n * Child adapters to fan out to. Each may be a bare {@link IAuditAdapter} or a\n * {@link CompositeChild} carrying an `id` for clearer log attribution.\n */\n children: ReadonlyArray<IAuditAdapter | CompositeChild>;\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\nfunction normalize(\n child: IAuditAdapter | CompositeChild,\n index: number,\n): { id: string; adapter: IAuditAdapter } {\n if ('adapter' in child) {\n return { id: child.id ?? `child[${index}]`, adapter: child.adapter };\n }\n return { id: `child[${index}]`, adapter: child };\n}\n\n/**\n * An {@link IAuditAdapter} that fans `append` out to N child adapters concurrently.\n * Every child receives the same entry. The call awaits all children\n * ({@link Promise.allSettled}) and never throws: a rejecting child is logged with\n * its index/identity and does not prevent the other children from receiving the\n * entry. A composite with zero children is a no-op that resolves immediately.\n *\n * @example\n * ```ts\n * const audit = new CompositeAuditAdapter({\n * children: [\n * { id: 'hash-chain', adapter: new HashChainAuditAdapter() },\n * { id: 's3-worm', adapter: s3Adapter },\n * ],\n * });\n * ```\n */\nexport class CompositeAuditAdapter implements IAuditAdapter {\n private readonly children: ReadonlyArray<{ id: string; adapter: IAuditAdapter }>;\n private readonly logger: Logger;\n\n constructor(options: CompositeAuditAdapterOptions) {\n this.logger = options.logger ?? noopLogger;\n this.children = options.children.map(normalize);\n }\n\n /**\n * Fan the entry out to every child concurrently and await all of them. Never\n * throws; each child rejection is caught and logged with the child's identity.\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n if (this.children.length === 0) return;\n\n const results = await Promise.allSettled(\n // Wrap each child in Promise.resolve().then(...) so a child that throws\n // synchronously (rather than returning a rejected promise) is still captured.\n this.children.map((c) =>\n Promise.resolve().then(() => c.adapter.append(tenantId, instanceId, entry, instance)),\n ),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i]!;\n if (result.status === 'rejected') {\n const child = this.children[i]!;\n this.logger.error(\n `CompositeAuditAdapter: child \"${child.id}\" failed to append`,\n result.reason,\n { tenantId, instanceId, childId: child.id, childIndex: i },\n );\n }\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/plugins/audit/canonicalize.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/audit/HashChainAuditAdapter.ts","../../src/plugins/audit/RedactingAuditAdapter.ts","../../src/plugins/audit/CompositeAuditAdapter.ts"],"names":["createHash"],"mappings":";;;;;AAiBO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChD,YAAY,IAAA,EAAc;AACxB,IAAA,KAAA,CAAM,CAAA,6DAAA,EAAgE,IAAI,CAAA,EAAA,CAAI,CAAA;AAC9E,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAA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Q,IAAA,CAAK,QAAA,CAAS,CAAC,CAAA;AAC7B,QAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,UACV,CAAA,8BAAA,EAAiC,MAAM,EAAE,CAAA,kBAAA,CAAA;AAAA,UACzC,MAAA,CAAO,MAAA;AAAA,UACP,EAAE,QAAA,EAAU,UAAA,EAAY,SAAS,KAAA,CAAM,EAAA,EAAI,YAAY,CAAA;AAAE,SAC3D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF","file":"audit.cjs","sourcesContent":["/**\n * Deterministic canonical JSON serialization for hashing.\n *\n * Guarantees a stable, reproducible string for the same logical value regardless\n * of key insertion order, so the same record always produces the same hash:\n * - Object keys are emitted in lexicographic order (recursively).\n * - `Date` values are serialized to their ISO-8601 string.\n * - `undefined` properties (and `undefined` array elements) are encoded as `null`\n * so that presence/position is preserved deterministically.\n * - `bigint` is encoded as its decimal string; functions/symbols are encoded as `null`.\n * - Circular references are detected and rejected (the caller decides how to react),\n * rather than throwing the native, unstable `TypeError` deep inside JSON.stringify.\n *\n * This module performs no I/O and has no dependencies; it is pure and unit-testable.\n */\n\n/** Thrown by {@link canonicalize} when a circular reference is encountered. */\nexport class CircularReferenceError extends Error {\n constructor(path: string) {\n super(`Circular reference detected during canonicalization at path \"${path}\".`);\n this.name = 'CircularReferenceError';\n }\n}\n\n/**\n * Produce a deterministic JSON string for `value`.\n *\n * @param value - Any JavaScript value. Plain objects, arrays, strings, numbers,\n * booleans, `null`, `undefined`, `Date`, and `bigint` are supported.\n * @returns A stable string suitable for hashing.\n * @throws {CircularReferenceError} If the value graph contains a cycle.\n */\nexport function canonicalize(value: unknown): string {\n const seen = new Set<object>();\n\n const encode = (v: unknown, path: string): string => {\n if (v === null || v === undefined) return 'null';\n\n const t = typeof v;\n if (t === 'number') return Number.isFinite(v as number) ? String(v) : 'null';\n if (t === 'boolean') return (v as boolean) ? 'true' : 'false';\n if (t === 'bigint') return JSON.stringify((v as bigint).toString());\n if (t === 'string') return JSON.stringify(v);\n if (t === 'function' || t === 'symbol') return 'null';\n\n if (v instanceof Date) return JSON.stringify(v.toISOString());\n\n if (Array.isArray(v)) {\n if (seen.has(v)) throw new CircularReferenceError(path);\n seen.add(v);\n const parts = v.map((item, i) => encode(item, `${path}[${i}]`));\n seen.delete(v);\n return `[${parts.join(',')}]`;\n }\n\n if (t === 'object') {\n const obj = v as Record<string, unknown>;\n if (seen.has(obj)) throw new CircularReferenceError(path);\n seen.add(obj);\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const key of keys) {\n const child = obj[key];\n // Mirror JSON.stringify: skip keys whose value is undefined inside objects.\n if (child === undefined) continue;\n parts.push(`${JSON.stringify(key)}:${encode(child, `${path}.${key}`)}`);\n }\n seen.delete(obj);\n return `{${parts.join(',')}}`;\n }\n\n return 'null';\n };\n\n return encode(value, '$');\n}\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n CANNOT_CANCEL: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.\n SCHEDULER_SHUTDOWN: 503,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport { canonicalize, CircularReferenceError } from './canonicalize.js';\nimport { ApprovalValidationError } from '../../errors.js';\n\n/** The fixed sentinel used as the previous-hash of the genesis (first) entry. */\nexport const GENESIS_PREV_HASH = '0'.repeat(64);\n\n/** A single persisted record in a hash chain. The shape is intentionally exact. */\nexport interface ChainRecord {\n /** The original audit entry, captured verbatim. */\n readonly entry: AuditEntry;\n /** SHA-256 (hex) over the canonical serialization of `{ seq, prevHash, entry }`. */\n readonly hash: string;\n /** The `hash` of the preceding record, or {@link GENESIS_PREV_HASH} for the first. */\n readonly prevHash: string;\n /** Monotonic sequence number within this (tenant, instance) chain. */\n readonly seq: number;\n}\n\n/**\n * Persists a single chain record. Implementations may target any durable sink\n * (Kafka, S3 WORM bucket, append-only table, …). The record's `(tenantId, instanceId)`\n * is supplied alongside it so the sink can partition without inferring identity from\n * the entry. The adapter awaits this writer but tolerates rejection: a failed write\n * is logged and swallowed.\n */\nexport type ChainRecordWriter = (\n tenantId: string,\n instanceId: string,\n record: ChainRecord,\n) => Promise<void>;\n\n/** Reads back the ordered chain for a (tenant, instance). */\nexport type ChainRecordReader = (\n tenantId: string,\n instanceId: string,\n) => Promise<readonly ChainRecord[]>;\n\n/** Result of {@link HashChainAuditAdapter.verify}. */\nexport interface VerifyResult {\n /** True when every record's hash and linkage recompute correctly. */\n ok: boolean;\n /**\n * The lowest `seq` whose stored hash or `prevHash` linkage failed, or — for a\n * tail truncation — the first missing `seq` (the gap point at the end of the\n * chain). Present only when `ok` is false.\n */\n brokenAt?: number;\n}\n\n/** Constructor options for {@link HashChainAuditAdapter}. */\nexport interface HashChainAuditAdapterOptions {\n /**\n * Async sink for each persisted record. Defaults to an internal in-memory store.\n * If you supply a custom `writer`, also supply a matching {@link reader} so the\n * adapter can recompute the chain during {@link HashChainAuditAdapter.verify}.\n */\n writer?: ChainRecordWriter;\n /** Reads back the ordered chain for verification. Required when a custom `writer` is supplied. */\n reader?: ChainRecordReader;\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\n/** The composite chain key (tenant + instance) never collides across tenants or instances. */\nfunction chainKey(tenantId: string, instanceId: string): string {\n // Length-prefix the tenant id so that (\"a\", \"b:c\") and (\"a:b\", \"c\") cannot collide.\n return `${tenantId.length}:${tenantId}:${instanceId}`;\n}\n\n/**\n * Tamper-evident {@link IAuditAdapter}. Every appended entry is wrapped in a\n * {@link ChainRecord} whose `hash` is a SHA-256 over a canonical serialization of\n * `{ seq, prevHash, entry }`, with `prevHash` linking to the previous record's hash.\n * Any later mutation, deletion, or reordering of a record breaks the recomputed\n * chain, which {@link verify} detects and pinpoints.\n *\n * Chains are partitioned by `(tenantId, instanceId)`: separate instances or tenants\n * never share a sequence counter or hash linkage. Appends to the same chain are\n * serialized so concurrent calls cannot interleave `seq`/`prevHash`.\n *\n * **Tail-truncation detection.** A pure re-hash of the stored chain cannot, on its\n * own, detect that the *last* record(s) were dropped: a truncated prefix still\n * re-hashes and re-links perfectly. To close this gap the adapter records an\n * in-process **high-water mark** per `(tenantId, instanceId)` — the highest `seq`\n * it has ever appended (advanced before the writer is awaited). {@link verify}\n * compares the stored chain's last `seq` against this high-water mark and reports\n * `{ ok: false, brokenAt: <first missing seq> }` when the tail is short. Callers\n * who hold an external anchor (e.g. a durably persisted length) may also pass\n * `expectedLength` to {@link verify} to assert truncation **across process\n * restarts**, when the in-process high-water mark has been lost.\n *\n * *Limit:* with neither an in-process high-water mark (e.g. a fresh process that\n * never appended to this chain) nor an `expectedLength` argument, truncation of\n * the tail is undetectable — there is no record of how long the chain *should* be.\n *\n * `append` never throws: writer rejections and canonicalization failures are logged\n * and swallowed, honoring the {@link IAuditAdapter} must-not-throw contract.\n *\n * @example\n * ```ts\n * const audit = new HashChainAuditAdapter();\n * // ...wire as ApprovalEngineOptions.auditAdapter...\n * const result = await audit.verify(tenantId, instanceId); // { ok: true }\n * ```\n */\nexport class HashChainAuditAdapter implements IAuditAdapter {\n private readonly writer: ChainRecordWriter;\n private readonly reader: ChainRecordReader;\n private readonly logger: Logger;\n\n /** In-memory default store, keyed by composite chain key. Used only when no custom writer/reader. */\n private readonly store = new Map<string, ChainRecord[]>();\n /**\n * Last hash + seq per chain key, tracked in-process so the next append links\n * without re-reading the sink. The `seq` field doubles as the per-chain\n * **high-water mark**: the highest `seq` ever appended in this process, which\n * {@link verify} uses to detect a truncated tail.\n */\n private readonly heads = new Map<string, { prevHash: string; seq: number }>();\n /** Per-chain promise tail used to serialize appends to the same (tenant, instance). */\n private readonly locks = new Map<string, Promise<void>>();\n\n constructor(options: HashChainAuditAdapterOptions = {}) {\n this.logger = options.logger ?? noopLogger;\n\n if (options.writer && !options.reader) {\n // A custom sink with no reader cannot be verified; fail fast at construction\n // rather than silently producing a chain that verify() cannot inspect.\n throw new ApprovalValidationError(\n 'HashChainAuditAdapter: a custom `writer` requires a matching `reader` for verification.',\n );\n }\n\n this.writer =\n options.writer ??\n (async (tenantId, instanceId, record) => {\n const key = chainKey(tenantId, instanceId);\n const chain = this.store.get(key);\n if (chain) {\n chain.push(record);\n } else {\n this.store.set(key, [record]);\n }\n });\n\n this.reader =\n options.reader ??\n (async (tenantId, instanceId) => this.store.get(chainKey(tenantId, instanceId)) ?? []);\n }\n\n /**\n * Append an entry to the (tenant, instance) chain. Computes the next `seq` and\n * `prevHash`, hashes the canonical record, and persists via the injected writer.\n * Never throws.\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n _instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n const key = chainKey(tenantId, instanceId);\n\n // Serialize per-chain: chain the work onto the existing tail so two concurrent\n // appends to the same (tenant, instance) cannot read the same head.\n const prior = this.locks.get(key) ?? Promise.resolve();\n const work = prior.then(() => this.appendLocked(key, tenantId, instanceId, entry));\n // The lock tail must never reject (it would poison every subsequent append).\n this.locks.set(\n key,\n work.then(\n () => undefined,\n () => undefined,\n ),\n );\n await work;\n }\n\n private async appendLocked(\n key: string,\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n ): Promise<void> {\n try {\n const head = this.heads.get(key);\n const seq = head ? head.seq + 1 : 0;\n const prevHash = head ? head.prevHash : GENESIS_PREV_HASH;\n\n const hash = this.computeHash(seq, prevHash, entry);\n const record: ChainRecord = Object.freeze({ entry, hash, prevHash, seq });\n\n // Advance the in-process head BEFORE awaiting the writer so a slow or failing\n // writer cannot cause the next append to reuse this seq/prevHash. The chain's\n // logical integrity is independent of whether the sink durably accepted it.\n this.heads.set(key, { prevHash: hash, seq });\n\n try {\n await this.writer(tenantId, instanceId, record);\n } catch (err) {\n // Writer failure (including on the genesis entry) is logged and swallowed.\n // The in-process head already advanced, so subsequent appends stay linked;\n // if the sink dropped this record, verify() will surface the gap deterministically.\n this.logger.error(\n 'HashChainAuditAdapter: writer rejected; entry not durably persisted',\n err,\n { tenantId, instanceId, seq },\n );\n }\n } catch (err) {\n // Canonicalization/hashing failure (e.g. circular reference). Swallow per contract.\n if (err instanceof CircularReferenceError) {\n this.logger.error('HashChainAuditAdapter: entry could not be canonicalized', err, {\n tenantId,\n instanceId,\n });\n } else {\n this.logger.error('HashChainAuditAdapter: unexpected error during append', err, {\n tenantId,\n instanceId,\n });\n }\n }\n }\n\n /** Compute the SHA-256 (hex) hash for a record's `{ seq, prevHash, entry }`. */\n private computeHash(seq: number, prevHash: string, entry: AuditEntry): string {\n const canonical = canonicalize({ seq, prevHash, entry });\n return createHash('sha256').update(canonical, 'utf8').digest('hex');\n }\n\n /**\n * Recompute the entire chain for `(tenantId, instanceId)` from genesis and,\n * additionally, detect a truncated tail.\n *\n * Per-record integrity (tamper, deletion, reorder, broken linkage) is found by\n * re-hashing and re-linking from genesis. Tail truncation — dropping the last\n * record(s) — leaves a perfectly self-consistent prefix, so it is detected by\n * comparing the chain's last `seq` against an **expected high-water mark**:\n *\n * - `expectedLength`, when supplied, is the authoritative expected record count\n * (so the expected high-water `seq` is `expectedLength - 1`). Use this with an\n * external anchor to assert truncation even across process restarts.\n * - otherwise the in-process high-water mark recorded by {@link append} is used.\n *\n * When the stored chain is shorter than expected, `brokenAt` is the first\n * missing `seq` (the gap point at the tail). With neither an `expectedLength`\n * argument nor an in-process high-water mark, a truncated tail is undetectable.\n *\n * @param tenantId - Tenant partition.\n * @param instanceId - Instance partition.\n * @param expectedLength - Optional external anchor: the number of records the\n * chain is expected to contain. When provided it overrides the in-process\n * high-water mark for the truncation check.\n * @returns `{ ok: true }` for an untouched chain (and an empty chain when no\n * high-water mark/`expectedLength` says otherwise), otherwise\n * `{ ok: false, brokenAt }`.\n */\n async verify(\n tenantId: string,\n instanceId: string,\n expectedLength?: number,\n ): Promise<VerifyResult> {\n const key = chainKey(tenantId, instanceId);\n const chain = await this.reader(tenantId, instanceId);\n\n // Resolve the expected number of records: the explicit anchor wins; otherwise\n // fall back to the in-process high-water mark (highest appended seq + 1).\n let expectedCount: number | undefined;\n if (expectedLength !== undefined) {\n expectedCount = expectedLength;\n } else {\n const head = this.heads.get(key);\n if (head !== undefined) expectedCount = head.seq + 1;\n }\n\n // Empty chain: only \"ok\" if nothing was expected. If an anchor/high-water\n // mark says records should exist, the entire tail was truncated.\n if (chain.length === 0) {\n if (expectedCount !== undefined && expectedCount > 0) {\n return { ok: false, brokenAt: 0 };\n }\n return { ok: true };\n }\n\n let expectedPrev = GENESIS_PREV_HASH;\n for (let i = 0; i < chain.length; i++) {\n const record = chain[i]!;\n\n // Sequence must start at 0 and increment by exactly 1 (detects deletion/reorder/gap).\n if (record.seq !== i) return { ok: false, brokenAt: Math.min(record.seq, i) };\n\n // Linkage to the previous record's hash must hold.\n if (record.prevHash !== expectedPrev) return { ok: false, brokenAt: record.seq };\n\n // The stored hash must equal the recomputed hash of its content (detects tamper).\n let recomputed: string;\n try {\n recomputed = this.computeHash(record.seq, record.prevHash, record.entry);\n } catch {\n return { ok: false, brokenAt: record.seq };\n }\n if (recomputed !== record.hash) return { ok: false, brokenAt: record.seq };\n\n expectedPrev = record.hash;\n }\n\n // Tail-truncation check: the per-record loop above cannot see records that are\n // simply absent from the end. Compare the actual length against the expected\n // high-water mark; a short chain means the tail was dropped.\n if (expectedCount !== undefined && chain.length < expectedCount) {\n return { ok: false, brokenAt: chain.length };\n }\n\n return { ok: true };\n }\n\n /**\n * Read the ordered chain for `(tenantId, instanceId)`. Returns whatever the\n * configured reader yields (the default in-memory reader returns the live array;\n * callers should treat it as read-only).\n */\n async getChain(tenantId: string, instanceId: string): Promise<readonly ChainRecord[]> {\n return this.reader(tenantId, instanceId);\n }\n}\n","import type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** Default token substituted in place of redacted values. */\nexport const DEFAULT_REDACTION_MASK = '[REDACTED]';\n\n/** Constructor options for {@link RedactingAuditAdapter}. */\nexport interface RedactingAuditAdapterOptions {\n /**\n * The wrapped adapter that receives the redacted entry.\n */\n inner: IAuditAdapter;\n\n /**\n * Dot-delimited field paths to redact, scoped to the bag they live in.\n *\n * Paths target the structured value bags (`oldValue`, `newValue`) of an\n * {@link AuditEntry}. Prefix a path with `oldValue.` or `newValue.` to scope it,\n * or supply an unscoped path (e.g. `applicant.ssn`) to apply it to BOTH bags.\n *\n * A trailing `.*` wildcard redacts every direct child of the matched object\n * (e.g. `card.*` masks every field under `card`). A path that does not resolve\n * to an existing value is a no-op.\n *\n * @example ['newValue.applicant.ssn', 'card.*', 'oldValue.bankAccount']\n */\n fieldPaths?: string[];\n\n /**\n * Free-text top-level entry fields to redact wholesale (value replaced by the mask).\n * Defaults to `[]`. Common choices: `['comment', 'reason']`.\n */\n freeTextFields?: Array<'comment' | 'reason'>;\n\n /** Token used to replace redacted values. Defaults to {@link DEFAULT_REDACTION_MASK}. */\n mask?: string;\n\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\n/** Deep-clone a value, preserving `Date` instances and dropping functions/symbols. */\nfunction deepClone<T>(value: T): T {\n return cloneValue(value) as T;\n}\n\nfunction cloneValue(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n if (value instanceof Date) return new Date(value.getTime());\n if (Array.isArray(value)) return value.map((v) => cloneValue(v));\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = cloneValue(v);\n }\n return out;\n}\n\n/** A field path scoped to one or both structured bags. */\ninterface ParsedPath {\n bag: 'oldValue' | 'newValue' | 'both';\n /** Remaining segments after the optional bag prefix. */\n segments: string[];\n /** True when the final segment is the `*` wildcard. */\n wildcard: boolean;\n}\n\nfunction parsePath(raw: string): ParsedPath | null {\n const parts = raw.split('.').filter((p) => p.length > 0);\n if (parts.length === 0) return null;\n\n let bag: ParsedPath['bag'] = 'both';\n let segments = parts;\n if (parts[0] === 'oldValue' || parts[0] === 'newValue') {\n bag = parts[0];\n segments = parts.slice(1);\n }\n\n let wildcard = false;\n if (segments[segments.length - 1] === '*') {\n wildcard = true;\n segments = segments.slice(0, -1);\n }\n\n // A bare `oldValue.*` / `newValue.*` (wildcard with no remaining segments) masks\n // every direct child of that whole bag.\n if (segments.length === 0 && !wildcard) return null;\n return { bag, segments, wildcard };\n}\n\n/**\n * Apply one parsed path to a single bag object, masking in place. The bag has\n * already been deep-cloned by the caller, so mutation here is safe.\n */\nfunction redactInBag(bag: Record<string, unknown>, path: ParsedPath, mask: string): void {\n // Walk to the parent of the target. Any non-object along the way means the path\n // does not resolve — leave the structure untouched.\n let cursor: unknown = bag;\n for (let i = 0; i < path.segments.length - (path.wildcard ? 0 : 1); i++) {\n const seg = path.segments[i]!;\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n cursor = (cursor as Record<string, unknown>)[seg];\n }\n\n if (path.wildcard) {\n // After walking all segments, `cursor` is the object whose children we mask.\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n const target = cursor as Record<string, unknown>;\n for (const key of Object.keys(target)) {\n target[key] = mask;\n }\n return;\n }\n\n // Non-wildcard: `cursor` is the parent; mask the final key if it exists.\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n const parent = cursor as Record<string, unknown>;\n const finalKey = path.segments[path.segments.length - 1]!;\n if (Object.prototype.hasOwnProperty.call(parent, finalKey)) {\n parent[finalKey] = mask;\n }\n}\n\n/**\n * An {@link IAuditAdapter} decorator that strips configured PII from each entry\n * before forwarding to a wrapped adapter. The caller's original `entry` and\n * `instance` are never mutated — redaction operates on a deep clone.\n *\n * Redaction targets the structured bags (`oldValue`, `newValue`) by dot-path,\n * supports a trailing `.*` wildcard to mask every child of an object, and can\n * blank out free-text fields (`comment`, `reason`). Paths that do not resolve,\n * or that point at `null`/array/primitive values, are no-ops that leave the\n * entry structurally intact.\n *\n * @example\n * ```ts\n * const audit = new RedactingAuditAdapter({\n * inner: new HashChainAuditAdapter(),\n * fieldPaths: ['newValue.applicant.ssn', 'card.*'],\n * freeTextFields: ['comment', 'reason'],\n * });\n * ```\n */\nexport class RedactingAuditAdapter implements IAuditAdapter {\n private readonly inner: IAuditAdapter;\n private readonly parsedPaths: ParsedPath[];\n private readonly freeTextFields: ReadonlyArray<'comment' | 'reason'>;\n private readonly mask: string;\n private readonly logger: Logger;\n\n constructor(options: RedactingAuditAdapterOptions) {\n this.inner = options.inner;\n this.mask = options.mask ?? DEFAULT_REDACTION_MASK;\n this.freeTextFields = options.freeTextFields ?? [];\n this.logger = options.logger ?? noopLogger;\n this.parsedPaths = (options.fieldPaths ?? [])\n .map(parsePath)\n .filter((p): p is ParsedPath => p !== null);\n }\n\n /**\n * Deep-clone the entry, redact configured fields on the clone, then forward to\n * the wrapped adapter. The caller's `entry` reference and contents are unchanged.\n * Never throws (delegates the must-not-throw guarantee to the wrapped adapter and\n * swallows any unexpected local error).\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n let redacted: AuditEntry;\n try {\n redacted = this.redactEntry(entry);\n } catch (err) {\n // Redaction must never break the audit path. On the unexpected event that\n // cloning/redaction fails, log and forward the original entry unmodified so\n // the audit record is not silently dropped.\n this.logger.error('RedactingAuditAdapter: redaction failed; forwarding original entry', err, {\n tenantId,\n instanceId,\n });\n redacted = entry;\n }\n await this.inner.append(tenantId, instanceId, redacted, instance);\n }\n\n /** Produce a redacted deep clone of `entry` without touching the original. */\n private redactEntry(entry: AuditEntry): AuditEntry {\n const clone = deepClone(entry);\n\n // Free-text fields: blank the value wholesale if present and non-empty/defined.\n for (const field of this.freeTextFields) {\n if (clone[field] !== undefined) {\n clone[field] = this.mask;\n }\n }\n\n // Structured bags.\n for (const path of this.parsedPaths) {\n if ((path.bag === 'oldValue' || path.bag === 'both') && clone.oldValue) {\n redactInBag(clone.oldValue, path, this.mask);\n }\n if ((path.bag === 'newValue' || path.bag === 'both') && clone.newValue) {\n redactInBag(clone.newValue, path, this.mask);\n }\n }\n\n return clone;\n }\n}\n","import type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** A child adapter, optionally tagged with a stable identity for diagnostics. */\nexport interface CompositeChild {\n /** Human-readable identity used in logs when this child rejects (defaults to its index). */\n readonly id?: string;\n readonly adapter: IAuditAdapter;\n}\n\n/** Constructor options for {@link CompositeAuditAdapter}. */\nexport interface CompositeAuditAdapterOptions {\n /**\n * Child adapters to fan out to. Each may be a bare {@link IAuditAdapter} or a\n * {@link CompositeChild} carrying an `id` for clearer log attribution.\n */\n children: ReadonlyArray<IAuditAdapter | CompositeChild>;\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\nfunction normalize(\n child: IAuditAdapter | CompositeChild,\n index: number,\n): { id: string; adapter: IAuditAdapter } {\n if ('adapter' in child) {\n return { id: child.id ?? `child[${index}]`, adapter: child.adapter };\n }\n return { id: `child[${index}]`, adapter: child };\n}\n\n/**\n * An {@link IAuditAdapter} that fans `append` out to N child adapters concurrently.\n * Every child receives the same entry. The call awaits all children\n * ({@link Promise.allSettled}) and never throws: a rejecting child is logged with\n * its index/identity and does not prevent the other children from receiving the\n * entry. A composite with zero children is a no-op that resolves immediately.\n *\n * @example\n * ```ts\n * const audit = new CompositeAuditAdapter({\n * children: [\n * { id: 'hash-chain', adapter: new HashChainAuditAdapter() },\n * { id: 's3-worm', adapter: s3Adapter },\n * ],\n * });\n * ```\n */\nexport class CompositeAuditAdapter implements IAuditAdapter {\n private readonly children: ReadonlyArray<{ id: string; adapter: IAuditAdapter }>;\n private readonly logger: Logger;\n\n constructor(options: CompositeAuditAdapterOptions) {\n this.logger = options.logger ?? noopLogger;\n this.children = options.children.map(normalize);\n }\n\n /**\n * Fan the entry out to every child concurrently and await all of them. Never\n * throws; each child rejection is caught and logged with the child's identity.\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n if (this.children.length === 0) return;\n\n const results = await Promise.allSettled(\n // Wrap each child in Promise.resolve().then(...) so a child that throws\n // synchronously (rather than returning a rejected promise) is still captured.\n this.children.map((c) =>\n Promise.resolve().then(() => c.adapter.append(tenantId, instanceId, entry, instance)),\n ),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i]!;\n if (result.status === 'rejected') {\n const child = this.children[i]!;\n this.logger.error(\n `CompositeAuditAdapter: child \"${child.id}\" failed to append`,\n result.reason,\n { tenantId, instanceId, childId: child.id, childIndex: i },\n );\n }\n }\n }\n}\n"]}
@@ -68,13 +68,17 @@ var ApprovalError = class extends Error {
68
68
  toJSON() {
69
69
  return { code: this.code, message: this.message, name: this.name };
70
70
  }
71
+ /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */
71
72
  toHttpStatus() {
72
73
  const map = {
73
74
  NOT_FOUND: 404,
74
75
  CONFLICT: 409,
76
+ CANNOT_CANCEL: 409,
75
77
  FORBIDDEN: 403,
76
78
  VALIDATION: 422,
77
- TEMPLATE_NOT_FOUND: 404
79
+ TEMPLATE_NOT_FOUND: 404,
80
+ // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.
81
+ SCHEDULER_SHUTDOWN: 503
78
82
  };
79
83
  return map[this.code] ?? 500;
80
84
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/audit/canonicalize.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/audit/HashChainAuditAdapter.ts","../../src/plugins/audit/RedactingAuditAdapter.ts","../../src/plugins/audit/CompositeAuditAdapter.ts"],"names":[],"mappings":";;;AAiBO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChD,YAAY,IAAA,EAAc;AACxB,IAAA,KAAA,CAAM,CAAA,6DAAA,EAAgE,IAAI,CAAA,EAAA,CAAI,CAAA;AAC9E,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AACF;AAUO,SAAS,aAAa,KAAA,EAAwB;AACnD,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAE7B,EAAA,MAAM,MAAA,GAAS,CAAC,CAAA,EAAY,IAAA,KAAyB;AACnD,IAAA,IAAI,CAAA,KAAM,IAAA,IAAQ,CAAA,KAAM,MAAA,EAAW,OAAO,MAAA;AAE1C,IAAA,MAAM,IAAI,OAAO,CAAA;AACjB,IAAA,IAAI,CAAA,KAAM,UAAU,OAAO,MAAA,CAAO,SAAS,CAAW,CAAA,GAAI,MAAA,CAAO,CAAC,CAAA,GAAI,MAAA;AACtE,IAAA,IAAI,CAAA,KAAM,SAAA,EAAW,OAAQ,CAAA,GAAgB,MAAA,GAAS,OAAA;AACtD,IAAA,IAAI,MAAM,QAAA,EAAU,OAAO,KAAK,SAAA,CAAW,CAAA,CAAa,UAAU,CAAA;AAClE,IAAA,IAAI,CAAA,KAAM,QAAA,EAAU,OAAO,IAAA,CAAK,UAAU,CAAC,CAAA;AAC3C,IAAA,IAAI,CAAA,KAAM,UAAA,IAAc,CAAA,KAAM,QAAA,EAAU,OAAO,MAAA;AAE/C,IAAA,IAAI,aAAa,IAAA,EAAM,OAAO,KAA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AAA;AAAA,QAAI,CAAC,CAAA,KACjB,OAAA,CAAQ,OAAA,GAAU,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,CAAQ,MAAA,CAAO,QAAA,EAAU,UAAA,EAAY,KAAA,EAAO,QAAQ,CAAC;AAAA;AACtF,KACF;AAEA,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AACvC,MAAA,MAAM,MAAA,GAAS,QAAQ,CAAC,CAAA;AACxB,MAAA,IAAI,MAAA,CAAO,WAAW,UAAA,EAAY;AAChC,QAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,QAAA,CAAS,CAAC,CAAA;AAC7B,QAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,UACV,CAAA,8BAAA,EAAiC,MAAM,EAAE,CAAA,kBAAA,CAAA;AAAA,UACzC,MAAA,CAAO,MAAA;AAAA,UACP,EAAE,QAAA,EAAU,UAAA,EAAY,SAAS,KAAA,CAAM,EAAA,EAAI,YAAY,CAAA;AAAE,SAC3D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF","file":"audit.js","sourcesContent":["/**\n * Deterministic canonical JSON serialization for hashing.\n *\n * Guarantees a stable, reproducible string for the same logical value regardless\n * of key insertion order, so the same record always produces the same hash:\n * - Object keys are emitted in lexicographic order (recursively).\n * - `Date` values are serialized to their ISO-8601 string.\n * - `undefined` properties (and `undefined` array elements) are encoded as `null`\n * so that presence/position is preserved deterministically.\n * - `bigint` is encoded as its decimal string; functions/symbols are encoded as `null`.\n * - Circular references are detected and rejected (the caller decides how to react),\n * rather than throwing the native, unstable `TypeError` deep inside JSON.stringify.\n *\n * This module performs no I/O and has no dependencies; it is pure and unit-testable.\n */\n\n/** Thrown by {@link canonicalize} when a circular reference is encountered. */\nexport class CircularReferenceError extends Error {\n constructor(path: string) {\n super(`Circular reference detected during canonicalization at path \"${path}\".`);\n this.name = 'CircularReferenceError';\n }\n}\n\n/**\n * Produce a deterministic JSON string for `value`.\n *\n * @param value - Any JavaScript value. Plain objects, arrays, strings, numbers,\n * booleans, `null`, `undefined`, `Date`, and `bigint` are supported.\n * @returns A stable string suitable for hashing.\n * @throws {CircularReferenceError} If the value graph contains a cycle.\n */\nexport function canonicalize(value: unknown): string {\n const seen = new Set<object>();\n\n const encode = (v: unknown, path: string): string => {\n if (v === null || v === undefined) return 'null';\n\n const t = typeof v;\n if (t === 'number') return Number.isFinite(v as number) ? String(v) : 'null';\n if (t === 'boolean') return (v as boolean) ? 'true' : 'false';\n if (t === 'bigint') return JSON.stringify((v as bigint).toString());\n if (t === 'string') return JSON.stringify(v);\n if (t === 'function' || t === 'symbol') return 'null';\n\n if (v instanceof Date) return JSON.stringify(v.toISOString());\n\n if (Array.isArray(v)) {\n if (seen.has(v)) throw new CircularReferenceError(path);\n seen.add(v);\n const parts = v.map((item, i) => encode(item, `${path}[${i}]`));\n seen.delete(v);\n return `[${parts.join(',')}]`;\n }\n\n if (t === 'object') {\n const obj = v as Record<string, unknown>;\n if (seen.has(obj)) throw new CircularReferenceError(path);\n seen.add(obj);\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const key of keys) {\n const child = obj[key];\n // Mirror JSON.stringify: skip keys whose value is undefined inside objects.\n if (child === undefined) continue;\n parts.push(`${JSON.stringify(key)}:${encode(child, `${path}.${key}`)}`);\n }\n seen.delete(obj);\n return `{${parts.join(',')}}`;\n }\n\n return 'null';\n };\n\n return encode(value, '$');\n}\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport { canonicalize, CircularReferenceError } from './canonicalize.js';\nimport { ApprovalValidationError } from '../../errors.js';\n\n/** The fixed sentinel used as the previous-hash of the genesis (first) entry. */\nexport const GENESIS_PREV_HASH = '0'.repeat(64);\n\n/** A single persisted record in a hash chain. The shape is intentionally exact. */\nexport interface ChainRecord {\n /** The original audit entry, captured verbatim. */\n readonly entry: AuditEntry;\n /** SHA-256 (hex) over the canonical serialization of `{ seq, prevHash, entry }`. */\n readonly hash: string;\n /** The `hash` of the preceding record, or {@link GENESIS_PREV_HASH} for the first. */\n readonly prevHash: string;\n /** Monotonic sequence number within this (tenant, instance) chain. */\n readonly seq: number;\n}\n\n/**\n * Persists a single chain record. Implementations may target any durable sink\n * (Kafka, S3 WORM bucket, append-only table, …). The record's `(tenantId, instanceId)`\n * is supplied alongside it so the sink can partition without inferring identity from\n * the entry. The adapter awaits this writer but tolerates rejection: a failed write\n * is logged and swallowed.\n */\nexport type ChainRecordWriter = (\n tenantId: string,\n instanceId: string,\n record: ChainRecord,\n) => Promise<void>;\n\n/** Reads back the ordered chain for a (tenant, instance). */\nexport type ChainRecordReader = (\n tenantId: string,\n instanceId: string,\n) => Promise<readonly ChainRecord[]>;\n\n/** Result of {@link HashChainAuditAdapter.verify}. */\nexport interface VerifyResult {\n /** True when every record's hash and linkage recompute correctly. */\n ok: boolean;\n /**\n * The lowest `seq` whose stored hash or `prevHash` linkage failed, or — for a\n * tail truncation — the first missing `seq` (the gap point at the end of the\n * chain). Present only when `ok` is false.\n */\n brokenAt?: number;\n}\n\n/** Constructor options for {@link HashChainAuditAdapter}. */\nexport interface HashChainAuditAdapterOptions {\n /**\n * Async sink for each persisted record. Defaults to an internal in-memory store.\n * If you supply a custom `writer`, also supply a matching {@link reader} so the\n * adapter can recompute the chain during {@link HashChainAuditAdapter.verify}.\n */\n writer?: ChainRecordWriter;\n /** Reads back the ordered chain for verification. Required when a custom `writer` is supplied. */\n reader?: ChainRecordReader;\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\n/** The composite chain key (tenant + instance) never collides across tenants or instances. */\nfunction chainKey(tenantId: string, instanceId: string): string {\n // Length-prefix the tenant id so that (\"a\", \"b:c\") and (\"a:b\", \"c\") cannot collide.\n return `${tenantId.length}:${tenantId}:${instanceId}`;\n}\n\n/**\n * Tamper-evident {@link IAuditAdapter}. Every appended entry is wrapped in a\n * {@link ChainRecord} whose `hash` is a SHA-256 over a canonical serialization of\n * `{ seq, prevHash, entry }`, with `prevHash` linking to the previous record's hash.\n * Any later mutation, deletion, or reordering of a record breaks the recomputed\n * chain, which {@link verify} detects and pinpoints.\n *\n * Chains are partitioned by `(tenantId, instanceId)`: separate instances or tenants\n * never share a sequence counter or hash linkage. Appends to the same chain are\n * serialized so concurrent calls cannot interleave `seq`/`prevHash`.\n *\n * **Tail-truncation detection.** A pure re-hash of the stored chain cannot, on its\n * own, detect that the *last* record(s) were dropped: a truncated prefix still\n * re-hashes and re-links perfectly. To close this gap the adapter records an\n * in-process **high-water mark** per `(tenantId, instanceId)` — the highest `seq`\n * it has ever appended (advanced before the writer is awaited). {@link verify}\n * compares the stored chain's last `seq` against this high-water mark and reports\n * `{ ok: false, brokenAt: <first missing seq> }` when the tail is short. Callers\n * who hold an external anchor (e.g. a durably persisted length) may also pass\n * `expectedLength` to {@link verify} to assert truncation **across process\n * restarts**, when the in-process high-water mark has been lost.\n *\n * *Limit:* with neither an in-process high-water mark (e.g. a fresh process that\n * never appended to this chain) nor an `expectedLength` argument, truncation of\n * the tail is undetectable — there is no record of how long the chain *should* be.\n *\n * `append` never throws: writer rejections and canonicalization failures are logged\n * and swallowed, honoring the {@link IAuditAdapter} must-not-throw contract.\n *\n * @example\n * ```ts\n * const audit = new HashChainAuditAdapter();\n * // ...wire as ApprovalEngineOptions.auditAdapter...\n * const result = await audit.verify(tenantId, instanceId); // { ok: true }\n * ```\n */\nexport class HashChainAuditAdapter implements IAuditAdapter {\n private readonly writer: ChainRecordWriter;\n private readonly reader: ChainRecordReader;\n private readonly logger: Logger;\n\n /** In-memory default store, keyed by composite chain key. Used only when no custom writer/reader. */\n private readonly store = new Map<string, ChainRecord[]>();\n /**\n * Last hash + seq per chain key, tracked in-process so the next append links\n * without re-reading the sink. The `seq` field doubles as the per-chain\n * **high-water mark**: the highest `seq` ever appended in this process, which\n * {@link verify} uses to detect a truncated tail.\n */\n private readonly heads = new Map<string, { prevHash: string; seq: number }>();\n /** Per-chain promise tail used to serialize appends to the same (tenant, instance). */\n private readonly locks = new Map<string, Promise<void>>();\n\n constructor(options: HashChainAuditAdapterOptions = {}) {\n this.logger = options.logger ?? noopLogger;\n\n if (options.writer && !options.reader) {\n // A custom sink with no reader cannot be verified; fail fast at construction\n // rather than silently producing a chain that verify() cannot inspect.\n throw new ApprovalValidationError(\n 'HashChainAuditAdapter: a custom `writer` requires a matching `reader` for verification.',\n );\n }\n\n this.writer =\n options.writer ??\n (async (tenantId, instanceId, record) => {\n const key = chainKey(tenantId, instanceId);\n const chain = this.store.get(key);\n if (chain) {\n chain.push(record);\n } else {\n this.store.set(key, [record]);\n }\n });\n\n this.reader =\n options.reader ??\n (async (tenantId, instanceId) => this.store.get(chainKey(tenantId, instanceId)) ?? []);\n }\n\n /**\n * Append an entry to the (tenant, instance) chain. Computes the next `seq` and\n * `prevHash`, hashes the canonical record, and persists via the injected writer.\n * Never throws.\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n _instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n const key = chainKey(tenantId, instanceId);\n\n // Serialize per-chain: chain the work onto the existing tail so two concurrent\n // appends to the same (tenant, instance) cannot read the same head.\n const prior = this.locks.get(key) ?? Promise.resolve();\n const work = prior.then(() => this.appendLocked(key, tenantId, instanceId, entry));\n // The lock tail must never reject (it would poison every subsequent append).\n this.locks.set(\n key,\n work.then(\n () => undefined,\n () => undefined,\n ),\n );\n await work;\n }\n\n private async appendLocked(\n key: string,\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n ): Promise<void> {\n try {\n const head = this.heads.get(key);\n const seq = head ? head.seq + 1 : 0;\n const prevHash = head ? head.prevHash : GENESIS_PREV_HASH;\n\n const hash = this.computeHash(seq, prevHash, entry);\n const record: ChainRecord = Object.freeze({ entry, hash, prevHash, seq });\n\n // Advance the in-process head BEFORE awaiting the writer so a slow or failing\n // writer cannot cause the next append to reuse this seq/prevHash. The chain's\n // logical integrity is independent of whether the sink durably accepted it.\n this.heads.set(key, { prevHash: hash, seq });\n\n try {\n await this.writer(tenantId, instanceId, record);\n } catch (err) {\n // Writer failure (including on the genesis entry) is logged and swallowed.\n // The in-process head already advanced, so subsequent appends stay linked;\n // if the sink dropped this record, verify() will surface the gap deterministically.\n this.logger.error(\n 'HashChainAuditAdapter: writer rejected; entry not durably persisted',\n err,\n { tenantId, instanceId, seq },\n );\n }\n } catch (err) {\n // Canonicalization/hashing failure (e.g. circular reference). Swallow per contract.\n if (err instanceof CircularReferenceError) {\n this.logger.error('HashChainAuditAdapter: entry could not be canonicalized', err, {\n tenantId,\n instanceId,\n });\n } else {\n this.logger.error('HashChainAuditAdapter: unexpected error during append', err, {\n tenantId,\n instanceId,\n });\n }\n }\n }\n\n /** Compute the SHA-256 (hex) hash for a record's `{ seq, prevHash, entry }`. */\n private computeHash(seq: number, prevHash: string, entry: AuditEntry): string {\n const canonical = canonicalize({ seq, prevHash, entry });\n return createHash('sha256').update(canonical, 'utf8').digest('hex');\n }\n\n /**\n * Recompute the entire chain for `(tenantId, instanceId)` from genesis and,\n * additionally, detect a truncated tail.\n *\n * Per-record integrity (tamper, deletion, reorder, broken linkage) is found by\n * re-hashing and re-linking from genesis. Tail truncation — dropping the last\n * record(s) — leaves a perfectly self-consistent prefix, so it is detected by\n * comparing the chain's last `seq` against an **expected high-water mark**:\n *\n * - `expectedLength`, when supplied, is the authoritative expected record count\n * (so the expected high-water `seq` is `expectedLength - 1`). Use this with an\n * external anchor to assert truncation even across process restarts.\n * - otherwise the in-process high-water mark recorded by {@link append} is used.\n *\n * When the stored chain is shorter than expected, `brokenAt` is the first\n * missing `seq` (the gap point at the tail). With neither an `expectedLength`\n * argument nor an in-process high-water mark, a truncated tail is undetectable.\n *\n * @param tenantId - Tenant partition.\n * @param instanceId - Instance partition.\n * @param expectedLength - Optional external anchor: the number of records the\n * chain is expected to contain. When provided it overrides the in-process\n * high-water mark for the truncation check.\n * @returns `{ ok: true }` for an untouched chain (and an empty chain when no\n * high-water mark/`expectedLength` says otherwise), otherwise\n * `{ ok: false, brokenAt }`.\n */\n async verify(\n tenantId: string,\n instanceId: string,\n expectedLength?: number,\n ): Promise<VerifyResult> {\n const key = chainKey(tenantId, instanceId);\n const chain = await this.reader(tenantId, instanceId);\n\n // Resolve the expected number of records: the explicit anchor wins; otherwise\n // fall back to the in-process high-water mark (highest appended seq + 1).\n let expectedCount: number | undefined;\n if (expectedLength !== undefined) {\n expectedCount = expectedLength;\n } else {\n const head = this.heads.get(key);\n if (head !== undefined) expectedCount = head.seq + 1;\n }\n\n // Empty chain: only \"ok\" if nothing was expected. If an anchor/high-water\n // mark says records should exist, the entire tail was truncated.\n if (chain.length === 0) {\n if (expectedCount !== undefined && expectedCount > 0) {\n return { ok: false, brokenAt: 0 };\n }\n return { ok: true };\n }\n\n let expectedPrev = GENESIS_PREV_HASH;\n for (let i = 0; i < chain.length; i++) {\n const record = chain[i]!;\n\n // Sequence must start at 0 and increment by exactly 1 (detects deletion/reorder/gap).\n if (record.seq !== i) return { ok: false, brokenAt: Math.min(record.seq, i) };\n\n // Linkage to the previous record's hash must hold.\n if (record.prevHash !== expectedPrev) return { ok: false, brokenAt: record.seq };\n\n // The stored hash must equal the recomputed hash of its content (detects tamper).\n let recomputed: string;\n try {\n recomputed = this.computeHash(record.seq, record.prevHash, record.entry);\n } catch {\n return { ok: false, brokenAt: record.seq };\n }\n if (recomputed !== record.hash) return { ok: false, brokenAt: record.seq };\n\n expectedPrev = record.hash;\n }\n\n // Tail-truncation check: the per-record loop above cannot see records that are\n // simply absent from the end. Compare the actual length against the expected\n // high-water mark; a short chain means the tail was dropped.\n if (expectedCount !== undefined && chain.length < expectedCount) {\n return { ok: false, brokenAt: chain.length };\n }\n\n return { ok: true };\n }\n\n /**\n * Read the ordered chain for `(tenantId, instanceId)`. Returns whatever the\n * configured reader yields (the default in-memory reader returns the live array;\n * callers should treat it as read-only).\n */\n async getChain(tenantId: string, instanceId: string): Promise<readonly ChainRecord[]> {\n return this.reader(tenantId, instanceId);\n }\n}\n","import type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** Default token substituted in place of redacted values. */\nexport const DEFAULT_REDACTION_MASK = '[REDACTED]';\n\n/** Constructor options for {@link RedactingAuditAdapter}. */\nexport interface RedactingAuditAdapterOptions {\n /**\n * The wrapped adapter that receives the redacted entry.\n */\n inner: IAuditAdapter;\n\n /**\n * Dot-delimited field paths to redact, scoped to the bag they live in.\n *\n * Paths target the structured value bags (`oldValue`, `newValue`) of an\n * {@link AuditEntry}. Prefix a path with `oldValue.` or `newValue.` to scope it,\n * or supply an unscoped path (e.g. `applicant.ssn`) to apply it to BOTH bags.\n *\n * A trailing `.*` wildcard redacts every direct child of the matched object\n * (e.g. `card.*` masks every field under `card`). A path that does not resolve\n * to an existing value is a no-op.\n *\n * @example ['newValue.applicant.ssn', 'card.*', 'oldValue.bankAccount']\n */\n fieldPaths?: string[];\n\n /**\n * Free-text top-level entry fields to redact wholesale (value replaced by the mask).\n * Defaults to `[]`. Common choices: `['comment', 'reason']`.\n */\n freeTextFields?: Array<'comment' | 'reason'>;\n\n /** Token used to replace redacted values. Defaults to {@link DEFAULT_REDACTION_MASK}. */\n mask?: string;\n\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\n/** Deep-clone a value, preserving `Date` instances and dropping functions/symbols. */\nfunction deepClone<T>(value: T): T {\n return cloneValue(value) as T;\n}\n\nfunction cloneValue(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n if (value instanceof Date) return new Date(value.getTime());\n if (Array.isArray(value)) return value.map((v) => cloneValue(v));\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = cloneValue(v);\n }\n return out;\n}\n\n/** A field path scoped to one or both structured bags. */\ninterface ParsedPath {\n bag: 'oldValue' | 'newValue' | 'both';\n /** Remaining segments after the optional bag prefix. */\n segments: string[];\n /** True when the final segment is the `*` wildcard. */\n wildcard: boolean;\n}\n\nfunction parsePath(raw: string): ParsedPath | null {\n const parts = raw.split('.').filter((p) => p.length > 0);\n if (parts.length === 0) return null;\n\n let bag: ParsedPath['bag'] = 'both';\n let segments = parts;\n if (parts[0] === 'oldValue' || parts[0] === 'newValue') {\n bag = parts[0];\n segments = parts.slice(1);\n }\n\n let wildcard = false;\n if (segments[segments.length - 1] === '*') {\n wildcard = true;\n segments = segments.slice(0, -1);\n }\n\n // A bare `oldValue.*` / `newValue.*` (wildcard with no remaining segments) masks\n // every direct child of that whole bag.\n if (segments.length === 0 && !wildcard) return null;\n return { bag, segments, wildcard };\n}\n\n/**\n * Apply one parsed path to a single bag object, masking in place. The bag has\n * already been deep-cloned by the caller, so mutation here is safe.\n */\nfunction redactInBag(bag: Record<string, unknown>, path: ParsedPath, mask: string): void {\n // Walk to the parent of the target. Any non-object along the way means the path\n // does not resolve — leave the structure untouched.\n let cursor: unknown = bag;\n for (let i = 0; i < path.segments.length - (path.wildcard ? 0 : 1); i++) {\n const seg = path.segments[i]!;\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n cursor = (cursor as Record<string, unknown>)[seg];\n }\n\n if (path.wildcard) {\n // After walking all segments, `cursor` is the object whose children we mask.\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n const target = cursor as Record<string, unknown>;\n for (const key of Object.keys(target)) {\n target[key] = mask;\n }\n return;\n }\n\n // Non-wildcard: `cursor` is the parent; mask the final key if it exists.\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n const parent = cursor as Record<string, unknown>;\n const finalKey = path.segments[path.segments.length - 1]!;\n if (Object.prototype.hasOwnProperty.call(parent, finalKey)) {\n parent[finalKey] = mask;\n }\n}\n\n/**\n * An {@link IAuditAdapter} decorator that strips configured PII from each entry\n * before forwarding to a wrapped adapter. The caller's original `entry` and\n * `instance` are never mutated — redaction operates on a deep clone.\n *\n * Redaction targets the structured bags (`oldValue`, `newValue`) by dot-path,\n * supports a trailing `.*` wildcard to mask every child of an object, and can\n * blank out free-text fields (`comment`, `reason`). Paths that do not resolve,\n * or that point at `null`/array/primitive values, are no-ops that leave the\n * entry structurally intact.\n *\n * @example\n * ```ts\n * const audit = new RedactingAuditAdapter({\n * inner: new HashChainAuditAdapter(),\n * fieldPaths: ['newValue.applicant.ssn', 'card.*'],\n * freeTextFields: ['comment', 'reason'],\n * });\n * ```\n */\nexport class RedactingAuditAdapter implements IAuditAdapter {\n private readonly inner: IAuditAdapter;\n private readonly parsedPaths: ParsedPath[];\n private readonly freeTextFields: ReadonlyArray<'comment' | 'reason'>;\n private readonly mask: string;\n private readonly logger: Logger;\n\n constructor(options: RedactingAuditAdapterOptions) {\n this.inner = options.inner;\n this.mask = options.mask ?? DEFAULT_REDACTION_MASK;\n this.freeTextFields = options.freeTextFields ?? [];\n this.logger = options.logger ?? noopLogger;\n this.parsedPaths = (options.fieldPaths ?? [])\n .map(parsePath)\n .filter((p): p is ParsedPath => p !== null);\n }\n\n /**\n * Deep-clone the entry, redact configured fields on the clone, then forward to\n * the wrapped adapter. The caller's `entry` reference and contents are unchanged.\n * Never throws (delegates the must-not-throw guarantee to the wrapped adapter and\n * swallows any unexpected local error).\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n let redacted: AuditEntry;\n try {\n redacted = this.redactEntry(entry);\n } catch (err) {\n // Redaction must never break the audit path. On the unexpected event that\n // cloning/redaction fails, log and forward the original entry unmodified so\n // the audit record is not silently dropped.\n this.logger.error('RedactingAuditAdapter: redaction failed; forwarding original entry', err, {\n tenantId,\n instanceId,\n });\n redacted = entry;\n }\n await this.inner.append(tenantId, instanceId, redacted, instance);\n }\n\n /** Produce a redacted deep clone of `entry` without touching the original. */\n private redactEntry(entry: AuditEntry): AuditEntry {\n const clone = deepClone(entry);\n\n // Free-text fields: blank the value wholesale if present and non-empty/defined.\n for (const field of this.freeTextFields) {\n if (clone[field] !== undefined) {\n clone[field] = this.mask;\n }\n }\n\n // Structured bags.\n for (const path of this.parsedPaths) {\n if ((path.bag === 'oldValue' || path.bag === 'both') && clone.oldValue) {\n redactInBag(clone.oldValue, path, this.mask);\n }\n if ((path.bag === 'newValue' || path.bag === 'both') && clone.newValue) {\n redactInBag(clone.newValue, path, this.mask);\n }\n }\n\n return clone;\n }\n}\n","import type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** A child adapter, optionally tagged with a stable identity for diagnostics. */\nexport interface CompositeChild {\n /** Human-readable identity used in logs when this child rejects (defaults to its index). */\n readonly id?: string;\n readonly adapter: IAuditAdapter;\n}\n\n/** Constructor options for {@link CompositeAuditAdapter}. */\nexport interface CompositeAuditAdapterOptions {\n /**\n * Child adapters to fan out to. Each may be a bare {@link IAuditAdapter} or a\n * {@link CompositeChild} carrying an `id` for clearer log attribution.\n */\n children: ReadonlyArray<IAuditAdapter | CompositeChild>;\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\nfunction normalize(\n child: IAuditAdapter | CompositeChild,\n index: number,\n): { id: string; adapter: IAuditAdapter } {\n if ('adapter' in child) {\n return { id: child.id ?? `child[${index}]`, adapter: child.adapter };\n }\n return { id: `child[${index}]`, adapter: child };\n}\n\n/**\n * An {@link IAuditAdapter} that fans `append` out to N child adapters concurrently.\n * Every child receives the same entry. The call awaits all children\n * ({@link Promise.allSettled}) and never throws: a rejecting child is logged with\n * its index/identity and does not prevent the other children from receiving the\n * entry. A composite with zero children is a no-op that resolves immediately.\n *\n * @example\n * ```ts\n * const audit = new CompositeAuditAdapter({\n * children: [\n * { id: 'hash-chain', adapter: new HashChainAuditAdapter() },\n * { id: 's3-worm', adapter: s3Adapter },\n * ],\n * });\n * ```\n */\nexport class CompositeAuditAdapter implements IAuditAdapter {\n private readonly children: ReadonlyArray<{ id: string; adapter: IAuditAdapter }>;\n private readonly logger: Logger;\n\n constructor(options: CompositeAuditAdapterOptions) {\n this.logger = options.logger ?? noopLogger;\n this.children = options.children.map(normalize);\n }\n\n /**\n * Fan the entry out to every child concurrently and await all of them. Never\n * throws; each child rejection is caught and logged with the child's identity.\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n if (this.children.length === 0) return;\n\n const results = await Promise.allSettled(\n // Wrap each child in Promise.resolve().then(...) so a child that throws\n // synchronously (rather than returning a rejected promise) is still captured.\n this.children.map((c) =>\n Promise.resolve().then(() => c.adapter.append(tenantId, instanceId, entry, instance)),\n ),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i]!;\n if (result.status === 'rejected') {\n const child = this.children[i]!;\n this.logger.error(\n `CompositeAuditAdapter: child \"${child.id}\" failed to append`,\n result.reason,\n { tenantId, instanceId, childId: child.id, childIndex: i },\n );\n }\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/plugins/audit/canonicalize.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/audit/HashChain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AAA,EAAU,UAAA,EAAY,KAAA,EAAO,QAAQ,CAAC;AAAA;AACtF,KACF;AAEA,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AACvC,MAAA,MAAM,MAAA,GAAS,QAAQ,CAAC,CAAA;AACxB,MAAA,IAAI,MAAA,CAAO,WAAW,UAAA,EAAY;AAChC,QAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,QAAA,CAAS,CAAC,CAAA;AAC7B,QAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,UACV,CAAA,8BAAA,EAAiC,MAAM,EAAE,CAAA,kBAAA,CAAA;AAAA,UACzC,MAAA,CAAO,MAAA;AAAA,UACP,EAAE,QAAA,EAAU,UAAA,EAAY,SAAS,KAAA,CAAM,EAAA,EAAI,YAAY,CAAA;AAAE,SAC3D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF","file":"audit.js","sourcesContent":["/**\n * Deterministic canonical JSON serialization for hashing.\n *\n * Guarantees a stable, reproducible string for the same logical value regardless\n * of key insertion order, so the same record always produces the same hash:\n * - Object keys are emitted in lexicographic order (recursively).\n * - `Date` values are serialized to their ISO-8601 string.\n * - `undefined` properties (and `undefined` array elements) are encoded as `null`\n * so that presence/position is preserved deterministically.\n * - `bigint` is encoded as its decimal string; functions/symbols are encoded as `null`.\n * - Circular references are detected and rejected (the caller decides how to react),\n * rather than throwing the native, unstable `TypeError` deep inside JSON.stringify.\n *\n * This module performs no I/O and has no dependencies; it is pure and unit-testable.\n */\n\n/** Thrown by {@link canonicalize} when a circular reference is encountered. */\nexport class CircularReferenceError extends Error {\n constructor(path: string) {\n super(`Circular reference detected during canonicalization at path \"${path}\".`);\n this.name = 'CircularReferenceError';\n }\n}\n\n/**\n * Produce a deterministic JSON string for `value`.\n *\n * @param value - Any JavaScript value. Plain objects, arrays, strings, numbers,\n * booleans, `null`, `undefined`, `Date`, and `bigint` are supported.\n * @returns A stable string suitable for hashing.\n * @throws {CircularReferenceError} If the value graph contains a cycle.\n */\nexport function canonicalize(value: unknown): string {\n const seen = new Set<object>();\n\n const encode = (v: unknown, path: string): string => {\n if (v === null || v === undefined) return 'null';\n\n const t = typeof v;\n if (t === 'number') return Number.isFinite(v as number) ? String(v) : 'null';\n if (t === 'boolean') return (v as boolean) ? 'true' : 'false';\n if (t === 'bigint') return JSON.stringify((v as bigint).toString());\n if (t === 'string') return JSON.stringify(v);\n if (t === 'function' || t === 'symbol') return 'null';\n\n if (v instanceof Date) return JSON.stringify(v.toISOString());\n\n if (Array.isArray(v)) {\n if (seen.has(v)) throw new CircularReferenceError(path);\n seen.add(v);\n const parts = v.map((item, i) => encode(item, `${path}[${i}]`));\n seen.delete(v);\n return `[${parts.join(',')}]`;\n }\n\n if (t === 'object') {\n const obj = v as Record<string, unknown>;\n if (seen.has(obj)) throw new CircularReferenceError(path);\n seen.add(obj);\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const key of keys) {\n const child = obj[key];\n // Mirror JSON.stringify: skip keys whose value is undefined inside objects.\n if (child === undefined) continue;\n parts.push(`${JSON.stringify(key)}:${encode(child, `${path}.${key}`)}`);\n }\n seen.delete(obj);\n return `{${parts.join(',')}}`;\n }\n\n return 'null';\n };\n\n return encode(value, '$');\n}\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n CANNOT_CANCEL: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.\n SCHEDULER_SHUTDOWN: 503,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport { canonicalize, CircularReferenceError } from './canonicalize.js';\nimport { ApprovalValidationError } from '../../errors.js';\n\n/** The fixed sentinel used as the previous-hash of the genesis (first) entry. */\nexport const GENESIS_PREV_HASH = '0'.repeat(64);\n\n/** A single persisted record in a hash chain. The shape is intentionally exact. */\nexport interface ChainRecord {\n /** The original audit entry, captured verbatim. */\n readonly entry: AuditEntry;\n /** SHA-256 (hex) over the canonical serialization of `{ seq, prevHash, entry }`. */\n readonly hash: string;\n /** The `hash` of the preceding record, or {@link GENESIS_PREV_HASH} for the first. */\n readonly prevHash: string;\n /** Monotonic sequence number within this (tenant, instance) chain. */\n readonly seq: number;\n}\n\n/**\n * Persists a single chain record. Implementations may target any durable sink\n * (Kafka, S3 WORM bucket, append-only table, …). The record's `(tenantId, instanceId)`\n * is supplied alongside it so the sink can partition without inferring identity from\n * the entry. The adapter awaits this writer but tolerates rejection: a failed write\n * is logged and swallowed.\n */\nexport type ChainRecordWriter = (\n tenantId: string,\n instanceId: string,\n record: ChainRecord,\n) => Promise<void>;\n\n/** Reads back the ordered chain for a (tenant, instance). */\nexport type ChainRecordReader = (\n tenantId: string,\n instanceId: string,\n) => Promise<readonly ChainRecord[]>;\n\n/** Result of {@link HashChainAuditAdapter.verify}. */\nexport interface VerifyResult {\n /** True when every record's hash and linkage recompute correctly. */\n ok: boolean;\n /**\n * The lowest `seq` whose stored hash or `prevHash` linkage failed, or — for a\n * tail truncation — the first missing `seq` (the gap point at the end of the\n * chain). Present only when `ok` is false.\n */\n brokenAt?: number;\n}\n\n/** Constructor options for {@link HashChainAuditAdapter}. */\nexport interface HashChainAuditAdapterOptions {\n /**\n * Async sink for each persisted record. Defaults to an internal in-memory store.\n * If you supply a custom `writer`, also supply a matching {@link reader} so the\n * adapter can recompute the chain during {@link HashChainAuditAdapter.verify}.\n */\n writer?: ChainRecordWriter;\n /** Reads back the ordered chain for verification. Required when a custom `writer` is supplied. */\n reader?: ChainRecordReader;\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\n/** The composite chain key (tenant + instance) never collides across tenants or instances. */\nfunction chainKey(tenantId: string, instanceId: string): string {\n // Length-prefix the tenant id so that (\"a\", \"b:c\") and (\"a:b\", \"c\") cannot collide.\n return `${tenantId.length}:${tenantId}:${instanceId}`;\n}\n\n/**\n * Tamper-evident {@link IAuditAdapter}. Every appended entry is wrapped in a\n * {@link ChainRecord} whose `hash` is a SHA-256 over a canonical serialization of\n * `{ seq, prevHash, entry }`, with `prevHash` linking to the previous record's hash.\n * Any later mutation, deletion, or reordering of a record breaks the recomputed\n * chain, which {@link verify} detects and pinpoints.\n *\n * Chains are partitioned by `(tenantId, instanceId)`: separate instances or tenants\n * never share a sequence counter or hash linkage. Appends to the same chain are\n * serialized so concurrent calls cannot interleave `seq`/`prevHash`.\n *\n * **Tail-truncation detection.** A pure re-hash of the stored chain cannot, on its\n * own, detect that the *last* record(s) were dropped: a truncated prefix still\n * re-hashes and re-links perfectly. To close this gap the adapter records an\n * in-process **high-water mark** per `(tenantId, instanceId)` — the highest `seq`\n * it has ever appended (advanced before the writer is awaited). {@link verify}\n * compares the stored chain's last `seq` against this high-water mark and reports\n * `{ ok: false, brokenAt: <first missing seq> }` when the tail is short. Callers\n * who hold an external anchor (e.g. a durably persisted length) may also pass\n * `expectedLength` to {@link verify} to assert truncation **across process\n * restarts**, when the in-process high-water mark has been lost.\n *\n * *Limit:* with neither an in-process high-water mark (e.g. a fresh process that\n * never appended to this chain) nor an `expectedLength` argument, truncation of\n * the tail is undetectable — there is no record of how long the chain *should* be.\n *\n * `append` never throws: writer rejections and canonicalization failures are logged\n * and swallowed, honoring the {@link IAuditAdapter} must-not-throw contract.\n *\n * @example\n * ```ts\n * const audit = new HashChainAuditAdapter();\n * // ...wire as ApprovalEngineOptions.auditAdapter...\n * const result = await audit.verify(tenantId, instanceId); // { ok: true }\n * ```\n */\nexport class HashChainAuditAdapter implements IAuditAdapter {\n private readonly writer: ChainRecordWriter;\n private readonly reader: ChainRecordReader;\n private readonly logger: Logger;\n\n /** In-memory default store, keyed by composite chain key. Used only when no custom writer/reader. */\n private readonly store = new Map<string, ChainRecord[]>();\n /**\n * Last hash + seq per chain key, tracked in-process so the next append links\n * without re-reading the sink. The `seq` field doubles as the per-chain\n * **high-water mark**: the highest `seq` ever appended in this process, which\n * {@link verify} uses to detect a truncated tail.\n */\n private readonly heads = new Map<string, { prevHash: string; seq: number }>();\n /** Per-chain promise tail used to serialize appends to the same (tenant, instance). */\n private readonly locks = new Map<string, Promise<void>>();\n\n constructor(options: HashChainAuditAdapterOptions = {}) {\n this.logger = options.logger ?? noopLogger;\n\n if (options.writer && !options.reader) {\n // A custom sink with no reader cannot be verified; fail fast at construction\n // rather than silently producing a chain that verify() cannot inspect.\n throw new ApprovalValidationError(\n 'HashChainAuditAdapter: a custom `writer` requires a matching `reader` for verification.',\n );\n }\n\n this.writer =\n options.writer ??\n (async (tenantId, instanceId, record) => {\n const key = chainKey(tenantId, instanceId);\n const chain = this.store.get(key);\n if (chain) {\n chain.push(record);\n } else {\n this.store.set(key, [record]);\n }\n });\n\n this.reader =\n options.reader ??\n (async (tenantId, instanceId) => this.store.get(chainKey(tenantId, instanceId)) ?? []);\n }\n\n /**\n * Append an entry to the (tenant, instance) chain. Computes the next `seq` and\n * `prevHash`, hashes the canonical record, and persists via the injected writer.\n * Never throws.\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n _instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n const key = chainKey(tenantId, instanceId);\n\n // Serialize per-chain: chain the work onto the existing tail so two concurrent\n // appends to the same (tenant, instance) cannot read the same head.\n const prior = this.locks.get(key) ?? Promise.resolve();\n const work = prior.then(() => this.appendLocked(key, tenantId, instanceId, entry));\n // The lock tail must never reject (it would poison every subsequent append).\n this.locks.set(\n key,\n work.then(\n () => undefined,\n () => undefined,\n ),\n );\n await work;\n }\n\n private async appendLocked(\n key: string,\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n ): Promise<void> {\n try {\n const head = this.heads.get(key);\n const seq = head ? head.seq + 1 : 0;\n const prevHash = head ? head.prevHash : GENESIS_PREV_HASH;\n\n const hash = this.computeHash(seq, prevHash, entry);\n const record: ChainRecord = Object.freeze({ entry, hash, prevHash, seq });\n\n // Advance the in-process head BEFORE awaiting the writer so a slow or failing\n // writer cannot cause the next append to reuse this seq/prevHash. The chain's\n // logical integrity is independent of whether the sink durably accepted it.\n this.heads.set(key, { prevHash: hash, seq });\n\n try {\n await this.writer(tenantId, instanceId, record);\n } catch (err) {\n // Writer failure (including on the genesis entry) is logged and swallowed.\n // The in-process head already advanced, so subsequent appends stay linked;\n // if the sink dropped this record, verify() will surface the gap deterministically.\n this.logger.error(\n 'HashChainAuditAdapter: writer rejected; entry not durably persisted',\n err,\n { tenantId, instanceId, seq },\n );\n }\n } catch (err) {\n // Canonicalization/hashing failure (e.g. circular reference). Swallow per contract.\n if (err instanceof CircularReferenceError) {\n this.logger.error('HashChainAuditAdapter: entry could not be canonicalized', err, {\n tenantId,\n instanceId,\n });\n } else {\n this.logger.error('HashChainAuditAdapter: unexpected error during append', err, {\n tenantId,\n instanceId,\n });\n }\n }\n }\n\n /** Compute the SHA-256 (hex) hash for a record's `{ seq, prevHash, entry }`. */\n private computeHash(seq: number, prevHash: string, entry: AuditEntry): string {\n const canonical = canonicalize({ seq, prevHash, entry });\n return createHash('sha256').update(canonical, 'utf8').digest('hex');\n }\n\n /**\n * Recompute the entire chain for `(tenantId, instanceId)` from genesis and,\n * additionally, detect a truncated tail.\n *\n * Per-record integrity (tamper, deletion, reorder, broken linkage) is found by\n * re-hashing and re-linking from genesis. Tail truncation — dropping the last\n * record(s) — leaves a perfectly self-consistent prefix, so it is detected by\n * comparing the chain's last `seq` against an **expected high-water mark**:\n *\n * - `expectedLength`, when supplied, is the authoritative expected record count\n * (so the expected high-water `seq` is `expectedLength - 1`). Use this with an\n * external anchor to assert truncation even across process restarts.\n * - otherwise the in-process high-water mark recorded by {@link append} is used.\n *\n * When the stored chain is shorter than expected, `brokenAt` is the first\n * missing `seq` (the gap point at the tail). With neither an `expectedLength`\n * argument nor an in-process high-water mark, a truncated tail is undetectable.\n *\n * @param tenantId - Tenant partition.\n * @param instanceId - Instance partition.\n * @param expectedLength - Optional external anchor: the number of records the\n * chain is expected to contain. When provided it overrides the in-process\n * high-water mark for the truncation check.\n * @returns `{ ok: true }` for an untouched chain (and an empty chain when no\n * high-water mark/`expectedLength` says otherwise), otherwise\n * `{ ok: false, brokenAt }`.\n */\n async verify(\n tenantId: string,\n instanceId: string,\n expectedLength?: number,\n ): Promise<VerifyResult> {\n const key = chainKey(tenantId, instanceId);\n const chain = await this.reader(tenantId, instanceId);\n\n // Resolve the expected number of records: the explicit anchor wins; otherwise\n // fall back to the in-process high-water mark (highest appended seq + 1).\n let expectedCount: number | undefined;\n if (expectedLength !== undefined) {\n expectedCount = expectedLength;\n } else {\n const head = this.heads.get(key);\n if (head !== undefined) expectedCount = head.seq + 1;\n }\n\n // Empty chain: only \"ok\" if nothing was expected. If an anchor/high-water\n // mark says records should exist, the entire tail was truncated.\n if (chain.length === 0) {\n if (expectedCount !== undefined && expectedCount > 0) {\n return { ok: false, brokenAt: 0 };\n }\n return { ok: true };\n }\n\n let expectedPrev = GENESIS_PREV_HASH;\n for (let i = 0; i < chain.length; i++) {\n const record = chain[i]!;\n\n // Sequence must start at 0 and increment by exactly 1 (detects deletion/reorder/gap).\n if (record.seq !== i) return { ok: false, brokenAt: Math.min(record.seq, i) };\n\n // Linkage to the previous record's hash must hold.\n if (record.prevHash !== expectedPrev) return { ok: false, brokenAt: record.seq };\n\n // The stored hash must equal the recomputed hash of its content (detects tamper).\n let recomputed: string;\n try {\n recomputed = this.computeHash(record.seq, record.prevHash, record.entry);\n } catch {\n return { ok: false, brokenAt: record.seq };\n }\n if (recomputed !== record.hash) return { ok: false, brokenAt: record.seq };\n\n expectedPrev = record.hash;\n }\n\n // Tail-truncation check: the per-record loop above cannot see records that are\n // simply absent from the end. Compare the actual length against the expected\n // high-water mark; a short chain means the tail was dropped.\n if (expectedCount !== undefined && chain.length < expectedCount) {\n return { ok: false, brokenAt: chain.length };\n }\n\n return { ok: true };\n }\n\n /**\n * Read the ordered chain for `(tenantId, instanceId)`. Returns whatever the\n * configured reader yields (the default in-memory reader returns the live array;\n * callers should treat it as read-only).\n */\n async getChain(tenantId: string, instanceId: string): Promise<readonly ChainRecord[]> {\n return this.reader(tenantId, instanceId);\n }\n}\n","import type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** Default token substituted in place of redacted values. */\nexport const DEFAULT_REDACTION_MASK = '[REDACTED]';\n\n/** Constructor options for {@link RedactingAuditAdapter}. */\nexport interface RedactingAuditAdapterOptions {\n /**\n * The wrapped adapter that receives the redacted entry.\n */\n inner: IAuditAdapter;\n\n /**\n * Dot-delimited field paths to redact, scoped to the bag they live in.\n *\n * Paths target the structured value bags (`oldValue`, `newValue`) of an\n * {@link AuditEntry}. Prefix a path with `oldValue.` or `newValue.` to scope it,\n * or supply an unscoped path (e.g. `applicant.ssn`) to apply it to BOTH bags.\n *\n * A trailing `.*` wildcard redacts every direct child of the matched object\n * (e.g. `card.*` masks every field under `card`). A path that does not resolve\n * to an existing value is a no-op.\n *\n * @example ['newValue.applicant.ssn', 'card.*', 'oldValue.bankAccount']\n */\n fieldPaths?: string[];\n\n /**\n * Free-text top-level entry fields to redact wholesale (value replaced by the mask).\n * Defaults to `[]`. Common choices: `['comment', 'reason']`.\n */\n freeTextFields?: Array<'comment' | 'reason'>;\n\n /** Token used to replace redacted values. Defaults to {@link DEFAULT_REDACTION_MASK}. */\n mask?: string;\n\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\n/** Deep-clone a value, preserving `Date` instances and dropping functions/symbols. */\nfunction deepClone<T>(value: T): T {\n return cloneValue(value) as T;\n}\n\nfunction cloneValue(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n if (value instanceof Date) return new Date(value.getTime());\n if (Array.isArray(value)) return value.map((v) => cloneValue(v));\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = cloneValue(v);\n }\n return out;\n}\n\n/** A field path scoped to one or both structured bags. */\ninterface ParsedPath {\n bag: 'oldValue' | 'newValue' | 'both';\n /** Remaining segments after the optional bag prefix. */\n segments: string[];\n /** True when the final segment is the `*` wildcard. */\n wildcard: boolean;\n}\n\nfunction parsePath(raw: string): ParsedPath | null {\n const parts = raw.split('.').filter((p) => p.length > 0);\n if (parts.length === 0) return null;\n\n let bag: ParsedPath['bag'] = 'both';\n let segments = parts;\n if (parts[0] === 'oldValue' || parts[0] === 'newValue') {\n bag = parts[0];\n segments = parts.slice(1);\n }\n\n let wildcard = false;\n if (segments[segments.length - 1] === '*') {\n wildcard = true;\n segments = segments.slice(0, -1);\n }\n\n // A bare `oldValue.*` / `newValue.*` (wildcard with no remaining segments) masks\n // every direct child of that whole bag.\n if (segments.length === 0 && !wildcard) return null;\n return { bag, segments, wildcard };\n}\n\n/**\n * Apply one parsed path to a single bag object, masking in place. The bag has\n * already been deep-cloned by the caller, so mutation here is safe.\n */\nfunction redactInBag(bag: Record<string, unknown>, path: ParsedPath, mask: string): void {\n // Walk to the parent of the target. Any non-object along the way means the path\n // does not resolve — leave the structure untouched.\n let cursor: unknown = bag;\n for (let i = 0; i < path.segments.length - (path.wildcard ? 0 : 1); i++) {\n const seg = path.segments[i]!;\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n cursor = (cursor as Record<string, unknown>)[seg];\n }\n\n if (path.wildcard) {\n // After walking all segments, `cursor` is the object whose children we mask.\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n const target = cursor as Record<string, unknown>;\n for (const key of Object.keys(target)) {\n target[key] = mask;\n }\n return;\n }\n\n // Non-wildcard: `cursor` is the parent; mask the final key if it exists.\n if (cursor === null || typeof cursor !== 'object' || Array.isArray(cursor)) return;\n const parent = cursor as Record<string, unknown>;\n const finalKey = path.segments[path.segments.length - 1]!;\n if (Object.prototype.hasOwnProperty.call(parent, finalKey)) {\n parent[finalKey] = mask;\n }\n}\n\n/**\n * An {@link IAuditAdapter} decorator that strips configured PII from each entry\n * before forwarding to a wrapped adapter. The caller's original `entry` and\n * `instance` are never mutated — redaction operates on a deep clone.\n *\n * Redaction targets the structured bags (`oldValue`, `newValue`) by dot-path,\n * supports a trailing `.*` wildcard to mask every child of an object, and can\n * blank out free-text fields (`comment`, `reason`). Paths that do not resolve,\n * or that point at `null`/array/primitive values, are no-ops that leave the\n * entry structurally intact.\n *\n * @example\n * ```ts\n * const audit = new RedactingAuditAdapter({\n * inner: new HashChainAuditAdapter(),\n * fieldPaths: ['newValue.applicant.ssn', 'card.*'],\n * freeTextFields: ['comment', 'reason'],\n * });\n * ```\n */\nexport class RedactingAuditAdapter implements IAuditAdapter {\n private readonly inner: IAuditAdapter;\n private readonly parsedPaths: ParsedPath[];\n private readonly freeTextFields: ReadonlyArray<'comment' | 'reason'>;\n private readonly mask: string;\n private readonly logger: Logger;\n\n constructor(options: RedactingAuditAdapterOptions) {\n this.inner = options.inner;\n this.mask = options.mask ?? DEFAULT_REDACTION_MASK;\n this.freeTextFields = options.freeTextFields ?? [];\n this.logger = options.logger ?? noopLogger;\n this.parsedPaths = (options.fieldPaths ?? [])\n .map(parsePath)\n .filter((p): p is ParsedPath => p !== null);\n }\n\n /**\n * Deep-clone the entry, redact configured fields on the clone, then forward to\n * the wrapped adapter. The caller's `entry` reference and contents are unchanged.\n * Never throws (delegates the must-not-throw guarantee to the wrapped adapter and\n * swallows any unexpected local error).\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n let redacted: AuditEntry;\n try {\n redacted = this.redactEntry(entry);\n } catch (err) {\n // Redaction must never break the audit path. On the unexpected event that\n // cloning/redaction fails, log and forward the original entry unmodified so\n // the audit record is not silently dropped.\n this.logger.error('RedactingAuditAdapter: redaction failed; forwarding original entry', err, {\n tenantId,\n instanceId,\n });\n redacted = entry;\n }\n await this.inner.append(tenantId, instanceId, redacted, instance);\n }\n\n /** Produce a redacted deep clone of `entry` without touching the original. */\n private redactEntry(entry: AuditEntry): AuditEntry {\n const clone = deepClone(entry);\n\n // Free-text fields: blank the value wholesale if present and non-empty/defined.\n for (const field of this.freeTextFields) {\n if (clone[field] !== undefined) {\n clone[field] = this.mask;\n }\n }\n\n // Structured bags.\n for (const path of this.parsedPaths) {\n if ((path.bag === 'oldValue' || path.bag === 'both') && clone.oldValue) {\n redactInBag(clone.oldValue, path, this.mask);\n }\n if ((path.bag === 'newValue' || path.bag === 'both') && clone.newValue) {\n redactInBag(clone.newValue, path, this.mask);\n }\n }\n\n return clone;\n }\n}\n","import type { IAuditAdapter } from '../../adapters/IAuditAdapter.js';\nimport type { AuditEntry, ApprovalInstance } from '../../types/index.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** A child adapter, optionally tagged with a stable identity for diagnostics. */\nexport interface CompositeChild {\n /** Human-readable identity used in logs when this child rejects (defaults to its index). */\n readonly id?: string;\n readonly adapter: IAuditAdapter;\n}\n\n/** Constructor options for {@link CompositeAuditAdapter}. */\nexport interface CompositeAuditAdapterOptions {\n /**\n * Child adapters to fan out to. Each may be a bare {@link IAuditAdapter} or a\n * {@link CompositeChild} carrying an `id` for clearer log attribution.\n */\n children: ReadonlyArray<IAuditAdapter | CompositeChild>;\n /** Structured logger; defaults to a no-op logger. */\n logger?: Logger;\n}\n\nfunction normalize(\n child: IAuditAdapter | CompositeChild,\n index: number,\n): { id: string; adapter: IAuditAdapter } {\n if ('adapter' in child) {\n return { id: child.id ?? `child[${index}]`, adapter: child.adapter };\n }\n return { id: `child[${index}]`, adapter: child };\n}\n\n/**\n * An {@link IAuditAdapter} that fans `append` out to N child adapters concurrently.\n * Every child receives the same entry. The call awaits all children\n * ({@link Promise.allSettled}) and never throws: a rejecting child is logged with\n * its index/identity and does not prevent the other children from receiving the\n * entry. A composite with zero children is a no-op that resolves immediately.\n *\n * @example\n * ```ts\n * const audit = new CompositeAuditAdapter({\n * children: [\n * { id: 'hash-chain', adapter: new HashChainAuditAdapter() },\n * { id: 's3-worm', adapter: s3Adapter },\n * ],\n * });\n * ```\n */\nexport class CompositeAuditAdapter implements IAuditAdapter {\n private readonly children: ReadonlyArray<{ id: string; adapter: IAuditAdapter }>;\n private readonly logger: Logger;\n\n constructor(options: CompositeAuditAdapterOptions) {\n this.logger = options.logger ?? noopLogger;\n this.children = options.children.map(normalize);\n }\n\n /**\n * Fan the entry out to every child concurrently and await all of them. Never\n * throws; each child rejection is caught and logged with the child's identity.\n */\n async append(\n tenantId: string,\n instanceId: string,\n entry: AuditEntry,\n instance: Readonly<ApprovalInstance>,\n ): Promise<void> {\n if (this.children.length === 0) return;\n\n const results = await Promise.allSettled(\n // Wrap each child in Promise.resolve().then(...) so a child that throws\n // synchronously (rather than returning a rejected promise) is still captured.\n this.children.map((c) =>\n Promise.resolve().then(() => c.adapter.append(tenantId, instanceId, entry, instance)),\n ),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i]!;\n if (result.status === 'rejected') {\n const child = this.children[i]!;\n this.logger.error(\n `CompositeAuditAdapter: child \"${child.id}\" failed to append`,\n result.reason,\n { tenantId, instanceId, childId: child.id, childIndex: i },\n );\n }\n }\n }\n}\n"]}
@@ -379,13 +379,17 @@ var ApprovalError = class extends Error {
379
379
  toJSON() {
380
380
  return { code: this.code, message: this.message, name: this.name };
381
381
  }
382
+ /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */
382
383
  toHttpStatus() {
383
384
  const map = {
384
385
  NOT_FOUND: 404,
385
386
  CONFLICT: 409,
387
+ CANNOT_CANCEL: 409,
386
388
  FORBIDDEN: 403,
387
389
  VALIDATION: 422,
388
- TEMPLATE_NOT_FOUND: 404
390
+ TEMPLATE_NOT_FOUND: 404,
391
+ // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.
392
+ SCHEDULER_SHUTDOWN: 503
389
393
  };
390
394
  return map[this.code] ?? 500;
391
395
  }