@dxos/edge-client 0.6.11 → 0.6.12-main.2d19bf1

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 (58) 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 +344 -178
  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 +122 -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 +343 -175
  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 +152 -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 +644 -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 +123 -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 +24 -13
  26. package/dist/types/src/edge-client.d.ts.map +1 -1
  27. package/dist/types/src/edge-http-client.d.ts +35 -0
  28. package/dist/types/src/edge-http-client.d.ts.map +1 -0
  29. package/dist/types/src/errors.d.ts +4 -1
  30. package/dist/types/src/errors.d.ts.map +1 -1
  31. package/dist/types/src/index.d.ts +3 -0
  32. package/dist/types/src/index.d.ts.map +1 -1
  33. package/dist/types/src/protocol.d.ts +2 -2
  34. package/dist/types/src/protocol.d.ts.map +1 -1
  35. package/dist/types/src/testing/index.d.ts +2 -0
  36. package/dist/types/src/testing/index.d.ts.map +1 -0
  37. package/dist/types/src/testing/test-utils.d.ts +20 -0
  38. package/dist/types/src/testing/test-utils.d.ts.map +1 -0
  39. package/dist/types/src/utils.d.ts +2 -0
  40. package/dist/types/src/utils.d.ts.map +1 -0
  41. package/package.json +29 -14
  42. package/src/auth.ts +135 -0
  43. package/src/defs.ts +2 -3
  44. package/src/edge-client.test.ts +50 -18
  45. package/src/edge-client.ts +75 -23
  46. package/src/edge-http-client.ts +151 -0
  47. package/src/errors.ts +8 -2
  48. package/src/index.ts +3 -0
  49. package/src/persistent-lifecycle.test.ts +2 -2
  50. package/src/protocol.test.ts +1 -2
  51. package/src/protocol.ts +2 -2
  52. package/src/testing/index.ts +5 -0
  53. package/src/testing/test-utils.ts +111 -0
  54. package/src/utils.ts +10 -0
  55. package/src/websocket.test.ts +5 -4
  56. package/dist/types/src/test-utils.d.ts +0 -11
  57. package/dist/types/src/test-utils.d.ts.map +0 -1
  58. package/src/test-utils.ts +0 -49
@@ -1,3 +1,10 @@
1
+ import {
2
+ Protocol,
3
+ getTypename,
4
+ protocol,
5
+ toUint8Array
6
+ } from "./chunk-ZWJXA37R.mjs";
7
+
1
8
  // packages/core/mesh/edge-client/src/index.ts
2
9
  export * from "@dxos/protocols/buf/dxos/edge/messenger_pb";
3
10
 
@@ -5,123 +12,21 @@ export * from "@dxos/protocols/buf/dxos/edge/messenger_pb";
5
12
  import WebSocket from "isomorphic-ws";
6
13
  import { Trigger, Event, scheduleTaskInterval, scheduleTask, TriggerState } from "@dxos/async";
7
14
  import { Context, LifecycleState as LifecycleState2, Resource as Resource2 } from "@dxos/context";
8
- import { invariant as invariant2 } from "@dxos/invariant";
15
+ import { randomBytes } from "@dxos/crypto";
9
16
  import { log as log2 } from "@dxos/log";
10
- import { buf as buf2 } from "@dxos/protocols/buf";
11
- import { MessageSchema as MessageSchema2 } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
12
-
13
- // packages/core/mesh/edge-client/src/defs.ts
14
- import { AnySchema } from "@bufbuild/protobuf/wkt";
15
- import { SwarmRequestSchema, SwarmResponseSchema, TextMessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
16
-
17
- // packages/core/mesh/edge-client/src/protocol.ts
18
- import { invariant } from "@dxos/invariant";
19
- import { buf, bufWkt } from "@dxos/protocols/buf";
17
+ import { buf } from "@dxos/protocols/buf";
20
18
  import { MessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
21
- import { bufferToArray } from "@dxos/util";
22
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/protocol.ts";
23
- var getTypename = (typeName) => `type.googleapis.com/${typeName}`;
24
- var Protocol = class {
25
- constructor(types) {
26
- this._typeRegistry = buf.createRegistry(...types);
27
- }
28
- get typeRegistry() {
29
- return this._typeRegistry;
30
- }
31
- toJson(message) {
32
- try {
33
- return buf.toJson(MessageSchema, message, {
34
- registry: this.typeRegistry
35
- });
36
- } catch (err) {
37
- return {
38
- type: this.getPayloadType(message)
39
- };
40
- }
41
- }
42
- /**
43
- * Return the payload with the given type.
44
- */
45
- getPayload(message, type) {
46
- invariant(message.payload, void 0, {
47
- F: __dxlog_file,
48
- L: 40,
49
- S: this,
50
- A: [
51
- "message.payload",
52
- ""
53
- ]
54
- });
55
- const payloadTypename = this.getPayloadType(message);
56
- if (type && type.typeName !== payloadTypename) {
57
- throw new Error(`Unexpected payload type: ${payloadTypename}; expected ${type.typeName}`);
58
- }
59
- invariant(bufWkt.anyIs(message.payload, type), `Unexpected payload type: ${payloadTypename}}`, {
60
- F: __dxlog_file,
61
- L: 46,
62
- S: this,
63
- A: [
64
- "bufWkt.anyIs(message.payload, type)",
65
- "`Unexpected payload type: ${payloadTypename}}`"
66
- ]
67
- });
68
- const payload = bufWkt.anyUnpack(message.payload, this.typeRegistry);
69
- invariant(payload, `Empty payload: ${payloadTypename}}`, {
70
- F: __dxlog_file,
71
- L: 48,
72
- S: this,
73
- A: [
74
- "payload",
75
- "`Empty payload: ${payloadTypename}}`"
76
- ]
77
- });
78
- return payload;
79
- }
80
- /**
81
- * Get the payload type.
82
- */
83
- getPayloadType(message) {
84
- if (!message.payload) {
85
- return void 0;
86
- }
87
- const [, type] = message.payload.typeUrl.split("/");
88
- return type;
89
- }
90
- /**
91
- * Create a packed message.
92
- */
93
- createMessage(type, { source, target, payload, serviceId }) {
94
- return buf.create(MessageSchema, {
95
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
96
- source,
97
- target,
98
- serviceId,
99
- payload: payload ? bufWkt.anyPack(type, buf.create(type, payload)) : void 0
100
- });
101
- }
102
- };
103
- var toUint8Array = async (data) => {
104
- if (data instanceof Buffer) {
105
- return bufferToArray(data);
106
- }
107
- if (data instanceof Blob) {
108
- return new Uint8Array(await data.arrayBuffer());
109
- }
110
- throw new Error(`Unexpected datatype: ${data}`);
111
- };
112
-
113
- // packages/core/mesh/edge-client/src/defs.ts
114
- var protocol = new Protocol([
115
- SwarmRequestSchema,
116
- SwarmResponseSchema,
117
- TextMessageSchema,
118
- AnySchema
119
- ]);
19
+ import { schema } from "@dxos/protocols/proto";
120
20
 
121
21
  // packages/core/mesh/edge-client/src/errors.ts
122
- var WebsocketClosedError = class extends Error {
22
+ var EdgeConnectionClosedError = class extends Error {
23
+ constructor() {
24
+ super("Edge connection closed.");
25
+ }
26
+ };
27
+ var EdgeIdentityChangedError = class extends Error {
123
28
  constructor() {
124
- super("WebSocket connection closed");
29
+ super("Edge identity changed.");
125
30
  }
126
31
  };
127
32
 
@@ -136,7 +41,7 @@ function _ts_decorate(decorators, target, key, desc) {
136
41
  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;
137
42
  return c > 3 && r && Object.defineProperty(target, key, r), r;
138
43
  }
139
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/persistent-lifecycle.ts";
44
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/persistent-lifecycle.ts";
140
45
  var INIT_RESTART_DELAY = 100;
141
46
  var DEFAULT_MAX_RESTART_DELAY = 5e3;
142
47
  var PersistentLifecycle = class extends Resource {
@@ -157,7 +62,7 @@ var PersistentLifecycle = class extends Resource {
157
62
  log.warn("Restart failed", {
158
63
  err
159
64
  }, {
160
- F: __dxlog_file2,
65
+ F: __dxlog_file,
161
66
  L: 64,
162
67
  S: this,
163
68
  C: (f, a) => f(...a)
@@ -169,7 +74,7 @@ var PersistentLifecycle = class extends Resource {
169
74
  log.warn("Start failed", {
170
75
  err
171
76
  }, {
172
- F: __dxlog_file2,
77
+ F: __dxlog_file,
173
78
  L: 69,
174
79
  S: this,
175
80
  C: (f, a) => f(...a)
@@ -186,7 +91,7 @@ var PersistentLifecycle = class extends Resource {
186
91
  log(`restarting in ${this._restartAfter}ms`, {
187
92
  state: this._lifecycleState
188
93
  }, {
189
- F: __dxlog_file2,
94
+ F: __dxlog_file,
190
95
  L: 81,
191
96
  S: this,
192
97
  C: (f, a) => f(...a)
@@ -218,17 +123,25 @@ _ts_decorate([
218
123
  synchronized
219
124
  ], PersistentLifecycle.prototype, "scheduleRestart", null);
220
125
 
126
+ // packages/core/mesh/edge-client/src/utils.ts
127
+ var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
128
+ const isSecure = baseUrl.startsWith("https") || baseUrl.startsWith("wss");
129
+ const url = new URL(baseUrl);
130
+ url.protocol = protocol2 + (isSecure ? "s" : "");
131
+ return url.toString();
132
+ };
133
+
221
134
  // packages/core/mesh/edge-client/src/edge-client.ts
222
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
135
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
223
136
  var DEFAULT_TIMEOUT = 1e4;
224
137
  var SIGNAL_KEEPALIVE_INTERVAL = 5e3;
225
138
  var EdgeClient = class extends Resource2 {
226
- constructor(_identityKey, _peerKey, _config) {
139
+ constructor(_identity, _config) {
227
140
  super();
228
- this._identityKey = _identityKey;
229
- this._peerKey = _peerKey;
141
+ this._identity = _identity;
230
142
  this._config = _config;
231
143
  this.reconnect = new Event();
144
+ this.connected = new Event();
232
145
  this._persistentLifecycle = new PersistentLifecycle({
233
146
  start: async () => this._openWebSocket(),
234
147
  stop: async () => this._closeWebSocket(),
@@ -239,25 +152,27 @@ var EdgeClient = class extends Resource2 {
239
152
  this._ws = void 0;
240
153
  this._keepaliveCtx = void 0;
241
154
  this._heartBeatContext = void 0;
242
- this._protocol = this._config.protocol ?? protocol;
155
+ this._baseUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
243
156
  }
244
157
  // TODO(burdon): Attach logging.
245
158
  get info() {
246
159
  return {
247
160
  open: this.isOpen,
248
- identity: this._identityKey,
249
- device: this._peerKey
161
+ identity: this._identity.identityKey,
162
+ device: this._identity.peerKey
250
163
  };
251
164
  }
165
+ get isConnected() {
166
+ return Boolean(this._ws) && this._ready.state === TriggerState.RESOLVED;
167
+ }
252
168
  get identityKey() {
253
- return this._identityKey;
169
+ return this._identity.identityKey;
254
170
  }
255
171
  get peerKey() {
256
- return this._peerKey;
172
+ return this._identity.peerKey;
257
173
  }
258
- setIdentity({ peerKey, identityKey }) {
259
- this._peerKey = peerKey;
260
- this._identityKey = identityKey;
174
+ setIdentity(identity) {
175
+ this._identity = identity;
261
176
  this._persistentLifecycle.scheduleRestart();
262
177
  }
263
178
  addListener(listener) {
@@ -271,8 +186,8 @@ var EdgeClient = class extends Resource2 {
271
186
  log2("opening...", {
272
187
  info: this.info
273
188
  }, {
274
- F: __dxlog_file3,
275
- L: 101,
189
+ F: __dxlog_file2,
190
+ L: 122,
276
191
  S: this,
277
192
  C: (f, a) => f(...a)
278
193
  });
@@ -280,8 +195,8 @@ var EdgeClient = class extends Resource2 {
280
195
  log2.warn("Error while opening connection", {
281
196
  err
282
197
  }, {
283
- F: __dxlog_file3,
284
- L: 103,
198
+ F: __dxlog_file2,
199
+ L: 124,
285
200
  S: this,
286
201
  C: (f, a) => f(...a)
287
202
  });
@@ -292,31 +207,51 @@ var EdgeClient = class extends Resource2 {
292
207
  */
293
208
  async _close() {
294
209
  log2("closing...", {
295
- peerKey: this._peerKey
210
+ peerKey: this._identity.peerKey
296
211
  }, {
297
- F: __dxlog_file3,
298
- L: 111,
212
+ F: __dxlog_file2,
213
+ L: 132,
299
214
  S: this,
300
215
  C: (f, a) => f(...a)
301
216
  });
302
217
  await this._persistentLifecycle.close();
303
218
  }
304
219
  async _openWebSocket() {
305
- const url = new URL(`/ws/${this._identityKey}/${this._peerKey}`, this._config.socketEndpoint);
306
- this._ws = new WebSocket(url);
220
+ let protocolHeader;
221
+ if (!this._config.disableAuth) {
222
+ const challenge = randomBytes(32);
223
+ const credential = await this._identity.presentCredentials({
224
+ challenge
225
+ });
226
+ protocolHeader = encodePresentationIntoAuthHeader(credential);
227
+ }
228
+ const url = new URL(`/ws/${this._identity.identityKey}/${this._identity.peerKey}`, this._baseUrl);
229
+ log2("Opening websocket", {
230
+ url: url.toString(),
231
+ protocolHeader
232
+ }, {
233
+ F: __dxlog_file2,
234
+ L: 147,
235
+ S: this,
236
+ C: (f, a) => f(...a)
237
+ });
238
+ this._ws = new WebSocket(url, protocolHeader ? [
239
+ protocolHeader
240
+ ] : []);
307
241
  this._ws.onopen = () => {
308
242
  log2("opened", this.info, {
309
- F: __dxlog_file3,
310
- L: 120,
243
+ F: __dxlog_file2,
244
+ L: 151,
311
245
  S: this,
312
246
  C: (f, a) => f(...a)
313
247
  });
314
248
  this._ready.wake();
249
+ this.connected.emit();
315
250
  };
316
251
  this._ws.onclose = () => {
317
252
  log2("closed", this.info, {
318
- F: __dxlog_file3,
319
- L: 124,
253
+ F: __dxlog_file2,
254
+ L: 156,
320
255
  S: this,
321
256
  C: (f, a) => f(...a)
322
257
  });
@@ -327,8 +262,8 @@ var EdgeClient = class extends Resource2 {
327
262
  error: event.error,
328
263
  info: event.message
329
264
  }, {
330
- F: __dxlog_file3,
331
- L: 128,
265
+ F: __dxlog_file2,
266
+ L: 160,
332
267
  S: this,
333
268
  C: (f, a) => f(...a)
334
269
  });
@@ -340,13 +275,13 @@ var EdgeClient = class extends Resource2 {
340
275
  return;
341
276
  }
342
277
  const data = await toUint8Array(event.data);
343
- const message = buf2.fromBinary(MessageSchema2, data);
278
+ const message = buf.fromBinary(MessageSchema, data);
344
279
  log2("received", {
345
- peerKey: this._peerKey,
280
+ peerKey: this._identity.peerKey,
346
281
  payload: protocol.getPayloadType(message)
347
282
  }, {
348
- F: __dxlog_file3,
349
- L: 141,
283
+ F: __dxlog_file2,
284
+ L: 173,
350
285
  S: this,
351
286
  C: (f, a) => f(...a)
352
287
  });
@@ -359,8 +294,8 @@ var EdgeClient = class extends Resource2 {
359
294
  err,
360
295
  payload: protocol.getPayloadType(message)
361
296
  }, {
362
- F: __dxlog_file3,
363
- L: 147,
297
+ F: __dxlog_file2,
298
+ L: 179,
364
299
  S: this,
365
300
  C: (f, a) => f(...a)
366
301
  });
@@ -372,8 +307,8 @@ var EdgeClient = class extends Resource2 {
372
307
  timeout: this._config.timeout ?? DEFAULT_TIMEOUT
373
308
  });
374
309
  this._keepaliveCtx = new Context(void 0, {
375
- F: __dxlog_file3,
376
- L: 154
310
+ F: __dxlog_file2,
311
+ L: 189
377
312
  });
378
313
  scheduleTaskInterval(this._keepaliveCtx, async () => {
379
314
  this._ws?.send("__ping__");
@@ -386,7 +321,7 @@ var EdgeClient = class extends Resource2 {
386
321
  return;
387
322
  }
388
323
  try {
389
- this._ready.throw(new WebsocketClosedError());
324
+ this._ready.throw(this.isOpen ? new EdgeIdentityChangedError() : new EdgeConnectionClosedError());
390
325
  this._ready.reset();
391
326
  void this._keepaliveCtx?.dispose();
392
327
  this._keepaliveCtx = void 0;
@@ -407,8 +342,8 @@ var EdgeClient = class extends Resource2 {
407
342
  log2.warn("Error closing websocket", {
408
343
  err
409
344
  }, {
410
- F: __dxlog_file3,
411
- L: 190,
345
+ F: __dxlog_file2,
346
+ L: 225,
412
347
  S: this,
413
348
  C: (f, a) => f(...a)
414
349
  });
@@ -420,38 +355,32 @@ var EdgeClient = class extends Resource2 {
420
355
  */
421
356
  async send(message) {
422
357
  if (this._ready.state !== TriggerState.RESOLVED) {
358
+ log2("waiting for websocket to become ready", void 0, {
359
+ F: __dxlog_file2,
360
+ L: 235,
361
+ S: this,
362
+ C: (f, a) => f(...a)
363
+ });
423
364
  await this._ready.wait({
424
365
  timeout: this._config.timeout ?? DEFAULT_TIMEOUT
425
366
  });
426
367
  }
427
- invariant2(this._ws, void 0, {
428
- F: __dxlog_file3,
429
- L: 202,
430
- S: this,
431
- A: [
432
- "this._ws",
433
- ""
434
- ]
435
- });
436
- invariant2(!message.source || message.source.peerKey === this._peerKey, void 0, {
437
- F: __dxlog_file3,
438
- L: 203,
439
- S: this,
440
- A: [
441
- "!message.source || message.source.peerKey === this._peerKey",
442
- ""
443
- ]
444
- });
368
+ if (!this._ws) {
369
+ throw new EdgeConnectionClosedError();
370
+ }
371
+ if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)) {
372
+ throw new EdgeIdentityChangedError();
373
+ }
445
374
  log2("sending...", {
446
- peerKey: this._peerKey,
375
+ peerKey: this._identity.peerKey,
447
376
  payload: protocol.getPayloadType(message)
448
377
  }, {
449
- F: __dxlog_file3,
450
- L: 204,
378
+ F: __dxlog_file2,
379
+ L: 248,
451
380
  S: this,
452
381
  C: (f, a) => f(...a)
453
382
  });
454
- this._ws.send(buf2.toBinary(MessageSchema2, message));
383
+ this._ws.send(buf.toBinary(MessageSchema, message));
455
384
  }
456
385
  _onHeartbeat() {
457
386
  if (this._lifecycleState !== LifecycleState2.OPEN) {
@@ -459,17 +388,254 @@ var EdgeClient = class extends Resource2 {
459
388
  }
460
389
  void this._heartBeatContext?.dispose();
461
390
  this._heartBeatContext = new Context(void 0, {
462
- F: __dxlog_file3,
463
- L: 213
391
+ F: __dxlog_file2,
392
+ L: 257
464
393
  });
465
394
  scheduleTask(this._heartBeatContext, () => {
466
395
  this._persistentLifecycle.scheduleRestart();
467
396
  }, 2 * SIGNAL_KEEPALIVE_INTERVAL);
468
397
  }
469
398
  };
399
+ var encodePresentationIntoAuthHeader = (presentation) => {
400
+ const encoded = schema.getCodecForType("dxos.halo.credentials.Presentation").encode(presentation);
401
+ const encodedToken = Buffer.from(encoded).toString("base64").replace(/=*$/, "").replaceAll("/", "|");
402
+ return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
403
+ };
404
+
405
+ // packages/core/mesh/edge-client/src/auth.ts
406
+ import { createCredential, signPresentation } from "@dxos/credentials";
407
+ import { Keyring } from "@dxos/keyring";
408
+ import { PublicKey } from "@dxos/keys";
409
+ var createDeviceEdgeIdentity = async (signer, key) => {
410
+ return {
411
+ identityKey: key.toHex(),
412
+ peerKey: key.toHex(),
413
+ presentCredentials: async ({ challenge }) => {
414
+ return signPresentation({
415
+ presentation: {
416
+ credentials: [
417
+ // Verifier requires at least one credential in the presentation to establish the subject.
418
+ await createCredential({
419
+ assertion: {
420
+ "@type": "dxos.halo.credentials.Auth"
421
+ },
422
+ issuer: key,
423
+ subject: key,
424
+ signer
425
+ })
426
+ ]
427
+ },
428
+ signer,
429
+ signerKey: key,
430
+ nonce: challenge
431
+ });
432
+ }
433
+ };
434
+ };
435
+ var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
436
+ const credentialsToSign = credentials.length > 0 ? credentials : [
437
+ await createCredential({
438
+ assertion: {
439
+ "@type": "dxos.halo.credentials.Auth"
440
+ },
441
+ issuer: identityKey,
442
+ subject: identityKey,
443
+ signer,
444
+ chain,
445
+ signingKey: peerKey
446
+ })
447
+ ];
448
+ return {
449
+ identityKey: identityKey.toHex(),
450
+ peerKey: peerKey.toHex(),
451
+ presentCredentials: async ({ challenge }) => {
452
+ return signPresentation({
453
+ presentation: {
454
+ credentials: credentialsToSign
455
+ },
456
+ signer,
457
+ nonce: challenge,
458
+ signerKey: peerKey,
459
+ chain
460
+ });
461
+ }
462
+ };
463
+ };
464
+ var createEphemeralEdgeIdentity = async () => {
465
+ const keyring = new Keyring();
466
+ const key = await keyring.createKey();
467
+ return createDeviceEdgeIdentity(keyring, key);
468
+ };
469
+ var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
470
+ const deviceAdmission = await createCredential({
471
+ assertion: {
472
+ "@type": "dxos.halo.credentials.AuthorizedDevice",
473
+ deviceKey,
474
+ identityKey
475
+ },
476
+ issuer: identityKey,
477
+ subject: deviceKey,
478
+ signer
479
+ });
480
+ return createChainEdgeIdentity(signer, identityKey, deviceKey, {
481
+ credential: deviceAdmission
482
+ }, [
483
+ await createCredential({
484
+ assertion: {
485
+ "@type": "dxos.halo.credentials.Auth"
486
+ },
487
+ issuer: identityKey,
488
+ subject: identityKey,
489
+ signer
490
+ })
491
+ ]);
492
+ };
493
+ var createStubEdgeIdentity = () => {
494
+ const identityKey = PublicKey.random();
495
+ const deviceKey = PublicKey.random();
496
+ return {
497
+ identityKey: identityKey.toHex(),
498
+ peerKey: deviceKey.toHex(),
499
+ presentCredentials: async () => {
500
+ throw new Error("Stub identity does not support authentication.");
501
+ }
502
+ };
503
+ };
504
+
505
+ // packages/core/mesh/edge-client/src/edge-http-client.ts
506
+ import { sleep as sleep2 } from "@dxos/async";
507
+ import { Context as Context2 } from "@dxos/context";
508
+ import { log as log3 } from "@dxos/log";
509
+ import { EdgeCallFailedError, EdgeAuthChallengeError } from "@dxos/protocols";
510
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
511
+ var DEFAULT_RETRY_TIMEOUT = 1500;
512
+ var DEFAULT_RETRY_JITTER = 500;
513
+ var DEFAULT_MAX_RETRIES_COUNT = 3;
514
+ var EdgeHttpClient = class {
515
+ constructor(baseUrl) {
516
+ this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
517
+ log3("created", {
518
+ url: this._baseUrl
519
+ }, {
520
+ F: __dxlog_file3,
521
+ L: 30,
522
+ S: this,
523
+ C: (f, a) => f(...a)
524
+ });
525
+ }
526
+ getCredentialsForNotarization(spaceId, args) {
527
+ return this._call(`/spaces/${spaceId}/notarization`, {
528
+ ...args,
529
+ method: "GET"
530
+ });
531
+ }
532
+ async notarizeCredentials(spaceId, body, args) {
533
+ await this._call(`/spaces/${spaceId}/notarization`, {
534
+ ...args,
535
+ body,
536
+ method: "POST"
537
+ });
538
+ }
539
+ async joinSpaceByInvitation(spaceId, body, args) {
540
+ return this._call(`/spaces/${spaceId}/join`, {
541
+ ...args,
542
+ body,
543
+ method: "POST"
544
+ });
545
+ }
546
+ async _call(path, args) {
547
+ const requestContext = args.context ?? new Context2(void 0, {
548
+ F: __dxlog_file3,
549
+ L: 54
550
+ });
551
+ const shouldRetry = createRetryHandler(args);
552
+ const request = createRequest(args);
553
+ const url = `${this._baseUrl}${path.startsWith("/") ? path.slice(1) : path}`;
554
+ log3.info("call", {
555
+ method: args.method,
556
+ path
557
+ }, {
558
+ F: __dxlog_file3,
559
+ L: 59,
560
+ S: this,
561
+ C: (f, a) => f(...a)
562
+ });
563
+ while (true) {
564
+ let processingError;
565
+ let retryAfterHeaderValue = Number.NaN;
566
+ try {
567
+ const response = await fetch(url, request);
568
+ retryAfterHeaderValue = Number(response.headers.get("Retry-After"));
569
+ if (response.ok) {
570
+ const body = await response.json();
571
+ if (body.success) {
572
+ return body.data;
573
+ }
574
+ if (body.errorData?.type === "auth_challenge" && typeof body.errorData?.challenge === "string") {
575
+ processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
576
+ } else {
577
+ processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
578
+ }
579
+ } else {
580
+ processingError = EdgeCallFailedError.fromHttpFailure(response);
581
+ }
582
+ } catch (error) {
583
+ processingError = EdgeCallFailedError.fromProcessingFailureCause(error);
584
+ }
585
+ if (processingError.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
586
+ log3.info("retrying edge request", {
587
+ path,
588
+ processingError
589
+ }, {
590
+ F: __dxlog_file3,
591
+ L: 88,
592
+ S: this,
593
+ C: (f, a) => f(...a)
594
+ });
595
+ } else {
596
+ throw processingError;
597
+ }
598
+ }
599
+ }
600
+ };
601
+ var createRequest = (args) => {
602
+ return {
603
+ method: args.method,
604
+ body: args.body && JSON.stringify(args.body)
605
+ };
606
+ };
607
+ var createRetryHandler = (args) => {
608
+ if (!args.retry || args.retry.count < 1) {
609
+ return async () => false;
610
+ }
611
+ let retries = 0;
612
+ const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
613
+ const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
614
+ const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;
615
+ return async (ctx, retryAfter) => {
616
+ if (++retries > maxRetries || ctx.disposed) {
617
+ return false;
618
+ }
619
+ if (retryAfter) {
620
+ await sleep2(retryAfter);
621
+ } else {
622
+ const timeout = baseTimeout + Math.random() * jitter;
623
+ await sleep2(timeout);
624
+ }
625
+ return true;
626
+ };
627
+ };
470
628
  export {
471
629
  EdgeClient,
630
+ EdgeConnectionClosedError,
631
+ EdgeHttpClient,
632
+ EdgeIdentityChangedError,
472
633
  Protocol,
634
+ createChainEdgeIdentity,
635
+ createDeviceEdgeIdentity,
636
+ createEphemeralEdgeIdentity,
637
+ createStubEdgeIdentity,
638
+ createTestHaloEdgeIdentity,
473
639
  getTypename,
474
640
  protocol,
475
641
  toUint8Array