This is a demo/state-machine library, not a production payment system. Every claim below is verifiable against the source in
src/.
escrow-state-machine-ts models the rules of an off-chain milestone escrow:
state transitions, fee math, settlement reporting, quorum counting, and
webhook signing. It holds no real money, runs no on-chain code, and its
cryptography is HMAC (webhook signatures, and the optional keyed audit
hash chain described below) plus Ed25519 for opt-in signed quorum
approvals (approveSigned()) and opt-in webhook signing/verification
(buildSettlementWebhook / verifySettlementWebhook with a
signingKey / publicKey or keyResolver, backlog #1567).
quorum.approve()records caller-trust approvals.src/quorum.tsstores signer id strings; plainapprove()performs no signature verification, no key management, and no DAO governance. Callingapprove("dao-3")is only as trustworthy as the caller who says "dao-3 approved". The optionalmaxApprovalAgeMsexpiry window only bounds how long a recorded approval counts (the audit log keeps expired entries); it does not authenticate the approval itself. A misspelled config key cannot silently disable that window or the threshold:createQuorum/restoreQuorumreject unknownQuorumConfigfields (quorum: unknown option "<key>") before any field is read, so a typo'dmaxApprovalAgecannot leave approvals permanently valid and a typo'dthreshholdcannot leave the threshold at 1;restoreSignedQuorumSnapshotlikewise rejects unknown restore options (onlynowis legal) instead of falling back to wall-clock. Opt-in verification exists:approveSigned()verifies an Ed25519 signature over the canonical statementescrow-quorum:approve:<signerId>against a public key registered inQuorumConfig.signerPublicKeys(non-Ed25519/private keys are rejected at construction), marks the log entryverified: true, and throws without recording anything on failure. The statement binds the signer id only — not an escrow or outcome — so a signature is meaningful only inside the quorum it was collected for; use one quorum per arbitration. Without astatementContext(or astatementScope) the same signature verifies in every quorum that registers the same signer key, so one captured vote can count toward — and dispatch — two different escrows. Recommendation: configure a uniquestatementContextper escrow (the escrow id is the natural value) whenever the same signer keys vote in more than one arbitration.test/quorumNoContextCrossEscrowReuse.test.tspins both sides: the reuse under the default configuration, and the binding once distinct contexts are set. An unsignedrestoreQuorum()drops the recordedverifiedflags — the snapshot carries no signature to re-verify, so every restored approval is an unverified claim until a freshapproveSigned()re-earns the flag; only the HMAC-signed envelope restore keeps them, because its MAC authenticates the snapshot. When the snapshot crosses an untrusted boundary, wrap it in the HMAC-signed envelope (exportSignedQuorumSnapshot/restoreSignedQuorumSnapshot, same shape as the escrow envelope): the MAC covers the whole snapshot, so a forgedverifiedflag or an invented approval fails closed at restore; the envelope may also carry anexpiresAtcovered by the MAC, and the secret is never written into the envelope — integrity protection only, not encryption. Quorum approvalevidenceis capped at 32,768 characters (the sameMAX_EVIDENCE_LENGTHceiling as escrow history evidence), enforced atapprove(),approveSigned(), and snapshot restore, so an oversized reference can neither be recorded live nor smuggled in through a rehydrated snapshot; signer ids are capped at 256 characters (MAX_ACTOR_LENGTH) because they are written verbatim into the approval log and snapshots. Both caps reject outright, never truncate.src/arbitration.tswires the count todispatchArbitration(it refuses to dispatch below threshold and recordsquorum <approvals>/<threshold> [signer, …]in the audit note — the counted signers, approval-time order, expired approvals excluded — but it does not make the approvals cryptographic — see the honesty note in its header comment. Opt in to a verified-only gate withdispatchArbitration(..., { requireVerifiedApprovals: true }): the threshold is re-counted fromverifiedApprovalCount()/verifiedApprovals()(same expiry semantics ashasQuorum()), a short verified count throwsarbitration requires quorum: <verified>/<threshold> verified approvalsand leaves the escrow untouched, and the audit note records the verified count and verified signers only — a plain claim never appears in it. The gate proves the signers held their keys: signature authenticity, not arbitration fairness — a verified vote says nothing about whether the outcome is just, and a quorum restored from an unsigned snapshot reads 0 verified votes until its signers re-earn the flag with a freshapproveSigned(). A duck-typed quorum without the verified views fails closed under the option instead of being trusted on its plain count.- Split amounts are caller-asserted, not quorum-endorsed.
QuorumStatementScopebinds only the escrow id and the outcome ("split") — it has no amount field — so a quorum scoped to a split endorses the outcome "split" and never a particular division: the same 5/9 vote that dispatches a 70/30 split dispatches a 99/1 split.dispatchArbitration(..., { split })forwardsopts.splitverbatim to the dispatch (src/arbitration.ts); the dispatch only checks that the two shares sum exactly to the still-locked balance. A caller with dispatch rights can therefore take a quorum that voted "split" and settle 99/1 — the vote says the arbitrators chose a split, not that they chose this split.buildSettlementReportlikewise trusts thesplitCentsrecorded on theARBITRATE_SPLITentry: its sum check is an arithmetic guardrail (the legs must add up to the locked remainder), not an endorsement of the division. Obtain the division from the arbitration decision record out of band before dispatching, and never read a balanced report as approval of the split.test/splitAmountsCallerAsserted.test.tspins both sides: a split-scoped quorum dispatches 99/1 and 1/99 alike, and the report accepts any legs that sum to the locked remainder. VERIFY_PASSis a caller trust decision. Dispatching it verifies no oracle signatures, zero-knowledge proofs, or TEE attestations (README FAQ: "Where is that here?" — it isn't, deliberately). The opt-inrequireVerifyEvidenceconstructor flag only requires a non-emptyevidencereference on the audit entry; the library records the caller's claim, it does not check it.- Webhook secret distribution is the caller's responsibility.
src/webhooks.tsdocuments this in its header comment and the README repeats it: whoever holds the secret can forgesha256=<hex>signatures. This library does not generate, store, or distribute secrets — store the secret like any other API credential. The same holds for the opt-in Ed25519 path (backlog #1567): the sender keeps the private key and publishes the public key (or itskeyId→ public-key mapping) out of band — a public key is not a secret, but a receiver that resolves keys from an untrusted directory can be pointed at an attacker's key, so the mapping itself must come from a source the receiver trusts. What the library does offer is rotation support on the verify side:verifySettlementWebhookaccepts a{ secrets: [...] }candidate set, so during the caller's own rotation window signatures made with either the old or the new secret verify (any-match wins, all-mismatch fails closed). The rotation schedule itself stays entirely with the caller. - The RBAC actor is a caller assertion, NOT identity.
EscrowOptions.rolePolicymaps events to allowed actor names anddispatch(..., { actor })checks the supplied string against that allowlist — but the caller asserts the actor string and nothing verifies who the caller is. Anyone who can calldispatchcan claim to be"treasury". The policy guarantees only that dispatches violating the declared allowlist do not happen and that the audit trail records the actor string it was given (the actor is covered by the entry's hash chain). Real identity authentication — sessions, signatures, verified credentials — remains entirely the caller's responsibility. - Receiver-side trust.
buildSettlementWebhookderives every payload field from the audit-backedSettlementReport(nothing is invented), but the receiver must verify the signature over the raw body bytes; an unverified receiver is trusting the network, not the escrow.
- Money boundary checks.
assertNonNegativeMoney(src/stateMachine.ts) rejects non-number, non-finite, and negative amounts with a descriptive error at thedispatch("FUND", …)boundary;calculateDepositandsettleReleaseapply the same finite/non-negative checks to their inputs. Illegal money fails fast instead of silently poisoning downstream accounting. - Webhook verification is constant-time and fail-closed.
verifySettlementWebhookcompares HMAC signatures withtimingSafeEqual; malformed signatures (anything matching neithersha256=<64 hex>nored25519=<base64>, or aned25519=value that does not decode to exactly 64 bytes) returnfalserather than throwing, so hostile input cannot turn verification into an unhandled exception. Verify over the raw body bytes — the object overload re-stringifies with a fixed key order for in-process convenience, but raw bytes are the transport-safe path (documented insrc/webhooks.ts). Configuration errors still throw rather than silently passing: an emptysecretsarray (or an empty secret inside it) throwscannot verify settlement webhook: …, as does a caller-suppliedpublicKeythat is not an Ed25519 public key. A badkeyResolverreturn, by contrast, fails closed asfalse— the resolver is untrusted input, not caller configuration. Signatures don't expire on their own: without the opt-inmaxAgeMs, a legitimately-signed payload from a year ago still verifies. PassVerifyWebhookOptions.maxAgeMsto fail-closed reject payloads older than the window (signature is checked first; an unparseableatreturnsfalse). Future timestamps are not bounded bymaxAgeMsalone — pass the companion opt-inVerifyWebhookOptions.maxFutureSkewMsto also fail-closed reject payloads whoseatlies further in the future than the tolerated clock skew (same inclusive boundary, same signature-first order); together the two form a two-sided freshness window. With neither set, verification is signature-only. - Settlement never runs on uncorroborated amounts.
depositAmountFromHistory(src/settlementReport.ts) throwssettlement requires a FUND amountwhen the audit history has no FUND event or any FUND lacks anamount— undefined/NaN never silently poisons the settlement math.buildSettlementReportadditionally cross-checks the caller-supplied deposit against the audit-history total. - Event-level RBAC allowlist (when a policy is set).
Escrowconstructed withrolePolicyrejects a dispatch of a listed event whoseactoris missing or not in the allowlist withactor not authorized for …, before any transition — no history is appended and no idempotency key is consumed. Events the policy does not list are unrestricted, and an escrow with no policy skips the check entirely. Invalid policies throw at construction (invalid option: rolePolicy …). This enforces the declared allowlist only; it does not authenticate the actor (see the caller-trust section above). - Audit-attribution gate (when
requireActor: true).Escrowconstructed withrequireActorrejects any dispatch without anactorwithactor required: …, after the transition/RBAC/amount-cap checks and before any append — no history is appended and no idempotency key is consumed. A listed event without an actor reports the RBAC error first (that check runs earlier), so this gate only speaks for events the policy does not list. The switch IS part oftoJSON()/fromJSON()snapshots (requireActor, written only when true): a restored escrow keeps enforcing it unlessEscrow.fromJSON(snapshot, { requireActor: false })explicitly overrides it, and a tampered gate in a stored snapshot is rejected. A bare history carries no gate, sofromHistorystill needs the option re-supplied. Like the policy, it does not authenticate the actor — it only guarantees the audit trail names one. - Settlement-reference gate (when
requireSettlementRef: true).Escrowconstructed withrequireSettlementRefrejects a RELEASE without asettlementRefwithsettlement reference required: …, after the transition/RBAC/amount-cap checks (after therequireActorgate) and before any append — no history is appended and no idempotency key is consumed. Other events are unaffected, and the default (gate off) keeps a reference-free RELEASE legal. The switch IS part oftoJSON()/fromJSON()snapshots (requireSettlementRef, written only when true): a restored escrow keeps enforcing it unless an explicitEscrow.fromJSON(snapshot, { requireSettlementRef: false })overrides it, and a tampered gate in a stored snapshot is rejected. A bare history carries no gate, sofromHistorystill needs the option re-supplied. Like the evidence gate, it does not verify the external settlement — it only guarantees the audit trail names the transfer. - Refund-reference gate (when
requireRefundRef: true).Escrowconstructed withrequireRefundRefrejects an ARBITRATE_REFUND without arefundRefwithrefund reference required: …, after the transition/RBAC/amount-cap checks (after therequireActorandrequireSettlementRefgates) and before any append — no history is appended and no idempotency key is consumed. Other events are unaffected, and the default (gate off) keeps a reference-free ARBITRATE_REFUND legal. The switch IS part oftoJSON()/fromJSON()snapshots (requireRefundRef, written only when true): a restored escrow keeps enforcing it unless an explicitEscrow.fromJSON(snapshot, { requireRefundRef: false })overrides it, and a tampered gate in a stored snapshot is rejected. A bare history carries no gate, sofromHistorystill needs the option re-supplied. Like the settlement gate, it does not verify the external refund — it only guarantees the audit trail names the transfer. - Per-state visit budget (when
maxVisitsByStateis set).Escrowconstructed with a per-state visit budget rejects a dispatch whose target state already used its budget withstate visit budget exhausted: …, after the transition/RBAC/amount-cap checks and before any append — no history is appended and no idempotency key is consumed. The count is derived from the append-only history (1 for the initial state plus 1 per entry landing there), so a restored escrow resumes with the exact count the live escrow had, and the budget IS part oftoJSON()/fromJSON()snapshots (maxVisitsByState, written only when non-empty; a tampered budget in a stored snapshot is rejected). A bare history carries no budget, sofromHistorystill needs the option re-supplied. Honest limit: the budget caps re-entry into a state, not total history length — an escrow can still grow a long history by walking distinct states and events the budget does not list — and it is opt-in: without it the milestone loop (FUNDED → SUBMIT_MILESTONE → MILESTONE_SUBMITTED → PARTIAL_RELEASE → FUNDED) is unbounded by design. - Optimistic-concurrency guard (when
expectedSeqis passed).dispatchrejects a caller whoseexpectedSeqno longer equals the current history length withdispatch conflict: …, before any other check and with no side effects (no append, no idempotency key consumed, no listener notified) — two writers racing off the same snapshot cannot both advance the escrow in-process. It is not a distributed lock: separate processes hold separate histories and still need store-level compare-and-swap. - Strict snapshot validation.
Escrow.fromJSONrunsparseEscrowSnapshoton untrusted input: non-empty id, seq from 1 with no gaps, continuous from/to chain starting at CREATED, canonical ISO-8601 non-decreasing timestamps,amountonly on FUND and PARTIAL_RELEASE entries (aPARTIAL_RELEASEamount must also be greater than zero and no larger than the still-locked balance), string-only notes,actor(when present) a non-empty string,rolePolicy(when present) a valid allowlist of known events, andidempotencyKeys(when present) an array of non-empty strings. Anything else throwsinvalid snapshot: …. The per-state visit budget (maxVisitsByState, when present) must map known states to positive integers, and is validated strictly but never consulted against the stored history — it governs future dispatches only. - Delivery fail-fast.
deliverSettlementWebhookrejects invalid URLs, non-http(s) protocols, and bad retry/timeout options before any request, and never retries 3xx/4xx other than 429 (the request itself is at fault); only 429/5xx/network errors get retries, with a 429Retry-Afterhint honored over the exponential backoff — the hint is clamped tomaxRetryDelayMs(default 60s), so a runaway value cannot park the delivery promise for longer than the cap. Option typos fail closed on the delivery side too: the single-delivery options and the fan-out call-level options are scanned against their known keys before any other validation or request, and an unknown key throws naming the key — a typo'dtimeouMsormaxEndpointis reported as itself instead of silently running with the default timeout or dropping the fan-out cap; a typo'd per-endpoint override fails only that endpoint ({ ok: false, attempts: 0 }, no request made). Plaintext transport is refused by default: anhttp:endpoint URL throws before any request unless the caller explicitly passesallowInsecureHttp: true— the signed payload plus theX-Signatureheader are replayable over the clear, so plaintext delivery is a real replay threat. Honest limit: the refusal only blocks plaintext; it does not validate certificates or pin TLS.
All amounts use cents rounding (round2: Math.round(n * 100) / 100 in
src/settlement.ts and src/feeCalculator.ts). This is not big-decimal
arithmetic and has not been audited. Invariant tests assert fund
conservation within ±1 cent only (test/invariants.test.ts). Do not use
for precision-critical accounting.
Escrow.history returns a detached, frozen snapshot on every call: the
array is Object.freezed and each entry is a frozen copy
(src/stateMachine.ts). In-process callers cannot push, splice, or
rewrite entry fields to tamper with the audit log; dispatch() remains
the only way to append. (toJSON() returns a detached deep copy as
well, so snapshots exported for persistence are detached and safe.)
Persisted snapshots get a second layer: every entry is hash-chained
(prevHash/hash, SHA-256 over the canonical entry serialization, genesis
prevHash is "GENESIS"). Escrow.fromJSON() re-verifies the chain on
chained snapshots and rejects a broken one, so an entry rewritten on disk
(amount/note/evidence/actor changed, an entry deleted or reordered) is detected
on rehydration instead of silently accepted. verifyHistoryChain() is
exported for standalone checks (watchdogs, log-shipper validation).
Honest limits: the default chain is unkeyed — it is tamper evidence, not a MAC. It catches edits by anyone who rewrites entries without recomputing the chain (manual edits, log-shipper corruption, partial restores). It does not stop an attacker who rewrites the whole JSON and recomputes the hashes.
That gap has an opt-in fix: construct the escrow with an auditKey
(new Escrow(id, { auditKey }), a non-empty string or Buffer) and every
chain link becomes HMAC-SHA256 over the same canonical input. Rewriting
the JSON then requires the key as well as the data. Verification is
fail-closed across modes: a keyed chain does not verify without the key or
with the wrong one (verifyHistoryChain(history, key),
Escrow.fromJSON(snapshot, { auditKey })), and an unkeyed chain does not
verify when a key is supplied. In keyed mode the stored MAC is compared
in constant time (timingSafeEqual with a length guard), so an online
verifier leaks no per-byte timing signal; a forged digest of the wrong
shape fails verification instead of throwing. In keyed mode the residual risks move to
the key itself: anyone who obtains the key can rewrite the log and re-MAC
it, so key generation, storage, and distribution are the caller's
responsibility — the library never generates, stores, or transmits keys,
and the key is never written into snapshots (a restored escrow must be
handed the key again, and a legacy hashless snapshot restored with a key
is chained in keyed mode on rehydration). Legacy (hashless) snapshots are
still accepted and deterministically chained on rehydration; a snapshot
that mixes chained and hashless entries is rejected.
Dedupe snapshots get the same treatment as an opt-in layer:
SettlementEventDedupe.exportSignedSnapshot(secret) wraps the
unsigned { v: 1, entries } snapshot in an HMAC-SHA256 envelope
{ v: 1, snapshot, mac } (same shape and canonical form as the
sibling rfc9421 ReplayCache signed snapshot), and
restoreSignedSnapshot(envelope, secret) verifies the MAC in
constant time before any snapshot parsing. A rewritten persisted
file — a deleted consumed eventId, an injected forged one, a
shifted seenAtMs — then fails closed at startup instead of
silently reopening the double-settlement window or discarding a
legitimate settlement as an apparent duplicate. The unsigned
snapshot stays accepted as trusted configuration, and the two
forms never accept each other, so a signed restore cannot
silently downgrade. The MAC is integrity protection only, not
encryption: the eventIds inside are wire-visible values, and the
secret is never written into the envelope — a restored dedupe
must be handed the secret again, like the audit key above, and
key storage and distribution remain the caller's responsibility.
Each envelope can also carry an optional expiry:
exportSignedSnapshot(secret, { expiresAt }) or
{ maxAgeMs, now? } writes a canonical ISO-8601 UTC expiresAt
into the envelope, covered by the MAC, so a stolen envelope cannot
keep a dedupe alive past its expiry; restore rejects an expired
envelope (now > expiresAt) after the MAC check and before any
snapshot parsing. An envelope without expiresAt never expires.
Escrow snapshots get the same treatment at the snapshot level:
Escrow.exportSignedSnapshot(secret) wraps the whole
EscrowSnapshot in an HMAC-SHA256 envelope { v: 1, snapshot, mac }
(same shape and canonical form as the dedupe envelope), and
Escrow.restoreSignedSnapshot(envelope, secret, opts?) verifies
the MAC in constant time before any snapshot parsing. This closes
the gap the hash chain leaves open: the chain covers history
entries only, so without the envelope a rewritten persisted file
could push a deadline back, loosen a rolePolicy, clear consumed
idempotency keys, or lift a deposit cap without breaking any
history link — with the envelope, any such rewrite fails closed
at restore. The envelope secret need not equal the escrow's
auditKey (they protect different things and are managed
independently); opts.auditKey is still handed to fromJSON on
restore so a keyed chain re-verifies under its own key. The
unsigned fromJSON() path stays accepted as trusted
configuration, and the two forms never accept each other.
Each envelope can also carry an optional expiry:
exportSignedSnapshot(secret, { expiresAt }) or
{ maxAgeMs, now? } writes a canonical ISO-8601 UTC expiresAt
into the envelope, covered by the MAC, so a stolen envelope cannot
resurrect the escrow's state — a revoked policy, cleared
idempotency keys, a pushed-back deadline — after its expiry;
restore rejects an expired envelope (now > expiresAt) after the
MAC check and before any snapshot parsing. An envelope without
expiresAt never expires.
Outbox snapshots get the same treatment:
SettlementWebhookOutbox.exportSignedSnapshot(secret) wraps the
unsigned { v: 1, entries } snapshot in an HMAC-SHA256 envelope
{ v: 1, snapshot, mac } (same shape and canonical form as the
dedupe envelope), and restoreSignedSnapshot(envelope, secret, opts) (alias fromSignedSnapshot) verifies the MAC in constant
time before any snapshot parsing. A rewritten persisted file — a
lowered attempts count that resurrects a dead letter, an inflated
one that pushes a still-retryable pair into the dead letter, a
forged lastError/lastAt or (endpoint, eventId) key — then
fails closed at startup instead of silently rewriting the failure
ledger. The unsigned snapshot stays accepted as trusted
configuration, and the two forms never accept each other, so a
signed restore cannot silently downgrade. The MAC is integrity
protection only, not encryption: the endpoints and eventIds inside
are wire-visible values, and the secret is never written into the
envelope — a restored outbox must be handed the secret again, like
the audit key above, and key storage and distribution remain the
caller's responsibility. Each envelope can also carry an optional
expiry: exportSignedSnapshot(secret, { expiresAt }) or
{ maxAgeMs, now? } writes a canonical ISO-8601 UTC expiresAt
into the envelope, covered by the MAC, so a stolen envelope cannot
resurrect a cleared dead letter after its expiry; restore rejects
an expired envelope (now > expiresAt) after the MAC check and
before any snapshot parsing. An envelope without expiresAt never
expires.
- Real oracle/Chainlink/zk-SNARK/TEE verification behind
VERIFY_PASS - Cryptographic multi-sig (a threshold signature scheme, or an on-chain
multi-sig contract). What this repo does have is per-signer Ed25519
approval verification:
approveSigned()verifies each vote's signature over the canonical statementescrow-quorum:approve:<signerId>against a public key registered inQuorumConfig.signerPublicKeys, marks the entryverified: true, anddispatchArbitrationcan gate on verified votes only (requireVerifiedApprovals: true). That is still not multi-sig: votes are verified one signer at a time, there is no joint key or on-chain contract, and a plainapprove()claim still counts unless the verified-only gate is opted into — see the Trust model section above for the exact semantics and the unsigned-snapshot caveat - Secret management, storage, or distribution for webhook secrets (rotation-window verification accepts multiple candidate secrets, but the library never generates, stores, or schedules the rotation itself)
- A deadline scheduler (
EXPIREis dispatched by the caller) - Identity authentication (this repo's
rolePolicyis only a caller-supplied actor allowlist — see above), concurrency control beyond the single-processexpectedSeqoptimistic guard ondispatch(two processes restoring the same snapshot can still race; cross-process writers need store-level compare-and-swap), durable storage, a shared/distributed idempotency store (this repo's consumed keys persist only inside each escrow's owntoJSON()snapshot) - Audited money math
If you find a security problem in this demo, please open an issue on this repository describing it. Do not include secrets, private keys, or any credentials in the report.
Even though this is a demo / reproduction library, reports are still welcome — especially for the areas this file makes security claims about: webhook signature verification, the audit hash chain (keyed and unkeyed), and money conservation in settlement and fee math. No response-time commitment is made; reports are triaged as time permits.
Reference and demo use only.