@ledgerhq/agent-intent-sdk 0.2.0 → 0.3.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,7 +192,7 @@ 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";
@@ -117,10 +203,24 @@ function runHost(socket, identity, request, authenticate, persist, timeouts) {
117
203
  let completionTimer;
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
221
  clearTimeout(phaseTimer);
123
222
  clearTimeout(completionTimer);
223
+ clearTimeout(reconnectTimer);
124
224
  stopKeepAlive();
125
225
  });
126
226
  const armCandidateTimer = () => {
@@ -129,11 +229,13 @@ function runHost(socket, identity, request, authenticate, persist, timeouts) {
129
229
  };
130
230
  const armHandshakeTimer = () => {
131
231
  clearTimeout(phaseTimer);
132
- phaseTimer = deadlineTimer(timeouts.handshakeTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment channel handshake timed out.")));
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
+ phaseTimer = deadlineTimer(timeouts.handshakeTimeoutMs, request.expiresAt, () => loseSocket("Enrollment channel handshake timed out."));
133
235
  };
134
236
  completionTimer = 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
240
  clearTimeout(phaseTimer);
139
241
  state = "connected";
@@ -142,43 +244,145 @@ function runHost(socket, identity, request, authenticate, persist, timeouts) {
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)
174
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")
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,29 +408,54 @@ 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, {});
411
+ if (settled)
412
+ return;
207
413
  clearTimeout(phaseTimer);
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
460
  clearTimeout(completionTimer);
232
461
  clearTimeout(phaseTimer);
@@ -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
  }
@@ -258,30 +488,58 @@ function openCandidateSession(socket, request, timeouts) {
258
488
  let phaseTimer;
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
511
  clearTimeout(phaseTimer);
277
512
  clearTimeout(sessionTimer);
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.")));
522
+ const sessionTimer = deadlineTimer(timeouts.completionTimeoutMs, request.expiresAt, () => failNamingRejection("Enrollment completion delivery timed out.", "Enrollment rejection timed out."));
282
523
  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.")));
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
+ clearTimeout(phaseTimer);
539
+ clearTimeout(sessionTimer);
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);
@@ -335,40 +601,61 @@ function openCandidateSession(socket, request, timeouts) {
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
+ phaseTimer = deadlineTimer(timeouts.acknowledgementTimeoutMs, request.expiresAt, () => fail(channelError(timeoutMessage)));
640
+ })
641
+ .catch(fail);
642
+ });
354
643
  return {
355
644
  ready,
356
645
  get failed() {
357
- return state === "failed";
646
+ return state === "failed" || socketLost;
358
647
  },
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);
648
+ get rejectionRefused() {
649
+ return rejectionRefused;
650
+ },
651
+ deliver: (completionPayload) => {
652
+ deliveryDigest = completionDigest(completionPayload);
653
+ return sendAndAwaitAcknowledgement("sent", { completion: completionPayload }, "Enrollment completion acknowledgement timed out.");
654
+ },
655
+ reject: () => ready
656
+ .then(() => sendAndAwaitAcknowledgement("rejecting", USER_REJECTION, "Enrollment rejection acknowledgement timed out."))
657
+ .catch((error) => {
658
+ throw rejectionFailure ?? error;
372
659
  }),
373
660
  close: () => fail(channelError("This enrollment completion channel has been closed.")),
374
661
  };
@@ -401,12 +688,7 @@ async function decryptPayload(cipher, envelope, request) {
401
688
  if (!constantTimeEqual(cipher.requestDigest, signedRequestDigest(request))) {
402
689
  throw channelError("Enrollment channel request binding changed.");
403
690
  }
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);
691
+ const blob = base64ToBytes(ciphertextOf(envelope));
410
692
  if (blob.length <= 28)
411
693
  throw channelError("Enrollment channel payload is malformed.");
412
694
  try {
@@ -434,17 +716,61 @@ async function sendEncrypted(socket, publisher, message, cipher, request, payloa
434
716
  publisher: publisher.toLowerCase(),
435
717
  message,
436
718
  };
437
- const encrypted = await encryptPayload(cipher, metadata, payload);
438
- send(socket, {
719
+ send(socket, await sealEnvelope(cipher, metadata, payload));
720
+ }
721
+ /** Encrypts the payload into the field the relay forwards for this message. */
722
+ async function sealEnvelope(cipher, metadata, payload, nonce) {
723
+ const encrypted = await encryptPayload(cipher, metadata, payload, nonce);
724
+ return {
439
725
  ...metadata,
440
- payload: { encrypted },
441
- });
726
+ payload: metadata.message === "Failure"
727
+ ? { type: HOST_REFUSAL_TYPE, message: encrypted }
728
+ : { encrypted },
729
+ };
730
+ }
731
+ /** Reads the ciphertext from where `sealEnvelope` puts it; any other payload shape is refused. */
732
+ function ciphertextOf({ message, payload }) {
733
+ const fields = Object.keys(payload);
734
+ const field = message === "Failure" ? "message" : "encrypted";
735
+ if (fields.length !== (message === "Failure" ? 2 : 1) ||
736
+ !Object.prototype.hasOwnProperty.call(payload, field) ||
737
+ (message === "Failure" && payload.type !== HOST_REFUSAL_TYPE)) {
738
+ throw channelError("Enrollment channel encrypted envelope is malformed.");
739
+ }
740
+ return stringField(payload, field);
741
+ }
742
+ /**
743
+ * Reads a TrustchainShareCredential body, which is a completion or the user's rejection. Only
744
+ * the rejection carries a `reason`, so a body with one is exactly the rejection or invalid, and
745
+ * never a completion. An invalid body throws.
746
+ */
747
+ function readShareCredential(payload, request) {
748
+ if (hasReason(payload)) {
749
+ if (!isReasonBody(payload, USER_REJECTION.reason)) {
750
+ throw channelError("Enrollment channel rejection is invalid.");
751
+ }
752
+ return { kind: "rejection" };
753
+ }
754
+ const serialized = stringField(payload, "completion");
755
+ return {
756
+ kind: "completion",
757
+ serialized,
758
+ completion: parseChannelCompletion(serialized, request),
759
+ };
760
+ }
761
+ /** Only the bodies of a rejection and its answers carry a `reason`. */
762
+ function hasReason(payload) {
763
+ return Object.prototype.hasOwnProperty.call(payload, "reason");
764
+ }
765
+ function isReasonBody(payload, reason) {
766
+ return Object.keys(payload).length === 1 && payload.reason === reason;
442
767
  }
443
768
  function send(socket, envelope) {
444
769
  socket.send(JSON.stringify(envelope));
445
770
  }
446
771
  /** Pings the relay until the returned stop function runs. */
447
- function keepRelayAlive(socket) {
772
+ function keepRelayAlive(socket, onSilent) {
773
+ let deadline;
448
774
  const timer = setInterval(() => {
449
775
  try {
450
776
  socket.send(RELAY_KEEPALIVE_PING);
@@ -452,8 +778,19 @@ function keepRelayAlive(socket) {
452
778
  catch {
453
779
  // A socket that cannot send is closing; its close and error listeners report the failure.
454
780
  }
781
+ if (onSilent) {
782
+ clearTimeout(deadline);
783
+ deadline = setTimeout(onSilent, RELAY_PONG_TIMEOUT_MS);
784
+ }
455
785
  }, RELAY_KEEPALIVE_INTERVAL_MS);
456
- return () => clearInterval(timer);
786
+ // Any frame proves the socket is alive, not only the pong. The socket type has no
787
+ // removeEventListener; once stopped, this listener only clears a cleared timer.
788
+ if (onSilent)
789
+ socket.addEventListener("message", () => clearTimeout(deadline));
790
+ return () => {
791
+ clearInterval(timer);
792
+ clearTimeout(deadline);
793
+ };
457
794
  }
458
795
  function isRelayKeepAliveReply(data) {
459
796
  return frameText(data) === RELAY_KEEPALIVE_PONG;
@@ -568,14 +905,14 @@ function base64ToBytes(value) {
568
905
  throw channelError("Enrollment channel payload is not valid base64.");
569
906
  }
570
907
  }
571
- function failChannel(socket, reject, finished, beforeReject) {
908
+ function failChannel(closeSocket, reject, finished, beforeReject) {
572
909
  let failed = false;
573
910
  return (reason) => {
574
911
  if (failed || finished())
575
912
  return;
576
913
  failed = true;
577
914
  beforeReject();
578
- socket.close();
915
+ closeSocket();
579
916
  reject(asChannelError(reason));
580
917
  };
581
918
  }
@@ -659,6 +996,8 @@ export const enrollmentChannelCryptoVectors = {
659
996
  const cipher = await makeCipher(sharedSecret, request);
660
997
  return encryptPayload(cipher, envelope, payload, nonce);
661
998
  },
999
+ /** The whole relay frame, as the channel sends it. */
1000
+ envelope: async (sharedSecret, request, envelope, payload, nonce) => JSON.stringify(await sealEnvelope(await makeCipher(sharedSecret, request), envelope, payload, nonce)),
662
1001
  };
663
1002
  function asChannelError(reason) {
664
1003
  return reason instanceof AgentIntentSdkError