@dxos/edge-client 0.6.11 → 0.6.12-main.568932b

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 +347 -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 +346 -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 +647 -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 +23 -13
  26. package/dist/types/src/edge-client.d.ts.map +1 -1
  27. package/dist/types/src/edge-http-client.d.ts +34 -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 +76 -23
  46. package/src/edge-http-client.ts +153 -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
@@ -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,23 @@ _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;
174
+ var DISABLE_AUTH = true;
248
175
  var EdgeClient = class extends import_context.Resource {
249
- constructor(_identityKey, _peerKey, _config) {
176
+ constructor(_identity, _config) {
250
177
  super();
251
- this._identityKey = _identityKey;
252
- this._peerKey = _peerKey;
178
+ this._identity = _identity;
253
179
  this._config = _config;
254
180
  this.reconnect = new import_async.Event();
181
+ this.connected = new import_async.Event();
255
182
  this._persistentLifecycle = new PersistentLifecycle({
256
183
  start: async () => this._openWebSocket(),
257
184
  stop: async () => this._closeWebSocket(),
@@ -262,25 +189,27 @@ var EdgeClient = class extends import_context.Resource {
262
189
  this._ws = void 0;
263
190
  this._keepaliveCtx = void 0;
264
191
  this._heartBeatContext = void 0;
265
- this._protocol = this._config.protocol ?? protocol;
192
+ this._baseUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
266
193
  }
267
194
  // TODO(burdon): Attach logging.
268
195
  get info() {
269
196
  return {
270
197
  open: this.isOpen,
271
- identity: this._identityKey,
272
- device: this._peerKey
198
+ identity: this._identity.identityKey,
199
+ device: this._identity.peerKey
273
200
  };
274
201
  }
202
+ get isConnected() {
203
+ return Boolean(this._ws) && this._ready.state === import_async.TriggerState.RESOLVED;
204
+ }
275
205
  get identityKey() {
276
- return this._identityKey;
206
+ return this._identity.identityKey;
277
207
  }
278
208
  get peerKey() {
279
- return this._peerKey;
209
+ return this._identity.peerKey;
280
210
  }
281
- setIdentity({ peerKey, identityKey }) {
282
- this._peerKey = peerKey;
283
- this._identityKey = identityKey;
211
+ setIdentity(identity) {
212
+ this._identity = identity;
284
213
  this._persistentLifecycle.scheduleRestart();
285
214
  }
286
215
  addListener(listener) {
@@ -294,8 +223,8 @@ var EdgeClient = class extends import_context.Resource {
294
223
  (0, import_log.log)("opening...", {
295
224
  info: this.info
296
225
  }, {
297
- F: __dxlog_file3,
298
- L: 101,
226
+ F: __dxlog_file2,
227
+ L: 123,
299
228
  S: this,
300
229
  C: (f, a) => f(...a)
301
230
  });
@@ -303,8 +232,8 @@ var EdgeClient = class extends import_context.Resource {
303
232
  import_log.log.warn("Error while opening connection", {
304
233
  err
305
234
  }, {
306
- F: __dxlog_file3,
307
- L: 103,
235
+ F: __dxlog_file2,
236
+ L: 125,
308
237
  S: this,
309
238
  C: (f, a) => f(...a)
310
239
  });
@@ -315,31 +244,51 @@ var EdgeClient = class extends import_context.Resource {
315
244
  */
316
245
  async _close() {
317
246
  (0, import_log.log)("closing...", {
318
- peerKey: this._peerKey
247
+ peerKey: this._identity.peerKey
319
248
  }, {
320
- F: __dxlog_file3,
321
- L: 111,
249
+ F: __dxlog_file2,
250
+ L: 133,
322
251
  S: this,
323
252
  C: (f, a) => f(...a)
324
253
  });
325
254
  await this._persistentLifecycle.close();
326
255
  }
327
256
  async _openWebSocket() {
328
- const url = new URL(`/ws/${this._identityKey}/${this._peerKey}`, this._config.socketEndpoint);
329
- this._ws = new import_isomorphic_ws.default(url);
257
+ let protocolHeader;
258
+ if (!DISABLE_AUTH) {
259
+ const challenge = (0, import_crypto.randomBytes)(32);
260
+ const credential = await this._identity.presentCredentials({
261
+ challenge
262
+ });
263
+ protocolHeader = encodePresentationIntoAuthHeader(credential);
264
+ }
265
+ const url = new URL(`/ws/${this._identity.identityKey}/${this._identity.peerKey}`, this._baseUrl);
266
+ (0, import_log.log)("Opening websocket", {
267
+ url: url.toString(),
268
+ protocolHeader
269
+ }, {
270
+ F: __dxlog_file2,
271
+ L: 148,
272
+ S: this,
273
+ C: (f, a) => f(...a)
274
+ });
275
+ this._ws = new import_isomorphic_ws.default(url, protocolHeader ? [
276
+ protocolHeader
277
+ ] : []);
330
278
  this._ws.onopen = () => {
331
279
  (0, import_log.log)("opened", this.info, {
332
- F: __dxlog_file3,
333
- L: 120,
280
+ F: __dxlog_file2,
281
+ L: 152,
334
282
  S: this,
335
283
  C: (f, a) => f(...a)
336
284
  });
337
285
  this._ready.wake();
286
+ this.connected.emit();
338
287
  };
339
288
  this._ws.onclose = () => {
340
289
  (0, import_log.log)("closed", this.info, {
341
- F: __dxlog_file3,
342
- L: 124,
290
+ F: __dxlog_file2,
291
+ L: 157,
343
292
  S: this,
344
293
  C: (f, a) => f(...a)
345
294
  });
@@ -350,8 +299,8 @@ var EdgeClient = class extends import_context.Resource {
350
299
  error: event.error,
351
300
  info: event.message
352
301
  }, {
353
- F: __dxlog_file3,
354
- L: 128,
302
+ F: __dxlog_file2,
303
+ L: 161,
355
304
  S: this,
356
305
  C: (f, a) => f(...a)
357
306
  });
@@ -362,14 +311,14 @@ var EdgeClient = class extends import_context.Resource {
362
311
  this._onHeartbeat();
363
312
  return;
364
313
  }
365
- const data = await toUint8Array(event.data);
314
+ const data = await (0, import_chunk_ANV2HBEH.toUint8Array)(event.data);
366
315
  const message = import_buf.buf.fromBinary(import_messenger_pb.MessageSchema, data);
367
316
  (0, import_log.log)("received", {
368
- peerKey: this._peerKey,
369
- payload: protocol.getPayloadType(message)
317
+ peerKey: this._identity.peerKey,
318
+ payload: import_chunk_ANV2HBEH.protocol.getPayloadType(message)
370
319
  }, {
371
- F: __dxlog_file3,
372
- L: 141,
320
+ F: __dxlog_file2,
321
+ L: 174,
373
322
  S: this,
374
323
  C: (f, a) => f(...a)
375
324
  });
@@ -380,10 +329,10 @@ var EdgeClient = class extends import_context.Resource {
380
329
  } catch (err) {
381
330
  import_log.log.error("processing", {
382
331
  err,
383
- payload: protocol.getPayloadType(message)
332
+ payload: import_chunk_ANV2HBEH.protocol.getPayloadType(message)
384
333
  }, {
385
- F: __dxlog_file3,
386
- L: 147,
334
+ F: __dxlog_file2,
335
+ L: 180,
387
336
  S: this,
388
337
  C: (f, a) => f(...a)
389
338
  });
@@ -395,8 +344,8 @@ var EdgeClient = class extends import_context.Resource {
395
344
  timeout: this._config.timeout ?? DEFAULT_TIMEOUT
396
345
  });
397
346
  this._keepaliveCtx = new import_context.Context(void 0, {
398
- F: __dxlog_file3,
399
- L: 154
347
+ F: __dxlog_file2,
348
+ L: 190
400
349
  });
401
350
  (0, import_async.scheduleTaskInterval)(this._keepaliveCtx, async () => {
402
351
  this._ws?.send("__ping__");
@@ -409,7 +358,7 @@ var EdgeClient = class extends import_context.Resource {
409
358
  return;
410
359
  }
411
360
  try {
412
- this._ready.throw(new WebsocketClosedError());
361
+ this._ready.throw(this.isOpen ? new EdgeIdentityChangedError() : new EdgeConnectionClosedError());
413
362
  this._ready.reset();
414
363
  void this._keepaliveCtx?.dispose();
415
364
  this._keepaliveCtx = void 0;
@@ -430,8 +379,8 @@ var EdgeClient = class extends import_context.Resource {
430
379
  import_log.log.warn("Error closing websocket", {
431
380
  err
432
381
  }, {
433
- F: __dxlog_file3,
434
- L: 190,
382
+ F: __dxlog_file2,
383
+ L: 226,
435
384
  S: this,
436
385
  C: (f, a) => f(...a)
437
386
  });
@@ -443,34 +392,28 @@ var EdgeClient = class extends import_context.Resource {
443
392
  */
444
393
  async send(message) {
445
394
  if (this._ready.state !== import_async.TriggerState.RESOLVED) {
395
+ (0, import_log.log)("waiting for websocket to become ready", void 0, {
396
+ F: __dxlog_file2,
397
+ L: 236,
398
+ S: this,
399
+ C: (f, a) => f(...a)
400
+ });
446
401
  await this._ready.wait({
447
402
  timeout: this._config.timeout ?? DEFAULT_TIMEOUT
448
403
  });
449
404
  }
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
- });
405
+ if (!this._ws) {
406
+ throw new EdgeConnectionClosedError();
407
+ }
408
+ if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)) {
409
+ throw new EdgeIdentityChangedError();
410
+ }
468
411
  (0, import_log.log)("sending...", {
469
- peerKey: this._peerKey,
470
- payload: protocol.getPayloadType(message)
412
+ peerKey: this._identity.peerKey,
413
+ payload: import_chunk_ANV2HBEH.protocol.getPayloadType(message)
471
414
  }, {
472
- F: __dxlog_file3,
473
- L: 204,
415
+ F: __dxlog_file2,
416
+ L: 249,
474
417
  S: this,
475
418
  C: (f, a) => f(...a)
476
419
  });
@@ -482,18 +425,246 @@ var EdgeClient = class extends import_context.Resource {
482
425
  }
483
426
  void this._heartBeatContext?.dispose();
484
427
  this._heartBeatContext = new import_context.Context(void 0, {
485
- F: __dxlog_file3,
486
- L: 213
428
+ F: __dxlog_file2,
429
+ L: 258
487
430
  });
488
431
  (0, import_async.scheduleTask)(this._heartBeatContext, () => {
489
432
  this._persistentLifecycle.scheduleRestart();
490
433
  }, 2 * SIGNAL_KEEPALIVE_INTERVAL);
491
434
  }
492
435
  };
436
+ var encodePresentationIntoAuthHeader = (presentation) => {
437
+ const encoded = import_proto.schema.getCodecForType("dxos.halo.credentials.Presentation").encode(presentation);
438
+ const encodedToken = Buffer.from(encoded).toString("base64").replace(/=*$/, "").replaceAll("/", "|");
439
+ return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
440
+ };
441
+ var createDeviceEdgeIdentity = async (signer, key) => {
442
+ return {
443
+ identityKey: key.toHex(),
444
+ peerKey: key.toHex(),
445
+ presentCredentials: async ({ challenge }) => {
446
+ return (0, import_credentials.signPresentation)({
447
+ presentation: {
448
+ credentials: [
449
+ // Verifier requires at least one credential in the presentation to establish the subject.
450
+ await (0, import_credentials.createCredential)({
451
+ assertion: {
452
+ "@type": "dxos.halo.credentials.Auth"
453
+ },
454
+ issuer: key,
455
+ subject: key,
456
+ signer
457
+ })
458
+ ]
459
+ },
460
+ signer,
461
+ signerKey: key,
462
+ nonce: challenge
463
+ });
464
+ }
465
+ };
466
+ };
467
+ var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
468
+ const credentialsToSign = credentials.length > 0 ? credentials : [
469
+ await (0, import_credentials.createCredential)({
470
+ assertion: {
471
+ "@type": "dxos.halo.credentials.Auth"
472
+ },
473
+ issuer: identityKey,
474
+ subject: identityKey,
475
+ signer,
476
+ chain,
477
+ signingKey: peerKey
478
+ })
479
+ ];
480
+ return {
481
+ identityKey: identityKey.toHex(),
482
+ peerKey: peerKey.toHex(),
483
+ presentCredentials: async ({ challenge }) => {
484
+ return (0, import_credentials.signPresentation)({
485
+ presentation: {
486
+ credentials: credentialsToSign
487
+ },
488
+ signer,
489
+ nonce: challenge,
490
+ signerKey: peerKey,
491
+ chain
492
+ });
493
+ }
494
+ };
495
+ };
496
+ var createEphemeralEdgeIdentity = async () => {
497
+ const keyring = new import_keyring.Keyring();
498
+ const key = await keyring.createKey();
499
+ return createDeviceEdgeIdentity(keyring, key);
500
+ };
501
+ var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
502
+ const deviceAdmission = await (0, import_credentials.createCredential)({
503
+ assertion: {
504
+ "@type": "dxos.halo.credentials.AuthorizedDevice",
505
+ deviceKey,
506
+ identityKey
507
+ },
508
+ issuer: identityKey,
509
+ subject: deviceKey,
510
+ signer
511
+ });
512
+ return createChainEdgeIdentity(signer, identityKey, deviceKey, {
513
+ credential: deviceAdmission
514
+ }, [
515
+ await (0, import_credentials.createCredential)({
516
+ assertion: {
517
+ "@type": "dxos.halo.credentials.Auth"
518
+ },
519
+ issuer: identityKey,
520
+ subject: identityKey,
521
+ signer
522
+ })
523
+ ]);
524
+ };
525
+ var createStubEdgeIdentity = () => {
526
+ const identityKey = import_keys.PublicKey.random();
527
+ const deviceKey = import_keys.PublicKey.random();
528
+ return {
529
+ identityKey: identityKey.toHex(),
530
+ peerKey: deviceKey.toHex(),
531
+ presentCredentials: async () => {
532
+ throw new Error("Stub identity does not support authentication.");
533
+ }
534
+ };
535
+ };
536
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
537
+ var DEFAULT_RETRY_TIMEOUT = 1500;
538
+ var DEFAULT_RETRY_JITTER = 500;
539
+ var DEFAULT_MAX_RETRIES_COUNT = 3;
540
+ var EdgeHttpClient = class {
541
+ constructor(baseUrl) {
542
+ this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
543
+ (0, import_log3.log)("created", {
544
+ url: this._baseUrl
545
+ }, {
546
+ F: __dxlog_file3,
547
+ L: 27,
548
+ S: this,
549
+ C: (f, a) => f(...a)
550
+ });
551
+ }
552
+ getCredentialsForNotarization(spaceId, args) {
553
+ return this._call(`/spaces/${spaceId}/notarization`, {
554
+ ...args,
555
+ method: "GET"
556
+ });
557
+ }
558
+ async notarizeCredentials(spaceId, body, args) {
559
+ await this._call(`/spaces/${spaceId}/notarization`, {
560
+ ...args,
561
+ body,
562
+ method: "POST"
563
+ });
564
+ }
565
+ async _call(path, args) {
566
+ const requestContext = args.context ?? new import_context3.Context(void 0, {
567
+ F: __dxlog_file3,
568
+ L: 43
569
+ });
570
+ const shouldRetry = createRetryHandler(args);
571
+ const request = createRequest(args);
572
+ const url = `${this._baseUrl}${path.startsWith("/") ? path.slice(1) : path}`;
573
+ import_log3.log.info("call", {
574
+ method: args.method,
575
+ path
576
+ }, {
577
+ F: __dxlog_file3,
578
+ L: 48,
579
+ S: this,
580
+ C: (f, a) => f(...a)
581
+ });
582
+ while (true) {
583
+ let processingError;
584
+ let retryAfterHeaderValue = Number.NaN;
585
+ try {
586
+ const response = await fetch(url, request);
587
+ retryAfterHeaderValue = Number(response.headers.get("Retry-After"));
588
+ if (response.ok) {
589
+ const body = await response.json();
590
+ if (body.success) {
591
+ return body.data;
592
+ }
593
+ const isNonRetryable = body.errorData != null;
594
+ if (isNonRetryable) {
595
+ throw new import_protocols.EdgeCallFailedError(body.reason, body.errorData);
596
+ }
597
+ processingError = new import_protocols.EdgeCallFailedError(body.reason);
598
+ } else {
599
+ processingError = import_protocols.EdgeCallFailedError.fromFailureResponse(response);
600
+ if (!isRetryable(response.status)) {
601
+ throw processingError;
602
+ }
603
+ }
604
+ } catch (error) {
605
+ processingError = import_protocols.EdgeCallFailedError.fromProcessingFailureCause(error);
606
+ }
607
+ if (await shouldRetry(requestContext, retryAfterHeaderValue)) {
608
+ import_log3.log.info("retrying edge request", {
609
+ path,
610
+ processingError
611
+ }, {
612
+ F: __dxlog_file3,
613
+ L: 81,
614
+ S: this,
615
+ C: (f, a) => f(...a)
616
+ });
617
+ } else {
618
+ throw processingError;
619
+ }
620
+ }
621
+ }
622
+ };
623
+ var createRequest = (args) => {
624
+ return {
625
+ method: args.method,
626
+ body: args.body && JSON.stringify(args.body)
627
+ };
628
+ };
629
+ var isRetryable = (status) => {
630
+ if (status === 501) {
631
+ return false;
632
+ }
633
+ return !(status >= 400 && status < 500);
634
+ };
635
+ var createRetryHandler = (args) => {
636
+ if (!args.retry || args.retry.count < 1) {
637
+ return async () => false;
638
+ }
639
+ let retries = 0;
640
+ const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
641
+ const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
642
+ const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;
643
+ return async (ctx, retryAfter) => {
644
+ if (++retries > maxRetries || ctx.disposed) {
645
+ return false;
646
+ }
647
+ if (retryAfter) {
648
+ await (0, import_async3.sleep)(retryAfter);
649
+ } else {
650
+ const timeout = baseTimeout + Math.random() * jitter;
651
+ await (0, import_async3.sleep)(timeout);
652
+ }
653
+ return true;
654
+ };
655
+ };
493
656
  // Annotate the CommonJS export names for ESM import in node:
494
657
  0 && (module.exports = {
495
658
  EdgeClient,
659
+ EdgeConnectionClosedError,
660
+ EdgeHttpClient,
661
+ EdgeIdentityChangedError,
496
662
  Protocol,
663
+ createChainEdgeIdentity,
664
+ createDeviceEdgeIdentity,
665
+ createEphemeralEdgeIdentity,
666
+ createStubEdgeIdentity,
667
+ createTestHaloEdgeIdentity,
497
668
  getTypename,
498
669
  protocol,
499
670
  toUint8Array,