@dxos/edge-client 0.8.2-main.12df754 → 0.8.2-main.2f9c567
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.
- package/dist/lib/browser/chunk-TKYUZ5ZK.mjs +302 -0
- package/dist/lib/browser/chunk-TKYUZ5ZK.mjs.map +7 -0
- package/dist/lib/browser/edge-ws-muxer.mjs +11 -0
- package/dist/lib/browser/edge-ws-muxer.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +70 -32
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +32 -20
- package/dist/lib/browser/testing/index.mjs.map +3 -3
- package/dist/lib/node/chunk-ZOL3YSDR.cjs +322 -0
- package/dist/lib/node/chunk-ZOL3YSDR.cjs.map +7 -0
- package/dist/lib/node/edge-ws-muxer.cjs +33 -0
- package/dist/lib/node/edge-ws-muxer.cjs.map +7 -0
- package/dist/lib/node/index.cjs +83 -45
- package/dist/lib/node/index.cjs.map +3 -3
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +32 -21
- package/dist/lib/node/testing/index.cjs.map +3 -3
- package/dist/lib/node-esm/chunk-25HGRGNZ.mjs +304 -0
- package/dist/lib/node-esm/chunk-25HGRGNZ.mjs.map +7 -0
- package/dist/lib/node-esm/edge-ws-muxer.mjs +12 -0
- package/dist/lib/node-esm/edge-ws-muxer.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +70 -32
- package/dist/lib/node-esm/index.mjs.map +3 -3
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +32 -20
- package/dist/lib/node-esm/testing/index.mjs.map +3 -3
- package/dist/types/src/edge-ws-connection.d.ts +1 -0
- package/dist/types/src/edge-ws-connection.d.ts.map +1 -1
- package/dist/types/src/edge-ws-muxer.d.ts +35 -0
- package/dist/types/src/edge-ws-muxer.d.ts.map +1 -0
- package/dist/types/src/edge-ws-muxer.test.d.ts +2 -0
- package/dist/types/src/edge-ws-muxer.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/testing/test-utils.d.ts +6 -2
- package/dist/types/src/testing/test-utils.d.ts.map +1 -1
- package/package.json +19 -14
- package/src/edge-client.ts +2 -2
- package/src/edge-ws-connection.ts +36 -18
- package/src/edge-ws-muxer.test.ts +55 -0
- package/src/edge-ws-muxer.ts +217 -0
- package/src/index.ts +1 -0
- package/src/testing/test-utils.ts +33 -26
- package/dist/lib/browser/chunk-ZWJXA37R.mjs +0 -113
- package/dist/lib/browser/chunk-ZWJXA37R.mjs.map +0 -7
- package/dist/lib/node/chunk-ANV2HBEH.cjs +0 -136
- package/dist/lib/node/chunk-ANV2HBEH.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-HNVT57AU.mjs +0 -115
- package/dist/lib/node-esm/chunk-HNVT57AU.mjs.map +0 -7
package/dist/lib/node/index.cjs
CHANGED
|
@@ -29,23 +29,26 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
29
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
30
|
var node_exports = {};
|
|
31
31
|
__export(node_exports, {
|
|
32
|
+
CLOUDFLARE_MESSAGE_MAX_BYTES: () => import_chunk_ZOL3YSDR.CLOUDFLARE_MESSAGE_MAX_BYTES,
|
|
33
|
+
CLOUDFLARE_RPC_MAX_BYTES: () => import_chunk_ZOL3YSDR.CLOUDFLARE_RPC_MAX_BYTES,
|
|
32
34
|
EdgeClient: () => EdgeClient,
|
|
33
35
|
EdgeConnectionClosedError: () => EdgeConnectionClosedError,
|
|
34
36
|
EdgeHttpClient: () => EdgeHttpClient,
|
|
35
37
|
EdgeIdentityChangedError: () => EdgeIdentityChangedError,
|
|
36
|
-
Protocol: () =>
|
|
38
|
+
Protocol: () => import_chunk_ZOL3YSDR.Protocol,
|
|
39
|
+
WebSocketMuxer: () => import_chunk_ZOL3YSDR.WebSocketMuxer,
|
|
37
40
|
createChainEdgeIdentity: () => createChainEdgeIdentity,
|
|
38
41
|
createDeviceEdgeIdentity: () => createDeviceEdgeIdentity,
|
|
39
42
|
createEphemeralEdgeIdentity: () => createEphemeralEdgeIdentity,
|
|
40
43
|
createStubEdgeIdentity: () => createStubEdgeIdentity,
|
|
41
44
|
createTestHaloEdgeIdentity: () => createTestHaloEdgeIdentity,
|
|
42
|
-
getTypename: () =>
|
|
45
|
+
getTypename: () => import_chunk_ZOL3YSDR.getTypename,
|
|
43
46
|
handleAuthChallenge: () => handleAuthChallenge,
|
|
44
|
-
protocol: () =>
|
|
45
|
-
toUint8Array: () =>
|
|
47
|
+
protocol: () => import_chunk_ZOL3YSDR.protocol,
|
|
48
|
+
toUint8Array: () => import_chunk_ZOL3YSDR.toUint8Array
|
|
46
49
|
});
|
|
47
50
|
module.exports = __toCommonJS(node_exports);
|
|
48
|
-
var
|
|
51
|
+
var import_chunk_ZOL3YSDR = require("./chunk-ZOL3YSDR.cjs");
|
|
49
52
|
__reExport(node_exports, require("@dxos/protocols/buf/dxos/edge/messenger_pb"), module.exports);
|
|
50
53
|
var import_async = require("@dxos/async");
|
|
51
54
|
var import_context = require("@dxos/context");
|
|
@@ -58,6 +61,7 @@ var import_async2 = require("@dxos/async");
|
|
|
58
61
|
var import_context2 = require("@dxos/context");
|
|
59
62
|
var import_invariant2 = require("@dxos/invariant");
|
|
60
63
|
var import_log2 = require("@dxos/log");
|
|
64
|
+
var import_protocols = require("@dxos/protocols");
|
|
61
65
|
var import_buf = require("@dxos/protocols/buf");
|
|
62
66
|
var import_messenger_pb = require("@dxos/protocols/buf/dxos/edge/messenger_pb");
|
|
63
67
|
var import_credentials = require("@dxos/credentials");
|
|
@@ -67,7 +71,7 @@ var import_keys = require("@dxos/keys");
|
|
|
67
71
|
var import_async3 = require("@dxos/async");
|
|
68
72
|
var import_context3 = require("@dxos/context");
|
|
69
73
|
var import_log3 = require("@dxos/log");
|
|
70
|
-
var
|
|
74
|
+
var import_protocols2 = require("@dxos/protocols");
|
|
71
75
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-identity.ts";
|
|
72
76
|
var handleAuthChallenge = async (failedResponse, identity) => {
|
|
73
77
|
(0, import_invariant.invariant)(failedResponse.status === 401, void 0, {
|
|
@@ -113,7 +117,6 @@ function _ts_decorate(decorators, target, key, desc) {
|
|
|
113
117
|
var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/edge-client/src/edge-ws-connection.ts";
|
|
114
118
|
var SIGNAL_KEEPALIVE_INTERVAL = 4e3;
|
|
115
119
|
var SIGNAL_KEEPALIVE_TIMEOUT = 12e3;
|
|
116
|
-
var CLOUDFLARE_MESSAGE_LENGTH_LIMIT = 1024 * 1024;
|
|
117
120
|
var EdgeWsConnection = class extends import_context2.Resource {
|
|
118
121
|
constructor(_identity, _connectionInfo, _callbacks) {
|
|
119
122
|
super();
|
|
@@ -131,47 +134,73 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
131
134
|
send(message) {
|
|
132
135
|
(0, import_invariant2.invariant)(this._ws, void 0, {
|
|
133
136
|
F: __dxlog_file2,
|
|
134
|
-
L:
|
|
137
|
+
L: 52,
|
|
135
138
|
S: this,
|
|
136
139
|
A: [
|
|
137
140
|
"this._ws",
|
|
138
141
|
""
|
|
139
142
|
]
|
|
140
143
|
});
|
|
144
|
+
(0, import_invariant2.invariant)(this._wsMuxer, void 0, {
|
|
145
|
+
F: __dxlog_file2,
|
|
146
|
+
L: 53,
|
|
147
|
+
S: this,
|
|
148
|
+
A: [
|
|
149
|
+
"this._wsMuxer",
|
|
150
|
+
""
|
|
151
|
+
]
|
|
152
|
+
});
|
|
141
153
|
(0, import_log2.log)("sending...", {
|
|
142
154
|
peerKey: this._identity.peerKey,
|
|
143
|
-
payload:
|
|
155
|
+
payload: import_chunk_ZOL3YSDR.protocol.getPayloadType(message)
|
|
144
156
|
}, {
|
|
145
157
|
F: __dxlog_file2,
|
|
146
|
-
L:
|
|
158
|
+
L: 54,
|
|
147
159
|
S: this,
|
|
148
160
|
C: (f, a) => f(...a)
|
|
149
161
|
});
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
162
|
+
if (this._ws?.protocol.includes(import_protocols.EdgeWebsocketProtocol.V0)) {
|
|
163
|
+
const binary = import_buf.buf.toBinary(import_messenger_pb.MessageSchema, message);
|
|
164
|
+
if (binary.length > import_chunk_ZOL3YSDR.CLOUDFLARE_MESSAGE_MAX_BYTES) {
|
|
165
|
+
import_log2.log.error("Message dropped because it was too large (>1MB).", {
|
|
166
|
+
byteLength: binary.byteLength,
|
|
167
|
+
serviceId: message.serviceId,
|
|
168
|
+
payload: import_chunk_ZOL3YSDR.protocol.getPayloadType(message)
|
|
169
|
+
}, {
|
|
170
|
+
F: __dxlog_file2,
|
|
171
|
+
L: 58,
|
|
172
|
+
S: this,
|
|
173
|
+
C: (f, a) => f(...a)
|
|
174
|
+
});
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
this._ws.send(binary);
|
|
178
|
+
} else {
|
|
179
|
+
this._wsMuxer.send(message).catch((e) => import_log2.log.catch(e, void 0, {
|
|
157
180
|
F: __dxlog_file2,
|
|
158
|
-
L:
|
|
181
|
+
L: 67,
|
|
159
182
|
S: this,
|
|
160
183
|
C: (f, a) => f(...a)
|
|
161
|
-
});
|
|
162
|
-
return;
|
|
184
|
+
}));
|
|
163
185
|
}
|
|
164
|
-
this._ws.send(encoded);
|
|
165
186
|
}
|
|
166
187
|
async _open() {
|
|
188
|
+
const baseProtocols = [
|
|
189
|
+
...Object.values(import_protocols.EdgeWebsocketProtocol)
|
|
190
|
+
];
|
|
167
191
|
this._ws = new import_isomorphic_ws.default(this._connectionInfo.url.toString(), this._connectionInfo.protocolHeader ? [
|
|
192
|
+
...baseProtocols,
|
|
168
193
|
this._connectionInfo.protocolHeader
|
|
169
|
-
] : [
|
|
194
|
+
] : [
|
|
195
|
+
...baseProtocols
|
|
196
|
+
]);
|
|
197
|
+
const muxer = new import_chunk_ZOL3YSDR.WebSocketMuxer(this._ws);
|
|
198
|
+
this._wsMuxer = muxer;
|
|
170
199
|
this._ws.onopen = () => {
|
|
171
200
|
if (this.isOpen) {
|
|
172
201
|
(0, import_log2.log)("connected", void 0, {
|
|
173
202
|
F: __dxlog_file2,
|
|
174
|
-
L:
|
|
203
|
+
L: 84,
|
|
175
204
|
S: this,
|
|
176
205
|
C: (f, a) => f(...a)
|
|
177
206
|
});
|
|
@@ -182,7 +211,7 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
182
211
|
currentIdentity: this._identity
|
|
183
212
|
}, {
|
|
184
213
|
F: __dxlog_file2,
|
|
185
|
-
L:
|
|
214
|
+
L: 88,
|
|
186
215
|
S: this,
|
|
187
216
|
C: (f, a) => f(...a)
|
|
188
217
|
});
|
|
@@ -195,11 +224,12 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
195
224
|
reason: event.reason
|
|
196
225
|
}, {
|
|
197
226
|
F: __dxlog_file2,
|
|
198
|
-
L:
|
|
227
|
+
L: 93,
|
|
199
228
|
S: this,
|
|
200
229
|
C: (f, a) => f(...a)
|
|
201
230
|
});
|
|
202
231
|
this._callbacks.onRestartRequired();
|
|
232
|
+
muxer.destroy();
|
|
203
233
|
}
|
|
204
234
|
};
|
|
205
235
|
this._ws.onerror = (event) => {
|
|
@@ -209,7 +239,7 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
209
239
|
info: event.message
|
|
210
240
|
}, {
|
|
211
241
|
F: __dxlog_file2,
|
|
212
|
-
L:
|
|
242
|
+
L: 100,
|
|
213
243
|
S: this,
|
|
214
244
|
C: (f, a) => f(...a)
|
|
215
245
|
});
|
|
@@ -219,7 +249,7 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
219
249
|
error: event.error
|
|
220
250
|
}, {
|
|
221
251
|
F: __dxlog_file2,
|
|
222
|
-
L:
|
|
252
|
+
L: 103,
|
|
223
253
|
S: this,
|
|
224
254
|
C: (f, a) => f(...a)
|
|
225
255
|
});
|
|
@@ -231,7 +261,7 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
231
261
|
event: event.type
|
|
232
262
|
}, {
|
|
233
263
|
F: __dxlog_file2,
|
|
234
|
-
L:
|
|
264
|
+
L: 111,
|
|
235
265
|
S: this,
|
|
236
266
|
C: (f, a) => f(...a)
|
|
237
267
|
});
|
|
@@ -241,15 +271,18 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
241
271
|
this._rescheduleHeartbeatTimeout();
|
|
242
272
|
return;
|
|
243
273
|
}
|
|
244
|
-
const
|
|
245
|
-
if (this.isOpen) {
|
|
246
|
-
|
|
274
|
+
const bytes = await (0, import_chunk_ZOL3YSDR.toUint8Array)(event.data);
|
|
275
|
+
if (!this.isOpen) {
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const message = this._ws?.protocol?.includes(import_protocols.EdgeWebsocketProtocol.V0) ? import_buf.buf.fromBinary(import_messenger_pb.MessageSchema, bytes) : muxer.receiveData(bytes);
|
|
279
|
+
if (message) {
|
|
247
280
|
(0, import_log2.log)("received", {
|
|
248
281
|
from: message.source,
|
|
249
|
-
payload:
|
|
282
|
+
payload: import_chunk_ZOL3YSDR.protocol.getPayloadType(message)
|
|
250
283
|
}, {
|
|
251
284
|
F: __dxlog_file2,
|
|
252
|
-
L:
|
|
285
|
+
L: 128,
|
|
253
286
|
S: this,
|
|
254
287
|
C: (f, a) => f(...a)
|
|
255
288
|
});
|
|
@@ -263,6 +296,8 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
263
296
|
try {
|
|
264
297
|
this._ws?.close();
|
|
265
298
|
this._ws = void 0;
|
|
299
|
+
this._wsMuxer?.destroy();
|
|
300
|
+
this._wsMuxer = void 0;
|
|
266
301
|
} catch (err) {
|
|
267
302
|
if (err instanceof Error && err.message.includes("WebSocket is closed before the connection is established.")) {
|
|
268
303
|
return;
|
|
@@ -271,7 +306,7 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
271
306
|
err
|
|
272
307
|
}, {
|
|
273
308
|
F: __dxlog_file2,
|
|
274
|
-
L:
|
|
309
|
+
L: 146,
|
|
275
310
|
S: this,
|
|
276
311
|
C: (f, a) => f(...a)
|
|
277
312
|
});
|
|
@@ -280,7 +315,7 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
280
315
|
_scheduleHeartbeats() {
|
|
281
316
|
(0, import_invariant2.invariant)(this._ws, void 0, {
|
|
282
317
|
F: __dxlog_file2,
|
|
283
|
-
L:
|
|
318
|
+
L: 151,
|
|
284
319
|
S: this,
|
|
285
320
|
A: [
|
|
286
321
|
"this._ws",
|
|
@@ -300,13 +335,13 @@ var EdgeWsConnection = class extends import_context2.Resource {
|
|
|
300
335
|
void this._inactivityTimeoutCtx?.dispose();
|
|
301
336
|
this._inactivityTimeoutCtx = new import_context2.Context(void 0, {
|
|
302
337
|
F: __dxlog_file2,
|
|
303
|
-
L:
|
|
338
|
+
L: 170
|
|
304
339
|
});
|
|
305
340
|
(0, import_async2.scheduleTask)(this._inactivityTimeoutCtx, () => {
|
|
306
341
|
if (this.isOpen) {
|
|
307
342
|
import_log2.log.warn("restart due to inactivity timeout", void 0, {
|
|
308
343
|
F: __dxlog_file2,
|
|
309
|
-
L:
|
|
344
|
+
L: 175,
|
|
310
345
|
S: this,
|
|
311
346
|
C: (f, a) => f(...a)
|
|
312
347
|
});
|
|
@@ -390,7 +425,7 @@ var EdgeClient = class extends import_context.Resource {
|
|
|
390
425
|
});
|
|
391
426
|
this._identity = identity;
|
|
392
427
|
this._closeCurrentConnection(new EdgeIdentityChangedError());
|
|
393
|
-
this._persistentLifecycle.scheduleRestart();
|
|
428
|
+
void this._persistentLifecycle.scheduleRestart();
|
|
394
429
|
}
|
|
395
430
|
}
|
|
396
431
|
onMessage(listener) {
|
|
@@ -502,7 +537,7 @@ var EdgeClient = class extends import_context.Resource {
|
|
|
502
537
|
onRestartRequired: () => {
|
|
503
538
|
if (this._isActive(connection)) {
|
|
504
539
|
this._closeCurrentConnection();
|
|
505
|
-
this._persistentLifecycle.scheduleRestart();
|
|
540
|
+
void this._persistentLifecycle.scheduleRestart();
|
|
506
541
|
} else {
|
|
507
542
|
import_log.log.verbose("restart requested by inactive connection", void 0, {
|
|
508
543
|
F: __dxlog_file3,
|
|
@@ -573,7 +608,7 @@ var EdgeClient = class extends import_context.Resource {
|
|
|
573
608
|
} catch (err) {
|
|
574
609
|
import_log.log.error("ws incoming message processing failed", {
|
|
575
610
|
err,
|
|
576
|
-
payload:
|
|
611
|
+
payload: import_chunk_ZOL3YSDR.protocol.getPayloadType(message)
|
|
577
612
|
}, {
|
|
578
613
|
F: __dxlog_file3,
|
|
579
614
|
L: 235,
|
|
@@ -930,19 +965,19 @@ var EdgeHttpClient = class {
|
|
|
930
965
|
C: (f, a) => f(...a)
|
|
931
966
|
});
|
|
932
967
|
if (body.errorData?.type === "auth_challenge" && typeof body.errorData?.challenge === "string") {
|
|
933
|
-
processingError = new
|
|
968
|
+
processingError = new import_protocols2.EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
|
|
934
969
|
} else {
|
|
935
|
-
processingError =
|
|
970
|
+
processingError = import_protocols2.EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
|
|
936
971
|
}
|
|
937
972
|
} else if (response.status === 401 && !handledAuth) {
|
|
938
973
|
authHeader = await this._handleUnauthorized(response);
|
|
939
974
|
handledAuth = true;
|
|
940
975
|
continue;
|
|
941
976
|
} else {
|
|
942
|
-
processingError =
|
|
977
|
+
processingError = import_protocols2.EdgeCallFailedError.fromHttpFailure(response);
|
|
943
978
|
}
|
|
944
979
|
} catch (error) {
|
|
945
|
-
processingError =
|
|
980
|
+
processingError = import_protocols2.EdgeCallFailedError.fromProcessingFailureCause(error);
|
|
946
981
|
}
|
|
947
982
|
if (processingError.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
|
|
948
983
|
(0, import_log3.log)("retrying edge request", {
|
|
@@ -967,7 +1002,7 @@ var EdgeHttpClient = class {
|
|
|
967
1002
|
S: this,
|
|
968
1003
|
C: (f, a) => f(...a)
|
|
969
1004
|
});
|
|
970
|
-
throw
|
|
1005
|
+
throw import_protocols2.EdgeCallFailedError.fromHttpFailure(response);
|
|
971
1006
|
}
|
|
972
1007
|
const challenge = await handleAuthChallenge(response, this._edgeIdentity);
|
|
973
1008
|
this._authHeader = encodeAuthHeader(challenge);
|
|
@@ -1016,11 +1051,14 @@ var encodeAuthHeader = (challenge) => {
|
|
|
1016
1051
|
};
|
|
1017
1052
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1018
1053
|
0 && (module.exports = {
|
|
1054
|
+
CLOUDFLARE_MESSAGE_MAX_BYTES,
|
|
1055
|
+
CLOUDFLARE_RPC_MAX_BYTES,
|
|
1019
1056
|
EdgeClient,
|
|
1020
1057
|
EdgeConnectionClosedError,
|
|
1021
1058
|
EdgeHttpClient,
|
|
1022
1059
|
EdgeIdentityChangedError,
|
|
1023
1060
|
Protocol,
|
|
1061
|
+
WebSocketMuxer,
|
|
1024
1062
|
createChainEdgeIdentity,
|
|
1025
1063
|
createDeviceEdgeIdentity,
|
|
1026
1064
|
createEphemeralEdgeIdentity,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/index.ts", "../../../src/edge-client.ts", "../../../src/edge-identity.ts", "../../../src/edge-ws-connection.ts", "../../../src/errors.ts", "../../../src/utils.ts", "../../../src/auth.ts", "../../../src/edge-http-client.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nexport * from '@dxos/protocols/buf/dxos/edge/messenger_pb';\n\nexport * from './edge-client';\nexport * from './defs';\nexport * from './protocol';\nexport * from './errors';\nexport * from './auth';\nexport * from './edge-http-client';\nexport * from './edge-identity';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Trigger, scheduleMicroTask, TriggerState, PersistentLifecycle, Event } from '@dxos/async';\nimport { Resource, type Lifecycle } from '@dxos/context';\nimport { log, logInfo } from '@dxos/log';\nimport { type Message } from '@dxos/protocols/buf/dxos/edge/messenger_pb';\nimport { EdgeStatus } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { protocol } from './defs';\nimport { type EdgeIdentity, handleAuthChallenge } from './edge-identity';\nimport { EdgeWsConnection } from './edge-ws-connection';\nimport { EdgeConnectionClosedError, EdgeIdentityChangedError } from './errors';\nimport { type Protocol } from './protocol';\nimport { getEdgeUrlWithProtocol } from './utils';\n\nconst DEFAULT_TIMEOUT = 10_000;\n\nexport type MessageListener = (message: Message) => void;\nexport type ReconnectListener = () => void;\n\nexport interface EdgeConnection extends Required<Lifecycle> {\n statusChanged: Event<EdgeStatus>;\n get info(): any;\n get identityKey(): string;\n get peerKey(): string;\n get isOpen(): boolean;\n get status(): EdgeStatus;\n setIdentity(identity: EdgeIdentity): void;\n onMessage(listener: MessageListener): () => void;\n onReconnected(listener: ReconnectListener): () => void;\n send(message: Message): Promise<void>;\n}\n\nexport type MessengerConfig = {\n socketEndpoint: string;\n timeout?: number;\n protocol?: Protocol;\n disableAuth?: boolean;\n};\n\n/**\n * Messenger client for EDGE:\n * - While open, uses PersistentLifecycle to keep an open EdgeWsConnection, reconnecting on failures.\n * - Manages identity and re-create EdgeWsConnection when identity changes.\n * - Dispatches connection state and message notifications.\n */\nexport class EdgeClient extends Resource implements EdgeConnection {\n public readonly statusChanged = new Event<EdgeStatus>();\n\n private readonly _persistentLifecycle = new PersistentLifecycle<EdgeWsConnection>({\n start: async () => this._connect(),\n stop: async (state: EdgeWsConnection) => this._disconnect(state),\n });\n\n private readonly _messageListeners = new Set<MessageListener>();\n private readonly _reconnectListeners = new Set<ReconnectListener>();\n private readonly _baseWsUrl: string;\n private readonly _baseHttpUrl: string;\n private _currentConnection?: EdgeWsConnection = undefined;\n private _ready = new Trigger();\n\n constructor(\n private _identity: EdgeIdentity,\n private readonly _config: MessengerConfig,\n ) {\n super();\n this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, 'ws');\n this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, 'http');\n }\n\n @logInfo\n public get info() {\n return {\n open: this.isOpen,\n status: this.status,\n identity: this._identity.identityKey,\n device: this._identity.peerKey,\n };\n }\n\n get status(): EdgeStatus {\n return Boolean(this._currentConnection) && this._ready.state === TriggerState.RESOLVED\n ? EdgeStatus.CONNECTED\n : EdgeStatus.NOT_CONNECTED;\n }\n\n get identityKey() {\n return this._identity.identityKey;\n }\n\n get peerKey() {\n return this._identity.peerKey;\n }\n\n setIdentity(identity: EdgeIdentity) {\n if (identity.identityKey !== this._identity.identityKey || identity.peerKey !== this._identity.peerKey) {\n log('Edge identity changed', { identity, oldIdentity: this._identity });\n this._identity = identity;\n this._closeCurrentConnection(new EdgeIdentityChangedError());\n this._persistentLifecycle.scheduleRestart();\n }\n }\n\n public onMessage(listener: MessageListener): () => void {\n this._messageListeners.add(listener);\n return () => this._messageListeners.delete(listener);\n }\n\n public onReconnected(listener: () => void): () => void {\n this._reconnectListeners.add(listener);\n if (this._ready.state === TriggerState.RESOLVED) {\n // Microtask so that listener is always called asynchronously, no matter the state of the ready trigger\n // at the moment of registration.\n scheduleMicroTask(this._ctx, () => {\n if (this._reconnectListeners.has(listener)) {\n try {\n listener();\n } catch (error) {\n log.catch(error);\n }\n }\n });\n }\n return () => this._reconnectListeners.delete(listener);\n }\n\n /**\n * Open connection to messaging service.\n */\n protected override async _open() {\n log('opening...', { info: this.info });\n this._persistentLifecycle.open().catch((err) => {\n log.warn('Error while opening connection', { err });\n });\n }\n\n /**\n * Close connection and free resources.\n */\n protected override async _close() {\n log('closing...', { peerKey: this._identity.peerKey });\n this._closeCurrentConnection();\n await this._persistentLifecycle.close();\n }\n\n private async _connect(): Promise<EdgeWsConnection | undefined> {\n if (this._ctx.disposed) {\n return undefined;\n }\n\n const identity = this._identity;\n const path = `/ws/${identity.identityKey}/${identity.peerKey}`;\n const protocolHeader = this._config.disableAuth ? undefined : await this._createAuthHeader(path);\n if (this._identity !== identity) {\n log('identity changed during auth header request');\n return undefined;\n }\n\n const restartRequired = new Trigger();\n const url = new URL(path, this._baseWsUrl);\n log('Opening websocket', { url: url.toString(), protocolHeader });\n const connection = new EdgeWsConnection(\n identity,\n { url, protocolHeader },\n {\n onConnected: () => {\n if (this._isActive(connection)) {\n this._ready.wake();\n this._notifyReconnected();\n } else {\n log.verbose('connected callback ignored, because connection is not active');\n }\n },\n onRestartRequired: () => {\n if (this._isActive(connection)) {\n this._closeCurrentConnection();\n this._persistentLifecycle.scheduleRestart();\n } else {\n log.verbose('restart requested by inactive connection');\n }\n restartRequired.wake();\n },\n onMessage: (message) => {\n if (this._isActive(connection)) {\n this._notifyMessageReceived(message);\n } else {\n log.verbose('ignored a message on inactive connection', {\n from: message.source,\n type: message.payload?.typeUrl,\n });\n }\n },\n },\n );\n this._currentConnection = connection;\n\n await connection.open();\n // Race with restartRequired so that restart is not blocked by _connect execution.\n // Wait on ready to attempt a reconnect if it times out.\n await Promise.race([this._ready.wait({ timeout: this._config.timeout ?? DEFAULT_TIMEOUT }), restartRequired]);\n\n return connection;\n }\n\n private async _disconnect(state: EdgeWsConnection) {\n await state.close();\n this.statusChanged.emit(this.status);\n }\n\n private _closeCurrentConnection(error: Error = new EdgeConnectionClosedError()) {\n this._currentConnection = undefined;\n this._ready.throw(error);\n this._ready.reset();\n this.statusChanged.emit(this.status);\n }\n\n private _notifyReconnected() {\n this.statusChanged.emit(this.status);\n for (const listener of this._reconnectListeners) {\n try {\n listener();\n } catch (err) {\n log.error('ws reconnect listener failed', { err });\n }\n }\n }\n\n private _notifyMessageReceived(message: Message) {\n for (const listener of this._messageListeners) {\n try {\n listener(message);\n } catch (err) {\n log.error('ws incoming message processing failed', { err, payload: protocol.getPayloadType(message) });\n }\n }\n }\n\n /**\n * Send message.\n * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.\n */\n public async send(message: Message): Promise<void> {\n if (this._ready.state !== TriggerState.RESOLVED) {\n log('waiting for websocket to become ready');\n await this._ready.wait({ timeout: this._config.timeout ?? DEFAULT_TIMEOUT });\n }\n\n if (!this._currentConnection) {\n throw new EdgeConnectionClosedError();\n }\n\n if (\n message.source &&\n (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)\n ) {\n throw new EdgeIdentityChangedError();\n }\n\n this._currentConnection.send(message);\n }\n\n private async _createAuthHeader(path: string): Promise<string | undefined> {\n const httpUrl = new URL(path, this._baseHttpUrl);\n httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), 'http');\n const response = await fetch(httpUrl, { method: 'GET' });\n if (response.status === 401) {\n return encodePresentationWsAuthHeader(await handleAuthChallenge(response, this._identity));\n } else {\n log.warn('no auth challenge from edge', { status: response.status, statusText: response.statusText });\n return undefined;\n }\n }\n\n private _isActive = (connection: EdgeWsConnection) => connection === this._currentConnection;\n}\n\nconst encodePresentationWsAuthHeader = (encodedPresentation: Uint8Array): string => {\n // = and / characters are not allowed in the WebSocket subprotocol header.\n const encodedToken = Buffer.from(encodedPresentation).toString('base64').replace(/=*$/, '').replaceAll('/', '|');\n return `base64url.bearer.authorization.dxos.org.${encodedToken}`;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Presentation } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nexport interface EdgeIdentity {\n peerKey: string;\n identityKey: string;\n /**\n * Returns credential presentation issued by the identity key.\n * Presentation must have the provided challenge.\n * Presentation may include ServiceAccess credentials.\n */\n presentCredentials({ challenge }: { challenge: Uint8Array }): Promise<Presentation>;\n}\n\nexport const handleAuthChallenge = async (failedResponse: Response, identity: EdgeIdentity): Promise<Uint8Array> => {\n invariant(failedResponse.status === 401);\n\n const headerValue = failedResponse.headers.get('Www-Authenticate');\n invariant(headerValue?.startsWith('VerifiablePresentation challenge='));\n\n const challenge = headerValue?.slice('VerifiablePresentation challenge='.length);\n invariant(challenge);\n\n const presentation = await identity.presentCredentials({ challenge: Buffer.from(challenge, 'base64') });\n return schema.getCodecForType('dxos.halo.credentials.Presentation').encode(presentation);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'isomorphic-ws';\n\nimport { scheduleTask, scheduleTaskInterval } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log, logInfo } from '@dxos/log';\nimport { buf } from '@dxos/protocols/buf';\nimport { MessageSchema, type Message } from '@dxos/protocols/buf/dxos/edge/messenger_pb';\n\nimport { protocol } from './defs';\nimport { type EdgeIdentity } from './edge-identity';\nimport { toUint8Array } from './protocol';\n\nconst SIGNAL_KEEPALIVE_INTERVAL = 4_000;\nconst SIGNAL_KEEPALIVE_TIMEOUT = 12_000;\n\n/**\n * 1MB websocket message limit: https://developers.cloudflare.com/durable-objects/platform/limits/\n */\nconst CLOUDFLARE_MESSAGE_LENGTH_LIMIT = 1024 * 1024;\n\nexport type EdgeWsConnectionCallbacks = {\n onConnected: () => void;\n onMessage: (message: Message) => void;\n onRestartRequired: () => void;\n};\n\nexport class EdgeWsConnection extends Resource {\n private _inactivityTimeoutCtx: Context | undefined;\n private _ws: WebSocket | undefined;\n\n constructor(\n private readonly _identity: EdgeIdentity,\n private readonly _connectionInfo: { url: URL; protocolHeader?: string },\n private readonly _callbacks: EdgeWsConnectionCallbacks,\n ) {\n super();\n }\n\n @logInfo\n public get info() {\n return {\n open: this.isOpen,\n identity: this._identity.identityKey,\n device: this._identity.peerKey,\n };\n }\n\n public send(message: Message) {\n invariant(this._ws);\n log('sending...', { peerKey: this._identity.peerKey, payload: protocol.getPayloadType(message) });\n const encoded = buf.toBinary(MessageSchema, message);\n if (encoded.byteLength >= CLOUDFLARE_MESSAGE_LENGTH_LIMIT) {\n log.error('edge message dropped due to websocket message limit', {\n byteLength: encoded.byteLength,\n serviceId: message.serviceId,\n payload: protocol.getPayloadType(message),\n });\n return;\n }\n this._ws.send(encoded);\n }\n\n protected override async _open() {\n this._ws = new WebSocket(\n this._connectionInfo.url.toString(),\n this._connectionInfo.protocolHeader ? [this._connectionInfo.protocolHeader] : [],\n );\n\n this._ws.onopen = () => {\n if (this.isOpen) {\n log('connected');\n this._callbacks.onConnected();\n this._scheduleHeartbeats();\n } else {\n log.verbose('connected after becoming inactive', { currentIdentity: this._identity });\n }\n };\n this._ws.onclose = (event) => {\n if (this.isOpen) {\n log.warn('disconnected while being open', { code: event.code, reason: event.reason });\n this._callbacks.onRestartRequired();\n }\n };\n this._ws.onerror = (event) => {\n if (this.isOpen) {\n log.warn('edge connection socket error', { error: event.error, info: event.message });\n this._callbacks.onRestartRequired();\n } else {\n log.verbose('error ignored on closed connection', { error: event.error });\n }\n };\n /**\n * https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data\n */\n this._ws.onmessage = async (event) => {\n if (!this.isOpen) {\n log.verbose('message ignored on closed connection', { event: event.type });\n return;\n }\n if (event.data === '__pong__') {\n this._rescheduleHeartbeatTimeout();\n return;\n }\n const data = await toUint8Array(event.data);\n if (this.isOpen) {\n const message = buf.fromBinary(MessageSchema, data);\n log('received', { from: message.source, payload: protocol.getPayloadType(message) });\n this._callbacks.onMessage(message);\n }\n };\n }\n\n protected override async _close() {\n void this._inactivityTimeoutCtx?.dispose().catch(() => {});\n\n try {\n this._ws?.close();\n this._ws = undefined;\n } catch (err) {\n if (err instanceof Error && err.message.includes('WebSocket is closed before the connection is established.')) {\n return;\n }\n log.warn('Error closing websocket', { err });\n }\n }\n\n private _scheduleHeartbeats() {\n invariant(this._ws);\n scheduleTaskInterval(\n this._ctx,\n async () => {\n // TODO(mykola): use RFC6455 ping/pong once implemented in the browser?\n // Cloudflare's worker responds to this `without interrupting hibernation`. https://developers.cloudflare.com/durable-objects/api/websockets/#setwebsocketautoresponse\n this._ws?.send('__ping__');\n },\n SIGNAL_KEEPALIVE_INTERVAL,\n );\n this._ws.send('__ping__');\n this._rescheduleHeartbeatTimeout();\n }\n\n private _rescheduleHeartbeatTimeout() {\n if (!this.isOpen) {\n return;\n }\n void this._inactivityTimeoutCtx?.dispose();\n this._inactivityTimeoutCtx = new Context();\n scheduleTask(\n this._inactivityTimeoutCtx,\n () => {\n if (this.isOpen) {\n log.warn('restart due to inactivity timeout');\n this._callbacks.onRestartRequired();\n }\n },\n SIGNAL_KEEPALIVE_TIMEOUT,\n );\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport class EdgeConnectionClosedError extends Error {\n constructor() {\n super('Edge connection closed.');\n }\n}\n\nexport class EdgeIdentityChangedError extends Error {\n constructor() {\n super('Edge identity changed.');\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const getEdgeUrlWithProtocol = (baseUrl: string, protocol: 'http' | 'ws') => {\n const isSecure = baseUrl.startsWith('https') || baseUrl.startsWith('wss');\n const url = new URL(baseUrl);\n url.protocol = protocol + (isSecure ? 's' : '');\n return url.toString();\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { createCredential, signPresentation } from '@dxos/credentials';\nimport { type Signer } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { type Chain, type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport type { EdgeIdentity } from './edge-identity';\n\n/**\n * Edge identity backed by a device key without a credential chain.\n */\nexport const createDeviceEdgeIdentity = async (signer: Signer, key: PublicKey): Promise<EdgeIdentity> => {\n return {\n identityKey: key.toHex(),\n peerKey: key.toHex(),\n presentCredentials: async ({ challenge }) => {\n return signPresentation({\n presentation: {\n credentials: [\n // Verifier requires at least one credential in the presentation to establish the subject.\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: key,\n subject: key,\n signer,\n }),\n ],\n },\n signer,\n signerKey: key,\n nonce: challenge,\n });\n },\n };\n};\n\n/**\n * Edge identity backed by a chain of credentials.\n */\nexport const createChainEdgeIdentity = async (\n signer: Signer,\n identityKey: PublicKey,\n peerKey: PublicKey,\n chain: Chain | undefined,\n credentials: Credential[],\n): Promise<EdgeIdentity> => {\n const credentialsToSign =\n credentials.length > 0\n ? credentials\n : [\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: identityKey,\n subject: identityKey,\n signer,\n chain,\n signingKey: peerKey,\n }),\n ];\n\n return {\n identityKey: identityKey.toHex(),\n peerKey: peerKey.toHex(),\n presentCredentials: async ({ challenge }) => {\n // TODO: make chain required after device invitation flow update release\n invariant(chain);\n return signPresentation({\n presentation: {\n credentials: credentialsToSign,\n },\n signer,\n nonce: challenge,\n signerKey: peerKey,\n chain,\n });\n },\n };\n};\n\n/**\n * Edge identity backed by a random ephemeral key without HALO.\n */\nexport const createEphemeralEdgeIdentity = async (): Promise<EdgeIdentity> => {\n const keyring = new Keyring();\n const key = await keyring.createKey();\n return createDeviceEdgeIdentity(keyring, key);\n};\n\n/**\n * Creates a HALO chain of credentials to act as an edge identity.\n */\nexport const createTestHaloEdgeIdentity = async (\n signer: Signer,\n identityKey: PublicKey,\n deviceKey: PublicKey,\n): Promise<EdgeIdentity> => {\n const deviceAdmission = await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.AuthorizedDevice',\n deviceKey,\n identityKey,\n },\n issuer: identityKey,\n subject: deviceKey,\n signer,\n });\n return createChainEdgeIdentity(signer, identityKey, deviceKey, { credential: deviceAdmission }, [\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: identityKey,\n subject: identityKey,\n signer,\n }),\n ]);\n};\n\nexport const createStubEdgeIdentity = (): EdgeIdentity => {\n const identityKey = PublicKey.random();\n const deviceKey = PublicKey.random();\n return {\n identityKey: identityKey.toHex(),\n peerKey: deviceKey.toHex(),\n presentCredentials: async () => {\n throw new Error('Stub identity does not support authentication.');\n },\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { sleep } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { type PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n EdgeCallFailedError,\n type EdgeHttpResponse,\n type GetNotarizationResponseBody,\n type PostNotarizationRequestBody,\n type JoinSpaceRequest,\n type JoinSpaceResponseBody,\n EdgeAuthChallengeError,\n type CreateAgentResponseBody,\n type CreateAgentRequestBody,\n type GetAgentStatusResponseBody,\n type RecoverIdentityRequest,\n type RecoverIdentityResponseBody,\n type UploadFunctionRequest,\n type UploadFunctionResponseBody,\n type ObjectId,\n type ExecuteWorkflowResponseBody,\n type QueueQuery,\n type QueryResult,\n type InitiateOAuthFlowRequest,\n type InitiateOAuthFlowResponse,\n type CreateSpaceRequest,\n type CreateSpaceResponseBody,\n} from '@dxos/protocols';\n\nimport { type EdgeIdentity, handleAuthChallenge } from './edge-identity';\nimport { getEdgeUrlWithProtocol } from './utils';\n\nconst DEFAULT_RETRY_TIMEOUT = 1500;\nconst DEFAULT_RETRY_JITTER = 500;\nconst DEFAULT_MAX_RETRIES_COUNT = 3;\n\nexport class EdgeHttpClient {\n private readonly _baseUrl: string;\n\n private _edgeIdentity: EdgeIdentity | undefined;\n\n /**\n * Auth header is cached until receiving the next 401 from EDGE, at which point it gets refreshed.\n */\n private _authHeader: string | undefined;\n\n constructor(baseUrl: string) {\n this._baseUrl = getEdgeUrlWithProtocol(baseUrl, 'http');\n log('created', { url: this._baseUrl });\n }\n\n get baseUrl() {\n return this._baseUrl;\n }\n\n setIdentity(identity: EdgeIdentity) {\n if (this._edgeIdentity?.identityKey !== identity.identityKey || this._edgeIdentity?.peerKey !== identity.peerKey) {\n this._edgeIdentity = identity;\n this._authHeader = undefined;\n }\n }\n\n public createAgent(body: CreateAgentRequestBody, args?: EdgeHttpGetArgs): Promise<CreateAgentResponseBody> {\n return this._call('/agents/create', { ...args, method: 'POST', body });\n }\n\n public getAgentStatus(\n request: { ownerIdentityKey: PublicKey },\n args?: EdgeHttpGetArgs,\n ): Promise<GetAgentStatusResponseBody> {\n return this._call(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, { ...args, method: 'GET' });\n }\n\n public getCredentialsForNotarization(spaceId: SpaceId, args?: EdgeHttpGetArgs): Promise<GetNotarizationResponseBody> {\n return this._call(`/spaces/${spaceId}/notarization`, { ...args, method: 'GET' });\n }\n\n public async notarizeCredentials(\n spaceId: SpaceId,\n body: PostNotarizationRequestBody,\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n await this._call(`/spaces/${spaceId}/notarization`, { ...args, body, method: 'POST' });\n }\n\n public async joinSpaceByInvitation(\n spaceId: SpaceId,\n body: JoinSpaceRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<JoinSpaceResponseBody> {\n return this._call(`/spaces/${spaceId}/join`, { ...args, body, method: 'POST' });\n }\n\n public async recoverIdentity(\n body: RecoverIdentityRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<RecoverIdentityResponseBody> {\n return this._call('/identity/recover', { ...args, body, method: 'POST' });\n }\n\n public async executeWorkflow(\n spaceId: SpaceId,\n graphId: ObjectId,\n input: any,\n args?: EdgeHttpGetArgs,\n ): Promise<ExecuteWorkflowResponseBody> {\n return this._call(`/workflows/${spaceId}/${graphId}`, { ...args, body: input, method: 'POST' });\n }\n\n public async uploadFunction(\n pathParts: { spaceId: SpaceId; functionId?: string },\n body: UploadFunctionRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<UploadFunctionResponseBody> {\n const path = ['functions', pathParts.spaceId, ...(pathParts.functionId ? [pathParts.functionId] : [])].join('/');\n return this._call(path, { ...args, body, method: 'PUT' });\n }\n\n public async initiateOAuthFlow(\n body: InitiateOAuthFlowRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<InitiateOAuthFlowResponse> {\n return this._call('/oauth/initiate', { ...args, body, method: 'POST' });\n }\n\n public async queryQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n query: QueueQuery,\n args?: EdgeHttpGetArgs,\n ): Promise<QueryResult> {\n const { queueId } = query;\n const queryParams = new URLSearchParams();\n if (query.after != null) {\n queryParams.set('after', query.after);\n }\n if (query.before != null) {\n queryParams.set('before', query.before);\n }\n if (query.limit != null) {\n queryParams.set('limit', query.limit.toString());\n }\n if (query.reverse != null) {\n queryParams.set('reverse', query.reverse.toString());\n }\n if (query.objectIds != null) {\n queryParams.set('objectIds', query.objectIds.join(','));\n }\n return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query?${queryParams.toString()}`, {\n ...args,\n method: 'GET',\n });\n }\n\n public async insertIntoQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n queueId: ObjectId,\n objects: unknown[],\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {\n ...args,\n body: { objects },\n method: 'POST',\n });\n }\n\n async deleteFromQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n queueId: ObjectId,\n objectIds: ObjectId[],\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {\n ...args,\n query: { ids: objectIds.join(',') },\n method: 'DELETE',\n });\n }\n\n async createSpace(body: CreateSpaceRequest, args?: EdgeHttpGetArgs): Promise<CreateSpaceResponseBody> {\n return this._call('/spaces/create', { ...args, body, method: 'POST' });\n }\n\n private async _call<T>(path: string, args: EdgeHttpCallArgs): Promise<T> {\n const requestContext = args.context ?? new Context();\n const shouldRetry = createRetryHandler(args);\n let url = `${this._baseUrl}${path.startsWith('/') ? path.slice(1) : path}`;\n\n if (args.query) {\n const queryParams = new URLSearchParams();\n for (const [key, value] of Object.entries(args.query)) {\n queryParams.set(key, value.toString());\n }\n url += `?${queryParams.toString()}`;\n }\n\n log('call', { method: args.method, path, request: args.body });\n\n let handledAuth = false;\n let authHeader = this._authHeader;\n while (true) {\n let processingError: EdgeCallFailedError;\n let retryAfterHeaderValue: number = Number.NaN;\n try {\n const request = createRequest(args, authHeader);\n const response = await fetch(url, request);\n\n retryAfterHeaderValue = Number(response.headers.get('Retry-After'));\n\n if (response.ok) {\n const body = (await response.json()) as EdgeHttpResponse<T>;\n if (body.success) {\n return body.data;\n }\n\n log('unsuccessful edge response', { path, body });\n\n if (body.errorData?.type === 'auth_challenge' && typeof body.errorData?.challenge === 'string') {\n processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);\n } else {\n processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);\n }\n } else if (response.status === 401 && !handledAuth) {\n authHeader = await this._handleUnauthorized(response);\n handledAuth = true;\n continue;\n } else {\n processingError = EdgeCallFailedError.fromHttpFailure(response);\n }\n } catch (error: any) {\n processingError = EdgeCallFailedError.fromProcessingFailureCause(error);\n }\n\n if (processingError.isRetryable && (await shouldRetry(requestContext, retryAfterHeaderValue))) {\n log('retrying edge request', { path, processingError });\n } else {\n throw processingError;\n }\n }\n }\n\n private async _handleUnauthorized(response: Response) {\n if (!this._edgeIdentity) {\n log.warn('edge unauthorized response received before identity was set');\n throw EdgeCallFailedError.fromHttpFailure(response);\n }\n const challenge = await handleAuthChallenge(response, this._edgeIdentity);\n this._authHeader = encodeAuthHeader(challenge);\n log('auth header updated');\n return this._authHeader;\n }\n}\n\nconst createRetryHandler = (args: EdgeHttpCallArgs) => {\n if (!args.retry || args.retry.count < 1) {\n return async () => false;\n }\n let retries = 0;\n const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;\n const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;\n const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;\n return async (ctx: Context, retryAfter: number) => {\n if (++retries > maxRetries || ctx.disposed) {\n return false;\n }\n\n if (retryAfter) {\n await sleep(retryAfter);\n } else {\n const timeout = baseTimeout + Math.random() * jitter;\n await sleep(timeout);\n }\n\n return true;\n };\n};\n\nexport type RetryConfig = {\n /**\n * A number of call retries, not counting the initial request.\n */\n count: number;\n /**\n * Delay before retries in ms.\n */\n timeout?: number;\n /**\n * A random amount of time before retrying to help prevent large bursts of requests.\n */\n jitter?: number;\n};\n\nexport type EdgeHttpGetArgs = { context?: Context; retry?: RetryConfig };\n\nexport type EdgeHttpPostArgs = { context?: Context; body?: any; retry?: RetryConfig };\n\ntype EdgeHttpCallArgs = {\n method: string;\n body?: any;\n context?: Context;\n retry?: RetryConfig;\n query?: Record<string, string>;\n};\n\nconst createRequest = (args: EdgeHttpCallArgs, authHeader: string | undefined): RequestInit => {\n return {\n method: args.method,\n body: args.body && JSON.stringify(args.body),\n headers: authHeader ? { Authorization: authHeader } : undefined,\n };\n};\n\nconst encodeAuthHeader = (challenge: Uint8Array) => {\n const encodedChallenge = Buffer.from(challenge).toString('base64');\n return `VerifiablePresentation pb;base64,${encodedChallenge}`;\n};\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,yBAAc;ACAd,mBAAqF;AACrF,qBAAyC;AACzC,iBAA6B;AAE7B,sBAA2B;ACJ3B,uBAA0B;AAC1B,mBAAuB;ACDvB,2BAAsB;AAEtB,IAAAA,gBAAmD;AACnD,IAAAC,kBAAkC;AAClC,IAAAC,oBAA0B;AAC1B,IAAAC,cAA6B;AAC7B,iBAAoB;AACpB,0BAA4C;AGP5C,yBAAmD;AAEnD,IAAAD,oBAA0B;AAC1B,qBAAwB;AACxB,kBAA0B;ACJ1B,IAAAF,gBAAsB;AACtB,IAAAC,kBAAwB;AAExB,IAAAE,cAAoB;AACpB,uBAuBO;;ALZA,IAAMC,sBAAsB,OAAOC,gBAA0BC,aAAAA;AAClEC,kCAAUF,eAAeG,WAAW,KAAA,QAAA;;;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leAuthChallenge", "failedResponse", "identity", "invariant", "status", "headerValue", "headers", "get", "startsWith", "challenge", "slice", "length", "presentation", "presentCredentials", "Buffer", "from", "schema", "getCodecForType", "encode", "SIGNAL_KEEPALIVE_INTERVAL", "SIGNAL_KEEPALIVE_TIMEOUT", "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nexport * from '@dxos/protocols/buf/dxos/edge/messenger_pb';\n\nexport * from './edge-client';\nexport * from './defs';\nexport * from './protocol';\nexport * from './errors';\nexport * from './auth';\nexport * from './edge-http-client';\nexport * from './edge-identity';\nexport * from './edge-ws-muxer';\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Trigger, scheduleMicroTask, TriggerState, PersistentLifecycle, Event } from '@dxos/async';\nimport { Resource, type Lifecycle } from '@dxos/context';\nimport { log, logInfo } from '@dxos/log';\nimport { type Message } from '@dxos/protocols/buf/dxos/edge/messenger_pb';\nimport { EdgeStatus } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { protocol } from './defs';\nimport { type EdgeIdentity, handleAuthChallenge } from './edge-identity';\nimport { EdgeWsConnection } from './edge-ws-connection';\nimport { EdgeConnectionClosedError, EdgeIdentityChangedError } from './errors';\nimport { type Protocol } from './protocol';\nimport { getEdgeUrlWithProtocol } from './utils';\n\nconst DEFAULT_TIMEOUT = 10_000;\n\nexport type MessageListener = (message: Message) => void;\nexport type ReconnectListener = () => void;\n\nexport interface EdgeConnection extends Required<Lifecycle> {\n statusChanged: Event<EdgeStatus>;\n get info(): any;\n get identityKey(): string;\n get peerKey(): string;\n get isOpen(): boolean;\n get status(): EdgeStatus;\n setIdentity(identity: EdgeIdentity): void;\n onMessage(listener: MessageListener): () => void;\n onReconnected(listener: ReconnectListener): () => void;\n send(message: Message): Promise<void>;\n}\n\nexport type MessengerConfig = {\n socketEndpoint: string;\n timeout?: number;\n protocol?: Protocol;\n disableAuth?: boolean;\n};\n\n/**\n * Messenger client for EDGE:\n * - While open, uses PersistentLifecycle to keep an open EdgeWsConnection, reconnecting on failures.\n * - Manages identity and re-create EdgeWsConnection when identity changes.\n * - Dispatches connection state and message notifications.\n */\nexport class EdgeClient extends Resource implements EdgeConnection {\n public readonly statusChanged = new Event<EdgeStatus>();\n\n private readonly _persistentLifecycle = new PersistentLifecycle<EdgeWsConnection>({\n start: async () => this._connect(),\n stop: async (state: EdgeWsConnection) => this._disconnect(state),\n });\n\n private readonly _messageListeners = new Set<MessageListener>();\n private readonly _reconnectListeners = new Set<ReconnectListener>();\n private readonly _baseWsUrl: string;\n private readonly _baseHttpUrl: string;\n private _currentConnection?: EdgeWsConnection = undefined;\n private _ready = new Trigger();\n\n constructor(\n private _identity: EdgeIdentity,\n private readonly _config: MessengerConfig,\n ) {\n super();\n this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, 'ws');\n this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, 'http');\n }\n\n @logInfo\n public get info() {\n return {\n open: this.isOpen,\n status: this.status,\n identity: this._identity.identityKey,\n device: this._identity.peerKey,\n };\n }\n\n get status(): EdgeStatus {\n return Boolean(this._currentConnection) && this._ready.state === TriggerState.RESOLVED\n ? EdgeStatus.CONNECTED\n : EdgeStatus.NOT_CONNECTED;\n }\n\n get identityKey() {\n return this._identity.identityKey;\n }\n\n get peerKey() {\n return this._identity.peerKey;\n }\n\n setIdentity(identity: EdgeIdentity) {\n if (identity.identityKey !== this._identity.identityKey || identity.peerKey !== this._identity.peerKey) {\n log('Edge identity changed', { identity, oldIdentity: this._identity });\n this._identity = identity;\n this._closeCurrentConnection(new EdgeIdentityChangedError());\n void this._persistentLifecycle.scheduleRestart();\n }\n }\n\n public onMessage(listener: MessageListener): () => void {\n this._messageListeners.add(listener);\n return () => this._messageListeners.delete(listener);\n }\n\n public onReconnected(listener: () => void): () => void {\n this._reconnectListeners.add(listener);\n if (this._ready.state === TriggerState.RESOLVED) {\n // Microtask so that listener is always called asynchronously, no matter the state of the ready trigger\n // at the moment of registration.\n scheduleMicroTask(this._ctx, () => {\n if (this._reconnectListeners.has(listener)) {\n try {\n listener();\n } catch (error) {\n log.catch(error);\n }\n }\n });\n }\n return () => this._reconnectListeners.delete(listener);\n }\n\n /**\n * Open connection to messaging service.\n */\n protected override async _open() {\n log('opening...', { info: this.info });\n this._persistentLifecycle.open().catch((err) => {\n log.warn('Error while opening connection', { err });\n });\n }\n\n /**\n * Close connection and free resources.\n */\n protected override async _close() {\n log('closing...', { peerKey: this._identity.peerKey });\n this._closeCurrentConnection();\n await this._persistentLifecycle.close();\n }\n\n private async _connect(): Promise<EdgeWsConnection | undefined> {\n if (this._ctx.disposed) {\n return undefined;\n }\n\n const identity = this._identity;\n const path = `/ws/${identity.identityKey}/${identity.peerKey}`;\n const protocolHeader = this._config.disableAuth ? undefined : await this._createAuthHeader(path);\n if (this._identity !== identity) {\n log('identity changed during auth header request');\n return undefined;\n }\n\n const restartRequired = new Trigger();\n const url = new URL(path, this._baseWsUrl);\n log('Opening websocket', { url: url.toString(), protocolHeader });\n const connection = new EdgeWsConnection(\n identity,\n { url, protocolHeader },\n {\n onConnected: () => {\n if (this._isActive(connection)) {\n this._ready.wake();\n this._notifyReconnected();\n } else {\n log.verbose('connected callback ignored, because connection is not active');\n }\n },\n onRestartRequired: () => {\n if (this._isActive(connection)) {\n this._closeCurrentConnection();\n void this._persistentLifecycle.scheduleRestart();\n } else {\n log.verbose('restart requested by inactive connection');\n }\n restartRequired.wake();\n },\n onMessage: (message) => {\n if (this._isActive(connection)) {\n this._notifyMessageReceived(message);\n } else {\n log.verbose('ignored a message on inactive connection', {\n from: message.source,\n type: message.payload?.typeUrl,\n });\n }\n },\n },\n );\n this._currentConnection = connection;\n\n await connection.open();\n // Race with restartRequired so that restart is not blocked by _connect execution.\n // Wait on ready to attempt a reconnect if it times out.\n await Promise.race([this._ready.wait({ timeout: this._config.timeout ?? DEFAULT_TIMEOUT }), restartRequired]);\n\n return connection;\n }\n\n private async _disconnect(state: EdgeWsConnection) {\n await state.close();\n this.statusChanged.emit(this.status);\n }\n\n private _closeCurrentConnection(error: Error = new EdgeConnectionClosedError()) {\n this._currentConnection = undefined;\n this._ready.throw(error);\n this._ready.reset();\n this.statusChanged.emit(this.status);\n }\n\n private _notifyReconnected() {\n this.statusChanged.emit(this.status);\n for (const listener of this._reconnectListeners) {\n try {\n listener();\n } catch (err) {\n log.error('ws reconnect listener failed', { err });\n }\n }\n }\n\n private _notifyMessageReceived(message: Message) {\n for (const listener of this._messageListeners) {\n try {\n listener(message);\n } catch (err) {\n log.error('ws incoming message processing failed', { err, payload: protocol.getPayloadType(message) });\n }\n }\n }\n\n /**\n * Send message.\n * NOTE: The message is guaranteed to be delivered but the service must respond with a message to confirm processing.\n */\n public async send(message: Message): Promise<void> {\n if (this._ready.state !== TriggerState.RESOLVED) {\n log('waiting for websocket to become ready');\n await this._ready.wait({ timeout: this._config.timeout ?? DEFAULT_TIMEOUT });\n }\n\n if (!this._currentConnection) {\n throw new EdgeConnectionClosedError();\n }\n\n if (\n message.source &&\n (message.source.peerKey !== this._identity.peerKey || message.source.identityKey !== this.identityKey)\n ) {\n throw new EdgeIdentityChangedError();\n }\n\n this._currentConnection.send(message);\n }\n\n private async _createAuthHeader(path: string): Promise<string | undefined> {\n const httpUrl = new URL(path, this._baseHttpUrl);\n httpUrl.protocol = getEdgeUrlWithProtocol(this._baseWsUrl.toString(), 'http');\n const response = await fetch(httpUrl, { method: 'GET' });\n if (response.status === 401) {\n return encodePresentationWsAuthHeader(await handleAuthChallenge(response, this._identity));\n } else {\n log.warn('no auth challenge from edge', { status: response.status, statusText: response.statusText });\n return undefined;\n }\n }\n\n private _isActive = (connection: EdgeWsConnection) => connection === this._currentConnection;\n}\n\nconst encodePresentationWsAuthHeader = (encodedPresentation: Uint8Array): string => {\n // = and / characters are not allowed in the WebSocket subprotocol header.\n const encodedToken = Buffer.from(encodedPresentation).toString('base64').replace(/=*$/, '').replaceAll('/', '|');\n return `base64url.bearer.authorization.dxos.org.${encodedToken}`;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Presentation } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nexport interface EdgeIdentity {\n peerKey: string;\n identityKey: string;\n /**\n * Returns credential presentation issued by the identity key.\n * Presentation must have the provided challenge.\n * Presentation may include ServiceAccess credentials.\n */\n presentCredentials({ challenge }: { challenge: Uint8Array }): Promise<Presentation>;\n}\n\nexport const handleAuthChallenge = async (failedResponse: Response, identity: EdgeIdentity): Promise<Uint8Array> => {\n invariant(failedResponse.status === 401);\n\n const headerValue = failedResponse.headers.get('Www-Authenticate');\n invariant(headerValue?.startsWith('VerifiablePresentation challenge='));\n\n const challenge = headerValue?.slice('VerifiablePresentation challenge='.length);\n invariant(challenge);\n\n const presentation = await identity.presentCredentials({ challenge: Buffer.from(challenge, 'base64') });\n return schema.getCodecForType('dxos.halo.credentials.Presentation').encode(presentation);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'isomorphic-ws';\n\nimport { scheduleTask, scheduleTaskInterval } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log, logInfo } from '@dxos/log';\nimport { EdgeWebsocketProtocol } from '@dxos/protocols';\nimport { buf } from '@dxos/protocols/buf';\nimport { MessageSchema, type Message } from '@dxos/protocols/buf/dxos/edge/messenger_pb';\n\nimport { protocol } from './defs';\nimport { type EdgeIdentity } from './edge-identity';\nimport { CLOUDFLARE_MESSAGE_MAX_BYTES, WebSocketMuxer } from './edge-ws-muxer';\nimport { toUint8Array } from './protocol';\n\nconst SIGNAL_KEEPALIVE_INTERVAL = 4_000;\nconst SIGNAL_KEEPALIVE_TIMEOUT = 12_000;\n\nexport type EdgeWsConnectionCallbacks = {\n onConnected: () => void;\n onMessage: (message: Message) => void;\n onRestartRequired: () => void;\n};\n\nexport class EdgeWsConnection extends Resource {\n private _inactivityTimeoutCtx: Context | undefined;\n private _ws: WebSocket | undefined;\n private _wsMuxer: WebSocketMuxer | undefined;\n\n constructor(\n private readonly _identity: EdgeIdentity,\n private readonly _connectionInfo: { url: URL; protocolHeader?: string },\n private readonly _callbacks: EdgeWsConnectionCallbacks,\n ) {\n super();\n }\n\n @logInfo\n public get info() {\n return {\n open: this.isOpen,\n identity: this._identity.identityKey,\n device: this._identity.peerKey,\n };\n }\n\n public send(message: Message) {\n invariant(this._ws);\n invariant(this._wsMuxer);\n log('sending...', { peerKey: this._identity.peerKey, payload: protocol.getPayloadType(message) });\n if (this._ws?.protocol.includes(EdgeWebsocketProtocol.V0)) {\n const binary = buf.toBinary(MessageSchema, message);\n if (binary.length > CLOUDFLARE_MESSAGE_MAX_BYTES) {\n log.error('Message dropped because it was too large (>1MB).', {\n byteLength: binary.byteLength,\n serviceId: message.serviceId,\n payload: protocol.getPayloadType(message),\n });\n return;\n }\n this._ws.send(binary);\n } else {\n this._wsMuxer.send(message).catch((e) => log.catch(e));\n }\n }\n\n protected override async _open() {\n const baseProtocols = [...Object.values(EdgeWebsocketProtocol)];\n this._ws = new WebSocket(\n this._connectionInfo.url.toString(),\n this._connectionInfo.protocolHeader\n ? [...baseProtocols, this._connectionInfo.protocolHeader]\n : [...baseProtocols],\n );\n const muxer = new WebSocketMuxer(this._ws);\n this._wsMuxer = muxer;\n\n this._ws.onopen = () => {\n if (this.isOpen) {\n log('connected');\n this._callbacks.onConnected();\n this._scheduleHeartbeats();\n } else {\n log.verbose('connected after becoming inactive', { currentIdentity: this._identity });\n }\n };\n this._ws.onclose = (event) => {\n if (this.isOpen) {\n log.warn('disconnected while being open', { code: event.code, reason: event.reason });\n this._callbacks.onRestartRequired();\n muxer.destroy();\n }\n };\n this._ws.onerror = (event) => {\n if (this.isOpen) {\n log.warn('edge connection socket error', { error: event.error, info: event.message });\n this._callbacks.onRestartRequired();\n } else {\n log.verbose('error ignored on closed connection', { error: event.error });\n }\n };\n /**\n * https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data\n */\n this._ws.onmessage = async (event) => {\n if (!this.isOpen) {\n log.verbose('message ignored on closed connection', { event: event.type });\n return;\n }\n if (event.data === '__pong__') {\n this._rescheduleHeartbeatTimeout();\n return;\n }\n const bytes = await toUint8Array(event.data);\n if (!this.isOpen) {\n return;\n }\n\n const message = this._ws?.protocol?.includes(EdgeWebsocketProtocol.V0)\n ? buf.fromBinary(MessageSchema, bytes)\n : muxer.receiveData(bytes);\n\n if (message) {\n log('received', { from: message.source, payload: protocol.getPayloadType(message) });\n this._callbacks.onMessage(message);\n }\n };\n }\n\n protected override async _close() {\n void this._inactivityTimeoutCtx?.dispose().catch(() => {});\n\n try {\n this._ws?.close();\n this._ws = undefined;\n this._wsMuxer?.destroy();\n this._wsMuxer = undefined;\n } catch (err) {\n if (err instanceof Error && err.message.includes('WebSocket is closed before the connection is established.')) {\n return;\n }\n log.warn('Error closing websocket', { err });\n }\n }\n\n private _scheduleHeartbeats() {\n invariant(this._ws);\n scheduleTaskInterval(\n this._ctx,\n async () => {\n // TODO(mykola): use RFC6455 ping/pong once implemented in the browser?\n // Cloudflare's worker responds to this `without interrupting hibernation`. https://developers.cloudflare.com/durable-objects/api/websockets/#setwebsocketautoresponse\n this._ws?.send('__ping__');\n },\n SIGNAL_KEEPALIVE_INTERVAL,\n );\n this._ws.send('__ping__');\n this._rescheduleHeartbeatTimeout();\n }\n\n private _rescheduleHeartbeatTimeout() {\n if (!this.isOpen) {\n return;\n }\n void this._inactivityTimeoutCtx?.dispose();\n this._inactivityTimeoutCtx = new Context();\n scheduleTask(\n this._inactivityTimeoutCtx,\n () => {\n if (this.isOpen) {\n log.warn('restart due to inactivity timeout');\n this._callbacks.onRestartRequired();\n }\n },\n SIGNAL_KEEPALIVE_TIMEOUT,\n );\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport class EdgeConnectionClosedError extends Error {\n constructor() {\n super('Edge connection closed.');\n }\n}\n\nexport class EdgeIdentityChangedError extends Error {\n constructor() {\n super('Edge identity changed.');\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const getEdgeUrlWithProtocol = (baseUrl: string, protocol: 'http' | 'ws') => {\n const isSecure = baseUrl.startsWith('https') || baseUrl.startsWith('wss');\n const url = new URL(baseUrl);\n url.protocol = protocol + (isSecure ? 's' : '');\n return url.toString();\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { createCredential, signPresentation } from '@dxos/credentials';\nimport { type Signer } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { type Chain, type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport type { EdgeIdentity } from './edge-identity';\n\n/**\n * Edge identity backed by a device key without a credential chain.\n */\nexport const createDeviceEdgeIdentity = async (signer: Signer, key: PublicKey): Promise<EdgeIdentity> => {\n return {\n identityKey: key.toHex(),\n peerKey: key.toHex(),\n presentCredentials: async ({ challenge }) => {\n return signPresentation({\n presentation: {\n credentials: [\n // Verifier requires at least one credential in the presentation to establish the subject.\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: key,\n subject: key,\n signer,\n }),\n ],\n },\n signer,\n signerKey: key,\n nonce: challenge,\n });\n },\n };\n};\n\n/**\n * Edge identity backed by a chain of credentials.\n */\nexport const createChainEdgeIdentity = async (\n signer: Signer,\n identityKey: PublicKey,\n peerKey: PublicKey,\n chain: Chain | undefined,\n credentials: Credential[],\n): Promise<EdgeIdentity> => {\n const credentialsToSign =\n credentials.length > 0\n ? credentials\n : [\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: identityKey,\n subject: identityKey,\n signer,\n chain,\n signingKey: peerKey,\n }),\n ];\n\n return {\n identityKey: identityKey.toHex(),\n peerKey: peerKey.toHex(),\n presentCredentials: async ({ challenge }) => {\n // TODO: make chain required after device invitation flow update release\n invariant(chain);\n return signPresentation({\n presentation: {\n credentials: credentialsToSign,\n },\n signer,\n nonce: challenge,\n signerKey: peerKey,\n chain,\n });\n },\n };\n};\n\n/**\n * Edge identity backed by a random ephemeral key without HALO.\n */\nexport const createEphemeralEdgeIdentity = async (): Promise<EdgeIdentity> => {\n const keyring = new Keyring();\n const key = await keyring.createKey();\n return createDeviceEdgeIdentity(keyring, key);\n};\n\n/**\n * Creates a HALO chain of credentials to act as an edge identity.\n */\nexport const createTestHaloEdgeIdentity = async (\n signer: Signer,\n identityKey: PublicKey,\n deviceKey: PublicKey,\n): Promise<EdgeIdentity> => {\n const deviceAdmission = await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.AuthorizedDevice',\n deviceKey,\n identityKey,\n },\n issuer: identityKey,\n subject: deviceKey,\n signer,\n });\n return createChainEdgeIdentity(signer, identityKey, deviceKey, { credential: deviceAdmission }, [\n await createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n issuer: identityKey,\n subject: identityKey,\n signer,\n }),\n ]);\n};\n\nexport const createStubEdgeIdentity = (): EdgeIdentity => {\n const identityKey = PublicKey.random();\n const deviceKey = PublicKey.random();\n return {\n identityKey: identityKey.toHex(),\n peerKey: deviceKey.toHex(),\n presentCredentials: async () => {\n throw new Error('Stub identity does not support authentication.');\n },\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { sleep } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { type PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n EdgeCallFailedError,\n type EdgeHttpResponse,\n type GetNotarizationResponseBody,\n type PostNotarizationRequestBody,\n type JoinSpaceRequest,\n type JoinSpaceResponseBody,\n EdgeAuthChallengeError,\n type CreateAgentResponseBody,\n type CreateAgentRequestBody,\n type GetAgentStatusResponseBody,\n type RecoverIdentityRequest,\n type RecoverIdentityResponseBody,\n type UploadFunctionRequest,\n type UploadFunctionResponseBody,\n type ObjectId,\n type ExecuteWorkflowResponseBody,\n type QueueQuery,\n type QueryResult,\n type InitiateOAuthFlowRequest,\n type InitiateOAuthFlowResponse,\n type CreateSpaceRequest,\n type CreateSpaceResponseBody,\n} from '@dxos/protocols';\n\nimport { type EdgeIdentity, handleAuthChallenge } from './edge-identity';\nimport { getEdgeUrlWithProtocol } from './utils';\n\nconst DEFAULT_RETRY_TIMEOUT = 1500;\nconst DEFAULT_RETRY_JITTER = 500;\nconst DEFAULT_MAX_RETRIES_COUNT = 3;\n\nexport class EdgeHttpClient {\n private readonly _baseUrl: string;\n\n private _edgeIdentity: EdgeIdentity | undefined;\n\n /**\n * Auth header is cached until receiving the next 401 from EDGE, at which point it gets refreshed.\n */\n private _authHeader: string | undefined;\n\n constructor(baseUrl: string) {\n this._baseUrl = getEdgeUrlWithProtocol(baseUrl, 'http');\n log('created', { url: this._baseUrl });\n }\n\n get baseUrl() {\n return this._baseUrl;\n }\n\n setIdentity(identity: EdgeIdentity) {\n if (this._edgeIdentity?.identityKey !== identity.identityKey || this._edgeIdentity?.peerKey !== identity.peerKey) {\n this._edgeIdentity = identity;\n this._authHeader = undefined;\n }\n }\n\n public createAgent(body: CreateAgentRequestBody, args?: EdgeHttpGetArgs): Promise<CreateAgentResponseBody> {\n return this._call('/agents/create', { ...args, method: 'POST', body });\n }\n\n public getAgentStatus(\n request: { ownerIdentityKey: PublicKey },\n args?: EdgeHttpGetArgs,\n ): Promise<GetAgentStatusResponseBody> {\n return this._call(`/users/${request.ownerIdentityKey.toHex()}/agent/status`, { ...args, method: 'GET' });\n }\n\n public getCredentialsForNotarization(spaceId: SpaceId, args?: EdgeHttpGetArgs): Promise<GetNotarizationResponseBody> {\n return this._call(`/spaces/${spaceId}/notarization`, { ...args, method: 'GET' });\n }\n\n public async notarizeCredentials(\n spaceId: SpaceId,\n body: PostNotarizationRequestBody,\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n await this._call(`/spaces/${spaceId}/notarization`, { ...args, body, method: 'POST' });\n }\n\n public async joinSpaceByInvitation(\n spaceId: SpaceId,\n body: JoinSpaceRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<JoinSpaceResponseBody> {\n return this._call(`/spaces/${spaceId}/join`, { ...args, body, method: 'POST' });\n }\n\n public async recoverIdentity(\n body: RecoverIdentityRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<RecoverIdentityResponseBody> {\n return this._call('/identity/recover', { ...args, body, method: 'POST' });\n }\n\n public async executeWorkflow(\n spaceId: SpaceId,\n graphId: ObjectId,\n input: any,\n args?: EdgeHttpGetArgs,\n ): Promise<ExecuteWorkflowResponseBody> {\n return this._call(`/workflows/${spaceId}/${graphId}`, { ...args, body: input, method: 'POST' });\n }\n\n public async uploadFunction(\n pathParts: { spaceId: SpaceId; functionId?: string },\n body: UploadFunctionRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<UploadFunctionResponseBody> {\n const path = ['functions', pathParts.spaceId, ...(pathParts.functionId ? [pathParts.functionId] : [])].join('/');\n return this._call(path, { ...args, body, method: 'PUT' });\n }\n\n public async initiateOAuthFlow(\n body: InitiateOAuthFlowRequest,\n args?: EdgeHttpGetArgs,\n ): Promise<InitiateOAuthFlowResponse> {\n return this._call('/oauth/initiate', { ...args, body, method: 'POST' });\n }\n\n public async queryQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n query: QueueQuery,\n args?: EdgeHttpGetArgs,\n ): Promise<QueryResult> {\n const { queueId } = query;\n const queryParams = new URLSearchParams();\n if (query.after != null) {\n queryParams.set('after', query.after);\n }\n if (query.before != null) {\n queryParams.set('before', query.before);\n }\n if (query.limit != null) {\n queryParams.set('limit', query.limit.toString());\n }\n if (query.reverse != null) {\n queryParams.set('reverse', query.reverse.toString());\n }\n if (query.objectIds != null) {\n queryParams.set('objectIds', query.objectIds.join(','));\n }\n return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}/query?${queryParams.toString()}`, {\n ...args,\n method: 'GET',\n });\n }\n\n public async insertIntoQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n queueId: ObjectId,\n objects: unknown[],\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {\n ...args,\n body: { objects },\n method: 'POST',\n });\n }\n\n async deleteFromQueue(\n subspaceTag: string,\n spaceId: SpaceId,\n queueId: ObjectId,\n objectIds: ObjectId[],\n args?: EdgeHttpGetArgs,\n ): Promise<void> {\n return this._call(`/spaces/${subspaceTag}/${spaceId}/queue/${queueId}`, {\n ...args,\n query: { ids: objectIds.join(',') },\n method: 'DELETE',\n });\n }\n\n async createSpace(body: CreateSpaceRequest, args?: EdgeHttpGetArgs): Promise<CreateSpaceResponseBody> {\n return this._call('/spaces/create', { ...args, body, method: 'POST' });\n }\n\n private async _call<T>(path: string, args: EdgeHttpCallArgs): Promise<T> {\n const requestContext = args.context ?? new Context();\n const shouldRetry = createRetryHandler(args);\n let url = `${this._baseUrl}${path.startsWith('/') ? path.slice(1) : path}`;\n\n if (args.query) {\n const queryParams = new URLSearchParams();\n for (const [key, value] of Object.entries(args.query)) {\n queryParams.set(key, value.toString());\n }\n url += `?${queryParams.toString()}`;\n }\n\n log('call', { method: args.method, path, request: args.body });\n\n let handledAuth = false;\n let authHeader = this._authHeader;\n while (true) {\n let processingError: EdgeCallFailedError;\n let retryAfterHeaderValue: number = Number.NaN;\n try {\n const request = createRequest(args, authHeader);\n const response = await fetch(url, request);\n\n retryAfterHeaderValue = Number(response.headers.get('Retry-After'));\n\n if (response.ok) {\n const body = (await response.json()) as EdgeHttpResponse<T>;\n if (body.success) {\n return body.data;\n }\n\n log('unsuccessful edge response', { path, body });\n\n if (body.errorData?.type === 'auth_challenge' && typeof body.errorData?.challenge === 'string') {\n processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);\n } else {\n processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);\n }\n } else if (response.status === 401 && !handledAuth) {\n authHeader = await this._handleUnauthorized(response);\n handledAuth = true;\n continue;\n } else {\n processingError = EdgeCallFailedError.fromHttpFailure(response);\n }\n } catch (error: any) {\n processingError = EdgeCallFailedError.fromProcessingFailureCause(error);\n }\n\n if (processingError.isRetryable && (await shouldRetry(requestContext, retryAfterHeaderValue))) {\n log('retrying edge request', { path, processingError });\n } else {\n throw processingError;\n }\n }\n }\n\n private async _handleUnauthorized(response: Response) {\n if (!this._edgeIdentity) {\n log.warn('edge unauthorized response received before identity was set');\n throw EdgeCallFailedError.fromHttpFailure(response);\n }\n const challenge = await handleAuthChallenge(response, this._edgeIdentity);\n this._authHeader = encodeAuthHeader(challenge);\n log('auth header updated');\n return this._authHeader;\n }\n}\n\nconst createRetryHandler = (args: EdgeHttpCallArgs) => {\n if (!args.retry || args.retry.count < 1) {\n return async () => false;\n }\n let retries = 0;\n const maxRetries = args.retry.count ?? DEFAULT_MAX_RETRIES_COUNT;\n const baseTimeout = args.retry.timeout ?? DEFAULT_RETRY_TIMEOUT;\n const jitter = args.retry.jitter ?? DEFAULT_RETRY_JITTER;\n return async (ctx: Context, retryAfter: number) => {\n if (++retries > maxRetries || ctx.disposed) {\n return false;\n }\n\n if (retryAfter) {\n await sleep(retryAfter);\n } else {\n const timeout = baseTimeout + Math.random() * jitter;\n await sleep(timeout);\n }\n\n return true;\n };\n};\n\nexport type RetryConfig = {\n /**\n * A number of call retries, not counting the initial request.\n */\n count: number;\n /**\n * Delay before retries in ms.\n */\n timeout?: number;\n /**\n * A random amount of time before retrying to help prevent large bursts of requests.\n */\n jitter?: number;\n};\n\nexport type EdgeHttpGetArgs = { context?: Context; retry?: RetryConfig };\n\nexport type EdgeHttpPostArgs = { context?: Context; body?: any; retry?: RetryConfig };\n\ntype EdgeHttpCallArgs = {\n method: string;\n body?: any;\n context?: Context;\n retry?: RetryConfig;\n query?: Record<string, string>;\n};\n\nconst createRequest = (args: EdgeHttpCallArgs, authHeader: string | undefined): RequestInit => {\n return {\n method: args.method,\n body: args.body && JSON.stringify(args.body),\n headers: authHeader ? { Authorization: authHeader } : undefined,\n };\n};\n\nconst encodeAuthHeader = (challenge: Uint8Array) => {\n const encodedChallenge = Buffer.from(challenge).toString('base64');\n return `VerifiablePresentation pb;base64,${encodedChallenge}`;\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,yBAAc;ACAd,mBAAqF;AACrF,qBAAyC;AACzC,iBAA6B;AAE7B,sBAA2B;ACJ3B,uBAA0B;AAC1B,mBAAuB;ACDvB,2BAAsB;AAEtB,IAAAA,gBAAmD;AACnD,IAAAC,kBAAkC;AAClC,IAAAC,oBAA0B;AAC1B,IAAAC,cAA6B;AAC7B,uBAAsC;AACtC,iBAAoB;AACpB,0BAA4C;AGR5C,yBAAmD;AAEnD,IAAAD,oBAA0B;AAC1B,qBAAwB;AACxB,kBAA0B;ACJ1B,IAAAF,gBAAsB;AACtB,IAAAC,kBAAwB;AAExB,IAAAE,cAAoB;AACpB,IAAAC,oBAuBO;;ALZA,IAAMC,sBAAsB,OAAOC,gBAA0BC,aAAAA;AAClEC,kCAAUF,eAAeG,WAAW,KAAA,QAAA;;;;;;;;;AAEpC,QAAMC,cAAcJ,eAAeK,QAAQC,IAAI,kBAAA;AAC/CJ,kCAAUE,aAAaG,WAAW,mCAAA,GAAA,QAAA;;;;;;;;;AAElC,QAAMC,YAAYJ,aAAaK,MAAM,oCAAoCC,MAAM;AAC/ER,kCAAUM,WAAAA,QAAAA;;;;;;;;;AAEV,QAAMG,eAAe,MAAMV,SAASW,mBAAmB;IAAEJ,WAAWK,OAAOC,KAAKN,WAAW,QAAA;EAAU,CAAA;AACrG,SAAOO,oBAAOC,gBAAgB,oCAAA,EAAsCC,OAAON,YAAAA;AAC7E;;;;;;;;ACXA,IAAMO,4BAA4B;AAClC,IAAMC,2BAA2B;AAQ1B,IAAMC,mBAAN,cAA+BC,yBAAAA;EAKpCC,YACmBC,WACAC,iBACAC,YACjB;AACA,UAAK;SAJYF,YAAA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6
|
+
"names": ["import_async", "import_context", "import_invariant", "import_log", "import_protocols", "handleAuthChallenge", "failedResponse", "identity", "invariant", "status", "headerValue", "headers", "get", "startsWith", "challenge", "slice", "length", "presentation", "presentCredentials", "Buffer", "from", "schema", "getCodecForType", "encode", "SIGNAL_KEEPALIVE_INTERVAL", "SIGNAL_KEEPALIVE_TIMEOUT", "EdgeWsConnection", "Resource", "constructor", "_identity", "_connectionInfo", "_callbacks", "info", "open", "isOpen", "identityKey", "device", "peerKey", "send", "message", "_ws", "_wsMuxer", "log", "payload", "protocol", "getPayloadType", "includes", "EdgeWebsocketProtocol", "V0", "binary", "buf", "toBinary", "MessageSchema", "CLOUDFLARE_MESSAGE_MAX_BYTES", "error", "byteLength", "serviceId", "catch", "e", "_open", "baseProtocols", "Object", "values", "WebSocket", "url", "toString", "protocolHeader", "muxer", "WebSocketMuxer", "onopen", "onConnected", "_scheduleHeartbeats", "verbose", "currentIdentity", "onclose", "event", "warn", "code", "reason", "onRestartRequired", "destroy", "onerror", "onmessage", "type", "data", "_rescheduleHeartbeatTimeout", "bytes", "toUint8Array", "fromBinary", "receiveData", "source", "onMessage", "_close", "_inactivityTimeoutCtx", "dispose", "close", "undefined", "err", "Error", "scheduleTaskInterval", "_ctx", "Context", "scheduleTask", "logInfo", "EdgeConnectionClosedError", "EdgeIdentityChangedError", "getEdgeUrlWithProtocol", "baseUrl", "isSecure", "URL", "DEFAULT_TIMEOUT", "EdgeClient", "_config", "statusChanged", "Event", "_persistentLifecycle", "PersistentLifecycle", "start", "_connect", "stop", "state", "_disconnect", "_messageListeners", "Set", "_reconnectListeners", "_currentConnection", "_ready", "Trigger", "_isActive", "connection", "_baseWsUrl", "socketEndpoint", "_baseHttpUrl", "Boolean", "TriggerState", "RESOLVED", "EdgeStatus", "CONNECTED", "NOT_CONNECTED", "setIdentity", "oldIdentity", "_closeCurrentConnection", "scheduleRestart", "listener", "add", "delete", "onReconnected", "scheduleMicroTask", "has", "disposed", "path", "disableAuth", "_createAuthHeader", "restartRequired", "wake", "_notifyReconnected", "_notifyMessageReceived", "typeUrl", "Promise", "race", "wait", "timeout", "emit", "throw", "reset", "httpUrl", "response", "fetch", "method", "encodePresentationWsAuthHeader", "statusText", "encodedPresentation", "encodedToken", "replace", "replaceAll", "createDeviceEdgeIdentity", "signer", "key", "toHex", "signPresentation", "credentials", "createCredential", "assertion", "issuer", "subject", "signerKey", "nonce", "createChainEdgeIdentity", "chain", "credentialsToSign", "signingKey", "createEphemeralEdgeIdentity", "keyring", "Keyring", "createKey", "createTestHaloEdgeIdentity", "deviceKey", "deviceAdmission", "credential", "createStubEdgeIdentity", "PublicKey", "random", "DEFAULT_RETRY_TIMEOUT", "DEFAULT_RETRY_JITTER", "DEFAULT_MAX_RETRIES_COUNT", "EdgeHttpClient", "_baseUrl", "_edgeIdentity", "_authHeader", "createAgent", "body", "args", "_call", "getAgentStatus", "request", "ownerIdentityKey", "getCredentialsForNotarization", "spaceId", "notarizeCredentials", "joinSpaceByInvitation", "recoverIdentity", "executeWorkflow", "graphId", "input", "uploadFunction", "pathParts", "functionId", "join", "initiateOAuthFlow", "queryQueue", "subspaceTag", "query", "queueId", "queryParams", "URLSearchParams", "after", "set", "before", "limit", "reverse", "objectIds", "insertIntoQueue", "objects", "deleteFromQueue", "ids", "createSpace", "requestContext", "context", "shouldRetry", "createRetryHandler", "value", "entries", "handledAuth", "authHeader", "processingError", "retryAfterHeaderValue", "Number", "NaN", "createRequest", "ok", "json", "success", "errorData", "EdgeAuthChallengeError", "EdgeCallFailedError", "fromUnsuccessfulResponse", "_handleUnauthorized", "fromHttpFailure", "fromProcessingFailureCause", "isRetryable", "encodeAuthHeader", "retry", "count", "retries", "maxRetries", "baseTimeout", "jitter", "ctx", "retryAfter", "sleep", "Math", "JSON", "stringify", "Authorization", "encodedChallenge"]
|
|
7
7
|
}
|