@serfab/cadre-core 1.15.0 → 1.17.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.
- package/README.md +1 -1
- package/dist/bootstrap-peer-store-file.js +1 -1
- package/dist/bootstrap-peer-store.d.ts +1 -1
- package/dist/bootstrap-peer-store.js +4 -4
- package/dist/cadre-invite-protocol.d.ts +55 -138
- package/dist/cadre-invite-protocol.js +94 -449
- package/dist/cadre-invite-protocol.js.map +1 -1
- package/dist/cadre-join-request.d.ts +15 -2
- package/dist/cadre-join-request.js +22 -3
- package/dist/cadre-join-request.js.map +1 -1
- package/dist/cadre-node.d.ts +530 -247
- package/dist/cadre-node.js +1046 -525
- package/dist/cadre-node.js.map +1 -1
- package/dist/control-authorization.d.ts +36 -14
- package/dist/control-authorization.js +20 -3
- package/dist/control-authorization.js.map +1 -1
- package/dist/control-cohort.d.ts +22 -23
- package/dist/control-cohort.js +24 -24
- package/dist/control-cohort.js.map +1 -1
- package/dist/control-database.d.ts +416 -136
- package/dist/control-database.js +757 -378
- package/dist/control-database.js.map +1 -1
- package/dist/control-protocol-guard.d.ts +5 -4
- package/dist/control-protocol-guard.js +6 -3
- package/dist/control-protocol-guard.js.map +1 -1
- package/dist/control-schema-version.d.ts +80 -0
- package/dist/control-schema-version.js +203 -0
- package/dist/control-schema-version.js.map +1 -0
- package/dist/control-schema.d.ts +45 -5
- package/dist/control-schema.js +254 -70
- package/dist/control-schema.js.map +1 -1
- package/dist/control-write-retry.d.ts +5 -5
- package/dist/control-write-retry.js +10 -8
- package/dist/control-write-retry.js.map +1 -1
- package/dist/delegate-admission.d.ts +13 -0
- package/dist/delegate-admission.js +27 -0
- package/dist/delegate-admission.js.map +1 -1
- package/dist/ed25519-key.d.ts +10 -7
- package/dist/ed25519-key.js +23 -20
- package/dist/ed25519-key.js.map +1 -1
- package/dist/edge-node/config.d.ts +122 -0
- package/dist/edge-node/config.js +199 -0
- package/dist/edge-node/config.js.map +1 -0
- package/dist/edge-node/dissolve.d.ts +95 -0
- package/dist/edge-node/dissolve.js +184 -0
- package/dist/edge-node/dissolve.js.map +1 -0
- package/dist/edge-node/edge-join.d.ts +44 -0
- package/dist/edge-node/edge-join.js +227 -0
- package/dist/edge-node/edge-join.js.map +1 -0
- package/dist/edge-node/edge-node.d.ts +295 -0
- package/dist/edge-node/edge-node.js +704 -0
- package/dist/edge-node/edge-node.js.map +1 -0
- package/dist/edge-node/index.d.ts +18 -0
- package/dist/edge-node/index.js +18 -0
- package/dist/edge-node/index.js.map +1 -0
- package/dist/edge-node/join-credential.d.ts +11 -0
- package/dist/edge-node/join-credential.js +11 -0
- package/dist/edge-node/join-credential.js.map +1 -0
- package/dist/edge-node/lazy-raw-storage.d.ts +40 -0
- package/dist/edge-node/lazy-raw-storage.js +134 -0
- package/dist/edge-node/lazy-raw-storage.js.map +1 -0
- package/dist/edge-node/node-local.d.ts +60 -0
- package/dist/edge-node/node-local.js +58 -0
- package/dist/edge-node/node-local.js.map +1 -0
- package/dist/edge-node/options.d.ts +83 -0
- package/dist/edge-node/options.js +110 -0
- package/dist/edge-node/options.js.map +1 -0
- package/dist/edge-node/owner-grant.d.ts +41 -0
- package/dist/edge-node/owner-grant.js +38 -0
- package/dist/edge-node/owner-grant.js.map +1 -0
- package/dist/edge-node/platform.d.ts +140 -0
- package/dist/edge-node/platform.js +12 -0
- package/dist/edge-node/platform.js.map +1 -0
- package/dist/edge-node/strand-move.d.ts +115 -0
- package/dist/edge-node/strand-move.js +223 -0
- package/dist/edge-node/strand-move.js.map +1 -0
- package/dist/edge-node/strands.d.ts +28 -0
- package/dist/edge-node/strands.js +60 -0
- package/dist/edge-node/strands.js.map +1 -0
- package/dist/index.d.ts +16 -7
- package/dist/index.js +26 -7
- package/dist/index.js.map +1 -1
- package/dist/joined-strand-store.d.ts +3 -3
- package/dist/joined-strand-store.js +3 -3
- package/dist/joined-strand-store.js.map +1 -1
- package/dist/key-store.d.ts +9 -4
- package/dist/key-store.js +9 -4
- package/dist/key-store.js.map +1 -1
- package/dist/machine-removal.d.ts +19 -39
- package/dist/machine-removal.js +24 -98
- package/dist/machine-removal.js.map +1 -1
- package/dist/member-redemption.d.ts +250 -0
- package/dist/member-redemption.js +485 -0
- package/dist/member-redemption.js.map +1 -0
- package/dist/owner-anchor-sync.d.ts +4 -4
- package/dist/owner-anchor-sync.js +16 -15
- package/dist/owner-anchor-sync.js.map +1 -1
- package/dist/owner-grant-protocol.d.ts +247 -0
- package/dist/owner-grant-protocol.js +330 -0
- package/dist/owner-grant-protocol.js.map +1 -0
- package/dist/owner-key-export.d.ts +70 -0
- package/dist/owner-key-export.js +279 -0
- package/dist/owner-key-export.js.map +1 -0
- package/dist/owner-key-flows.d.ts +55 -0
- package/dist/owner-key-flows.js +60 -0
- package/dist/owner-key-flows.js.map +1 -0
- package/dist/owner-key-store.d.ts +31 -0
- package/dist/owner-key-store.js +81 -0
- package/dist/owner-key-store.js.map +1 -0
- package/dist/owner-keys.d.ts +78 -0
- package/dist/owner-keys.js +133 -0
- package/dist/owner-keys.js.map +1 -0
- package/dist/owner-signer.d.ts +54 -0
- package/dist/owner-signer.js +51 -0
- package/dist/owner-signer.js.map +1 -0
- package/dist/peer-authorization.d.ts +83 -18
- package/dist/peer-authorization.js +123 -53
- package/dist/peer-authorization.js.map +1 -1
- package/dist/provider/rent-node.js +1 -1
- package/dist/provider/rent-node.js.map +1 -1
- package/dist/seed-bootstrap.d.ts +131 -109
- package/dist/seed-bootstrap.js +260 -248
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/seed-trust-policy.js +4 -4
- package/dist/strand-addr-protocol.d.ts +4 -1
- package/dist/strand-addr-protocol.js +8 -2
- package/dist/strand-addr-protocol.js.map +1 -1
- package/dist/strand-cohort.d.ts +3 -0
- package/dist/strand-cohort.js.map +1 -1
- package/dist/strand-database.d.ts +1 -0
- package/dist/strand-database.js +3 -0
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-first-sync-gate.d.ts +4 -3
- package/dist/strand-first-sync-gate.js +4 -3
- package/dist/strand-first-sync-gate.js.map +1 -1
- package/dist/strand-instance-manager.d.ts +1 -1
- package/dist/strand-membership-writer.d.ts +13 -2
- package/dist/strand-membership-writer.js +52 -16
- package/dist/strand-membership-writer.js.map +1 -1
- package/dist/strand-move.d.ts +6 -5
- package/dist/strand-move.js +31 -30
- package/dist/strand-move.js.map +1 -1
- package/dist/strand-peer-redial.js +2 -3
- package/dist/strand-peer-redial.js.map +1 -1
- package/dist/types.d.ts +286 -103
- package/dist/types.js.map +1 -1
- package/package.json +16 -7
- package/src/bootstrap-peer-store-file.ts +44 -44
- package/src/bootstrap-peer-store.ts +214 -214
- package/src/cadre-invite-protocol.ts +131 -531
- package/src/cadre-join-request.ts +188 -167
- package/src/cadre-node.ts +1166 -541
- package/src/control-authorization.ts +47 -14
- package/src/control-cohort.ts +127 -128
- package/src/control-database.ts +940 -456
- package/src/control-protocol-guard.ts +7 -4
- package/src/control-schema-version.ts +251 -0
- package/src/control-schema.ts +265 -70
- package/src/control-write-retry.ts +569 -567
- package/src/delegate-admission.ts +37 -0
- package/src/ed25519-key.ts +174 -171
- package/src/edge-node/config.ts +277 -0
- package/src/edge-node/dissolve.ts +251 -0
- package/src/edge-node/edge-join.ts +319 -0
- package/src/edge-node/edge-node.ts +1045 -0
- package/src/edge-node/index.ts +59 -0
- package/src/edge-node/join-credential.ts +16 -0
- package/src/edge-node/lazy-raw-storage.ts +178 -0
- package/src/edge-node/node-local.ts +84 -0
- package/src/edge-node/options.ts +179 -0
- package/src/edge-node/owner-grant.ts +63 -0
- package/src/edge-node/platform.ts +151 -0
- package/src/edge-node/strand-move.ts +270 -0
- package/src/edge-node/strands.ts +72 -0
- package/src/index.ts +102 -5
- package/src/joined-strand-store.ts +4 -4
- package/src/key-store.ts +10 -4
- package/src/machine-removal.ts +26 -111
- package/src/member-redemption.ts +642 -0
- package/src/owner-anchor-sync.ts +19 -18
- package/src/owner-grant-protocol.ts +532 -0
- package/src/owner-key-export.ts +348 -0
- package/src/owner-key-flows.ts +109 -0
- package/src/owner-key-store.ts +85 -0
- package/src/owner-keys.ts +178 -0
- package/src/owner-signer.ts +94 -0
- package/src/peer-authorization.ts +558 -488
- package/src/provider/rent-node.ts +1 -1
- package/src/seed-bootstrap.ts +301 -312
- package/src/seed-trust-policy.ts +4 -4
- package/src/strand-addr-protocol.ts +547 -538
- package/src/strand-cohort.ts +4 -0
- package/src/strand-database.ts +3 -0
- package/src/strand-first-sync-gate.ts +4 -3
- package/src/strand-instance-manager.ts +1 -1
- package/src/strand-membership-writer.ts +61 -16
- package/src/strand-move.ts +45 -36
- package/src/strand-peer-redial.ts +2 -3
- package/src/types.ts +304 -103
|
@@ -8,12 +8,14 @@
|
|
|
8
8
|
* ownership) through `ControlDatabase.redeemCadreInvite`, and answers with the party id,
|
|
9
9
|
* the row and dial hints. The owner that minted the invitation need not be online.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
* the
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
11
|
+
* The exchange shape — one frame each way, the member's hardening and admission of the
|
|
12
|
+
* device, the device's address-by-address dialing in passes — is `member-redemption.ts`'s,
|
|
13
|
+
* shared with the owner-grant protocol; this module supplies the invitation's bundle, request,
|
|
14
|
+
* checks, writes and refusal codes. Stranger-facing by design — the device is not a member
|
|
15
|
+
* when it dials — so the connection gate admits a stranger while a live invitation exists
|
|
16
|
+
* (`membership-connection-gater.ts`), and the handler's own trust decision is the proof of
|
|
17
|
+
* possession: nothing touches the database for a caller that cannot prove it holds the
|
|
18
|
+
* invitation and is the identity it names.
|
|
17
19
|
*
|
|
18
20
|
* The seed protocol is left untouched so `SeedMessage` can grow independently.
|
|
19
21
|
*/
|
|
@@ -21,47 +23,27 @@ import debug from 'debug';
|
|
|
21
23
|
import { multiaddr } from '@multiformats/multiaddr';
|
|
22
24
|
import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
|
|
23
25
|
import { sign } from '@optimystic/quereus-plugin-crypto';
|
|
24
|
-
import {
|
|
25
|
-
import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
|
|
26
|
-
import { relayedRequestBudgetMs } from './link-budget.js';
|
|
27
|
-
import { cadreInviteRedeemMessage, cadreInviteConsentMessage, CadreInviteIssuerUnknownError, InvitationExhaustedError, parseNullableStoredDatetimeMs } from './control-database.js';
|
|
26
|
+
import { cadreInviteRedeemMessage, cadreInviteConsentMessage, CadreInviteIssuerUnknownError, InvitationExhaustedError } from './control-database.js';
|
|
28
27
|
import { verifyCadreInviteRow, verifyCadreInviteRedemption } from './peer-authorization.js';
|
|
29
|
-
import { ed25519PublicKeyB64FromPeerId
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import { isRetriableControlWriteFailure } from './control-write-retry.js';
|
|
33
|
-
import { CADRE_INVITATION_PREFIX, CADRE_JOIN_REQUEST_PREFIX } from './cadre-join-request.js';
|
|
28
|
+
import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
|
|
29
|
+
import { CADRE_INVITATION_PREFIX, CADRE_JOIN_REQUEST_PREFIX, OWNER_GRANT_PREFIX, OWNER_KEY_EXPORT_STEM } from './cadre-join-request.js';
|
|
30
|
+
import { MemberRedemptionHandler, constraintRefusal, dialRedemption, dialRedemptionInPasses, isBoundedString, isEd25519KeyB64, isNullableBoundedString, isNullableUseCap, rejection, writeFailureRefusal } from './member-redemption.js';
|
|
34
31
|
const log = debug('sereus:cadre:invite-proto');
|
|
35
32
|
/** Protocol id for cadre invitation redemption (parallel to `/sereus/seed/1.0.0`). */
|
|
36
33
|
export const CADRE_INVITE_PROTOCOL = '/sereus/cadre-invite/1.0.0';
|
|
37
|
-
/**
|
|
38
|
-
|
|
39
|
-
* a reply adds a peer list of a cadre's size. Both fit in a few KB; 64 KiB is the
|
|
40
|
-
* defensive bound a stranger can make the handler buffer.
|
|
41
|
-
*/
|
|
42
|
-
const MAX_CADRE_INVITE_MSG_SIZE = 64 * 1024;
|
|
43
|
-
/**
|
|
44
|
-
* Default time the member waits for the request frame before aborting the read (ms). The
|
|
45
|
-
* read only: a stranger opens the stream, so the bound is on a caller that opens one and
|
|
46
|
-
* never sends. Same figure as the seed handler's.
|
|
47
|
-
*/
|
|
48
|
-
// 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
|
|
49
|
-
const DEFAULT_REDEEM_READ_TIMEOUT_MS = 10000;
|
|
50
|
-
/** Default cap on concurrent inbound redemptions; over it the handler answers `busy`. */
|
|
51
|
-
const DEFAULT_MAX_CONCURRENT_REDEMPTIONS = 100;
|
|
52
|
-
/** Longest string field accepted off the wire; a stamp is 342 base64url chars, a signature 86. */
|
|
53
|
-
const MAX_WIRE_FIELD_LENGTH = 1024;
|
|
34
|
+
/** What the dialer calls the credential in log lines, deadline labels and error text. */
|
|
35
|
+
const LABEL = 'Cadre invitation';
|
|
54
36
|
/** Most addresses a request may carry for the device, and a reply per peer (`sanitizeAddrs`). */
|
|
55
37
|
const MAX_ADDRS = 16;
|
|
56
38
|
/** Most machines an invitation bundle may name; the issuer caps its own list far below this. */
|
|
57
39
|
const MAX_BUNDLE_MEMBERS = 64;
|
|
58
40
|
/** Most peers a reply may carry as dial hints. */
|
|
59
41
|
const MAX_REPLY_PEERS = 256;
|
|
60
|
-
const BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
61
42
|
/**
|
|
62
43
|
* Encode a bundle for out-of-band delivery: {@link CADRE_INVITATION_PREFIX}, then base64url
|
|
63
44
|
* over JSON. The prefix lets an app tell an invitation from a join request
|
|
64
|
-
* (`cadre-join-request.ts`)
|
|
45
|
+
* (`cadre-join-request.ts`) or an owner grant (`owner-grant-protocol.ts`) and name the mistake
|
|
46
|
+
* when one is pasted for the other.
|
|
65
47
|
*/
|
|
66
48
|
export function encodeCadreInvitation(invitation) {
|
|
67
49
|
return `${CADRE_INVITATION_PREFIX}${uint8ArrayToString(new TextEncoder().encode(JSON.stringify(invitation)), 'base64url')}`;
|
|
@@ -72,11 +54,17 @@ export function encodeCadreInvitation(invitation) {
|
|
|
72
54
|
* without a node (a settings screen that wants to show which cadre an invitation joins) can
|
|
73
55
|
* decode one.
|
|
74
56
|
*
|
|
75
|
-
* @throws on a join request, a string without the prefix or
|
|
76
|
-
* it, or one that decodes to another shape or version.
|
|
57
|
+
* @throws on an owner key, an owner grant or a join request, a string without the prefix or
|
|
58
|
+
* that is not base64url JSON after it, or one that decodes to another shape or version.
|
|
77
59
|
*/
|
|
78
60
|
export function decodeCadreInvitation(encoded) {
|
|
79
61
|
const trimmed = encoded.trim();
|
|
62
|
+
if (trimmed.startsWith(OWNER_KEY_EXPORT_STEM)) {
|
|
63
|
+
throw new Error('This is an owner key, not a cadre invitation; it is private, so import it only where the app asks for an owner key');
|
|
64
|
+
}
|
|
65
|
+
if (trimmed.startsWith(OWNER_GRANT_PREFIX)) {
|
|
66
|
+
throw new Error('This is an owner grant, not a cadre invitation; paste it where the app asks for an owner grant');
|
|
67
|
+
}
|
|
80
68
|
if (trimmed.startsWith(CADRE_JOIN_REQUEST_PREFIX)) {
|
|
81
69
|
throw new Error('This is a join request, not a cadre invitation; paste it into the app that manages your cadre');
|
|
82
70
|
}
|
|
@@ -120,9 +108,6 @@ export const CADRE_INVITE_REJECTION_RETRYABLE = {
|
|
|
120
108
|
export function isCadreInviteRejectionCode(value) {
|
|
121
109
|
return typeof value === 'string' && Object.prototype.hasOwnProperty.call(CADRE_INVITE_REJECTION_RETRYABLE, value);
|
|
122
110
|
}
|
|
123
|
-
function rejection(code, reason) {
|
|
124
|
-
return { accepted: false, code, reason };
|
|
125
|
-
}
|
|
126
111
|
// ── Errors the device sees ───────────────────────────────────────────────────
|
|
127
112
|
/**
|
|
128
113
|
* A member answered and refused. `code` is `'unrecognized'` when the frame carried none this
|
|
@@ -169,30 +154,15 @@ export class CadreInviteReplyInvalidError extends Error {
|
|
|
169
154
|
}
|
|
170
155
|
}
|
|
171
156
|
// ── Shape checks (both directions) ───────────────────────────────────────────
|
|
172
|
-
function isBoundedString(value, max = MAX_WIRE_FIELD_LENGTH) {
|
|
173
|
-
return typeof value === 'string' && value.length > 0 && value.length <= max;
|
|
174
|
-
}
|
|
175
|
-
function isEd25519KeyB64(value) {
|
|
176
|
-
if (!isBoundedString(value) || !BASE64URL.test(value))
|
|
177
|
-
return false;
|
|
178
|
-
try {
|
|
179
|
-
requireEd25519PublicKeyB64(value, 'key');
|
|
180
|
-
return true;
|
|
181
|
-
}
|
|
182
|
-
catch {
|
|
183
|
-
return false;
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
157
|
/** Is `value` a {@link CadreInviteRow} with every column in its stored form and bounded? */
|
|
187
158
|
export function isWellFormedCadreInviteRow(value) {
|
|
188
159
|
if (typeof value !== 'object' || value === null)
|
|
189
160
|
return false;
|
|
190
161
|
const row = value;
|
|
191
162
|
return isEd25519KeyB64(row.key)
|
|
192
|
-
&& (row.peerId
|
|
193
|
-
&&
|
|
194
|
-
&& (row.
|
|
195
|
-
&& (row.totalUses === null || (Number.isInteger(row.totalUses) && row.totalUses >= 1))
|
|
163
|
+
&& isNullableBoundedString(row.peerId)
|
|
164
|
+
&& isNullableBoundedString(row.expiresAt)
|
|
165
|
+
&& isNullableUseCap(row.totalUses)
|
|
196
166
|
&& isBoundedString(row.stampId)
|
|
197
167
|
&& isEd25519KeyB64(row.issuerKey)
|
|
198
168
|
&& isBoundedString(row.issuerSig);
|
|
@@ -247,31 +217,15 @@ function sanitizePeers(peers) {
|
|
|
247
217
|
break;
|
|
248
218
|
if (typeof entry !== 'object' || entry === null)
|
|
249
219
|
continue;
|
|
250
|
-
const { peerId, multiaddrs,
|
|
220
|
+
const { peerId, multiaddrs, preferred } = entry;
|
|
251
221
|
if (!isBoundedString(peerId))
|
|
252
222
|
continue;
|
|
253
|
-
out.push({
|
|
254
|
-
peerId,
|
|
255
|
-
multiaddrs: sanitizeAddrs(multiaddrs),
|
|
256
|
-
isOwner: isOwner === true,
|
|
257
|
-
...(isEd25519KeyB64(publicKey) ? { publicKey } : {})
|
|
258
|
-
});
|
|
223
|
+
out.push({ peerId, multiaddrs: sanitizeAddrs(multiaddrs), preferred: preferred === true });
|
|
259
224
|
}
|
|
260
225
|
return out;
|
|
261
226
|
}
|
|
262
|
-
/**
|
|
263
|
-
|
|
264
|
-
* acceptance. A refusal keeps only its code and reason, as sent. Throws on a frame that is
|
|
265
|
-
* neither.
|
|
266
|
-
*/
|
|
267
|
-
function decodeReply(value) {
|
|
268
|
-
if (typeof value !== 'object' || value === null) {
|
|
269
|
-
throw new Error('Cadre invitation reply is not an object');
|
|
270
|
-
}
|
|
271
|
-
const reply = value;
|
|
272
|
-
if (reply.accepted !== true) {
|
|
273
|
-
return { accepted: false, code: reply.code, reason: reply.reason };
|
|
274
|
-
}
|
|
227
|
+
/** An acceptance frame's fields, the attacker-influenced ones sanitized. Throws on a malformed one. */
|
|
228
|
+
function decodeAccepted(reply) {
|
|
275
229
|
if (!isBoundedString(reply.partyId) || !isWellFormedCadreInviteRow(reply.invite)) {
|
|
276
230
|
throw new Error('Cadre invitation acceptance is missing its party id or a well-formed row');
|
|
277
231
|
}
|
|
@@ -326,131 +280,38 @@ export function verifyRedeemReply(reply, invitation, isTrustedIssuer) {
|
|
|
326
280
|
/** Constraint names the schema refuses a redemption with, and the code each maps to. */
|
|
327
281
|
const REDEEM_CONSTRAINT_CODES = [
|
|
328
282
|
[/CHECK constraint failed: Authorized\b/, 'invite-spent', 'The invitation is expired, withdrawn, exhausted, or its issuer is no longer an owner'],
|
|
329
|
-
[/CHECK constraint failed: (InvitePossessed|PeerConsented|PeerExists
|
|
283
|
+
[/CHECK constraint failed: (InvitePossessed|PeerConsented|PeerExists)\b/, 'invite-invalid', 'The redemption does not satisfy the invitation'],
|
|
330
284
|
[/CHECK constraint failed: NotRevoked\b/, 'invite-spent', 'The invitation was withdrawn'],
|
|
331
285
|
];
|
|
332
|
-
/** Which named constraint, if any, refused the write — read off the error's cause chain. */
|
|
333
|
-
function constraintRejection(error) {
|
|
334
|
-
if (!(error instanceof Error))
|
|
335
|
-
return null;
|
|
336
|
-
const messages = chainMessages(error);
|
|
337
|
-
for (const [pattern, code, reason] of REDEEM_CONSTRAINT_CODES) {
|
|
338
|
-
if (messages.some((message) => pattern.test(message)))
|
|
339
|
-
return rejection(code, reason);
|
|
340
|
-
}
|
|
341
|
-
return null;
|
|
342
|
-
}
|
|
343
|
-
/** A write failure that is not a refusal: the retry gave up (`conflict`), or something else (`internal`). */
|
|
344
|
-
function writeFailureRejection(error) {
|
|
345
|
-
// NOTE: a seat torn on a member alone with an uncaught-up device was measured answering
|
|
346
|
-
// `internal`, not `conflict` (cadre-invite-redeemed-at-a-member-without-the-row). Both are
|
|
347
|
-
// retryable, so the device is unaffected; if the two codes ever diverge in retryability,
|
|
348
|
-
// find which tear `isRetriableControlWriteFailure` does not recognise.
|
|
349
|
-
return isRetriableControlWriteFailure(error)
|
|
350
|
-
? rejection('conflict', 'The redemption write failed transiently; nothing was recorded')
|
|
351
|
-
: rejection('internal', 'Internal redemption error');
|
|
352
|
-
}
|
|
353
286
|
/**
|
|
354
|
-
* Member side
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
*
|
|
359
|
-
*
|
|
360
|
-
* Registered only by a started `CadreNode`, after its control database is up, like the
|
|
361
|
-
* formation responder; nothing here is reachable on a node without one.
|
|
287
|
+
* Member side of the invitation protocol (`MemberRedemptionHandler` has the shape): after the
|
|
288
|
+
* request's shape, it checks the party, the connecting identity (an ed25519 peer id is an
|
|
289
|
+
* identity multihash of the very key, and this is the only layer that can check the pair),
|
|
290
|
+
* both signatures and a targeted invitation's device, then seats the row from the bundle and
|
|
291
|
+
* redeems. An issuer this member does not know as an owner is the one retryable refusal left:
|
|
292
|
+
* the device tries the next address, which may hold the issuer's row.
|
|
362
293
|
*/
|
|
363
|
-
export class CadreInviteHandler {
|
|
294
|
+
export class CadreInviteHandler extends MemberRedemptionHandler {
|
|
364
295
|
constructor(options) {
|
|
365
|
-
|
|
366
|
-
this.
|
|
367
|
-
this.
|
|
368
|
-
this.
|
|
369
|
-
this.
|
|
370
|
-
|
|
371
|
-
/** In-flight inbound redemptions. */
|
|
372
|
-
get activeCount() {
|
|
373
|
-
return this.active;
|
|
296
|
+
super('Cadre invite', CADRE_INVITE_PROTOCOL, options);
|
|
297
|
+
this.busyRefusal = rejection('busy', 'Too many concurrent redemptions');
|
|
298
|
+
this.internalRefusal = rejection('internal', 'Internal redemption error');
|
|
299
|
+
this.malformedRefusal = rejection('invite-invalid', 'Malformed redemption request');
|
|
300
|
+
this.peerId = options.peerId;
|
|
301
|
+
this.store = options.store;
|
|
374
302
|
}
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
* because a phone redeems through a relay, whose connection libp2p marks limited; the
|
|
378
|
-
* exchange is two small frames, well inside any relay's cap.
|
|
379
|
-
*/
|
|
380
|
-
async register(node, protocolId = CADRE_INVITE_PROTOCOL) {
|
|
381
|
-
if (this.registered.has(node))
|
|
382
|
-
return;
|
|
383
|
-
await node.handle(protocolId, async (rawStream, rawConnection) => {
|
|
384
|
-
await this.handleStream(rawStream, rawConnection.remotePeer.toString());
|
|
385
|
-
}, { runOnLimitedConnection: true });
|
|
386
|
-
this.registered.add(node);
|
|
387
|
-
log('cadre invitation handler registered (%s)', protocolId);
|
|
303
|
+
isWellFormedRequest(value) {
|
|
304
|
+
return isWellFormedRedeemRequest(value);
|
|
388
305
|
}
|
|
389
|
-
async unregister(node, protocolId = CADRE_INVITE_PROTOCOL) {
|
|
390
|
-
if (!this.registered.has(node))
|
|
391
|
-
return;
|
|
392
|
-
await node.unhandle(protocolId);
|
|
393
|
-
this.registered.delete(node);
|
|
394
|
-
log('cadre invitation handler unregistered (%s)', protocolId);
|
|
395
|
-
}
|
|
396
|
-
/**
|
|
397
|
-
* One inbound redemption: read the frame, decide, reply, close. Public as the seam the
|
|
398
|
-
* protocol spec drives directly; `remotePeerId` is the connection's authenticated peer.
|
|
399
|
-
*/
|
|
400
|
-
async handleStream(stream, remotePeerId) {
|
|
401
|
-
if (this.active >= this.maxConcurrent) {
|
|
402
|
-
log('refusing redemption from %s: %d in flight at cap %d', remotePeerId, this.active, this.maxConcurrent);
|
|
403
|
-
await replyAndClose(stream, rejection('busy', 'Too many concurrent redemptions'), 'Cadre invite');
|
|
404
|
-
return;
|
|
405
|
-
}
|
|
406
|
-
this.active++;
|
|
407
|
-
try {
|
|
408
|
-
const reply = await this.decide(stream, remotePeerId);
|
|
409
|
-
log('redemption from %s: %s', remotePeerId, reply.accepted ? 'accepted' : `refused (${reply.code})`);
|
|
410
|
-
await replyAndClose(stream, reply, 'Cadre invite');
|
|
411
|
-
}
|
|
412
|
-
catch (error) {
|
|
413
|
-
log('redemption from %s failed: %o', remotePeerId, error);
|
|
414
|
-
await replyAndClose(stream, rejection('internal', 'Internal redemption error'), 'Cadre invite');
|
|
415
|
-
}
|
|
416
|
-
finally {
|
|
417
|
-
this.active--;
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
/**
|
|
421
|
-
* Read the request frame to EOF, bounded and size-capped; JSON only, shape is `decide`'s.
|
|
422
|
-
* Throws on a frame that cannot be read, which {@link handleStream} answers `internal`:
|
|
423
|
-
* a read timeout or a cut frame proves nothing about the invitation, so the device must
|
|
424
|
-
* stay free to try the next address.
|
|
425
|
-
*/
|
|
426
|
-
async readRequest(stream) {
|
|
427
|
-
const data = await readStreamToEnd(stream, { maxBytes: MAX_CADRE_INVITE_MSG_SIZE, timeoutMs: this.readTimeoutMs, label: 'Cadre invite' });
|
|
428
|
-
return JSON.parse(new TextDecoder().decode(decodeLengthPrefixedFrame(data, MAX_CADRE_INVITE_MSG_SIZE)));
|
|
429
|
-
}
|
|
430
|
-
async decide(stream, remotePeerId) {
|
|
431
|
-
const request = await this.readRequest(stream);
|
|
432
|
-
const refused = this.checkRequest(request, remotePeerId);
|
|
433
|
-
if (refused)
|
|
434
|
-
return refused;
|
|
435
|
-
return await this.seatAndRedeem(request, remotePeerId);
|
|
436
|
-
}
|
|
437
|
-
/**
|
|
438
|
-
* The checks that cost no database work, in order: shape, party, connecting identity (an
|
|
439
|
-
* ed25519 peer id is an identity multihash of the very key, and this is the only layer that
|
|
440
|
-
* can check the pair), both signatures, and a targeted invitation's device.
|
|
441
|
-
*/
|
|
442
306
|
checkRequest(request, remotePeerId) {
|
|
443
|
-
if (
|
|
444
|
-
return rejection('invite-invalid', 'Malformed redemption request');
|
|
445
|
-
}
|
|
446
|
-
if (request.partyId !== this.options.partyId) {
|
|
307
|
+
if (request.partyId !== this.partyId) {
|
|
447
308
|
return rejection('party-mismatch', 'This machine serves another cadre');
|
|
448
309
|
}
|
|
449
310
|
if (ed25519PublicKeyB64FromPeerId(remotePeerId) !== request.peerKey) {
|
|
450
311
|
return rejection('invite-invalid', 'The peer key is not the connecting identity');
|
|
451
312
|
}
|
|
452
313
|
const fields = { inviteKey: request.invite.key, usageStampId: request.usageStampId, peerKey: request.peerKey };
|
|
453
|
-
if (!verifyCadreInviteRedemption(this.
|
|
314
|
+
if (!verifyCadreInviteRedemption(this.partyId, fields, request.inviteSig, request.peerSig)) {
|
|
454
315
|
return rejection('invite-invalid', 'The redemption signatures do not verify');
|
|
455
316
|
}
|
|
456
317
|
if (request.invite.peerId !== null && request.invite.peerId !== remotePeerId) {
|
|
@@ -458,37 +319,23 @@ export class CadreInviteHandler {
|
|
|
458
319
|
}
|
|
459
320
|
return null;
|
|
460
321
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
* seat the row from the bundle (its own transaction; a no-op when held), then redeem. The
|
|
464
|
-
* admission comes first because the seat is already a write the device takes part in. An
|
|
465
|
-
* issuer this member does not know as an owner is the one retryable refusal left: the device
|
|
466
|
-
* tries the next address, which may hold the issuer's row.
|
|
467
|
-
*/
|
|
468
|
-
async seatAndRedeem(request, remotePeerId) {
|
|
469
|
-
const release = await this.admitDeviceIfLive(request.invite, remotePeerId);
|
|
470
|
-
try {
|
|
471
|
-
return await this.seatAndRedeemAdmitted(request, remotePeerId);
|
|
472
|
-
}
|
|
473
|
-
finally {
|
|
474
|
-
release();
|
|
475
|
-
}
|
|
322
|
+
isLive(request) {
|
|
323
|
+
return this.store.isCadreInviteLive(request.invite);
|
|
476
324
|
}
|
|
477
|
-
/**
|
|
478
|
-
async
|
|
479
|
-
const { store } = this.options;
|
|
325
|
+
/** The two writes — the seat (its own transaction; a no-op when held) and the redemption — each answered by name when it fails. */
|
|
326
|
+
async redeemAdmitted(request, remotePeerId) {
|
|
480
327
|
try {
|
|
481
|
-
await store.seatCadreInvite(request.invite);
|
|
328
|
+
await this.store.seatCadreInvite(request.invite);
|
|
482
329
|
}
|
|
483
330
|
catch (error) {
|
|
484
331
|
if (error instanceof CadreInviteIssuerUnknownError) {
|
|
485
332
|
return rejection('issuer-unknown', 'The invitation\'s issuer is not known as an owner here');
|
|
486
333
|
}
|
|
487
334
|
log('seating invitation %s from %s failed: %o', request.invite.key, remotePeerId, error);
|
|
488
|
-
return
|
|
335
|
+
return constraintRefusal(error, REDEEM_CONSTRAINT_CODES) ?? writeFailureRefusal(error);
|
|
489
336
|
}
|
|
490
337
|
try {
|
|
491
|
-
const result = await store.redeemCadreInvite({
|
|
338
|
+
const result = await this.store.redeemCadreInvite({
|
|
492
339
|
inviteKey: request.invite.key,
|
|
493
340
|
peerId: remotePeerId,
|
|
494
341
|
peerKey: request.peerKey,
|
|
@@ -504,57 +351,16 @@ export class CadreInviteHandler {
|
|
|
504
351
|
return rejection('invite-spent', 'The invitation has no uses left');
|
|
505
352
|
}
|
|
506
353
|
log('redeeming invitation %s for %s failed: %o', request.invite.key, remotePeerId, error);
|
|
507
|
-
return
|
|
354
|
+
return constraintRefusal(error, REDEEM_CONSTRAINT_CODES) ?? writeFailureRefusal(error);
|
|
508
355
|
}
|
|
509
356
|
// The row as held: the seat inserted this copy verbatim, or found the same row (its key
|
|
510
357
|
// is the primary key and every column is under the issuer's signature).
|
|
511
|
-
return { accepted: true, partyId: this.
|
|
512
|
-
}
|
|
513
|
-
/**
|
|
514
|
-
* Admit the device to this member's control replication before the first write of the
|
|
515
|
-
* exchange (the seat, when this member does not hold the row; otherwise the admission), and
|
|
516
|
-
* resolve to the release that ends the admission. The device is not a member until the
|
|
517
|
-
* admission is written, so only this puts it in this member's control write cohort, and it
|
|
518
|
-
* must be there to hold the rows that admit it. It is pushed the control store first,
|
|
519
|
-
* because a cohort node with no base revision of a block refuses a commit to it; a member
|
|
520
|
-
* alone with the device would then have half its cohort refusing, and the write would tear
|
|
521
|
-
* instead of committing.
|
|
522
|
-
*
|
|
523
|
-
* Only for an invitation still live here, judged on the row this member holds or, before
|
|
524
|
-
* the seat, on the bundle's copy once its issuer signature verifies
|
|
525
|
-
* (`ControlDatabase.isCadreInviteLive`): the holder of a withdrawn, expired or spent one,
|
|
526
|
-
* or of a forged copy naming a real owner, is refused without being sent anything. The
|
|
527
|
-
* retry of an admission already written can read as spent too and is sent nothing; it
|
|
528
|
-
* needs nothing, since the device is a member and the ordinary catch-up reaches it.
|
|
529
|
-
* Best-effort: a failed check or push is logged and the writes go ahead without the device
|
|
530
|
-
* admitted, then commit or are answered retryably.
|
|
531
|
-
*/
|
|
532
|
-
async admitDeviceIfLive(invite, remotePeerId) {
|
|
533
|
-
const { admitDevice, store } = this.options;
|
|
534
|
-
const notAdmitted = () => undefined;
|
|
535
|
-
if (!admitDevice)
|
|
536
|
-
return notAdmitted;
|
|
537
|
-
try {
|
|
538
|
-
if (!await store.isCadreInviteLive(invite)) {
|
|
539
|
-
log('invitation %s is not live here; %s is not admitted before the write', invite.key, remotePeerId);
|
|
540
|
-
return notAdmitted;
|
|
541
|
-
}
|
|
542
|
-
// NOTE: accepted tradeoff — when a write then fails (the seat refused, the last use
|
|
543
|
-
// taken by a race, the row expiring between this check and the write), the device keeps
|
|
544
|
-
// a copy of a control store it was not admitted to. It holds a live owner-signed
|
|
545
|
-
// invitation and proved possession and consent, and a seed hands an un-enrolled machine
|
|
546
|
-
// the same information. Revisit if a control table ever carries data a non-member must not see.
|
|
547
|
-
return await admitDevice(remotePeerId);
|
|
548
|
-
}
|
|
549
|
-
catch (error) {
|
|
550
|
-
log('admitting %s before its admission write failed (writing anyway): %o', remotePeerId, error);
|
|
551
|
-
return notAdmitted;
|
|
552
|
-
}
|
|
358
|
+
return { accepted: true, partyId: this.partyId, invite: request.invite, peers: await this.peersBestEffort() };
|
|
553
359
|
}
|
|
554
360
|
/** Dial hints are an optimization; a failed read costs the device its hints, not its membership. */
|
|
555
361
|
async peersBestEffort() {
|
|
556
362
|
try {
|
|
557
|
-
return await this.
|
|
363
|
+
return await this.store.querySeedPeers(this.peerId);
|
|
558
364
|
}
|
|
559
365
|
catch (error) {
|
|
560
366
|
log('peer projection for the reply failed (continuing without hints): %o', error);
|
|
@@ -562,213 +368,52 @@ export class CadreInviteHandler {
|
|
|
562
368
|
}
|
|
563
369
|
}
|
|
564
370
|
}
|
|
565
|
-
/**
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
function asError(error) {
|
|
582
|
-
if (error instanceof Error)
|
|
583
|
-
return error;
|
|
584
|
-
// A WebSocket transport rejects a refused dial with an `ErrorEvent`, whose text is its `message`.
|
|
585
|
-
const message = error?.message;
|
|
586
|
-
return new Error(typeof message === 'string' && message.length > 0 ? message : String(error), { cause: error });
|
|
587
|
-
}
|
|
588
|
-
/**
|
|
589
|
-
* Run `op` with a signal that aborts when either `deadline` or the caller's `signal` does.
|
|
590
|
-
* Relayed by hand rather than with `AbortSignal.any`, which the phone runtimes lack.
|
|
591
|
-
*/
|
|
592
|
-
async function underDeadlineAndCaller(deadline, caller, op) {
|
|
593
|
-
if (!caller)
|
|
594
|
-
return await op(deadline);
|
|
595
|
-
const either = new AbortController();
|
|
596
|
-
const abort = () => either.abort();
|
|
597
|
-
deadline.addEventListener('abort', abort, { once: true });
|
|
598
|
-
caller.addEventListener('abort', abort, { once: true });
|
|
599
|
-
// An abort between the caller's last check and the listener above fired no event.
|
|
600
|
-
if (caller.aborted)
|
|
601
|
-
abort();
|
|
602
|
-
try {
|
|
603
|
-
return await op(either.signal);
|
|
604
|
-
}
|
|
605
|
-
finally {
|
|
606
|
-
deadline.removeEventListener('abort', abort);
|
|
607
|
-
caller.removeEventListener('abort', abort);
|
|
608
|
-
}
|
|
371
|
+
/** The invitation's half of the shared dial loop: its label, protocol, bundle, codec, checks and errors. */
|
|
372
|
+
function inviteRedemption(options) {
|
|
373
|
+
return {
|
|
374
|
+
label: LABEL,
|
|
375
|
+
protocolId: options.protocolId ?? CADRE_INVITE_PROTOCOL,
|
|
376
|
+
members: options.invitation.members,
|
|
377
|
+
request: options.request,
|
|
378
|
+
decodeAccepted,
|
|
379
|
+
refusal: (code, reason) => new CadreInviteRejectedError(code, reason),
|
|
380
|
+
verifyAccepted: (reply) => verifyRedeemReply(reply, options.invitation, options.isTrustedIssuer),
|
|
381
|
+
unreachable: (outcomes) => new CadreInviteUnreachableError(outcomes),
|
|
382
|
+
...(options.linkRoundTripMs !== undefined ? { linkRoundTripMs: options.linkRoundTripMs } : {}),
|
|
383
|
+
...(options.addressBudgetMs !== undefined ? { addressBudgetMs: options.addressBudgetMs } : {}),
|
|
384
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
385
|
+
};
|
|
609
386
|
}
|
|
610
387
|
/**
|
|
611
388
|
* Device side: try the bundle's addresses one at a time, each under its own deadline, and
|
|
612
|
-
* stop at the first acceptance or the first final refusal
|
|
613
|
-
*
|
|
614
|
-
*
|
|
615
|
-
*
|
|
616
|
-
*
|
|
617
|
-
* and a retry at the next member after a dropped reply is answered as already a member.
|
|
389
|
+
* stop at the first acceptance or the first final refusal (`dialRedemption` in
|
|
390
|
+
* `member-redemption.ts`). Every address gets the SAME request, with one `usageStampId`:
|
|
391
|
+
* `CadreInviteUsage` is keyed by it, so a member the device gave up on that was still
|
|
392
|
+
* committing cannot admit it twice, and a retry at the next member after a dropped reply is
|
|
393
|
+
* answered as already a member.
|
|
618
394
|
*
|
|
619
395
|
* @throws {CadreInviteRejectedError} on a final refusal (its `retryable` is false).
|
|
620
396
|
* @throws {CadreInviteReplyInvalidError} on an acceptance that fails {@link verifyRedeemReply}.
|
|
621
397
|
* @throws {CadreInviteUnreachableError} when every address was tried and none accepted.
|
|
622
398
|
* @throws the reason of `options.signal` once it aborts.
|
|
623
399
|
*/
|
|
624
|
-
export
|
|
625
|
-
|
|
626
|
-
const budgetMs = options.addressBudgetMs ?? relayedRequestBudgetMs(options.linkRoundTripMs);
|
|
627
|
-
const outcomes = [];
|
|
628
|
-
for (const addr of options.invitation.members) {
|
|
629
|
-
options.signal?.throwIfAborted();
|
|
630
|
-
// Between attempts: a relayed address's relay leg goes through libp2p's dial queue, which
|
|
631
|
-
// needs a macrotask to drop an aborted job (see `tryAddrsInTurn`).
|
|
632
|
-
if (outcomes.length > 0)
|
|
633
|
-
await nextMacrotask();
|
|
634
|
-
let parsed;
|
|
635
|
-
try {
|
|
636
|
-
parsed = multiaddr(addr);
|
|
637
|
-
}
|
|
638
|
-
catch (error) {
|
|
639
|
-
outcomes.push({ addr, error: new Error('not a multiaddr', { cause: error }) });
|
|
640
|
-
continue;
|
|
641
|
-
}
|
|
642
|
-
try {
|
|
643
|
-
const reply = await withDeadline(budgetMs, `Cadre invitation redemption via ${addr}`, (deadline) => underDeadlineAndCaller(deadline, options.signal, (signal) => exchangeRedemption(node, parsed, options.request, signal, budgetMs, protocolId)));
|
|
644
|
-
if (!reply.accepted) {
|
|
645
|
-
const refusal = new CadreInviteRejectedError(reply.code, reply.reason);
|
|
646
|
-
if (!refusal.retryable)
|
|
647
|
-
throw refusal;
|
|
648
|
-
log('redemption via %s refused retryably (%s); trying the next address', addr, refusal.code);
|
|
649
|
-
outcomes.push({ addr, error: refusal });
|
|
650
|
-
continue;
|
|
651
|
-
}
|
|
652
|
-
verifyRedeemReply(reply, options.invitation, options.isTrustedIssuer);
|
|
653
|
-
return { reply, memberPeerId: trailingPeerId(parsed), memberAddr: addr };
|
|
654
|
-
}
|
|
655
|
-
catch (error) {
|
|
656
|
-
if (error instanceof CadreInviteRejectedError || error instanceof CadreInviteReplyInvalidError)
|
|
657
|
-
throw error;
|
|
658
|
-
// The caller's abort cut this attempt short; its reason, not the cut, is the answer.
|
|
659
|
-
options.signal?.throwIfAborted();
|
|
660
|
-
log('redemption via %s failed before an answer (%s); trying the next address', addr, asError(error).message);
|
|
661
|
-
outcomes.push({ addr, error: asError(error) });
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
throw new CadreInviteUnreachableError(outcomes);
|
|
665
|
-
}
|
|
666
|
-
/** Pause after the first pass in which no member accepted; doubled after each further one. */
|
|
667
|
-
const REDEEM_PASS_FIRST_PAUSE_MS = 5000;
|
|
668
|
-
/** Longest pause between passes. */
|
|
669
|
-
const REDEEM_PASS_MAX_PAUSE_MS = 60000;
|
|
670
|
-
/**
|
|
671
|
-
* Device side, in passes: one {@link redeemAtMembers} pass over the bundle's addresses, or,
|
|
672
|
-
* with `waitForMember`, as many as it takes, pausing between them (5 s after the first,
|
|
673
|
-
* doubling to 60 s, never past the invitation's expiry). Every pass sends the same signed
|
|
674
|
-
* request, so a member that admitted the device on a pass whose reply was lost answers a later
|
|
675
|
-
* pass as already a member, with no second usage row.
|
|
676
|
-
*
|
|
677
|
-
* A wait ends at the first acceptance, at a final refusal or an invalid reply (thrown as
|
|
678
|
-
* {@link redeemAtMembers} throws them), when the invitation expires by this device's clock
|
|
679
|
-
* (thrown as the `invite-spent` refusal a member would give), when `signal` aborts (its reason
|
|
680
|
-
* thrown), and when `node` stops. A bundle that names no address has nothing to wait for and
|
|
681
|
-
* throws at once.
|
|
682
|
-
*/
|
|
683
|
-
export async function redeemInPasses(node, options) {
|
|
684
|
-
for (let pass = 1;; pass++) {
|
|
685
|
-
if (options.waitForMember) {
|
|
686
|
-
// One pass leaves expiry to the member, whose clock decides; a wait has nothing else to end it.
|
|
687
|
-
refuseIfExpired(options.invitation.invite);
|
|
688
|
-
refuseIfStopped(node);
|
|
689
|
-
}
|
|
690
|
-
reportProgress(options.onProgress, { state: 'redeeming', pass });
|
|
691
|
-
try {
|
|
692
|
-
return await redeemAtMembers(node, options);
|
|
693
|
-
}
|
|
694
|
-
catch (error) {
|
|
695
|
-
if (!options.waitForMember || !(error instanceof CadreInviteUnreachableError) || error.outcomes.length === 0)
|
|
696
|
-
throw error;
|
|
697
|
-
const pauseMs = pauseAfterPass(pass, options.invitation.invite);
|
|
698
|
-
reportProgress(options.onProgress, {
|
|
699
|
-
state: 'waiting', pass, retryAtMs: Date.now() + pauseMs, reason: waitReason(error.outcomes), outcomes: error.outcomes
|
|
700
|
-
});
|
|
701
|
-
log('redemption pass %d found no member ready; the next pass in %d ms', pass, pauseMs);
|
|
702
|
-
await pause(pauseMs, options.signal, node);
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
// NOTE: judged by this device's clock, so one running ahead ends a wait before the members
|
|
707
|
-
// would refuse it. If waits are seen ending early on skewed phones, allow a grace margin here.
|
|
708
|
-
function refuseIfExpired(invite) {
|
|
709
|
-
const expiresAtMs = parseNullableStoredDatetimeMs(invite.expiresAt);
|
|
710
|
-
if (expiresAtMs !== null && expiresAtMs <= Date.now()) {
|
|
711
|
-
throw new CadreInviteRejectedError('invite-spent', 'the invitation expired before a member accepted it');
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
/** A stopped node's every dial fails at once, which would otherwise read as "no member answered" until expiry. */
|
|
715
|
-
function refuseIfStopped(node) {
|
|
716
|
-
if (node.status !== 'started') {
|
|
717
|
-
throw new Error(`Cadre invitation redemption stopped waiting: the node is ${node.status}`);
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
/** The pause after pass `pass`, cut short at the invitation's expiry so the next check ends the wait then. */
|
|
721
|
-
function pauseAfterPass(pass, invite) {
|
|
722
|
-
const backoffMs = Math.min(REDEEM_PASS_FIRST_PAUSE_MS * 2 ** (pass - 1), REDEEM_PASS_MAX_PAUSE_MS);
|
|
723
|
-
const expiresAtMs = parseNullableStoredDatetimeMs(invite.expiresAt);
|
|
724
|
-
return expiresAtMs === null ? backoffMs : Math.max(0, Math.min(backoffMs, expiresAtMs - Date.now()));
|
|
725
|
-
}
|
|
726
|
-
/** Any refusal means a member answered and is not ready yet; otherwise none answered at all. */
|
|
727
|
-
function waitReason(outcomes) {
|
|
728
|
-
return outcomes.some((outcome) => outcome.error instanceof CadreInviteRejectedError) ? 'member-not-ready' : 'no-member-answered';
|
|
729
|
-
}
|
|
730
|
-
/** A UI callback must not break the join. */
|
|
731
|
-
function reportProgress(onProgress, progress) {
|
|
732
|
-
if (!onProgress)
|
|
733
|
-
return;
|
|
734
|
-
try {
|
|
735
|
-
onProgress(progress);
|
|
736
|
-
}
|
|
737
|
-
catch (error) {
|
|
738
|
-
log('redemption progress callback threw (ignored): %o', error);
|
|
739
|
-
}
|
|
400
|
+
export function redeemAtMembers(node, options) {
|
|
401
|
+
return dialRedemption(node, inviteRedemption(options));
|
|
740
402
|
}
|
|
741
403
|
/**
|
|
742
|
-
*
|
|
743
|
-
*
|
|
744
|
-
*
|
|
404
|
+
* Device side, in passes (`dialRedemptionInPasses` in `member-redemption.ts`): one
|
|
405
|
+
* {@link redeemAtMembers} pass, or, with `waitForMember`, as many as it takes, pausing between
|
|
406
|
+
* them and never past the invitation's expiry, which by this device's clock is thrown as the
|
|
407
|
+
* `invite-spent` refusal a member would give.
|
|
745
408
|
*/
|
|
746
|
-
function
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
}
|
|
756
|
-
const settle = () => {
|
|
757
|
-
clearTimeout(timer);
|
|
758
|
-
signal?.removeEventListener('abort', onAbort);
|
|
759
|
-
node.removeEventListener('stop', onStop);
|
|
760
|
-
};
|
|
761
|
-
const onAbort = () => {
|
|
762
|
-
settle();
|
|
763
|
-
reject(signal.reason);
|
|
764
|
-
};
|
|
765
|
-
const onStop = () => {
|
|
766
|
-
settle();
|
|
767
|
-
resolve();
|
|
768
|
-
};
|
|
769
|
-
const timer = setTimeout(onStop, ms);
|
|
770
|
-
signal?.addEventListener('abort', onAbort, { once: true });
|
|
771
|
-
node.addEventListener('stop', onStop, { once: true });
|
|
772
|
-
});
|
|
409
|
+
export function redeemInPasses(node, options) {
|
|
410
|
+
const passes = {
|
|
411
|
+
...inviteRedemption(options),
|
|
412
|
+
waitForMember: options.waitForMember,
|
|
413
|
+
expiresAt: options.invitation.invite.expiresAt,
|
|
414
|
+
expired: () => new CadreInviteRejectedError('invite-spent', 'the invitation expired before a member accepted it'),
|
|
415
|
+
...(options.onProgress ? { onProgress: options.onProgress } : {}),
|
|
416
|
+
};
|
|
417
|
+
return dialRedemptionInPasses(node, passes);
|
|
773
418
|
}
|
|
774
419
|
//# sourceMappingURL=cadre-invite-protocol.js.map
|