@optimystic/db-core 0.25.0 → 0.26.0

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 (104) hide show
  1. package/dist/src/cohort-topic/membership/verifier.d.ts +8 -0
  2. package/dist/src/cohort-topic/membership/verifier.d.ts.map +1 -1
  3. package/dist/src/cohort-topic/membership/verifier.js +17 -0
  4. package/dist/src/cohort-topic/membership/verifier.js.map +1 -1
  5. package/dist/src/cohort-topic/promotion.d.ts +25 -0
  6. package/dist/src/cohort-topic/promotion.d.ts.map +1 -1
  7. package/dist/src/cohort-topic/promotion.js +58 -11
  8. package/dist/src/cohort-topic/promotion.js.map +1 -1
  9. package/dist/src/cohort-topic/wire/primitives.d.ts +6 -0
  10. package/dist/src/cohort-topic/wire/primitives.d.ts.map +1 -1
  11. package/dist/src/cohort-topic/wire/primitives.js +6 -0
  12. package/dist/src/cohort-topic/wire/primitives.js.map +1 -1
  13. package/dist/src/cohort-topic/wire/types.d.ts +5 -0
  14. package/dist/src/cohort-topic/wire/types.d.ts.map +1 -1
  15. package/dist/src/cohort-topic/wire/validate.d.ts.map +1 -1
  16. package/dist/src/cohort-topic/wire/validate.js +10 -19
  17. package/dist/src/cohort-topic/wire/validate.js.map +1 -1
  18. package/dist/src/collection/collection.d.ts +8 -1
  19. package/dist/src/collection/collection.d.ts.map +1 -1
  20. package/dist/src/collection/collection.js +19 -3
  21. package/dist/src/collection/collection.js.map +1 -1
  22. package/dist/src/matchmaking/wire.d.ts +2 -2
  23. package/dist/src/matchmaking/wire.d.ts.map +1 -1
  24. package/dist/src/matchmaking/wire.js +3 -3
  25. package/dist/src/matchmaking/wire.js.map +1 -1
  26. package/dist/src/network/struct.d.ts +5 -5
  27. package/dist/src/network/struct.d.ts.map +1 -1
  28. package/dist/src/testing/index.d.ts +1 -0
  29. package/dist/src/testing/index.d.ts.map +1 -1
  30. package/dist/src/testing/index.js +1 -0
  31. package/dist/src/testing/index.js.map +1 -1
  32. package/dist/src/testing/refresh-probe.d.ts +31 -0
  33. package/dist/src/testing/refresh-probe.d.ts.map +1 -0
  34. package/dist/src/testing/refresh-probe.js +39 -0
  35. package/dist/src/testing/refresh-probe.js.map +1 -0
  36. package/dist/src/testing/test-transactor.d.ts +58 -5
  37. package/dist/src/testing/test-transactor.d.ts.map +1 -1
  38. package/dist/src/testing/test-transactor.js +87 -4
  39. package/dist/src/testing/test-transactor.js.map +1 -1
  40. package/dist/src/transaction/coordinator.d.ts +90 -6
  41. package/dist/src/transaction/coordinator.d.ts.map +1 -1
  42. package/dist/src/transaction/coordinator.js +311 -90
  43. package/dist/src/transaction/coordinator.js.map +1 -1
  44. package/dist/src/transaction/errors.d.ts +42 -0
  45. package/dist/src/transaction/errors.d.ts.map +1 -1
  46. package/dist/src/transaction/errors.js +50 -0
  47. package/dist/src/transaction/errors.js.map +1 -1
  48. package/dist/src/transaction/index.d.ts +1 -1
  49. package/dist/src/transaction/index.d.ts.map +1 -1
  50. package/dist/src/transaction/index.js +1 -1
  51. package/dist/src/transaction/index.js.map +1 -1
  52. package/dist/src/transaction/session.d.ts +7 -3
  53. package/dist/src/transaction/session.d.ts.map +1 -1
  54. package/dist/src/transaction/session.js +7 -3
  55. package/dist/src/transaction/session.js.map +1 -1
  56. package/dist/src/transaction/transaction.d.ts +12 -2
  57. package/dist/src/transaction/transaction.d.ts.map +1 -1
  58. package/dist/src/transaction/transaction.js.map +1 -1
  59. package/dist/src/transactor/network-transactor.d.ts +1 -1
  60. package/dist/src/transactor/network-transactor.d.ts.map +1 -1
  61. package/dist/src/transactor/network-transactor.js +6 -26
  62. package/dist/src/transactor/network-transactor.js.map +1 -1
  63. package/dist/src/transactor/transactor-source.d.ts +4 -6
  64. package/dist/src/transactor/transactor-source.d.ts.map +1 -1
  65. package/dist/src/transactor/transactor-source.js +4 -6
  66. package/dist/src/transactor/transactor-source.js.map +1 -1
  67. package/dist/src/transform/atomic.d.ts.map +1 -1
  68. package/dist/src/transform/atomic.js +7 -0
  69. package/dist/src/transform/atomic.js.map +1 -1
  70. package/dist/src/transform/base-pins.d.ts +48 -0
  71. package/dist/src/transform/base-pins.d.ts.map +1 -0
  72. package/dist/src/transform/base-pins.js +65 -0
  73. package/dist/src/transform/base-pins.js.map +1 -0
  74. package/dist/src/transform/digest.d.ts +4 -2
  75. package/dist/src/transform/digest.d.ts.map +1 -1
  76. package/dist/src/transform/digest.js +14 -19
  77. package/dist/src/transform/digest.js.map +1 -1
  78. package/dist/src/transform/tracker.d.ts +31 -3
  79. package/dist/src/transform/tracker.d.ts.map +1 -1
  80. package/dist/src/transform/tracker.js +105 -13
  81. package/dist/src/transform/tracker.js.map +1 -1
  82. package/package.json +1 -1
  83. package/src/cohort-topic/membership/verifier.ts +487 -461
  84. package/src/cohort-topic/promotion.ts +86 -14
  85. package/src/cohort-topic/wire/primitives.ts +195 -188
  86. package/src/cohort-topic/wire/types.ts +480 -475
  87. package/src/cohort-topic/wire/validate.ts +504 -512
  88. package/src/collection/collection.ts +19 -3
  89. package/src/matchmaking/wire.ts +605 -603
  90. package/src/network/struct.ts +5 -5
  91. package/src/testing/index.ts +1 -0
  92. package/src/testing/refresh-probe.ts +52 -0
  93. package/src/testing/test-transactor.ts +100 -4
  94. package/src/transaction/coordinator.ts +312 -99
  95. package/src/transaction/errors.ts +141 -91
  96. package/src/transaction/index.ts +1 -1
  97. package/src/transaction/session.ts +7 -3
  98. package/src/transaction/transaction.ts +12 -2
  99. package/src/transactor/network-transactor.ts +1025 -1045
  100. package/src/transactor/transactor-source.ts +170 -172
  101. package/src/transform/atomic.ts +6 -0
  102. package/src/transform/base-pins.ts +83 -0
  103. package/src/transform/digest.ts +14 -19
  104. package/src/transform/tracker.ts +108 -15
@@ -1,461 +1,487 @@
1
- /**
2
- * Cohort-topic substrate — participant-side membership verification with a trust-anchor gate.
3
- *
4
- * Per `docs/cohort-topic.md` §Membership snapshots and §Bootstrapping trust. A participant verifying
5
- * a threshold-signed message:
6
- *
7
- * 1. takes the message's `signers`, the cohort `coord` the signers should belong to, and the tier;
8
- * 2. looks up the cached `MembershipCertV1` for that coord (or pulls the source's `current`);
9
- * 3. checks the signers are a `≥ minSigs` subset of the cert's members and the signature verifies;
10
- * 4. **on failure against a cached/stale cert, re-fetches the cert from any cohort member exactly
11
- * once and retries**; still failing → the message is untrusted.
12
- *
13
- * **Trust anchoring (the gate this module adds).** Self-consistency (a cert's own threshold signature
14
- * is a `≥ minSigs` quorum over its own `members`) proves only internal well-formedness — *not* that the
15
- * attesting key set is the legitimate cohort for the coord. An adversary controlling `k − x` keys could
16
- * mint a self-consistent cert over a coord it does not own. So before a (re)fetched cert is believed,
17
- * {@link CachingMembershipVerifier.certIsTrusted} requires it to be self-consistent **AND** anchored by
18
- * at least one of:
19
- *
20
- * - **Trust root** — `(coord, epoch, member-set)` is in the out-of-band-seeded {@link TrustRoot} set
21
- * (the genesis-block cohorts). Base case of every chain; checked before the direct anchor, so a
22
- * configured root is authoritative.
23
- * - **Direct anchor** — the injected {@link IMembershipTrustAnchor} vouches for the binding from a
24
- * source the node directly trusts (FRET ring agreement / tx-log commit cert, bound in db-p2p). A
25
- * `"rejected"` verdict is **fatal** (a forgery, even if self-consistent) and overrides the fallback.
26
- * - **Attestation chain** — a cert carrying a rotation attestation (`prevEpoch`/`rotationSig`/
27
- * `rotationSigners`) inherits trust when the node already holds a **trusted** predecessor for the same
28
- * coord at `prevEpoch` whose members form a `≥ minSigs` quorum over this cert's signing payload.
29
- *
30
- * **Interim TOFU fallback (documented limit).** For a coord the node cannot anchor (the direct anchor
31
- * returns `"unknown"` and there is no trust root / chain) and that has **no trusted cert yet**, the
32
- * verifier falls back to trust-on-first-use of any self-consistent cert — identical to the pre-anchor
33
- * behavior, so there is strictly no regression on coords no node can verify today (distant T2/T3, and
34
- * T0/T1 until the committed-index binding lands). Once a coord *does* hold a trusted cert, the chain
35
- * governs successors: an un-anchored cert for an already-trusted coord is rejected (no TOFU downgrade),
36
- * which is what gives the rotation chain its teeth. The FRET / tx-log direct-anchor bindings that close
37
- * the remaining TOFU gap are tracked in `cohort-topic-trust-anchor-fret-binding` and the backlog
38
- * `...-fret-stabilization-proof` / `...-txlog-committed-binding` tickets.
39
- *
40
- * **Deviation from the ticket sketch (documented):** `verifyMessage` takes the cohort `tier`. A coord
41
- * is an opaque hash, so the T0/T1-vs-T2/T3 source dispatch the same ticket mandates cannot be derived
42
- * from the coord alone; the caller already knows the tier (it computed the coord from the message's
43
- * claimed tier/topic). The `tier` is threaded into the gate so the direct anchor is consulted with the
44
- * same tier the router used (the binding is tier-scoped).
45
- */
46
-
47
- import type { IMembershipTrustAnchor, RingCoord, TrustRoot } from "../ports.js";
48
- import { noAuthorityTrustAnchor } from "../ports.js";
49
- import { b64urlToBytes, bytesToB64url, decodeMembershipCertV1 } from "../wire/codec.js";
50
- import { CohortWireError } from "../wire/validate.js";
51
- import type { MembershipCertV1 } from "../wire/types.js";
52
- import { DEFAULT_MIN_SIGS, type CohortSigner } from "../sig/threshold.js";
53
- import { membershipCertSigningPayload } from "../sig/payloads.js";
54
- import type { IMembershipSourceRouter } from "./source.js";
55
- import { LruMap } from "../../utility/lru-map.js";
56
-
57
- /**
58
- * Default hard cap on distinct coords the verifier's per-coord maps retain (`byCoord`, `lastFetchAt`,
59
- * `staleGapStrikes`). Beyond it the least-recently-used coord is evicted — bounding memory under a flood
60
- * of verify-misses against attacker-chosen coords. Same 100k ballpark as the sibling anti-DoS caps
61
- * ({@link import("../antidos/replay-guard.js").DEFAULT_REPLAY_GUARD_MAX_KEYS}).
62
- */
63
- export const DEFAULT_MEMBERSHIP_VERIFIER_MAX_COORDS = 100_000;
64
-
65
- /** Outcome of verifying a threshold-signed message against cohort membership. */
66
- export type VerifyResult = "verified" | "untrusted";
67
-
68
- /** Caches certs per coord and verifies threshold-signed messages with one stale-cert refetch. */
69
- export interface MembershipVerifier {
70
- /** Cache `cert` as the latest known membership for its coord. */
71
- cache(cert: MembershipCertV1): void;
72
- /**
73
- * Verify a threshold-signed message. `expectedCoord` is the cohort the `signers` should belong to;
74
- * `tier` selects the membership source. Performs the single refetch+retry internally.
75
- *
76
- * `opts` bounds the network amplification a flood-exposed caller (the `promote` handler) can suffer:
77
- * when **both** `minRefetchIntervalMs` and `now` are given, the stale-cert `source.fetch()` retry is
78
- * **rate-limited per coord** — at most one refetch per coord per interval — so a stream of verify-misses
79
- * (e.g. forged notices) drives a bounded membership-fetch rate rather than one dial per message.
80
- * Eventual refetch is *preserved*: a cold cache or a membership rotation still re-fetches once the
81
- * interval elapses (unlike outright suppression). Omit `opts` (the default, and every existing caller)
82
- * for the unbounded exactly-one-refetch behavior.
83
- */
84
- verifyMessage(signers: readonly Uint8Array[], expectedCoord: RingCoord, tier: number, payload: Uint8Array, sig: Uint8Array, opts?: RefetchBound): Promise<VerifyResult>;
85
- }
86
-
87
- /**
88
- * Caller-supplied bound on the membership-cert refetch rate (anti-amplification on a flood-exposed verify
89
- * path). Both fields are required to take effect; omit either for unbounded refetch.
90
- */
91
- export interface RefetchBound {
92
- /** Minimum wall-clock gap (ms) between `source.fetch()` refetches for the same coord. */
93
- readonly minRefetchIntervalMs?: number;
94
- /** Current wall clock (ms) for the interval comparison. */
95
- readonly now?: number;
96
- }
97
-
98
- export interface MembershipVerifierDeps {
99
- signer: CohortSigner;
100
- router: IMembershipSourceRouter;
101
- minSigs?: number;
102
- maxMessageBytes?: number;
103
- /**
104
- * Direct (base-case) trust anchor for a cert's `coord → keyset` binding. Defaults to
105
- * {@link noAuthorityTrustAnchor} (every coord `"unknown"`), which preserves the interim TOFU behavior.
106
- * db-p2p injects the FRET-ring-backed anchor.
107
- */
108
- anchor?: IMembershipTrustAnchor;
109
- /** Out-of-band-seeded genesis trust roots (the base case of every attestation chain). Defaults to `[]`. */
110
- trustRoots?: readonly TrustRoot[];
111
- /**
112
- * Number of **consecutive** gap-signalled refetches after which a **trust-locked** coord whose direct
113
- * anchor has gone `"unknown"` re-enters the interim TOFU regime — the exit from a stale trust-lock a
114
- * former cohort member would otherwise be stranded in until the host process restarts.
115
- *
116
- * The lock (a coord holding a *trusted* cached cert refuses any un-anchored refetch — no TOFU downgrade)
117
- * has no other exit: a node that served coord `C`, self-published its cert (locking `C`), then left `C`'s
118
- * cohort keeps distrusting every later-epoch message from `C` if it missed an intermediate rotation, since
119
- * the refetched cert's `prevEpoch` no longer matches the stale cached epoch and the anchor no longer
120
- * vouches for `C`. Recovery counts **only** refetched certs presenting an *explicit chain gap* a full
121
- * rotation attestation whose `prevEpoch ≠` the cached trusted epoch (the network provably rotated past the
122
- * cached epoch through an epoch this node never witnessed). A forged rotation off the *current* cached
123
- * predecessor (`prevEpoch == cachedEpoch`) never counts as a strike, so the lock's headline invariant
124
- * (un-anchored successor of a matching predecessor stays rejected) is preserved.
125
- *
126
- * Defaults to `3`. Setting it to `0` (or a negative) **disables** recovery which re-opens the stale-lock
127
- * liveness bug, so leave it on unless a caller has an independent lock-drop mechanism (see the
128
- * drop-the-lock-on-demotion tripwire in the ticket).
129
- */
130
- staleGapRecoveryStrikes?: number;
131
- /**
132
- * Hard LRU cap on distinct coords retained across the verifier's per-coord maps (`byCoord`,
133
- * `lastFetchAt`, `staleGapStrikes`); the least-recently-used coord is evicted beyond it. Bounds memory
134
- * under a flood of verify-misses against attacker-chosen coords. Defaults to
135
- * {@link DEFAULT_MEMBERSHIP_VERIFIER_MAX_COORDS}; must be a positive integer (mirrors the sibling
136
- * anti-DoS `maxKeys` guard).
137
- */
138
- maxCoords?: number;
139
- }
140
-
141
- /** Result of the trust gate: accept as a trusted anchor, accept as interim TOFU, or reject outright. */
142
- type CertTrust = "trusted" | "tofu" | "reject";
143
-
144
- /** A cached cert and whether it is *trusted* (may serve as an attestation-chain predecessor). */
145
- interface CachedCert {
146
- cert: MembershipCertV1;
147
- /** True only when the cert passed via trust-root / direct-anchor / chain, or was self-published (`cache`). */
148
- trusted: boolean;
149
- }
150
-
151
- /** A {@link TrustRoot} pre-normalized to the cert's base64url form for cheap matching. */
152
- interface NormalizedTrustRoot {
153
- coord: string;
154
- epoch: string;
155
- members: ReadonlySet<string>;
156
- }
157
-
158
- class CachingMembershipVerifier implements MembershipVerifier {
159
- // LRU-capped so a flood of verify-misses against attacker-chosen coords cannot grow these maps without
160
- // bound (coordKey is base64url of an attacker-derivable RingCoord). Each is capped INDEPENDENTLY: the
161
- // aux maps may briefly retain a coord `byCoord` already evicted — harmless (a stale `lastFetchAt` at
162
- // worst permits one extra refetch; a stale strike count is itself bounded).
163
- // NOTE: `byCoord` also holds this node's OWN `cache()`-published trusted cert (the trust lock). Under an
164
- // attacker-coord flood the LRU can evict a trusted self-published entry, re-opening that coord to TOFU on
165
- // next sight — the trust lock is best-effort under memory pressure. This mirrors the documented penalty
166
- // tradeoff on the replay-guard cap and is acceptable; do not file it as a separate ticket.
167
- private readonly byCoord: LruMap<string, CachedCert>;
168
- /** Per-coord timestamp of the last `source.fetch()` attempt (the rate-limit clock for {@link RefetchBound}). */
169
- private readonly lastFetchAt: LruMap<string, number>;
170
- /**
171
- * Per-coord count of *consecutive* gap-signalled refetches against a trust-locked coord (base64url key).
172
- * Reset to zero whenever a message verifies for the coord (see {@link verifyMessage}); at
173
- * {@link staleGapRecoveryStrikes} the lock is released back to TOFU (see {@link staleGapRecovery}).
174
- */
175
- private readonly staleGapStrikes: LruMap<string, number>;
176
- private readonly minSigs: number;
177
- private readonly anchor: IMembershipTrustAnchor;
178
- private readonly trustRoots: readonly NormalizedTrustRoot[];
179
- private readonly staleGapRecoveryStrikes: number;
180
-
181
- constructor(private readonly deps: MembershipVerifierDeps) {
182
- this.minSigs = deps.minSigs ?? DEFAULT_MIN_SIGS;
183
- this.anchor = deps.anchor ?? noAuthorityTrustAnchor;
184
- this.trustRoots = (deps.trustRoots ?? []).map(normalizeTrustRoot);
185
- this.staleGapRecoveryStrikes = deps.staleGapRecoveryStrikes ?? 3;
186
- const maxCoords = deps.maxCoords ?? DEFAULT_MEMBERSHIP_VERIFIER_MAX_COORDS;
187
- if (!Number.isInteger(maxCoords) || maxCoords <= 0) {
188
- throw new RangeError(`maxCoords must be a positive integer, got ${maxCoords}`);
189
- }
190
- this.byCoord = new LruMap(maxCoords);
191
- this.lastFetchAt = new LruMap(maxCoords);
192
- this.staleGapStrikes = new LruMap(maxCoords);
193
- }
194
-
195
- cache(cert: MembershipCertV1): void {
196
- // The public cache feeds this node its OWN freshly-published cert — a node trusts a cert it itself
197
- // published, so it is marked trusted and may anchor the next rotation in the attestation chain.
198
- this.byCoord.set(cert.cohortCoord, { cert, trusted: true });
199
- }
200
-
201
- async verifyMessage(signers: readonly Uint8Array[], expectedCoord: RingCoord, tier: number, payload: Uint8Array, sig: Uint8Array, opts?: RefetchBound): Promise<VerifyResult> {
202
- const coordKey = bytesToB64url(expectedCoord);
203
- const source = this.deps.router.for(tier);
204
-
205
- // Seed from the cheap cached view if we hold nothing yet. A cached cert already passed the gate when
206
- // it was loaded (or was self-published via `cache`), so it is used directly for message verification.
207
- let cert = this.byCoord.get(coordKey)?.cert;
208
- if (cert === undefined) {
209
- cert = await this.loadFrom(source.current(expectedCoord), tier);
210
- }
211
- if (cert !== undefined && this.messageVerifies(cert, signers, payload, sig)) {
212
- this.staleGapStrikes.delete(coordKey); // a verify resets the consecutive stale-gap strike count
213
- return "verified";
214
- }
215
-
216
- // Single fetch-and-retry: a stale or missing cert forces a network refresh. A flood-exposed caller
217
- // (the ungated `promote` handler) bounds the amplification via {@link RefetchBound}: the refetch is
218
- // then rate-limited to at most one per coord per interval, so a stream of verify-misses (forged
219
- // notices) cannot turn into a storm of membership dials. Eventual refetch survives a cold cache or a
220
- // membership rotation still refreshes once the interval elapses.
221
- if (!this.refetchAllowed(coordKey, opts)) {
222
- return "untrusted";
223
- }
224
- const refreshed = await this.loadFrom(source.fetch(expectedCoord), tier);
225
- if (refreshed !== undefined && this.messageVerifies(refreshed, signers, payload, sig)) {
226
- this.staleGapStrikes.delete(coordKey); // a verify resets the consecutive stale-gap strike count
227
- return "verified";
228
- }
229
- return "untrusted";
230
- }
231
-
232
- /**
233
- * Whether a `source.fetch()` refetch is permitted for `coordKey` now. Unbounded (always `true`) unless
234
- * the caller supplies both `minRefetchIntervalMs` and `now`, in which case at most one refetch per coord
235
- * per interval is allowed — the per-coord fetch-rate bound that caps flood amplification. Records the
236
- * attempt time when it returns `true` (the dial is about to happen).
237
- */
238
- private refetchAllowed(coordKey: string, opts?: RefetchBound): boolean {
239
- const minInterval = opts?.minRefetchIntervalMs;
240
- const now = opts?.now;
241
- if (minInterval === undefined || now === undefined) {
242
- return true;
243
- }
244
- const last = this.lastFetchAt.get(coordKey);
245
- if (last !== undefined && now - last < minInterval) {
246
- return false;
247
- }
248
- this.lastFetchAt.set(coordKey, now);
249
- return true;
250
- }
251
-
252
- /**
253
- * Decode an encoded cert, run it through the trust gate, cache it (with its trusted status), and return
254
- * it for message verification; `undefined` if absent, malformed, or rejected by the gate. A rejected
255
- * cert (failed self-consistency, a `"rejected"` direct anchor, or an un-anchored cert for an
256
- * already-trusted coord) is treated exactly like an absent cert, so the single refetch still fires.
257
- */
258
- private async loadFrom(pending: Promise<Uint8Array | undefined>, tier: number): Promise<MembershipCertV1 | undefined> {
259
- const encoded = await pending;
260
- if (encoded === undefined) {
261
- return undefined;
262
- }
263
- let cert: MembershipCertV1;
264
- let trust: CertTrust;
265
- try {
266
- cert = decodeMembershipCertV1(encoded, this.deps.maxMessageBytes);
267
- trust = this.certIsTrusted(cert, tier);
268
- } catch (err) {
269
- if (err instanceof CohortWireError) {
270
- return undefined; // a malformed cert (or non-base64url signer) is treated as no cert
271
- }
272
- throw err;
273
- }
274
- if (trust === "reject") {
275
- return undefined;
276
- }
277
- // Only a `"trusted"` cert may anchor a successor in the attestation chain; a `"tofu"` cert is cached
278
- // for message verification but must never launder trust into a rotation.
279
- this.byCoord.set(cert.cohortCoord, { cert, trusted: trust === "trusted" });
280
- return cert;
281
- }
282
-
283
- /**
284
- * The trust gate (see the module header). A cert is accepted iff it is self-consistent **and** anchored
285
- * by a trust root, the direct anchor, or the attestation chain; otherwise it falls to the interim TOFU
286
- * fallback (first-use only). Returns whether the cert is a trusted anchor (`"trusted"`), an interim
287
- * TOFU acceptance (`"tofu"`), or rejected (`"reject"`).
288
- */
289
- private certIsTrusted(cert: MembershipCertV1, tier: number): CertTrust {
290
- if (!this.certIsSelfConsistent(cert)) {
291
- return "reject"; // internal well-formedness is the precondition for any trust path
292
- }
293
- if (this.matchesTrustRoot(cert)) {
294
- return "trusted"; // a configured genesis root is authoritative, checked before the direct anchor
295
- }
296
- const verdict = this.anchor.directAnchor(cert, tier);
297
- if (verdict === "anchored") {
298
- return "trusted";
299
- }
300
- if (verdict === "rejected") {
301
- return "reject"; // a contradicted binding is a forgery — fatal, overrides the TOFU fallback
302
- }
303
- // verdict === "unknown": no local authority for this coord. Try the attestation chain, else fall back.
304
- if (this.hasRotationAttestation(cert) && this.chainGrantsTrust(cert)) {
305
- return "trusted";
306
- }
307
- const fallback = this.fallbackTrust(cert);
308
- if (fallback !== "reject") {
309
- return fallback; // first-use TOFU (coord not locked): no stale lock to recover from
310
- }
311
- // fallback === "reject" the coord is trust-locked (holds a *trusted* cert) and this un-anchored cert
312
- // did not chain-verify the state that strands a former cohort member forever. Consult the stale-gap
313
- // recovery counter, which releases the lock only on a demonstrated chain gap (never a forged rotation
314
- // off the current predecessor). See {@link staleGapRecovery}.
315
- return this.staleGapRecovery(cert);
316
- }
317
-
318
- /**
319
- * Bounded re-TOFU recovery for a coord that is **trust-locked at a stale epoch it can no longer anchor**.
320
- * Reached from {@link certIsTrusted} only when the coord already holds a *trusted* cached cert (locked),
321
- * the direct anchor said `"unknown"`, and `cert` did not chain-verify — i.e. {@link fallbackTrust} would
322
- * otherwise reject it forever. Runs on the *refetch* load only: a locked coord always holds a cached cert,
323
- * so `verifyMessage` never routes it through the `source.current()` seed path, and the strike logic keys on
324
- * "coord is locked", so `current()` never accrues a strike.
325
- *
326
- * NOTE: recovery fires **only** on a demonstrated chain gap — a full rotation attestation whose
327
- * `prevEpoch ≠` the cached trusted epoch (proof the network rotated past the cached epoch through at least
328
- * one epoch this node never witnessed). A forged rotation off the *current* cached predecessor
329
- * (`prevEpoch == cachedEpoch`) is NOT a gap, never counts as a strike, and stays rejected no matter how
330
- * often it is presented — that is the lock's headline invariant. After
331
- * {@link staleGapRecoveryStrikes} *consecutive* gap-signalled strikes the lock is released back to TOFU
332
- * (returns `"tofu"`, so {@link loadFrom} re-caches the cert as **untrusted** — a re-TOFU'd cert must never
333
- * launder trust into a rotation), which is no weaker than the documented TOFU baseline: a former member
334
- * returns to the same regime a never-member is already in. Strikes accrue only on refetches that actually
335
- * reach the source, so a {@link RefetchBound}-suppressed refetch observes no cert and recovery paces itself
336
- * with the (bounded) refetch rate — intended, do not "fix" that pacing.
337
- */
338
- private staleGapRecovery(cert: MembershipCertV1): CertTrust {
339
- const coordKey = cert.cohortCoord;
340
- const locked = this.byCoord.get(coordKey);
341
- // Recovery-eligible only on an explicit rotation gap: a full attestation whose prevEpoch is neither the
342
- // cert's own epoch (a self-referential rotation) nor the cached trusted epoch (a forgery off the current
343
- // predecessor — the case the lock exists to reject).
344
- const isGap =
345
- this.staleGapRecoveryStrikes > 0 &&
346
- locked !== undefined &&
347
- this.hasRotationAttestation(cert) &&
348
- cert.prevEpoch !== cert.cohortEpoch &&
349
- cert.prevEpoch !== locked.cert.cohortEpoch;
350
- if (!isGap) {
351
- return "reject"; // not a recovery-eligible gap → stay locked, exactly as before
352
- }
353
- const strikes = (this.staleGapStrikes.get(coordKey) ?? 0) + 1;
354
- if (strikes < this.staleGapRecoveryStrikes) {
355
- this.staleGapStrikes.set(coordKey, strikes);
356
- return "reject"; // below threshold: keep rejecting; the inbound message stays untrusted
357
- }
358
- // Threshold reached: release the lock. `loadFrom` re-caches this cert as untrusted (`trusted: false`),
359
- // and the message-verify retry runs against it, so the inbound later-epoch message finally verifies.
360
- this.staleGapStrikes.delete(coordKey);
361
- return "tofu";
362
- }
363
-
364
- /**
365
- * The interim fallback for a coord with no trust-root / anchor / chain coverage. Trust-on-first-use:
366
- * accept a self-consistent cert when the coord holds **no trusted cert yet**, preserving the pre-anchor
367
- * behavior on coords no node can verify today. But once a coord *is* trust-established, an un-anchored
368
- * cert (a failed/absent rotation, including a forged rotation off a trusted predecessor) is **rejected**
369
- * no silent TOFU downgrade which is what gives the attestation chain its teeth.
370
- */
371
- private fallbackTrust(cert: MembershipCertV1): CertTrust {
372
- return this.byCoord.get(cert.cohortCoord)?.trusted ? "reject" : "tofu";
373
- }
374
-
375
- /** Whether a cert carries a full rotation attestation (all three fields; validated all-or-nothing on the wire). */
376
- private hasRotationAttestation(cert: MembershipCertV1): boolean {
377
- return cert.prevEpoch !== undefined && cert.rotationSig !== undefined && cert.rotationSigners !== undefined;
378
- }
379
-
380
- /**
381
- * Whether `cert`'s rotation attestation is valid: a **trusted** predecessor for the same coord is cached
382
- * at `prevEpoch`, the rotation is not self-referential, and the predecessor's members form a `≥ minSigs`
383
- * quorum over this cert's signing payload via `rotationSig`. A predecessor that only reached the cache via
384
- * TOFU (not trusted) must not anchor the successor the trusted-cache invariant.
385
- */
386
- private chainGrantsTrust(cert: MembershipCertV1): boolean {
387
- const prevEpoch = cert.prevEpoch!;
388
- if (prevEpoch === cert.cohortEpoch) {
389
- return false; // a cert cannot rotate from itself
390
- }
391
- const predecessor = this.byCoord.get(cert.cohortCoord);
392
- if (predecessor === undefined || !predecessor.trusted || predecessor.cert.cohortEpoch !== prevEpoch) {
393
- return false;
394
- }
395
- // `rotationSigners` is validated only as a string array, so `b64urlToBytes` may throw `CohortWireError`
396
- // on a malformed signer — `loadFrom`'s try/catch turns that into "no cert", as for `certIsSelfConsistent`.
397
- return this.deps.signer.verifyThreshold(
398
- membershipCertSigningPayload(cert),
399
- b64urlToBytes(cert.rotationSig!),
400
- cert.rotationSigners!.map((s) => b64urlToBytes(s)),
401
- predecessor.cert,
402
- this.minSigs,
403
- );
404
- }
405
-
406
- /** Whether `cert` matches a configured trust root by `(coord, epoch)` and an order-independent member set. */
407
- private matchesTrustRoot(cert: MembershipCertV1): boolean {
408
- for (const root of this.trustRoots) {
409
- if (root.coord === cert.cohortCoord && root.epoch === cert.cohortEpoch && setEqualsArray(root.members, cert.members)) {
410
- return true;
411
- }
412
- }
413
- return false;
414
- }
415
-
416
- /** A cert is self-consistent only if its own threshold signature is a valid quorum of its members. */
417
- private certIsSelfConsistent(cert: MembershipCertV1): boolean {
418
- // `signers` is validated only as a string array (not per-element base64url), so `b64urlToBytes`
419
- // below may throw `CohortWireError` on a malformed signer — `loadFrom`'s try/catch turns that
420
- // into "no cert" rather than letting it escape.
421
- return this.deps.signer.verifyThreshold(
422
- membershipCertSigningPayload(cert),
423
- b64urlToBytes(cert.thresholdSig),
424
- cert.signers.map((s) => b64urlToBytes(s)),
425
- cert,
426
- this.minSigs,
427
- );
428
- }
429
-
430
- private messageVerifies(cert: MembershipCertV1, signers: readonly Uint8Array[], payload: Uint8Array, sig: Uint8Array): boolean {
431
- return this.deps.signer.verifyThreshold(payload, sig, signers, cert, this.minSigs);
432
- }
433
- }
434
-
435
- /** Pre-normalize a {@link TrustRoot} (raw bytes) to the cert's base64url form for cheap matching. */
436
- function normalizeTrustRoot(root: TrustRoot): NormalizedTrustRoot {
437
- return {
438
- coord: bytesToB64url(root.coord),
439
- epoch: bytesToB64url(root.epoch),
440
- members: new Set(root.members.map(bytesToB64url)),
441
- };
442
- }
443
-
444
- /** Order-independent set equality between a trust-root member set and a cert's member array (duplicate-safe). */
445
- function setEqualsArray(set: ReadonlySet<string>, members: readonly string[]): boolean {
446
- const seen = new Set<string>();
447
- for (const m of members) {
448
- if (!set.has(m)) {
449
- return false; // a member not in the root → not a root match
450
- }
451
- seen.add(m);
452
- }
453
- // Cover both directions: every distinct cert member is in the root AND every root member is covered,
454
- // so a duplicate-inflated member list cannot masquerade as a full-set match.
455
- return seen.size === set.size;
456
- }
457
-
458
- /** Build a participant-side {@link MembershipVerifier}. */
459
- export function createMembershipVerifier(deps: MembershipVerifierDeps): MembershipVerifier {
460
- return new CachingMembershipVerifier(deps);
461
- }
1
+ /**
2
+ * Cohort-topic substrate — participant-side membership verification with a trust-anchor gate.
3
+ *
4
+ * Per `docs/cohort-topic.md` §Membership snapshots and §Bootstrapping trust. A participant verifying
5
+ * a threshold-signed message:
6
+ *
7
+ * 1. takes the message's `signers`, the cohort `coord` the signers should belong to, and the tier;
8
+ * 2. looks up the cached `MembershipCertV1` for that coord (or pulls the source's `current`);
9
+ * 3. checks the signers are a `≥ minSigs` subset of the cert's members and the signature verifies;
10
+ * 4. **on failure against a cached/stale cert, re-fetches the cert from any cohort member exactly
11
+ * once and retries**; still failing → the message is untrusted.
12
+ *
13
+ * **Trust anchoring (the gate this module adds).** Self-consistency (a cert's own threshold signature
14
+ * is a `≥ minSigs` quorum over its own `members`) proves only internal well-formedness — *not* that the
15
+ * attesting key set is the legitimate cohort for the coord. An adversary controlling `k − x` keys could
16
+ * mint a self-consistent cert over a coord it does not own. So before a (re)fetched cert is believed,
17
+ * {@link CachingMembershipVerifier.certIsTrusted} requires it to be self-consistent **AND** anchored by
18
+ * at least one of:
19
+ *
20
+ * - **Trust root** — `(coord, epoch, member-set)` is in the out-of-band-seeded {@link TrustRoot} set
21
+ * (the genesis-block cohorts). Base case of every chain; checked before the direct anchor, so a
22
+ * configured root is authoritative.
23
+ * - **Direct anchor** — the injected {@link IMembershipTrustAnchor} vouches for the binding from a
24
+ * source the node directly trusts (FRET ring agreement / tx-log commit cert, bound in db-p2p). A
25
+ * `"rejected"` verdict is **fatal** (a forgery, even if self-consistent) and overrides the fallback.
26
+ * - **Attestation chain** — a cert carrying a rotation attestation (`prevEpoch`/`rotationSig`/
27
+ * `rotationSigners`) inherits trust when the node already holds a **trusted** predecessor for the same
28
+ * coord at `prevEpoch` whose members form a `≥ minSigs` quorum over this cert's signing payload.
29
+ *
30
+ * **Interim TOFU fallback (documented limit).** For a coord the node cannot anchor (the direct anchor
31
+ * returns `"unknown"` and there is no trust root / chain) and that has **no trusted cert yet**, the
32
+ * verifier falls back to trust-on-first-use of any self-consistent cert — identical to the pre-anchor
33
+ * behavior, so there is strictly no regression on coords no node can verify today (distant T2/T3, and
34
+ * T0/T1 until the committed-index binding lands). Once a coord *does* hold a trusted cert, the chain
35
+ * governs successors: an un-anchored cert for an already-trusted coord is rejected (no TOFU downgrade),
36
+ * which is what gives the rotation chain its teeth. The FRET / tx-log direct-anchor bindings that close
37
+ * the remaining TOFU gap are tracked in `cohort-topic-trust-anchor-fret-binding` and the backlog
38
+ * `...-fret-stabilization-proof` / `...-txlog-committed-binding` tickets.
39
+ *
40
+ * **Deviation from the ticket sketch (documented):** `verifyMessage` takes the cohort `tier`. A coord
41
+ * is an opaque hash, so the T0/T1-vs-T2/T3 source dispatch the same ticket mandates cannot be derived
42
+ * from the coord alone; the caller already knows the tier (it computed the coord from the message's
43
+ * claimed tier/topic). The `tier` is threaded into the gate so the direct anchor is consulted with the
44
+ * same tier the router used (the binding is tier-scoped).
45
+ */
46
+
47
+ import type { IMembershipTrustAnchor, RingCoord, TrustRoot } from "../ports.js";
48
+ import { noAuthorityTrustAnchor } from "../ports.js";
49
+ import { b64urlToBytes, bytesToB64url, decodeMembershipCertV1 } from "../wire/codec.js";
50
+ import { CohortWireError } from "../wire/validate.js";
51
+ import type { MembershipCertV1 } from "../wire/types.js";
52
+ import { DEFAULT_MIN_SIGS, type CohortSigner } from "../sig/threshold.js";
53
+ import { membershipCertSigningPayload } from "../sig/payloads.js";
54
+ import type { IMembershipSourceRouter } from "./source.js";
55
+ import { LruMap } from "../../utility/lru-map.js";
56
+
57
+ /**
58
+ * Default hard cap on distinct coords the verifier's per-coord maps retain (`byCoord`, `lastFetchAt`,
59
+ * `staleGapStrikes`). Beyond it the least-recently-used coord is evicted — bounding memory under a flood
60
+ * of verify-misses against attacker-chosen coords. Same 100k ballpark as the sibling anti-DoS caps
61
+ * ({@link import("../antidos/replay-guard.js").DEFAULT_REPLAY_GUARD_MAX_KEYS}).
62
+ */
63
+ export const DEFAULT_MEMBERSHIP_VERIFIER_MAX_COORDS = 100_000;
64
+
65
+ /** Outcome of verifying a threshold-signed message against cohort membership. */
66
+ export type VerifyResult = "verified" | "untrusted";
67
+
68
+ /** Caches certs per coord and verifies threshold-signed messages with one stale-cert refetch. */
69
+ export interface MembershipVerifier {
70
+ /** Cache `cert` as the latest known membership for its coord. */
71
+ cache(cert: MembershipCertV1): void;
72
+ /**
73
+ * Drop everything cached for `cohortCoord` (base64url form, as on a cert's `cohortCoord`): the cached
74
+ * cert including a *trusted* self-published one, i.e. the trust lock — and any stale-gap strike
75
+ * count. The coord re-enters the cold-cache regime (interim TOFU on next sight). The host calls this
76
+ * when it evicts the coord's engine, so a lock published by a since-evicted engine cannot strand the
77
+ * coord's later-epoch messages. A no-op for a coord the verifier holds nothing for.
78
+ */
79
+ forget(cohortCoord: string): void;
80
+ /**
81
+ * Verify a threshold-signed message. `expectedCoord` is the cohort the `signers` should belong to;
82
+ * `tier` selects the membership source. Performs the single refetch+retry internally.
83
+ *
84
+ * `opts` bounds the network amplification a flood-exposed caller (the `promote` handler) can suffer:
85
+ * when **both** `minRefetchIntervalMs` and `now` are given, the stale-cert `source.fetch()` retry is
86
+ * **rate-limited per coord** — at most one refetch per coord per interval — so a stream of verify-misses
87
+ * (e.g. forged notices) drives a bounded membership-fetch rate rather than one dial per message.
88
+ * Eventual refetch is *preserved*: a cold cache or a membership rotation still re-fetches once the
89
+ * interval elapses (unlike outright suppression). Omit `opts` (the default, and every existing caller)
90
+ * for the unbounded exactly-one-refetch behavior.
91
+ */
92
+ verifyMessage(signers: readonly Uint8Array[], expectedCoord: RingCoord, tier: number, payload: Uint8Array, sig: Uint8Array, opts?: RefetchBound): Promise<VerifyResult>;
93
+ }
94
+
95
+ /**
96
+ * Caller-supplied bound on the membership-cert refetch rate (anti-amplification on a flood-exposed verify
97
+ * path). Both fields are required to take effect; omit either for unbounded refetch.
98
+ */
99
+ export interface RefetchBound {
100
+ /** Minimum wall-clock gap (ms) between `source.fetch()` refetches for the same coord. */
101
+ readonly minRefetchIntervalMs?: number;
102
+ /** Current wall clock (ms) for the interval comparison. */
103
+ readonly now?: number;
104
+ }
105
+
106
+ export interface MembershipVerifierDeps {
107
+ signer: CohortSigner;
108
+ router: IMembershipSourceRouter;
109
+ minSigs?: number;
110
+ maxMessageBytes?: number;
111
+ /**
112
+ * Direct (base-case) trust anchor for a cert's `coord keyset` binding. Defaults to
113
+ * {@link noAuthorityTrustAnchor} (every coord `"unknown"`), which preserves the interim TOFU behavior.
114
+ * db-p2p injects the FRET-ring-backed anchor.
115
+ */
116
+ anchor?: IMembershipTrustAnchor;
117
+ /** Out-of-band-seeded genesis trust roots (the base case of every attestation chain). Defaults to `[]`. */
118
+ trustRoots?: readonly TrustRoot[];
119
+ /**
120
+ * Number of **consecutive** gap-signalled refetches after which a **trust-locked** coord whose direct
121
+ * anchor has gone `"unknown"` re-enters the interim TOFU regime the exit from a stale trust-lock a
122
+ * former cohort member would otherwise be stranded in until the host process restarts.
123
+ *
124
+ * The lock (a coord holding a *trusted* cached cert refuses any un-anchored refetch — no TOFU downgrade)
125
+ * has no other exit: a node that served coord `C`, self-published its cert (locking `C`), then left `C`'s
126
+ * cohort keeps distrusting every later-epoch message from `C` if it missed an intermediate rotation, since
127
+ * the refetched cert's `prevEpoch` no longer matches the stale cached epoch and the anchor no longer
128
+ * vouches for `C`. Recovery counts **only** refetched certs presenting an *explicit chain gap* — a full
129
+ * rotation attestation whose `prevEpoch ≠` the cached trusted epoch (the network provably rotated past the
130
+ * cached epoch through an epoch this node never witnessed). A forged rotation off the *current* cached
131
+ * predecessor (`prevEpoch == cachedEpoch`) never counts as a strike, so the lock's headline invariant
132
+ * (un-anchored successor of a matching predecessor stays rejected) is preserved.
133
+ *
134
+ * Defaults to `3`. Setting it to `0` (or a negative) **disables** recovery which re-opens the stale-lock
135
+ * liveness bug, so leave it on unless a caller has an independent lock-drop mechanism (see the
136
+ * drop-the-lock-on-demotion tripwire in the ticket).
137
+ */
138
+ staleGapRecoveryStrikes?: number;
139
+ /**
140
+ * Hard LRU cap on distinct coords retained across the verifier's per-coord maps (`byCoord`,
141
+ * `lastFetchAt`, `staleGapStrikes`); the least-recently-used coord is evicted beyond it. Bounds memory
142
+ * under a flood of verify-misses against attacker-chosen coords. Defaults to
143
+ * {@link DEFAULT_MEMBERSHIP_VERIFIER_MAX_COORDS}; must be a positive integer (mirrors the sibling
144
+ * anti-DoS `maxKeys` guard).
145
+ */
146
+ maxCoords?: number;
147
+ }
148
+
149
+ /** Result of the trust gate: accept as a trusted anchor, accept as interim TOFU, or reject outright. */
150
+ type CertTrust = "trusted" | "tofu" | "reject";
151
+
152
+ /** A cached cert and whether it is *trusted* (may serve as an attestation-chain predecessor). */
153
+ interface CachedCert {
154
+ cert: MembershipCertV1;
155
+ /** True only when the cert passed via trust-root / direct-anchor / chain, or was self-published (`cache`). */
156
+ trusted: boolean;
157
+ }
158
+
159
+ /** A {@link TrustRoot} pre-normalized to the cert's base64url form for cheap matching. */
160
+ interface NormalizedTrustRoot {
161
+ coord: string;
162
+ epoch: string;
163
+ members: ReadonlySet<string>;
164
+ }
165
+
166
+ class CachingMembershipVerifier implements MembershipVerifier {
167
+ // LRU-capped so a flood of verify-misses against attacker-chosen coords cannot grow these maps without
168
+ // bound (coordKey is base64url of an attacker-derivable RingCoord). Each is capped INDEPENDENTLY: the
169
+ // aux maps may briefly retain a coord `byCoord` already evicted — harmless (a stale `lastFetchAt` at
170
+ // worst permits one extra refetch; a stale strike count is itself bounded).
171
+ // NOTE: `byCoord` also holds this node's OWN `cache()`-published trusted cert (the trust lock). Under an
172
+ // attacker-coord flood the LRU can evict a trusted self-published entry, re-opening that coord to TOFU on
173
+ // next sight the trust lock is best-effort under memory pressure. This mirrors the documented penalty
174
+ // tradeoff on the replay-guard cap and is acceptable; do not file it as a separate ticket.
175
+ private readonly byCoord: LruMap<string, CachedCert>;
176
+ /** Per-coord timestamp of the last `source.fetch()` attempt (the rate-limit clock for {@link RefetchBound}). */
177
+ private readonly lastFetchAt: LruMap<string, number>;
178
+ /**
179
+ * Per-coord count of *consecutive* gap-signalled refetches against a trust-locked coord (base64url key).
180
+ * Reset to zero whenever a message verifies for the coord (see {@link verifyMessage}); at
181
+ * {@link staleGapRecoveryStrikes} the lock is released back to TOFU (see {@link staleGapRecovery}).
182
+ */
183
+ private readonly staleGapStrikes: LruMap<string, number>;
184
+ private readonly minSigs: number;
185
+ private readonly anchor: IMembershipTrustAnchor;
186
+ private readonly trustRoots: readonly NormalizedTrustRoot[];
187
+ private readonly staleGapRecoveryStrikes: number;
188
+
189
+ constructor(private readonly deps: MembershipVerifierDeps) {
190
+ this.minSigs = deps.minSigs ?? DEFAULT_MIN_SIGS;
191
+ this.anchor = deps.anchor ?? noAuthorityTrustAnchor;
192
+ this.trustRoots = (deps.trustRoots ?? []).map(normalizeTrustRoot);
193
+ this.staleGapRecoveryStrikes = deps.staleGapRecoveryStrikes ?? 3;
194
+ const maxCoords = deps.maxCoords ?? DEFAULT_MEMBERSHIP_VERIFIER_MAX_COORDS;
195
+ if (!Number.isInteger(maxCoords) || maxCoords <= 0) {
196
+ throw new RangeError(`maxCoords must be a positive integer, got ${maxCoords}`);
197
+ }
198
+ this.byCoord = new LruMap(maxCoords);
199
+ this.lastFetchAt = new LruMap(maxCoords);
200
+ this.staleGapStrikes = new LruMap(maxCoords);
201
+ }
202
+
203
+ cache(cert: MembershipCertV1): void {
204
+ // The public cache feeds this node its OWN freshly-published cert — a node trusts a cert it itself
205
+ // published, so it is marked trusted and may anchor the next rotation in the attestation chain.
206
+ this.byCoord.set(cert.cohortCoord, { cert, trusted: true });
207
+ }
208
+
209
+ forget(cohortCoord: string): void {
210
+ // Drop the cached cert (the trust lock, when the entry was trusted) and the strike counter — the
211
+ // coord returns to the cold-cache / interim-TOFU regime. `lastFetchAt` is deliberately KEPT: it is
212
+ // anti-amplification state (the refetch rate-limit clock), not trust state, and keeping it means a
213
+ // forget cannot be used to reset a flood-exposed coord's refetch budget.
214
+ //
215
+ // NOTE: this drops the coord's entry whatever its provenance — a *remotely* fetched cert is discarded
216
+ // alongside a self-published lock, so the next sight of the coord re-runs the trust gate from cold.
217
+ // Harmless in both regimes today: with a working trust anchor the refetch re-derives the same
218
+ // `"trusted"` verdict, and with the anchor `"unknown"` the coord was already TOFU-grade with a bounded
219
+ // re-TOFU exit (`staleGapRecoveryStrikes`), so a forget only shortens a path that was already open.
220
+ // The caller today is engine eviction, which an attacker can drive by spraying coords — so if `forget`
221
+ // ever gains a caller in a regime where re-TOFU is NOT otherwise reachable, narrow it to the
222
+ // self-published lock (clear `trusted`, keep the cert) instead of deleting the entry.
223
+ this.byCoord.delete(cohortCoord);
224
+ this.staleGapStrikes.delete(cohortCoord);
225
+ }
226
+
227
+ async verifyMessage(signers: readonly Uint8Array[], expectedCoord: RingCoord, tier: number, payload: Uint8Array, sig: Uint8Array, opts?: RefetchBound): Promise<VerifyResult> {
228
+ const coordKey = bytesToB64url(expectedCoord);
229
+ const source = this.deps.router.for(tier);
230
+
231
+ // Seed from the cheap cached view if we hold nothing yet. A cached cert already passed the gate when
232
+ // it was loaded (or was self-published via `cache`), so it is used directly for message verification.
233
+ let cert = this.byCoord.get(coordKey)?.cert;
234
+ if (cert === undefined) {
235
+ cert = await this.loadFrom(source.current(expectedCoord), tier);
236
+ }
237
+ if (cert !== undefined && this.messageVerifies(cert, signers, payload, sig)) {
238
+ this.staleGapStrikes.delete(coordKey); // a verify resets the consecutive stale-gap strike count
239
+ return "verified";
240
+ }
241
+
242
+ // Single fetch-and-retry: a stale or missing cert forces a network refresh. A flood-exposed caller
243
+ // (the ungated `promote` handler) bounds the amplification via {@link RefetchBound}: the refetch is
244
+ // then rate-limited to at most one per coord per interval, so a stream of verify-misses (forged
245
+ // notices) cannot turn into a storm of membership dials. Eventual refetch survives — a cold cache or a
246
+ // membership rotation still refreshes once the interval elapses.
247
+ if (!this.refetchAllowed(coordKey, opts)) {
248
+ return "untrusted";
249
+ }
250
+ const refreshed = await this.loadFrom(source.fetch(expectedCoord), tier);
251
+ if (refreshed !== undefined && this.messageVerifies(refreshed, signers, payload, sig)) {
252
+ this.staleGapStrikes.delete(coordKey); // a verify resets the consecutive stale-gap strike count
253
+ return "verified";
254
+ }
255
+ return "untrusted";
256
+ }
257
+
258
+ /**
259
+ * Whether a `source.fetch()` refetch is permitted for `coordKey` now. Unbounded (always `true`) unless
260
+ * the caller supplies both `minRefetchIntervalMs` and `now`, in which case at most one refetch per coord
261
+ * per interval is allowed — the per-coord fetch-rate bound that caps flood amplification. Records the
262
+ * attempt time when it returns `true` (the dial is about to happen).
263
+ */
264
+ private refetchAllowed(coordKey: string, opts?: RefetchBound): boolean {
265
+ const minInterval = opts?.minRefetchIntervalMs;
266
+ const now = opts?.now;
267
+ if (minInterval === undefined || now === undefined) {
268
+ return true;
269
+ }
270
+ const last = this.lastFetchAt.get(coordKey);
271
+ if (last !== undefined && now - last < minInterval) {
272
+ return false;
273
+ }
274
+ this.lastFetchAt.set(coordKey, now);
275
+ return true;
276
+ }
277
+
278
+ /**
279
+ * Decode an encoded cert, run it through the trust gate, cache it (with its trusted status), and return
280
+ * it for message verification; `undefined` if absent, malformed, or rejected by the gate. A rejected
281
+ * cert (failed self-consistency, a `"rejected"` direct anchor, or an un-anchored cert for an
282
+ * already-trusted coord) is treated exactly like an absent cert, so the single refetch still fires.
283
+ */
284
+ private async loadFrom(pending: Promise<Uint8Array | undefined>, tier: number): Promise<MembershipCertV1 | undefined> {
285
+ const encoded = await pending;
286
+ if (encoded === undefined) {
287
+ return undefined;
288
+ }
289
+ let cert: MembershipCertV1;
290
+ let trust: CertTrust;
291
+ try {
292
+ cert = decodeMembershipCertV1(encoded, this.deps.maxMessageBytes);
293
+ trust = this.certIsTrusted(cert, tier);
294
+ } catch (err) {
295
+ if (err instanceof CohortWireError) {
296
+ return undefined; // a malformed cert (or non-base64url signer) is treated as no cert
297
+ }
298
+ throw err;
299
+ }
300
+ if (trust === "reject") {
301
+ return undefined;
302
+ }
303
+ // Only a `"trusted"` cert may anchor a successor in the attestation chain; a `"tofu"` cert is cached
304
+ // for message verification but must never launder trust into a rotation.
305
+ this.byCoord.set(cert.cohortCoord, { cert, trusted: trust === "trusted" });
306
+ return cert;
307
+ }
308
+
309
+ /**
310
+ * The trust gate (see the module header). A cert is accepted iff it is self-consistent **and** anchored
311
+ * by a trust root, the direct anchor, or the attestation chain; otherwise it falls to the interim TOFU
312
+ * fallback (first-use only). Returns whether the cert is a trusted anchor (`"trusted"`), an interim
313
+ * TOFU acceptance (`"tofu"`), or rejected (`"reject"`).
314
+ */
315
+ private certIsTrusted(cert: MembershipCertV1, tier: number): CertTrust {
316
+ if (!this.certIsSelfConsistent(cert)) {
317
+ return "reject"; // internal well-formedness is the precondition for any trust path
318
+ }
319
+ if (this.matchesTrustRoot(cert)) {
320
+ return "trusted"; // a configured genesis root is authoritative, checked before the direct anchor
321
+ }
322
+ const verdict = this.anchor.directAnchor(cert, tier);
323
+ if (verdict === "anchored") {
324
+ return "trusted";
325
+ }
326
+ if (verdict === "rejected") {
327
+ return "reject"; // a contradicted binding is a forgery fatal, overrides the TOFU fallback
328
+ }
329
+ // verdict === "unknown": no local authority for this coord. Try the attestation chain, else fall back.
330
+ if (this.hasRotationAttestation(cert) && this.chainGrantsTrust(cert)) {
331
+ return "trusted";
332
+ }
333
+ const fallback = this.fallbackTrust(cert);
334
+ if (fallback !== "reject") {
335
+ return fallback; // first-use TOFU (coord not locked): no stale lock to recover from
336
+ }
337
+ // fallback === "reject" ⟺ the coord is trust-locked (holds a *trusted* cert) and this un-anchored cert
338
+ // did not chain-verify — the state that strands a former cohort member forever. Consult the stale-gap
339
+ // recovery counter, which releases the lock only on a demonstrated chain gap (never a forged rotation
340
+ // off the current predecessor). See {@link staleGapRecovery}.
341
+ return this.staleGapRecovery(cert);
342
+ }
343
+
344
+ /**
345
+ * Bounded re-TOFU recovery for a coord that is **trust-locked at a stale epoch it can no longer anchor**.
346
+ * Reached from {@link certIsTrusted} only when the coord already holds a *trusted* cached cert (locked),
347
+ * the direct anchor said `"unknown"`, and `cert` did not chain-verify — i.e. {@link fallbackTrust} would
348
+ * otherwise reject it forever. Runs on the *refetch* load only: a locked coord always holds a cached cert,
349
+ * so `verifyMessage` never routes it through the `source.current()` seed path, and the strike logic keys on
350
+ * "coord is locked", so `current()` never accrues a strike.
351
+ *
352
+ * NOTE: recovery fires **only** on a demonstrated chain gap — a full rotation attestation whose
353
+ * `prevEpoch ≠` the cached trusted epoch (proof the network rotated past the cached epoch through at least
354
+ * one epoch this node never witnessed). A forged rotation off the *current* cached predecessor
355
+ * (`prevEpoch == cachedEpoch`) is NOT a gap, never counts as a strike, and stays rejected no matter how
356
+ * often it is presented that is the lock's headline invariant. After
357
+ * {@link staleGapRecoveryStrikes} *consecutive* gap-signalled strikes the lock is released back to TOFU
358
+ * (returns `"tofu"`, so {@link loadFrom} re-caches the cert as **untrusted** a re-TOFU'd cert must never
359
+ * launder trust into a rotation), which is no weaker than the documented TOFU baseline: a former member
360
+ * returns to the same regime a never-member is already in. Strikes accrue only on refetches that actually
361
+ * reach the source, so a {@link RefetchBound}-suppressed refetch observes no cert and recovery paces itself
362
+ * with the (bounded) refetch rate — intended, do not "fix" that pacing.
363
+ */
364
+ private staleGapRecovery(cert: MembershipCertV1): CertTrust {
365
+ const coordKey = cert.cohortCoord;
366
+ const locked = this.byCoord.get(coordKey);
367
+ // Recovery-eligible only on an explicit rotation gap: a full attestation whose prevEpoch is neither the
368
+ // cert's own epoch (a self-referential rotation) nor the cached trusted epoch (a forgery off the current
369
+ // predecessorthe case the lock exists to reject).
370
+ const isGap =
371
+ this.staleGapRecoveryStrikes > 0 &&
372
+ locked !== undefined &&
373
+ this.hasRotationAttestation(cert) &&
374
+ cert.prevEpoch !== cert.cohortEpoch &&
375
+ cert.prevEpoch !== locked.cert.cohortEpoch;
376
+ if (!isGap) {
377
+ return "reject"; // not a recovery-eligible gap stay locked, exactly as before
378
+ }
379
+ const strikes = (this.staleGapStrikes.get(coordKey) ?? 0) + 1;
380
+ if (strikes < this.staleGapRecoveryStrikes) {
381
+ this.staleGapStrikes.set(coordKey, strikes);
382
+ return "reject"; // below threshold: keep rejecting; the inbound message stays untrusted
383
+ }
384
+ // Threshold reached: release the lock. `loadFrom` re-caches this cert as untrusted (`trusted: false`),
385
+ // and the message-verify retry runs against it, so the inbound later-epoch message finally verifies.
386
+ this.staleGapStrikes.delete(coordKey);
387
+ return "tofu";
388
+ }
389
+
390
+ /**
391
+ * The interim fallback for a coord with no trust-root / anchor / chain coverage. Trust-on-first-use:
392
+ * accept a self-consistent cert when the coord holds **no trusted cert yet**, preserving the pre-anchor
393
+ * behavior on coords no node can verify today. But once a coord *is* trust-established, an un-anchored
394
+ * cert (a failed/absent rotation, including a forged rotation off a trusted predecessor) is **rejected**
395
+ * no silent TOFU downgrade which is what gives the attestation chain its teeth.
396
+ */
397
+ private fallbackTrust(cert: MembershipCertV1): CertTrust {
398
+ return this.byCoord.get(cert.cohortCoord)?.trusted ? "reject" : "tofu";
399
+ }
400
+
401
+ /** Whether a cert carries a full rotation attestation (all three fields; validated all-or-nothing on the wire). */
402
+ private hasRotationAttestation(cert: MembershipCertV1): boolean {
403
+ return cert.prevEpoch !== undefined && cert.rotationSig !== undefined && cert.rotationSigners !== undefined;
404
+ }
405
+
406
+ /**
407
+ * Whether `cert`'s rotation attestation is valid: a **trusted** predecessor for the same coord is cached
408
+ * at `prevEpoch`, the rotation is not self-referential, and the predecessor's members form a `≥ minSigs`
409
+ * quorum over this cert's signing payload via `rotationSig`. A predecessor that only reached the cache via
410
+ * TOFU (not trusted) must not anchor the successor — the trusted-cache invariant.
411
+ */
412
+ private chainGrantsTrust(cert: MembershipCertV1): boolean {
413
+ const prevEpoch = cert.prevEpoch!;
414
+ if (prevEpoch === cert.cohortEpoch) {
415
+ return false; // a cert cannot rotate from itself
416
+ }
417
+ const predecessor = this.byCoord.get(cert.cohortCoord);
418
+ if (predecessor === undefined || !predecessor.trusted || predecessor.cert.cohortEpoch !== prevEpoch) {
419
+ return false;
420
+ }
421
+ // `rotationSigners` is validated only as a string array, so `b64urlToBytes` may throw `CohortWireError`
422
+ // on a malformed signer — `loadFrom`'s try/catch turns that into "no cert", as for `certIsSelfConsistent`.
423
+ return this.deps.signer.verifyThreshold(
424
+ membershipCertSigningPayload(cert),
425
+ b64urlToBytes(cert.rotationSig!),
426
+ cert.rotationSigners!.map((s) => b64urlToBytes(s)),
427
+ predecessor.cert,
428
+ this.minSigs,
429
+ );
430
+ }
431
+
432
+ /** Whether `cert` matches a configured trust root by `(coord, epoch)` and an order-independent member set. */
433
+ private matchesTrustRoot(cert: MembershipCertV1): boolean {
434
+ for (const root of this.trustRoots) {
435
+ if (root.coord === cert.cohortCoord && root.epoch === cert.cohortEpoch && setEqualsArray(root.members, cert.members)) {
436
+ return true;
437
+ }
438
+ }
439
+ return false;
440
+ }
441
+
442
+ /** A cert is self-consistent only if its own threshold signature is a valid quorum of its members. */
443
+ private certIsSelfConsistent(cert: MembershipCertV1): boolean {
444
+ // `signers` is validated only as a string array (not per-element base64url), so `b64urlToBytes`
445
+ // below may throw `CohortWireError` on a malformed signer — `loadFrom`'s try/catch turns that
446
+ // into "no cert" rather than letting it escape.
447
+ return this.deps.signer.verifyThreshold(
448
+ membershipCertSigningPayload(cert),
449
+ b64urlToBytes(cert.thresholdSig),
450
+ cert.signers.map((s) => b64urlToBytes(s)),
451
+ cert,
452
+ this.minSigs,
453
+ );
454
+ }
455
+
456
+ private messageVerifies(cert: MembershipCertV1, signers: readonly Uint8Array[], payload: Uint8Array, sig: Uint8Array): boolean {
457
+ return this.deps.signer.verifyThreshold(payload, sig, signers, cert, this.minSigs);
458
+ }
459
+ }
460
+
461
+ /** Pre-normalize a {@link TrustRoot} (raw bytes) to the cert's base64url form for cheap matching. */
462
+ function normalizeTrustRoot(root: TrustRoot): NormalizedTrustRoot {
463
+ return {
464
+ coord: bytesToB64url(root.coord),
465
+ epoch: bytesToB64url(root.epoch),
466
+ members: new Set(root.members.map(bytesToB64url)),
467
+ };
468
+ }
469
+
470
+ /** Order-independent set equality between a trust-root member set and a cert's member array (duplicate-safe). */
471
+ function setEqualsArray(set: ReadonlySet<string>, members: readonly string[]): boolean {
472
+ const seen = new Set<string>();
473
+ for (const m of members) {
474
+ if (!set.has(m)) {
475
+ return false; // a member not in the root → not a root match
476
+ }
477
+ seen.add(m);
478
+ }
479
+ // Cover both directions: every distinct cert member is in the root AND every root member is covered,
480
+ // so a duplicate-inflated member list cannot masquerade as a full-set match.
481
+ return seen.size === set.size;
482
+ }
483
+
484
+ /** Build a participant-side {@link MembershipVerifier}. */
485
+ export function createMembershipVerifier(deps: MembershipVerifierDeps): MembershipVerifier {
486
+ return new CachingMembershipVerifier(deps);
487
+ }