@ledgerhq/agent-intent-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +333 -2
  3. package/dist/auth.d.ts +35 -0
  4. package/dist/auth.d.ts.map +1 -0
  5. package/dist/auth.js +366 -0
  6. package/dist/auth.js.map +1 -0
  7. package/dist/bytes.d.ts +7 -0
  8. package/dist/bytes.d.ts.map +1 -0
  9. package/dist/bytes.js +26 -0
  10. package/dist/bytes.js.map +1 -0
  11. package/dist/client.d.ts +34 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +149 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.d.ts.map +1 -0
  17. package/dist/completion.js +78 -0
  18. package/dist/completion.js.map +1 -0
  19. package/dist/enrollment.d.ts +54 -0
  20. package/dist/enrollment.d.ts.map +1 -0
  21. package/dist/enrollment.js +143 -0
  22. package/dist/enrollment.js.map +1 -0
  23. package/dist/enrollmentChannel.d.ts +85 -0
  24. package/dist/enrollmentChannel.d.ts.map +1 -0
  25. package/dist/enrollmentChannel.js +671 -0
  26. package/dist/enrollmentChannel.js.map +1 -0
  27. package/dist/fingerprint.d.ts +2 -0
  28. package/dist/fingerprint.d.ts.map +1 -0
  29. package/dist/fingerprint.js +36 -0
  30. package/dist/fingerprint.js.map +1 -0
  31. package/dist/identity.d.ts +13 -0
  32. package/dist/identity.d.ts.map +1 -0
  33. package/dist/identity.js +28 -0
  34. package/dist/identity.js.map +1 -0
  35. package/dist/index.d.ts +13 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +13 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/intentPage.d.ts +71 -0
  40. package/dist/intentPage.d.ts.map +1 -0
  41. package/dist/intentPage.js +103 -0
  42. package/dist/intentPage.js.map +1 -0
  43. package/dist/intents.d.ts +93 -0
  44. package/dist/intents.d.ts.map +1 -0
  45. package/dist/intents.js +294 -0
  46. package/dist/intents.js.map +1 -0
  47. package/dist/recovery.d.ts +67 -0
  48. package/dist/recovery.d.ts.map +1 -0
  49. package/dist/recovery.js +188 -0
  50. package/dist/recovery.js.map +1 -0
  51. package/dist/requestFields.d.ts +64 -0
  52. package/dist/requestFields.d.ts.map +1 -0
  53. package/dist/requestFields.js +230 -0
  54. package/dist/requestFields.js.map +1 -0
  55. package/dist/userAgent.d.ts +16 -0
  56. package/dist/userAgent.d.ts.map +1 -0
  57. package/dist/userAgent.js +53 -0
  58. package/dist/userAgent.js.map +1 -0
  59. package/package.json +66 -3
@@ -0,0 +1,671 @@
1
+ import { hkdf } from "@noble/hashes/hkdf.js";
2
+ import { sha256 } from "@noble/hashes/sha2.js";
3
+ import { AgentIntentSdkError, bytesToHex, concatBytes, hexToBytes } from "./bytes.js";
4
+ import { parseAgentEnrollmentCompletion } from "./completion.js";
5
+ import { AGENT_ENROLLMENT_CHANNEL_VERSION, agentEnrollmentSearch, canonicalAgentEnrollmentPayload, validateAgentEnrollment, } from "./enrollment.js";
6
+ import { createSoftwareAgentIdentity } from "./identity.js";
7
+ import { agentRecoverySearch, canonicalAgentRecoveryPayload, isAgentRecoveryRequest, parseAgentRecoveryCompletion, validateAgentRecovery, } from "./recovery.js";
8
+ const PROTOCOL_VERSION = 1;
9
+ const CHANNEL_DOMAIN = new TextEncoder().encode("agent-intent:enrollment-channel:v1");
10
+ // The Trustchain relay drops a client after 5 minutes without a frame sent to it. Its own
11
+ // WebSocket heartbeats and pong replies do not count, but it answers a text "ping" with a
12
+ // text "pong" to the sender only, so each side sends one well inside that window.
13
+ const RELAY_KEEPALIVE_INTERVAL_MS = 60_000;
14
+ const RELAY_KEEPALIVE_PING = "ping";
15
+ const RELAY_KEEPALIVE_PONG = "pong";
16
+ export const AGENT_ENROLLMENT_CHANNEL_DEFAULT_TIMEOUTS = {
17
+ candidateTimeoutMs: 15 * 60_000,
18
+ handshakeTimeoutMs: 30_000,
19
+ completionTimeoutMs: 15 * 60_000,
20
+ acknowledgementTimeoutMs: 30_000,
21
+ persistTimeoutMs: 30_000,
22
+ };
23
+ export function createAgentEnrollmentChannelHost(input) {
24
+ const identity = createSoftwareAgentIdentity();
25
+ const publisher = identity.publicKey;
26
+ const timeouts = resolveTimeouts(input.timeouts);
27
+ let used = false;
28
+ let closed = false;
29
+ let session;
30
+ return {
31
+ binding: { environment: input.environment, hostPublicKey: publisher },
32
+ waitForCompletion: ({ request, authenticate, persist }) => {
33
+ if (used)
34
+ throw channelError("This enrollment host session has already been used.");
35
+ if (closed)
36
+ throw channelError("This enrollment host session has been closed.");
37
+ if (typeof authenticate !== "function" || typeof persist !== "function") {
38
+ throw channelError("Enrollment completion authentication and persistence are required.");
39
+ }
40
+ assertHostRequest(request, input.environment, publisher);
41
+ used = true;
42
+ let socket;
43
+ try {
44
+ socket = socketFactory(input.webSocketFactory)(relayUrl(input.relayBaseUrl, publisher));
45
+ }
46
+ catch (error) {
47
+ return Promise.reject(asChannelError(error));
48
+ }
49
+ session = runHost(socket, identity, request, authenticate, persist, timeouts);
50
+ return session.completion;
51
+ },
52
+ close: () => {
53
+ closed = true;
54
+ session?.close();
55
+ },
56
+ };
57
+ }
58
+ export function createAgentEnrollmentChannelCandidate(input) {
59
+ assertCandidateRequest(input.request, input.now ?? new Date());
60
+ const timeouts = resolveTimeouts(input.timeouts);
61
+ let session;
62
+ let delivering = false;
63
+ let delivered = false;
64
+ let closed = false;
65
+ const assertUsable = () => {
66
+ if (delivered)
67
+ throw channelError("This enrollment completion has already been sent.");
68
+ if (closed)
69
+ throw channelError("This enrollment completion channel has been closed.");
70
+ assertCandidateRequest(input.request, new Date());
71
+ };
72
+ const connectSession = () => {
73
+ if (session === undefined || session.failed) {
74
+ try {
75
+ session = openCandidateSession(socketFactory(input.webSocketFactory)(relayUrl(input.relayBaseUrl, input.request.channel.hostPublicKey)), input.request, timeouts);
76
+ }
77
+ catch (error) {
78
+ return Promise.reject(asChannelError(error));
79
+ }
80
+ }
81
+ const active = session;
82
+ return active.ready.then(() => active);
83
+ };
84
+ return {
85
+ connect: () => {
86
+ assertUsable();
87
+ return connectSession().then(() => undefined);
88
+ },
89
+ deliver: (completionPayload) => {
90
+ if (delivering)
91
+ throw channelError("This enrollment completion is already being sent.");
92
+ assertUsable();
93
+ delivering = true;
94
+ return connectSession()
95
+ .then((active) => active.deliver(completionPayload))
96
+ .then(() => {
97
+ delivered = true;
98
+ })
99
+ .finally(() => {
100
+ delivering = false;
101
+ });
102
+ },
103
+ close: () => {
104
+ closed = true;
105
+ session?.close();
106
+ },
107
+ };
108
+ }
109
+ function runHost(socket, identity, request, authenticate, persist, timeouts) {
110
+ let close = () => undefined;
111
+ const completion = new Promise((resolve, reject) => {
112
+ let state = "connected";
113
+ let peer = "";
114
+ let cipher;
115
+ let challenge = "";
116
+ let phaseTimer;
117
+ let completionTimer;
118
+ let stopKeepAlive = () => undefined;
119
+ let messageQueue = Promise.resolve();
120
+ const fail = failChannel(socket, reject, () => state === "finished", () => {
121
+ state = "finished";
122
+ clearTimeout(phaseTimer);
123
+ clearTimeout(completionTimer);
124
+ stopKeepAlive();
125
+ });
126
+ const armCandidateTimer = () => {
127
+ clearTimeout(phaseTimer);
128
+ phaseTimer = deadlineTimer(timeouts.candidateTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment channel timed out waiting for the frontend candidate.")));
129
+ };
130
+ const armHandshakeTimer = () => {
131
+ clearTimeout(phaseTimer);
132
+ phaseTimer = deadlineTimer(timeouts.handshakeTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment channel handshake timed out.")));
133
+ };
134
+ completionTimer = deadlineTimer(timeouts.completionTimeoutMs, request.expiresAt, () => fail(channelError("Enrollment completion timed out.")));
135
+ const resetCandidate = () => {
136
+ if (state === "finished")
137
+ return;
138
+ clearTimeout(phaseTimer);
139
+ state = "connected";
140
+ peer = "";
141
+ cipher = undefined;
142
+ challenge = "";
143
+ armCandidateTimer();
144
+ };
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
+ }
156
+ }
157
+ resetCandidate();
158
+ if (!(reason instanceof AgentIntentSdkError)) {
159
+ // Normalize callback failures without exposing their potentially sensitive details.
160
+ asChannelError(reason);
161
+ }
162
+ };
163
+ // Stops timers and keepalive itself rather than relying on the socket's close event.
164
+ close = () => fail(channelError("This enrollment host session has been closed."));
165
+ 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))
174
+ return;
175
+ messageQueue = messageQueue
176
+ .then(async () => {
177
+ const envelope = parseEnvelope(event.data);
178
+ if (envelope.message === "Failure")
179
+ 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.
182
+ if (envelope.message === "InitiateHandshake" &&
183
+ (state === "connected" || state === "challenged" || state === "authenticated")) {
184
+ const candidatePublicKey = stringField(envelope.payload, "ephemeral_public_key");
185
+ if (candidatePublicKey.toLowerCase() !== envelope.publisher.toLowerCase()) {
186
+ throw channelError("Enrollment channel publisher does not match its ephemeral key.");
187
+ }
188
+ peer = envelope.publisher.toLowerCase();
189
+ state = "challenged";
190
+ armHandshakeTimer();
191
+ cipher = await makeCipher(identity.deriveSharedSecret(hexToBytes(candidatePublicKey)), request);
192
+ challenge = randomDigits(6);
193
+ await sendEncrypted(socket, identity.publicKey, "HandshakeChallenge", cipher, request, {
194
+ digits: challenge,
195
+ connected: false,
196
+ });
197
+ return;
198
+ }
199
+ assertPeer(envelope, peer);
200
+ if (state === "challenged" && envelope.message === "CompleteHandshakeChallenge") {
201
+ const activeCipher = requireCipher(cipher);
202
+ const answer = await decryptPayload(activeCipher, envelope, request);
203
+ if (stringField(answer, "digits") !== challenge) {
204
+ throw channelError("Enrollment channel key confirmation failed.");
205
+ }
206
+ await sendEncrypted(socket, identity.publicKey, "HandshakeCompletionSucceeded", activeCipher, request, {});
207
+ clearTimeout(phaseTimer);
208
+ state = "authenticated";
209
+ return;
210
+ }
211
+ if (state === "authenticated" && envelope.message === "TrustchainShareCredential") {
212
+ state = "authenticating";
213
+ const activeCipher = requireCipher(cipher);
214
+ const payload = await decryptPayload(activeCipher, envelope, request);
215
+ const serialized = stringField(payload, "completion");
216
+ const completion = parseChannelCompletion(serialized, request);
217
+ try {
218
+ await withinDeadline(() => authenticate(completion), timeouts.persistTimeoutMs, request.expiresAt, "Enrollment completion authentication timed out.");
219
+ }
220
+ catch (error) {
221
+ await rejectCandidate(error);
222
+ return;
223
+ }
224
+ state = "persisting";
225
+ await withinDeadline(() => persist(completion), timeouts.persistTimeoutMs, request.expiresAt, "Enrollment completion persistence timed out.");
226
+ await sendEncrypted(socket, identity.publicKey, "TrustchainAddedMember", activeCipher, request, {
227
+ acknowledged: true,
228
+ digest: completionDigest(serialized),
229
+ });
230
+ state = "finished";
231
+ clearTimeout(completionTimer);
232
+ clearTimeout(phaseTimer);
233
+ stopKeepAlive();
234
+ socket.close();
235
+ resolve(completion);
236
+ return;
237
+ }
238
+ throw channelError(`Unexpected ${envelope.message} enrollment channel message.`);
239
+ })
240
+ .catch(async (error) => {
241
+ if (state === "persisting" || state === "finished") {
242
+ fail(error);
243
+ return;
244
+ }
245
+ await rejectCandidate(error);
246
+ });
247
+ });
248
+ });
249
+ return { completion, close: () => close() };
250
+ }
251
+ function openCandidateSession(socket, request, timeouts) {
252
+ // Each session uses its own ephemeral key so a reconnect never shares a channel key.
253
+ const identity = createSoftwareAgentIdentity();
254
+ const publisher = identity.publicKey;
255
+ let state = "connecting";
256
+ let cipher;
257
+ let failure;
258
+ let phaseTimer;
259
+ let stopKeepAlive = () => undefined;
260
+ let messageQueue = Promise.resolve();
261
+ let delivery;
262
+ let resolveReady = () => undefined;
263
+ let rejectReady = () => undefined;
264
+ const ready = new Promise((resolve, reject) => {
265
+ resolveReady = resolve;
266
+ rejectReady = reject;
267
+ });
268
+ // Callers observe failures through connect()/deliver(); an idle session must not leak a rejection.
269
+ ready.catch(() => undefined);
270
+ const fail = failChannel(socket, (error) => {
271
+ failure = asChannelError(error);
272
+ rejectReady(failure);
273
+ delivery?.reject(failure);
274
+ }, () => state === "finished", () => {
275
+ state = "failed";
276
+ clearTimeout(phaseTimer);
277
+ clearTimeout(sessionTimer);
278
+ stopKeepAlive();
279
+ });
280
+ // 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.")));
285
+ socket.addEventListener("open", () => {
286
+ if (state !== "connecting")
287
+ return;
288
+ try {
289
+ send(socket, {
290
+ version: PROTOCOL_VERSION,
291
+ publisher,
292
+ message: "InitiateHandshake",
293
+ payload: { ephemeral_public_key: publisher },
294
+ });
295
+ state = "initiated";
296
+ stopKeepAlive = keepRelayAlive(socket);
297
+ }
298
+ catch (error) {
299
+ fail(error);
300
+ }
301
+ });
302
+ socket.addEventListener("message", (event) => {
303
+ if (isRelayKeepAliveReply(event.data))
304
+ return;
305
+ messageQueue = messageQueue
306
+ .then(async () => {
307
+ 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
+ }
311
+ 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.");
317
+ }
318
+ throw channelError("The enrollment relay rejected the session.");
319
+ }
320
+ if (state === "initiated" && envelope.message === "HandshakeChallenge") {
321
+ cipher = await makeCipher(identity.deriveSharedSecret(hexToBytes(request.channel.hostPublicKey)), request);
322
+ const challenge = await decryptPayload(cipher, envelope, request);
323
+ await sendEncrypted(socket, publisher, "CompleteHandshakeChallenge", cipher, request, {
324
+ digits: stringField(challenge, "digits"),
325
+ });
326
+ state = "confirmed";
327
+ return;
328
+ }
329
+ if (state === "confirmed" && envelope.message === "HandshakeCompletionSucceeded") {
330
+ await decryptPayload(requireCipher(cipher), envelope, request);
331
+ clearTimeout(phaseTimer);
332
+ state = "ready";
333
+ resolveReady();
334
+ return;
335
+ }
336
+ if (state === "sent" && envelope.message === "TrustchainAddedMember") {
337
+ const acknowledgement = await decryptPayload(cipher, envelope, request);
338
+ if (acknowledgement.acknowledged !== true ||
339
+ stringField(acknowledgement, "digest") !== delivery?.digest) {
340
+ throw channelError("Enrollment completion acknowledgement is invalid.");
341
+ }
342
+ state = "finished";
343
+ clearTimeout(phaseTimer);
344
+ clearTimeout(sessionTimer);
345
+ stopKeepAlive();
346
+ socket.close();
347
+ delivery.resolve();
348
+ return;
349
+ }
350
+ throw channelError(`Unexpected ${envelope.message} enrollment channel message.`);
351
+ })
352
+ .catch(fail);
353
+ });
354
+ return {
355
+ ready,
356
+ get failed() {
357
+ return state === "failed";
358
+ },
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);
372
+ }),
373
+ close: () => fail(channelError("This enrollment completion channel has been closed.")),
374
+ };
375
+ }
376
+ async function makeCipher(sharedSecret, request) {
377
+ const requestDigest = signedRequestDigest(request);
378
+ const keyBytes = deriveChannelKeyBytes(sharedSecret, requestDigest);
379
+ return {
380
+ key: await crypto.subtle.importKey("raw", toArrayBuffer(keyBytes), "AES-GCM", false, [
381
+ "encrypt",
382
+ "decrypt",
383
+ ]),
384
+ requestDigest,
385
+ };
386
+ }
387
+ async function encryptPayload(cipher, envelope, value, nonce = crypto.getRandomValues(new Uint8Array(12))) {
388
+ if (nonce.length !== 12)
389
+ throw channelError("Enrollment channel nonce must be 12 bytes.");
390
+ const plaintext = new TextEncoder().encode(JSON.stringify(value));
391
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
392
+ name: "AES-GCM",
393
+ iv: toArrayBuffer(nonce),
394
+ additionalData: toArrayBuffer(envelopeAad(envelope, cipher.requestDigest)),
395
+ }, cipher.key, plaintext));
396
+ return bytesToBase64(concatBytes(nonce, encrypted));
397
+ }
398
+ async function decryptPayload(cipher, envelope, request) {
399
+ if (!cipher)
400
+ throw channelError("Enrollment channel encryption is not initialized.");
401
+ if (!constantTimeEqual(cipher.requestDigest, signedRequestDigest(request))) {
402
+ throw channelError("Enrollment channel request binding changed.");
403
+ }
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);
410
+ if (blob.length <= 28)
411
+ throw channelError("Enrollment channel payload is malformed.");
412
+ try {
413
+ const plaintext = await crypto.subtle.decrypt({
414
+ name: "AES-GCM",
415
+ iv: blob.slice(0, 12),
416
+ additionalData: toArrayBuffer(envelopeAad(envelope, cipher.requestDigest)),
417
+ }, cipher.key, blob.slice(12));
418
+ const value = JSON.parse(new TextDecoder().decode(plaintext));
419
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
420
+ throw new Error("not an object");
421
+ }
422
+ return value;
423
+ }
424
+ catch {
425
+ throw channelError("Enrollment channel payload could not be authenticated.");
426
+ }
427
+ }
428
+ async function sendEncrypted(socket, publisher, message, cipher, request, payload) {
429
+ if (!constantTimeEqual(cipher.requestDigest, signedRequestDigest(request))) {
430
+ throw channelError("Enrollment channel request binding changed.");
431
+ }
432
+ const metadata = {
433
+ version: PROTOCOL_VERSION,
434
+ publisher: publisher.toLowerCase(),
435
+ message,
436
+ };
437
+ const encrypted = await encryptPayload(cipher, metadata, payload);
438
+ send(socket, {
439
+ ...metadata,
440
+ payload: { encrypted },
441
+ });
442
+ }
443
+ function send(socket, envelope) {
444
+ socket.send(JSON.stringify(envelope));
445
+ }
446
+ /** Pings the relay until the returned stop function runs. */
447
+ function keepRelayAlive(socket) {
448
+ const timer = setInterval(() => {
449
+ try {
450
+ socket.send(RELAY_KEEPALIVE_PING);
451
+ }
452
+ catch {
453
+ // A socket that cannot send is closing; its close and error listeners report the failure.
454
+ }
455
+ }, RELAY_KEEPALIVE_INTERVAL_MS);
456
+ return () => clearInterval(timer);
457
+ }
458
+ function isRelayKeepAliveReply(data) {
459
+ return frameText(data) === RELAY_KEEPALIVE_PONG;
460
+ }
461
+ function frameText(data) {
462
+ return typeof data === "string" ? data : String(data);
463
+ }
464
+ function parseEnvelope(data) {
465
+ let value;
466
+ try {
467
+ value = JSON.parse(frameText(data));
468
+ }
469
+ catch {
470
+ throw channelError("Enrollment relay returned invalid JSON.");
471
+ }
472
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
473
+ throw channelError("Enrollment relay returned an invalid message.");
474
+ }
475
+ const envelope = value;
476
+ if (envelope.version !== PROTOCOL_VERSION ||
477
+ typeof envelope.publisher !== "string" ||
478
+ !isRelayMessageName(envelope.message) ||
479
+ typeof envelope.payload !== "object" ||
480
+ envelope.payload === null ||
481
+ Array.isArray(envelope.payload)) {
482
+ throw channelError("Enrollment relay returned an invalid message.");
483
+ }
484
+ return envelope;
485
+ }
486
+ function stringField(value, field) {
487
+ const result = value[field];
488
+ if (typeof result !== "string" || result.length === 0) {
489
+ throw channelError(`Enrollment channel ${field} is missing.`);
490
+ }
491
+ return result;
492
+ }
493
+ function isRelayMessageName(value) {
494
+ return [
495
+ "InitiateHandshake",
496
+ "HandshakeChallenge",
497
+ "CompleteHandshakeChallenge",
498
+ "HandshakeCompletionSucceeded",
499
+ "TrustchainShareCredential",
500
+ "TrustchainAddedMember",
501
+ "Failure",
502
+ ].includes(String(value));
503
+ }
504
+ function assertPeer(envelope, expected) {
505
+ if (!expected || envelope.publisher.toLowerCase() !== expected) {
506
+ throw channelError("Enrollment channel peer changed during the session.");
507
+ }
508
+ }
509
+ function requireCipher(cipher) {
510
+ if (!cipher)
511
+ throw channelError("Enrollment channel encryption is not initialized.");
512
+ return cipher;
513
+ }
514
+ function relayUrl(baseUrl, hostPublicKey) {
515
+ const url = new URL("/v1/qr", baseUrl);
516
+ if (url.protocol === "https:")
517
+ url.protocol = "wss:";
518
+ else if (url.protocol === "http:")
519
+ url.protocol = "ws:";
520
+ else
521
+ throw channelError("Enrollment relay must use an HTTP or HTTPS base URL.");
522
+ url.searchParams.set("host", hostPublicKey);
523
+ return url.toString();
524
+ }
525
+ function socketFactory(factory) {
526
+ if (factory)
527
+ return factory;
528
+ if (typeof WebSocket === "undefined") {
529
+ throw channelError("This runtime does not provide WebSocket support.");
530
+ }
531
+ return (url) => new WebSocket(url);
532
+ }
533
+ function completionDigest(payload) {
534
+ return bytesToHex(sha256(new TextEncoder().encode(payload)));
535
+ }
536
+ function signedRequestDigest(request) {
537
+ return sha256(concatBytes(isAgentRecoveryRequest(request)
538
+ ? canonicalAgentRecoveryPayload(request)
539
+ : canonicalAgentEnrollmentPayload(request), new Uint8Array([0]), hexToBytes(request.signature)));
540
+ }
541
+ function deriveChannelKeyBytes(sharedSecret, requestDigest) {
542
+ return hkdf(sha256, sharedSecret, requestDigest, CHANNEL_DOMAIN, 32);
543
+ }
544
+ function envelopeAad(envelope, requestDigest) {
545
+ return new TextEncoder().encode(JSON.stringify({
546
+ domain: "agent-intent:enrollment-channel:aad:v1",
547
+ requestDigest: bytesToHex(requestDigest),
548
+ version: envelope.version,
549
+ publisher: envelope.publisher,
550
+ message: envelope.message,
551
+ }));
552
+ }
553
+ function randomDigits(length) {
554
+ return Array.from(crypto.getRandomValues(new Uint8Array(length)), (byte) => byte % 10).join("");
555
+ }
556
+ function bytesToBase64(value) {
557
+ let binary = "";
558
+ for (const byte of value)
559
+ binary += String.fromCharCode(byte);
560
+ return btoa(binary);
561
+ }
562
+ function base64ToBytes(value) {
563
+ try {
564
+ const binary = atob(value);
565
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
566
+ }
567
+ catch {
568
+ throw channelError("Enrollment channel payload is not valid base64.");
569
+ }
570
+ }
571
+ function failChannel(socket, reject, finished, beforeReject) {
572
+ let failed = false;
573
+ return (reason) => {
574
+ if (failed || finished())
575
+ return;
576
+ failed = true;
577
+ beforeReject();
578
+ socket.close();
579
+ reject(asChannelError(reason));
580
+ };
581
+ }
582
+ function assertHostRequest(request, environment, hostPublicKey) {
583
+ assertCandidateRequest(request, new Date());
584
+ if (request.channel.environment !== environment ||
585
+ request.channel.hostPublicKey.toLowerCase() !== hostPublicKey.toLowerCase()) {
586
+ throw channelError("The signed enrollment request does not belong to this host.");
587
+ }
588
+ }
589
+ function assertCandidateRequest(request, now) {
590
+ const recovery = isAgentRecoveryRequest(request);
591
+ if ((!recovery && request.version !== AGENT_ENROLLMENT_CHANNEL_VERSION) ||
592
+ request.channel === undefined) {
593
+ throw channelError("Automatic completion requires an enrollment channel request.");
594
+ }
595
+ const validation = recovery
596
+ ? validateAgentRecovery(agentRecoverySearch(request), now)
597
+ : validateAgentEnrollment(agentEnrollmentSearch(request), now);
598
+ if (validation.status === "invalid") {
599
+ throw channelError(validation.reason === "expired"
600
+ ? "The enrollment channel has expired."
601
+ : "The enrollment channel request is not authentic.");
602
+ }
603
+ }
604
+ function parseChannelCompletion(serialized, request) {
605
+ if (isAgentRecoveryRequest(request)) {
606
+ return parseAgentRecoveryCompletion(serialized, request.publicKey, request.previousTrustchainId, request.signature);
607
+ }
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;
613
+ }
614
+ function resolveTimeouts(timeouts) {
615
+ const resolved = { ...AGENT_ENROLLMENT_CHANNEL_DEFAULT_TIMEOUTS, ...timeouts };
616
+ for (const [name, value] of Object.entries(resolved)) {
617
+ if (!Number.isSafeInteger(value) || value <= 0) {
618
+ throw channelError(`${name} must be a positive integer number of milliseconds.`);
619
+ }
620
+ }
621
+ return resolved;
622
+ }
623
+ function deadlineTimer(timeoutMs, expiresAt, onTimeout) {
624
+ const remaining = Date.parse(expiresAt) - Date.now();
625
+ return setTimeout(onTimeout, Math.max(0, Math.min(timeoutMs, remaining)));
626
+ }
627
+ async function withinDeadline(operation, timeoutMs, expiresAt, message) {
628
+ return await new Promise((resolve, reject) => {
629
+ const timer = deadlineTimer(timeoutMs, expiresAt, () => reject(channelError(message)));
630
+ void Promise.resolve()
631
+ .then(operation)
632
+ .then((value) => {
633
+ clearTimeout(timer);
634
+ resolve(value);
635
+ }, (error) => {
636
+ clearTimeout(timer);
637
+ reject(error);
638
+ });
639
+ });
640
+ }
641
+ function constantTimeEqual(left, right) {
642
+ if (left.length !== right.length)
643
+ return false;
644
+ let difference = 0;
645
+ for (let index = 0; index < left.length; index += 1) {
646
+ difference |= left[index] ^ right[index];
647
+ }
648
+ return difference === 0;
649
+ }
650
+ function toArrayBuffer(value) {
651
+ return Uint8Array.from(value).buffer;
652
+ }
653
+ /** @internal Protocol-vector helpers. Not exported from the package root. */
654
+ export const enrollmentChannelCryptoVectors = {
655
+ signedRequestDigest: (request) => bytesToHex(signedRequestDigest(request)),
656
+ deriveKey: (sharedSecret, request) => bytesToHex(deriveChannelKeyBytes(sharedSecret, signedRequestDigest(request))),
657
+ aad: (request, envelope) => new TextDecoder().decode(envelopeAad(envelope, signedRequestDigest(request))),
658
+ encrypt: async (sharedSecret, request, envelope, payload, nonce) => {
659
+ const cipher = await makeCipher(sharedSecret, request);
660
+ return encryptPayload(cipher, envelope, payload, nonce);
661
+ },
662
+ };
663
+ function asChannelError(reason) {
664
+ return reason instanceof AgentIntentSdkError
665
+ ? reason
666
+ : channelError(reason instanceof Error ? reason.message : "Enrollment channel failed.");
667
+ }
668
+ function channelError(message) {
669
+ return new AgentIntentSdkError(message);
670
+ }
671
+ //# sourceMappingURL=enrollmentChannel.js.map