@serfab/cadre-core 0.10.0 → 0.12.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 (145) hide show
  1. package/README.md +255 -255
  2. package/dist/announce-addrs.d.ts +49 -0
  3. package/dist/announce-addrs.js +78 -0
  4. package/dist/announce-addrs.js.map +1 -0
  5. package/dist/cadre-node.d.ts +484 -58
  6. package/dist/cadre-node.js +953 -182
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/control-cohort.d.ts +26 -0
  9. package/dist/control-cohort.js +26 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +222 -125
  12. package/dist/control-database.js +356 -266
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +8 -7
  15. package/dist/control-formation-recorder.js +8 -7
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +103 -0
  18. package/dist/control-read-retry.js +145 -0
  19. package/dist/control-read-retry.js.map +1 -0
  20. package/dist/control-retry.d.ts +101 -0
  21. package/dist/control-retry.js +108 -0
  22. package/dist/control-retry.js.map +1 -0
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +805 -774
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +65 -31
  27. package/dist/control-write-retry.js +33 -103
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +17 -15
  30. package/dist/delegate-admission.js +17 -15
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/index.d.ts +7 -5
  33. package/dist/index.js +18 -9
  34. package/dist/index.js.map +1 -1
  35. package/dist/membership-connection-gater.d.ts +211 -25
  36. package/dist/membership-connection-gater.js +309 -29
  37. package/dist/membership-connection-gater.js.map +1 -1
  38. package/dist/peer-addr-book.d.ts +92 -0
  39. package/dist/peer-addr-book.js +220 -0
  40. package/dist/peer-addr-book.js.map +1 -0
  41. package/dist/peer-record.d.ts +26 -0
  42. package/dist/peer-record.js +32 -0
  43. package/dist/peer-record.js.map +1 -1
  44. package/dist/relay-addrs.d.ts +76 -26
  45. package/dist/relay-addrs.js +115 -27
  46. package/dist/relay-addrs.js.map +1 -1
  47. package/dist/relay-reservation.d.ts +20 -15
  48. package/dist/relay-reservation.js +18 -14
  49. package/dist/relay-reservation.js.map +1 -1
  50. package/dist/seed-bootstrap.d.ts +7 -0
  51. package/dist/seed-bootstrap.js +15 -13
  52. package/dist/seed-bootstrap.js.map +1 -1
  53. package/dist/strand-addr-protocol.js +16 -0
  54. package/dist/strand-addr-protocol.js.map +1 -1
  55. package/dist/strand-backfill.js +13 -4
  56. package/dist/strand-backfill.js.map +1 -1
  57. package/dist/strand-cohort.d.ts +4 -37
  58. package/dist/strand-cohort.js +4 -15
  59. package/dist/strand-cohort.js.map +1 -1
  60. package/dist/strand-database.d.ts +11 -16
  61. package/dist/strand-database.js +19 -7
  62. package/dist/strand-database.js.map +1 -1
  63. package/dist/strand-formation-manager.d.ts +18 -17
  64. package/dist/strand-formation-manager.js +25 -27
  65. package/dist/strand-formation-manager.js.map +1 -1
  66. package/dist/strand-formation-protocol.d.ts +7 -7
  67. package/dist/strand-formation-protocol.js +8 -8
  68. package/dist/strand-formation-protocol.js.map +1 -1
  69. package/dist/strand-instance-manager.d.ts +53 -21
  70. package/dist/strand-instance-manager.js +128 -37
  71. package/dist/strand-instance-manager.js.map +1 -1
  72. package/dist/strand-membership-writer.d.ts +113 -19
  73. package/dist/strand-membership-writer.js +219 -51
  74. package/dist/strand-membership-writer.js.map +1 -1
  75. package/dist/strand-solicitation.d.ts +3 -3
  76. package/dist/strand-solicitation.js +4 -5
  77. package/dist/strand-solicitation.js.map +1 -1
  78. package/dist/strand-wake-protocol.d.ts +47 -2
  79. package/dist/strand-wake-protocol.js +76 -6
  80. package/dist/strand-wake-protocol.js.map +1 -1
  81. package/dist/types.d.ts +107 -54
  82. package/dist/types.js.map +1 -1
  83. package/package.json +8 -7
  84. package/src/announce-addrs.ts +93 -0
  85. package/src/arachnode-stub.ts +159 -159
  86. package/src/bootstrap-peer-store-file.ts +44 -44
  87. package/src/bootstrap-peer-store.ts +172 -172
  88. package/src/cadre-node.ts +1026 -194
  89. package/src/canonical-json.ts +30 -30
  90. package/src/control-authorization.ts +114 -114
  91. package/src/control-cohort.ts +130 -103
  92. package/src/control-database.ts +376 -298
  93. package/src/control-formation-recorder.ts +305 -304
  94. package/src/control-read-retry.ts +167 -0
  95. package/src/control-retry.ts +190 -0
  96. package/src/control-schema.ts +817 -786
  97. package/src/control-stream.ts +205 -205
  98. package/src/control-write-retry.ts +383 -473
  99. package/src/delegate-admission.ts +304 -302
  100. package/src/device-token.ts +94 -94
  101. package/src/diagnostics/connection-path.ts +277 -277
  102. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  103. package/src/ed25519-key.ts +134 -134
  104. package/src/enrollment.ts +199 -199
  105. package/src/file-durable-slot.ts +61 -61
  106. package/src/formation-approval.ts +604 -604
  107. package/src/fs-atomic.ts +107 -107
  108. package/src/hibernation-manager.ts +437 -437
  109. package/src/identity-key.ts +109 -109
  110. package/src/index.ts +435 -406
  111. package/src/key-store-file.ts +132 -132
  112. package/src/key-store.ts +99 -99
  113. package/src/membership-connection-gater.ts +368 -39
  114. package/src/node-local-snapshot.ts +260 -260
  115. package/src/peer-addr-book.ts +250 -0
  116. package/src/peer-authorization.ts +259 -259
  117. package/src/peer-record.ts +197 -164
  118. package/src/push-credentials.ts +84 -84
  119. package/src/push-node.ts +64 -64
  120. package/src/push-notifier-apns.ts +247 -247
  121. package/src/push-notifier-fcm.ts +220 -220
  122. package/src/push-notifier-shared.ts +28 -28
  123. package/src/push-notifier.ts +52 -52
  124. package/src/relay-addrs.ts +134 -27
  125. package/src/relay-reservation.ts +22 -17
  126. package/src/seed-bootstrap.ts +15 -15
  127. package/src/seed-trust-policy.ts +140 -140
  128. package/src/strand-addr-protocol.ts +458 -441
  129. package/src/strand-backfill.ts +28 -5
  130. package/src/strand-cohort.ts +38 -77
  131. package/src/strand-database.ts +202 -204
  132. package/src/strand-formation-manager.ts +26 -28
  133. package/src/strand-formation-protocol.ts +692 -692
  134. package/src/strand-instance-manager.ts +636 -553
  135. package/src/strand-member-key.ts +39 -39
  136. package/src/strand-member-registry.ts +182 -182
  137. package/src/strand-membership-writer.ts +1627 -1430
  138. package/src/strand-solicitation.ts +471 -472
  139. package/src/strand-transport-key.ts +58 -58
  140. package/src/strand-wake-payload.ts +32 -32
  141. package/src/strand-wake-protocol.ts +400 -314
  142. package/src/strand-watcher.ts +314 -314
  143. package/src/trusted-owner-store-file.ts +41 -41
  144. package/src/trusted-owner-store.ts +171 -171
  145. package/src/types.ts +1354 -1303
@@ -1,302 +1,304 @@
1
- /**
2
- * Delegate-peer admission grants for a party control node that also runs the
3
- * circuit-relay server.
4
- *
5
- * A strand node runs as its own libp2p instance with its own transport peerId,
6
- * derived from the cadre identity key + strandId (`strand-transport-key.ts`).
7
- * That derivation uses the member's PRIVATE seed by design, so no third party —
8
- * including a co-cadre relay — can recompute it. When a NAT'd member's strand
9
- * node tries to reserve a circuit-relay slot on a sibling's control node, the
10
- * relay's membership connection gater sees an unknown peerId and denies the
11
- * connection, which kills the reservation and fails the strand's
12
- * `libp2p.start()` outright.
13
- *
14
- * The resolution (docs/strands.md → "Relays and admission"): a party control
15
- * node running a relay is party-private infrastructure — it relays for its own
16
- * party's nodes, including the extra transport identities its members' strand
17
- * nodes run as, and for nobody else. The mechanism is a **member-announced
18
- * delegate grant**: before a member's control node starts a strand node, it
19
- * tells its siblings (over the already-authenticated `/sereus/strand-addr/1.0.0`
20
- * RPC) the derived peerId that strand node will use, and the receiver holds a
21
- * short-lived, in-memory admission grant for exactly that peerId. The grant is
22
- * consulted ONLY by the connection-level gate
23
- * (`CadreNode.admitInboundControlConnection`); the fail-closed per-stream gate
24
- * (`authorizeInboundControlStream`) never honors it, so a delegate gets the
25
- * connection (all a circuit-relay `hop` reservation needs) and nothing more.
26
- *
27
- * A grant is a delegation of trust to an already-trusted member: the receiver
28
- * cannot verify that the announced peerId really is the member's strand node,
29
- * so an authorized member can hand CONNECTION-level access to a peerId of its
30
- * choosing for up to {@link DELEGATE_GRANT_TTL_MS}. The caps below bound how
31
- * far a buggy or compromised member can stretch that.
32
- *
33
- * The receiver side is {@link DelegateAdmissionStore}. The announcer side keeps
34
- * its own throttle state (a "last announced at" map that `CadreNode` owns) and
35
- * decides from it, per reconcile pass, which relays are due a re-announce —
36
- * {@link dueRelayAnnounces} and {@link pruneStoppedStrandAnnounces} are that
37
- * decision, pure and testable, kept here beside the TTL they are derived from.
38
- */
39
-
40
- import debug from 'debug';
41
- import { multiaddr } from '@multiformats/multiaddr';
42
- import { peerIdFromString } from '@libp2p/peer-id';
43
-
44
- const log = debug('sereus:cadre:delegate-admission');
45
-
46
- /**
47
- * How long one announced delegate grant stays valid without a re-announce.
48
- * Announcers refresh at half this (`CadreNode`'s reconcile pass), so a live
49
- * strand's grant never lapses while its control node can still reach the relay.
50
- */
51
- export const DELEGATE_GRANT_TTL_MS = 30 * 60 * 1000;
52
-
53
- /** Cap on live grants per announcing member (soonest-expiry evicted first). */
54
- export const MAX_DELEGATE_GRANTS_PER_MEMBER = 32;
55
-
56
- /** Cap on live grants in total (soonest-expiry evicted first). */
57
- export const MAX_DELEGATE_GRANTS = 256;
58
-
59
- /** One recorded delegate admission grant. */
60
- interface DelegateGrant {
61
- /** The authorized member whose control node announced this delegate. */
62
- announcerPeerId: string;
63
- /** The strand the delegate serves — diagnostics + per-strand replace semantics. */
64
- strandId: string;
65
- /** The delegate transport peerId the grant admits. */
66
- delegatePeerId: string;
67
- /** Epoch ms after which the grant is inert. */
68
- expiresAt: number;
69
- }
70
-
71
- /**
72
- * Composite map key for the per-(peer, strand) state on both sides: the
73
- * receiver's replace-per-(announcer, strand) grant, and the announcer's
74
- * per-(target, strand) throttle timestamp.
75
- */
76
- export function peerStrandKey(peerId: string, strandId: string): string {
77
- return `${peerId}\n${strandId}`;
78
- }
79
-
80
- /** The `strandId` half of a {@link peerStrandKey}. */
81
- function strandIdOfKey(key: string): string {
82
- return key.slice(key.indexOf('\n') + 1);
83
- }
84
-
85
- /**
86
- * In-memory store of delegate admission grants, keyed by (announcer, strandId)
87
- * so a re-announce REPLACES the previous delegate peerId rather than
88
- * accumulating — a restarted strand cannot leak grants. Expired entries are
89
- * pruned lazily on every read/write. Injectable `now` keeps expiry testable
90
- * without fake timers.
91
- */
92
- export class DelegateAdmissionStore {
93
- private readonly grants = new Map<string, DelegateGrant>();
94
- private readonly ttlMs: number;
95
-
96
- constructor(ttlMs: number = DELEGATE_GRANT_TTL_MS) {
97
- this.ttlMs = ttlMs;
98
- }
99
-
100
- /** Number of live (unexpired at last prune) grants — test/diagnostic surface. */
101
- get size(): number {
102
- return this.grants.size;
103
- }
104
-
105
- /**
106
- * Record (or refresh) a grant: `delegatePeerId` acts on behalf of
107
- * `announcerPeerId` for `strandId`, valid for the store's TTL from `now`.
108
- * Enforces {@link MAX_DELEGATE_GRANTS_PER_MEMBER} and
109
- * {@link MAX_DELEGATE_GRANTS}, evicting the soonest-expiry grant first —
110
- * biased against the stalest delegation, never against the fresh announce.
111
- */
112
- grant(announcerPeerId: string, strandId: string, delegatePeerId: string, now: number = Date.now()): void {
113
- this.prune(now);
114
- const key = peerStrandKey(announcerPeerId, strandId);
115
- if (!this.grants.has(key)) {
116
- this.evictAtCap(
117
- MAX_DELEGATE_GRANTS_PER_MEMBER,
118
- (g) => g.announcerPeerId === announcerPeerId
119
- );
120
- this.evictAtCap(MAX_DELEGATE_GRANTS, () => true);
121
- }
122
- this.grants.set(key, { announcerPeerId, strandId, delegatePeerId, expiresAt: now + this.ttlMs });
123
- log('Delegate grant recorded: %s → %s (strand %s, %d live)', announcerPeerId, delegatePeerId, strandId, this.grants.size);
124
- }
125
-
126
- /**
127
- * Drop every grant. Called when the owning node stops: grants are scoped to
128
- * the session that recorded them, and outliving it would admit delegates
129
- * announced against a node that no longer exists.
130
- */
131
- clear(): void {
132
- this.grants.clear();
133
- }
134
-
135
- /** Is `remotePeerId` covered by a live grant? Prunes expired entries as it goes. */
136
- has(remotePeerId: string, now: number = Date.now()): boolean {
137
- this.prune(now);
138
- for (const grant of this.grants.values()) {
139
- if (grant.delegatePeerId === remotePeerId) {
140
- return true;
141
- }
142
- }
143
- return false;
144
- }
145
-
146
- /** Drop every grant whose expiry has passed. */
147
- private prune(now: number): void {
148
- for (const [key, grant] of this.grants) {
149
- if (grant.expiresAt <= now) {
150
- this.grants.delete(key);
151
- }
152
- }
153
- }
154
-
155
- /**
156
- * If the grants matching `filter` are at `cap`, evict the soonest-expiry one
157
- * among them to make room for the insert the caller is about to do.
158
- */
159
- private evictAtCap(cap: number, filter: (grant: DelegateGrant) => boolean): void {
160
- let count = 0;
161
- let victimKey: string | undefined;
162
- let victimExpiry = Number.POSITIVE_INFINITY;
163
- for (const [key, grant] of this.grants) {
164
- if (!filter(grant)) {
165
- continue;
166
- }
167
- count++;
168
- if (grant.expiresAt < victimExpiry) {
169
- victimExpiry = grant.expiresAt;
170
- victimKey = key;
171
- }
172
- }
173
- if (count >= cap && victimKey !== undefined) {
174
- const victim = this.grants.get(victimKey)!;
175
- this.grants.delete(victimKey);
176
- log('Delegate grant cap %d hit — evicted soonest-expiry grant %s → %s (strand %s)',
177
- cap, victim.announcerPeerId, victim.delegatePeerId, victim.strandId);
178
- }
179
- }
180
- }
181
-
182
- /** A circuit relay named by a multiaddr, as an announce target. */
183
- export interface CircuitRelayTarget {
184
- /** The relay's peerId — the `<relay>` in `…/p2p/<relay>/p2p-circuit…`. */
185
- relayPeerId: string;
186
- /**
187
- * The relay's DIRECT dial multiaddr (the prefix before `/p2p-circuit`),
188
- * usable as a dial fallback when no connection to the relay is open yet.
189
- */
190
- relayAddr: string;
191
- }
192
-
193
- /**
194
- * Extract the circuit relays named by a multiaddr list — for each
195
- * `…/p2p/<relay>/p2p-circuit…` entry, the relay's peerId and its direct dial
196
- * prefix. A bare `/p2p-circuit` (no relay named), a non-circuit addr, an
197
- * unparsable addr, and an unparsable relay peerId are all skipped. A trailing
198
- * `/p2p/<dst>` after the circuit component names the DESTINATION, never the
199
- * relay, and is ignored. Deduplicated by relay peerId (first addr wins).
200
- */
201
- export function extractCircuitRelayTargets(addrs: string[]): CircuitRelayTarget[] {
202
- const byRelay = new Map<string, CircuitRelayTarget>();
203
- for (const addr of addrs) {
204
- const target = circuitRelayTarget(addr);
205
- if (target && !byRelay.has(target.relayPeerId)) {
206
- byRelay.set(target.relayPeerId, target);
207
- }
208
- }
209
- return [...byRelay.values()];
210
- }
211
-
212
- /**
213
- * Of `relays`, the ones whose grant for `strandId` is due a re-announce: never
214
- * announced to, or last announced at least half the TTL ago. Half, so a failed
215
- * refresh has one more attempt before the grant lapses — a lapsed grant means
216
- * the relay denies the strand node's reservation re-dial.
217
- *
218
- * `announceAt` is the announcer-side "last announced at" map, keyed by
219
- * {@link peerStrandKey} on the peer announced TO.
220
- */
221
- export function dueRelayAnnounces(
222
- announceAt: ReadonlyMap<string, number>,
223
- relays: readonly CircuitRelayTarget[],
224
- strandId: string,
225
- now: number,
226
- ttlMs: number = DELEGATE_GRANT_TTL_MS
227
- ): CircuitRelayTarget[] {
228
- return relays.filter(
229
- (relay) => now - (announceAt.get(peerStrandKey(relay.relayPeerId, strandId)) ?? 0) >= ttlMs / 2
230
- );
231
- }
232
-
233
- /**
234
- * Drop `announceAt` entries whose strand is no longer running — a stopped
235
- * strand needs no refresh, and without this the map grows for the node's
236
- * lifetime. Mutates in place.
237
- */
238
- export function pruneStoppedStrandAnnounces(
239
- announceAt: Map<string, number>,
240
- runningStrandIds: ReadonlySet<string>
241
- ): void {
242
- for (const key of announceAt.keys()) {
243
- if (!runningStrandIds.has(strandIdOfKey(key))) {
244
- announceAt.delete(key);
245
- }
246
- }
247
- }
248
-
249
- /**
250
- * The circuit relay named by `addr`, throwing when `addr` is unparsable or names
251
- * no relay. The throwing form exists for CONFIG-facing callers (`relay-addrs.ts`),
252
- * where a typo must fail loudly rather than cost the node its reachability;
253
- * {@link extractCircuitRelayTargets} reads runtime-discovered addrs instead and
254
- * logs-and-skips.
255
- */
256
- export function circuitRelayTargetOrThrow(addr: string): CircuitRelayTarget {
257
- const target = parseCircuitRelayTarget(addr);
258
- if (!target) {
259
- throw new Error(`Multiaddr names no circuit relay (expected …/p2p/<relayPeerId>/p2p-circuit): ${addr}`);
260
- }
261
- return target;
262
- }
263
-
264
- /**
265
- * The circuit relay named by `addr`; null when `addr` is well-formed but simply
266
- * names no relay (a direct listen addr, a bare `/p2p-circuit`), and THROWS when
267
- * `addr` is malformed (unparsable multiaddr, garbage relay peerId). The two
268
- * callers want opposite things from the first case and the same thing from the
269
- * second, so the distinction lives here rather than in either of them.
270
- */
271
- function parseCircuitRelayTarget(addr: string): CircuitRelayTarget | null {
272
- const ma = multiaddr(addr);
273
- const components = ma.getComponents();
274
- const circuitIdx = components.findIndex((c) => c.name === 'p2p-circuit');
275
- if (circuitIdx < 1) {
276
- return null;
277
- }
278
- const relay = components[circuitIdx - 1];
279
- if (relay.name !== 'p2p' || !relay.value) {
280
- return null;
281
- }
282
- peerIdFromString(relay.value); // validate; throws on garbage
283
- return {
284
- relayPeerId: relay.value,
285
- relayAddr: ma.decapsulate('/p2p-circuit').toString()
286
- };
287
- }
288
-
289
- /**
290
- * One-addr body of {@link extractCircuitRelayTargets}; null when `addr` names no
291
- * relay. Only a MALFORMED addr logs — the addr lists this reads (a node's live
292
- * multiaddrs, its configured listen addrs) are mostly direct addrs, and calling
293
- * each of those "unparsable" is both wrong and per-announce noise.
294
- */
295
- function circuitRelayTarget(addr: string): CircuitRelayTarget | null {
296
- try {
297
- return parseCircuitRelayTarget(addr);
298
- } catch (err) {
299
- log('Skipping unparsable relay addr %s: %o', addr, err);
300
- return null;
301
- }
302
- }
1
+ /**
2
+ * Delegate-peer admission grants for a party control node that also runs the
3
+ * circuit-relay server.
4
+ *
5
+ * A strand node runs as its own libp2p instance with its own transport peerId,
6
+ * derived from the cadre identity key + strandId (`strand-transport-key.ts`).
7
+ * That derivation uses the member's PRIVATE seed by design, so no third party —
8
+ * including a co-cadre relay — can recompute it: a sibling's relay sees an
9
+ * unknown peerId it has no way to place as a member.
10
+ *
11
+ * The resolution (docs/strands.md → "Relay willingness"): a party control
12
+ * node running a relay is party-private infrastructure — it relays for its own
13
+ * party's nodes, including the extra transport identities its members' strand
14
+ * nodes run as. The mechanism is a **member-announced delegate grant**: before
15
+ * a member's control node starts a strand node, it tells its siblings (over the
16
+ * already-authenticated `/sereus/strand-addr/1.0.0` RPC) the derived peerId
17
+ * that strand node will use, and the receiver holds a short-lived, in-memory
18
+ * admission grant for exactly that peerId. The grant is consulted by the
19
+ * connection-level gate (`CadreNode.admitInboundControlConnection`) and by the
20
+ * relay-reservation admission (`CadreNode.admitControlRelayReservation`) — a
21
+ * granted delegate is admitted outright, never drawing on the small
22
+ * unauthorized-reservation budget that unplaced peers share
23
+ * (`membership-connection-gater.ts` → "The relay-reservation seam") and never
24
+ * racing its not-reserving connection deadline. The fail-closed per-stream gate
25
+ * (`authorizeInboundControlStream`) never honors a grant, so a delegate gets
26
+ * the connection and its reservation (all a circuit-relay `hop` needs) and
27
+ * nothing more.
28
+ *
29
+ * A grant is a delegation of trust to an already-trusted member: the receiver
30
+ * cannot verify that the announced peerId really is the member's strand node,
31
+ * so an authorized member can hand CONNECTION-level access to a peerId of its
32
+ * choosing for up to {@link DELEGATE_GRANT_TTL_MS}. The caps below bound how
33
+ * far a buggy or compromised member can stretch that.
34
+ *
35
+ * The receiver side is {@link DelegateAdmissionStore}. The announcer side keeps
36
+ * its own throttle state (a "last announced at" map that `CadreNode` owns) and
37
+ * decides from it, per reconcile pass, which relays are due a re-announce —
38
+ * {@link dueRelayAnnounces} and {@link pruneStoppedStrandAnnounces} are that
39
+ * decision, pure and testable, kept here beside the TTL they are derived from.
40
+ */
41
+
42
+ import debug from 'debug';
43
+ import { multiaddr } from '@multiformats/multiaddr';
44
+ import { peerIdFromString } from '@libp2p/peer-id';
45
+
46
+ const log = debug('sereus:cadre:delegate-admission');
47
+
48
+ /**
49
+ * How long one announced delegate grant stays valid without a re-announce.
50
+ * Announcers refresh at half this (`CadreNode`'s reconcile pass), so a live
51
+ * strand's grant never lapses while its control node can still reach the relay.
52
+ */
53
+ export const DELEGATE_GRANT_TTL_MS = 30 * 60 * 1000;
54
+
55
+ /** Cap on live grants per announcing member (soonest-expiry evicted first). */
56
+ export const MAX_DELEGATE_GRANTS_PER_MEMBER = 32;
57
+
58
+ /** Cap on live grants in total (soonest-expiry evicted first). */
59
+ export const MAX_DELEGATE_GRANTS = 256;
60
+
61
+ /** One recorded delegate admission grant. */
62
+ interface DelegateGrant {
63
+ /** The authorized member whose control node announced this delegate. */
64
+ announcerPeerId: string;
65
+ /** The strand the delegate serves — diagnostics + per-strand replace semantics. */
66
+ strandId: string;
67
+ /** The delegate transport peerId the grant admits. */
68
+ delegatePeerId: string;
69
+ /** Epoch ms after which the grant is inert. */
70
+ expiresAt: number;
71
+ }
72
+
73
+ /**
74
+ * Composite map key for the per-(peer, strand) state on both sides: the
75
+ * receiver's replace-per-(announcer, strand) grant, and the announcer's
76
+ * per-(target, strand) throttle timestamp.
77
+ */
78
+ export function peerStrandKey(peerId: string, strandId: string): string {
79
+ return `${peerId}\n${strandId}`;
80
+ }
81
+
82
+ /** The `strandId` half of a {@link peerStrandKey}. */
83
+ function strandIdOfKey(key: string): string {
84
+ return key.slice(key.indexOf('\n') + 1);
85
+ }
86
+
87
+ /**
88
+ * In-memory store of delegate admission grants, keyed by (announcer, strandId)
89
+ * so a re-announce REPLACES the previous delegate peerId rather than
90
+ * accumulating — a restarted strand cannot leak grants. Expired entries are
91
+ * pruned lazily on every read/write. Injectable `now` keeps expiry testable
92
+ * without fake timers.
93
+ */
94
+ export class DelegateAdmissionStore {
95
+ private readonly grants = new Map<string, DelegateGrant>();
96
+ private readonly ttlMs: number;
97
+
98
+ constructor(ttlMs: number = DELEGATE_GRANT_TTL_MS) {
99
+ this.ttlMs = ttlMs;
100
+ }
101
+
102
+ /** Number of live (unexpired at last prune) grants — test/diagnostic surface. */
103
+ get size(): number {
104
+ return this.grants.size;
105
+ }
106
+
107
+ /**
108
+ * Record (or refresh) a grant: `delegatePeerId` acts on behalf of
109
+ * `announcerPeerId` for `strandId`, valid for the store's TTL from `now`.
110
+ * Enforces {@link MAX_DELEGATE_GRANTS_PER_MEMBER} and
111
+ * {@link MAX_DELEGATE_GRANTS}, evicting the soonest-expiry grant first —
112
+ * biased against the stalest delegation, never against the fresh announce.
113
+ */
114
+ grant(announcerPeerId: string, strandId: string, delegatePeerId: string, now: number = Date.now()): void {
115
+ this.prune(now);
116
+ const key = peerStrandKey(announcerPeerId, strandId);
117
+ if (!this.grants.has(key)) {
118
+ this.evictAtCap(
119
+ MAX_DELEGATE_GRANTS_PER_MEMBER,
120
+ (g) => g.announcerPeerId === announcerPeerId
121
+ );
122
+ this.evictAtCap(MAX_DELEGATE_GRANTS, () => true);
123
+ }
124
+ this.grants.set(key, { announcerPeerId, strandId, delegatePeerId, expiresAt: now + this.ttlMs });
125
+ log('Delegate grant recorded: %s → %s (strand %s, %d live)', announcerPeerId, delegatePeerId, strandId, this.grants.size);
126
+ }
127
+
128
+ /**
129
+ * Drop every grant. Called when the owning node stops: grants are scoped to
130
+ * the session that recorded them, and outliving it would admit delegates
131
+ * announced against a node that no longer exists.
132
+ */
133
+ clear(): void {
134
+ this.grants.clear();
135
+ }
136
+
137
+ /** Is `remotePeerId` covered by a live grant? Prunes expired entries as it goes. */
138
+ has(remotePeerId: string, now: number = Date.now()): boolean {
139
+ this.prune(now);
140
+ for (const grant of this.grants.values()) {
141
+ if (grant.delegatePeerId === remotePeerId) {
142
+ return true;
143
+ }
144
+ }
145
+ return false;
146
+ }
147
+
148
+ /** Drop every grant whose expiry has passed. */
149
+ private prune(now: number): void {
150
+ for (const [key, grant] of this.grants) {
151
+ if (grant.expiresAt <= now) {
152
+ this.grants.delete(key);
153
+ }
154
+ }
155
+ }
156
+
157
+ /**
158
+ * If the grants matching `filter` are at `cap`, evict the soonest-expiry one
159
+ * among them to make room for the insert the caller is about to do.
160
+ */
161
+ private evictAtCap(cap: number, filter: (grant: DelegateGrant) => boolean): void {
162
+ let count = 0;
163
+ let victimKey: string | undefined;
164
+ let victimExpiry = Number.POSITIVE_INFINITY;
165
+ for (const [key, grant] of this.grants) {
166
+ if (!filter(grant)) {
167
+ continue;
168
+ }
169
+ count++;
170
+ if (grant.expiresAt < victimExpiry) {
171
+ victimExpiry = grant.expiresAt;
172
+ victimKey = key;
173
+ }
174
+ }
175
+ if (count >= cap && victimKey !== undefined) {
176
+ const victim = this.grants.get(victimKey)!;
177
+ this.grants.delete(victimKey);
178
+ log('Delegate grant cap %d hit — evicted soonest-expiry grant %s → %s (strand %s)',
179
+ cap, victim.announcerPeerId, victim.delegatePeerId, victim.strandId);
180
+ }
181
+ }
182
+ }
183
+
184
+ /** A circuit relay named by a multiaddr, as an announce target. */
185
+ export interface CircuitRelayTarget {
186
+ /** The relay's peerId — the `<relay>` in `…/p2p/<relay>/p2p-circuit…`. */
187
+ relayPeerId: string;
188
+ /**
189
+ * The relay's DIRECT dial multiaddr (the prefix before `/p2p-circuit`),
190
+ * usable as a dial fallback when no connection to the relay is open yet.
191
+ */
192
+ relayAddr: string;
193
+ }
194
+
195
+ /**
196
+ * Extract the circuit relays named by a multiaddr list — for each
197
+ * `…/p2p/<relay>/p2p-circuit…` entry, the relay's peerId and its direct dial
198
+ * prefix. A bare `/p2p-circuit` (no relay named), a non-circuit addr, an
199
+ * unparsable addr, and an unparsable relay peerId are all skipped. A trailing
200
+ * `/p2p/<dst>` after the circuit component names the DESTINATION, never the
201
+ * relay, and is ignored. Deduplicated by relay peerId (first addr wins).
202
+ */
203
+ export function extractCircuitRelayTargets(addrs: string[]): CircuitRelayTarget[] {
204
+ const byRelay = new Map<string, CircuitRelayTarget>();
205
+ for (const addr of addrs) {
206
+ const target = circuitRelayTarget(addr);
207
+ if (target && !byRelay.has(target.relayPeerId)) {
208
+ byRelay.set(target.relayPeerId, target);
209
+ }
210
+ }
211
+ return [...byRelay.values()];
212
+ }
213
+
214
+ /**
215
+ * Of `relays`, the ones whose grant for `strandId` is due a re-announce: never
216
+ * announced to, or last announced at least half the TTL ago. Half, so a failed
217
+ * refresh has one more attempt before the grant lapses — a lapsed grant means
218
+ * the relay denies the strand node's reservation re-dial.
219
+ *
220
+ * `announceAt` is the announcer-side "last announced at" map, keyed by
221
+ * {@link peerStrandKey} on the peer announced TO.
222
+ */
223
+ export function dueRelayAnnounces(
224
+ announceAt: ReadonlyMap<string, number>,
225
+ relays: readonly CircuitRelayTarget[],
226
+ strandId: string,
227
+ now: number,
228
+ ttlMs: number = DELEGATE_GRANT_TTL_MS
229
+ ): CircuitRelayTarget[] {
230
+ return relays.filter(
231
+ (relay) => now - (announceAt.get(peerStrandKey(relay.relayPeerId, strandId)) ?? 0) >= ttlMs / 2
232
+ );
233
+ }
234
+
235
+ /**
236
+ * Drop `announceAt` entries whose strand is no longer running — a stopped
237
+ * strand needs no refresh, and without this the map grows for the node's
238
+ * lifetime. Mutates in place.
239
+ */
240
+ export function pruneStoppedStrandAnnounces(
241
+ announceAt: Map<string, number>,
242
+ runningStrandIds: ReadonlySet<string>
243
+ ): void {
244
+ for (const key of announceAt.keys()) {
245
+ if (!runningStrandIds.has(strandIdOfKey(key))) {
246
+ announceAt.delete(key);
247
+ }
248
+ }
249
+ }
250
+
251
+ /**
252
+ * The circuit relay named by `addr`, throwing when `addr` is unparsable or names
253
+ * no relay. The throwing form exists for CONFIG-facing callers (`relay-addrs.ts`),
254
+ * where a typo must fail loudly rather than cost the node its reachability;
255
+ * {@link extractCircuitRelayTargets} reads runtime-discovered addrs instead and
256
+ * logs-and-skips.
257
+ */
258
+ export function circuitRelayTargetOrThrow(addr: string): CircuitRelayTarget {
259
+ const target = parseCircuitRelayTarget(addr);
260
+ if (!target) {
261
+ throw new Error(`Multiaddr names no circuit relay (expected …/p2p/<relayPeerId>/p2p-circuit): ${addr}`);
262
+ }
263
+ return target;
264
+ }
265
+
266
+ /**
267
+ * The circuit relay named by `addr`; null when `addr` is well-formed but simply
268
+ * names no relay (a direct listen addr, a bare `/p2p-circuit`), and THROWS when
269
+ * `addr` is malformed (unparsable multiaddr, garbage relay peerId). The two
270
+ * callers want opposite things from the first case and the same thing from the
271
+ * second, so the distinction lives here rather than in either of them.
272
+ */
273
+ function parseCircuitRelayTarget(addr: string): CircuitRelayTarget | null {
274
+ const ma = multiaddr(addr);
275
+ const components = ma.getComponents();
276
+ const circuitIdx = components.findIndex((c) => c.name === 'p2p-circuit');
277
+ if (circuitIdx < 1) {
278
+ return null;
279
+ }
280
+ const relay = components[circuitIdx - 1];
281
+ if (relay.name !== 'p2p' || !relay.value) {
282
+ return null;
283
+ }
284
+ peerIdFromString(relay.value); // validate; throws on garbage
285
+ return {
286
+ relayPeerId: relay.value,
287
+ relayAddr: ma.decapsulate('/p2p-circuit').toString()
288
+ };
289
+ }
290
+
291
+ /**
292
+ * One-addr body of {@link extractCircuitRelayTargets}; null when `addr` names no
293
+ * relay. Only a MALFORMED addr logs — the addr lists this reads (a node's live
294
+ * multiaddrs, its configured listen addrs) are mostly direct addrs, and calling
295
+ * each of those "unparsable" is both wrong and per-announce noise.
296
+ */
297
+ function circuitRelayTarget(addr: string): CircuitRelayTarget | null {
298
+ try {
299
+ return parseCircuitRelayTarget(addr);
300
+ } catch (err) {
301
+ log('Skipping unparsable relay addr %s: %o', addr, err);
302
+ return null;
303
+ }
304
+ }