@dxos/edge-client 0.6.12 → 0.6.13-main.09887cd

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