@dxos/edge-client 0.8.3 → 0.8.4-main.1068cf700f

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 (66) hide show
  1. package/dist/lib/{browser/chunk-VHS3XEIX.mjs → neutral/chunk-VESGVCLQ.mjs} +15 -11
  2. package/dist/lib/{browser/chunk-VHS3XEIX.mjs.map → neutral/chunk-VESGVCLQ.mjs.map} +3 -3
  3. package/dist/lib/{browser → neutral}/edge-ws-muxer.mjs +1 -1
  4. package/dist/lib/{browser → neutral}/index.mjs +694 -354
  5. package/dist/lib/neutral/index.mjs.map +7 -0
  6. package/dist/lib/neutral/meta.json +1 -0
  7. package/dist/lib/{browser → neutral}/testing/index.mjs +61 -16
  8. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  9. package/dist/types/src/edge-client.d.ts +15 -15
  10. package/dist/types/src/edge-client.d.ts.map +1 -1
  11. package/dist/types/src/edge-http-client.d.ts +59 -31
  12. package/dist/types/src/edge-http-client.d.ts.map +1 -1
  13. package/dist/types/src/edge-http-client.test.d.ts +2 -0
  14. package/dist/types/src/edge-http-client.test.d.ts.map +1 -0
  15. package/dist/types/src/edge-ws-connection.d.ts +20 -0
  16. package/dist/types/src/edge-ws-connection.d.ts.map +1 -1
  17. package/dist/types/src/edge-ws-muxer.d.ts.map +1 -1
  18. package/dist/types/src/http-client.d.ts +25 -0
  19. package/dist/types/src/http-client.d.ts.map +1 -0
  20. package/dist/types/src/http-client.test.d.ts +2 -0
  21. package/dist/types/src/http-client.test.d.ts.map +1 -0
  22. package/dist/types/src/index.d.ts +4 -3
  23. package/dist/types/src/index.d.ts.map +1 -1
  24. package/dist/types/src/testing/index.d.ts +1 -0
  25. package/dist/types/src/testing/index.d.ts.map +1 -1
  26. package/dist/types/src/testing/test-server.d.ts +9 -0
  27. package/dist/types/src/testing/test-server.d.ts.map +1 -0
  28. package/dist/types/src/testing/test-utils.d.ts +3 -3
  29. package/dist/types/src/testing/test-utils.d.ts.map +1 -1
  30. package/dist/types/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +30 -21
  32. package/src/edge-client.test.ts +4 -4
  33. package/src/edge-client.ts +73 -42
  34. package/src/edge-http-client.test.ts +22 -0
  35. package/src/edge-http-client.ts +368 -152
  36. package/src/edge-ws-connection.ts +129 -8
  37. package/src/edge-ws-muxer.ts +1 -1
  38. package/src/http-client.test.ts +58 -0
  39. package/src/http-client.ts +77 -0
  40. package/src/index.ts +4 -3
  41. package/src/testing/index.ts +1 -0
  42. package/src/testing/test-server.ts +45 -0
  43. package/src/testing/test-utils.ts +9 -9
  44. package/src/websocket.test.ts +1 -1
  45. package/dist/lib/browser/index.mjs.map +0 -7
  46. package/dist/lib/browser/meta.json +0 -1
  47. package/dist/lib/browser/testing/index.mjs.map +0 -7
  48. package/dist/lib/node/chunk-XNHBUTNB.cjs +0 -317
  49. package/dist/lib/node/chunk-XNHBUTNB.cjs.map +0 -7
  50. package/dist/lib/node/edge-ws-muxer.cjs +0 -33
  51. package/dist/lib/node/edge-ws-muxer.cjs.map +0 -7
  52. package/dist/lib/node/index.cjs +0 -1060
  53. package/dist/lib/node/index.cjs.map +0 -7
  54. package/dist/lib/node/meta.json +0 -1
  55. package/dist/lib/node/testing/index.cjs +0 -169
  56. package/dist/lib/node/testing/index.cjs.map +0 -7
  57. package/dist/lib/node-esm/chunk-HGQUUFIJ.mjs +0 -299
  58. package/dist/lib/node-esm/chunk-HGQUUFIJ.mjs.map +0 -7
  59. package/dist/lib/node-esm/edge-ws-muxer.mjs +0 -12
  60. package/dist/lib/node-esm/edge-ws-muxer.mjs.map +0 -7
  61. package/dist/lib/node-esm/index.mjs +0 -1035
  62. package/dist/lib/node-esm/index.mjs.map +0 -7
  63. package/dist/lib/node-esm/meta.json +0 -1
  64. package/dist/lib/node-esm/testing/index.mjs +0 -141
  65. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  66. /package/dist/lib/{browser → neutral}/edge-ws-muxer.mjs.map +0 -0
@@ -1,1035 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- CLOUDFLARE_MESSAGE_MAX_BYTES,
4
- CLOUDFLARE_RPC_MAX_BYTES,
5
- Protocol,
6
- WebSocketMuxer,
7
- getTypename,
8
- protocol,
9
- toUint8Array
10
- } from "./chunk-HGQUUFIJ.mjs";
11
-
12
- // packages/core/mesh/edge-client/src/index.ts
13
- export * from "@dxos/protocols/buf/dxos/edge/messenger_pb";
14
-
15
- // packages/core/mesh/edge-client/src/edge-client.ts
16
- import { Trigger, scheduleMicroTask, TriggerState, PersistentLifecycle, Event } from "@dxos/async";
17
- import { Resource as Resource2 } from "@dxos/context";
18
- import { log as log2, logInfo as logInfo2 } from "@dxos/log";
19
- import { EdgeStatus } from "@dxos/protocols/proto/dxos/client/services";
20
-
21
- // packages/core/mesh/edge-client/src/edge-identity.ts
22
- import { invariant } from "@dxos/invariant";
23
- import { schema } from "@dxos/protocols/proto";
24
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-identity.ts";
25
- var handleAuthChallenge = async (failedResponse, identity) => {
26
- invariant(failedResponse.status === 401, void 0, {
27
- F: __dxlog_file,
28
- L: 21,
29
- S: void 0,
30
- A: [
31
- "failedResponse.status === 401",
32
- ""
33
- ]
34
- });
35
- const headerValue = failedResponse.headers.get("Www-Authenticate");
36
- invariant(headerValue?.startsWith("VerifiablePresentation challenge="), void 0, {
37
- F: __dxlog_file,
38
- L: 24,
39
- S: void 0,
40
- A: [
41
- "headerValue?.startsWith('VerifiablePresentation challenge=')",
42
- ""
43
- ]
44
- });
45
- const challenge = headerValue?.slice("VerifiablePresentation challenge=".length);
46
- invariant(challenge, void 0, {
47
- F: __dxlog_file,
48
- L: 27,
49
- S: void 0,
50
- A: [
51
- "challenge",
52
- ""
53
- ]
54
- });
55
- const presentation = await identity.presentCredentials({
56
- challenge: Buffer.from(challenge, "base64")
57
- });
58
- return schema.getCodecForType("dxos.halo.credentials.Presentation").encode(presentation);
59
- };
60
-
61
- // packages/core/mesh/edge-client/src/edge-ws-connection.ts
62
- import WebSocket from "isomorphic-ws";
63
- import { scheduleTask, scheduleTaskInterval } from "@dxos/async";
64
- import { Context, Resource } from "@dxos/context";
65
- import { invariant as invariant2 } from "@dxos/invariant";
66
- import { log, logInfo } from "@dxos/log";
67
- import { EdgeWebsocketProtocol } from "@dxos/protocols";
68
- import { buf } from "@dxos/protocols/buf";
69
- import { MessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
70
- function _ts_decorate(decorators, target, key, desc) {
71
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
72
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
73
- 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;
74
- return c > 3 && r && Object.defineProperty(target, key, r), r;
75
- }
76
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-ws-connection.ts";
77
- var SIGNAL_KEEPALIVE_INTERVAL = 4e3;
78
- var SIGNAL_KEEPALIVE_TIMEOUT = 12e3;
79
- var EdgeWsConnection = class extends Resource {
80
- constructor(_identity, _connectionInfo, _callbacks) {
81
- super(), this._identity = _identity, this._connectionInfo = _connectionInfo, this._callbacks = _callbacks;
82
- }
83
- get info() {
84
- return {
85
- open: this.isOpen,
86
- identity: this._identity.identityKey,
87
- device: this._identity.peerKey
88
- };
89
- }
90
- send(message) {
91
- invariant2(this._ws, void 0, {
92
- F: __dxlog_file2,
93
- L: 52,
94
- S: this,
95
- A: [
96
- "this._ws",
97
- ""
98
- ]
99
- });
100
- invariant2(this._wsMuxer, void 0, {
101
- F: __dxlog_file2,
102
- L: 53,
103
- S: this,
104
- A: [
105
- "this._wsMuxer",
106
- ""
107
- ]
108
- });
109
- log("sending...", {
110
- peerKey: this._identity.peerKey,
111
- payload: protocol.getPayloadType(message)
112
- }, {
113
- F: __dxlog_file2,
114
- L: 54,
115
- S: this,
116
- C: (f, a) => f(...a)
117
- });
118
- if (this._ws?.protocol.includes(EdgeWebsocketProtocol.V0)) {
119
- const binary = buf.toBinary(MessageSchema, message);
120
- if (binary.length > CLOUDFLARE_MESSAGE_MAX_BYTES) {
121
- log.error("Message dropped because it was too large (>1MB).", {
122
- byteLength: binary.byteLength,
123
- serviceId: message.serviceId,
124
- payload: protocol.getPayloadType(message)
125
- }, {
126
- F: __dxlog_file2,
127
- L: 58,
128
- S: this,
129
- C: (f, a) => f(...a)
130
- });
131
- return;
132
- }
133
- this._ws.send(binary);
134
- } else {
135
- this._wsMuxer.send(message).catch((e) => log.catch(e, void 0, {
136
- F: __dxlog_file2,
137
- L: 67,
138
- S: this,
139
- C: (f, a) => f(...a)
140
- }));
141
- }
142
- }
143
- async _open() {
144
- const baseProtocols = [
145
- ...Object.values(EdgeWebsocketProtocol)
146
- ];
147
- this._ws = new WebSocket(this._connectionInfo.url.toString(), this._connectionInfo.protocolHeader ? [
148
- ...baseProtocols,
149
- this._connectionInfo.protocolHeader
150
- ] : [
151
- ...baseProtocols
152
- ]);
153
- const muxer = new WebSocketMuxer(this._ws);
154
- this._wsMuxer = muxer;
155
- this._ws.onopen = () => {
156
- if (this.isOpen) {
157
- log("connected", void 0, {
158
- F: __dxlog_file2,
159
- L: 84,
160
- S: this,
161
- C: (f, a) => f(...a)
162
- });
163
- this._callbacks.onConnected();
164
- this._scheduleHeartbeats();
165
- } else {
166
- log.verbose("connected after becoming inactive", {
167
- currentIdentity: this._identity
168
- }, {
169
- F: __dxlog_file2,
170
- L: 88,
171
- S: this,
172
- C: (f, a) => f(...a)
173
- });
174
- }
175
- };
176
- this._ws.onclose = (event) => {
177
- if (this.isOpen) {
178
- log.warn("disconnected while being open", {
179
- code: event.code,
180
- reason: event.reason
181
- }, {
182
- F: __dxlog_file2,
183
- L: 93,
184
- S: this,
185
- C: (f, a) => f(...a)
186
- });
187
- this._callbacks.onRestartRequired();
188
- muxer.destroy();
189
- }
190
- };
191
- this._ws.onerror = (event) => {
192
- if (this.isOpen) {
193
- log.warn("edge connection socket error", {
194
- error: event.error,
195
- info: event.message
196
- }, {
197
- F: __dxlog_file2,
198
- L: 100,
199
- S: this,
200
- C: (f, a) => f(...a)
201
- });
202
- this._callbacks.onRestartRequired();
203
- } else {
204
- log.verbose("error ignored on closed connection", {
205
- error: event.error
206
- }, {
207
- F: __dxlog_file2,
208
- L: 103,
209
- S: this,
210
- C: (f, a) => f(...a)
211
- });
212
- }
213
- };
214
- this._ws.onmessage = async (event) => {
215
- if (!this.isOpen) {
216
- log.verbose("message ignored on closed connection", {
217
- event: event.type
218
- }, {
219
- F: __dxlog_file2,
220
- L: 111,
221
- S: this,
222
- C: (f, a) => f(...a)
223
- });
224
- return;
225
- }
226
- if (event.data === "__pong__") {
227
- this._rescheduleHeartbeatTimeout();
228
- return;
229
- }
230
- const bytes = await toUint8Array(event.data);
231
- if (!this.isOpen) {
232
- return;
233
- }
234
- const message = this._ws?.protocol?.includes(EdgeWebsocketProtocol.V0) ? buf.fromBinary(MessageSchema, bytes) : muxer.receiveData(bytes);
235
- if (message) {
236
- log("received", {
237
- from: message.source,
238
- payload: protocol.getPayloadType(message)
239
- }, {
240
- F: __dxlog_file2,
241
- L: 128,
242
- S: this,
243
- C: (f, a) => f(...a)
244
- });
245
- this._callbacks.onMessage(message);
246
- }
247
- };
248
- }
249
- async _close() {
250
- void this._inactivityTimeoutCtx?.dispose().catch(() => {
251
- });
252
- try {
253
- this._ws?.close();
254
- this._ws = void 0;
255
- this._wsMuxer?.destroy();
256
- this._wsMuxer = void 0;
257
- } catch (err) {
258
- if (err instanceof Error && err.message.includes("WebSocket is closed before the connection is established.")) {
259
- return;
260
- }
261
- log.warn("Error closing websocket", {
262
- err
263
- }, {
264
- F: __dxlog_file2,
265
- L: 146,
266
- S: this,
267
- C: (f, a) => f(...a)
268
- });
269
- }
270
- }
271
- _scheduleHeartbeats() {
272
- invariant2(this._ws, void 0, {
273
- F: __dxlog_file2,
274
- L: 151,
275
- S: this,
276
- A: [
277
- "this._ws",
278
- ""
279
- ]
280
- });
281
- scheduleTaskInterval(this._ctx, async () => {
282
- this._ws?.send("__ping__");
283
- }, SIGNAL_KEEPALIVE_INTERVAL);
284
- this._ws.send("__ping__");
285
- this._rescheduleHeartbeatTimeout();
286
- }
287
- _rescheduleHeartbeatTimeout() {
288
- if (!this.isOpen) {
289
- return;
290
- }
291
- void this._inactivityTimeoutCtx?.dispose();
292
- this._inactivityTimeoutCtx = new Context(void 0, {
293
- F: __dxlog_file2,
294
- L: 170
295
- });
296
- scheduleTask(this._inactivityTimeoutCtx, () => {
297
- if (this.isOpen) {
298
- log.warn("restart due to inactivity timeout", void 0, {
299
- F: __dxlog_file2,
300
- L: 175,
301
- S: this,
302
- C: (f, a) => f(...a)
303
- });
304
- this._callbacks.onRestartRequired();
305
- }
306
- }, SIGNAL_KEEPALIVE_TIMEOUT);
307
- }
308
- };
309
- _ts_decorate([
310
- logInfo
311
- ], EdgeWsConnection.prototype, "info", null);
312
-
313
- // packages/core/mesh/edge-client/src/errors.ts
314
- var EdgeConnectionClosedError = class extends Error {
315
- constructor() {
316
- super("Edge connection closed.");
317
- }
318
- };
319
- var EdgeIdentityChangedError = class extends Error {
320
- constructor() {
321
- super("Edge identity changed.");
322
- }
323
- };
324
-
325
- // packages/core/mesh/edge-client/src/utils.ts
326
- var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
327
- const isSecure = baseUrl.startsWith("https") || baseUrl.startsWith("wss");
328
- const url = new URL(baseUrl);
329
- url.protocol = protocol2 + (isSecure ? "s" : "");
330
- return url.toString();
331
- };
332
-
333
- // packages/core/mesh/edge-client/src/edge-client.ts
334
- function _ts_decorate2(decorators, target, key, desc) {
335
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
336
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
337
- 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;
338
- return c > 3 && r && Object.defineProperty(target, key, r), r;
339
- }
340
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
341
- var DEFAULT_TIMEOUT = 1e4;
342
- var EdgeClient = class extends Resource2 {
343
- constructor(_identity, _config) {
344
- super(), this._identity = _identity, this._config = _config, this.statusChanged = new Event(), this._persistentLifecycle = new PersistentLifecycle({
345
- start: async () => this._connect(),
346
- stop: async (state) => this._disconnect(state)
347
- }), this._messageListeners = /* @__PURE__ */ new Set(), this._reconnectListeners = /* @__PURE__ */ new Set(), this._currentConnection = void 0, this._ready = new Trigger(), this._isActive = (connection) => connection === this._currentConnection;
348
- this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
349
- this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
350
- }
351
- get info() {
352
- return {
353
- open: this.isOpen,
354
- status: this.status,
355
- identity: this._identity.identityKey,
356
- device: this._identity.peerKey
357
- };
358
- }
359
- get status() {
360
- return Boolean(this._currentConnection) && this._ready.state === TriggerState.RESOLVED ? EdgeStatus.CONNECTED : EdgeStatus.NOT_CONNECTED;
361
- }
362
- get identityKey() {
363
- return this._identity.identityKey;
364
- }
365
- get peerKey() {
366
- return this._identity.peerKey;
367
- }
368
- setIdentity(identity) {
369
- if (identity.identityKey !== this._identity.identityKey || identity.peerKey !== this._identity.peerKey) {
370
- log2("Edge identity changed", {
371
- identity,
372
- oldIdentity: this._identity
373
- }, {
374
- F: __dxlog_file3,
375
- L: 99,
376
- S: this,
377
- C: (f, a) => f(...a)
378
- });
379
- this._identity = identity;
380
- this._closeCurrentConnection(new EdgeIdentityChangedError());
381
- void this._persistentLifecycle.scheduleRestart();
382
- }
383
- }
384
- onMessage(listener) {
385
- this._messageListeners.add(listener);
386
- return () => this._messageListeners.delete(listener);
387
- }
388
- onReconnected(listener) {
389
- this._reconnectListeners.add(listener);
390
- if (this._ready.state === TriggerState.RESOLVED) {
391
- scheduleMicroTask(this._ctx, () => {
392
- if (this._reconnectListeners.has(listener)) {
393
- try {
394
- listener();
395
- } catch (error) {
396
- log2.catch(error, void 0, {
397
- F: __dxlog_file3,
398
- L: 121,
399
- S: this,
400
- C: (f, a) => f(...a)
401
- });
402
- }
403
- }
404
- });
405
- }
406
- return () => this._reconnectListeners.delete(listener);
407
- }
408
- /**
409
- * Open connection to messaging service.
410
- */
411
- async _open() {
412
- log2("opening...", {
413
- info: this.info
414
- }, {
415
- F: __dxlog_file3,
416
- L: 133,
417
- S: this,
418
- C: (f, a) => f(...a)
419
- });
420
- this._persistentLifecycle.open().catch((err) => {
421
- log2.warn("Error while opening connection", {
422
- err
423
- }, {
424
- F: __dxlog_file3,
425
- L: 135,
426
- S: this,
427
- C: (f, a) => f(...a)
428
- });
429
- });
430
- }
431
- /**
432
- * Close connection and free resources.
433
- */
434
- async _close() {
435
- log2("closing...", {
436
- peerKey: this._identity.peerKey
437
- }, {
438
- F: __dxlog_file3,
439
- L: 143,
440
- S: this,
441
- C: (f, a) => f(...a)
442
- });
443
- this._closeCurrentConnection();
444
- await this._persistentLifecycle.close();
445
- }
446
- async _connect() {
447
- if (this._ctx.disposed) {
448
- return void 0;
449
- }
450
- const identity = this._identity;
451
- const path = `/ws/${identity.identityKey}/${identity.peerKey}`;
452
- const protocolHeader = this._config.disableAuth ? void 0 : await this._createAuthHeader(path);
453
- if (this._identity !== identity) {
454
- log2("identity changed during auth header request", void 0, {
455
- F: __dxlog_file3,
456
- L: 157,
457
- S: this,
458
- C: (f, a) => f(...a)
459
- });
460
- return void 0;
461
- }
462
- const restartRequired = new Trigger();
463
- const url = new URL(path, this._baseWsUrl);
464
- log2("Opening websocket", {
465
- url: url.toString(),
466
- protocolHeader
467
- }, {
468
- F: __dxlog_file3,
469
- L: 163,
470
- S: this,
471
- C: (f, a) => f(...a)
472
- });
473
- const connection = new EdgeWsConnection(identity, {
474
- url,
475
- protocolHeader
476
- }, {
477
- onConnected: () => {
478
- if (this._isActive(connection)) {
479
- this._ready.wake();
480
- this._notifyReconnected();
481
- } else {
482
- log2.verbose("connected callback ignored, because connection is not active", void 0, {
483
- F: __dxlog_file3,
484
- L: 173,
485
- S: this,
486
- C: (f, a) => f(...a)
487
- });
488
- }
489
- },
490
- onRestartRequired: () => {
491
- if (this._isActive(connection)) {
492
- this._closeCurrentConnection();
493
- void this._persistentLifecycle.scheduleRestart();
494
- } else {
495
- log2.verbose("restart requested by inactive connection", void 0, {
496
- F: __dxlog_file3,
497
- L: 181,
498
- S: this,
499
- C: (f, a) => f(...a)
500
- });
501
- }
502
- restartRequired.wake();
503
- },
504
- onMessage: (message) => {
505
- if (this._isActive(connection)) {
506
- this._notifyMessageReceived(message);
507
- } else {
508
- log2.verbose("ignored a message on inactive connection", {
509
- from: message.source,
510
- type: message.payload?.typeUrl
511
- }, {
512
- F: __dxlog_file3,
513
- L: 189,
514
- S: this,
515
- C: (f, a) => f(...a)
516
- });
517
- }
518
- }
519
- });
520
- this._currentConnection = connection;
521
- await connection.open();
522
- await Promise.race([
523
- this._ready.wait({
524
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
525
- }),
526
- restartRequired
527
- ]);
528
- return connection;
529
- }
530
- async _disconnect(state) {
531
- await state.close();
532
- this.statusChanged.emit(this.status);
533
- }
534
- _closeCurrentConnection(error = new EdgeConnectionClosedError()) {
535
- this._currentConnection = void 0;
536
- this._ready.throw(error);
537
- this._ready.reset();
538
- this.statusChanged.emit(this.status);
539
- }
540
- _notifyReconnected() {
541
- this.statusChanged.emit(this.status);
542
- for (const listener of this._reconnectListeners) {
543
- try {
544
- listener();
545
- } catch (err) {
546
- log2.error("ws reconnect listener failed", {
547
- err
548
- }, {
549
- F: __dxlog_file3,
550
- L: 225,
551
- S: this,
552
- C: (f, a) => f(...a)
553
- });
554
- }
555
- }
556
- }
557
- _notifyMessageReceived(message) {
558
- for (const listener of this._messageListeners) {
559
- try {
560
- listener(message);
561
- } catch (err) {
562
- log2.error("ws incoming message processing failed", {
563
- err,
564
- payload: protocol.getPayloadType(message)
565
- }, {
566
- F: __dxlog_file3,
567
- L: 235,
568
- S: this,
569
- C: (f, a) => f(...a)
570
- });
571
- }
572
- }
573
- }
574
- /**
575
- * Send message.
576
- * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.
577
- */
578
- async send(message) {
579
- if (this._ready.state !== TriggerState.RESOLVED) {
580
- log2("waiting for websocket to become ready", void 0, {
581
- F: __dxlog_file3,
582
- L: 246,
583
- S: this,
584
- C: (f, a) => f(...a)
585
- });
586
- await this._ready.wait({
587
- timeout: this._config.timeout ?? DEFAULT_TIMEOUT
588
- });
589
- }
590
- if (!this._currentConnection) {
591
- throw new EdgeConnectionClosedError();
592
- }
593
- if (message.source && (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)) {
594
- throw new EdgeIdentityChangedError();
595
- }
596
- this._currentConnection.send(message);
597
- }
598
- async _createAuthHeader(path) {
599
- const httpUrl = new URL(path, this._baseHttpUrl);
600
- httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), "http");
601
- const response = await fetch(httpUrl, {
602
- method: "GET"
603
- });
604
- if (response.status === 401) {
605
- return encodePresentationWsAuthHeader(await handleAuthChallenge(response, this._identity));
606
- } else {
607
- log2.warn("no auth challenge from edge", {
608
- status: response.status,
609
- statusText: response.statusText
610
- }, {
611
- F: __dxlog_file3,
612
- L: 271,
613
- S: this,
614
- C: (f, a) => f(...a)
615
- });
616
- return void 0;
617
- }
618
- }
619
- };
620
- _ts_decorate2([
621
- logInfo2
622
- ], EdgeClient.prototype, "info", null);
623
- var encodePresentationWsAuthHeader = (encodedPresentation) => {
624
- const encodedToken = Buffer.from(encodedPresentation).toString("base64").replace(/=*$/, "").replaceAll("/", "|");
625
- return `base64url.bearer.authorization.dxos.org.${encodedToken}`;
626
- };
627
-
628
- // packages/core/mesh/edge-client/src/auth.ts
629
- import { createCredential, signPresentation } from "@dxos/credentials";
630
- import { invariant as invariant3 } from "@dxos/invariant";
631
- import { Keyring } from "@dxos/keyring";
632
- import { PublicKey } from "@dxos/keys";
633
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/auth.ts";
634
- var createDeviceEdgeIdentity = async (signer, key) => {
635
- return {
636
- identityKey: key.toHex(),
637
- peerKey: key.toHex(),
638
- presentCredentials: async ({ challenge }) => {
639
- return signPresentation({
640
- presentation: {
641
- credentials: [
642
- // Verifier requires at least one credential in the presentation to establish the subject.
643
- await createCredential({
644
- assertion: {
645
- "@type": "dxos.halo.credentials.Auth"
646
- },
647
- issuer: key,
648
- subject: key,
649
- signer
650
- })
651
- ]
652
- },
653
- signer,
654
- signerKey: key,
655
- nonce: challenge
656
- });
657
- }
658
- };
659
- };
660
- var createChainEdgeIdentity = async (signer, identityKey, peerKey, chain, credentials) => {
661
- const credentialsToSign = credentials.length > 0 ? credentials : [
662
- await createCredential({
663
- assertion: {
664
- "@type": "dxos.halo.credentials.Auth"
665
- },
666
- issuer: identityKey,
667
- subject: identityKey,
668
- signer,
669
- chain,
670
- signingKey: peerKey
671
- })
672
- ];
673
- return {
674
- identityKey: identityKey.toHex(),
675
- peerKey: peerKey.toHex(),
676
- presentCredentials: async ({ challenge }) => {
677
- invariant3(chain, void 0, {
678
- F: __dxlog_file4,
679
- L: 75,
680
- S: void 0,
681
- A: [
682
- "chain",
683
- ""
684
- ]
685
- });
686
- return signPresentation({
687
- presentation: {
688
- credentials: credentialsToSign
689
- },
690
- signer,
691
- nonce: challenge,
692
- signerKey: peerKey,
693
- chain
694
- });
695
- }
696
- };
697
- };
698
- var createEphemeralEdgeIdentity = async () => {
699
- const keyring = new Keyring();
700
- const key = await keyring.createKey();
701
- return createDeviceEdgeIdentity(keyring, key);
702
- };
703
- var createTestHaloEdgeIdentity = async (signer, identityKey, deviceKey) => {
704
- const deviceAdmission = await createCredential({
705
- assertion: {
706
- "@type": "dxos.halo.credentials.AuthorizedDevice",
707
- deviceKey,
708
- identityKey
709
- },
710
- issuer: identityKey,
711
- subject: deviceKey,
712
- signer
713
- });
714
- return createChainEdgeIdentity(signer, identityKey, deviceKey, {
715
- credential: deviceAdmission
716
- }, [
717
- await createCredential({
718
- assertion: {
719
- "@type": "dxos.halo.credentials.Auth"
720
- },
721
- issuer: identityKey,
722
- subject: identityKey,
723
- signer
724
- })
725
- ]);
726
- };
727
- var createStubEdgeIdentity = () => {
728
- const identityKey = PublicKey.random();
729
- const deviceKey = PublicKey.random();
730
- return {
731
- identityKey: identityKey.toHex(),
732
- peerKey: deviceKey.toHex(),
733
- presentCredentials: async () => {
734
- throw new Error("Stub identity does not support authentication.");
735
- }
736
- };
737
- };
738
-
739
- // packages/core/mesh/edge-client/src/edge-http-client.ts
740
- import { sleep } from "@dxos/async";
741
- import { Context as Context2 } from "@dxos/context";
742
- import { log as log3 } from "@dxos/log";
743
- import { EdgeCallFailedError, EdgeAuthChallengeError } from "@dxos/protocols";
744
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
745
- var DEFAULT_RETRY_TIMEOUT = 1500;
746
- var DEFAULT_RETRY_JITTER = 500;
747
- var DEFAULT_MAX_RETRIES_COUNT = 3;
748
- var EdgeHttpClient = class {
749
- constructor(baseUrl) {
750
- this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
751
- log3("created", {
752
- url: this._baseUrl
753
- }, {
754
- F: __dxlog_file5,
755
- L: 53,
756
- S: this,
757
- C: (f, a) => f(...a)
758
- });
759
- }
760
- get baseUrl() {
761
- return this._baseUrl;
762
- }
763
- setIdentity(identity) {
764
- if (this._edgeIdentity?.identityKey !== identity.identityKey || this._edgeIdentity?.peerKey !== identity.peerKey) {
765
- this._edgeIdentity = identity;
766
- this._authHeader = void 0;
767
- }
768
- }
769
- createAgent(body, args) {
770
- return this._call("/agents/create", {
771
- ...args,
772
- method: "POST",
773
- body
774
- });
775
- }
776
- getAgentStatus(request, args) {
777
- return this._call(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, {
778
- ...args,
779
- method: "GET"
780
- });
781
- }
782
- getCredentialsForNotarization(spaceId, args) {
783
- return this._call(`/spaces/${spaceId}/notarization`, {
784
- ...args,
785
- method: "GET"
786
- });
787
- }
788
- async notarizeCredentials(spaceId, body, args) {
789
- await this._call(`/spaces/${spaceId}/notarization`, {
790
- ...args,
791
- body,
792
- method: "POST"
793
- });
794
- }
795
- async joinSpaceByInvitation(spaceId, body, args) {
796
- return this._call(`/spaces/${spaceId}/join`, {
797
- ...args,
798
- body,
799
- method: "POST"
800
- });
801
- }
802
- async recoverIdentity(body, args) {
803
- return this._call("/identity/recover", {
804
- ...args,
805
- body,
806
- method: "POST"
807
- });
808
- }
809
- async executeWorkflow(spaceId, graphId, input, args) {
810
- return this._call(`/workflows/${spaceId}/${graphId}`, {
811
- ...args,
812
- body: input,
813
- method: "POST"
814
- });
815
- }
816
- async uploadFunction(pathParts, body, args) {
817
- const path = [
818
- "functions",
819
- ...pathParts.functionId ? [
820
- pathParts.functionId
821
- ] : []
822
- ].join("/");
823
- return this._call(path, {
824
- ...args,
825
- body,
826
- method: "PUT"
827
- });
828
- }
829
- async initiateOAuthFlow(body, args) {
830
- return this._call("/oauth/initiate", {
831
- ...args,
832
- body,
833
- method: "POST"
834
- });
835
- }
836
- async queryQueue(subspaceTag, spaceId, query, args) {
837
- const { queueId } = query;
838
- const queryParams = new URLSearchParams();
839
- if (query.after != null) {
840
- queryParams.set("after", query.after);
841
- }
842
- if (query.before != null) {
843
- queryParams.set("before", query.before);
844
- }
845
- if (query.limit != null) {
846
- queryParams.set("limit", query.limit.toString());
847
- }
848
- if (query.reverse != null) {
849
- queryParams.set("reverse", query.reverse.toString());
850
- }
851
- if (query.objectIds != null) {
852
- queryParams.set("objectIds", query.objectIds.join(","));
853
- }
854
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query?${queryParams.toString()}`, {
855
- ...args,
856
- method: "GET"
857
- });
858
- }
859
- async insertIntoQueue(subspaceTag, spaceId, queueId, objects, args) {
860
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {
861
- ...args,
862
- body: {
863
- objects
864
- },
865
- method: "POST"
866
- });
867
- }
868
- async deleteFromQueue(subspaceTag, spaceId, queueId, objectIds, args) {
869
- return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {
870
- ...args,
871
- query: {
872
- ids: objectIds.join(",")
873
- },
874
- method: "DELETE"
875
- });
876
- }
877
- async createSpace(body, args) {
878
- return this._call("/spaces/create", {
879
- ...args,
880
- body,
881
- method: "POST"
882
- });
883
- }
884
- async _call(path, args) {
885
- const requestContext = args.context ?? new Context2(void 0, {
886
- F: __dxlog_file5,
887
- L: 192
888
- });
889
- const shouldRetry = createRetryHandler(args);
890
- let url = `${this._baseUrl}${path.startsWith("/") ? path.slice(1) : path}`;
891
- if (args.query) {
892
- const queryParams = new URLSearchParams();
893
- for (const [key, value] of Object.entries(args.query)) {
894
- queryParams.set(key, value.toString());
895
- }
896
- url += `?${queryParams.toString()}`;
897
- }
898
- log3("call", {
899
- method: args.method,
900
- path,
901
- request: args.body
902
- }, {
903
- F: __dxlog_file5,
904
- L: 204,
905
- S: this,
906
- C: (f, a) => f(...a)
907
- });
908
- let handledAuth = false;
909
- let authHeader = this._authHeader;
910
- while (true) {
911
- let processingError;
912
- let retryAfterHeaderValue = Number.NaN;
913
- try {
914
- const request = createRequest(args, authHeader);
915
- const response = await fetch(url, request);
916
- retryAfterHeaderValue = Number(response.headers.get("Retry-After"));
917
- if (response.ok) {
918
- const body = await response.json();
919
- if (body.success) {
920
- return body.data;
921
- }
922
- log3("unsuccessful edge response", {
923
- path,
924
- body
925
- }, {
926
- F: __dxlog_file5,
927
- L: 223,
928
- S: this,
929
- C: (f, a) => f(...a)
930
- });
931
- if (body.errorData?.type === "auth_challenge" && typeof body.errorData?.challenge === "string") {
932
- processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
933
- } else {
934
- processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
935
- }
936
- } else if (response.status === 401 && !handledAuth) {
937
- authHeader = await this._handleUnauthorized(response);
938
- handledAuth = true;
939
- continue;
940
- } else {
941
- processingError = EdgeCallFailedError.fromHttpFailure(response);
942
- }
943
- } catch (error) {
944
- processingError = EdgeCallFailedError.fromProcessingFailureCause(error);
945
- }
946
- if (processingError.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
947
- log3("retrying edge request", {
948
- path,
949
- processingError
950
- }, {
951
- F: __dxlog_file5,
952
- L: 242,
953
- S: this,
954
- C: (f, a) => f(...a)
955
- });
956
- } else {
957
- throw processingError;
958
- }
959
- }
960
- }
961
- async _handleUnauthorized(response) {
962
- if (!this._edgeIdentity) {
963
- log3.warn("edge unauthorized response received before identity was set", void 0, {
964
- F: __dxlog_file5,
965
- L: 251,
966
- S: this,
967
- C: (f, a) => f(...a)
968
- });
969
- throw EdgeCallFailedError.fromHttpFailure(response);
970
- }
971
- const challenge = await handleAuthChallenge(response, this._edgeIdentity);
972
- this._authHeader = encodeAuthHeader(challenge);
973
- log3("auth header updated", void 0, {
974
- F: __dxlog_file5,
975
- L: 256,
976
- S: this,
977
- C: (f, a) => f(...a)
978
- });
979
- return this._authHeader;
980
- }
981
- };
982
- var createRetryHandler = (args) => {
983
- if (!args.retry || args.retry.count < 1) {
984
- return async () => false;
985
- }
986
- let retries = 0;
987
- const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
988
- const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
989
- const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;
990
- return async (ctx, retryAfter) => {
991
- if (++retries > maxRetries || ctx.disposed) {
992
- return false;
993
- }
994
- if (retryAfter) {
995
- await sleep(retryAfter);
996
- } else {
997
- const timeout = baseTimeout + Math.random() * jitter;
998
- await sleep(timeout);
999
- }
1000
- return true;
1001
- };
1002
- };
1003
- var createRequest = (args, authHeader) => {
1004
- return {
1005
- method: args.method,
1006
- body: args.body && JSON.stringify(args.body),
1007
- headers: authHeader ? {
1008
- Authorization: authHeader
1009
- } : void 0
1010
- };
1011
- };
1012
- var encodeAuthHeader = (challenge) => {
1013
- const encodedChallenge = Buffer.from(challenge).toString("base64");
1014
- return `VerifiablePresentation pb;base64,${encodedChallenge}`;
1015
- };
1016
- export {
1017
- CLOUDFLARE_MESSAGE_MAX_BYTES,
1018
- CLOUDFLARE_RPC_MAX_BYTES,
1019
- EdgeClient,
1020
- EdgeConnectionClosedError,
1021
- EdgeHttpClient,
1022
- EdgeIdentityChangedError,
1023
- Protocol,
1024
- WebSocketMuxer,
1025
- createChainEdgeIdentity,
1026
- createDeviceEdgeIdentity,
1027
- createEphemeralEdgeIdentity,
1028
- createStubEdgeIdentity,
1029
- createTestHaloEdgeIdentity,
1030
- getTypename,
1031
- handleAuthChallenge,
1032
- protocol,
1033
- toUint8Array
1034
- };
1035
- //# sourceMappingURL=index.mjs.map