@serfab/cadre-core 0.10.0 → 0.11.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 (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. package/src/types.ts +1309 -1303
@@ -1,302 +1,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. 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. 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
+ }