@dxos/client-services 0.3.11-main.dafb7f2 → 0.3.11-main.df1e30a

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 (53) hide show
  1. package/dist/lib/browser/{chunk-TFTFBP6C.mjs → chunk-NA7EQA7E.mjs} +200 -103
  2. package/dist/lib/browser/chunk-NA7EQA7E.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +1 -1
  4. package/dist/lib/browser/index.mjs.map +1 -1
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/packlets/testing/index.mjs +4 -11
  7. package/dist/lib/browser/packlets/testing/index.mjs.map +3 -3
  8. package/dist/lib/node/{chunk-Y77542J4.cjs → chunk-LTQYCVFH.cjs} +283 -186
  9. package/dist/lib/node/chunk-LTQYCVFH.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +37 -37
  11. package/dist/lib/node/index.cjs.map +1 -1
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/packlets/testing/index.cjs +11 -18
  14. package/dist/lib/node/packlets/testing/index.cjs.map +3 -3
  15. package/dist/types/src/packlets/identity/identity-service.d.ts +3 -3
  16. package/dist/types/src/packlets/identity/identity-service.d.ts.map +1 -1
  17. package/dist/types/src/packlets/invitations/device-invitation-protocol.d.ts +2 -0
  18. package/dist/types/src/packlets/invitations/device-invitation-protocol.d.ts.map +1 -1
  19. package/dist/types/src/packlets/invitations/invitation-protocol.d.ts +28 -3
  20. package/dist/types/src/packlets/invitations/invitation-protocol.d.ts.map +1 -1
  21. package/dist/types/src/packlets/invitations/invitations-handler.d.ts.map +1 -1
  22. package/dist/types/src/packlets/invitations/space-invitation-protocol.d.ts +2 -0
  23. package/dist/types/src/packlets/invitations/space-invitation-protocol.d.ts.map +1 -1
  24. package/dist/types/src/packlets/services/diagnostics.d.ts +4 -0
  25. package/dist/types/src/packlets/services/diagnostics.d.ts.map +1 -1
  26. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  27. package/dist/types/src/packlets/spaces/automerge-space-state.d.ts +2 -0
  28. package/dist/types/src/packlets/spaces/automerge-space-state.d.ts.map +1 -1
  29. package/dist/types/src/packlets/spaces/data-space-manager.d.ts.map +1 -1
  30. package/dist/types/src/packlets/spaces/data-space.d.ts +1 -0
  31. package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
  32. package/dist/types/src/packlets/testing/invitation-utils.d.ts.map +1 -1
  33. package/dist/types/src/version.d.ts +1 -1
  34. package/package.json +35 -35
  35. package/src/packlets/identity/identity-manager.ts +1 -1
  36. package/src/packlets/identity/identity-service.test.ts +1 -1
  37. package/src/packlets/identity/identity-service.ts +6 -3
  38. package/src/packlets/invitations/device-invitation-protocol.test.ts +14 -0
  39. package/src/packlets/invitations/device-invitation-protocol.ts +14 -0
  40. package/src/packlets/invitations/invitation-protocol.ts +44 -6
  41. package/src/packlets/invitations/invitations-handler.ts +20 -18
  42. package/src/packlets/invitations/space-invitation-protocol.test.ts +28 -0
  43. package/src/packlets/invitations/space-invitation-protocol.ts +11 -0
  44. package/src/packlets/services/diagnostics.ts +18 -0
  45. package/src/packlets/services/service-host.ts +27 -12
  46. package/src/packlets/spaces/automerge-space-state.ts +4 -0
  47. package/src/packlets/spaces/data-space-manager.ts +5 -1
  48. package/src/packlets/spaces/data-space.ts +21 -1
  49. package/src/packlets/spaces/spaces-service.ts +1 -1
  50. package/src/packlets/testing/invitation-utils.ts +2 -10
  51. package/src/version.ts +1 -1
  52. package/dist/lib/browser/chunk-TFTFBP6C.mjs.map +0 -7
  53. package/dist/lib/node/chunk-Y77542J4.cjs.map +0 -7
@@ -2,24 +2,62 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { type Invitation } from '@dxos/protocols/proto/dxos/client/services';
6
- import { type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';
7
- import {
8
- type AdmissionRequest,
9
- type AdmissionResponse,
10
- type IntroductionRequest,
5
+ import type { ApiError } from '@dxos/protocols';
6
+ import type { Invitation } from '@dxos/protocols/proto/dxos/client/services';
7
+ import type { ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';
8
+ import type {
9
+ AdmissionRequest,
10
+ AdmissionResponse,
11
+ IntroductionRequest,
11
12
  } from '@dxos/protocols/proto/dxos/halo/invitations';
12
13
 
13
14
  export interface InvitationProtocol {
15
+ //
14
16
  // Debugging
17
+ //
18
+
19
+ /**
20
+ * Protocol-specific debug info to include in logs.
21
+ */
15
22
  toJSON(): object;
16
23
 
24
+ //
17
25
  // Host
26
+ //
27
+
28
+ /**
29
+ * Protocol-specific information to include in the invitation.
30
+ */
18
31
  getInvitationContext(): Partial<Invitation> & Pick<Invitation, 'kind'>;
32
+
33
+ /**
34
+ * Once authentication is successful, the host can admit the guest to the requested resource.
35
+ */
19
36
  admit(request: AdmissionRequest, guestProfile?: ProfileDocument): Promise<AdmissionResponse>;
20
37
 
38
+ //
21
39
  // Guest
40
+ //
41
+
42
+ /**
43
+ * Check if the invitation is valid.
44
+ *
45
+ * For example, the guest may already be a member of the space.
46
+ */
47
+ checkInvitation(invitation: Partial<Invitation>): ApiError | undefined;
48
+
49
+ /**
50
+ * Get profile information to send to the host to identify the guest.
51
+ */
22
52
  createIntroduction(): IntroductionRequest;
53
+
54
+ /**
55
+ * Get key information to send to the host in order to create an admission credential for the guest.
56
+ */
23
57
  createAdmissionRequest(): Promise<AdmissionRequest>;
58
+
59
+ /**
60
+ * Redeem the admission credential.
61
+ */
24
62
  accept(response: AdmissionResponse, request: AdmissionRequest): Promise<Partial<Invitation>>;
25
63
  }
@@ -303,9 +303,6 @@ export class InvitationsHandler {
303
303
  }
304
304
  }
305
305
  }
306
- } else {
307
- // Notify that introduction is complete even if auth is not required.
308
- setState({ state: Invitation.State.READY_FOR_AUTHENTICATION });
309
306
  }
310
307
 
311
308
  // 3. Send admission credentials to host (with local space keys).
@@ -321,7 +318,7 @@ export class InvitationsHandler {
321
318
 
322
319
  // 5. Success.
323
320
  log('admitted by host', { ...protocol.toJSON() });
324
- setState({ ...result, state: Invitation.State.SUCCESS });
321
+ setState({ ...result, target: invitation.target, state: Invitation.State.SUCCESS });
325
322
  log.trace('dxos.sdk.invitations-handler.guest.onOpen', trace.end({ id: traceId }));
326
323
  } catch (err: any) {
327
324
  if (err instanceof TimeoutError) {
@@ -355,20 +352,25 @@ export class InvitationsHandler {
355
352
  };
356
353
 
357
354
  scheduleTask(ctx, async () => {
358
- invariant(invitation.swarmKey);
359
- const topic = invitation.swarmKey;
360
- const swarmConnection = await this._networkManager.joinSwarm({
361
- topic,
362
- peerId: PublicKey.random(),
363
- protocolProvider: createTeleportProtocolFactory(async (teleport) => {
364
- teleport.addExtension('dxos.halo.invitations', createExtension());
365
- }),
366
- topology: new StarTopology(topic),
367
- label: 'invitation guest',
368
- });
369
- ctx.onDispose(() => swarmConnection.close());
370
-
371
- setState({ state: Invitation.State.CONNECTING });
355
+ const error = protocol.checkInvitation(invitation);
356
+ if (error) {
357
+ stream.error(error);
358
+ } else {
359
+ invariant(invitation.swarmKey);
360
+ const topic = invitation.swarmKey;
361
+ const swarmConnection = await this._networkManager.joinSwarm({
362
+ topic,
363
+ peerId: PublicKey.random(),
364
+ protocolProvider: createTeleportProtocolFactory(async (teleport) => {
365
+ teleport.addExtension('dxos.halo.invitations', createExtension());
366
+ }),
367
+ topology: new StarTopology(topic),
368
+ label: 'invitation guest',
369
+ });
370
+ ctx.onDispose(() => swarmConnection.close());
371
+
372
+ setState({ state: Invitation.State.CONNECTING });
373
+ }
372
374
  });
373
375
 
374
376
  const observable = new AuthenticatingInvitation({
@@ -7,6 +7,7 @@ import { expect } from 'chai';
7
7
  import { asyncChain, Trigger } from '@dxos/async';
8
8
  import { raise } from '@dxos/debug';
9
9
  import { testLocalDatabase } from '@dxos/echo-pipeline/testing';
10
+ import { AlreadyJoinedError } from '@dxos/protocols';
10
11
  import { Invitation } from '@dxos/protocols/proto/dxos/client/services';
11
12
  import { afterTest, describe, test } from '@dxos/test';
12
13
 
@@ -71,6 +72,33 @@ describe('services/space-invitations-protocol', () => {
71
72
  }
72
73
  });
73
74
 
75
+ test('invitation when already joined', async () => {
76
+ const [host, guest] = await asyncChain<ServiceContext>([createIdentity, closeAfterTest])(createPeers(2));
77
+
78
+ const space1 = await host.dataSpaceManager!.createSpace();
79
+ const spaceKey = space1.key;
80
+
81
+ await Promise.all(performInvitation({ host, guest, options: { kind: Invitation.Kind.SPACE, spaceKey } }));
82
+
83
+ {
84
+ const space1 = host.dataSpaceManager!.spaces.get(spaceKey)!;
85
+ const space2 = guest.dataSpaceManager!.spaces.get(spaceKey)!;
86
+ expect(space1).not.to.be.undefined;
87
+ expect(space2).not.to.be.undefined;
88
+
89
+ await host.dataSpaceManager?.waitUntilSpaceReady(space1.key);
90
+ await guest.dataSpaceManager?.waitUntilSpaceReady(space2.key);
91
+ }
92
+
93
+ const [_, guestResult] = performInvitation({
94
+ host,
95
+ guest,
96
+ options: { kind: Invitation.Kind.SPACE, spaceKey },
97
+ });
98
+
99
+ expect((await guestResult).error).to.be.instanceOf(AlreadyJoinedError);
100
+ });
101
+
74
102
  test('creates and accepts invitation with retry', async () => {
75
103
  const [host, guest] = await asyncChain<ServiceContext>([createIdentity, closeAfterTest])(createPeers(2));
76
104
 
@@ -8,6 +8,7 @@ import { invariant } from '@dxos/invariant';
8
8
  import { type Keyring } from '@dxos/keyring';
9
9
  import { type PublicKey } from '@dxos/keys';
10
10
  import { log } from '@dxos/log';
11
+ import { AlreadyJoinedError } from '@dxos/protocols';
11
12
  import { Invitation } from '@dxos/protocols/proto/dxos/client/services';
12
13
  import { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';
13
14
  import { type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';
@@ -76,6 +77,12 @@ export class SpaceInvitationProtocol implements InvitationProtocol {
76
77
  };
77
78
  }
78
79
 
80
+ checkInvitation(invitation: Partial<Invitation>) {
81
+ if (invitation.spaceKey && this._spaceManager.spaces.has(invitation.spaceKey)) {
82
+ return new AlreadyJoinedError('Already joined space.');
83
+ }
84
+ }
85
+
79
86
  createIntroduction(): IntroductionRequest {
80
87
  return {
81
88
  profile: this._signingContext.getProfile(),
@@ -104,6 +111,10 @@ export class SpaceInvitationProtocol implements InvitationProtocol {
104
111
  invariant(assertion['@type'] === 'dxos.halo.credentials.SpaceMember', 'Invalid credential');
105
112
  invariant(credential.subject.id.equals(this._signingContext.identityKey));
106
113
 
114
+ if (this._spaceManager.spaces.has(assertion.spaceKey)) {
115
+ throw new AlreadyJoinedError('Already joined space.');
116
+ }
117
+
107
118
  // Create local space.
108
119
  await this._spaceManager.acceptSpace({
109
120
  spaceKey: assertion.spaceKey,
@@ -48,6 +48,7 @@ export type Diagnostics = {
48
48
  swarms?: SwarmInfo[];
49
49
  feeds?: Partial<SubscribeToFeedsResponse.Feed>[];
50
50
  metrics?: Metrics;
51
+ storage?: { file: string; count: number }[];
51
52
  };
52
53
 
53
54
  // TODO(burdon): Normalize for ECHO/HALO.
@@ -95,6 +96,23 @@ export const createDiagnostics = async (
95
96
  }).catch(() => undefined);
96
97
  }
97
98
 
99
+ if (typeof navigator !== 'undefined' && navigator.storage) {
100
+ const map = new Map();
101
+ const dir = await navigator.storage.getDirectory();
102
+ for await (const filename of (dir as any)?.keys()) {
103
+ const idx = filename.indexOf('-', filename.indexOf('-') + 1);
104
+ if (idx === -1) {
105
+ continue;
106
+ }
107
+
108
+ map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);
109
+ }
110
+
111
+ diagnostics.storage = Array.from(map.entries())
112
+ .sort((a, b) => b[1] - a[1])
113
+ .map(([file, count]) => ({ file, count }));
114
+ }
115
+
98
116
  const identity = serviceContext.identityManager.identity;
99
117
  if (identity) {
100
118
  // Identity.
@@ -8,7 +8,7 @@ import { type Config } from '@dxos/config';
8
8
  import { Context } from '@dxos/context';
9
9
  import { DocumentModel } from '@dxos/document-model';
10
10
  import { DataServiceImpl } from '@dxos/echo-pipeline';
11
- import { type TypedObject, base } from '@dxos/echo-schema';
11
+ import { type TypedObject, base, getRawDoc } from '@dxos/echo-schema';
12
12
  import { invariant } from '@dxos/invariant';
13
13
  import { PublicKey } from '@dxos/keys';
14
14
  import { log } from '@dxos/log';
@@ -28,7 +28,7 @@ import { ServiceContext } from './service-context';
28
28
  import { ServiceRegistry } from './service-registry';
29
29
  import { DevicesServiceImpl } from '../devices';
30
30
  import { DevtoolsServiceImpl, DevtoolsHostEvents } from '../devtools';
31
- import { type CreateIdentityOptions, IdentityServiceImpl } from '../identity';
31
+ import { IdentityServiceImpl, type CreateIdentityOptions } from '../identity';
32
32
  import { InvitationsServiceImpl } from '../invitations';
33
33
  import { Lock, type ResourceLock } from '../locks';
34
34
  import { LoggingServiceImpl } from '../logging';
@@ -260,7 +260,7 @@ export class ClientServicesHost {
260
260
  SystemService: this._systemService,
261
261
 
262
262
  IdentityService: new IdentityServiceImpl(
263
- (params) => this._createIdentity(params),
263
+ (params, useAutomerge) => this._createIdentity(params, useAutomerge),
264
264
  this._serviceContext.identityManager,
265
265
  this._serviceContext.keyring,
266
266
  (profile) => this._serviceContext.broadcastProfileUpdate(profile),
@@ -351,21 +351,36 @@ export class ClientServicesHost {
351
351
  await this._callbacks?.onReset?.();
352
352
  }
353
353
 
354
- private async _createIdentity(params?: CreateIdentityOptions) {
354
+ private async _createIdentity(params: CreateIdentityOptions, useAutomerge: boolean) {
355
355
  const identity = await this._serviceContext.createIdentity(params);
356
356
 
357
357
  // Setup default space.
358
358
  await this._serviceContext.initialized.wait();
359
359
  const space = await this._serviceContext.dataSpaceManager!.createSpace();
360
- const obj: TypedObject = new Properties(undefined, { automerge: false });
360
+
361
+ const obj: TypedObject = new Properties(undefined, { automerge: useAutomerge });
361
362
  obj[defaultKey] = identity.identityKey.toHex();
362
- await this._serviceRegistry.services.DataService!.write({
363
- spaceKey: space.key,
364
- batch: {
365
- objects: [createGenesisMutationFromTypedObject(obj)],
366
- },
367
- });
368
- await this._serviceRegistry.services.DataService!.flush({ spaceKey: space.key });
363
+
364
+ if (!useAutomerge) {
365
+ await this._serviceRegistry.services.DataService!.write({
366
+ spaceKey: space.key,
367
+ batch: {
368
+ objects: [createGenesisMutationFromTypedObject(obj)],
369
+ },
370
+ });
371
+ await this._serviceRegistry.services.DataService!.flush({ spaceKey: space.key });
372
+ } else {
373
+ // TODO(dmaretskyi): Refactor this.
374
+ const automergeIndex = space.automergeSpaceState.rootUrl;
375
+ invariant(automergeIndex);
376
+ const document = await this._serviceContext.automergeHost.repo.find(automergeIndex as any);
377
+ await document.whenReady();
378
+
379
+ document.change((doc: any) => {
380
+ doc.objects ??= {};
381
+ doc.objects[obj[base]._id] = getRawDoc(obj).handle.docSync();
382
+ });
383
+ }
369
384
 
370
385
  return identity;
371
386
  }
@@ -9,6 +9,8 @@ export class AutomergeSpaceState implements CredentialProcessor {
9
9
  public rootUrl: string | undefined = undefined;
10
10
  public lastEpoch: SpecificCredential<Epoch> | undefined = undefined;
11
11
 
12
+ constructor(private readonly _onNewRoot: (rootUrl: string) => void) {}
13
+
12
14
  async processCredential(credential: Credential) {
13
15
  if (!checkCredentialType(credential, 'dxos.halo.credentials.Epoch')) {
14
16
  return;
@@ -17,6 +19,8 @@ export class AutomergeSpaceState implements CredentialProcessor {
17
19
  this.lastEpoch = credential;
18
20
  if (credential.subject.assertion.automergeRoot) {
19
21
  this.rootUrl = credential.subject.assertion.automergeRoot;
22
+
23
+ this._onNewRoot(this.rootUrl);
20
24
  }
21
25
  }
22
26
  }
@@ -143,6 +143,9 @@ export class DataSpaceManager {
143
143
  const space = await this._constructSpace(metadata);
144
144
 
145
145
  const automergeRoot = this._automergeHost.repo.create();
146
+ automergeRoot.change((doc: any) => {
147
+ doc.experimental_spaceKey = spaceKey.toHex();
148
+ });
146
149
 
147
150
  const credentials = await spaceGenesis(this._keyring, this._signingContext, space.inner, automergeRoot.url);
148
151
  await this._metadataStore.addSpace(metadata);
@@ -222,12 +225,13 @@ export class DataSpaceManager {
222
225
  credentialProvider: createAuthProvider(this._signingContext.credentialSigner),
223
226
  credentialAuthenticator: deferFunction(() => dataSpace.authVerifier.verifier),
224
227
  },
225
- onNetworkConnection: (session) => {
228
+ onAuthorizedConnection: (session) => {
226
229
  session.addExtension(
227
230
  'dxos.mesh.teleport.gossip',
228
231
  gossip.createExtension({ remotePeerId: session.remotePeerId }),
229
232
  );
230
233
  session.addExtension('dxos.mesh.teleport.notarization', dataSpace.notarizationPlugin.createExtension());
234
+ this._automergeHost.authorizeDevice(space.key, session.remotePeerId);
231
235
  session.addExtension('dxos.mesh.teleport.automerge', this._automergeHost.createExtension());
232
236
  },
233
237
  onAuthFailure: () => {
@@ -15,6 +15,7 @@ import {
15
15
  type AutomergeHost,
16
16
  } from '@dxos/echo-pipeline';
17
17
  import { type FeedStore } from '@dxos/feed-store';
18
+ import { failedInvariant } from '@dxos/invariant';
18
19
  import { type Keyring } from '@dxos/keyring';
19
20
  import { PublicKey } from '@dxos/keys';
20
21
  import { log } from '@dxos/log';
@@ -92,7 +93,7 @@ export class DataSpace {
92
93
  private readonly _automergeHost: AutomergeHost;
93
94
 
94
95
  // TODO(dmaretskyi): Move into Space?
95
- private readonly _automergeSpaceState = new AutomergeSpaceState();
96
+ private readonly _automergeSpaceState = new AutomergeSpaceState((rootUrl) => this._onNewAutomergeRoot(rootUrl));
96
97
 
97
98
  private _state = SpaceState.CLOSED;
98
99
 
@@ -363,6 +364,25 @@ export class DataSpace {
363
364
  }
364
365
  }
365
366
 
367
+ private _onNewAutomergeRoot(rootUrl: string) {
368
+ log.info('loading automerge root doc for space', { space: this.key, rootUrl });
369
+ const handle = this._automergeHost.repo.find(rootUrl as any);
370
+
371
+ queueMicrotask(async () => {
372
+ try {
373
+ await handle.whenReady();
374
+ const doc = handle.docSync() ?? failedInvariant();
375
+ if (!doc.experimental_spaceKey) {
376
+ handle.change((doc: any) => {
377
+ doc.experimental_spaceKey = this.key.toHex();
378
+ });
379
+ }
380
+ } catch (err) {
381
+ log.warn('error loading automerge root doc', { space: this.key, rootUrl, err });
382
+ }
383
+ });
384
+ }
385
+
366
386
  // TODO(dmaretskyi): Use profile from signing context.
367
387
  async updateOwnProfile(profile: ProfileDocument) {
368
388
  const credential = await this._signingContext.credentialSigner.createCredential({
@@ -41,7 +41,7 @@ export class SpacesServiceImpl implements SpacesService {
41
41
 
42
42
  async createSpace(): Promise<Space> {
43
43
  if (!this._identityManager.identity) {
44
- throw new Error('This device has no HALO identity available. See https://docs.dxos.org/guide/halo');
44
+ throw new Error('This device has no HALO identity available. See https://docs.dxos.org/guide/platform/halo');
45
45
  }
46
46
 
47
47
  const dataSpaceManager = await this._getDataSpaceManager();
@@ -3,7 +3,7 @@
3
3
  //
4
4
 
5
5
  import { Trigger } from '@dxos/async';
6
- import { type AuthenticatingInvitation, type CancellableInvitation } from '@dxos/client-protocol';
6
+ import { InvitationEncoder, type AuthenticatingInvitation, type CancellableInvitation } from '@dxos/client-protocol';
7
7
  import { invariant } from '@dxos/invariant';
8
8
  import { Invitation } from '@dxos/protocols/proto/dxos/client/services';
9
9
 
@@ -13,15 +13,7 @@ import { ServiceContext } from '../services';
13
13
  * Strip secrets from invitation before giving it to the peer.
14
14
  */
15
15
  export const sanitizeInvitation = (invitation: Invitation): Invitation => {
16
- return {
17
- invitationId: invitation.invitationId,
18
- type: invitation.type,
19
- kind: invitation.kind,
20
- authMethod: invitation.authMethod,
21
- swarmKey: invitation.swarmKey,
22
- state: invitation.state,
23
- timeout: invitation.timeout,
24
- };
16
+ return InvitationEncoder.decode(InvitationEncoder.encode(invitation));
25
17
  };
26
18
 
27
19
  export type InvitationHost = {
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const DXOS_VERSION = "0.3.11-main.dafb7f2";
1
+ export const DXOS_VERSION = "0.3.11-main.df1e30a";