@serfab/cadre-core 1.13.0 → 1.14.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 (120) hide show
  1. package/dist/cadre-invite-protocol.d.ts +348 -0
  2. package/dist/cadre-invite-protocol.js +605 -0
  3. package/dist/cadre-invite-protocol.js.map +1 -0
  4. package/dist/cadre-node.d.ts +523 -180
  5. package/dist/cadre-node.js +921 -293
  6. package/dist/cadre-node.js.map +1 -1
  7. package/dist/claim-proof.d.ts +45 -0
  8. package/dist/claim-proof.js +132 -0
  9. package/dist/claim-proof.js.map +1 -0
  10. package/dist/control-authorization.d.ts +80 -19
  11. package/dist/control-authorization.js +55 -13
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.js +1 -1
  14. package/dist/control-cohort.js.map +1 -1
  15. package/dist/control-database.d.ts +514 -97
  16. package/dist/control-database.js +1033 -195
  17. package/dist/control-database.js.map +1 -1
  18. package/dist/control-protocol-guard.d.ts +142 -0
  19. package/dist/control-protocol-guard.js +293 -0
  20. package/dist/control-protocol-guard.js.map +1 -0
  21. package/dist/control-schema.d.ts +1 -1
  22. package/dist/control-schema.js +801 -1067
  23. package/dist/control-schema.js.map +1 -1
  24. package/dist/control-stream.d.ts +4 -0
  25. package/dist/control-stream.js +22 -7
  26. package/dist/control-stream.js.map +1 -1
  27. package/dist/delegate-admission.d.ts +1 -1
  28. package/dist/delegate-admission.js +1 -1
  29. package/dist/device-token.d.ts +11 -9
  30. package/dist/device-token.js +14 -12
  31. package/dist/device-token.js.map +1 -1
  32. package/dist/ed25519-key.d.ts +15 -0
  33. package/dist/ed25519-key.js +28 -1
  34. package/dist/ed25519-key.js.map +1 -1
  35. package/dist/index.d.ts +14 -9
  36. package/dist/index.js +27 -9
  37. package/dist/index.js.map +1 -1
  38. package/dist/link-budget.d.ts +16 -29
  39. package/dist/link-budget.js +16 -31
  40. package/dist/link-budget.js.map +1 -1
  41. package/dist/membership-connection-gater.d.ts +190 -151
  42. package/dist/membership-connection-gater.js +235 -173
  43. package/dist/membership-connection-gater.js.map +1 -1
  44. package/dist/node-claim-payload.d.ts +19 -0
  45. package/dist/node-claim-payload.js +120 -0
  46. package/dist/node-claim-payload.js.map +1 -0
  47. package/dist/owner-anchor-sync.d.ts +22 -0
  48. package/dist/owner-anchor-sync.js +143 -0
  49. package/dist/owner-anchor-sync.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +113 -18
  51. package/dist/peer-authorization.js +225 -29
  52. package/dist/peer-authorization.js.map +1 -1
  53. package/dist/peer-dial.d.ts +19 -0
  54. package/dist/peer-dial.js +22 -1
  55. package/dist/peer-dial.js.map +1 -1
  56. package/dist/peer-join-backfill.d.ts +26 -2
  57. package/dist/peer-join-backfill.js +54 -12
  58. package/dist/peer-join-backfill.js.map +1 -1
  59. package/dist/peer-record.d.ts +13 -9
  60. package/dist/peer-record.js +16 -12
  61. package/dist/peer-record.js.map +1 -1
  62. package/dist/pending-join-runner.d.ts +66 -58
  63. package/dist/pending-join-runner.js +136 -145
  64. package/dist/pending-join-runner.js.map +1 -1
  65. package/dist/push-fanout.d.ts +8 -2
  66. package/dist/push-fanout.js +8 -2
  67. package/dist/push-fanout.js.map +1 -1
  68. package/dist/seed-bootstrap.d.ts +147 -122
  69. package/dist/seed-bootstrap.js +284 -269
  70. package/dist/seed-bootstrap.js.map +1 -1
  71. package/dist/seed-trust-policy.d.ts +98 -37
  72. package/dist/seed-trust-policy.js +188 -2
  73. package/dist/seed-trust-policy.js.map +1 -1
  74. package/dist/strand-addr-protocol.d.ts +24 -26
  75. package/dist/strand-addr-protocol.js +19 -26
  76. package/dist/strand-addr-protocol.js.map +1 -1
  77. package/dist/strand-formation-protocol.js +1 -1
  78. package/dist/strand-formation-protocol.js.map +1 -1
  79. package/dist/strand-revocation-enforcer.d.ts +11 -11
  80. package/dist/strand-revocation-enforcer.js +11 -11
  81. package/dist/strand-wake-protocol.d.ts +13 -16
  82. package/dist/strand-wake-protocol.js +13 -20
  83. package/dist/strand-wake-protocol.js.map +1 -1
  84. package/dist/trusted-owner-store.d.ts +35 -5
  85. package/dist/trusted-owner-store.js +50 -8
  86. package/dist/trusted-owner-store.js.map +1 -1
  87. package/dist/types.d.ts +302 -87
  88. package/dist/types.js.map +1 -1
  89. package/package.json +8 -7
  90. package/src/cadre-invite-protocol.ts +864 -0
  91. package/src/cadre-node.ts +9381 -8686
  92. package/src/claim-proof.ts +147 -0
  93. package/src/control-authorization.ts +203 -117
  94. package/src/control-cohort.ts +1 -1
  95. package/src/control-database.ts +1216 -218
  96. package/src/control-protocol-guard.ts +348 -0
  97. package/src/control-schema.ts +812 -1078
  98. package/src/control-stream.ts +26 -7
  99. package/src/delegate-admission.ts +1 -1
  100. package/src/device-token.ts +14 -10
  101. package/src/ed25519-key.ts +28 -1
  102. package/src/index.ts +84 -10
  103. package/src/link-budget.ts +16 -32
  104. package/src/membership-connection-gater.ts +637 -570
  105. package/src/node-claim-payload.ts +125 -0
  106. package/src/owner-anchor-sync.ts +171 -0
  107. package/src/peer-authorization.ts +258 -29
  108. package/src/peer-dial.ts +22 -1
  109. package/src/peer-join-backfill.ts +56 -11
  110. package/src/peer-record.ts +16 -11
  111. package/src/pending-join-runner.ts +729 -735
  112. package/src/push-fanout.ts +8 -2
  113. package/src/seed-bootstrap.ts +344 -321
  114. package/src/seed-trust-policy.ts +353 -140
  115. package/src/strand-addr-protocol.ts +26 -35
  116. package/src/strand-formation-protocol.ts +1 -1
  117. package/src/strand-revocation-enforcer.ts +11 -11
  118. package/src/strand-wake-protocol.ts +13 -23
  119. package/src/trusted-owner-store.ts +242 -171
  120. package/src/types.ts +2471 -2242
@@ -0,0 +1,864 @@
1
+ /**
2
+ * Cadre invitation redemption transport: `/sereus/cadre-invite/1.0.0`.
3
+ *
4
+ * A device holding a cadre invitation (an owner-signed `CadreInvite` row plus the private
5
+ * half of the invitation keypair, see {@link CadreInvitation}) dials ANY member machine the
6
+ * invitation names and proves possession; the member seats the row if it does not hold it
7
+ * yet, writes the device's `CadrePeer` row (and `OwnerKey` row, when the invitation grants
8
+ * ownership) through `ControlDatabase.redeemCadreInvite`, and answers with the party id,
9
+ * the row and dial hints. The owner that minted the invitation need not be online.
10
+ *
11
+ * Same shape as the seed and wake protocols: one length-prefixed JSON frame each way over
12
+ * the shared primitives in `control-stream.ts`. Stranger-facing by design — the device is
13
+ * not a member when it dials — so the connection gate admits a stranger while a live
14
+ * invitation exists (`membership-connection-gater.ts`), and the handler's own trust
15
+ * decision is the proof of possession: nothing touches the database for a caller that
16
+ * cannot prove it holds the invitation and is the identity it names.
17
+ *
18
+ * The seed protocol is left untouched so `SeedMessage` can grow independently.
19
+ */
20
+
21
+ import debug from 'debug';
22
+ import { multiaddr, type Multiaddr } from '@multiformats/multiaddr';
23
+ import type { Connection, Libp2p } from '@libp2p/interface';
24
+ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
25
+ import { sign } from '@optimystic/quereus-plugin-crypto';
26
+ import { type ControlStream, withDeadline, exchangeFrame, readStreamToEnd, replyAndClose } from './control-stream.js';
27
+ import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
28
+ import { relayedRequestBudgetMs } from './link-budget.js';
29
+ import {
30
+ cadreInviteRedeemMessage,
31
+ cadreInviteConsentMessage,
32
+ CadreInviteIssuerUnknownError,
33
+ InvitationExhaustedError,
34
+ type ControlDatabase
35
+ } from './control-database.js';
36
+ import { verifyCadreInviteRow, verifyCadreInviteRedemption } from './peer-authorization.js';
37
+ import { ed25519PublicKeyB64FromPeerId, requireEd25519PublicKeyB64 } from './ed25519-key.js';
38
+ import { trailingPeerId } from './peer-record.js';
39
+ import { nextMacrotask } from './peer-dial.js';
40
+ import { chainMessages } from './control-retry.js';
41
+ import { isRetriableControlWriteFailure } from './control-write-retry.js';
42
+ import type { CadreInviteRow, SeedPeer } from './types.js';
43
+
44
+ const log = debug('sereus:cadre:invite-proto');
45
+
46
+ /** Protocol id for cadre invitation redemption (parallel to `/sereus/seed/1.0.0`). */
47
+ export const CADRE_INVITE_PROTOCOL = '/sereus/cadre-invite/1.0.0';
48
+
49
+ /**
50
+ * Cap on either frame. A request is one signed row, two signatures and a few addresses;
51
+ * a reply adds a peer list of a cadre's size. Both fit in a few KB; 64 KiB is the
52
+ * defensive bound a stranger can make the handler buffer.
53
+ */
54
+ const MAX_CADRE_INVITE_MSG_SIZE = 64 * 1024;
55
+
56
+ /**
57
+ * Default time the member waits for the request frame before aborting the read (ms). The
58
+ * read only: a stranger opens the stream, so the bound is on a caller that opens one and
59
+ * never sends. Same figure as the seed handler's.
60
+ */
61
+ // eslint-disable-next-line no-restricted-syntax -- link-independent: a receiver cap on one frame on a stream the peer already opened; it bounds a peer that opens a stream and never sends, not the dial
62
+ const DEFAULT_REDEEM_READ_TIMEOUT_MS = 10_000;
63
+
64
+ /** Default cap on concurrent inbound redemptions; over it the handler answers `busy`. */
65
+ const DEFAULT_MAX_CONCURRENT_REDEMPTIONS = 100;
66
+
67
+ /** Longest string field accepted off the wire; a stamp is 342 base64url chars, a signature 86. */
68
+ const MAX_WIRE_FIELD_LENGTH = 1024;
69
+
70
+ /** Most addresses a request may carry for the device, and a reply per peer (`sanitizeAddrs`). */
71
+ const MAX_ADDRS = 16;
72
+
73
+ /** Most machines an invitation bundle may name; the issuer caps its own list far below this. */
74
+ const MAX_BUNDLE_MEMBERS = 64;
75
+
76
+ /** Most peers a reply may carry as dial hints. */
77
+ const MAX_REPLY_PEERS = 256;
78
+
79
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
80
+
81
+ // ── The invitation bundle ────────────────────────────────────────────────────
82
+
83
+ /**
84
+ * What an owner hands out (QR, paste, link) and a device redeems. An invitation is an
85
+ * ed25519 keypair: the row holds the public half, `invitePrivateKey` is the proof of
86
+ * possession, and whoever holds this bundle can redeem it — treat it as a bearer
87
+ * credential for the row's lifetime (an untargeted owner-granting one defaults to a
88
+ * 15-minute expiry for that reason).
89
+ *
90
+ * Carrying the signed row is what makes redemption work at a member that has not received
91
+ * the row by replication: the member seats it from the bundle under its stored issuer
92
+ * signature. The row's own signature covers every column, so a bundle whose row was
93
+ * altered cannot be seated anywhere.
94
+ */
95
+ export interface CadreInvitation {
96
+ v: 1;
97
+ /** The cadre the invitation joins; a device refuses one for another party. */
98
+ partyId: string;
99
+ /** The invitation's ed25519 seed, base64url: the proof of possession. */
100
+ invitePrivateKey: string;
101
+ /** The owner-signed row exactly as issued (`ControlDatabase.insertCadreInvite`). */
102
+ invite: CadreInviteRow;
103
+ /**
104
+ * The issuer's anchored owner keys. The redeeming device pins them before it dials
105
+ * (`CadreNode.trustOwnerKeys`) and checks the member's reply against them. Sourced from
106
+ * the issuer's node-local anchor only, never the replicated `OwnerKey` table, for the
107
+ * reason the seed invite gives: the device anchors whatever arrives here.
108
+ */
109
+ ownerKeys: string[];
110
+ /**
111
+ * Multiaddrs ending in `/p2p/<peerId>`: the issuer's own first, then up to
112
+ * `INVITATION_SIBLING_MACHINES` other members (`invitation-bootstrap.ts`). The device
113
+ * tries them in order.
114
+ */
115
+ members: string[];
116
+ }
117
+
118
+ /** Encode a bundle for out-of-band delivery: base64url over JSON, as seeds and open invitations are. */
119
+ export function encodeCadreInvitation(invitation: CadreInvitation): string {
120
+ return uint8ArrayToString(new TextEncoder().encode(JSON.stringify(invitation)), 'base64url');
121
+ }
122
+
123
+ /**
124
+ * Decode a bundle, refusing anything that is not a well-formed version-1
125
+ * {@link CadreInvitation}. Standalone so a client without a node (a settings screen that
126
+ * wants to show which cadre an invitation joins) can decode one.
127
+ *
128
+ * @throws on a string that is not base64url JSON, or decodes to another shape or version.
129
+ */
130
+ export function decodeCadreInvitation(encoded: string): CadreInvitation {
131
+ let parsed: unknown;
132
+ try {
133
+ parsed = JSON.parse(new TextDecoder().decode(uint8ArrayFromString(encoded.trim(), 'base64url')));
134
+ } catch (error) {
135
+ throw new Error('Cadre invitation does not decode as base64url JSON', { cause: error });
136
+ }
137
+ if (!isWellFormedCadreInvitation(parsed)) {
138
+ throw new Error('Cadre invitation is malformed or of an unsupported version');
139
+ }
140
+ return parsed;
141
+ }
142
+
143
+ function isWellFormedCadreInvitation(value: unknown): value is CadreInvitation {
144
+ if (typeof value !== 'object' || value === null) return false;
145
+ const { v, partyId, invitePrivateKey, invite, ownerKeys, members } = value as Record<string, unknown>;
146
+ return v === 1
147
+ && isBoundedString(partyId)
148
+ && isEd25519KeyB64(invitePrivateKey)
149
+ && isWellFormedCadreInviteRow(invite)
150
+ && Array.isArray(ownerKeys) && ownerKeys.length > 0 && ownerKeys.every((key) => isEd25519KeyB64(key))
151
+ && Array.isArray(members) && members.length <= MAX_BUNDLE_MEMBERS && members.every((addr) => isBoundedString(addr));
152
+ }
153
+
154
+ // ── Wire messages ────────────────────────────────────────────────────────────
155
+
156
+ /** Device → member: one frame, the whole redemption. */
157
+ export interface CadreInviteRedeemRequest {
158
+ v: 1;
159
+ /** The cadre the device believes it is joining; a machine serving another party refuses by name. */
160
+ partyId: string;
161
+ /** The owner-signed row from the bundle. */
162
+ invite: CadreInviteRow;
163
+ /** The device's ed25519 public key, base64url; must be the key behind the connecting peer id. */
164
+ peerKey: string;
165
+ /** The device's dialable addresses; empty for a phone. Stored on its `CadrePeer` row. */
166
+ multiaddrs: string[];
167
+ /** Single-use nonce the device minted (`generateStampId`); both signatures cover it. */
168
+ usageStampId: string;
169
+ /** By `invitePrivateKey` over the `'redeem'` digest. */
170
+ inviteSig: string;
171
+ /** By the device's identity key over the `'consent'` digest. */
172
+ peerSig: string;
173
+ }
174
+
175
+ /**
176
+ * Why a member refused a redemption. Retryability is {@link CADRE_INVITE_REJECTION_RETRYABLE}'s;
177
+ * a retryable code moves the device to the next address the bundle names.
178
+ */
179
+ export type CadreInviteRejectionCode =
180
+ /**
181
+ * The issuer's `OwnerKey` row is not on this member (not replicated yet), or the issuer was
182
+ * removed; the member cannot tell which, so the device tries the next address.
183
+ */
184
+ | 'issuer-unknown'
185
+ /**
186
+ * A signature does not verify, the peer key is not the connecting identity, the request or
187
+ * the row is malformed, or the invitation names another device.
188
+ */
189
+ | 'invite-invalid'
190
+ /** Expired, withdrawn, exhausted, or issued by a key that is no longer an owner here. */
191
+ | 'invite-spent'
192
+ /** This machine serves another cadre than the one the invitation names. */
193
+ | 'party-mismatch'
194
+ /** The member is at its cap on concurrent redemptions. */
195
+ | 'busy'
196
+ /** The write failed transiently (the write retry gave up); nothing was recorded. */
197
+ | 'conflict'
198
+ /**
199
+ * An unexpected member-side failure, or a request frame the member could not read (timed
200
+ * out, oversized, not JSON): nothing was proved either way, so the device tries the next
201
+ * address, as the formation responder's `internal` is read.
202
+ */
203
+ | 'internal';
204
+
205
+ /** Which refusals are worth repeating at the next address — the one place that says so. */
206
+ export const CADRE_INVITE_REJECTION_RETRYABLE: Readonly<Record<CadreInviteRejectionCode, boolean>> = {
207
+ 'issuer-unknown': true,
208
+ 'invite-invalid': false,
209
+ 'invite-spent': false,
210
+ 'party-mismatch': false,
211
+ 'busy': true,
212
+ 'conflict': true,
213
+ 'internal': true
214
+ };
215
+
216
+ /** Is `value` a code this build knows? Own keys only, so a peer's `'constructor'` does not pass. */
217
+ export function isCadreInviteRejectionCode(value: unknown): value is CadreInviteRejectionCode {
218
+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(CADRE_INVITE_REJECTION_RETRYABLE, value);
219
+ }
220
+
221
+ /** Member → device. */
222
+ export interface CadreInviteRedeemReply {
223
+ accepted: boolean;
224
+ /** Present iff `!accepted`. */
225
+ code?: CadreInviteRejectionCode;
226
+ /** Human-facing text; present iff `!accepted`. */
227
+ reason?: string;
228
+ /** The member's party id; present iff `accepted`. */
229
+ partyId?: string;
230
+ /** The invitation row as this member holds it; present iff `accepted`. */
231
+ invite?: CadreInviteRow;
232
+ /**
233
+ * Dial hints for the rest of the cadre, unsigned: the member's own projection of its
234
+ * `CadrePeer` rows (`ControlDatabase.querySeedPeers`). `isOwner` is a dial hint only, as
235
+ * the seed's NOTE says; the device derives trust from its anchor, never from this.
236
+ */
237
+ peers?: SeedPeer[];
238
+ }
239
+
240
+ /** An accepting reply, every optional field present. */
241
+ export interface CadreInviteAccepted extends CadreInviteRedeemReply {
242
+ accepted: true;
243
+ partyId: string;
244
+ invite: CadreInviteRow;
245
+ peers: SeedPeer[];
246
+ }
247
+
248
+ /** A refusal as the member sends it: a code, a reason, nothing else. */
249
+ interface CadreInviteRejection extends CadreInviteRedeemReply {
250
+ accepted: false;
251
+ code: CadreInviteRejectionCode;
252
+ reason: string;
253
+ }
254
+
255
+ /**
256
+ * A refusal as the device reads it: the code and reason verbatim off the wire, untyped, so
257
+ * {@link CadreInviteRejectedError} is the one place that classifies a code this build does
258
+ * not know (as `'unrecognized'`, retryable) rather than the decoder folding it into a code
259
+ * it does.
260
+ */
261
+ interface CadreInviteRefusalFrame {
262
+ accepted: false;
263
+ code: unknown;
264
+ reason: unknown;
265
+ }
266
+
267
+ function rejection(code: CadreInviteRejectionCode, reason: string): CadreInviteRejection {
268
+ return { accepted: false, code, reason };
269
+ }
270
+
271
+ // ── Errors the device sees ───────────────────────────────────────────────────
272
+
273
+ /**
274
+ * A member answered and refused. `code` is `'unrecognized'` when the frame carried none this
275
+ * build knows (the two machines may run different versions), and such a refusal counts as
276
+ * retryable: trying the next address on an unknown answer is safe, giving up is not.
277
+ */
278
+ export class CadreInviteRejectedError extends Error {
279
+ readonly code: CadreInviteRejectionCode | 'unrecognized';
280
+ readonly reason: string;
281
+ readonly retryable: boolean;
282
+
283
+ /** Both arguments come straight off the wire, so neither is trusted to have its declared type. */
284
+ constructor(code: unknown, reason: unknown) {
285
+ const text = typeof reason === 'string' ? reason : 'no reason provided';
286
+ super(`Cadre invitation refused: ${text}`);
287
+ this.name = 'CadreInviteRejectedError';
288
+ this.code = isCadreInviteRejectionCode(code) ? code : 'unrecognized';
289
+ this.reason = text;
290
+ this.retryable = this.code === 'unrecognized' || CADRE_INVITE_REJECTION_RETRYABLE[this.code];
291
+ }
292
+ }
293
+
294
+ /** What one address the bundle named came to. */
295
+ export interface CadreInviteAddressOutcome {
296
+ addr: string;
297
+ /** A dial or exchange failure, or a retryable {@link CadreInviteRejectedError}. */
298
+ error: Error;
299
+ }
300
+
301
+ /**
302
+ * Every address the bundle names was tried and none accepted: each failed to dial, answered
303
+ * malformed, or refused retryably. Always retryable; `outcomes` says what each address did.
304
+ */
305
+ export class CadreInviteUnreachableError extends Error {
306
+ readonly retryable = true;
307
+
308
+ constructor(readonly outcomes: readonly CadreInviteAddressOutcome[]) {
309
+ super(outcomes.length === 0
310
+ ? 'Cadre invitation names no dialable member'
311
+ : `Cadre invitation could not be redeemed at any of its ${outcomes.length} address(es): `
312
+ + outcomes.map((outcome) => `${outcome.addr}: ${outcome.error.message}`).join('; '));
313
+ this.name = 'CadreInviteUnreachableError';
314
+ }
315
+ }
316
+
317
+ /**
318
+ * A member accepted but its reply does not check out: another party id, another invitation
319
+ * key, or a row not signed by one of the pinned owner keys. Final: a machine that answers
320
+ * like this is not a member of the cadre the invitation names, and the row it wrote (if any)
321
+ * is in a database the device will never trust.
322
+ */
323
+ export class CadreInviteReplyInvalidError extends Error {
324
+ readonly retryable = false;
325
+
326
+ constructor(message: string) {
327
+ super(`Cadre invitation reply refused: ${message}`);
328
+ this.name = 'CadreInviteReplyInvalidError';
329
+ }
330
+ }
331
+
332
+ // ── Shape checks (both directions) ───────────────────────────────────────────
333
+
334
+ function isBoundedString(value: unknown, max = MAX_WIRE_FIELD_LENGTH): value is string {
335
+ return typeof value === 'string' && value.length > 0 && value.length <= max;
336
+ }
337
+
338
+ function isEd25519KeyB64(value: unknown): value is string {
339
+ if (!isBoundedString(value) || !BASE64URL.test(value)) return false;
340
+ try {
341
+ requireEd25519PublicKeyB64(value, 'key');
342
+ return true;
343
+ } catch {
344
+ return false;
345
+ }
346
+ }
347
+
348
+ /** Is `value` a {@link CadreInviteRow} with every column in its stored form and bounded? */
349
+ export function isWellFormedCadreInviteRow(value: unknown): value is CadreInviteRow {
350
+ if (typeof value !== 'object' || value === null) return false;
351
+ const row = value as Record<string, unknown>;
352
+ return isEd25519KeyB64(row.key)
353
+ && (row.peerId === null || isBoundedString(row.peerId))
354
+ && typeof row.grantsOwner === 'boolean'
355
+ && (row.expiresAt === null || isBoundedString(row.expiresAt))
356
+ && (row.totalUses === null || (Number.isInteger(row.totalUses) && (row.totalUses as number) >= 1))
357
+ && isBoundedString(row.stampId)
358
+ && isEd25519KeyB64(row.issuerKey)
359
+ && isBoundedString(row.issuerSig);
360
+ }
361
+
362
+ function isWellFormedRedeemRequest(value: unknown): value is CadreInviteRedeemRequest {
363
+ if (typeof value !== 'object' || value === null) return false;
364
+ const { v, partyId, invite, peerKey, multiaddrs, usageStampId, inviteSig, peerSig } = value as Record<string, unknown>;
365
+ return v === 1
366
+ && isBoundedString(partyId)
367
+ && isWellFormedCadreInviteRow(invite)
368
+ && isEd25519KeyB64(peerKey)
369
+ && Array.isArray(multiaddrs)
370
+ && isBoundedString(usageStampId)
371
+ && isBoundedString(inviteSig)
372
+ && isBoundedString(peerSig);
373
+ }
374
+
375
+ /**
376
+ * Keep only parsable, distinct multiaddr strings, capped at {@link MAX_ADDRS}, order kept.
377
+ * Applied on both sides: the member bounds what it stores on the device's row, the device
378
+ * bounds what it merges into its peer store. A malformed entry is skipped, not fatal.
379
+ */
380
+ export function sanitizeAddrs(addrs: unknown): string[] {
381
+ if (!Array.isArray(addrs)) return [];
382
+ const out: string[] = [];
383
+ const seen = new Set<string>();
384
+ for (const entry of addrs) {
385
+ if (out.length >= MAX_ADDRS) break;
386
+ if (!isBoundedString(entry) || seen.has(entry)) continue;
387
+ try {
388
+ multiaddr(entry);
389
+ } catch (error) {
390
+ log('addrs: skipping unparsable entry: %o', error);
391
+ continue;
392
+ }
393
+ seen.add(entry);
394
+ out.push(entry);
395
+ }
396
+ return out;
397
+ }
398
+
399
+ /** The reply's peer list, bounded and each entry's addresses sanitized; anything else dropped. */
400
+ function sanitizePeers(peers: unknown): SeedPeer[] {
401
+ if (!Array.isArray(peers)) return [];
402
+ const out: SeedPeer[] = [];
403
+ for (const entry of peers) {
404
+ if (out.length >= MAX_REPLY_PEERS) break;
405
+ if (typeof entry !== 'object' || entry === null) continue;
406
+ const { peerId, multiaddrs, isOwner, publicKey } = entry as Record<string, unknown>;
407
+ if (!isBoundedString(peerId)) continue;
408
+ out.push({
409
+ peerId,
410
+ multiaddrs: sanitizeAddrs(multiaddrs),
411
+ isOwner: isOwner === true,
412
+ ...(isEd25519KeyB64(publicKey) ? { publicKey } : {})
413
+ });
414
+ }
415
+ return out;
416
+ }
417
+
418
+ /**
419
+ * Read a reply frame into a typed reply, sanitizing the attacker-influenced fields of an
420
+ * acceptance. A refusal keeps only its code and reason, as sent. Throws on a frame that is
421
+ * neither.
422
+ */
423
+ function decodeReply(value: unknown): CadreInviteAccepted | CadreInviteRefusalFrame {
424
+ if (typeof value !== 'object' || value === null) {
425
+ throw new Error('Cadre invitation reply is not an object');
426
+ }
427
+ const reply = value as Record<string, unknown>;
428
+ if (reply.accepted !== true) {
429
+ return { accepted: false, code: reply.code, reason: reply.reason };
430
+ }
431
+ if (!isBoundedString(reply.partyId) || !isWellFormedCadreInviteRow(reply.invite)) {
432
+ throw new Error('Cadre invitation acceptance is missing its party id or a well-formed row');
433
+ }
434
+ return { accepted: true, partyId: reply.partyId, invite: reply.invite, peers: sanitizePeers(reply.peers) };
435
+ }
436
+
437
+ // ── Request construction (device side) ───────────────────────────────────────
438
+
439
+ /** What the device signs with: its identity keypair in the crypto plugin's base64url form. */
440
+ export interface RedeemSigner {
441
+ /** The device's ed25519 public key, base64url — the key behind its peer id. */
442
+ peerKey: string;
443
+ /** The device's ed25519 seed, base64url. */
444
+ peerPrivateKey: string;
445
+ }
446
+
447
+ /**
448
+ * Build and sign the request for `invitation`: the holder's `'redeem'` signature with the
449
+ * invitation's private key and the device's `'consent'` signature with its own, both over
450
+ * (invitation key, `usageStampId`, device key) for the invitation's party. The same bytes
451
+ * the schema verifies at the member (`cadreInviteRedeemMessage` / `cadreInviteConsentMessage`),
452
+ * whose own `party_id()` must therefore be the party the bundle names.
453
+ */
454
+ export function signRedeemRequest(
455
+ invitation: CadreInvitation,
456
+ signer: RedeemSigner,
457
+ usageStampId: string,
458
+ multiaddrs: string[]
459
+ ): CadreInviteRedeemRequest {
460
+ const fields = { inviteKey: invitation.invite.key, usageStampId, peerKey: signer.peerKey };
461
+ const signB64 = (message: Uint8Array, privateKey: string): string =>
462
+ sign(message, privateKey, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
463
+ return {
464
+ v: 1,
465
+ partyId: invitation.partyId,
466
+ invite: invitation.invite,
467
+ peerKey: signer.peerKey,
468
+ multiaddrs: sanitizeAddrs(multiaddrs),
469
+ usageStampId,
470
+ inviteSig: signB64(cadreInviteRedeemMessage(invitation.partyId, fields), invitation.invitePrivateKey),
471
+ peerSig: signB64(cadreInviteConsentMessage(invitation.partyId, fields), signer.peerPrivateKey)
472
+ };
473
+ }
474
+
475
+ /**
476
+ * The device's check on an acceptance: the same party, the same invitation key, and a row
477
+ * signed by an issuer the device pinned from the bundle. Throws
478
+ * {@link CadreInviteReplyInvalidError} naming the first failure.
479
+ *
480
+ * What it proves is bounded: the request already carried the owner-signed row, so a machine
481
+ * that is not a member can echo it. The check catches a reply for another party or
482
+ * invitation and a row the pinned owners never signed; whether the answering machine is a
483
+ * member is settled afterwards, when the device syncs the control database and judges every
484
+ * row against its anchor (`CadreNode.listAuthorizedMembers`).
485
+ */
486
+ export function verifyRedeemReply(
487
+ reply: CadreInviteAccepted,
488
+ invitation: CadreInvitation,
489
+ isTrustedIssuer: (ownerKey: string) => boolean
490
+ ): void {
491
+ if (reply.partyId !== invitation.partyId) {
492
+ throw new CadreInviteReplyInvalidError(`the member serves party ${reply.partyId}, the invitation names ${invitation.partyId}`);
493
+ }
494
+ if (reply.invite.key !== invitation.invite.key) {
495
+ throw new CadreInviteReplyInvalidError('the member answered for a different invitation');
496
+ }
497
+ if (!isTrustedIssuer(reply.invite.issuerKey)) {
498
+ throw new CadreInviteReplyInvalidError('the row the member holds is not issued by one of the invitation\'s owner keys');
499
+ }
500
+ if (!verifyCadreInviteRow(invitation.partyId, reply.invite)) {
501
+ throw new CadreInviteReplyInvalidError('the row the member holds is not signed by its issuer');
502
+ }
503
+ }
504
+
505
+ // ── Member side (handler) ────────────────────────────────────────────────────
506
+
507
+ /** The control-database surface a redemption needs; a `ControlDatabase` satisfies it. */
508
+ export type CadreInviteStore = Pick<ControlDatabase, 'seatCadreInvite' | 'isCadreInviteLive' | 'redeemCadreInvite' | 'querySeedPeers'>;
509
+
510
+ export interface CadreInviteHandlerOptions {
511
+ /** This member's party id; a request for another party is refused by name. */
512
+ partyId: string;
513
+ store: CadreInviteStore;
514
+ /**
515
+ * Push this member's control store to the device and resolve once the push has finished,
516
+ * called after the request verified and before the row is seated and the admission is
517
+ * written. Absent, the writes go ahead with the device holding nothing; see
518
+ * `catchUpDeviceIfLive` for why that tears on a member alone with the device.
519
+ */
520
+ catchUpDevice?: (peerId: string) => Promise<void>;
521
+ /** Time to wait for the request frame; default {@link DEFAULT_REDEEM_READ_TIMEOUT_MS}. */
522
+ redeemReadTimeoutMs?: number;
523
+ /** Cap on concurrent inbound redemptions; default {@link DEFAULT_MAX_CONCURRENT_REDEMPTIONS}. */
524
+ maxConcurrentRedemptions?: number;
525
+ }
526
+
527
+ /** Constraint names the schema refuses a redemption with, and the code each maps to. */
528
+ const REDEEM_CONSTRAINT_CODES: ReadonlyArray<[RegExp, CadreInviteRejectionCode, string]> = [
529
+ [/CHECK constraint failed: Authorized\b/, 'invite-spent', 'The invitation is expired, withdrawn, exhausted, or its issuer is no longer an owner'],
530
+ [/CHECK constraint failed: (InvitePossessed|PeerConsented|PeerExists|OwnerExists)\b/, 'invite-invalid', 'The redemption does not satisfy the invitation'],
531
+ [/CHECK constraint failed: NotRevoked\b/, 'invite-spent', 'The invitation was withdrawn'],
532
+ ];
533
+
534
+ /** Which named constraint, if any, refused the write — read off the error's cause chain. */
535
+ function constraintRejection(error: unknown): CadreInviteRejection | null {
536
+ if (!(error instanceof Error)) return null;
537
+ const messages = chainMessages(error);
538
+ for (const [pattern, code, reason] of REDEEM_CONSTRAINT_CODES) {
539
+ if (messages.some((message) => pattern.test(message))) return rejection(code, reason);
540
+ }
541
+ return null;
542
+ }
543
+
544
+ /** A write failure that is not a refusal: the retry gave up (`conflict`), or something else (`internal`). */
545
+ function writeFailureRejection(error: unknown): CadreInviteRejection {
546
+ // NOTE: a seat torn on a member alone with an uncaught-up device was measured answering
547
+ // `internal`, not `conflict` (cadre-invite-redeemed-at-a-member-without-the-row). Both are
548
+ // retryable, so the device is unaffected; if the two codes ever diverge in retryability,
549
+ // find which tear `isRetriableControlWriteFailure` does not recognise.
550
+ return isRetriableControlWriteFailure(error)
551
+ ? rejection('conflict', 'The redemption write failed transiently; nothing was recorded')
552
+ : rejection('internal', 'Internal redemption error');
553
+ }
554
+
555
+ /**
556
+ * Member side: registers the handler and drives each inbound stream through the checks in
557
+ * cost order — shape, connecting identity, both signatures, target device — so no database
558
+ * work happens for a stranger that cannot prove anything, then hands the device the control
559
+ * store (`catchUpDevice`), seats the row and redeems.
560
+ * Hardened as the seed handler is: a concurrency cap (over it, `busy`) and a read timeout.
561
+ *
562
+ * Registered only by a started `CadreNode`, after its control database is up, like the
563
+ * formation responder; nothing here is reachable on a node without one.
564
+ */
565
+ export class CadreInviteHandler {
566
+ private readonly options: CadreInviteHandlerOptions;
567
+ private readonly readTimeoutMs: number;
568
+ private readonly maxConcurrent: number;
569
+ private readonly registered = new Set<Libp2p>();
570
+ private active = 0;
571
+
572
+ constructor(options: CadreInviteHandlerOptions) {
573
+ this.options = options;
574
+ this.readTimeoutMs = options.redeemReadTimeoutMs ?? DEFAULT_REDEEM_READ_TIMEOUT_MS;
575
+ this.maxConcurrent = options.maxConcurrentRedemptions ?? DEFAULT_MAX_CONCURRENT_REDEMPTIONS;
576
+ }
577
+
578
+ /** In-flight inbound redemptions. */
579
+ get activeCount(): number {
580
+ return this.active;
581
+ }
582
+
583
+ /**
584
+ * Register on `node`; rejects when libp2p refuses the registration. `runOnLimitedConnection`
585
+ * because a phone redeems through a relay, whose connection libp2p marks limited; the
586
+ * exchange is two small frames, well inside any relay's cap.
587
+ */
588
+ async register(node: Libp2p, protocolId: string = CADRE_INVITE_PROTOCOL): Promise<void> {
589
+ if (this.registered.has(node)) return;
590
+ await node.handle(protocolId, async (rawStream: unknown, rawConnection: unknown) => {
591
+ await this.handleStream(rawStream as ControlStream, (rawConnection as Connection).remotePeer.toString());
592
+ }, { runOnLimitedConnection: true });
593
+ this.registered.add(node);
594
+ log('cadre invitation handler registered (%s)', protocolId);
595
+ }
596
+
597
+ async unregister(node: Libp2p, protocolId: string = CADRE_INVITE_PROTOCOL): Promise<void> {
598
+ if (!this.registered.has(node)) return;
599
+ await node.unhandle(protocolId);
600
+ this.registered.delete(node);
601
+ log('cadre invitation handler unregistered (%s)', protocolId);
602
+ }
603
+
604
+ /**
605
+ * One inbound redemption: read the frame, decide, reply, close. Public as the seam the
606
+ * protocol spec drives directly; `remotePeerId` is the connection's authenticated peer.
607
+ */
608
+ async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
609
+ if (this.active >= this.maxConcurrent) {
610
+ log('refusing redemption from %s: %d in flight at cap %d', remotePeerId, this.active, this.maxConcurrent);
611
+ await replyAndClose(stream, rejection('busy', 'Too many concurrent redemptions'), 'Cadre invite');
612
+ return;
613
+ }
614
+ this.active++;
615
+ try {
616
+ const reply = await this.decide(stream, remotePeerId);
617
+ log('redemption from %s: %s', remotePeerId, reply.accepted ? 'accepted' : `refused (${reply.code})`);
618
+ await replyAndClose(stream, reply, 'Cadre invite');
619
+ } catch (error) {
620
+ log('redemption from %s failed: %o', remotePeerId, error);
621
+ await replyAndClose(stream, rejection('internal', 'Internal redemption error'), 'Cadre invite');
622
+ } finally {
623
+ this.active--;
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Read the request frame to EOF, bounded and size-capped; JSON only, shape is `decide`'s.
629
+ * Throws on a frame that cannot be read, which {@link handleStream} answers `internal`:
630
+ * a read timeout or a cut frame proves nothing about the invitation, so the device must
631
+ * stay free to try the next address.
632
+ */
633
+ private async readRequest(stream: ControlStream): Promise<unknown> {
634
+ const data = await readStreamToEnd(stream, { maxBytes: MAX_CADRE_INVITE_MSG_SIZE, timeoutMs: this.readTimeoutMs, label: 'Cadre invite' });
635
+ return JSON.parse(new TextDecoder().decode(decodeLengthPrefixedFrame(data, MAX_CADRE_INVITE_MSG_SIZE)));
636
+ }
637
+
638
+ private async decide(stream: ControlStream, remotePeerId: string): Promise<CadreInviteRedeemReply> {
639
+ const request = await this.readRequest(stream);
640
+ const refused = this.checkRequest(request, remotePeerId);
641
+ if (refused) return refused;
642
+ return await this.seatAndRedeem(request as CadreInviteRedeemRequest, remotePeerId);
643
+ }
644
+
645
+ /**
646
+ * The checks that cost no database work, in order: shape, party, connecting identity (an
647
+ * ed25519 peer id is an identity multihash of the very key, and this is the only layer that
648
+ * can check the pair), both signatures, and a targeted invitation's device.
649
+ */
650
+ private checkRequest(request: unknown, remotePeerId: string): CadreInviteRejection | null {
651
+ if (!isWellFormedRedeemRequest(request)) {
652
+ return rejection('invite-invalid', 'Malformed redemption request');
653
+ }
654
+ if (request.partyId !== this.options.partyId) {
655
+ return rejection('party-mismatch', 'This machine serves another cadre');
656
+ }
657
+ if (ed25519PublicKeyB64FromPeerId(remotePeerId) !== request.peerKey) {
658
+ return rejection('invite-invalid', 'The peer key is not the connecting identity');
659
+ }
660
+ const fields = { inviteKey: request.invite.key, usageStampId: request.usageStampId, peerKey: request.peerKey };
661
+ if (!verifyCadreInviteRedemption(this.options.partyId, fields, request.inviteSig, request.peerSig)) {
662
+ return rejection('invite-invalid', 'The redemption signatures do not verify');
663
+ }
664
+ if (request.invite.peerId !== null && request.invite.peerId !== remotePeerId) {
665
+ return rejection('invite-invalid', 'The invitation names another device');
666
+ }
667
+ return null;
668
+ }
669
+
670
+ /**
671
+ * Hand the device this member's control store, seat the row from the bundle (its own
672
+ * transaction; a no-op when held), then redeem. The push comes first because the seat is
673
+ * already a write the device takes part in (see {@link catchUpDeviceIfLive}). An issuer this
674
+ * member does not know as an owner is the one retryable refusal left: the device tries the
675
+ * next address, which may hold the issuer's row.
676
+ */
677
+ private async seatAndRedeem(request: CadreInviteRedeemRequest, remotePeerId: string): Promise<CadreInviteRedeemReply> {
678
+ const { store } = this.options;
679
+ await this.catchUpDeviceIfLive(request.invite, remotePeerId);
680
+ try {
681
+ await store.seatCadreInvite(request.invite);
682
+ } catch (error) {
683
+ if (error instanceof CadreInviteIssuerUnknownError) {
684
+ return rejection('issuer-unknown', 'The invitation\'s issuer is not known as an owner here');
685
+ }
686
+ log('seating invitation %s from %s failed: %o', request.invite.key, remotePeerId, error);
687
+ return constraintRejection(error) ?? writeFailureRejection(error);
688
+ }
689
+ try {
690
+ const result = await store.redeemCadreInvite({
691
+ inviteKey: request.invite.key,
692
+ peerId: remotePeerId,
693
+ peerKey: request.peerKey,
694
+ multiaddrs: sanitizeAddrs(request.multiaddrs),
695
+ usageStampId: request.usageStampId,
696
+ inviteSig: request.inviteSig,
697
+ peerSig: request.peerSig
698
+ });
699
+ log('invitation %s redeemed by %s (alreadyMember=%s)', request.invite.key, remotePeerId, result.alreadyMember);
700
+ } catch (error) {
701
+ if (error instanceof InvitationExhaustedError) {
702
+ return rejection('invite-spent', 'The invitation has no uses left');
703
+ }
704
+ log('redeeming invitation %s for %s failed: %o', request.invite.key, remotePeerId, error);
705
+ return constraintRejection(error) ?? writeFailureRejection(error);
706
+ }
707
+ // The row as held: the seat inserted this copy verbatim, or found the same row (its key
708
+ // is the primary key and every column is under the issuer's signature).
709
+ return { accepted: true, partyId: this.options.partyId, invite: request.invite, peers: await this.peersBestEffort() };
710
+ }
711
+
712
+ /**
713
+ * Push this member's control store to the device before the first write of the exchange
714
+ * (the seat, when this member does not hold the row; otherwise the admission). The device
715
+ * joined this member's control write cohort when it connected, and a cohort node with no
716
+ * base revision of a block refuses a commit to it; a member alone with the device then has
717
+ * half its cohort refusing, and the write tears instead of committing. With the store in
718
+ * hand the device holds the write too.
719
+ *
720
+ * Only for an invitation still live here, judged on the row this member holds or, before
721
+ * the seat, on the bundle's copy once its issuer signature verifies
722
+ * (`ControlDatabase.isCadreInviteLive`): the holder of a withdrawn, expired or spent one,
723
+ * or of a forged copy naming a real owner, is refused without being sent anything. The
724
+ * retry of an admission already written can read as spent too and is sent nothing; it
725
+ * needs nothing, since the device is a member and the ordinary catch-up reaches it.
726
+ * Best-effort: a failed check or push is logged and the writes go ahead, then commit or are
727
+ * answered retryably.
728
+ */
729
+ private async catchUpDeviceIfLive(invite: CadreInviteRow, remotePeerId: string): Promise<void> {
730
+ const { catchUpDevice, store } = this.options;
731
+ if (!catchUpDevice) return;
732
+ try {
733
+ if (!await store.isCadreInviteLive(invite)) {
734
+ log('invitation %s is not live here; %s is not caught up before the write', invite.key, remotePeerId);
735
+ return;
736
+ }
737
+ // NOTE: accepted tradeoff — when a write then fails (the seat refused, the last use
738
+ // taken by a race, the row expiring between this check and the write), the device keeps
739
+ // a copy of a control store it was not admitted to. It holds a live owner-signed
740
+ // invitation and proved possession and consent, and a seed hands an un-enrolled machine
741
+ // the same information. Revisit if a control table ever carries data a non-member must not see.
742
+ await catchUpDevice(remotePeerId);
743
+ } catch (error) {
744
+ log('catching up %s before its admission failed (writing anyway): %o', remotePeerId, error);
745
+ }
746
+ }
747
+
748
+ /** Dial hints are an optimization; a failed read costs the device its hints, not its membership. */
749
+ private async peersBestEffort(): Promise<SeedPeer[]> {
750
+ try {
751
+ return await this.options.store.querySeedPeers();
752
+ } catch (error) {
753
+ log('peer projection for the reply failed (continuing without hints): %o', error);
754
+ return [];
755
+ }
756
+ }
757
+ }
758
+
759
+ // ── Device side (dialer) ─────────────────────────────────────────────────────
760
+
761
+ export interface RedeemAtMembersOptions {
762
+ /** The bundle: its `members` are dialed in order. */
763
+ invitation: CadreInvitation;
764
+ /** The signed request ({@link signRedeemRequest}); the same one goes to every address. */
765
+ request: CadreInviteRedeemRequest;
766
+ /** Is this owner key one the device pinned from the bundle? The reply check's input. */
767
+ isTrustedIssuer: (ownerKey: string) => boolean;
768
+ /**
769
+ * This machine's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
770
+ * the per-address deadline derives: a dial that may need a relay plus one request
771
+ * (`relayedRequestBudgetMs`, 28.5 s at the default declaration), as seed delivery's is.
772
+ */
773
+ linkRoundTripMs?: number;
774
+ /** Per-address deadline override; default derived from `linkRoundTripMs`. */
775
+ addressBudgetMs?: number;
776
+ protocolId?: string;
777
+ }
778
+
779
+ /** What a successful redemption yields the device. */
780
+ export interface CadreInviteRedemption {
781
+ reply: CadreInviteAccepted;
782
+ /** The answering member's peer id, from the address's trailing `/p2p/`; null when it named none. */
783
+ memberPeerId: string | null;
784
+ /** The address that answered. */
785
+ memberAddr: string;
786
+ }
787
+
788
+ /**
789
+ * Open one stream to `addr`, send the request, half-close, read the one reply frame.
790
+ * `signal` is the per-address deadline: it cancels the dial and resets a live stream.
791
+ */
792
+ async function exchangeRedemption(
793
+ node: Libp2p,
794
+ addr: Multiaddr,
795
+ request: CadreInviteRedeemRequest,
796
+ signal: AbortSignal,
797
+ budgetMs: number,
798
+ protocolId: string
799
+ ): Promise<CadreInviteAccepted | CadreInviteRefusalFrame> {
800
+ // `runOnLimitedConnection`: a member may be reachable only through a relay (see `register`).
801
+ const rawStream = await node.dialProtocol(addr, protocolId, { runOnLimitedConnection: true, signal });
802
+ return await exchangeFrame(
803
+ rawStream as unknown as ControlStream,
804
+ signal,
805
+ request,
806
+ async (stream) => {
807
+ const data = await readStreamToEnd(stream, { maxBytes: MAX_CADRE_INVITE_MSG_SIZE, timeoutMs: budgetMs, label: 'Cadre invite reply' });
808
+ return decodeReply(JSON.parse(new TextDecoder().decode(decodeLengthPrefixedFrame(data, MAX_CADRE_INVITE_MSG_SIZE))));
809
+ },
810
+ 'Cadre invitation redemption aborted by its deadline'
811
+ );
812
+ }
813
+
814
+ function asError(error: unknown): Error {
815
+ return error instanceof Error ? error : new Error(String(error));
816
+ }
817
+
818
+ /**
819
+ * Device side: try the bundle's addresses one at a time, each under its own deadline, and
820
+ * stop at the first acceptance or the first final refusal. A dial failure, a malformed
821
+ * reply or a retryable refusal moves to the next address.
822
+ *
823
+ * Every address gets the SAME request, with one `usageStampId`: `CadreInviteUsage` is keyed
824
+ * by it, so a member the device gave up on that was still committing cannot admit it twice,
825
+ * and a retry at the next member after a dropped reply is answered as already a member.
826
+ *
827
+ * @throws {CadreInviteRejectedError} on a final refusal (its `retryable` is false).
828
+ * @throws {CadreInviteReplyInvalidError} on an acceptance that fails {@link verifyRedeemReply}.
829
+ * @throws {CadreInviteUnreachableError} when every address was tried and none accepted.
830
+ */
831
+ export async function redeemAtMembers(node: Libp2p, options: RedeemAtMembersOptions): Promise<CadreInviteRedemption> {
832
+ const protocolId = options.protocolId ?? CADRE_INVITE_PROTOCOL;
833
+ const budgetMs = options.addressBudgetMs ?? relayedRequestBudgetMs(options.linkRoundTripMs);
834
+ const outcomes: CadreInviteAddressOutcome[] = [];
835
+ for (const addr of options.invitation.members) {
836
+ // Between attempts: libp2p's dial queue needs a macrotask to drop an aborted job.
837
+ if (outcomes.length > 0) await nextMacrotask();
838
+ let parsed: Multiaddr;
839
+ try {
840
+ parsed = multiaddr(addr);
841
+ } catch (error) {
842
+ outcomes.push({ addr, error: new Error('not a multiaddr', { cause: error }) });
843
+ continue;
844
+ }
845
+ try {
846
+ const reply = await withDeadline(budgetMs, `Cadre invitation redemption via ${addr}`,
847
+ (signal) => exchangeRedemption(node, parsed, options.request, signal, budgetMs, protocolId));
848
+ if (!reply.accepted) {
849
+ const refusal = new CadreInviteRejectedError(reply.code, reply.reason);
850
+ if (!refusal.retryable) throw refusal;
851
+ log('redemption via %s refused retryably (%s); trying the next address', addr, refusal.code);
852
+ outcomes.push({ addr, error: refusal });
853
+ continue;
854
+ }
855
+ verifyRedeemReply(reply, options.invitation, options.isTrustedIssuer);
856
+ return { reply, memberPeerId: trailingPeerId(parsed), memberAddr: addr };
857
+ } catch (error) {
858
+ if (error instanceof CadreInviteRejectedError || error instanceof CadreInviteReplyInvalidError) throw error;
859
+ log('redemption via %s failed before an answer (%s); trying the next address', addr, asError(error).message);
860
+ outcomes.push({ addr, error: asError(error) });
861
+ }
862
+ }
863
+ throw new CadreInviteUnreachableError(outcomes);
864
+ }