@ledgerhq/agent-intent-sdk 0.2.0 → 0.4.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.
@@ -13,6 +13,28 @@ const CHANNEL_DOMAIN = new TextEncoder().encode("agent-intent:enrollment-channel
13
13
  const RELAY_KEEPALIVE_INTERVAL_MS = 60_000;
14
14
  const RELAY_KEEPALIVE_PING = "ping";
15
15
  const RELAY_KEEPALIVE_PONG = "pong";
16
+ // A socket can stay half-open without reporting close; the host treats a ping that gets no
17
+ // frame back within this window as a drop.
18
+ const RELAY_PONG_TIMEOUT_MS = 10_000;
19
+ // The relay closes the host socket once its candidate leaves. The host reopens on the same key
20
+ // until the request expires or the completion timeout elapses: at once, then after 1, 2 and 4
21
+ // seconds, then every 5 seconds. A socket that stayed open for a minute before it dropped
22
+ // restarts that backoff; the minute is measured on the monotonic clock, so a wall-clock change
23
+ // does not move it.
24
+ const HOST_RECONNECT_DELAYS_MS = [0, 1_000, 2_000, 4_000];
25
+ const HOST_RECONNECT_MAX_DELAY_MS = 5_000;
26
+ const HOST_RECONNECT_STABLE_MS = 60_000;
27
+ // The relay has no rejection message and refuses frames outside its own protocol, so a rejection
28
+ // travels like a completion: the candidate sends it as TrustchainShareCredential and the host
29
+ // acknowledges it with TrustchainAddedMember. Only a rejection and its acknowledgement carry a
30
+ // `reason`; a completion carries `completion` and its acknowledgement `acknowledged`.
31
+ const USER_REJECTION = { reason: "user-rejected" };
32
+ const REJECTION_ACKNOWLEDGEMENT = { reason: "rejection-acknowledged" };
33
+ // The host refuses a rejection or a completion with a Failure. The relay reads a Failure as
34
+ // `{ type, message }`, takes `type` from its own list, and forwards the message of this type
35
+ // untouched, so the encrypted reason travels there. The relay then closes both sides.
36
+ const HOST_REFUSAL_TYPE = "UNEXPECTED_SHARE_CREDENTIAL";
37
+ const REJECTION_REFUSED_MESSAGE = "The enrollment host already received a completion for this request; it can no longer be rejected.";
16
38
  export const AGENT_ENROLLMENT_CHANNEL_DEFAULT_TIMEOUTS = {
17
39
  candidateTimeoutMs: 15 * 60_000,
18
40
  handshakeTimeoutMs: 30_000,
@@ -20,6 +42,35 @@ export const AGENT_ENROLLMENT_CHANNEL_DEFAULT_TIMEOUTS = {
20
42
  acknowledgementTimeoutMs: 30_000,
21
43
  persistTimeoutMs: 30_000,
22
44
  };
45
+ /** The user rejected the signed enrollment or recovery request in the frontend. */
46
+ export class AgentEnrollmentRejectedError extends AgentIntentSdkError {
47
+ kind;
48
+ constructor(kind) {
49
+ super(`The user rejected this agent ${kind} request.`);
50
+ this.name = "AgentEnrollmentRejectedError";
51
+ this.kind = kind;
52
+ }
53
+ }
54
+ // ES2026, so not in the ES2023 lib; older browsers lack it.
55
+ const errorIsError = Error.isError;
56
+ /**
57
+ * Checked by shape rather than `instanceof`, so an error from another copy of the SDK or another
58
+ * realm of the same process still matches. It must still be a real `Error`, which `Error.isError`
59
+ * tells across realms. Where it is missing, `Object.prototype.toString` stands in, which an object
60
+ * can fool through `Symbol.toStringTag`. A structured clone, such as `postMessage` to a worker,
61
+ * keeps neither the name nor `kind`, so a cloned error does not match.
62
+ */
63
+ export function isAgentEnrollmentRejectedError(error) {
64
+ const isError = errorIsError === undefined
65
+ ? Object.prototype.toString.call(error) === "[object Error]"
66
+ : errorIsError(error);
67
+ if (!isError)
68
+ return false;
69
+ const { name, kind, message } = error;
70
+ return (name === "AgentEnrollmentRejectedError" &&
71
+ (kind === "enrollment" || kind === "recovery") &&
72
+ typeof message === "string");
73
+ }
23
74
  export function createAgentEnrollmentChannelHost(input) {
24
75
  const identity = createSoftwareAgentIdentity();
25
76
  const publisher = identity.publicKey;
@@ -39,14 +90,15 @@ export function createAgentEnrollmentChannelHost(input) {
39
90
  }
40
91
  assertHostRequest(request, input.environment, publisher);
41
92
  used = true;
93
+ const openSocket = () => socketFactory(input.webSocketFactory)(relayUrl(input.relayBaseUrl, publisher));
42
94
  let socket;
43
95
  try {
44
- socket = socketFactory(input.webSocketFactory)(relayUrl(input.relayBaseUrl, publisher));
96
+ socket = openSocket();
45
97
  }
46
98
  catch (error) {
47
99
  return Promise.reject(asChannelError(error));
48
100
  }
49
- session = runHost(socket, identity, request, authenticate, persist, timeouts);
101
+ session = runHost(socket, openSocket, identity, request, authenticate, persist, timeouts);
50
102
  return session.completion;
51
103
  },
52
104
  close: () => {
@@ -59,45 +111,79 @@ export function createAgentEnrollmentChannelCandidate(input) {
59
111
  assertCandidateRequest(input.request, input.now ?? new Date());
60
112
  const timeouts = resolveTimeouts(input.timeouts);
61
113
  let session;
62
- let delivering = false;
114
+ let pending;
115
+ // Set once the device may have committed the enrollment, which a rejection cannot undo.
116
+ let tooLateToReject;
63
117
  let delivered = false;
118
+ let rejected = false;
64
119
  let closed = false;
65
120
  const assertUsable = () => {
66
121
  if (delivered)
67
122
  throw channelError("This enrollment completion has already been sent.");
123
+ if (rejected)
124
+ throw channelError("This enrollment request has already been rejected.");
68
125
  if (closed)
69
126
  throw channelError("This enrollment completion channel has been closed.");
70
127
  assertCandidateRequest(input.request, new Date());
71
128
  };
72
- const connectSession = () => {
73
- if (session === undefined || session.failed) {
74
- try {
129
+ const withSession = (use) => {
130
+ try {
131
+ if (session === undefined || session.failed) {
75
132
  session = openCandidateSession(socketFactory(input.webSocketFactory)(relayUrl(input.relayBaseUrl, input.request.channel.hostPublicKey)), input.request, timeouts);
76
133
  }
77
- catch (error) {
78
- return Promise.reject(asChannelError(error));
79
- }
134
+ return use(session);
135
+ }
136
+ catch (error) {
137
+ return Promise.reject(asChannelError(error));
80
138
  }
81
- const active = session;
82
- return active.ready.then(() => active);
83
139
  };
84
140
  return {
85
141
  connect: () => {
86
142
  assertUsable();
87
- return connectSession().then(() => undefined);
143
+ // A running delivery or rejection owns the session, even one whose loss is still being
144
+ // reported, so connect() reports on it rather than opening another.
145
+ if (pending !== undefined && session !== undefined)
146
+ return session.ready;
147
+ return withSession((active) => active.ready.then(() => undefined));
88
148
  },
89
149
  deliver: (completionPayload) => {
90
- if (delivering)
150
+ if (pending === "delivery") {
91
151
  throw channelError("This enrollment completion is already being sent.");
152
+ }
153
+ if (pending === "rejection")
154
+ throw channelError("This enrollment request is being rejected.");
92
155
  assertUsable();
93
- delivering = true;
94
- return connectSession()
95
- .then((active) => active.deliver(completionPayload))
156
+ pending = "delivery";
157
+ tooLateToReject ??=
158
+ "This enrollment request can no longer be rejected once its completion delivery has started.";
159
+ return withSession((active) => active.ready.then(() => active.deliver(completionPayload)))
96
160
  .then(() => {
97
161
  delivered = true;
98
162
  })
99
163
  .finally(() => {
100
- delivering = false;
164
+ pending = undefined;
165
+ });
166
+ },
167
+ reject: () => {
168
+ // The host refuses it too once it received a completion; this check needs no round trip.
169
+ if (tooLateToReject !== undefined)
170
+ throw channelError(tooLateToReject);
171
+ if (pending === "rejection") {
172
+ throw channelError("This enrollment request is already being rejected.");
173
+ }
174
+ assertUsable();
175
+ pending = "rejection";
176
+ return withSession((active) => active.reject().catch((error) => {
177
+ // Final: each retry would only make the relay drop the host again and delay its reopening.
178
+ if (active.rejectionRefused)
179
+ tooLateToReject = REJECTION_REFUSED_MESSAGE;
180
+ throw error;
181
+ }))
182
+ .then(() => {
183
+ rejected = true;
184
+ })
185
+ .finally(() => {
186
+ pending = undefined;
101
187
  });
102
188
  },
103
189
  close: () => {
@@ -106,79 +192,197 @@ export function createAgentEnrollmentChannelCandidate(input) {
106
192
  },
107
193
  };
108
194
  }
109
- function runHost(socket, identity, request, authenticate, persist, timeouts) {
195
+ function runHost(initialSocket, openSocket, identity, request, authenticate, persist, timeouts) {
110
196
  let close = () => undefined;
111
197
  const completion = new Promise((resolve, reject) => {
112
198
  let state = "connected";
113
199
  let peer = "";
114
200
  let cipher;
115
201
  let challenge = "";
116
- let phaseTimer;
117
- let completionTimer;
202
+ let stopPhaseTimer = () => undefined;
203
+ let stopCompletionTimer = () => undefined;
118
204
  let stopKeepAlive = () => undefined;
119
205
  let messageQueue = Promise.resolve();
120
- const fail = failChannel(socket, reject, () => state === "finished", () => {
206
+ let socket = initialSocket;
207
+ // Set once the session resolves or fails; a handler resuming after an await can still
208
+ // move `state`, so reconnects and timers check this instead.
209
+ let settled = false;
210
+ // Survives candidate resets. A parsed completion does not prove the device committed, since
211
+ // the link is enough to build one, but neither does a failed authenticate() disprove it.
212
+ // Refusing a rejection then costs a wait until expiry; honoring one after a real commit would
213
+ // leave a Trustchain member whose agent treats it as rejected.
214
+ let completionReceived = false;
215
+ let attempts = 0;
216
+ let loseSocket = () => undefined;
217
+ let reconnectTimer;
218
+ const fail = failChannel(() => socket.close(), reject, () => settled, () => {
219
+ settled = true;
121
220
  state = "finished";
122
- clearTimeout(phaseTimer);
123
- clearTimeout(completionTimer);
221
+ stopPhaseTimer();
222
+ stopCompletionTimer();
223
+ clearTimeout(reconnectTimer);
124
224
  stopKeepAlive();
125
225
  });
126
226
  const armCandidateTimer = () => {
127
- clearTimeout(phaseTimer);
128
- phaseTimer = deadlineTimer(timeouts.candidateTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment channel timed out waiting for the frontend candidate.")));
227
+ stopPhaseTimer();
228
+ stopPhaseTimer = deadlineTimer(timeouts.candidateTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment channel timed out waiting for the frontend candidate.")));
129
229
  };
130
230
  const armHandshakeTimer = () => {
131
- clearTimeout(phaseTimer);
132
- phaseTimer = deadlineTimer(timeouts.handshakeTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment channel handshake timed out.")));
231
+ stopPhaseTimer();
232
+ // A candidate that stops answering is dropped like a relay drop, so another can connect.
233
+ // The lost path runs directly because some sockets never report their own close.
234
+ stopPhaseTimer = deadlineTimer(timeouts.handshakeTimeoutMs, request.expiresAt, () => loseSocket("Enrollment channel handshake timed out."));
133
235
  };
134
- completionTimer = deadlineTimer(timeouts.completionTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment completion timed out.")));
236
+ stopCompletionTimer = deadlineTimer(timeouts.completionTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment completion timed out.")));
135
237
  const resetCandidate = () => {
136
- if (state === "finished")
238
+ if (settled)
137
239
  return;
138
- clearTimeout(phaseTimer);
240
+ stopPhaseTimer();
139
241
  state = "connected";
140
242
  peer = "";
141
243
  cipher = undefined;
142
244
  challenge = "";
143
245
  armCandidateTimer();
144
246
  };
145
- const rejectCandidate = async (reason) => {
146
- const activeCipher = cipher;
147
- if (activeCipher) {
148
- try {
149
- await sendEncrypted(socket, identity.publicKey, "Failure", activeCipher, request, {
150
- rejected: true,
151
- });
152
- }
153
- catch {
154
- // The candidate is already unusable; keep the bounded host session available.
155
- }
247
+ const answerCandidate = async (activeCipher, message, payload) => {
248
+ try {
249
+ await sendEncrypted(socket, identity.publicKey, message, activeCipher, request, payload);
156
250
  }
157
- resetCandidate();
158
- if (!(reason instanceof AgentIntentSdkError)) {
159
- // Normalize callback failures without exposing their potentially sensitive details.
160
- asChannelError(reason);
251
+ catch {
252
+ // The candidate may be gone already; the host session stays bounded either way.
161
253
  }
162
254
  };
255
+ const dropCandidate = async (reason) => {
256
+ if (cipher)
257
+ await answerCandidate(cipher, "Failure", { reason });
258
+ resetCandidate();
259
+ };
163
260
  // Stops timers and keepalive itself rather than relying on the socket's close event.
164
261
  close = () => fail(channelError("This enrollment host session has been closed."));
165
262
  armCandidateTimer();
166
- socket.addEventListener("open", () => {
167
- if (state !== "finished")
168
- stopKeepAlive = keepRelayAlive(socket);
169
- });
170
- socket.addEventListener("error", () => fail(channelError("Enrollment relay connection failed.")));
171
- socket.addEventListener("close", () => fail(channelError("Enrollment relay closed before completion was acknowledged.")));
172
- socket.addEventListener("message", (event) => {
173
- if (isRelayKeepAliveReply(event.data))
263
+ const openReconnect = () => {
264
+ if (settled)
265
+ return;
266
+ // Timers stop while a laptop sleeps, so the wall clock decides whether the request expired.
267
+ if (Date.parse(request.expiresAt) <= Date.now()) {
268
+ fail(channelError("Enrollment completion timed out."));
269
+ return;
270
+ }
271
+ let source;
272
+ try {
273
+ source = openSocket();
274
+ attach(source, true);
275
+ }
276
+ catch {
277
+ // A factory or socket that throws is retried like a failed open; the queue must not reject.
278
+ try {
279
+ source?.close();
280
+ }
281
+ catch {
282
+ // The socket was never attached, so nothing reports its failure.
283
+ }
284
+ reconnect();
285
+ }
286
+ };
287
+ const reconnect = () => {
288
+ if (settled)
289
+ return;
290
+ // A drop before any candidate keeps the running wait for the first one.
291
+ if (state !== "connected")
292
+ resetCandidate();
293
+ const delay = HOST_RECONNECT_DELAYS_MS[attempts] ?? HOST_RECONNECT_MAX_DELAY_MS;
294
+ attempts += 1;
295
+ // The relay rejects a candidate that arrives while the host is away, so the first
296
+ // reopen does not wait for a timer.
297
+ if (delay === 0)
298
+ openReconnect();
299
+ else
300
+ reconnectTimer = setTimeout(openReconnect, delay);
301
+ };
302
+ const attach = (source, reopened) => {
303
+ let opened = false;
304
+ let openedAt = 0;
305
+ let lost = false;
306
+ const onLost = (message) => {
307
+ if (lost || source !== socket || settled)
308
+ return;
309
+ lost = true;
310
+ stopKeepAlive();
311
+ // A socket that only reported an error may still be open, and the relay keeps its
312
+ // candidate until it closes.
313
+ try {
314
+ source.close();
315
+ }
316
+ catch {
317
+ // A socket that cannot close is already gone.
318
+ }
319
+ if ((!opened && !reopened) || state === "authenticating" || state === "persisting") {
320
+ fail(channelError(message));
321
+ return;
322
+ }
323
+ if (opened && performance.now() - openedAt >= HOST_RECONNECT_STABLE_MS)
324
+ attempts = 0;
325
+ // Queued so a handler already running for this socket finishes before the reset.
326
+ messageQueue = messageQueue.then(reconnect);
327
+ };
328
+ source.addEventListener("open", () => {
329
+ opened = true;
330
+ openedAt = performance.now();
331
+ if (source === socket && !settled && !lost) {
332
+ stopKeepAlive = keepRelayAlive(source, () => onLost("Enrollment relay closed before completion was acknowledged."));
333
+ }
334
+ });
335
+ source.addEventListener("error", () => onLost("Enrollment relay connection failed."));
336
+ source.addEventListener("close", () => onLost("Enrollment relay closed before completion was acknowledged."));
337
+ source.addEventListener("message", (event) => {
338
+ if (source === socket && !isRelayKeepAliveReply(event.data)) {
339
+ handleMessage(event.data, () => lost);
340
+ }
341
+ });
342
+ socket = source;
343
+ loseSocket = onLost;
344
+ };
345
+ const failAsRejected = () => fail(new AgentEnrollmentRejectedError(isAgentRecoveryRequest(request) ? "recovery" : "enrollment"));
346
+ const recordShareCredential = (body) => {
347
+ if (body.kind === "completion")
348
+ completionReceived = true;
349
+ else if (!completionReceived)
350
+ failAsRejected();
351
+ };
352
+ // A frame queued before the relay dropped its socket would answer a candidate that left, so
353
+ // nothing is sent and nothing is authenticated. The confirmed peer's frames still count: a
354
+ // completion blocks later rejections like one on a live socket (see `completionReceived`),
355
+ // and a rejection needs no answer.
356
+ const recordWithoutAnswer = async (data) => {
357
+ if (state !== "authenticated")
174
358
  return;
359
+ try {
360
+ const envelope = parseEnvelope(data);
361
+ assertPeer(envelope, peer);
362
+ if (envelope.message !== "TrustchainShareCredential")
363
+ return;
364
+ const payload = await decryptPayload(requireCipher(cipher), envelope, request);
365
+ recordShareCredential(readShareCredential(payload, request));
366
+ }
367
+ catch {
368
+ // Any other frame would only reset the candidate, which the reconnect does anyway.
369
+ }
370
+ };
371
+ const handleMessage = (data, lost) => {
175
372
  messageQueue = messageQueue
176
373
  .then(async () => {
177
- const envelope = parseEnvelope(event.data);
374
+ if (settled)
375
+ return;
376
+ if (lost()) {
377
+ await recordWithoutAnswer(data);
378
+ return;
379
+ }
380
+ const envelope = parseEnvelope(data);
178
381
  if (envelope.message === "Failure")
179
382
  throw channelError("The enrollment relay rejected the session.");
180
- // A new candidate may replace one that has not delivered yet, so a frontend
181
- // that lost its relay socket while waiting for device approval can reconnect.
383
+ // The relay admits one candidate per host socket and closes the host when it leaves,
384
+ // which attach() handles by reopening. A relay that admits another candidate before
385
+ // delivery still gets a fresh handshake here.
182
386
  if (envelope.message === "InitiateHandshake" &&
183
387
  (state === "connected" || state === "challenged" || state === "authenticated")) {
184
388
  const candidatePublicKey = stringField(envelope.payload, "ephemeral_public_key");
@@ -204,32 +408,57 @@ function runHost(socket, identity, request, authenticate, persist, timeouts) {
204
408
  throw channelError("Enrollment channel key confirmation failed.");
205
409
  }
206
410
  await sendEncrypted(socket, identity.publicKey, "HandshakeCompletionSucceeded", activeCipher, request, {});
207
- clearTimeout(phaseTimer);
411
+ if (settled)
412
+ return;
413
+ stopPhaseTimer();
208
414
  state = "authenticated";
209
415
  return;
210
416
  }
211
417
  if (state === "authenticated" && envelope.message === "TrustchainShareCredential") {
212
- state = "authenticating";
213
418
  const activeCipher = requireCipher(cipher);
214
419
  const payload = await decryptPayload(activeCipher, envelope, request);
215
- const serialized = stringField(payload, "completion");
216
- const completion = parseChannelCompletion(serialized, request);
420
+ const body = readShareCredential(payload, request);
421
+ if (settled)
422
+ return;
423
+ // The relay dropped the socket during decryption, so this is a queued frame too.
424
+ if (lost()) {
425
+ recordShareCredential(body);
426
+ return;
427
+ }
428
+ // Only a confirmed peer can reject, and only while no completion has been received.
429
+ if (body.kind === "rejection") {
430
+ if (completionReceived) {
431
+ await dropCandidate("completion-received");
432
+ return;
433
+ }
434
+ await answerCandidate(activeCipher, "TrustchainAddedMember", REJECTION_ACKNOWLEDGEMENT);
435
+ // Settles before closing, so the relay's later close neither reconnects nor overrides it.
436
+ failAsRejected();
437
+ return;
438
+ }
439
+ state = "authenticating";
440
+ const { serialized, completion } = body;
441
+ completionReceived = true;
217
442
  try {
218
443
  await withinDeadline(() => authenticate(completion), timeouts.persistTimeoutMs, request.expiresAt, "Enrollment completion authentication timed out.");
219
444
  }
220
- catch (error) {
221
- await rejectCandidate(error);
445
+ catch {
446
+ // The callback's error may hold sensitive details, so the candidate only sees a reset.
447
+ await dropCandidate("reset");
222
448
  return;
223
449
  }
450
+ if (settled)
451
+ return;
224
452
  state = "persisting";
225
453
  await withinDeadline(() => persist(completion), timeouts.persistTimeoutMs, request.expiresAt, "Enrollment completion persistence timed out.");
226
454
  await sendEncrypted(socket, identity.publicKey, "TrustchainAddedMember", activeCipher, request, {
227
455
  acknowledged: true,
228
456
  digest: completionDigest(serialized),
229
457
  });
458
+ settled = true;
230
459
  state = "finished";
231
- clearTimeout(completionTimer);
232
- clearTimeout(phaseTimer);
460
+ stopCompletionTimer();
461
+ stopPhaseTimer();
233
462
  stopKeepAlive();
234
463
  socket.close();
235
464
  resolve(completion);
@@ -242,9 +471,10 @@ function runHost(socket, identity, request, authenticate, persist, timeouts) {
242
471
  fail(error);
243
472
  return;
244
473
  }
245
- await rejectCandidate(error);
474
+ await dropCandidate("reset");
246
475
  });
247
- });
476
+ };
477
+ attach(initialSocket, false);
248
478
  });
249
479
  return { completion, close: () => close() };
250
480
  }
@@ -255,33 +485,61 @@ function openCandidateSession(socket, request, timeouts) {
255
485
  let state = "connecting";
256
486
  let cipher;
257
487
  let failure;
258
- let phaseTimer;
488
+ let stopPhaseTimer = () => undefined;
259
489
  let stopKeepAlive = () => undefined;
260
490
  let messageQueue = Promise.resolve();
261
- let delivery;
491
+ let deliveryDigest = "";
492
+ let awaitingAcknowledgement;
493
+ // What reject() reports instead of `failure` when the session fails the same way under a delivery.
494
+ let rejectionFailure;
495
+ let rejectionRefused = false;
262
496
  let resolveReady = () => undefined;
263
497
  let rejectReady = () => undefined;
264
498
  const ready = new Promise((resolve, reject) => {
265
499
  resolveReady = resolve;
266
500
  rejectReady = reject;
267
501
  });
268
- // Callers observe failures through connect()/deliver(); an idle session must not leak a rejection.
502
+ // Callers observe failures through connect(), deliver() and reject(); an idle session must not
503
+ // leak a rejection.
269
504
  ready.catch(() => undefined);
270
- const fail = failChannel(socket, (error) => {
505
+ const fail = failChannel(() => socket.close(), (error) => {
271
506
  failure = asChannelError(error);
272
507
  rejectReady(failure);
273
- delivery?.reject(failure);
508
+ awaitingAcknowledgement?.reject(failure);
274
509
  }, () => state === "finished", () => {
275
510
  state = "failed";
276
- clearTimeout(phaseTimer);
277
- clearTimeout(sessionTimer);
511
+ stopPhaseTimer();
512
+ stopSessionTimer();
278
513
  stopKeepAlive();
279
514
  });
515
+ const failNamingRejection = (message, rejectionMessage) => {
516
+ if (state === "failed" || state === "finished")
517
+ return;
518
+ rejectionFailure = channelError(rejectionMessage);
519
+ fail(channelError(message));
520
+ };
280
521
  // Bounds the whole session, including the device-approval gap between connect() and deliver().
281
- const sessionTimer = deadlineTimer(timeouts.completionTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment completion delivery timed out.")));
282
- phaseTimer = deadlineTimer(timeouts.handshakeTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment channel handshake timed out.")));
283
- socket.addEventListener("error", () => fail(channelError("Enrollment relay connection failed.")));
284
- socket.addEventListener("close", () => fail(channelError("Enrollment relay closed before completion was acknowledged.")));
522
+ const stopSessionTimer = deadlineTimer(timeouts.completionTimeoutMs, request.expiresAt, () => failNamingRejection("Enrollment completion delivery timed out.", "Enrollment rejection timed out."));
523
+ stopPhaseTimer = deadlineTimer(timeouts.handshakeTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment channel handshake timed out.")));
524
+ // The relay closes right after it forwards the host's refusal, so a lost socket is reported
525
+ // behind the frames already received. The session counts as failed at once, so that the next
526
+ // call opens a fresh one.
527
+ let socketLost = false;
528
+ const loseSocket = (report) => {
529
+ socketLost = true;
530
+ messageQueue = messageQueue.then(report);
531
+ };
532
+ socket.addEventListener("error", () => loseSocket(() => fail(channelError("Enrollment relay connection failed."))));
533
+ socket.addEventListener("close", () => loseSocket(() => failNamingRejection("Enrollment relay closed before completion was acknowledged.", state === "rejecting"
534
+ ? "Enrollment relay closed before the rejection was acknowledged."
535
+ : "Enrollment relay closed before the rejection was sent.")));
536
+ const finish = () => {
537
+ state = "finished";
538
+ stopPhaseTimer();
539
+ stopSessionTimer();
540
+ stopKeepAlive();
541
+ socket.close();
542
+ };
285
543
  socket.addEventListener("open", () => {
286
544
  if (state !== "connecting")
287
545
  return;
@@ -305,17 +563,25 @@ function openCandidateSession(socket, request, timeouts) {
305
563
  messageQueue = messageQueue
306
564
  .then(async () => {
307
565
  const envelope = parseEnvelope(event.data);
308
- if (envelope.publisher.toLowerCase() !== request.channel.hostPublicKey.toLowerCase()) {
309
- throw channelError("Enrollment channel host does not match the signed request.");
310
- }
566
+ const fromHost = envelope.publisher.toLowerCase() === request.channel.hostPublicKey.toLowerCase();
311
567
  if (envelope.message === "Failure") {
312
- if (cipher && "encrypted" in envelope.payload) {
313
- await decryptPayload(cipher, envelope, request);
314
- throw channelError(state === "sent"
315
- ? "The enrollment host rejected this completion."
316
- : "The enrollment host reset this session.");
568
+ // The relay's own Failure does not carry the host key as publisher, and only the
569
+ // host's refusal decrypts.
570
+ const refusal = fromHost
571
+ ? await decryptPayload(cipher, envelope, request).catch(() => undefined)
572
+ : undefined;
573
+ if (refusal === undefined)
574
+ throw channelError("The enrollment relay rejected the session.");
575
+ if (state === "rejecting" && isReasonBody(refusal, "completion-received")) {
576
+ rejectionRefused = true;
577
+ throw channelError(REJECTION_REFUSED_MESSAGE);
317
578
  }
318
- throw channelError("The enrollment relay rejected the session.");
579
+ throw channelError(state === "sent"
580
+ ? "The enrollment host rejected this completion."
581
+ : "The enrollment host reset this session.");
582
+ }
583
+ if (!fromHost) {
584
+ throw channelError("Enrollment channel host does not match the signed request.");
319
585
  }
320
586
  if (state === "initiated" && envelope.message === "HandshakeChallenge") {
321
587
  cipher = await makeCipher(identity.deriveSharedSecret(hexToBytes(request.channel.hostPublicKey)), request);
@@ -328,47 +594,69 @@ function openCandidateSession(socket, request, timeouts) {
328
594
  }
329
595
  if (state === "confirmed" && envelope.message === "HandshakeCompletionSucceeded") {
330
596
  await decryptPayload(requireCipher(cipher), envelope, request);
331
- clearTimeout(phaseTimer);
597
+ stopPhaseTimer();
332
598
  state = "ready";
333
599
  resolveReady();
334
600
  return;
335
601
  }
336
602
  if (state === "sent" && envelope.message === "TrustchainAddedMember") {
337
603
  const acknowledgement = await decryptPayload(cipher, envelope, request);
338
- if (acknowledgement.acknowledged !== true ||
339
- stringField(acknowledgement, "digest") !== delivery?.digest) {
604
+ if (hasReason(acknowledgement) ||
605
+ acknowledgement.acknowledged !== true ||
606
+ stringField(acknowledgement, "digest") !== deliveryDigest) {
340
607
  throw channelError("Enrollment completion acknowledgement is invalid.");
341
608
  }
342
- state = "finished";
343
- clearTimeout(phaseTimer);
344
- clearTimeout(sessionTimer);
345
- stopKeepAlive();
346
- socket.close();
347
- delivery.resolve();
609
+ finish();
610
+ awaitingAcknowledgement?.resolve();
611
+ return;
612
+ }
613
+ if (state === "rejecting" && envelope.message === "TrustchainAddedMember") {
614
+ const acknowledgement = await decryptPayload(cipher, envelope, request);
615
+ if (!isReasonBody(acknowledgement, REJECTION_ACKNOWLEDGEMENT.reason)) {
616
+ throw channelError("Enrollment rejection acknowledgement is invalid.");
617
+ }
618
+ finish();
619
+ awaitingAcknowledgement?.resolve();
348
620
  return;
349
621
  }
350
622
  throw channelError(`Unexpected ${envelope.message} enrollment channel message.`);
351
623
  })
352
624
  .catch(fail);
353
625
  });
626
+ // A session carries one delivery or one rejection; either waits for the host to acknowledge it.
627
+ const sendAndAwaitAcknowledgement = (next, payload, timeoutMessage) => new Promise((resolve, reject) => {
628
+ if (state !== "ready") {
629
+ reject(failure ?? channelError("Enrollment channel is not connected."));
630
+ return;
631
+ }
632
+ state = next;
633
+ awaitingAcknowledgement = { resolve, reject };
634
+ messageQueue = messageQueue
635
+ .then(async () => {
636
+ await sendEncrypted(socket, publisher, "TrustchainShareCredential", requireCipher(cipher), request, payload);
637
+ if (state !== next)
638
+ return;
639
+ stopPhaseTimer();
640
+ stopPhaseTimer = deadlineTimer(timeouts.acknowledgementTimeoutMs, request.expiresAt, () => fail(channelError(timeoutMessage)));
641
+ })
642
+ .catch(fail);
643
+ });
354
644
  return {
355
645
  ready,
356
646
  get failed() {
357
- return state === "failed";
647
+ return state === "failed" || socketLost;
358
648
  },
359
- deliver: (completionPayload) => new Promise((resolve, reject) => {
360
- if (state !== "ready") {
361
- reject(failure ?? channelError("Enrollment channel is not connected."));
362
- return;
363
- }
364
- state = "sent";
365
- delivery = { digest: completionDigest(completionPayload), resolve, reject };
366
- messageQueue = messageQueue
367
- .then(async () => {
368
- await sendEncrypted(socket, publisher, "TrustchainShareCredential", requireCipher(cipher), request, { completion: completionPayload });
369
- phaseTimer = deadlineTimer(timeouts.acknowledgementTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment completion acknowledgement timed out.")));
370
- })
371
- .catch(fail);
649
+ get rejectionRefused() {
650
+ return rejectionRefused;
651
+ },
652
+ deliver: (completionPayload) => {
653
+ deliveryDigest = completionDigest(completionPayload);
654
+ return sendAndAwaitAcknowledgement("sent", { completion: completionPayload }, "Enrollment completion acknowledgement timed out.");
655
+ },
656
+ reject: () => ready
657
+ .then(() => sendAndAwaitAcknowledgement("rejecting", USER_REJECTION, "Enrollment rejection acknowledgement timed out."))
658
+ .catch((error) => {
659
+ throw rejectionFailure ?? error;
372
660
  }),
373
661
  close: () => fail(channelError("This enrollment completion channel has been closed.")),
374
662
  };
@@ -401,12 +689,7 @@ async function decryptPayload(cipher, envelope, request) {
401
689
  if (!constantTimeEqual(cipher.requestDigest, signedRequestDigest(request))) {
402
690
  throw channelError("Enrollment channel request binding changed.");
403
691
  }
404
- if (Object.keys(envelope.payload).length !== 1 ||
405
- !Object.prototype.hasOwnProperty.call(envelope.payload, "encrypted")) {
406
- throw channelError("Enrollment channel encrypted envelope is malformed.");
407
- }
408
- const encoded = stringField(envelope.payload, "encrypted");
409
- const blob = base64ToBytes(encoded);
692
+ const blob = base64ToBytes(ciphertextOf(envelope));
410
693
  if (blob.length <= 28)
411
694
  throw channelError("Enrollment channel payload is malformed.");
412
695
  try {
@@ -434,17 +717,61 @@ async function sendEncrypted(socket, publisher, message, cipher, request, payloa
434
717
  publisher: publisher.toLowerCase(),
435
718
  message,
436
719
  };
437
- const encrypted = await encryptPayload(cipher, metadata, payload);
438
- send(socket, {
720
+ send(socket, await sealEnvelope(cipher, metadata, payload));
721
+ }
722
+ /** Encrypts the payload into the field the relay forwards for this message. */
723
+ async function sealEnvelope(cipher, metadata, payload, nonce) {
724
+ const encrypted = await encryptPayload(cipher, metadata, payload, nonce);
725
+ return {
439
726
  ...metadata,
440
- payload: { encrypted },
441
- });
727
+ payload: metadata.message === "Failure"
728
+ ? { type: HOST_REFUSAL_TYPE, message: encrypted }
729
+ : { encrypted },
730
+ };
731
+ }
732
+ /** Reads the ciphertext from where `sealEnvelope` puts it; any other payload shape is refused. */
733
+ function ciphertextOf({ message, payload }) {
734
+ const fields = Object.keys(payload);
735
+ const field = message === "Failure" ? "message" : "encrypted";
736
+ if (fields.length !== (message === "Failure" ? 2 : 1) ||
737
+ !Object.prototype.hasOwnProperty.call(payload, field) ||
738
+ (message === "Failure" && payload.type !== HOST_REFUSAL_TYPE)) {
739
+ throw channelError("Enrollment channel encrypted envelope is malformed.");
740
+ }
741
+ return stringField(payload, field);
742
+ }
743
+ /**
744
+ * Reads a TrustchainShareCredential body, which is a completion or the user's rejection. Only
745
+ * the rejection carries a `reason`, so a body with one is exactly the rejection or invalid, and
746
+ * never a completion. An invalid body throws.
747
+ */
748
+ function readShareCredential(payload, request) {
749
+ if (hasReason(payload)) {
750
+ if (!isReasonBody(payload, USER_REJECTION.reason)) {
751
+ throw channelError("Enrollment channel rejection is invalid.");
752
+ }
753
+ return { kind: "rejection" };
754
+ }
755
+ const serialized = stringField(payload, "completion");
756
+ return {
757
+ kind: "completion",
758
+ serialized,
759
+ completion: parseChannelCompletion(serialized, request),
760
+ };
761
+ }
762
+ /** Only the bodies of a rejection and its answers carry a `reason`. */
763
+ function hasReason(payload) {
764
+ return Object.prototype.hasOwnProperty.call(payload, "reason");
765
+ }
766
+ function isReasonBody(payload, reason) {
767
+ return Object.keys(payload).length === 1 && payload.reason === reason;
442
768
  }
443
769
  function send(socket, envelope) {
444
770
  socket.send(JSON.stringify(envelope));
445
771
  }
446
772
  /** Pings the relay until the returned stop function runs. */
447
- function keepRelayAlive(socket) {
773
+ function keepRelayAlive(socket, onSilent) {
774
+ let deadline;
448
775
  const timer = setInterval(() => {
449
776
  try {
450
777
  socket.send(RELAY_KEEPALIVE_PING);
@@ -452,8 +779,19 @@ function keepRelayAlive(socket) {
452
779
  catch {
453
780
  // A socket that cannot send is closing; its close and error listeners report the failure.
454
781
  }
782
+ if (onSilent) {
783
+ clearTimeout(deadline);
784
+ deadline = setTimeout(onSilent, RELAY_PONG_TIMEOUT_MS);
785
+ }
455
786
  }, RELAY_KEEPALIVE_INTERVAL_MS);
456
- return () => clearInterval(timer);
787
+ // Any frame proves the socket is alive, not only the pong. The socket type has no
788
+ // removeEventListener; once stopped, this listener only clears a cleared timer.
789
+ if (onSilent)
790
+ socket.addEventListener("message", () => clearTimeout(deadline));
791
+ return () => {
792
+ clearInterval(timer);
793
+ clearTimeout(deadline);
794
+ };
457
795
  }
458
796
  function isRelayKeepAliveReply(data) {
459
797
  return frameText(data) === RELAY_KEEPALIVE_PONG;
@@ -568,14 +906,14 @@ function base64ToBytes(value) {
568
906
  throw channelError("Enrollment channel payload is not valid base64.");
569
907
  }
570
908
  }
571
- function failChannel(socket, reject, finished, beforeReject) {
909
+ function failChannel(closeSocket, reject, finished, beforeReject) {
572
910
  let failed = false;
573
911
  return (reason) => {
574
912
  if (failed || finished())
575
913
  return;
576
914
  failed = true;
577
915
  beforeReject();
578
- socket.close();
916
+ closeSocket();
579
917
  reject(asChannelError(reason));
580
918
  };
581
919
  }
@@ -605,11 +943,7 @@ function parseChannelCompletion(serialized, request) {
605
943
  if (isAgentRecoveryRequest(request)) {
606
944
  return parseAgentRecoveryCompletion(serialized, request.publicKey, request.previousTrustchainId, request.signature);
607
945
  }
608
- const completion = parseAgentEnrollmentCompletion(serialized, request.publicKey);
609
- if (completion.version !== 2) {
610
- throw channelError("The enrollment channel requires completion version 2.");
611
- }
612
- return completion;
946
+ return parseAgentEnrollmentCompletion(serialized, request.publicKey);
613
947
  }
614
948
  function resolveTimeouts(timeouts) {
615
949
  const resolved = { ...AGENT_ENROLLMENT_CHANNEL_DEFAULT_TIMEOUTS, ...timeouts };
@@ -620,20 +954,31 @@ function resolveTimeouts(timeouts) {
620
954
  }
621
955
  return resolved;
622
956
  }
957
+ // Delays above 2^31 - 1 ms overflow and fire almost immediately.
958
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
623
959
  function deadlineTimer(timeoutMs, expiresAt, onTimeout) {
624
- const remaining = Date.parse(expiresAt) - Date.now();
625
- return setTimeout(onTimeout, Math.max(0, Math.min(timeoutMs, remaining)));
960
+ const deadline = Math.min(Date.now() + timeoutMs, Date.parse(expiresAt));
961
+ let timer;
962
+ const arm = () => {
963
+ const remaining = deadline - Date.now();
964
+ timer =
965
+ remaining > MAX_TIMEOUT_MS
966
+ ? setTimeout(arm, MAX_TIMEOUT_MS)
967
+ : setTimeout(onTimeout, Math.max(0, remaining));
968
+ };
969
+ arm();
970
+ return () => clearTimeout(timer);
626
971
  }
627
972
  async function withinDeadline(operation, timeoutMs, expiresAt, message) {
628
973
  return await new Promise((resolve, reject) => {
629
- const timer = deadlineTimer(timeoutMs, expiresAt, () => reject(channelError(message)));
974
+ const stopTimer = deadlineTimer(timeoutMs, expiresAt, () => reject(channelError(message)));
630
975
  void Promise.resolve()
631
976
  .then(operation)
632
977
  .then((value) => {
633
- clearTimeout(timer);
978
+ stopTimer();
634
979
  resolve(value);
635
980
  }, (error) => {
636
- clearTimeout(timer);
981
+ stopTimer();
637
982
  reject(error);
638
983
  });
639
984
  });
@@ -659,6 +1004,8 @@ export const enrollmentChannelCryptoVectors = {
659
1004
  const cipher = await makeCipher(sharedSecret, request);
660
1005
  return encryptPayload(cipher, envelope, payload, nonce);
661
1006
  },
1007
+ /** The whole relay frame, as the channel sends it. */
1008
+ envelope: async (sharedSecret, request, envelope, payload, nonce) => JSON.stringify(await sealEnvelope(await makeCipher(sharedSecret, request), envelope, payload, nonce)),
662
1009
  };
663
1010
  function asChannelError(reason) {
664
1011
  return reason instanceof AgentIntentSdkError