@dxos/edge-client 0.6.13 → 0.6.14-main.69511f5

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 (61) hide show
  1. package/dist/lib/browser/chunk-ZWJXA37R.mjs +113 -0
  2. package/dist/lib/browser/chunk-ZWJXA37R.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +469 -160
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +125 -0
  7. package/dist/lib/browser/testing/index.mjs.map +7 -0
  8. package/dist/lib/node/chunk-ANV2HBEH.cjs +136 -0
  9. package/dist/lib/node/chunk-ANV2HBEH.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +468 -158
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +155 -0
  14. package/dist/lib/node/testing/index.cjs.map +7 -0
  15. package/dist/lib/node-esm/chunk-HNVT57AU.mjs +115 -0
  16. package/dist/lib/node-esm/chunk-HNVT57AU.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +787 -0
  18. package/dist/lib/node-esm/index.mjs.map +7 -0
  19. package/dist/lib/node-esm/meta.json +1 -0
  20. package/dist/lib/node-esm/testing/index.mjs +126 -0
  21. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  22. package/dist/types/src/auth.d.ts +22 -0
  23. package/dist/types/src/auth.d.ts.map +1 -0
  24. package/dist/types/src/defs.d.ts.map +1 -1
  25. package/dist/types/src/edge-client.d.ts +14 -13
  26. package/dist/types/src/edge-client.d.ts.map +1 -1
  27. package/dist/types/src/edge-http-client.d.ts +48 -0
  28. package/dist/types/src/edge-http-client.d.ts.map +1 -0
  29. package/dist/types/src/edge-identity.d.ts +15 -0
  30. package/dist/types/src/edge-identity.d.ts.map +1 -0
  31. package/dist/types/src/errors.d.ts +4 -1
  32. package/dist/types/src/errors.d.ts.map +1 -1
  33. package/dist/types/src/index.d.ts +4 -0
  34. package/dist/types/src/index.d.ts.map +1 -1
  35. package/dist/types/src/protocol.d.ts +2 -2
  36. package/dist/types/src/protocol.d.ts.map +1 -1
  37. package/dist/types/src/testing/index.d.ts +2 -0
  38. package/dist/types/src/testing/index.d.ts.map +1 -0
  39. package/dist/types/src/testing/test-utils.d.ts +21 -0
  40. package/dist/types/src/testing/test-utils.d.ts.map +1 -0
  41. package/dist/types/src/utils.d.ts +2 -0
  42. package/dist/types/src/utils.d.ts.map +1 -0
  43. package/package.json +27 -17
  44. package/src/auth.ts +135 -0
  45. package/src/defs.ts +2 -3
  46. package/src/edge-client.test.ts +50 -18
  47. package/src/edge-client.ts +76 -24
  48. package/src/edge-http-client.ts +210 -0
  49. package/src/edge-identity.ts +31 -0
  50. package/src/errors.ts +8 -2
  51. package/src/index.ts +4 -0
  52. package/src/persistent-lifecycle.test.ts +2 -2
  53. package/src/protocol.test.ts +1 -2
  54. package/src/protocol.ts +2 -2
  55. package/src/testing/index.ts +5 -0
  56. package/src/testing/test-utils.ts +114 -0
  57. package/src/utils.ts +10 -0
  58. package/src/websocket.test.ts +5 -4
  59. package/dist/types/src/test-utils.d.ts +0 -11
  60. package/dist/types/src/test-utils.d.ts.map +0 -1
  61. package/src/test-utils.ts +0 -49
@@ -0,0 +1,787 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+ import {
3
+ Protocol,
4
+ getTypename,
5
+ protocol,
6
+ toUint8Array
7
+ } from "./chunk-HNVT57AU.mjs";
8
+
9
+ // packages/core/mesh/edge-client/src/index.ts
10
+ export * from "@dxos/protocols/buf/dxos/edge/messenger_pb";
11
+
12
+ // packages/core/mesh/edge-client/src/edge-client.ts
13
+ import WebSocket from "isomorphic-ws";
14
+ import { Trigger, Event, scheduleTaskInterval, scheduleTask, TriggerState } from "@dxos/async";
15
+ import { Context, LifecycleState as LifecycleState2, Resource as Resource2 } from "@dxos/context";
16
+ import { log as log2 } from "@dxos/log";
17
+ import { buf } from "@dxos/protocols/buf";
18
+ import { MessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
19
+
20
+ // packages/core/mesh/edge-client/src/edge-identity.ts
21
+ import { invariant } from "@dxos/invariant";
22
+ import { schema } from "@dxos/protocols/proto";
23
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-identity.ts";
24
+ var handleAuthChallenge = async (failedResponse, identity) => {
25
+ invariant(failedResponse.status === 401, void 0, {
26
+ F: __dxlog_file,
27
+ L: 21,
28
+ S: void 0,
29
+ A: [
30
+ "failedResponse.status === 401",
31
+ ""
32
+ ]
33
+ });
34
+ const headerValue = failedResponse.headers.get("Www-Authenticate");
35
+ invariant(headerValue?.startsWith("VerifiablePresentation challenge="), void 0, {
36
+ F: __dxlog_file,
37
+ L: 24,
38
+ S: void 0,
39
+ A: [
40
+ "headerValue?.startsWith('VerifiablePresentation challenge=')",
41
+ ""
42
+ ]
43
+ });
44
+ const challenge = headerValue?.slice("VerifiablePresentation challenge=".length);
45
+ invariant(challenge, void 0, {
46
+ F: __dxlog_file,
47
+ L: 27,
48
+ S: void 0,
49
+ A: [
50
+ "challenge",
51
+ ""
52
+ ]
53
+ });
54
+ const presentation = await identity.presentCredentials({
55
+ challenge: Buffer.from(challenge, "base64")
56
+ });
57
+ return schema.getCodecForType("dxos.halo.credentials.Presentation").encode(presentation);
58
+ };
59
+
60
+ // packages/core/mesh/edge-client/src/errors.ts
61
+ var EdgeConnectionClosedError = class extends Error {
62
+ constructor() {
63
+ super("Edge connection closed.");
64
+ }
65
+ };
66
+ var EdgeIdentityChangedError = class extends Error {
67
+ constructor() {
68
+ super("Edge identity changed.");
69
+ }
70
+ };
71
+
72
+ // packages/core/mesh/edge-client/src/persistent-lifecycle.ts
73
+ import { DeferredTask, sleep, synchronized } from "@dxos/async";
74
+ import { cancelWithContext, LifecycleState, Resource } from "@dxos/context";
75
+ import { warnAfterTimeout } from "@dxos/debug";
76
+ import { log } from "@dxos/log";
77
+ function _ts_decorate(decorators, target, key, desc) {
78
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
79
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
80
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
81
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
82
+ }
83
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/persistent-lifecycle.ts";
84
+ var INIT_RESTART_DELAY = 100;
85
+ var DEFAULT_MAX_RESTART_DELAY = 5e3;
86
+ var PersistentLifecycle = class extends Resource {
87
+ constructor({ start, stop, onRestart, maxRestartDelay = DEFAULT_MAX_RESTART_DELAY }) {
88
+ super();
89
+ this._restartTask = void 0;
90
+ this._restartAfter = 0;
91
+ this._start = start;
92
+ this._stop = stop;
93
+ this._onRestart = onRestart;
94
+ this._maxRestartDelay = maxRestartDelay;
95
+ }
96
+ async _open() {
97
+ this._restartTask = new DeferredTask(this._ctx, async () => {
98
+ try {
99
+ await this._restart();
100
+ } catch (err) {
101
+ log.warn("Restart failed", {
102
+ err
103
+ }, {
104
+ F: __dxlog_file2,
105
+ L: 64,
106
+ S: this,
107
+ C: (f, a) => f(...a)
108
+ });
109
+ this._restartTask?.schedule();
110
+ }
111
+ });
112
+ await this._start().catch((err) => {
113
+ log.warn("Start failed", {
114
+ err
115
+ }, {
116
+ F: __dxlog_file2,
117
+ L: 69,
118
+ S: this,
119
+ C: (f, a) => f(...a)
120
+ });
121
+ this._restartTask?.schedule();
122
+ });
123
+ }
124
+ async _close() {
125
+ await this._restartTask?.join();
126
+ await this._stop();
127
+ this._restartTask = void 0;
128
+ }
129
+ async _restart() {
130
+ log(`restarting in ${this._restartAfter}ms`, {
131
+ state: this._lifecycleState
132
+ }, {
133
+ F: __dxlog_file2,
134
+ L: 81,
135
+ S: this,
136
+ C: (f, a) => f(...a)
137
+ });
138
+ await this._stop();
139
+ if (this._lifecycleState !== LifecycleState.OPEN) {
140
+ return;
141
+ }
142
+ await cancelWithContext(this._ctx, sleep(this._restartAfter));
143
+ this._restartAfter = Math.min(Math.max(this._restartAfter * 2, INIT_RESTART_DELAY), this._maxRestartDelay);
144
+ await warnAfterTimeout(5e3, "Connection establishment takes too long", () => this._start());
145
+ this._restartAfter = 0;
146
+ await this._onRestart?.();
147
+ }
148
+ /**
149
+ * Scheduling restart should be done from outside.
150
+ */
151
+ scheduleRestart() {
152
+ if (this._lifecycleState !== LifecycleState.OPEN) {
153
+ return;
154
+ }
155
+ this._restartTask.schedule();
156
+ }
157
+ };
158
+ _ts_decorate([
159
+ synchronized
160
+ ], PersistentLifecycle.prototype, "_open", null);
161
+ _ts_decorate([
162
+ synchronized
163
+ ], PersistentLifecycle.prototype, "scheduleRestart", null);
164
+
165
+ // packages/core/mesh/edge-client/src/utils.ts
166
+ var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
167
+ const isSecure = baseUrl.startsWith("https") || baseUrl.startsWith("wss");
168
+ const url = new URL(baseUrl);
169
+ url.protocol = protocol2 + (isSecure ? "s" : "");
170
+ return url.toString();
171
+ };
172
+
173
+ // packages/core/mesh/edge-client/src/edge-client.ts
174
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
175
+ var DEFAULT_TIMEOUT = 1e4;
176
+ var SIGNAL_KEEPALIVE_INTERVAL = 5e3;
177
+ var EdgeClient = class extends Resource2 {
178
+ constructor(_identity, _config) {
179
+ super();
180
+ this._identity = _identity;
181
+ this._config = _config;
182
+ this.reconnect = new Event();
183
+ this.connected = new Event();
184
+ this._persistentLifecycle = new PersistentLifecycle({
185
+ start: async () => this._openWebSocket(),
186
+ stop: async () => this._closeWebSocket(),
187
+ onRestart: async () => this.reconnect.emit()
188
+ });
189
+ this._listeners = /* @__PURE__ */ new Set();
190
+ this._ready = new Trigger();
191
+ this._ws = void 0;
192
+ this._keepaliveCtx = void 0;
193
+ this._heartBeatContext = void 0;
194
+ this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
195
+ this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
196
+ }
197
+ // TODO(burdon): Attach logging.
198
+ get info() {
199
+ return {
200
+ open: this.isOpen,
201
+ identity: this._identity.identityKey,
202
+ device: this._identity.peerKey
203
+ };
204
+ }
205
+ get isConnected() {
206
+ return Boolean(this._ws) && this._ready.state === TriggerState.RESOLVED;
207
+ }
208
+ get identityKey() {
209
+ return this._identity.identityKey;
210
+ }
211
+ get peerKey() {
212
+ return this._identity.peerKey;
213
+ }
214
+ setIdentity(identity) {
215
+ if (identity.identityKey !== this._identity.identityKey || identity.peerKey !== this._identity.peerKey) {
216
+ log2("Edge identity changed", {
217
+ identity,
218
+ oldIdentity: this._identity
219
+ }, {
220
+ F: __dxlog_file3,
221
+ L: 99,
222
+ S: this,
223
+ C: (f, a) => f(...a)
224
+ });
225
+ this._identity = identity;
226
+ this._persistentLifecycle.scheduleRestart();
227
+ }
228
+ }
229
+ addListener(listener) {
230
+ this._listeners.add(listener);
231
+ return () => this._listeners.delete(listener);
232
+ }
233
+ /**
234
+ * Open connection to messaging service.
235
+ */
236
+ async _open() {
237
+ log2("opening...", {
238
+ info: this.info
239
+ }, {
240
+ F: __dxlog_file3,
241
+ L: 114,
242
+ S: this,
243
+ C: (f, a) => f(...a)
244
+ });
245
+ this._persistentLifecycle.open().catch((err) => {
246
+ log2.warn("Error while opening connection", {
247
+ err
248
+ }, {
249
+ F: __dxlog_file3,
250
+ L: 116,
251
+ S: this,
252
+ C: (f, a) => f(...a)
253
+ });
254
+ });
255
+ }
256
+ /**
257
+ * Close connection and free resources.
258
+ */
259
+ async _close() {
260
+ log2("closing...", {
261
+ peerKey: this._identity.peerKey
262
+ }, {
263
+ F: __dxlog_file3,
264
+ L: 124,
265
+ S: this,
266
+ C: (f, a) => f(...a)
267
+ });
268
+ await this._persistentLifecycle.close();
269
+ }
270
+ async _openWebSocket() {
271
+ if (this._ctx.disposed) {
272
+ return;
273
+ }
274
+ const path = `/ws/${this._identity.identityKey}/${this._identity.peerKey}`;
275
+ const protocolHeader = this._config.disableAuth ? void 0 : await this._createAuthHeader(path);
276
+ const url = new URL(path, this._baseWsUrl);
277
+ log2("Opening websocket", {
278
+ url: url.toString(),
279
+ protocolHeader
280
+ }, {
281
+ F: __dxlog_file3,
282
+ L: 136,
283
+ S: this,
284
+ C: (f, a) => f(...a)
285
+ });
286
+ this._ws = new WebSocket(url, protocolHeader ? [
287
+ protocolHeader
288
+ ] : []);
289
+ this._ws.onopen = () => {
290
+ log2("opened", this.info, {
291
+ F: __dxlog_file3,
292
+ L: 140,
293
+ S: this,
294
+ C: (f, a) => f(...a)
295
+ });
296
+ this._ready.wake();
297
+ this.connected.emit();
298
+ };
299
+ this._ws.onclose = () => {
300
+ log2("closed", this.info, {
301
+ F: __dxlog_file3,
302
+ L: 145,
303
+ S: this,
304
+ C: (f, a) => f(...a)
305
+ });
306
+ this._persistentLifecycle.scheduleRestart();
307
+ };
308
+ this._ws.onerror = (event) => {
309
+ log2.warn("EdgeClient socket error", {
310
+ error: event.error,
311
+ info: event.message
312
+ }, {
313
+ F: __dxlog_file3,
314
+ L: 149,
315
+ S: this,
316
+ C: (f, a) => f(...a)
317
+ });
318
+ this._persistentLifecycle.scheduleRestart();
319
+ };
320
+ this._ws.onmessage = async (event) => {
321
+ if (event.data === "__pong__") {
322
+ this._onHeartbeat();
323
+ return;
324
+ }
325
+ const data = await toUint8Array(event.data);
326
+ const message = buf.fromBinary(MessageSchema, data);
327
+ log2("received", {
328
+ peerKey: this._identity.peerKey,
329
+ payload: protocol.getPayloadType(message)
330
+ }, {
331
+ F: __dxlog_file3,
332
+ L: 162,
333
+ S: this,
334
+ C: (f, a) => f(...a)
335
+ });
336
+ if (message) {
337
+ for (const listener of this._listeners) {
338
+ try {
339
+ await listener(message);
340
+ } catch (err) {
341
+ log2.error("processing", {
342
+ err,
343
+ payload: protocol.getPayloadType(message)
344
+ }, {
345
+ F: __dxlog_file3,
346
+ L: 168,
347
+ S: this,
348
+ C: (f, a) => f(...a)
349
+ });
350
+ }
351
+ }
352
+ }
353
+ };
354
+ await this._ready.wait({
355
+ timeout: this._config.timeout ?? DEFAULT_TIMEOUT
356
+ });
357
+ log2("Websocket is ready", {
358
+ identity: this._identity.identityKey,
359
+ peer: this._identity.peerKey
360
+ }, {
361
+ F: __dxlog_file3,
362
+ L: 176,
363
+ S: this,
364
+ C: (f, a) => f(...a)
365
+ });
366
+ this._keepaliveCtx = new Context(void 0, {
367
+ F: __dxlog_file3,
368
+ L: 179
369
+ });
370
+ scheduleTaskInterval(this._keepaliveCtx, async () => {
371
+ this._ws?.send("__ping__");
372
+ }, SIGNAL_KEEPALIVE_INTERVAL);
373
+ this._ws.send("__ping__");
374
+ this._onHeartbeat();
375
+ }
376
+ async _closeWebSocket() {
377
+ if (!this._ws) {
378
+ return;
379
+ }
380
+ try {
381
+ this._ready.throw(this.isOpen ? new EdgeIdentityChangedError() : new EdgeConnectionClosedError());
382
+ this._ready.reset();
383
+ void this._keepaliveCtx?.dispose();
384
+ this._keepaliveCtx = void 0;
385
+ void this._heartBeatContext?.dispose();
386
+ this._heartBeatContext = void 0;
387
+ this._ws.onopen = () => {
388
+ };
389
+ this._ws.onclose = () => {
390
+ };
391
+ this._ws.onerror = () => {
392
+ };
393
+ this._ws.close();
394
+ this._ws = void 0;
395
+ } catch (err) {
396
+ if (err instanceof Error && err.message.includes("WebSocket is closed before the connection is established.")) {
397
+ return;
398
+ }
399
+ log2.warn("Error closing websocket", {
400
+ err
401
+ }, {
402
+ F: __dxlog_file3,
403
+ L: 215,
404
+ S: this,
405
+ C: (f, a) => f(...a)
406
+ });
407
+ }
408
+ }
409
+ /**
410
+ * Send message.
411
+ * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.
412
+ */
413
+ async send(message) {
414
+ if (this._ready.state !== TriggerState.RESOLVED) {
415
+ log2("waiting for websocket to become ready", void 0, {
416
+ F: __dxlog_file3,
417
+ L: 225,
418
+ S: this,
419
+ C: (f, a) => f(...a)
420
+ });
421
+ await this._ready.wait({
422
+ timeout: this._config.timeout ?? DEFAULT_TIMEOUT
423
+ });
424
+ }
425
+ if (!this._ws) {
426
+ throw new EdgeConnectionClosedError();
427
+ }
428
+ if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)) {
429
+ throw new EdgeIdentityChangedError();
430
+ }
431
+ log2("sending...", {
432
+ peerKey: this._identity.peerKey,
433
+ payload: protocol.getPayloadType(message)
434
+ }, {
435
+ F: __dxlog_file3,
436
+ L: 238,
437
+ S: this,
438
+ C: (f, a) => f(...a)
439
+ });
440
+ this._ws.send(buf.toBinary(MessageSchema, message));
441
+ }
442
+ _onHeartbeat() {
443
+ if (this._lifecycleState !== LifecycleState2.OPEN) {
444
+ return;
445
+ }
446
+ void this._heartBeatContext?.dispose();
447
+ this._heartBeatContext = new Context(void 0, {
448
+ F: __dxlog_file3,
449
+ L: 247
450
+ });
451
+ scheduleTask(this._heartBeatContext, () => {
452
+ this._persistentLifecycle.scheduleRestart();
453
+ }, 2 * SIGNAL_KEEPALIVE_INTERVAL);
454
+ }
455
+ async _createAuthHeader(path) {
456
+ const httpUrl = new URL(path, this._baseHttpUrl);
457
+ httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), "http");
458
+ const response = await fetch(httpUrl, {
459
+ method: "GET"
460
+ });
461
+ if (response.status === 401) {
462
+ return encodePresentationWsAuthHeader(await handleAuthChallenge(response, this._identity));
463
+ } else {
464
+ log2.warn("no auth challenge from edge", {
465
+ status: response.status,
466
+ statusText: response.statusText
467
+ }, {
468
+ F: __dxlog_file3,
469
+ L: 264,
470
+ S: this,
471
+ C: (f, a) => f(...a)
472
+ });
473
+ return void 0;
474
+ }
475
+ }
476
+ };
477
+ var encodePresentationWsAuthHeader = (encodedPresentation) => {
478
+ const encodedToken = Buffer.from(encodedPresentation).toString("base64").replace(/=*$/, "").replaceAll("/", "|");
479
+ return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
480
+ };
481
+
482
+ // packages/core/mesh/edge-client/src/auth.ts
483
+ import { createCredential, signPresentation } from "@dxos/credentials";
484
+ import { Keyring } from "@dxos/keyring";
485
+ import { PublicKey } from "@dxos/keys";
486
+ var createDeviceEdgeIdentity = async (signer, key) => {
487
+ return {
488
+ identityKey: key.toHex(),
489
+ peerKey: key.toHex(),
490
+ presentCredentials: async ({ challenge }) => {
491
+ return signPresentation({
492
+ presentation: {
493
+ credentials: [
494
+ // Verifier requires at least one credential in the presentation to establish the subject.
495
+ await createCredential({
496
+ assertion: {
497
+ "@type": "dxos.halo.credentials.Auth"
498
+ },
499
+ issuer: key,
500
+ subject: key,
501
+ signer
502
+ })
503
+ ]
504
+ },
505
+ signer,
506
+ signerKey: key,
507
+ nonce: challenge
508
+ });
509
+ }
510
+ };
511
+ };
512
+ var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
513
+ const credentialsToSign = credentials.length > 0 ? credentials : [
514
+ await createCredential({
515
+ assertion: {
516
+ "@type": "dxos.halo.credentials.Auth"
517
+ },
518
+ issuer: identityKey,
519
+ subject: identityKey,
520
+ signer,
521
+ chain,
522
+ signingKey: peerKey
523
+ })
524
+ ];
525
+ return {
526
+ identityKey: identityKey.toHex(),
527
+ peerKey: peerKey.toHex(),
528
+ presentCredentials: async ({ challenge }) => {
529
+ return signPresentation({
530
+ presentation: {
531
+ credentials: credentialsToSign
532
+ },
533
+ signer,
534
+ nonce: challenge,
535
+ signerKey: peerKey,
536
+ chain
537
+ });
538
+ }
539
+ };
540
+ };
541
+ var createEphemeralEdgeIdentity = async () => {
542
+ const keyring = new Keyring();
543
+ const key = await keyring.createKey();
544
+ return createDeviceEdgeIdentity(keyring, key);
545
+ };
546
+ var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
547
+ const deviceAdmission = await createCredential({
548
+ assertion: {
549
+ "@type": "dxos.halo.credentials.AuthorizedDevice",
550
+ deviceKey,
551
+ identityKey
552
+ },
553
+ issuer: identityKey,
554
+ subject: deviceKey,
555
+ signer
556
+ });
557
+ return createChainEdgeIdentity(signer, identityKey, deviceKey, {
558
+ credential: deviceAdmission
559
+ }, [
560
+ await createCredential({
561
+ assertion: {
562
+ "@type": "dxos.halo.credentials.Auth"
563
+ },
564
+ issuer: identityKey,
565
+ subject: identityKey,
566
+ signer
567
+ })
568
+ ]);
569
+ };
570
+ var createStubEdgeIdentity = () => {
571
+ const identityKey = PublicKey.random();
572
+ const deviceKey = PublicKey.random();
573
+ return {
574
+ identityKey: identityKey.toHex(),
575
+ peerKey: deviceKey.toHex(),
576
+ presentCredentials: async () => {
577
+ throw new Error("Stub identity does not support authentication.");
578
+ }
579
+ };
580
+ };
581
+
582
+ // packages/core/mesh/edge-client/src/edge-http-client.ts
583
+ import { sleep as sleep2 } from "@dxos/async";
584
+ import { Context as Context2 } from "@dxos/context";
585
+ import { log as log3 } from "@dxos/log";
586
+ import { EdgeCallFailedError, EdgeAuthChallengeError } from "@dxos/protocols";
587
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
588
+ var DEFAULT_RETRY_TIMEOUT = 1500;
589
+ var DEFAULT_RETRY_JITTER = 500;
590
+ var DEFAULT_MAX_RETRIES_COUNT = 3;
591
+ var EdgeHttpClient = class {
592
+ constructor(baseUrl) {
593
+ this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
594
+ log3("created", {
595
+ url: this._baseUrl
596
+ }, {
597
+ F: __dxlog_file4,
598
+ L: 42,
599
+ S: this,
600
+ C: (f, a) => f(...a)
601
+ });
602
+ }
603
+ setIdentity(identity) {
604
+ this._edgeIdentity = identity;
605
+ }
606
+ createAgent(body, args) {
607
+ return this._call("/agents/create", {
608
+ ...args,
609
+ method: "POST",
610
+ body
611
+ });
612
+ }
613
+ getAgentStatus(request, args) {
614
+ return this._call(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, {
615
+ ...args,
616
+ method: "GET"
617
+ });
618
+ }
619
+ getCredentialsForNotarization(spaceId, args) {
620
+ return this._call(`/spaces/${spaceId}/notarization`, {
621
+ ...args,
622
+ method: "GET"
623
+ });
624
+ }
625
+ async notarizeCredentials(spaceId, body, args) {
626
+ await this._call(`/spaces/${spaceId}/notarization`, {
627
+ ...args,
628
+ body,
629
+ method: "POST"
630
+ });
631
+ }
632
+ async joinSpaceByInvitation(spaceId, body, args) {
633
+ return this._call(`/spaces/${spaceId}/join`, {
634
+ ...args,
635
+ body,
636
+ method: "POST"
637
+ });
638
+ }
639
+ async recoverIdentity(body, args) {
640
+ return this._call("/identity/recover", {
641
+ ...args,
642
+ body,
643
+ method: "POST"
644
+ });
645
+ }
646
+ async _call(path, args) {
647
+ const requestContext = args.context ?? new Context2(void 0, {
648
+ F: __dxlog_file4,
649
+ L: 88
650
+ });
651
+ const shouldRetry = createRetryHandler(args);
652
+ const url = `${this._baseUrl}${path.startsWith("/") ? path.slice(1) : path}`;
653
+ log3.info("call", {
654
+ method: args.method,
655
+ path,
656
+ request: args.body
657
+ }, {
658
+ F: __dxlog_file4,
659
+ L: 92,
660
+ S: this,
661
+ C: (f, a) => f(...a)
662
+ });
663
+ let handledAuth = false;
664
+ let authHeader = this._authHeader;
665
+ while (true) {
666
+ let processingError;
667
+ let retryAfterHeaderValue = Number.NaN;
668
+ try {
669
+ const request = createRequest(args, authHeader);
670
+ const response = await fetch(url, request);
671
+ retryAfterHeaderValue = Number(response.headers.get("Retry-After"));
672
+ if (response.ok) {
673
+ const body = await response.json();
674
+ if (body.success) {
675
+ return body.data;
676
+ }
677
+ log3.info("unsuccessful edge response", {
678
+ path,
679
+ body
680
+ }, {
681
+ F: __dxlog_file4,
682
+ L: 111,
683
+ S: this,
684
+ C: (f, a) => f(...a)
685
+ });
686
+ if (body.errorData?.type === "auth_challenge" && typeof body.errorData?.challenge === "string") {
687
+ processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
688
+ } else {
689
+ processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
690
+ }
691
+ } else if (response.status === 401 && !handledAuth) {
692
+ authHeader = await this._handleUnauthorized(response);
693
+ handledAuth = true;
694
+ continue;
695
+ } else {
696
+ processingError = EdgeCallFailedError.fromHttpFailure(response);
697
+ }
698
+ } catch (error) {
699
+ processingError = EdgeCallFailedError.fromProcessingFailureCause(error);
700
+ }
701
+ if (processingError.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
702
+ log3.info("retrying edge request", {
703
+ path,
704
+ processingError
705
+ }, {
706
+ F: __dxlog_file4,
707
+ L: 130,
708
+ S: this,
709
+ C: (f, a) => f(...a)
710
+ });
711
+ } else {
712
+ throw processingError;
713
+ }
714
+ }
715
+ }
716
+ async _handleUnauthorized(response) {
717
+ if (!this._edgeIdentity) {
718
+ log3.warn("edge unauthorized response received before identity was set", void 0, {
719
+ F: __dxlog_file4,
720
+ L: 139,
721
+ S: this,
722
+ C: (f, a) => f(...a)
723
+ });
724
+ throw EdgeCallFailedError.fromHttpFailure(response);
725
+ }
726
+ const challenge = await handleAuthChallenge(response, this._edgeIdentity);
727
+ this._authHeader = encodeAuthHeader(challenge);
728
+ log3("auth header updated", void 0, {
729
+ F: __dxlog_file4,
730
+ L: 144,
731
+ S: this,
732
+ C: (f, a) => f(...a)
733
+ });
734
+ return this._authHeader;
735
+ }
736
+ };
737
+ var createRetryHandler = (args) => {
738
+ if (!args.retry || args.retry.count < 1) {
739
+ return async () => false;
740
+ }
741
+ let retries = 0;
742
+ const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
743
+ const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
744
+ const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;
745
+ return async (ctx, retryAfter) => {
746
+ if (++retries > maxRetries || ctx.disposed) {
747
+ return false;
748
+ }
749
+ if (retryAfter) {
750
+ await sleep2(retryAfter);
751
+ } else {
752
+ const timeout = baseTimeout + Math.random() * jitter;
753
+ await sleep2(timeout);
754
+ }
755
+ return true;
756
+ };
757
+ };
758
+ var createRequest = (args, authHeader) => {
759
+ return {
760
+ method: args.method,
761
+ body: args.body && JSON.stringify(args.body),
762
+ headers: authHeader ? {
763
+ Authorization: authHeader
764
+ } : void 0
765
+ };
766
+ };
767
+ var encodeAuthHeader = (challenge) => {
768
+ const encodedChallenge = Buffer.from(challenge).toString("base64");
769
+ return `VerifiablePresentation pb;base64,${encodedChallenge}`;
770
+ };
771
+ export {
772
+ EdgeClient,
773
+ EdgeConnectionClosedError,
774
+ EdgeHttpClient,
775
+ EdgeIdentityChangedError,
776
+ Protocol,
777
+ createChainEdgeIdentity,
778
+ createDeviceEdgeIdentity,
779
+ createEphemeralEdgeIdentity,
780
+ createStubEdgeIdentity,
781
+ createTestHaloEdgeIdentity,
782
+ getTypename,
783
+ handleAuthChallenge,
784
+ protocol,
785
+ toUint8Array
786
+ };
787
+ //# sourceMappingURL=index.mjs.map