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