@dxos/client-services 0.1.22 → 0.1.24-next.6b1f434

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 (129) hide show
  1. package/dist/lib/browser/chunk-ZPZBLOQW.mjs +4086 -0
  2. package/dist/lib/browser/chunk-ZPZBLOQW.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +68 -3027
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/packlets/testing/index.mjs +198 -0
  7. package/dist/lib/browser/packlets/testing/index.mjs.map +7 -0
  8. package/dist/lib/node/index.cjs +1694 -667
  9. package/dist/lib/node/index.cjs.map +4 -4
  10. package/dist/lib/node/meta.json +1 -1
  11. package/dist/lib/node/packlets/testing/index.cjs +3806 -0
  12. package/dist/lib/node/packlets/testing/index.cjs.map +7 -0
  13. package/dist/types/src/packlets/deprecated/profile.d.ts +3 -1
  14. package/dist/types/src/packlets/deprecated/profile.d.ts.map +1 -1
  15. package/dist/types/src/packlets/deprecated/space.d.ts.map +1 -1
  16. package/dist/types/src/packlets/deprecated/system.d.ts +15 -9
  17. package/dist/types/src/packlets/deprecated/system.d.ts.map +1 -1
  18. package/dist/types/src/packlets/devtools/devtools.d.ts +2 -2
  19. package/dist/types/src/packlets/devtools/devtools.d.ts.map +1 -1
  20. package/dist/types/src/packlets/devtools/feeds.d.ts.map +1 -1
  21. package/dist/types/src/packlets/devtools/network.d.ts +3 -3
  22. package/dist/types/src/packlets/devtools/network.d.ts.map +1 -1
  23. package/dist/types/src/packlets/devtools/spaces.d.ts.map +1 -1
  24. package/dist/types/src/packlets/identity/authenticator.d.ts +9 -9
  25. package/dist/types/src/packlets/identity/authenticator.d.ts.map +1 -1
  26. package/dist/types/src/packlets/identity/identity-manager.d.ts +8 -2
  27. package/dist/types/src/packlets/identity/identity-manager.d.ts.map +1 -1
  28. package/dist/types/src/packlets/identity/identity.d.ts +5 -4
  29. package/dist/types/src/packlets/identity/identity.d.ts.map +1 -1
  30. package/dist/types/src/packlets/invitations/halo-invitations-handler.d.ts +11 -3
  31. package/dist/types/src/packlets/invitations/halo-invitations-handler.d.ts.map +1 -1
  32. package/dist/types/src/packlets/invitations/invitations.d.ts +1 -1
  33. package/dist/types/src/packlets/invitations/invitations.d.ts.map +1 -1
  34. package/dist/types/src/packlets/invitations/space-invitations-handler.d.ts +1 -1
  35. package/dist/types/src/packlets/invitations/space-invitations-handler.d.ts.map +1 -1
  36. package/dist/types/src/packlets/services/service-context.d.ts +3 -1
  37. package/dist/types/src/packlets/services/service-context.d.ts.map +1 -1
  38. package/dist/types/src/packlets/services/service-context.test.d.ts +2 -0
  39. package/dist/types/src/packlets/services/service-context.test.d.ts.map +1 -0
  40. package/dist/types/src/packlets/services/service-definitions.d.ts +1 -1
  41. package/dist/types/src/packlets/services/service-definitions.d.ts.map +1 -1
  42. package/dist/types/src/packlets/services/service-host.d.ts +9 -6
  43. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  44. package/dist/types/src/packlets/services/service-registry.d.ts +4 -3
  45. package/dist/types/src/packlets/services/service-registry.d.ts.map +1 -1
  46. package/dist/types/src/packlets/spaces/data-space-manager.d.ts +9 -2
  47. package/dist/types/src/packlets/spaces/data-space-manager.d.ts.map +1 -1
  48. package/dist/types/src/packlets/spaces/data-space-manager.test.d.ts +2 -0
  49. package/dist/types/src/packlets/spaces/data-space-manager.test.d.ts.map +1 -0
  50. package/dist/types/src/packlets/spaces/data-space.d.ts +20 -4
  51. package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
  52. package/dist/types/src/packlets/spaces/notarization-plugin.d.ts +50 -0
  53. package/dist/types/src/packlets/spaces/notarization-plugin.d.ts.map +1 -0
  54. package/dist/types/src/packlets/spaces/notarization-plugin.test.d.ts +2 -0
  55. package/dist/types/src/packlets/spaces/notarization-plugin.test.d.ts.map +1 -0
  56. package/dist/types/src/packlets/spaces/spaces-service.d.ts +3 -2
  57. package/dist/types/src/packlets/spaces/spaces-service.d.ts.map +1 -1
  58. package/dist/types/src/packlets/testing/credential-utils.d.ts +8 -0
  59. package/dist/types/src/packlets/testing/credential-utils.d.ts.map +1 -0
  60. package/dist/types/src/packlets/testing/index.d.ts +2 -0
  61. package/dist/types/src/packlets/testing/index.d.ts.map +1 -1
  62. package/dist/types/src/packlets/testing/invitation-utils.d.ts +3 -0
  63. package/dist/types/src/packlets/testing/invitation-utils.d.ts.map +1 -0
  64. package/dist/types/src/packlets/testing/test-builder.d.ts +31 -2
  65. package/dist/types/src/packlets/testing/test-builder.d.ts.map +1 -1
  66. package/dist/types/src/packlets/vault/iframe-host-runtime.d.ts +35 -0
  67. package/dist/types/src/packlets/vault/iframe-host-runtime.d.ts.map +1 -0
  68. package/dist/types/src/packlets/vault/{iframe-runtime.d.ts → iframe-proxy-runtime.d.ts} +9 -4
  69. package/dist/types/src/packlets/vault/iframe-proxy-runtime.d.ts.map +1 -0
  70. package/dist/types/src/packlets/vault/index.d.ts +6 -1
  71. package/dist/types/src/packlets/vault/index.d.ts.map +1 -1
  72. package/dist/types/src/packlets/vault/services.d.ts +9 -1
  73. package/dist/types/src/packlets/vault/services.d.ts.map +1 -1
  74. package/dist/types/src/packlets/vault/shell-controller.d.ts +24 -0
  75. package/dist/types/src/packlets/vault/shell-controller.d.ts.map +1 -0
  76. package/dist/types/src/packlets/vault/shell-runtime.d.ts +45 -0
  77. package/dist/types/src/packlets/vault/shell-runtime.d.ts.map +1 -0
  78. package/dist/types/src/packlets/vault/vault-resource-lock.d.ts +19 -0
  79. package/dist/types/src/packlets/vault/vault-resource-lock.d.ts.map +1 -0
  80. package/dist/types/src/packlets/vault/worker-runtime.d.ts +2 -1
  81. package/dist/types/src/packlets/vault/worker-runtime.d.ts.map +1 -1
  82. package/dist/types/src/packlets/vault/worker-session.d.ts +7 -4
  83. package/dist/types/src/packlets/vault/worker-session.d.ts.map +1 -1
  84. package/package.json +30 -29
  85. package/src/packlets/deprecated/profile.ts +20 -2
  86. package/src/packlets/deprecated/space.ts +41 -37
  87. package/src/packlets/deprecated/system.ts +26 -13
  88. package/src/packlets/devtools/devtools.ts +4 -4
  89. package/src/packlets/devtools/feeds.ts +11 -6
  90. package/src/packlets/devtools/network.ts +20 -9
  91. package/src/packlets/devtools/spaces.ts +8 -7
  92. package/src/packlets/identity/authenticator.test.ts +4 -4
  93. package/src/packlets/identity/authenticator.ts +27 -17
  94. package/src/packlets/identity/identity-manager.test.ts +25 -16
  95. package/src/packlets/identity/identity-manager.ts +25 -13
  96. package/src/packlets/identity/identity.test.ts +22 -23
  97. package/src/packlets/identity/identity.ts +15 -10
  98. package/src/packlets/invitations/halo-invitations-handler.test.ts +4 -45
  99. package/src/packlets/invitations/halo-invitations-handler.ts +33 -17
  100. package/src/packlets/invitations/invitations.ts +2 -1
  101. package/src/packlets/invitations/space-invitations-handler.test.ts +43 -26
  102. package/src/packlets/invitations/space-invitations-handler.ts +9 -12
  103. package/src/packlets/services/service-context.test.ts +56 -0
  104. package/src/packlets/services/service-context.ts +62 -10
  105. package/src/packlets/services/service-definitions.ts +1 -1
  106. package/src/packlets/services/service-host.test.ts +74 -5
  107. package/src/packlets/services/service-host.ts +86 -24
  108. package/src/packlets/services/service-registry.test.ts +2 -1
  109. package/src/packlets/services/service-registry.ts +5 -1
  110. package/src/packlets/spaces/data-space-manager.test.ts +131 -0
  111. package/src/packlets/spaces/data-space-manager.ts +61 -15
  112. package/src/packlets/spaces/data-space.ts +125 -14
  113. package/src/packlets/spaces/notarization-plugin.test.ts +81 -0
  114. package/src/packlets/spaces/notarization-plugin.ts +211 -0
  115. package/src/packlets/spaces/spaces-service.ts +10 -2
  116. package/src/packlets/testing/credential-utils.ts +28 -0
  117. package/src/packlets/testing/index.ts +2 -0
  118. package/src/packlets/testing/invitation-utils.ts +44 -0
  119. package/src/packlets/testing/test-builder.ts +96 -14
  120. package/src/packlets/vault/iframe-host-runtime.ts +131 -0
  121. package/src/packlets/vault/{iframe-runtime.ts → iframe-proxy-runtime.ts} +18 -3
  122. package/src/packlets/vault/index.ts +6 -1
  123. package/src/packlets/vault/services.ts +17 -1
  124. package/src/packlets/vault/shell-controller.ts +77 -0
  125. package/src/packlets/vault/shell-runtime.ts +133 -0
  126. package/src/packlets/vault/vault-resource-lock.ts +76 -0
  127. package/src/packlets/vault/worker-runtime.ts +16 -4
  128. package/src/packlets/vault/worker-session.ts +36 -26
  129. package/dist/types/src/packlets/vault/iframe-runtime.d.ts.map +0 -1
@@ -1,3027 +1,59 @@
1
1
  import "@dxos/node-std/globals"
2
-
3
- // packages/sdk/client-services/src/packlets/deprecated/space.ts
4
- import assert from "@dxos/node-std/assert";
5
- import { EventSubscriptions } from "@dxos/async";
6
- import { Stream } from "@dxos/codec-protobuf";
7
- import { todo } from "@dxos/debug";
8
- import { log } from "@dxos/log";
9
- import { SpaceMember } from "@dxos/protocols/proto/dxos/client";
10
- import { humanize } from "@dxos/util";
11
- var SpaceServiceImpl = class {
12
- constructor(serviceContext) {
13
- this.serviceContext = serviceContext;
14
- this.inviteeInvitations = /* @__PURE__ */ new Map();
15
- }
16
- subscribeToSpace(request) {
17
- return new Stream(({ next }) => {
18
- next({
19
- space: {
20
- publicKey: request.spaceKey,
21
- isOpen: true,
22
- isActive: true,
23
- members: []
24
- }
25
- });
26
- });
27
- }
28
- subscribeSpaces() {
29
- return new Stream(({ next }) => {
30
- const subscriptions = new EventSubscriptions();
31
- const onUpdate = () => {
32
- const spaces = Array.from(this.serviceContext.dataSpaceManager.spaces.values()).map((space) => ({
33
- publicKey: space.key,
34
- isOpen: true,
35
- isActive: true,
36
- members: Array.from(space.inner.spaceState.members.values()).map((member) => {
37
- var _a, _b, _c;
38
- return {
39
- identityKey: member.key,
40
- profile: {
41
- identityKey: member.key,
42
- displayName: (_b = (_a = member.assertion.profile) == null ? void 0 : _a.displayName) != null ? _b : humanize(member.key)
43
- },
44
- presence: ((_c = this.serviceContext.identityManager.identity) == null ? void 0 : _c.identityKey.equals(member.key)) || space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0 ? SpaceMember.PresenceState.ONLINE : SpaceMember.PresenceState.OFFLINE
45
- };
46
- })
47
- }));
48
- log("update", {
49
- spaces
50
- }, {
51
- file: "space.ts",
52
- line: 120,
53
- scope: this,
54
- callSite: (f, a) => f(...a)
55
- });
56
- next({
57
- spaces
58
- });
59
- };
60
- setTimeout(async () => {
61
- if (!this.serviceContext.dataSpaceManager) {
62
- next({
63
- spaces: []
64
- });
65
- }
66
- await this.serviceContext.initialized.wait();
67
- subscriptions.add(this.serviceContext.dataSpaceManager.updated.on(() => {
68
- this.serviceContext.dataSpaceManager.spaces.forEach((space) => {
69
- subscriptions.add(space.stateUpdate.on(onUpdate));
70
- subscriptions.add(space.presence.updated.on(onUpdate));
71
- });
72
- onUpdate();
73
- }));
74
- this.serviceContext.dataSpaceManager.spaces.forEach((space) => {
75
- subscriptions.add(space.stateUpdate.on(onUpdate));
76
- subscriptions.add(space.presence.updated.on(onUpdate));
77
- });
78
- onUpdate();
79
- });
80
- return () => subscriptions.clear();
81
- });
82
- }
83
- async getSpaceDetails(request) {
84
- return todo();
85
- }
86
- async createSpace() {
87
- await this.serviceContext.initialized.wait();
88
- const space = await this.serviceContext.dataSpaceManager.createSpace();
89
- return {
90
- publicKey: space.key,
91
- isOpen: true,
92
- isActive: true
93
- };
94
- }
95
- async cloneSpace(snapshot) {
96
- return todo();
97
- }
98
- async setSpaceState(request) {
99
- return todo();
100
- }
101
- async authenticateInvitation(request) {
102
- var _a;
103
- assert(request.processId, "Process ID is missing.");
104
- const invitation = this.inviteeInvitations.get(request.processId);
105
- assert(invitation, "Invitation not found.");
106
- assert(request.secret, "Secret not provided.");
107
- invitation.secret = request.secret;
108
- (_a = invitation.secretTrigger) == null ? void 0 : _a.call(invitation);
109
- }
110
- subscribeMembers(request) {
111
- return todo();
112
- }
113
- async createSnapshot(request) {
114
- return todo();
115
- }
116
- };
117
-
118
- // packages/sdk/client-services/src/packlets/deprecated/profile.ts
119
- import { Stream as Stream2 } from "@dxos/codec-protobuf";
120
- import { todo as todo2 } from "@dxos/debug";
121
- var ProfileServiceImpl = class {
122
- constructor(context) {
123
- this.context = context;
124
- this.inviteeInvitations = /* @__PURE__ */ new Map();
125
- }
126
- subscribeProfile() {
127
- return new Stream2(({ next }) => {
128
- const emitNext = () => {
129
- var _a;
130
- return next({
131
- profile: this.context.identityManager.identity ? {
132
- identityKey: this.context.identityManager.identity.identityKey,
133
- deviceKey: this.context.identityManager.identity.deviceKey,
134
- displayName: (_a = this.context.identityManager.identity.profileDocument) == null ? void 0 : _a.displayName
135
- } : void 0
136
- });
137
- };
138
- emitNext();
139
- return this.context.identityManager.stateUpdate.on(emitNext);
140
- });
141
- }
142
- async createProfile(request) {
143
- var _a;
144
- await this.context.createIdentity({
145
- displayName: request.displayName
146
- });
147
- return {
148
- identityKey: this.context.identityManager.identity.identityKey,
149
- deviceKey: this.context.identityManager.identity.deviceKey,
150
- displayName: (_a = this.context.identityManager.identity.profileDocument) == null ? void 0 : _a.displayName
151
- };
152
- }
153
- async recoverProfile(request) {
154
- return todo2();
155
- if (!request.seedPhrase) {
156
- throw new Error("Recovery SeedPhrase not provided.");
157
- }
158
- }
159
- };
160
-
161
- // packages/sdk/client-services/src/packlets/deprecated/system.ts
162
- var SystemServiceImpl = class {
163
- constructor(_config, _serviceContext) {
164
- this._config = _config;
165
- this._serviceContext = _serviceContext;
166
- }
167
- // TODO(burdon): Remove.
168
- async initSession() {
169
- }
170
- async getConfig(request) {
171
- return this._config.values;
172
- }
173
- // TODO(burdon): Connect to iframe RPC heartbeat for network status?
174
- async getStatus(request) {
175
- return {
176
- message: `ok: ${Date.now()}`
177
- };
178
- }
179
- async reset(request) {
180
- await this._serviceContext.reset();
181
- }
182
- };
183
-
184
- // packages/sdk/client-services/src/packlets/deprecated/tracing.ts
185
- var TracingServiceImpl = class {
186
- constructor(_config) {
187
- this._config = _config;
188
- }
189
- async setTracingOptions() {
190
- throw new Error("Tracing not available.");
191
- }
192
- subscribeToRpcTrace() {
193
- throw new Error("Tracing not available.");
194
- }
195
- };
196
-
197
- // packages/sdk/client-services/src/packlets/devtools/devtools.ts
198
- import { Event as AsyncEvent } from "@dxos/async";
199
- import { Stream as Stream7 } from "@dxos/codec-protobuf";
200
-
201
- // packages/sdk/client-services/src/packlets/devtools/feeds.ts
202
- import { EventSubscriptions as EventSubscriptions2 } from "@dxos/async";
203
- import { Stream as Stream3 } from "@dxos/codec-protobuf";
204
- import { FeedIterator } from "@dxos/feed-store";
205
- import { PublicKey } from "@dxos/keys";
206
- import { ComplexMap } from "@dxos/util";
207
- var subscribeToFeeds = ({ feedStore }, { feedKeys }) => new Stream3(({ next }) => {
208
- if ((feedKeys == null ? void 0 : feedKeys.length) === 0) {
209
- return;
210
- }
211
- const feedMap = new ComplexMap(PublicKey.hash);
212
- const subscriptions = new EventSubscriptions2();
213
- const update = () => {
214
- const feeds = feedStore.feeds;
215
- feeds.filter((feed) => !(feedKeys == null ? void 0 : feedKeys.length) || feedKeys.some((feedKey) => feedKey.equals(feed.key))).forEach((feed) => {
216
- if (!feedMap.has(feed.key)) {
217
- feedMap.set(feed.key, feed);
218
- feed.on("close", update);
219
- subscriptions.add(feed.off("close", update));
220
- }
221
- });
222
- next({
223
- feeds: Array.from(feedMap.values()).map((feed) => ({
224
- feedKey: feed.key,
225
- length: feed.properties.length
226
- }))
227
- });
228
- };
229
- subscriptions.add(feedStore.feedOpened.on(update));
230
- update();
231
- return () => {
232
- subscriptions.clear();
233
- };
234
- });
235
- var subscribeToFeedBlocks = ({ feedStore }, { feedKey, maxBlocks = 10 }) => new Stream3(({ next }) => {
236
- if (!feedKey) {
237
- return;
238
- }
239
- const subscriptions = new EventSubscriptions2();
240
- const timeout = setTimeout(async () => {
241
- const feed = feedStore.getFeed(feedKey);
242
- if (!feed) {
243
- return;
244
- }
245
- const update = async () => {
246
- const iterator = new FeedIterator(feed);
247
- await iterator.open();
248
- const blocks = [];
249
- for await (const block of iterator) {
250
- blocks.push(block);
251
- if (blocks.length >= feed.properties.length) {
252
- break;
253
- }
254
- }
255
- next({
256
- blocks: blocks.slice(-maxBlocks)
257
- });
258
- await iterator.close();
259
- };
260
- feed.on("append", update);
261
- subscriptions.add(() => feed.off("append", update));
262
- feed.on("truncate", update);
263
- subscriptions.add(() => feed.off("truncate", update));
264
- await update();
265
- });
266
- return () => {
267
- subscriptions.clear();
268
- clearTimeout(timeout);
269
- };
270
- });
271
-
272
- // packages/sdk/client-services/src/packlets/devtools/keys.ts
273
- import { Stream as Stream4 } from "@dxos/codec-protobuf";
274
- var subscribeToKeyringKeys = ({ keyring }) => new Stream4(({ next }) => {
275
- const update = () => {
276
- next({
277
- keys: keyring.list()
278
- });
279
- };
280
- const unsubscribe = keyring.keysUpdate.on(update);
281
- update();
282
- return unsubscribe;
283
- });
284
-
285
- // packages/sdk/client-services/src/packlets/devtools/network.ts
286
- import { Stream as Stream5 } from "@dxos/codec-protobuf";
287
- import { PublicKey as PublicKey2 } from "@dxos/keys";
288
- var subscribeToNetworkStatus = ({ networkManager }) => new Stream5(({ next, close }) => {
289
- const update = () => {
290
- try {
291
- const status = networkManager.signalManager.getStatus();
292
- next({
293
- servers: status
294
- });
295
- } catch (err) {
296
- close(err);
297
- }
298
- };
299
- networkManager.signalManager.statusChanged.on(update);
300
- update();
301
- });
302
- var subscribeToSignalTrace = ({ networkManager }) => new Stream5(({ next }) => {
303
- next({
304
- events: []
305
- });
306
- const trace = [];
307
- networkManager.signalManager.commandTrace.on((msg) => {
308
- trace.push(msg);
309
- next({
310
- events: trace.map((msg2) => JSON.stringify(msg2))
311
- });
312
- });
313
- });
314
- var subscribeToNetworkTopics = ({ networkManager }) => new Stream5(({ next, close }) => {
315
- const update = () => {
316
- try {
317
- const topics = networkManager.topics;
318
- const labeledTopics = topics.map((topic) => {
319
- var _a, _b;
320
- return {
321
- topic,
322
- label: (_b = (_a = networkManager.getSwarm(topic)) == null ? void 0 : _a.label) != null ? _b : topic.toHex()
323
- };
324
- });
325
- next({
326
- topics: labeledTopics
327
- });
328
- } catch (err) {
329
- close(err);
330
- }
331
- };
332
- networkManager.topicsUpdated.on(update);
333
- update();
334
- });
335
- var subscribeToSwarmInfo = ({ networkManager }) => new Stream5(({ next }) => {
336
- var _a;
337
- const update = () => {
338
- var _a2;
339
- const info = (_a2 = networkManager.connectionLog) == null ? void 0 : _a2.swarms;
340
- if (info) {
341
- next({
342
- data: info
343
- });
344
- }
345
- };
346
- (_a = networkManager.connectionLog) == null ? void 0 : _a.update.on(update);
347
- update();
348
- });
349
- var getNetworkPeers = ({ networkManager }, request) => {
350
- if (!request.topic) {
351
- throw new Error("Expected a network topic");
352
- }
353
- const map = networkManager.getSwarmMap(PublicKey2.from(request.topic));
354
- return {
355
- peers: map == null ? void 0 : map.peers.map((peer) => ({
356
- ...peer,
357
- connections: peer.connections.map((connection) => connection.asUint8Array())
358
- }))
359
- };
360
- };
361
-
362
- // packages/sdk/client-services/src/packlets/devtools/spaces.ts
363
- import { Stream as Stream6 } from "@dxos/codec-protobuf";
364
- var subscribeToSpaces = (context, { spaceKeys = [] }) => new Stream6(({ next }) => {
365
- let unsubscribe;
366
- const update = async () => {
367
- const spaces = [
368
- ...context.spaceManager.spaces.values()
369
- ];
370
- const filteredSpaces = spaces.filter((space) => !(spaceKeys == null ? void 0 : spaceKeys.length) || spaceKeys.some((spaceKey) => spaceKey.equals(space.key)));
371
- next({
372
- spaces: filteredSpaces.map((space) => {
373
- const spaceMetadata = context.metadataStore.spaces.find((spaceMetadata2) => spaceMetadata2.key.equals(space.key));
374
- return {
375
- key: space.key,
376
- isOpen: space.isOpen,
377
- timeframe: spaceMetadata == null ? void 0 : spaceMetadata.latestTimeframe,
378
- genesisFeed: space.genesisFeedKey,
379
- controlFeed: space.controlFeedKey,
380
- dataFeed: space.dataFeedKey
381
- };
382
- })
383
- });
384
- };
385
- const timeout = setTimeout(async () => {
386
- await context.initialized.wait();
387
- unsubscribe = context.dataSpaceManager.updated.on(() => update());
388
- await update();
389
- });
390
- return () => {
391
- unsubscribe == null ? void 0 : unsubscribe();
392
- clearTimeout(timeout);
393
- };
394
- });
395
-
396
- // packages/sdk/client-services/src/packlets/devtools/devtools.ts
397
- var DevtoolsHostEvents = class {
398
- constructor() {
399
- this.ready = new AsyncEvent();
400
- }
401
- };
402
- var DevtoolsServiceImpl = class {
403
- constructor(params) {
404
- this.params = params;
405
- }
406
- events(request) {
407
- return new Stream7(({ next }) => {
408
- this.params.events.ready.on(() => {
409
- next({
410
- ready: {}
411
- });
412
- });
413
- });
414
- }
415
- getConfig(request) {
416
- throw new Error();
417
- }
418
- resetStorage(request) {
419
- throw new Error();
420
- }
421
- enableDebugLogging(request) {
422
- throw new Error();
423
- }
424
- disableDebugLogging(request) {
425
- throw new Error();
426
- }
427
- subscribeToKeyringKeys(request) {
428
- return subscribeToKeyringKeys({
429
- keyring: this.params.context.keyring
430
- });
431
- }
432
- subscribeToCredentialMessages(request) {
433
- throw new Error();
434
- }
435
- subscribeToSpaces(request) {
436
- return subscribeToSpaces(this.params.context, request);
437
- }
438
- subscribeToItems(request) {
439
- throw new Error();
440
- }
441
- subscribeToFeeds(request) {
442
- return subscribeToFeeds({
443
- feedStore: this.params.context.feedStore
444
- }, request);
445
- }
446
- subscribeToFeedBlocks(request) {
447
- return subscribeToFeedBlocks({
448
- feedStore: this.params.context.feedStore
449
- }, request);
450
- }
451
- getSpaceSnapshot(request) {
452
- throw new Error();
453
- }
454
- saveSpaceSnapshot(request) {
455
- throw new Error();
456
- }
457
- clearSnapshots(request) {
458
- throw new Error();
459
- }
460
- getNetworkPeers(request) {
461
- throw new Error();
462
- }
463
- subscribeToNetworkTopics(request) {
464
- throw new Error();
465
- }
466
- subscribeToSignalStatus(request) {
467
- return subscribeToNetworkStatus({
468
- networkManager: this.params.context.networkManager
469
- });
470
- }
471
- subscribeToSignalTrace() {
472
- return subscribeToSignalTrace({
473
- networkManager: this.params.context.networkManager
474
- });
475
- }
476
- subscribeToSwarmInfo() {
477
- return subscribeToSwarmInfo({
478
- networkManager: this.params.context.networkManager
479
- });
480
- }
481
- };
482
-
483
- // packages/sdk/client-services/src/packlets/identity/authenticator.ts
484
- import { Trigger } from "@dxos/async";
485
- import { Context } from "@dxos/context";
486
- import { verifyCredential } from "@dxos/credentials";
487
- import { log as log2 } from "@dxos/log";
488
- import { schema } from "@dxos/protocols";
489
- var createHaloAuthProvider = (signer) => async (nonce) => {
490
- const credential = await signer.createCredential({
491
- assertion: {
492
- "@type": "dxos.halo.credentials.Auth"
493
- },
494
- subject: signer.getIssuer(),
495
- nonce
496
- });
497
- return schema.getCodecForType("dxos.halo.credentials.Credential").encode(credential);
498
- };
499
- var HaloAuthVerifier = class {
500
- constructor(_params) {
501
- this._params = _params;
502
- this._ctx = new Context();
503
- }
504
- async close() {
505
- await this._ctx.dispose();
506
- }
507
- _isTrustedDevice(deviceKey) {
508
- const deviceSet = this._params.trustedDevicesProvider();
509
- return deviceSet.has(deviceKey);
510
- }
511
- get verifier() {
512
- return async (nonce, auth) => {
513
- const credential = schema.getCodecForType("dxos.halo.credentials.Credential").decode(auth);
514
- const result = await verifyCredential(credential);
515
- if (result.kind === "fail") {
516
- log2("Invalid credential", {
517
- result
518
- }, {
519
- file: "authenticator.ts",
520
- line: 61,
521
- scope: this,
522
- callSite: (f, a) => f(...a)
523
- });
524
- return false;
525
- }
526
- if (!credential.proof.nonce || !Buffer.from(nonce).equals(credential.proof.nonce)) {
527
- log2("Invalid nonce", {
528
- nonce,
529
- credential
530
- }, {
531
- file: "authenticator.ts",
532
- line: 66,
533
- scope: this,
534
- callSite: (f, a) => f(...a)
535
- });
536
- return false;
537
- }
538
- if (this._isTrustedDevice(credential.issuer)) {
539
- return true;
540
- }
541
- const trigger = new Trigger();
542
- this._ctx.onDispose(() => {
543
- trigger.wake(false);
544
- });
545
- const clear = this._params.update.on(this._ctx, () => {
546
- if (this._isTrustedDevice(credential.issuer)) {
547
- trigger.wake(true);
548
- }
549
- });
550
- try {
551
- await trigger.wait({
552
- timeout: this._params.authTimeout
553
- });
554
- return true;
555
- } catch (e) {
556
- return false;
557
- } finally {
558
- clear();
559
- }
560
- };
561
- }
562
- };
563
-
564
- // packages/sdk/client-services/src/packlets/identity/identity.ts
565
- import assert2 from "@dxos/node-std/assert";
566
- import { Event } from "@dxos/async";
567
- import { DeviceStateMachine, createCredentialSignerWithKey, createCredentialSignerWithChain, ProfileStateMachine } from "@dxos/credentials";
568
- import { writeMessages } from "@dxos/feed-store";
569
- import { log as log3 } from "@dxos/log";
570
- import { AdmittedFeed } from "@dxos/protocols/proto/dxos/halo/credentials";
571
- var AUTH_TIMEOUT = 3e4;
572
- var Identity = class {
573
- constructor({ space, signer, identityKey, deviceKey }) {
574
- this.stateUpdate = new Event();
575
- this.space = space;
576
- this._signer = signer;
577
- this.identityKey = identityKey;
578
- this.deviceKey = deviceKey;
579
- this._deviceStateMachine = this.space.spaceState.registerProcessor(new DeviceStateMachine({
580
- identityKey: this.identityKey,
581
- deviceKey: this.deviceKey,
582
- onUpdate: () => this.stateUpdate.emit()
583
- }));
584
- this._profileStateMachine = this.space.spaceState.registerProcessor(new ProfileStateMachine({
585
- identityKey: this.identityKey,
586
- onUpdate: () => this.stateUpdate.emit()
587
- }));
588
- this.authVerifier = new HaloAuthVerifier({
589
- trustedDevicesProvider: () => this.authorizedDeviceKeys,
590
- update: this.stateUpdate,
591
- authTimeout: AUTH_TIMEOUT
592
- });
593
- }
594
- // TODO(burdon): Expose state object?
595
- get authorizedDeviceKeys() {
596
- return this._deviceStateMachine.processor.authorizedDeviceKeys;
597
- }
598
- async open() {
599
- await this._deviceStateMachine.open();
600
- await this._profileStateMachine.open();
601
- await this.space.open();
602
- }
603
- async close() {
604
- await this.authVerifier.close();
605
- await this._deviceStateMachine.close();
606
- await this._profileStateMachine.close();
607
- await this.space.close();
608
- }
609
- async ready() {
610
- await this._deviceStateMachine.processor.deviceChainReady.wait();
611
- }
612
- get profileDocument() {
613
- return this._profileStateMachine.processor.profile;
614
- }
615
- /**
616
- * @test-only
617
- */
618
- get controlPipeline() {
619
- return this.space.controlPipeline;
620
- }
621
- get haloSpaceKey() {
622
- return this.space.key;
623
- }
624
- get haloGenesisFeedKey() {
625
- return this.space.genesisFeedKey;
626
- }
627
- getAdmissionCredentials() {
628
- return {
629
- deviceKey: this.deviceKey,
630
- controlFeedKey: this.space.controlFeedKey,
631
- dataFeedKey: this.space.dataFeedKey
632
- };
633
- }
634
- /**
635
- * Issues credentials as identity.
636
- * Requires identity to be ready.
637
- */
638
- getIdentityCredentialSigner() {
639
- assert2(this._deviceStateMachine.processor.deviceCredentialChain, "Device credential chain is not ready.");
640
- return createCredentialSignerWithChain(this._signer, this._deviceStateMachine.processor.deviceCredentialChain, this.deviceKey);
641
- }
642
- /**
643
- * Issues credentials as device.
644
- */
645
- getDeviceCredentialSigner() {
646
- return createCredentialSignerWithKey(this._signer, this.deviceKey);
647
- }
648
- async admitDevice({ deviceKey, controlFeedKey, dataFeedKey }) {
649
- log3("Admitting device:", {
650
- identityKey: this.identityKey,
651
- hostDevice: this.deviceKey,
652
- deviceKey,
653
- controlFeedKey,
654
- dataFeedKey
655
- }, {
656
- file: "identity.ts",
657
- line: 155,
658
- scope: this,
659
- callSite: (f, a) => f(...a)
660
- });
661
- const signer = this.getIdentityCredentialSigner();
662
- await writeMessages(this.controlPipeline.writer, [
663
- await signer.createCredential({
664
- subject: deviceKey,
665
- assertion: {
666
- "@type": "dxos.halo.credentials.AuthorizedDevice",
667
- identityKey: this.identityKey,
668
- deviceKey
669
- }
670
- }),
671
- await signer.createCredential({
672
- subject: controlFeedKey,
673
- assertion: {
674
- "@type": "dxos.halo.credentials.AdmittedFeed",
675
- spaceKey: this.haloSpaceKey,
676
- deviceKey,
677
- identityKey: this.identityKey,
678
- designation: AdmittedFeed.Designation.CONTROL
679
- }
680
- }),
681
- await signer.createCredential({
682
- subject: dataFeedKey,
683
- assertion: {
684
- "@type": "dxos.halo.credentials.AdmittedFeed",
685
- spaceKey: this.haloSpaceKey,
686
- deviceKey,
687
- identityKey: this.identityKey,
688
- designation: AdmittedFeed.Designation.DATA
689
- }
690
- })
691
- ].map((credential) => ({
692
- "@type": "dxos.echo.feed.CredentialsMessage",
693
- credential
694
- })));
695
- }
696
- };
697
-
698
- // packages/sdk/client-services/src/packlets/identity/identity-manager.ts
699
- import assert3 from "@dxos/node-std/assert";
700
- import { Event as Event2 } from "@dxos/async";
701
- import { createCredentialSignerWithKey as createCredentialSignerWithKey2, CredentialGenerator } from "@dxos/credentials";
702
- import { log as log4 } from "@dxos/log";
703
- import { AdmittedFeed as AdmittedFeed2 } from "@dxos/protocols/proto/dxos/halo/credentials";
704
- import { deferFunction } from "@dxos/util";
705
- var IdentityManager = class {
706
- // TODO(burdon): IdentityManagerParams.
707
- // TODO(dmaretskyi): Perhaps this should take/generate the peerKey outside of an initialized identity.
708
- constructor(_metadataStore, _keyring, _spaceManager) {
709
- this._metadataStore = _metadataStore;
710
- this._keyring = _keyring;
711
- this._spaceManager = _spaceManager;
712
- this.stateUpdate = new Event2();
713
- }
714
- get identity() {
715
- return this._identity;
716
- }
717
- async open() {
718
- await this._metadataStore.load();
719
- const identityRecord = this._metadataStore.getIdentityRecord();
720
- log4("identity record", {
721
- identityRecord
722
- }, {
723
- file: "identity-manager.ts",
724
- line: 57,
725
- scope: this,
726
- callSite: (f, a) => f(...a)
727
- });
728
- if (identityRecord) {
729
- this._identity = await this._constructIdentity(identityRecord);
730
- await this._identity.open();
731
- await this._identity.ready();
732
- this.stateUpdate.emit();
733
- }
734
- }
735
- async close() {
736
- var _a;
737
- await ((_a = this._identity) == null ? void 0 : _a.close());
738
- }
739
- async createIdentity({ displayName } = {}) {
740
- assert3(!this._identity, "Identity already exists.");
741
- log4("creating identity...", {}, {
742
- file: "identity-manager.ts",
743
- line: 72,
744
- scope: this,
745
- callSite: (f, a) => f(...a)
746
- });
747
- const controlFeedKey = await this._keyring.createKey();
748
- const identityRecord = {
749
- identityKey: await this._keyring.createKey(),
750
- deviceKey: await this._keyring.createKey(),
751
- haloSpace: {
752
- spaceKey: await this._keyring.createKey(),
753
- genesisFeedKey: controlFeedKey,
754
- writeControlFeedKey: controlFeedKey,
755
- writeDataFeedKey: await this._keyring.createKey()
756
- }
757
- };
758
- const identity = await this._constructIdentity(identityRecord);
759
- await identity.open();
760
- {
761
- const generator = new CredentialGenerator(this._keyring, identityRecord.identityKey, identityRecord.deviceKey);
762
- const credentials = [
763
- // Space genesis.
764
- ...await generator.createSpaceGenesis(identityRecord.haloSpace.spaceKey, identityRecord.haloSpace.genesisFeedKey),
765
- // Feed admission.
766
- await generator.createFeedAdmission(identityRecord.haloSpace.spaceKey, identityRecord.haloSpace.writeDataFeedKey, AdmittedFeed2.Designation.DATA)
767
- ];
768
- if (displayName) {
769
- credentials.push(await generator.createProfileCredential({
770
- displayName
771
- }));
772
- }
773
- credentials.push(await generator.createDeviceAuthorization(identityRecord.deviceKey));
774
- for (const credential of credentials) {
775
- await identity.controlPipeline.writer.write({
776
- "@type": "dxos.echo.feed.CredentialsMessage",
777
- credential
778
- });
779
- }
780
- }
781
- await this._metadataStore.setIdentityRecord(identityRecord);
782
- this._identity = identity;
783
- await this._identity.ready();
784
- this.stateUpdate.emit();
785
- log4("created identity", {
786
- identityKey: identity.identityKey,
787
- deviceKey: identity.deviceKey
788
- }, {
789
- file: "identity-manager.ts",
790
- line: 131,
791
- scope: this,
792
- callSite: (f, a) => f(...a)
793
- });
794
- return identity;
795
- }
796
- /**
797
- * Accept an existing identity. Expects it's device key to be authorized (now or later).
798
- */
799
- async acceptIdentity(params) {
800
- log4("accepting identity", {
801
- params
802
- }, {
803
- file: "identity-manager.ts",
804
- line: 139,
805
- scope: this,
806
- callSite: (f, a) => f(...a)
807
- });
808
- assert3(!this._identity, "Identity already exists.");
809
- const identityRecord = {
810
- identityKey: params.identityKey,
811
- deviceKey: await this._keyring.createKey(),
812
- haloSpace: {
813
- spaceKey: params.haloSpaceKey,
814
- genesisFeedKey: params.haloGenesisFeedKey,
815
- writeControlFeedKey: await this._keyring.createKey(),
816
- writeDataFeedKey: await this._keyring.createKey()
817
- }
818
- };
819
- const identity = await this._constructIdentity(identityRecord);
820
- await identity.open();
821
- this._identity = identity;
822
- await this._metadataStore.setIdentityRecord(identityRecord);
823
- this.stateUpdate.emit();
824
- return identity;
825
- }
826
- async _constructIdentity(identityRecord) {
827
- assert3(!this._identity);
828
- log4("constructing identity", {
829
- identityRecord
830
- }, {
831
- file: "identity-manager.ts",
832
- line: 163,
833
- scope: this,
834
- callSite: (f, a) => f(...a)
835
- });
836
- const space = await this._constructSpace({
837
- spaceRecord: identityRecord.haloSpace,
838
- swarmIdentity: {
839
- peerKey: identityRecord.deviceKey,
840
- credentialProvider: createHaloAuthProvider(createCredentialSignerWithKey2(this._keyring, identityRecord.deviceKey)),
841
- credentialAuthenticator: deferFunction(() => identity.authVerifier.verifier)
842
- },
843
- identityKey: identityRecord.identityKey
844
- });
845
- const identity = new Identity({
846
- space,
847
- signer: this._keyring,
848
- identityKey: identityRecord.identityKey,
849
- deviceKey: identityRecord.deviceKey
850
- });
851
- log4("done", {
852
- identityKey: identityRecord.identityKey
853
- }, {
854
- file: "identity-manager.ts",
855
- line: 182,
856
- scope: this,
857
- callSite: (f, a) => f(...a)
858
- });
859
- return identity;
860
- }
861
- async _constructSpace({ spaceRecord, swarmIdentity, identityKey }) {
862
- return this._spaceManager.constructSpace({
863
- metadata: {
864
- key: spaceRecord.spaceKey,
865
- genesisFeedKey: spaceRecord.genesisFeedKey,
866
- controlFeedKey: spaceRecord.writeControlFeedKey,
867
- dataFeedKey: spaceRecord.writeDataFeedKey
868
- },
869
- swarmIdentity,
870
- onNetworkConnection: () => {
871
- }
872
- });
873
- }
874
- };
875
-
876
- // packages/sdk/client-services/src/packlets/invitations/encoder.ts
877
- import base from "base-x";
878
- import { schema as schema2 } from "@dxos/protocols";
879
- var base62 = base("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
880
- var codec = schema2.getCodecForType("dxos.client.services.Invitation");
881
- var InvitationEncoder = class {
882
- static decode(text) {
883
- return codec.decode(base62.decode(text));
884
- }
885
- static encode(invitation) {
886
- return base62.encode(codec.encode(invitation));
887
- }
888
- };
889
-
890
- // packages/sdk/client-services/src/packlets/invitations/halo-invitations-handler.ts
891
- import assert5 from "@dxos/node-std/assert";
892
- import { scheduleTask, sleep, Trigger as Trigger2 } from "@dxos/async";
893
- import { Context as Context2 } from "@dxos/context";
894
- import { generatePasscode } from "@dxos/credentials";
895
- import { failUndefined } from "@dxos/debug";
896
- import { PublicKey as PublicKey3 } from "@dxos/keys";
897
- import { log as log5 } from "@dxos/log";
898
- import { createTeleportProtocolFactory, StarTopology } from "@dxos/network-manager";
899
- import { schema as schema3 } from "@dxos/protocols";
900
- import { Invitation as Invitation2 } from "@dxos/protocols/proto/dxos/client/services";
901
- import { AuthenticationResponse } from "@dxos/protocols/proto/dxos/halo/invitations";
902
- import { RpcExtension } from "@dxos/teleport";
903
-
904
- // packages/sdk/client-services/src/packlets/invitations/invitations.ts
905
- import assert4 from "@dxos/node-std/assert";
906
- import { CancellableObservableProvider } from "@dxos/async";
907
- import { Invitation } from "@dxos/protocols/proto/dxos/client/services";
908
- var AUTHENTICATION_CODE_LENGTH = 6;
909
- var INVITATION_TIMEOUT = 3 * 6e4;
910
- var ON_CLOSE_DELAY = 500;
911
- var InvitationObservableProvider = class extends CancellableObservableProvider {
912
- get invitation() {
913
- return this._invitation;
914
- }
915
- setInvitation(invitation) {
916
- this._invitation = invitation;
917
- }
918
- };
919
- var AuthenticatingInvitationProvider = class extends InvitationObservableProvider {
920
- // prettier-ignore
921
- constructor(_actions) {
922
- super(() => this._actions.onCancel());
923
- this._actions = _actions;
924
- }
925
- async authenticate(authenticationCode) {
926
- return this._actions.onAuthenticate(authenticationCode);
927
- }
928
- };
929
- var wrapObservable = async (observable) => {
930
- return new Promise((resolve, reject) => {
931
- const unsubscribe = observable.subscribe({
932
- onSuccess: (invitation) => {
933
- assert4(invitation.state === Invitation.State.SUCCESS);
934
- unsubscribe();
935
- resolve(invitation);
936
- },
937
- onError: (err) => {
938
- unsubscribe();
939
- reject(err);
940
- }
941
- });
942
- });
943
- };
944
-
945
- // packages/sdk/client-services/src/packlets/invitations/invitations-handler.ts
946
- var AbstractInvitationsHandler = class {
947
- // prettier-ignore
948
- constructor(_networkManager) {
949
- this._networkManager = _networkManager;
950
- }
951
- };
952
-
953
- // packages/sdk/client-services/src/packlets/invitations/halo-invitations-handler.ts
954
- var HaloInvitationsHandler = class extends AbstractInvitationsHandler {
955
- // prettier-ignore
956
- constructor(networkManager, _identityManager) {
957
- super(networkManager);
958
- this._identityManager = _identityManager;
959
- }
960
- /**
961
- * Creates an invitation and listens for a join request from the invited (guest) peer.
962
- */
963
- createInvitation(context, options) {
964
- var _a;
965
- const { type, timeout = INVITATION_TIMEOUT, swarmKey } = options != null ? options : {};
966
- assert5(type !== Invitation2.Type.OFFLINE);
967
- const identity = (_a = this._identityManager.identity) != null ? _a : failUndefined();
968
- const invitation = {
969
- type,
970
- invitationId: PublicKey3.random().toHex(),
971
- swarmKey: swarmKey != null ? swarmKey : PublicKey3.random(),
972
- authenticationCode: generatePasscode(AUTHENTICATION_CODE_LENGTH)
973
- };
974
- const ctx = new Context2({
975
- onError: (err) => {
976
- void ctx.dispose();
977
- observable.callback.onError(err);
978
- }
979
- });
980
- const observable = new InvitationObservableProvider(async () => {
981
- await ctx.dispose();
982
- });
983
- let authenticationCode;
984
- const complete = new Trigger2();
985
- const createExtension = () => {
986
- const hostInvitationExtension = new HostHaloInvitationExtension({
987
- requestAdmission: async () => {
988
- var _a2, _b;
989
- log5("responding with admission offer", {
990
- host: identity.deviceKey
991
- }, {
992
- file: "halo-invitations-handler.ts",
993
- line: 84,
994
- scope: this,
995
- callSite: (f, a) => f(...a)
996
- });
997
- (_b = (_a2 = observable.callback).onAuthenticating) == null ? void 0 : _b.call(_a2, invitation);
998
- return {
999
- identityKey: identity.identityKey,
1000
- haloSpaceKey: identity.haloSpaceKey,
1001
- genesisFeedKey: identity.haloGenesisFeedKey
1002
- };
1003
- },
1004
- authenticate: async ({ authenticationCode: code }) => {
1005
- log5("received authentication request", {
1006
- authenticationCode: code
1007
- }, {
1008
- file: "halo-invitations-handler.ts",
1009
- line: 98,
1010
- scope: this,
1011
- callSite: (f, a) => f(...a)
1012
- });
1013
- authenticationCode = code;
1014
- return {
1015
- status: AuthenticationResponse.Status.OK
1016
- };
1017
- },
1018
- // TODO(burdon): Not used: controlFeedKey, dataFeedKey.
1019
- presentAdmissionCredentials: async (credentials) => {
1020
- try {
1021
- if (invitation.type !== Invitation2.Type.INTERACTIVE_TESTING) {
1022
- if (invitation.authenticationCode === void 0 || invitation.authenticationCode !== authenticationCode) {
1023
- throw new Error(`invalid authentication code: ${authenticationCode}`);
1024
- }
1025
- }
1026
- log5("writing guest credentials", {
1027
- host: identity.deviceKey,
1028
- guest: credentials.deviceKey
1029
- }, {
1030
- file: "halo-invitations-handler.ts",
1031
- line: 113,
1032
- scope: this,
1033
- callSite: (f, a) => f(...a)
1034
- });
1035
- await identity.admitDevice(credentials);
1036
- complete.wake(credentials.deviceKey);
1037
- } catch (err) {
1038
- observable.callback.onError(err);
1039
- throw err;
1040
- }
1041
- },
1042
- onOpen: () => {
1043
- scheduleTask(ctx, async () => {
1044
- var _a2, _b;
1045
- try {
1046
- log5("connected", {
1047
- host: identity.deviceKey
1048
- }, {
1049
- file: "halo-invitations-handler.ts",
1050
- line: 129,
1051
- scope: this,
1052
- callSite: (f, a) => f(...a)
1053
- });
1054
- (_b = (_a2 = observable.callback).onConnected) == null ? void 0 : _b.call(_a2, invitation);
1055
- const deviceKey = await complete.wait({
1056
- timeout
1057
- });
1058
- log5("admitted guest", {
1059
- host: identity.deviceKey,
1060
- guest: deviceKey
1061
- }, {
1062
- file: "halo-invitations-handler.ts",
1063
- line: 132,
1064
- scope: this,
1065
- callSite: (f, a) => f(...a)
1066
- });
1067
- observable.callback.onSuccess(invitation);
1068
- } catch (err) {
1069
- if (!observable.cancelled) {
1070
- log5.error("failed", err, {
1071
- file: "halo-invitations-handler.ts",
1072
- line: 136,
1073
- scope: this,
1074
- callSite: (f, a) => f(...a)
1075
- });
1076
- observable.callback.onError(err);
1077
- }
1078
- } finally {
1079
- await sleep(ON_CLOSE_DELAY);
1080
- await ctx.dispose();
1081
- }
1082
- });
1083
- }
1084
- });
1085
- return hostInvitationExtension;
1086
- };
1087
- scheduleTask(ctx, async () => {
1088
- var _a2, _b;
1089
- const topic = invitation.swarmKey;
1090
- const swarmConnection = await this._networkManager.joinSwarm({
1091
- topic,
1092
- peerId: topic,
1093
- protocolProvider: createTeleportProtocolFactory(async (teleport) => {
1094
- teleport.addExtension("dxos.halo.invitations", createExtension());
1095
- }),
1096
- topology: new StarTopology(topic)
1097
- });
1098
- ctx.onDispose(() => swarmConnection.close());
1099
- (_b = (_a2 = observable.callback).onConnecting) == null ? void 0 : _b.call(_a2, invitation);
1100
- });
1101
- return observable;
1102
- }
1103
- /**
1104
- * Waits for the host peer (inviter) to accept our join request.
1105
- * The local guest peer (invitee) then sends the local halo invitation to the host,
1106
- * which then writes the guest's credentials to the halo.
1107
- */
1108
- acceptInvitation(invitation, options) {
1109
- const { timeout = INVITATION_TIMEOUT } = options != null ? options : {};
1110
- const ctx = new Context2({
1111
- onError: (err) => {
1112
- void ctx.dispose();
1113
- observable.callback.onError(err);
1114
- }
1115
- });
1116
- const authenticated = new Trigger2();
1117
- const observable = new AuthenticatingInvitationProvider({
1118
- onCancel: async () => {
1119
- await ctx.dispose();
1120
- },
1121
- // TODO(burdon): Consider retry.
1122
- onAuthenticate: async (code) => {
1123
- authenticated.wake(code);
1124
- }
1125
- });
1126
- let connectionCount = 0;
1127
- const complete = new Trigger2();
1128
- const createExtension = () => {
1129
- const extension = new GuestHaloInvitationExtension({
1130
- onOpen: () => {
1131
- scheduleTask(ctx, async () => {
1132
- var _a, _b, _c, _d;
1133
- try {
1134
- if (++connectionCount > 1) {
1135
- throw new Error(`multiple connections detected: ${connectionCount}`);
1136
- }
1137
- log5("connected", {}, {
1138
- file: "halo-invitations-handler.ts",
1139
- line: 209,
1140
- scope: this,
1141
- callSite: (f, a) => f(...a)
1142
- });
1143
- (_b = (_a = observable.callback).onConnected) == null ? void 0 : _b.call(_a, invitation);
1144
- log5("sending admission request", {}, {
1145
- file: "halo-invitations-handler.ts",
1146
- line: 213,
1147
- scope: this,
1148
- callSite: (f, a) => f(...a)
1149
- });
1150
- const { identityKey, haloSpaceKey, genesisFeedKey } = await extension.rpc.HaloHostService.requestAdmission();
1151
- if (invitation.type === void 0 || invitation.type === Invitation2.Type.INTERACTIVE) {
1152
- log5("guest waiting for authentication code...", {}, {
1153
- file: "halo-invitations-handler.ts",
1154
- line: 220,
1155
- scope: this,
1156
- callSite: (f, a) => f(...a)
1157
- });
1158
- (_d = (_c = observable.callback).onAuthenticating) == null ? void 0 : _d.call(_c, invitation);
1159
- const authenticationCode = await authenticated.wait({
1160
- timeout
1161
- });
1162
- log5("sending authentication request", {}, {
1163
- file: "halo-invitations-handler.ts",
1164
- line: 223,
1165
- scope: this,
1166
- callSite: (f, a) => f(...a)
1167
- });
1168
- await extension.rpc.HaloHostService.authenticate({
1169
- authenticationCode
1170
- });
1171
- }
1172
- const identity = await this._identityManager.acceptIdentity({
1173
- identityKey,
1174
- haloSpaceKey,
1175
- haloGenesisFeedKey: genesisFeedKey
1176
- });
1177
- log5("presenting admission credentials", {
1178
- guest: identity.deviceKey,
1179
- identityKey
1180
- }, {
1181
- file: "halo-invitations-handler.ts",
1182
- line: 236,
1183
- scope: this,
1184
- callSite: (f, a) => f(...a)
1185
- });
1186
- await extension.rpc.HaloHostService.presentAdmissionCredentials(identity.getAdmissionCredentials());
1187
- log5("admitted by host", {
1188
- guest: identity.deviceKey,
1189
- identityKey
1190
- }, {
1191
- file: "halo-invitations-handler.ts",
1192
- line: 240,
1193
- scope: this,
1194
- callSite: (f, a) => f(...a)
1195
- });
1196
- complete.wake(identityKey);
1197
- } catch (err) {
1198
- if (!observable.cancelled) {
1199
- log5.warn("auth failed", err, {
1200
- file: "halo-invitations-handler.ts",
1201
- line: 244,
1202
- scope: this,
1203
- callSite: (f, a) => f(...a)
1204
- });
1205
- observable.callback.onError(err);
1206
- }
1207
- } finally {
1208
- await ctx.dispose();
1209
- }
1210
- });
1211
- }
1212
- });
1213
- return extension;
1214
- };
1215
- scheduleTask(ctx, async () => {
1216
- var _a, _b;
1217
- assert5(invitation.swarmKey);
1218
- const topic = invitation.swarmKey;
1219
- const swarmConnection = await this._networkManager.joinSwarm({
1220
- topic,
1221
- peerId: PublicKey3.random(),
1222
- protocolProvider: createTeleportProtocolFactory(async (teleport) => {
1223
- teleport.addExtension("dxos.halo.invitations", createExtension());
1224
- }),
1225
- topology: new StarTopology(topic)
1226
- });
1227
- ctx.onDispose(() => swarmConnection.close());
1228
- (_b = (_a = observable.callback).onConnecting) == null ? void 0 : _b.call(_a, invitation);
1229
- invitation.identityKey = await complete.wait();
1230
- observable.callback.onSuccess(invitation);
1231
- await ctx.dispose();
1232
- });
1233
- return observable;
1234
- }
1235
- };
1236
- var HostHaloInvitationExtension = class extends RpcExtension {
1237
- constructor(_callbacks) {
1238
- super({
1239
- exposed: {
1240
- HaloHostService: schema3.getService("dxos.halo.invitations.HaloHostService")
1241
- }
1242
- });
1243
- this._callbacks = _callbacks;
1244
- }
1245
- async getHandlers() {
1246
- return {
1247
- // TODO(dmaretskyi): For now this is just forwarding the data to callbacks since we don't have session-specific logic.
1248
- // Perhaps in the future we will have more complex logic here.
1249
- HaloHostService: {
1250
- requestAdmission: async () => {
1251
- return this._callbacks.requestAdmission();
1252
- },
1253
- authenticate: async (credentials) => {
1254
- return this._callbacks.authenticate(credentials);
1255
- },
1256
- // TODO(burdon): Not used: controlFeedKey, dataFeedKey.
1257
- presentAdmissionCredentials: async (credentials) => {
1258
- return this._callbacks.presentAdmissionCredentials(credentials);
1259
- }
1260
- }
1261
- };
1262
- }
1263
- async onOpen(context) {
1264
- await super.onOpen(context);
1265
- this._callbacks.onOpen();
1266
- }
1267
- };
1268
- var GuestHaloInvitationExtension = class extends RpcExtension {
1269
- constructor(_callbacks) {
1270
- super({
1271
- requested: {
1272
- HaloHostService: schema3.getService("dxos.halo.invitations.HaloHostService")
1273
- }
1274
- });
1275
- this._callbacks = _callbacks;
1276
- }
1277
- async getHandlers() {
1278
- return {};
1279
- }
1280
- async onOpen(context) {
1281
- await super.onOpen(context);
1282
- this._callbacks.onOpen();
1283
- }
1284
- };
1285
-
1286
- // packages/sdk/client-services/src/packlets/invitations/invitations-proxy.ts
1287
- import assert6 from "@dxos/node-std/assert";
1288
- import { observableError } from "@dxos/async";
1289
- import { log as log6 } from "@dxos/log";
1290
- import { Invitation as Invitation3 } from "@dxos/protocols/proto/dxos/client/services";
1291
- var AbstractInvitationsProxy = class {
1292
- // prettier-ignore
1293
- constructor(_invitationsService) {
1294
- this._invitationsService = _invitationsService;
1295
- }
1296
- createInvitation(context, options) {
1297
- let invitationId;
1298
- const observable = new InvitationObservableProvider(async () => {
1299
- if (invitationId) {
1300
- await this._invitationsService.cancelInvitation({
1301
- invitationId
1302
- });
1303
- }
1304
- });
1305
- const invitation = {
1306
- ...this.getInvitationOptions(context),
1307
- ...options
1308
- };
1309
- const stream = this._invitationsService.createInvitation(invitation);
1310
- stream.subscribe((invitation2) => {
1311
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1312
- observable.setInvitation(invitation2);
1313
- switch (invitation2.state) {
1314
- case Invitation3.State.CONNECTING: {
1315
- assert6(invitation2.invitationId);
1316
- invitationId = invitation2.invitationId;
1317
- (_b = (_a = observable.callback).onConnecting) == null ? void 0 : _b.call(_a, invitation2);
1318
- break;
1319
- }
1320
- case Invitation3.State.CONNECTED: {
1321
- (_d = (_c = observable.callback).onConnected) == null ? void 0 : _d.call(_c, invitation2);
1322
- break;
1323
- }
1324
- case Invitation3.State.AUTHENTICATING: {
1325
- (_f = (_e = observable.callback).onAuthenticating) == null ? void 0 : _f.call(_e, invitation2);
1326
- break;
1327
- }
1328
- case Invitation3.State.SUCCESS: {
1329
- (_h = (_g = observable.callback).onSuccess) == null ? void 0 : _h.call(_g, invitation2);
1330
- break;
1331
- }
1332
- case Invitation3.State.CANCELLED: {
1333
- (_j = (_i = observable.callback).onCancelled) == null ? void 0 : _j.call(_i);
1334
- break;
1335
- }
1336
- default: {
1337
- log6.error(`Invalid state: ${invitation2.state}`, {}, {
1338
- file: "invitations-proxy.ts",
1339
- line: 81,
1340
- scope: this,
1341
- callSite: (f, a) => f(...a)
1342
- });
1343
- }
1344
- }
1345
- }, (err) => {
1346
- if (err) {
1347
- observableError(observable, err);
1348
- }
1349
- });
1350
- return observable;
1351
- }
1352
- acceptInvitation(invitation, options) {
1353
- assert6(invitation && invitation.swarmKey);
1354
- const observable = new AuthenticatingInvitationProvider({
1355
- onCancel: async () => {
1356
- var _a;
1357
- const invitationId = (_a = observable.invitation) == null ? void 0 : _a.invitationId;
1358
- assert6(invitationId);
1359
- await this._invitationsService.cancelInvitation({
1360
- invitationId
1361
- });
1362
- },
1363
- onAuthenticate: async (authenticationCode) => {
1364
- var _a;
1365
- const invitationId = (_a = observable.invitation) == null ? void 0 : _a.invitationId;
1366
- assert6(invitationId);
1367
- await this._invitationsService.authenticate({
1368
- invitationId,
1369
- authenticationCode
1370
- });
1371
- }
1372
- });
1373
- const stream = this._invitationsService.acceptInvitation({
1374
- ...invitation,
1375
- ...options
1376
- });
1377
- stream.subscribe((invitation2) => {
1378
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1379
- assert6(invitation2.invitationId);
1380
- observable.setInvitation(invitation2);
1381
- switch (invitation2.state) {
1382
- case Invitation3.State.CONNECTING: {
1383
- (_b = (_a = observable.callback).onConnecting) == null ? void 0 : _b.call(_a, invitation2);
1384
- break;
1385
- }
1386
- case Invitation3.State.CONNECTED: {
1387
- (_d = (_c = observable.callback).onConnected) == null ? void 0 : _d.call(_c, invitation2);
1388
- break;
1389
- }
1390
- case Invitation3.State.AUTHENTICATING: {
1391
- (_f = (_e = observable.callback).onAuthenticating) == null ? void 0 : _f.call(_e, invitation2);
1392
- break;
1393
- }
1394
- case Invitation3.State.SUCCESS: {
1395
- (_h = (_g = observable.callback).onSuccess) == null ? void 0 : _h.call(_g, invitation2);
1396
- break;
1397
- }
1398
- case Invitation3.State.CANCELLED: {
1399
- (_j = (_i = observable.callback).onCancelled) == null ? void 0 : _j.call(_i);
1400
- break;
1401
- }
1402
- default: {
1403
- log6.error(`Invalid state: ${invitation2.state}`, {}, {
1404
- file: "invitations-proxy.ts",
1405
- line: 146,
1406
- scope: this,
1407
- callSite: (f, a) => f(...a)
1408
- });
1409
- }
1410
- }
1411
- }, (err) => {
1412
- if (err) {
1413
- observableError(observable, err);
1414
- }
1415
- });
1416
- return observable;
1417
- }
1418
- };
1419
-
1420
- // packages/sdk/client-services/src/packlets/invitations/halo-invitations-proxy.ts
1421
- var HaloInvitationsProxy = class extends AbstractInvitationsProxy {
1422
- getInvitationOptions() {
1423
- return {};
1424
- }
1425
- };
1426
-
1427
- // packages/sdk/client-services/src/packlets/invitations/invitations-service.ts
1428
- import assert7 from "@dxos/node-std/assert";
1429
- import { Stream as Stream8 } from "@dxos/codec-protobuf";
1430
- import { log as log7 } from "@dxos/log";
1431
- import { Invitation as Invitation4 } from "@dxos/protocols/proto/dxos/client/services";
1432
- var AbstractInvitationsService = class {
1433
- // prettier-ignore
1434
- constructor(_identityManager, _getInvitationsHandler) {
1435
- this._identityManager = _identityManager;
1436
- this._getInvitationsHandler = _getInvitationsHandler;
1437
- this._createInvitations = /* @__PURE__ */ new Map();
1438
- this._acceptInvitations = /* @__PURE__ */ new Map();
1439
- }
1440
- // TODO(burdon): Guest/host label.
1441
- getLoggingContext() {
1442
- var _a;
1443
- return {
1444
- deviceKey: (_a = this._identityManager.identity) == null ? void 0 : _a.deviceKey
1445
- };
1446
- }
1447
- createInvitation(invitation) {
1448
- return new Stream8(({ next, close }) => {
1449
- const invitationsHandler = this._getInvitationsHandler();
1450
- const context = this.getContext(invitation);
1451
- log7("stream opened", this.getLoggingContext(), {
1452
- file: "invitations-service.ts",
1453
- line: 43,
1454
- scope: this,
1455
- callSite: (f, a) => f(...a)
1456
- });
1457
- let invitationId;
1458
- const { type, swarmKey } = invitation;
1459
- const observable = invitationsHandler.createInvitation(context, {
1460
- type,
1461
- swarmKey
1462
- });
1463
- observable.subscribe({
1464
- onConnecting: (invitation2) => {
1465
- assert7(invitation2.invitationId);
1466
- invitationId = invitation2.invitationId;
1467
- this._createInvitations.set(invitation2.invitationId, observable);
1468
- invitation2.state = Invitation4.State.CONNECTING;
1469
- next(invitation2);
1470
- },
1471
- onConnected: (invitation2) => {
1472
- assert7(invitation2.invitationId);
1473
- invitation2.state = Invitation4.State.CONNECTED;
1474
- next(invitation2);
1475
- },
1476
- onAuthenticating: (invitation2) => {
1477
- assert7(invitation2.invitationId);
1478
- invitation2.state = Invitation4.State.AUTHENTICATING;
1479
- next(invitation2);
1480
- },
1481
- onSuccess: (invitation2) => {
1482
- assert7(invitation2.invitationId);
1483
- invitation2.state = Invitation4.State.SUCCESS;
1484
- next(invitation2);
1485
- close();
1486
- },
1487
- onCancelled: () => {
1488
- assert7(invitationId);
1489
- invitation.invitationId = invitationId;
1490
- invitation.state = Invitation4.State.CANCELLED;
1491
- next(invitation);
1492
- close();
1493
- },
1494
- onTimeout: (err) => {
1495
- invitation.state = Invitation4.State.TIMEOUT;
1496
- close(err);
1497
- },
1498
- onError: (err) => {
1499
- invitation.state = Invitation4.State.ERROR;
1500
- close(err);
1501
- }
1502
- });
1503
- return (err) => {
1504
- const context2 = this.getLoggingContext();
1505
- if (err) {
1506
- log7.warn("stream closed", {
1507
- ...context2,
1508
- err
1509
- }, {
1510
- file: "invitations-service.ts",
1511
- line: 92,
1512
- scope: this,
1513
- callSite: (f, a) => f(...a)
1514
- });
1515
- } else {
1516
- log7("stream closed", context2, {
1517
- file: "invitations-service.ts",
1518
- line: 94,
1519
- scope: this,
1520
- callSite: (f, a) => f(...a)
1521
- });
1522
- }
1523
- this._createInvitations.delete(invitation.invitationId);
1524
- };
1525
- });
1526
- }
1527
- acceptInvitation(invitation, options) {
1528
- return new Stream8(({ next, close }) => {
1529
- log7("stream opened", this.getLoggingContext(), {
1530
- file: "invitations-service.ts",
1531
- line: 104,
1532
- scope: this,
1533
- callSite: (f, a) => f(...a)
1534
- });
1535
- const invitationsHandler = this._getInvitationsHandler();
1536
- let invitationId;
1537
- const observable = invitationsHandler.acceptInvitation(invitation, options);
1538
- observable.subscribe({
1539
- onConnecting: (invitation2) => {
1540
- assert7(invitation2.invitationId);
1541
- invitationId = invitation2.invitationId;
1542
- this._acceptInvitations.set(invitation2.invitationId, observable);
1543
- invitation2.state = Invitation4.State.CONNECTING;
1544
- next(invitation2);
1545
- },
1546
- onConnected: (invitation2) => {
1547
- assert7(invitation2.invitationId);
1548
- invitation2.state = Invitation4.State.CONNECTED;
1549
- next(invitation2);
1550
- },
1551
- onAuthenticating: (invitation2) => {
1552
- assert7(invitation2.invitationId);
1553
- invitation2.state = Invitation4.State.AUTHENTICATING;
1554
- next(invitation2);
1555
- },
1556
- onSuccess: (invitation2) => {
1557
- invitation2.state = Invitation4.State.SUCCESS;
1558
- next(invitation2);
1559
- close();
1560
- },
1561
- onCancelled: () => {
1562
- assert7(invitationId);
1563
- invitation.invitationId = invitationId;
1564
- invitation.state = Invitation4.State.CANCELLED;
1565
- next(invitation);
1566
- close();
1567
- },
1568
- onTimeout: (err) => {
1569
- invitation.state = Invitation4.State.TIMEOUT;
1570
- close(err);
1571
- },
1572
- onError: (err) => {
1573
- invitation.state = Invitation4.State.ERROR;
1574
- close(err);
1575
- }
1576
- });
1577
- return (err) => {
1578
- const context = this.getLoggingContext();
1579
- if (err) {
1580
- log7.warn("stream closed", {
1581
- ...context,
1582
- err
1583
- }, {
1584
- file: "invitations-service.ts",
1585
- line: 152,
1586
- scope: this,
1587
- callSite: (f, a) => f(...a)
1588
- });
1589
- } else {
1590
- log7("stream closed", context, {
1591
- file: "invitations-service.ts",
1592
- line: 154,
1593
- scope: this,
1594
- callSite: (f, a) => f(...a)
1595
- });
1596
- }
1597
- this._acceptInvitations.delete(invitation.invitationId);
1598
- };
1599
- });
1600
- }
1601
- async authenticate({ invitationId, authenticationCode }) {
1602
- log7("authenticating...", {}, {
1603
- file: "invitations-service.ts",
1604
- line: 163,
1605
- scope: this,
1606
- callSite: (f, a) => f(...a)
1607
- });
1608
- assert7(invitationId);
1609
- const observable = this._acceptInvitations.get(invitationId);
1610
- if (!observable) {
1611
- log7.warn("invalid invitation", {
1612
- invitationId
1613
- }, {
1614
- file: "invitations-service.ts",
1615
- line: 167,
1616
- scope: this,
1617
- callSite: (f, a) => f(...a)
1618
- });
1619
- } else {
1620
- await observable.authenticate(authenticationCode);
1621
- }
1622
- }
1623
- async cancelInvitation(invitation) {
1624
- var _a;
1625
- log7("cancelling...", {}, {
1626
- file: "invitations-service.ts",
1627
- line: 174,
1628
- scope: this,
1629
- callSite: (f, a) => f(...a)
1630
- });
1631
- assert7(invitation.invitationId);
1632
- const observable = (_a = this._createInvitations.get(invitation.invitationId)) != null ? _a : this._acceptInvitations.get(invitation.invitationId);
1633
- if (!observable) {
1634
- log7.warn("invalid invitation", {
1635
- invitationId: invitation.invitationId
1636
- }, {
1637
- file: "invitations-service.ts",
1638
- line: 179,
1639
- scope: this,
1640
- callSite: (f, a) => f(...a)
1641
- });
1642
- } else {
1643
- await (observable == null ? void 0 : observable.cancel());
1644
- }
1645
- }
1646
- };
1647
-
1648
- // packages/sdk/client-services/src/packlets/invitations/halo-invitations-service.ts
1649
- var HaloInvitationsServiceImpl = class extends AbstractInvitationsService {
1650
- // prettier-ignore
1651
- constructor(identityManager, invitationsHandler) {
1652
- super(identityManager, () => invitationsHandler);
1653
- this.invitationsHandler = invitationsHandler;
1654
- }
1655
- getContext(invitation) {
1656
- }
1657
- };
1658
-
1659
- // packages/sdk/client-services/src/packlets/invitations/space-invitations-handler.ts
1660
- import assert8 from "@dxos/node-std/assert";
1661
- import { scheduleTask as scheduleTask2, sleep as sleep2, Trigger as Trigger3 } from "@dxos/async";
1662
- import { Context as Context3 } from "@dxos/context";
1663
- import { createAdmissionCredentials, generatePasscode as generatePasscode2, getCredentialAssertion } from "@dxos/credentials";
1664
- import { writeMessages as writeMessages2 } from "@dxos/feed-store";
1665
- import { PublicKey as PublicKey4 } from "@dxos/keys";
1666
- import { log as log8 } from "@dxos/log";
1667
- import { createTeleportProtocolFactory as createTeleportProtocolFactory2, StarTopology as StarTopology2 } from "@dxos/network-manager";
1668
- import { schema as schema4 } from "@dxos/protocols";
1669
- import { Invitation as Invitation5 } from "@dxos/protocols/proto/dxos/client/services";
1670
- import { AuthenticationResponse as AuthenticationResponse2 } from "@dxos/protocols/proto/dxos/halo/invitations";
1671
- import { RpcExtension as RpcExtension2 } from "@dxos/teleport";
1672
- var MAX_OTP_ATTEMPTS = 3;
1673
- var SpaceInvitationsHandler = class extends AbstractInvitationsHandler {
1674
- constructor(networkManager, _spaceManager, _signingContext, _keyring) {
1675
- super(networkManager);
1676
- this._spaceManager = _spaceManager;
1677
- this._signingContext = _signingContext;
1678
- this._keyring = _keyring;
1679
- }
1680
- /**
1681
- * Creates an invitation and listens for a join request from the invited (guest) peer.
1682
- */
1683
- createInvitation(space, options) {
1684
- let swarmConnection;
1685
- const { type, timeout = INVITATION_TIMEOUT, swarmKey } = options != null ? options : {};
1686
- assert8(type !== Invitation5.Type.OFFLINE);
1687
- assert8(space);
1688
- const invitation = {
1689
- type,
1690
- invitationId: PublicKey4.random().toHex(),
1691
- swarmKey: swarmKey != null ? swarmKey : PublicKey4.random(),
1692
- spaceKey: space.key,
1693
- authenticationCode: generatePasscode2(AUTHENTICATION_CODE_LENGTH)
1694
- };
1695
- const ctx = new Context3({
1696
- onError: (err) => {
1697
- void ctx.dispose();
1698
- observable.callback.onError(err);
1699
- }
1700
- });
1701
- const observable = new InvitationObservableProvider(async () => {
1702
- await (swarmConnection == null ? void 0 : swarmConnection.close());
1703
- });
1704
- let authenticationCode;
1705
- let authenticationRetry = 0;
1706
- const createExtension = () => {
1707
- const complete = new Trigger3();
1708
- let guestProfile;
1709
- const hostInvitationExtension = new HostSpaceInvitationExtension({
1710
- introduce: async ({ profile }) => {
1711
- var _a, _b;
1712
- log8("guest introduced itself", {
1713
- guestProfile: profile,
1714
- host: this._signingContext.deviceKey,
1715
- spaceKey: space.key
1716
- }, {
1717
- file: "space-invitations-handler.ts",
1718
- line: 97,
1719
- scope: this,
1720
- callSite: (f, a) => f(...a)
1721
- });
1722
- guestProfile = profile;
1723
- (_b = (_a = observable.callback).onAuthenticating) == null ? void 0 : _b.call(_a, invitation);
1724
- },
1725
- authenticate: async ({ authenticationCode: code }) => {
1726
- log8("received authentication request", {
1727
- authenticationCode: code
1728
- }, {
1729
- file: "space-invitations-handler.ts",
1730
- line: 111,
1731
- scope: this,
1732
- callSite: (f, a) => f(...a)
1733
- });
1734
- let status = AuthenticationResponse2.Status.OK;
1735
- if (invitation.authenticationCode) {
1736
- if (authenticationRetry++ > MAX_OTP_ATTEMPTS) {
1737
- status = AuthenticationResponse2.Status.INVALID_OPT_ATTEMPTS;
1738
- } else if (code !== invitation.authenticationCode) {
1739
- status = AuthenticationResponse2.Status.INVALID_OTP;
1740
- } else {
1741
- authenticationCode = code;
1742
- }
1743
- }
1744
- return {
1745
- status
1746
- };
1747
- },
1748
- requestAdmission: async ({ identityKey, deviceKey, controlFeedKey, dataFeedKey }) => {
1749
- try {
1750
- if (invitation.type !== Invitation5.Type.INTERACTIVE_TESTING && invitation.type !== Invitation5.Type.MULTIUSE_TESTING) {
1751
- if (invitation.authenticationCode === void 0 || invitation.authenticationCode !== authenticationCode) {
1752
- throw new Error(`invalid authentication code: ${authenticationCode}`);
1753
- }
1754
- }
1755
- log8("writing guest credentials", {
1756
- host: this._signingContext.deviceKey,
1757
- guest: deviceKey
1758
- }, {
1759
- file: "space-invitations-handler.ts",
1760
- line: 138,
1761
- scope: this,
1762
- callSite: (f, a) => f(...a)
1763
- });
1764
- const credentials = await createAdmissionCredentials(this._signingContext.credentialSigner, identityKey, deviceKey, space.key, controlFeedKey, dataFeedKey, space.inner.genesisFeedKey, guestProfile);
1765
- assert8(credentials[0]["@type"] === "dxos.echo.feed.CredentialsMessage");
1766
- const spaceMemberCredential = credentials[0].credential;
1767
- assert8(getCredentialAssertion(spaceMemberCredential)["@type"] === "dxos.halo.credentials.SpaceMember");
1768
- await writeMessages2(space.inner.controlPipeline.writer, credentials);
1769
- complete.wake(deviceKey);
1770
- return {
1771
- credential: spaceMemberCredential
1772
- };
1773
- } catch (err) {
1774
- observable.callback.onError(err);
1775
- throw err;
1776
- }
1777
- },
1778
- onOpen: () => {
1779
- scheduleTask2(ctx, async () => {
1780
- var _a, _b;
1781
- try {
1782
- log8("connected", {
1783
- host: this._signingContext.deviceKey
1784
- }, {
1785
- file: "space-invitations-handler.ts",
1786
- line: 172,
1787
- scope: this,
1788
- callSite: (f, a) => f(...a)
1789
- });
1790
- (_b = (_a = observable.callback).onConnected) == null ? void 0 : _b.call(_a, invitation);
1791
- const deviceKey = await complete.wait({
1792
- timeout
1793
- });
1794
- log8("admitted guest", {
1795
- host: this._signingContext.deviceKey,
1796
- guest: deviceKey
1797
- }, {
1798
- file: "space-invitations-handler.ts",
1799
- line: 175,
1800
- scope: this,
1801
- callSite: (f, a) => f(...a)
1802
- });
1803
- observable.callback.onSuccess(invitation);
1804
- } catch (err) {
1805
- if (!observable.cancelled) {
1806
- log8.error("failed", err, {
1807
- file: "space-invitations-handler.ts",
1808
- line: 179,
1809
- scope: this,
1810
- callSite: (f, a) => f(...a)
1811
- });
1812
- observable.callback.onError(err);
1813
- }
1814
- } finally {
1815
- if (type !== Invitation5.Type.MULTIUSE_TESTING) {
1816
- await sleep2(ON_CLOSE_DELAY);
1817
- await ctx.dispose();
1818
- }
1819
- }
1820
- });
1821
- }
1822
- });
1823
- return hostInvitationExtension;
1824
- };
1825
- scheduleTask2(ctx, async () => {
1826
- var _a, _b;
1827
- const topic = invitation.swarmKey;
1828
- const swarmConnection2 = await this._networkManager.joinSwarm({
1829
- topic,
1830
- peerId: topic,
1831
- protocolProvider: createTeleportProtocolFactory2(async (teleport) => {
1832
- teleport.addExtension("dxos.halo.invitations", createExtension());
1833
- }),
1834
- topology: new StarTopology2(topic)
1835
- });
1836
- ctx.onDispose(() => swarmConnection2.close());
1837
- (_b = (_a = observable.callback).onConnecting) == null ? void 0 : _b.call(_a, invitation);
1838
- });
1839
- return observable;
1840
- }
1841
- /**
1842
- * Waits for the host peer (inviter) to accept our join request.
1843
- * The local guest peer (invitee) then sends the local space invitation to the host,
1844
- * which then writes the guest's credentials to the space.
1845
- */
1846
- acceptInvitation(invitation, options) {
1847
- const { timeout = INVITATION_TIMEOUT } = options != null ? options : {};
1848
- const ctx = new Context3({
1849
- onError: (err) => {
1850
- void ctx.dispose();
1851
- observable.callback.onError(err);
1852
- }
1853
- });
1854
- const authenticated = new Trigger3();
1855
- const observable = new AuthenticatingInvitationProvider({
1856
- onCancel: async () => {
1857
- await ctx.dispose();
1858
- },
1859
- onAuthenticate: async (code) => {
1860
- authenticated.wake(code);
1861
- }
1862
- });
1863
- let connectionCount = 0;
1864
- const complete = new Trigger3();
1865
- const createExtension = () => {
1866
- const extension = new GuestSpaceInvitationExtension({
1867
- onOpen: () => {
1868
- scheduleTask2(ctx, async () => {
1869
- var _a, _b, _c, _d;
1870
- try {
1871
- if (++connectionCount > 1) {
1872
- throw new Error(`multiple connections detected: ${connectionCount}`);
1873
- }
1874
- log8("connected", {
1875
- guest: this._signingContext.deviceKey
1876
- }, {
1877
- file: "space-invitations-handler.ts",
1878
- line: 252,
1879
- scope: this,
1880
- callSite: (f, a) => f(...a)
1881
- });
1882
- (_b = (_a = observable.callback).onConnected) == null ? void 0 : _b.call(_a, invitation);
1883
- log8("introduce", {
1884
- guest: this._signingContext.deviceKey
1885
- }, {
1886
- file: "space-invitations-handler.ts",
1887
- line: 256,
1888
- scope: this,
1889
- callSite: (f, a) => f(...a)
1890
- });
1891
- await extension.rpc.SpaceHostService.introduce({
1892
- profile: this._signingContext.profile
1893
- });
1894
- if (invitation.type === void 0 || invitation.type === Invitation5.Type.INTERACTIVE) {
1895
- for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {
1896
- log8("guest waiting for authentication code...", {}, {
1897
- file: "space-invitations-handler.ts",
1898
- line: 265,
1899
- scope: this,
1900
- callSite: (f, a) => f(...a)
1901
- });
1902
- (_d = (_c = observable.callback).onAuthenticating) == null ? void 0 : _d.call(_c, invitation);
1903
- const authenticationCode = await authenticated.wait({
1904
- timeout
1905
- });
1906
- log8("sending authentication request", {}, {
1907
- file: "space-invitations-handler.ts",
1908
- line: 269,
1909
- scope: this,
1910
- callSite: (f, a) => f(...a)
1911
- });
1912
- const response = await extension.rpc.SpaceHostService.authenticate({
1913
- authenticationCode
1914
- });
1915
- if (response.status === void 0 || response.status === AuthenticationResponse2.Status.OK) {
1916
- break;
1917
- }
1918
- if (response.status === AuthenticationResponse2.Status.INVALID_OTP) {
1919
- if (attempt === MAX_OTP_ATTEMPTS) {
1920
- throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);
1921
- } else {
1922
- log8("retrying invalid code", {
1923
- attempt
1924
- }, {
1925
- file: "space-invitations-handler.ts",
1926
- line: 279,
1927
- scope: this,
1928
- callSite: (f, a) => f(...a)
1929
- });
1930
- authenticated.reset();
1931
- }
1932
- }
1933
- }
1934
- }
1935
- const controlFeedKey = await this._keyring.createKey();
1936
- const dataFeedKey = await this._keyring.createKey();
1937
- log8("request admission", {
1938
- guest: this._signingContext.deviceKey
1939
- }, {
1940
- file: "space-invitations-handler.ts",
1941
- line: 290,
1942
- scope: this,
1943
- callSite: (f, a) => f(...a)
1944
- });
1945
- const { credential } = await extension.rpc.SpaceHostService.requestAdmission({
1946
- identityKey: this._signingContext.identityKey,
1947
- deviceKey: this._signingContext.deviceKey,
1948
- controlFeedKey,
1949
- dataFeedKey
1950
- });
1951
- const assertion = getCredentialAssertion(credential);
1952
- assert8(assertion["@type"] === "dxos.halo.credentials.SpaceMember", "Invalid credential");
1953
- assert8(credential.subject.id.equals(this._signingContext.identityKey));
1954
- const space = await this._spaceManager.acceptSpace({
1955
- spaceKey: assertion.spaceKey,
1956
- genesisFeedKey: assertion.genesisFeedKey,
1957
- controlFeedKey,
1958
- dataFeedKey
1959
- });
1960
- log8("admitted by host", {
1961
- guest: this._signingContext.deviceKey,
1962
- spaceKey: space.key
1963
- }, {
1964
- file: "space-invitations-handler.ts",
1965
- line: 313,
1966
- scope: this,
1967
- callSite: (f, a) => f(...a)
1968
- });
1969
- complete.wake();
1970
- } catch (err) {
1971
- if (!observable.cancelled) {
1972
- log8.warn("auth failed", err, {
1973
- file: "space-invitations-handler.ts",
1974
- line: 317,
1975
- scope: this,
1976
- callSite: (f, a) => f(...a)
1977
- });
1978
- observable.callback.onError(err);
1979
- }
1980
- } finally {
1981
- await ctx.dispose();
1982
- }
1983
- });
1984
- }
1985
- });
1986
- return extension;
1987
- };
1988
- scheduleTask2(ctx, async () => {
1989
- var _a, _b;
1990
- assert8(invitation.swarmKey);
1991
- const topic = invitation.swarmKey;
1992
- const swarmConnection = await this._networkManager.joinSwarm({
1993
- topic,
1994
- peerId: PublicKey4.random(),
1995
- protocolProvider: createTeleportProtocolFactory2(async (teleport) => {
1996
- teleport.addExtension("dxos.halo.invitations", createExtension());
1997
- }),
1998
- topology: new StarTopology2(topic)
1999
- });
2000
- ctx.onDispose(() => swarmConnection.close());
2001
- (_b = (_a = observable.callback).onConnecting) == null ? void 0 : _b.call(_a, invitation);
2002
- await complete.wait();
2003
- observable.callback.onSuccess(invitation);
2004
- await ctx.dispose();
2005
- });
2006
- return observable;
2007
- }
2008
- };
2009
- var HostSpaceInvitationExtension = class extends RpcExtension2 {
2010
- constructor(_callbacks) {
2011
- super({
2012
- exposed: {
2013
- SpaceHostService: schema4.getService("dxos.halo.invitations.SpaceHostService")
2014
- }
2015
- });
2016
- this._callbacks = _callbacks;
2017
- }
2018
- async getHandlers() {
2019
- return {
2020
- // TODO(dmaretskyi): For now this is just forwarding the data to callbacks since we don't have session-specific logic.
2021
- // Perhaps in the future we will have more complex logic here.
2022
- SpaceHostService: {
2023
- introduce: async (params) => {
2024
- return this._callbacks.introduce(params);
2025
- },
2026
- authenticate: async (credentials) => {
2027
- return this._callbacks.authenticate(credentials);
2028
- },
2029
- requestAdmission: async (credentials) => {
2030
- return this._callbacks.requestAdmission(credentials);
2031
- }
2032
- }
2033
- };
2034
- }
2035
- async onOpen(context) {
2036
- await super.onOpen(context);
2037
- this._callbacks.onOpen();
2038
- }
2039
- };
2040
- var GuestSpaceInvitationExtension = class extends RpcExtension2 {
2041
- constructor(_callbacks) {
2042
- super({
2043
- requested: {
2044
- SpaceHostService: schema4.getService("dxos.halo.invitations.SpaceHostService")
2045
- }
2046
- });
2047
- this._callbacks = _callbacks;
2048
- }
2049
- async getHandlers() {
2050
- return {};
2051
- }
2052
- async onOpen(context) {
2053
- await super.onOpen(context);
2054
- this._callbacks.onOpen();
2055
- }
2056
- };
2057
-
2058
- // packages/sdk/client-services/src/packlets/invitations/space-invitations-proxy.ts
2059
- var SpaceInvitationsProxy = class extends AbstractInvitationsProxy {
2060
- getInvitationOptions(context) {
2061
- return {
2062
- spaceKey: context
2063
- };
2064
- }
2065
- };
2066
-
2067
- // packages/sdk/client-services/src/packlets/invitations/space-invitations-service.ts
2068
- import assert9 from "@dxos/node-std/assert";
2069
- var SpaceInvitationsServiceImpl = class extends AbstractInvitationsService {
2070
- // prettier-ignore
2071
- constructor(identityManager, invitationsHandler, _getSpaceManager) {
2072
- super(identityManager, invitationsHandler);
2073
- this.invitationsHandler = invitationsHandler;
2074
- this._getSpaceManager = _getSpaceManager;
2075
- }
2076
- getContext(invitation) {
2077
- assert9(invitation.spaceKey);
2078
- const spaceManager = this._getSpaceManager();
2079
- const space = spaceManager.spaces.get(invitation.spaceKey);
2080
- assert9(space);
2081
- return space;
2082
- }
2083
- };
2084
-
2085
- // packages/sdk/client-services/src/packlets/services/service-context.ts
2086
- import { Trigger as Trigger4 } from "@dxos/async";
2087
- import { failUndefined as failUndefined2 } from "@dxos/debug";
2088
- import { MOCK_AUTH_PROVIDER, MOCK_AUTH_VERIFIER, valueEncoding, DataServiceSubscriptions, MetadataStore, SpaceManager, SnapshotStore } from "@dxos/echo-db";
2089
- import { FeedFactory, FeedStore } from "@dxos/feed-store";
2090
- import { Keyring } from "@dxos/keyring";
2091
- import { log as log10 } from "@dxos/log";
2092
-
2093
- // packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts
2094
- import { Event as Event3, synchronized, trackLeaks as trackLeaks2 } from "@dxos/async";
2095
- import { Context as Context5 } from "@dxos/context";
2096
- import { spaceGenesis, SnapshotManager } from "@dxos/echo-db";
2097
- import { PublicKey as PublicKey5 } from "@dxos/keys";
2098
- import { log as log9 } from "@dxos/log";
2099
- import { Presence } from "@dxos/teleport-extension-presence";
2100
- import { ComplexMap as ComplexMap2 } from "@dxos/util";
2101
-
2102
- // packages/sdk/client-services/src/packlets/spaces/data-space.ts
2103
- import assert10 from "@dxos/node-std/assert";
2104
- import { trackLeaks } from "@dxos/async";
2105
- import { Context as Context4 } from "@dxos/context";
2106
- import { DataPipelineControllerImpl } from "@dxos/echo-db";
2107
- var __decorate = function(decorators, target, key, desc) {
2108
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2109
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2110
- r = Reflect.decorate(decorators, target, key, desc);
2111
- else
2112
- for (var i = decorators.length - 1; i >= 0; i--)
2113
- if (d = decorators[i])
2114
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2115
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2116
- };
2117
- var DataSpace = class DataSpace2 {
2118
- constructor(params) {
2119
- this._ctx = new Context4();
2120
- this._inner = params.inner;
2121
- this._presence = params.presence;
2122
- this._dataPipelineController = new DataPipelineControllerImpl({
2123
- modelFactory: params.modelFactory,
2124
- metadataStore: params.metadataStore,
2125
- snapshotManager: params.snapshotManager,
2126
- memberKey: params.memberKey,
2127
- spaceKey: this._inner.key,
2128
- feedInfoProvider: (feedKey) => this._inner.spaceState.feeds.get(feedKey),
2129
- snapshotId: params.snapshotId
2130
- });
2131
- }
2132
- get key() {
2133
- return this._inner.key;
2134
- }
2135
- get inner() {
2136
- return this._inner;
2137
- }
2138
- get isOpen() {
2139
- return this._inner.isOpen;
2140
- }
2141
- get dataPipelineController() {
2142
- return this._dataPipelineController;
2143
- }
2144
- get database() {
2145
- assert10(this._dataPipelineController.database);
2146
- return this._dataPipelineController.database;
2147
- }
2148
- get stateUpdate() {
2149
- return this._inner.stateUpdate;
2150
- }
2151
- get presence() {
2152
- return this._presence;
2153
- }
2154
- async open() {
2155
- await this._inner.open();
2156
- await this._inner.initDataPipeline(this._dataPipelineController);
2157
- }
2158
- async close() {
2159
- await this._ctx.dispose();
2160
- await this._inner.close();
2161
- await this._presence.destroy();
2162
- }
2163
- };
2164
- DataSpace = __decorate([
2165
- trackLeaks("open", "close")
2166
- ], DataSpace);
2167
-
2168
- // packages/sdk/client-services/src/packlets/spaces/data-space-manager.ts
2169
- var __decorate2 = function(decorators, target, key, desc) {
2170
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2171
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2172
- r = Reflect.decorate(decorators, target, key, desc);
2173
- else
2174
- for (var i = decorators.length - 1; i >= 0; i--)
2175
- if (d = decorators[i])
2176
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2177
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2178
- };
2179
- var DataSpaceManager = class DataSpaceManager2 {
2180
- constructor(_spaceManager, _metadataStore, _dataServiceSubscriptions, _keyring, _signingContext, _modelFactory, _snapshotStore) {
2181
- this._spaceManager = _spaceManager;
2182
- this._metadataStore = _metadataStore;
2183
- this._dataServiceSubscriptions = _dataServiceSubscriptions;
2184
- this._keyring = _keyring;
2185
- this._signingContext = _signingContext;
2186
- this._modelFactory = _modelFactory;
2187
- this._snapshotStore = _snapshotStore;
2188
- this._ctx = new Context5();
2189
- this.updated = new Event3();
2190
- this._spaces = new ComplexMap2(PublicKey5.hash);
2191
- }
2192
- // TODO(burdon): Remove.
2193
- get spaces() {
2194
- return this._spaces;
2195
- }
2196
- async open() {
2197
- await this._metadataStore.load();
2198
- log9("metadata loaded", {
2199
- spaces: this._metadataStore.spaces.length
2200
- }, {
2201
- file: "data-space-manager.ts",
2202
- line: 54,
2203
- scope: this,
2204
- callSite: (f, a) => f(...a)
2205
- });
2206
- for (const spaceMetadata of this._metadataStore.spaces) {
2207
- log9("load space", {
2208
- spaceMetadata
2209
- }, {
2210
- file: "data-space-manager.ts",
2211
- line: 57,
2212
- scope: this,
2213
- callSite: (f, a) => f(...a)
2214
- });
2215
- const space = await this._constructSpace(spaceMetadata);
2216
- if (spaceMetadata.latestTimeframe) {
2217
- log9("waiting for latest timeframe", {
2218
- spaceMetadata
2219
- }, {
2220
- file: "data-space-manager.ts",
2221
- line: 60,
2222
- scope: this,
2223
- callSite: (f, a) => f(...a)
2224
- });
2225
- await space.dataPipelineController.waitUntilTimeframe(spaceMetadata.latestTimeframe);
2226
- }
2227
- }
2228
- }
2229
- async close() {
2230
- await this._ctx.dispose();
2231
- for (const space of this._spaces.values()) {
2232
- await space.close();
2233
- }
2234
- }
2235
- /**
2236
- * Creates a new space writing the genesis credentials to the control feed.
2237
- */
2238
- async createSpace() {
2239
- const spaceKey = await this._keyring.createKey();
2240
- const controlFeedKey = await this._keyring.createKey();
2241
- const dataFeedKey = await this._keyring.createKey();
2242
- const metadata = {
2243
- key: spaceKey,
2244
- genesisFeedKey: controlFeedKey,
2245
- controlFeedKey,
2246
- dataFeedKey
2247
- };
2248
- log9("creating space...", {
2249
- spaceKey
2250
- }, {
2251
- file: "data-space-manager.ts",
2252
- line: 89,
2253
- scope: this,
2254
- callSite: (f, a) => f(...a)
2255
- });
2256
- const space = await this._constructSpace(metadata);
2257
- await spaceGenesis(this._keyring, this._signingContext, space.inner);
2258
- await this._metadataStore.addSpace(metadata);
2259
- this.updated.emit();
2260
- return space;
2261
- }
2262
- // TODO(burdon): Rename join space.
2263
- async acceptSpace(opts) {
2264
- const metadata = {
2265
- key: opts.spaceKey,
2266
- genesisFeedKey: opts.genesisFeedKey,
2267
- controlFeedKey: opts.controlFeedKey,
2268
- dataFeedKey: opts.dataFeedKey
2269
- };
2270
- const space = await this._constructSpace(metadata);
2271
- await this._metadataStore.addSpace(metadata);
2272
- this.updated.emit();
2273
- return space;
2274
- }
2275
- async _constructSpace(metadata) {
2276
- const presence = new Presence({
2277
- localPeerId: this._signingContext.deviceKey,
2278
- announceInterval: 1e3,
2279
- offlineTimeout: 3e4,
2280
- identityKey: this._signingContext.identityKey
2281
- });
2282
- const snapshotManager = new SnapshotManager(this._snapshotStore);
2283
- const space = await this._spaceManager.constructSpace({
2284
- metadata,
2285
- swarmIdentity: {
2286
- peerKey: this._signingContext.deviceKey,
2287
- credentialProvider: this._signingContext.credentialProvider,
2288
- credentialAuthenticator: this._signingContext.credentialAuthenticator
2289
- },
2290
- onNetworkConnection: (session) => {
2291
- session.addExtension("dxos.mesh.teleport.presence", presence.createExtension({
2292
- remotePeerId: session.remotePeerId
2293
- }));
2294
- session.addExtension("dxos.mesh.teleport.objectsync", snapshotManager.objectSync.createExtension());
2295
- }
2296
- });
2297
- const dataSpace = new DataSpace({
2298
- inner: space,
2299
- modelFactory: this._modelFactory,
2300
- metadataStore: this._metadataStore,
2301
- snapshotManager,
2302
- presence,
2303
- memberKey: this._signingContext.identityKey,
2304
- snapshotId: metadata.snapshot
2305
- });
2306
- await dataSpace.open();
2307
- this._dataServiceSubscriptions.registerSpace(space.key, dataSpace.database.createDataServiceHost());
2308
- this._spaces.set(metadata.key, dataSpace);
2309
- return dataSpace;
2310
- }
2311
- };
2312
- __decorate2([
2313
- synchronized
2314
- ], DataSpaceManager.prototype, "open", null);
2315
- __decorate2([
2316
- synchronized
2317
- ], DataSpaceManager.prototype, "close", null);
2318
- __decorate2([
2319
- synchronized
2320
- ], DataSpaceManager.prototype, "createSpace", null);
2321
- __decorate2([
2322
- synchronized
2323
- ], DataSpaceManager.prototype, "acceptSpace", null);
2324
- DataSpaceManager = __decorate2([
2325
- trackLeaks2("open", "close")
2326
- ], DataSpaceManager);
2327
-
2328
- // packages/sdk/client-services/src/packlets/services/service-context.ts
2329
- var ServiceContext = class {
2330
- // prettier-ignore
2331
- constructor(storage, networkManager, modelFactory) {
2332
- this.storage = storage;
2333
- this.networkManager = networkManager;
2334
- this.modelFactory = modelFactory;
2335
- this.initialized = new Trigger4();
2336
- this.dataServiceSubscriptions = new DataServiceSubscriptions();
2337
- this.metadataStore = new MetadataStore(storage.createDirectory("metadata"));
2338
- this.snapshotStore = new SnapshotStore(storage.createDirectory("snapshots"));
2339
- this.keyring = new Keyring(storage.createDirectory("keyring"));
2340
- this.feedStore = new FeedStore({
2341
- factory: new FeedFactory({
2342
- root: storage.createDirectory("feeds"),
2343
- signer: this.keyring,
2344
- hypercore: {
2345
- valueEncoding
2346
- }
2347
- })
2348
- });
2349
- this.spaceManager = new SpaceManager({
2350
- feedStore: this.feedStore,
2351
- networkManager: this.networkManager
2352
- });
2353
- this.identityManager = new IdentityManager(this.metadataStore, this.keyring, this.spaceManager);
2354
- this.haloInvitations = new HaloInvitationsHandler(this.networkManager, this.identityManager);
2355
- }
2356
- async open() {
2357
- log10("opening...", {}, {
2358
- file: "service-context.ts",
2359
- line: 85,
2360
- scope: this,
2361
- callSite: (f, a) => f(...a)
2362
- });
2363
- await this.networkManager.open();
2364
- await this.spaceManager.open();
2365
- await this.identityManager.open();
2366
- if (this.identityManager.identity) {
2367
- await this._initialize();
2368
- }
2369
- log10("opened", {}, {
2370
- file: "service-context.ts",
2371
- line: 92,
2372
- scope: this,
2373
- callSite: (f, a) => f(...a)
2374
- });
2375
- }
2376
- async close() {
2377
- var _a;
2378
- log10("closing...", {}, {
2379
- file: "service-context.ts",
2380
- line: 96,
2381
- scope: this,
2382
- callSite: (f, a) => f(...a)
2383
- });
2384
- await ((_a = this.dataSpaceManager) == null ? void 0 : _a.close());
2385
- await this.identityManager.close();
2386
- await this.spaceManager.close();
2387
- await this.feedStore.close();
2388
- await this.networkManager.close();
2389
- this.dataServiceSubscriptions.clear();
2390
- log10("closed", {}, {
2391
- file: "service-context.ts",
2392
- line: 103,
2393
- scope: this,
2394
- callSite: (f, a) => f(...a)
2395
- });
2396
- }
2397
- async reset() {
2398
- log10("resetting...", {}, {
2399
- file: "service-context.ts",
2400
- line: 107,
2401
- scope: this,
2402
- callSite: (f, a) => f(...a)
2403
- });
2404
- await this.close();
2405
- await this.storage.reset();
2406
- log10("reset", {}, {
2407
- file: "service-context.ts",
2408
- line: 110,
2409
- scope: this,
2410
- callSite: (f, a) => f(...a)
2411
- });
2412
- }
2413
- async createIdentity(params = {}) {
2414
- const identity = await this.identityManager.createIdentity(params);
2415
- await this._initialize();
2416
- return identity;
2417
- }
2418
- // Called when identity is created.
2419
- async _initialize() {
2420
- var _a;
2421
- log10("initializing spaces...", {}, {
2422
- file: "service-context.ts",
2423
- line: 122,
2424
- scope: this,
2425
- callSite: (f, a) => f(...a)
2426
- });
2427
- const identity = (_a = this.identityManager.identity) != null ? _a : failUndefined2();
2428
- const signingContext = {
2429
- credentialProvider: MOCK_AUTH_PROVIDER,
2430
- credentialAuthenticator: MOCK_AUTH_VERIFIER,
2431
- credentialSigner: identity.getIdentityCredentialSigner(),
2432
- identityKey: identity.identityKey,
2433
- deviceKey: identity.deviceKey,
2434
- profile: identity.profileDocument
2435
- };
2436
- this.dataSpaceManager = new DataSpaceManager(this.spaceManager, this.metadataStore, this.dataServiceSubscriptions, this.keyring, signingContext, this.modelFactory, this.snapshotStore);
2437
- await this.dataSpaceManager.open();
2438
- this.spaceInvitations = new SpaceInvitationsHandler(this.networkManager, this.dataSpaceManager, signingContext, this.keyring);
2439
- this.initialized.wake();
2440
- }
2441
- };
2442
-
2443
- // packages/sdk/client-services/src/packlets/services/service-definitions.ts
2444
- import { schema as schema5 } from "@dxos/protocols";
2445
- import { createServiceBundle } from "@dxos/rpc";
2446
- var clientServiceBundle = createServiceBundle({
2447
- HaloInvitationsService: schema5.getService("dxos.client.services.HaloInvitationsService"),
2448
- DevicesService: schema5.getService("dxos.client.services.DevicesService"),
2449
- SpaceInvitationsService: schema5.getService("dxos.client.services.SpaceInvitationsService"),
2450
- SpacesService: schema5.getService("dxos.client.services.SpacesService"),
2451
- NetworkService: schema5.getService("dxos.client.services.NetworkService"),
2452
- // TODO(burdon): Deprecated.
2453
- SpaceService: schema5.getService("dxos.client.SpaceService"),
2454
- DataService: schema5.getService("dxos.echo.service.DataService"),
2455
- ProfileService: schema5.getService("dxos.client.ProfileService"),
2456
- SystemService: schema5.getService("dxos.client.SystemService"),
2457
- DevtoolsHost: schema5.getService("dxos.devtools.host.DevtoolsHost"),
2458
- TracingService: schema5.getService("dxos.devtools.host.TracingService")
2459
- });
2460
-
2461
- // packages/sdk/client-services/src/packlets/services/service-host.ts
2462
- import { raise as raise2 } from "@dxos/debug";
2463
- import { DataServiceImpl } from "@dxos/echo-db";
2464
- import { log as log11 } from "@dxos/log";
2465
- import { ModelFactory } from "@dxos/model-factory";
2466
- import { ObjectModel } from "@dxos/object-model";
2467
- import { TextModel } from "@dxos/text-model";
2468
-
2469
- // packages/sdk/client-services/src/packlets/identity/devices-service-impl.ts
2470
- import { EventSubscriptions as EventSubscriptions3 } from "@dxos/async";
2471
- import { Stream as Stream9 } from "@dxos/codec-protobuf";
2472
- var DevicesServiceImpl = class {
2473
- constructor(_identityManager) {
2474
- this._identityManager = _identityManager;
2475
- }
2476
- updateDevice() {
2477
- throw new Error("Method not implemented.");
2478
- }
2479
- queryDevices() {
2480
- return new Stream9(({ next }) => {
2481
- const update = () => {
2482
- var _a;
2483
- const deviceKeys = (_a = this._identityManager.identity) == null ? void 0 : _a.authorizedDeviceKeys;
2484
- if (!deviceKeys) {
2485
- next({
2486
- devices: []
2487
- });
2488
- } else {
2489
- next({
2490
- devices: Array.from(deviceKeys.values()).map((key) => ({
2491
- deviceKey: key
2492
- }))
2493
- });
2494
- }
2495
- };
2496
- const dispose = new EventSubscriptions3();
2497
- dispose.add(this._identityManager.stateUpdate.on(() => {
2498
- update();
2499
- if (this._identityManager.identity) {
2500
- dispose.add(this._identityManager.identity.stateUpdate.on(() => {
2501
- update();
2502
- }));
2503
- }
2504
- }));
2505
- update();
2506
- return () => dispose.clear();
2507
- });
2508
- }
2509
- };
2510
-
2511
- // packages/sdk/client-services/src/packlets/network/network-service.ts
2512
- import { Stream as Stream10 } from "@dxos/codec-protobuf";
2513
- var NetworkServiceImpl = class {
2514
- constructor(networkManager) {
2515
- this.networkManager = networkManager;
2516
- }
2517
- subscribeToNetworkStatus() {
2518
- return new Stream10(({ next }) => {
2519
- const unsubscribe = this.networkManager.connectionStateChanged.on((state) => next({
2520
- state
2521
- }));
2522
- next({
2523
- state: this.networkManager.connectionState
2524
- });
2525
- return unsubscribe;
2526
- });
2527
- }
2528
- async setNetworkOptions(request) {
2529
- await this.networkManager.setConnectionState(request.state);
2530
- }
2531
- };
2532
-
2533
- // packages/sdk/client-services/src/packlets/spaces/spaces-service.ts
2534
- import { scheduleTask as scheduleTask3 } from "@dxos/async";
2535
- import { Stream as Stream11 } from "@dxos/codec-protobuf";
2536
- import { raise } from "@dxos/debug";
2537
- import { SpaceNotFoundError } from "@dxos/echo-db";
2538
- var SpacesServiceImpl = class {
2539
- constructor(_spaceManager) {
2540
- this._spaceManager = _spaceManager;
2541
- }
2542
- async createSpace() {
2543
- throw new Error();
2544
- }
2545
- querySpaces() {
2546
- throw new Error();
2547
- }
2548
- queryMembers(query) {
2549
- throw new Error();
2550
- }
2551
- queryCredentials({ spaceKey }) {
2552
- return new Stream11(({ ctx, next }) => {
2553
- var _a;
2554
- const space = (_a = this._spaceManager.spaces.get(spaceKey)) != null ? _a : raise(new SpaceNotFoundError(spaceKey));
2555
- const processor = space.spaceState.registerProcessor({
2556
- process: async (credential) => {
2557
- next(credential);
2558
- }
2559
- });
2560
- ctx.onDispose(() => processor.close());
2561
- scheduleTask3(ctx, () => processor.open());
2562
- });
2563
- }
2564
- };
2565
-
2566
- // packages/sdk/client-services/src/packlets/storage/storage.ts
2567
- import { InvalidConfigError } from "@dxos/errors";
2568
- import { Runtime } from "@dxos/protocols/proto/dxos/config";
2569
- import { createStorage, StorageType } from "@dxos/random-access-storage";
2570
- var StorageDriver = Runtime.Client.Storage.StorageDriver;
2571
- var createStorageObjects = (config) => {
2572
- const { path = "dxos/storage", storageType, keyStorage, persistent = false } = config != null ? config : {};
2573
- if (persistent && storageType === StorageDriver.RAM) {
2574
- throw new InvalidConfigError("RAM storage cannot be used in persistent mode.");
2575
- }
2576
- if (!persistent && storageType !== void 0 && storageType !== StorageDriver.RAM) {
2577
- throw new InvalidConfigError("Cannot use a persistent storage in not persistent mode.");
2578
- }
2579
- if (persistent && keyStorage === StorageDriver.RAM) {
2580
- throw new InvalidConfigError("RAM key storage cannot be used in persistent mode.");
2581
- }
2582
- if (!persistent && keyStorage !== StorageDriver.RAM && keyStorage !== void 0) {
2583
- throw new InvalidConfigError("Cannot use a persistent key storage in not persistent mode.");
2584
- }
2585
- return {
2586
- storage: createStorage({
2587
- type: persistent ? toStorageType(storageType) : StorageType.RAM,
2588
- root: `${path}/`
2589
- })
2590
- };
2591
- };
2592
- var toStorageType = (type) => {
2593
- switch (type) {
2594
- case void 0:
2595
- return void 0;
2596
- case StorageDriver.RAM:
2597
- return StorageType.RAM;
2598
- case StorageDriver.CHROME:
2599
- return StorageType.CHROME;
2600
- case StorageDriver.FIREFOX:
2601
- return StorageType.FIREFOX;
2602
- case StorageDriver.IDB:
2603
- return StorageType.IDB;
2604
- case StorageDriver.NODE:
2605
- return StorageType.NODE;
2606
- default:
2607
- throw new Error(`Invalid storage type: ${StorageDriver[type]}`);
2608
- }
2609
- };
2610
-
2611
- // packages/sdk/client-services/src/packlets/services/service-registry.ts
2612
- var ServiceRegistry = class {
2613
- // prettier-ignore
2614
- constructor(_serviceBundle, _handlers) {
2615
- this._serviceBundle = _serviceBundle;
2616
- this._handlers = _handlers;
2617
- }
2618
- get descriptors() {
2619
- return this._serviceBundle;
2620
- }
2621
- get services() {
2622
- return this._handlers;
2623
- }
2624
- };
2625
-
2626
- // packages/sdk/client-services/src/packlets/services/service-host.ts
2627
- var createDefaultModelFactory = () => {
2628
- return new ModelFactory().registerModel(ObjectModel).registerModel(TextModel);
2629
- };
2630
- var ClientServicesHost = class {
2631
- constructor({
2632
- config,
2633
- modelFactory = createDefaultModelFactory(),
2634
- // TODO(burdon): Create ApolloLink abstraction (see Client).
2635
- networkManager,
2636
- storage = createStorageObjects(config.get("runtime.client.storage", {})).storage
2637
- }) {
2638
- this._config = config;
2639
- this._modelFactory = modelFactory;
2640
- this._networkManager = networkManager;
2641
- this._storage = storage;
2642
- }
2643
- get descriptors() {
2644
- return this._serviceRegistry.descriptors;
2645
- }
2646
- get services() {
2647
- return this._serviceRegistry.services;
2648
- }
2649
- async open() {
2650
- var _a;
2651
- log11("opening...", {}, {
2652
- file: "service-host.ts",
2653
- line: 73,
2654
- scope: this,
2655
- callSite: (f, a) => f(...a)
2656
- });
2657
- await this._initialize();
2658
- await this._serviceContext.open();
2659
- const deviceKey = (_a = this._serviceContext.identityManager.identity) == null ? void 0 : _a.deviceKey;
2660
- log11("opened", {
2661
- deviceKey
2662
- }, {
2663
- file: "service-host.ts",
2664
- line: 77,
2665
- scope: this,
2666
- callSite: (f, a) => f(...a)
2667
- });
2668
- }
2669
- async close() {
2670
- var _a;
2671
- const deviceKey = (_a = this._serviceContext.identityManager.identity) == null ? void 0 : _a.deviceKey;
2672
- log11("closing...", {
2673
- deviceKey
2674
- }, {
2675
- file: "service-host.ts",
2676
- line: 82,
2677
- scope: this,
2678
- callSite: (f, a) => f(...a)
2679
- });
2680
- await this._serviceContext.close();
2681
- log11("closed", {
2682
- deviceKey
2683
- }, {
2684
- file: "service-host.ts",
2685
- line: 84,
2686
- scope: this,
2687
- callSite: (f, a) => f(...a)
2688
- });
2689
- }
2690
- // TODO(burdon): Move into open.
2691
- async _initialize() {
2692
- this._serviceContext = new ServiceContext(this._storage, this._networkManager, this._modelFactory);
2693
- this._serviceRegistry = new ServiceRegistry(clientServiceBundle, {
2694
- HaloInvitationsService: new HaloInvitationsServiceImpl(this._serviceContext.identityManager, this._serviceContext.haloInvitations),
2695
- DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),
2696
- SpaceInvitationsService: new SpaceInvitationsServiceImpl(this._serviceContext.identityManager, () => {
2697
- var _a;
2698
- return (_a = this._serviceContext.spaceInvitations) != null ? _a : raise2(new Error("SpaceInvitations not initialized"));
2699
- }, () => {
2700
- var _a;
2701
- return (_a = this._serviceContext.dataSpaceManager) != null ? _a : raise2(new Error("SpaceManager not initialized"));
2702
- }),
2703
- SpacesService: new SpacesServiceImpl(this._serviceContext.spaceManager),
2704
- DataService: new DataServiceImpl(this._serviceContext.dataServiceSubscriptions),
2705
- NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager),
2706
- // TODO(burdon): Move to new protobuf definitions.
2707
- ProfileService: new ProfileServiceImpl(this._serviceContext),
2708
- SpaceService: new SpaceServiceImpl(this._serviceContext),
2709
- SystemService: new SystemServiceImpl(this._config, this._serviceContext),
2710
- TracingService: new TracingServiceImpl(this._config),
2711
- DevtoolsHost: new DevtoolsServiceImpl({
2712
- events: new DevtoolsHostEvents(),
2713
- config: this._config,
2714
- context: this._serviceContext
2715
- })
2716
- });
2717
- }
2718
- };
2719
-
2720
- // packages/sdk/client-services/src/packlets/services/service-proxy.ts
2721
- import { asyncTimeout } from "@dxos/async";
2722
- import { RemoteServiceConnectionTimeout } from "@dxos/errors";
2723
- import { createProtoRpcPeer } from "@dxos/rpc";
2724
- var ClientServicesProxy = class {
2725
- // prettier-ignore
2726
- constructor(port, _timeout = 3e4) {
2727
- this._timeout = _timeout;
2728
- this._proxy = createProtoRpcPeer({
2729
- requested: clientServiceBundle,
2730
- exposed: {},
2731
- handlers: {},
2732
- port
2733
- });
2734
- }
2735
- get proxy() {
2736
- return this._proxy;
2737
- }
2738
- get descriptors() {
2739
- return clientServiceBundle;
2740
- }
2741
- get services() {
2742
- return this._proxy.rpc;
2743
- }
2744
- async open() {
2745
- await asyncTimeout(this._proxy.open(), this._timeout, new RemoteServiceConnectionTimeout());
2746
- }
2747
- async close() {
2748
- await this._proxy.close();
2749
- }
2750
- };
2751
-
2752
- // packages/sdk/client-services/src/packlets/vault/iframe-runtime.ts
2753
- import { WebRTCTransportService } from "@dxos/network-manager";
2754
- import { createProtoRpcPeer as createProtoRpcPeer2 } from "@dxos/rpc";
2755
-
2756
- // packages/sdk/client-services/src/packlets/vault/services.ts
2757
- import { schema as schema6 } from "@dxos/protocols";
2758
- var iframeServiceBundle = {
2759
- IframeService: schema6.getService("dxos.iframe.IframeService"),
2760
- BridgeService: schema6.getService("dxos.mesh.bridge.BridgeService")
2761
- };
2762
- var workerServiceBundle = {
2763
- WorkerService: schema6.getService("dxos.iframe.WorkerService")
2764
- };
2765
-
2766
- // packages/sdk/client-services/src/packlets/vault/iframe-runtime.ts
2767
- var IFrameRuntime = class {
2768
- constructor({ systemPort, workerAppPort, windowAppPort }) {
2769
- this._transportService = new WebRTCTransportService();
2770
- this._systemPort = systemPort;
2771
- this._windowAppPort = windowAppPort;
2772
- this._workerAppPort = workerAppPort;
2773
- this._systemRpc = createProtoRpcPeer2({
2774
- requested: workerServiceBundle,
2775
- exposed: iframeServiceBundle,
2776
- handlers: {
2777
- BridgeService: this._transportService,
2778
- IframeService: {
2779
- async heartbeat() {
2780
- }
2781
- }
2782
- },
2783
- port: this._systemPort,
2784
- timeout: 200
2785
- });
2786
- this._workerAppPort.subscribe((msg) => this._windowAppPort.send(msg));
2787
- this._windowAppPort.subscribe((msg) => this._workerAppPort.send(msg));
2788
- }
2789
- async open(origin) {
2790
- await this._systemRpc.open();
2791
- await this._systemRpc.rpc.WorkerService.start({
2792
- origin
2793
- });
2794
- }
2795
- async close() {
2796
- await this._systemRpc.rpc.WorkerService.stop();
2797
- await this._systemRpc.close();
2798
- }
2799
- };
2800
-
2801
- // packages/sdk/client-services/src/packlets/vault/worker-runtime.ts
2802
- import { Trigger as Trigger6 } from "@dxos/async";
2803
- import { MemorySignalManager, MemorySignalManagerContext, WebsocketSignalManager } from "@dxos/messaging";
2804
- import { NetworkManager, WebRTCTransportProxyFactory } from "@dxos/network-manager";
2805
-
2806
- // packages/sdk/client-services/src/packlets/vault/worker-session.ts
2807
- import assert11 from "@dxos/node-std/assert";
2808
- import { Trigger as Trigger5 } from "@dxos/async";
2809
- import { log as log12, logInfo } from "@dxos/log";
2810
- import { createProtoRpcPeer as createProtoRpcPeer3 } from "@dxos/rpc";
2811
- import { Callback } from "@dxos/util";
2812
- var __decorate3 = function(decorators, target, key, desc) {
2813
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2814
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
2815
- r = Reflect.decorate(decorators, target, key, desc);
2816
- else
2817
- for (var i = decorators.length - 1; i >= 0; i--)
2818
- if (d = decorators[i])
2819
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2820
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2821
- };
2822
- var WorkerSession = class {
2823
- constructor({ getServices, systemPort, appPort, options = {
2824
- heartbeatInterval: 1e3
2825
- } }) {
2826
- this._startTrigger = new Trigger5();
2827
- this.onClose = new Callback();
2828
- assert11(options);
2829
- assert11(getServices);
2830
- this._options = options;
2831
- this._getServices = getServices;
2832
- this._clientRpc = createProtoRpcPeer3({
2833
- exposed: clientServiceBundle,
2834
- handlers: {
2835
- HaloInvitationsService: async () => (await this._getServices()).services.HaloInvitationsService,
2836
- DevicesService: async () => (await this._getServices()).services.DevicesService,
2837
- SpaceInvitationsService: async () => (await this._getServices()).services.SpaceInvitationsService,
2838
- SpacesService: async () => (await this._getServices()).services.SpacesService,
2839
- NetworkService: async () => (await this._getServices()).services.NetworkService,
2840
- SpaceService: async () => (await this._getServices()).services.SpaceService,
2841
- DataService: async () => (await this._getServices()).services.DataService,
2842
- ProfileService: async () => (await this._getServices()).services.ProfileService,
2843
- SystemService: async () => (await this._getServices()).services.SystemService,
2844
- DevtoolsHost: async () => (await this._getServices()).services.DevtoolsHost,
2845
- TracingService: async () => (await this._getServices()).services.TracingService
2846
- },
2847
- port: appPort
2848
- });
2849
- this._iframeRpc = createProtoRpcPeer3({
2850
- requested: iframeServiceBundle,
2851
- exposed: workerServiceBundle,
2852
- handlers: {
2853
- WorkerService: {
2854
- start: async (request) => {
2855
- this.origin = request.origin;
2856
- this._startTrigger.wake();
2857
- },
2858
- stop: async () => {
2859
- setTimeout(async () => {
2860
- try {
2861
- await this.close();
2862
- } catch (err) {
2863
- log12.catch(err, {}, {
2864
- file: "worker-session.ts",
2865
- line: 90,
2866
- scope: this,
2867
- callSite: (f, a) => f(...a)
2868
- });
2869
- }
2870
- });
2871
- }
2872
- }
2873
- },
2874
- port: systemPort,
2875
- timeout: 1e3
2876
- // With low timeout heartbeat may fail if the tab's thread is saturated.
2877
- });
2878
- this.bridgeService = this._iframeRpc.rpc.BridgeService;
2879
- }
2880
- async open() {
2881
- log12.info("opening..", {}, {
2882
- file: "worker-session.ts",
2883
- line: 104,
2884
- scope: this,
2885
- callSite: (f, a) => f(...a)
2886
- });
2887
- await Promise.all([
2888
- this._clientRpc.open(),
2889
- this._iframeRpc.open()
2890
- ]);
2891
- await this._startTrigger.wait({
2892
- timeout: 3e3
2893
- });
2894
- this._heartbeatTimer = setInterval(async () => {
2895
- try {
2896
- await this._iframeRpc.rpc.IframeService.heartbeat();
2897
- } catch (err1) {
2898
- log12.warn("Heartbeat failed", {
2899
- err: err1
2900
- }, {
2901
- file: "worker-session.ts",
2902
- line: 116,
2903
- scope: this,
2904
- callSite: (f, a) => f(...a)
2905
- });
2906
- try {
2907
- await this.close();
2908
- } catch (err) {
2909
- log12.catch(err, {}, {
2910
- file: "worker-session.ts",
2911
- line: 120,
2912
- scope: this,
2913
- callSite: (f, a) => f(...a)
2914
- });
2915
- }
2916
- }
2917
- }, this._options.heartbeatInterval);
2918
- }
2919
- async close() {
2920
- log12.info("closing..", {}, {
2921
- file: "worker-session.ts",
2922
- line: 127,
2923
- scope: this,
2924
- callSite: (f, a) => f(...a)
2925
- });
2926
- try {
2927
- await this.onClose.callIfSet();
2928
- } catch (err) {
2929
- log12.catch(err, {}, {
2930
- file: "worker-session.ts",
2931
- line: 131,
2932
- scope: this,
2933
- callSite: (f, a) => f(...a)
2934
- });
2935
- }
2936
- if (this._heartbeatTimer !== void 0) {
2937
- clearInterval(this._heartbeatTimer);
2938
- }
2939
- await Promise.all([
2940
- this._clientRpc.close(),
2941
- this._iframeRpc.close()
2942
- ]);
2943
- }
2944
- };
2945
- __decorate3([
2946
- logInfo
2947
- ], WorkerSession.prototype, "origin", void 0);
2948
-
2949
- // packages/sdk/client-services/src/packlets/vault/worker-runtime.ts
2950
- var WorkerRuntime = class {
2951
- // prettier-ignore
2952
- constructor(_configProvider) {
2953
- this._configProvider = _configProvider;
2954
- this._transportFactory = new WebRTCTransportProxyFactory();
2955
- this._ready = new Trigger6();
2956
- this.sessions = /* @__PURE__ */ new Set();
2957
- }
2958
- async start() {
2959
- try {
2960
- this._config = await this._configProvider();
2961
- const signalServer = this._config.get("runtime.services.signal.server");
2962
- this._clientServices = new ClientServicesHost({
2963
- config: this._config,
2964
- networkManager: new NetworkManager({
2965
- log: true,
2966
- signalManager: signalServer ? new WebsocketSignalManager([
2967
- signalServer
2968
- ]) : new MemorySignalManager(new MemorySignalManagerContext()),
2969
- transportFactory: this._transportFactory
2970
- })
2971
- });
2972
- await this._clientServices.open();
2973
- this._ready.wake(void 0);
2974
- } catch (err) {
2975
- this._ready.wake(err);
2976
- }
2977
- }
2978
- async stop() {
2979
- await this._clientServices.close();
2980
- }
2981
- /**
2982
- * Create a new session.
2983
- */
2984
- async createSession({ appPort, systemPort }) {
2985
- const session = new WorkerSession({
2986
- getServices: async () => {
2987
- const error = await this._ready.wait();
2988
- if (error !== void 0) {
2989
- throw error;
2990
- }
2991
- return this._clientServices;
2992
- },
2993
- appPort,
2994
- systemPort,
2995
- readySignal: this._ready
2996
- });
2997
- session.onClose.set(async () => {
2998
- this.sessions.delete(session);
2999
- this._reconnectWebrtc();
3000
- });
3001
- await session.open();
3002
- this.sessions.add(session);
3003
- this._reconnectWebrtc();
3004
- }
3005
- /**
3006
- * Selects one of the existing session fro WebRTC networking.
3007
- */
3008
- _reconnectWebrtc() {
3009
- if (this._sessionForNetworking) {
3010
- if (!this.sessions.has(this._sessionForNetworking)) {
3011
- this._sessionForNetworking = void 0;
3012
- }
3013
- }
3014
- if (!this._sessionForNetworking) {
3015
- const selected = Array.from(this.sessions).find((session) => session.bridgeService);
3016
- if (selected) {
3017
- this._sessionForNetworking = selected;
3018
- this._transportFactory.setBridgeService(selected.bridgeService);
3019
- } else {
3020
- this._transportFactory.setBridgeService(void 0);
3021
- }
3022
- }
3023
- }
3024
- };
2
+ import {
3
+ AUTHENTICATION_CODE_LENGTH,
4
+ AbstractInvitationsHandler,
5
+ AbstractInvitationsProxy,
6
+ AbstractInvitationsService,
7
+ AuthenticatingInvitationProvider,
8
+ ClientServicesHost,
9
+ ClientServicesProxy,
10
+ DevtoolsHostEvents,
11
+ DevtoolsServiceImpl,
12
+ HaloInvitationsHandler,
13
+ HaloInvitationsProxy,
14
+ HaloInvitationsServiceImpl,
15
+ IFrameHostRuntime,
16
+ IFrameProxyRuntime,
17
+ INVITATION_TIMEOUT,
18
+ Identity,
19
+ IdentityManager,
20
+ InvitationEncoder,
21
+ InvitationObservableProvider,
22
+ MemoryShellRuntime,
23
+ ON_CLOSE_DELAY,
24
+ ProfileServiceImpl,
25
+ ServiceContext,
26
+ ServiceRegistry,
27
+ ShellController,
28
+ ShellRuntimeImpl,
29
+ SpaceInvitationsHandler,
30
+ SpaceInvitationsProxy,
31
+ SpaceInvitationsServiceImpl,
32
+ SpaceServiceImpl,
33
+ SystemServiceImpl,
34
+ TracingServiceImpl,
35
+ TrustedKeySetAuthVerifier,
36
+ VaultResourceLock,
37
+ WorkerRuntime,
38
+ WorkerSession,
39
+ appServiceBundle,
40
+ clientServiceBundle,
41
+ createAuthProvider,
42
+ createDefaultModelFactory,
43
+ createStorageObjects,
44
+ getNetworkPeers,
45
+ iframeServiceBundle,
46
+ shellServiceBundle,
47
+ subscribeToFeedBlocks,
48
+ subscribeToFeeds,
49
+ subscribeToNetworkStatus,
50
+ subscribeToNetworkTopics,
51
+ subscribeToSignal,
52
+ subscribeToSpaces,
53
+ subscribeToSwarmInfo,
54
+ workerServiceBundle,
55
+ wrapObservable
56
+ } from "./chunk-ZPZBLOQW.mjs";
3025
57
  export {
3026
58
  AUTHENTICATION_CODE_LENGTH,
3027
59
  AbstractInvitationsHandler,
@@ -3032,40 +64,49 @@ export {
3032
64
  ClientServicesProxy,
3033
65
  DevtoolsHostEvents,
3034
66
  DevtoolsServiceImpl,
3035
- HaloAuthVerifier,
3036
67
  HaloInvitationsHandler,
3037
68
  HaloInvitationsProxy,
3038
69
  HaloInvitationsServiceImpl,
3039
- IFrameRuntime,
70
+ IFrameHostRuntime,
71
+ IFrameProxyRuntime,
3040
72
  INVITATION_TIMEOUT,
3041
73
  Identity,
3042
74
  IdentityManager,
3043
75
  InvitationEncoder,
3044
76
  InvitationObservableProvider,
77
+ MemoryShellRuntime,
3045
78
  ON_CLOSE_DELAY,
3046
79
  ProfileServiceImpl,
3047
80
  ServiceContext,
3048
81
  ServiceRegistry,
82
+ ShellController,
83
+ ShellRuntimeImpl,
3049
84
  SpaceInvitationsHandler,
3050
85
  SpaceInvitationsProxy,
3051
86
  SpaceInvitationsServiceImpl,
3052
87
  SpaceServiceImpl,
3053
88
  SystemServiceImpl,
3054
89
  TracingServiceImpl,
90
+ TrustedKeySetAuthVerifier,
91
+ VaultResourceLock,
3055
92
  WorkerRuntime,
3056
93
  WorkerSession,
94
+ appServiceBundle,
3057
95
  clientServiceBundle,
96
+ createAuthProvider,
3058
97
  createDefaultModelFactory,
3059
- createHaloAuthProvider,
3060
98
  createStorageObjects,
3061
99
  getNetworkPeers,
100
+ iframeServiceBundle,
101
+ shellServiceBundle,
3062
102
  subscribeToFeedBlocks,
3063
103
  subscribeToFeeds,
3064
104
  subscribeToNetworkStatus,
3065
105
  subscribeToNetworkTopics,
3066
- subscribeToSignalTrace,
106
+ subscribeToSignal,
3067
107
  subscribeToSpaces,
3068
108
  subscribeToSwarmInfo,
109
+ workerServiceBundle,
3069
110
  wrapObservable
3070
111
  };
3071
112
  //# sourceMappingURL=index.mjs.map