@dxos/client-services 0.4.10-main.d658471 → 0.4.10-main.d6ef25d

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 (80) hide show
  1. package/dist/lib/browser/{chunk-MYKBSRL5.mjs → chunk-BASAWGAA.mjs} +1232 -972
  2. package/dist/lib/browser/chunk-BASAWGAA.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +13 -3
  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 +9 -4
  7. package/dist/lib/browser/packlets/testing/index.mjs.map +3 -3
  8. package/dist/lib/node/{chunk-UBE57IO7.cjs → chunk-4PLPSVK3.cjs} +1094 -917
  9. package/dist/lib/node/chunk-4PLPSVK3.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +49 -39
  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 +14 -9
  14. package/dist/lib/node/packlets/testing/index.cjs.map +3 -3
  15. package/dist/types/src/index.d.ts +1 -0
  16. package/dist/types/src/index.d.ts.map +1 -1
  17. package/dist/types/src/packlets/diagnostics/browser-diagnostics-broadcast.d.ts +5 -0
  18. package/dist/types/src/packlets/diagnostics/browser-diagnostics-broadcast.d.ts.map +1 -0
  19. package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts +5 -0
  20. package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts.map +1 -0
  21. package/dist/types/src/packlets/diagnostics/diagnostics-collector.d.ts +15 -0
  22. package/dist/types/src/packlets/diagnostics/diagnostics-collector.d.ts.map +1 -0
  23. package/dist/types/src/packlets/{services → diagnostics}/diagnostics.d.ts +1 -1
  24. package/dist/types/src/packlets/diagnostics/diagnostics.d.ts.map +1 -0
  25. package/dist/types/src/packlets/diagnostics/index.d.ts +4 -0
  26. package/dist/types/src/packlets/diagnostics/index.d.ts.map +1 -0
  27. package/dist/types/src/packlets/indexing/util.d.ts +2 -1
  28. package/dist/types/src/packlets/indexing/util.d.ts.map +1 -1
  29. package/dist/types/src/packlets/invitations/index.d.ts +1 -0
  30. package/dist/types/src/packlets/invitations/index.d.ts.map +1 -1
  31. package/dist/types/src/packlets/invitations/invitation-extension.d.ts +1 -0
  32. package/dist/types/src/packlets/invitations/invitation-extension.d.ts.map +1 -1
  33. package/dist/types/src/packlets/invitations/invitations-handler.d.ts +4 -2
  34. package/dist/types/src/packlets/invitations/invitations-handler.d.ts.map +1 -1
  35. package/dist/types/src/packlets/invitations/invitations-manager.d.ts +42 -0
  36. package/dist/types/src/packlets/invitations/invitations-manager.d.ts.map +1 -0
  37. package/dist/types/src/packlets/invitations/invitations-service.d.ts +7 -23
  38. package/dist/types/src/packlets/invitations/invitations-service.d.ts.map +1 -1
  39. package/dist/types/src/packlets/services/index.d.ts +1 -1
  40. package/dist/types/src/packlets/services/index.d.ts.map +1 -1
  41. package/dist/types/src/packlets/services/service-context.d.ts +2 -0
  42. package/dist/types/src/packlets/services/service-context.d.ts.map +1 -1
  43. package/dist/types/src/packlets/services/service-host.d.ts +5 -1
  44. package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
  45. package/dist/types/src/packlets/services/util.d.ts +1 -0
  46. package/dist/types/src/packlets/services/util.d.ts.map +1 -1
  47. package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
  48. package/dist/types/src/packlets/system/system-service.d.ts +1 -1
  49. package/dist/types/src/packlets/system/system-service.d.ts.map +1 -1
  50. package/dist/types/src/packlets/testing/test-builder.d.ts +3 -1
  51. package/dist/types/src/packlets/testing/test-builder.d.ts.map +1 -1
  52. package/dist/types/src/version.d.ts +1 -1
  53. package/package.json +35 -34
  54. package/src/index.ts +1 -0
  55. package/src/packlets/diagnostics/browser-diagnostics-broadcast.ts +94 -0
  56. package/src/packlets/diagnostics/diagnostics-broadcast.ts +20 -0
  57. package/src/packlets/diagnostics/diagnostics-collector.ts +65 -0
  58. package/src/packlets/{services → diagnostics}/diagnostics.ts +2 -2
  59. package/src/packlets/diagnostics/index.ts +7 -0
  60. package/src/packlets/indexing/util.ts +15 -8
  61. package/src/packlets/invitations/index.ts +1 -0
  62. package/src/packlets/invitations/invitation-extension.ts +28 -1
  63. package/src/packlets/invitations/invitations-handler.ts +74 -34
  64. package/src/packlets/invitations/invitations-manager.ts +197 -0
  65. package/src/packlets/invitations/invitations-service.ts +21 -168
  66. package/src/packlets/services/automerge-host.test.ts +10 -4
  67. package/src/packlets/services/index.ts +1 -1
  68. package/src/packlets/services/service-context.test.ts +4 -1
  69. package/src/packlets/services/service-context.ts +16 -3
  70. package/src/packlets/services/service-host.ts +34 -19
  71. package/src/packlets/services/util.ts +2 -0
  72. package/src/packlets/spaces/data-space-manager.test.ts +4 -4
  73. package/src/packlets/spaces/data-space.ts +1 -1
  74. package/src/packlets/storage/level.ts +1 -1
  75. package/src/packlets/system/system-service.ts +1 -1
  76. package/src/packlets/testing/test-builder.ts +20 -4
  77. package/src/version.ts +1 -1
  78. package/dist/lib/browser/chunk-MYKBSRL5.mjs.map +0 -7
  79. package/dist/lib/node/chunk-UBE57IO7.cjs.map +0 -7
  80. package/dist/types/src/packlets/services/diagnostics.d.ts.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/client-services",
3
- "version": "0.4.10-main.d658471",
3
+ "version": "0.4.10-main.d6ef25d",
4
4
  "description": "DXOS client services implementation",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -10,6 +10,7 @@
10
10
  "browser": {
11
11
  "jsondown": false,
12
12
  "./src/packlets/locks/node.ts": "./src/packlets/locks/browser.ts",
13
+ "./src/packlets/diagnostics/diagnostics-broadcast.ts": "./src/packlets/diagnostics/browser-diagnostics-broadcast.ts",
13
14
  "./dist/lib/node/index.cjs": "./dist/lib/browser/index.mjs",
14
15
  "./testing.js": "./dist/lib/browser/packlets/testing/index.mjs"
15
16
  },
@@ -23,43 +24,43 @@
23
24
  "dependencies": {
24
25
  "level": "^8.0.1",
25
26
  "platform": "^1.3.6",
26
- "@dxos/async": "0.4.10-main.d658471",
27
- "@dxos/automerge": "0.4.10-main.d658471",
28
- "@dxos/codec-protobuf": "0.4.10-main.d658471",
29
- "@dxos/client-protocol": "0.4.10-main.d658471",
30
- "@dxos/context": "0.4.10-main.d658471",
31
- "@dxos/config": "0.4.10-main.d658471",
32
- "@dxos/credentials": "0.4.10-main.d658471",
33
- "@dxos/debug": "0.4.10-main.d658471",
34
- "@dxos/crypto": "0.4.10-main.d658471",
35
- "@dxos/echo-db": "0.4.10-main.d658471",
36
- "@dxos/echo-schema": "0.4.10-main.d658471",
37
- "@dxos/echo-pipeline": "0.4.10-main.d658471",
38
- "@dxos/indexing": "0.4.10-main.d658471",
39
- "@dxos/keyring": "0.4.10-main.d658471",
40
- "@dxos/invariant": "0.4.10-main.d658471",
41
- "@dxos/keys": "0.4.10-main.d658471",
42
- "@dxos/feed-store": "0.4.10-main.d658471",
43
- "@dxos/messaging": "0.4.10-main.d658471",
44
- "@dxos/lock-file": "0.4.10-main.d658471",
45
- "@dxos/log": "0.4.10-main.d658471",
46
- "@dxos/network-manager": "0.4.10-main.d658471",
47
- "@dxos/protocols": "0.4.10-main.d658471",
48
- "@dxos/random-access-storage": "0.4.10-main.d658471",
49
- "@dxos/node-std": "0.4.10-main.d658471",
50
- "@dxos/teleport": "0.4.10-main.d658471",
51
- "@dxos/rpc": "0.4.10-main.d658471",
52
- "@dxos/teleport-extension-gossip": "0.4.10-main.d658471",
53
- "@dxos/teleport-extension-object-sync": "0.4.10-main.d658471",
54
- "@dxos/timeframe": "0.4.10-main.d658471",
55
- "@dxos/tracing": "0.4.10-main.d658471",
56
- "@dxos/util": "0.4.10-main.d658471",
57
- "@dxos/websocket-rpc": "0.4.10-main.d658471"
27
+ "@dxos/async": "0.4.10-main.d6ef25d",
28
+ "@dxos/client-protocol": "0.4.10-main.d6ef25d",
29
+ "@dxos/automerge": "0.4.10-main.d6ef25d",
30
+ "@dxos/codec-protobuf": "0.4.10-main.d6ef25d",
31
+ "@dxos/config": "0.4.10-main.d6ef25d",
32
+ "@dxos/context": "0.4.10-main.d6ef25d",
33
+ "@dxos/crypto": "0.4.10-main.d6ef25d",
34
+ "@dxos/credentials": "0.4.10-main.d6ef25d",
35
+ "@dxos/debug": "0.4.10-main.d6ef25d",
36
+ "@dxos/echo-db": "0.4.10-main.d6ef25d",
37
+ "@dxos/echo-pipeline": "0.4.10-main.d6ef25d",
38
+ "@dxos/echo-schema": "0.4.10-main.d6ef25d",
39
+ "@dxos/feed-store": "0.4.10-main.d6ef25d",
40
+ "@dxos/invariant": "0.4.10-main.d6ef25d",
41
+ "@dxos/indexing": "0.4.10-main.d6ef25d",
42
+ "@dxos/keyring": "0.4.10-main.d6ef25d",
43
+ "@dxos/keys": "0.4.10-main.d6ef25d",
44
+ "@dxos/lock-file": "0.4.10-main.d6ef25d",
45
+ "@dxos/messaging": "0.4.10-main.d6ef25d",
46
+ "@dxos/log": "0.4.10-main.d6ef25d",
47
+ "@dxos/network-manager": "0.4.10-main.d6ef25d",
48
+ "@dxos/node-std": "0.4.10-main.d6ef25d",
49
+ "@dxos/random-access-storage": "0.4.10-main.d6ef25d",
50
+ "@dxos/protocols": "0.4.10-main.d6ef25d",
51
+ "@dxos/teleport": "0.4.10-main.d6ef25d",
52
+ "@dxos/rpc": "0.4.10-main.d6ef25d",
53
+ "@dxos/teleport-extension-gossip": "0.4.10-main.d6ef25d",
54
+ "@dxos/teleport-extension-object-sync": "0.4.10-main.d6ef25d",
55
+ "@dxos/tracing": "0.4.10-main.d6ef25d",
56
+ "@dxos/timeframe": "0.4.10-main.d6ef25d",
57
+ "@dxos/websocket-rpc": "0.4.10-main.d6ef25d",
58
+ "@dxos/util": "0.4.10-main.d6ef25d"
58
59
  },
59
60
  "devDependencies": {
60
61
  "@types/platform": "^1.3.4",
61
62
  "@types/readable-stream": "^2.3.9",
62
- "@dxos/signal": "0.4.10-main.d658471"
63
+ "@dxos/signal": "0.4.10-main.d6ef25d"
63
64
  },
64
65
  "publishConfig": {
65
66
  "access": "public"
package/src/index.ts CHANGED
@@ -10,3 +10,4 @@ export * from './packlets/spaces';
10
10
  export * from './packlets/storage';
11
11
  export * from './packlets/vault';
12
12
  export * from './packlets/locks';
13
+ export * from './packlets/diagnostics';
@@ -0,0 +1,94 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { Trigger } from '@dxos/async';
6
+ import { log } from '@dxos/log';
7
+ import { type SystemService } from '@dxos/protocols/proto/dxos/client/services';
8
+
9
+ import {
10
+ type CollectDiagnosticsBroadcastSender,
11
+ type CollectDiagnosticsBroadcastHandler,
12
+ } from './diagnostics-collector';
13
+
14
+ const CHANNEL_NAME = 'dxos.diagnostics.broadcast';
15
+
16
+ enum MessageType {
17
+ PROBE = 'probe',
18
+ PROBE_ACK = 'probe-ack',
19
+ REQUEST_DIAGNOSTICS = 'request-diagnostics',
20
+ RECEIVE_DIAGNOSTICS = 'receive-diagnostics',
21
+ }
22
+
23
+ interface Message {
24
+ type: MessageType;
25
+ payload?: any;
26
+ }
27
+
28
+ export const createCollectDiagnosticsBroadcastSender = (): CollectDiagnosticsBroadcastSender => {
29
+ return {
30
+ broadcastDiagnosticsRequest: async () => {
31
+ let expectedResponse = MessageType.PROBE_ACK;
32
+ let channel: BroadcastChannel | undefined;
33
+ try {
34
+ const trigger = new Trigger<Message>();
35
+ channel = new BroadcastChannel(CHANNEL_NAME);
36
+ channel.onmessage = (msg) => {
37
+ if (expectedResponse === msg.data.type) {
38
+ trigger.wake(msg.data);
39
+ }
40
+ };
41
+ channel.postMessage({ type: MessageType.PROBE });
42
+ await trigger.wait({ timeout: 200 });
43
+ expectedResponse = MessageType.RECEIVE_DIAGNOSTICS;
44
+ trigger.reset();
45
+ channel.postMessage({ type: MessageType.REQUEST_DIAGNOSTICS });
46
+ const diagnostics = await trigger.wait({ timeout: 5000 });
47
+ return diagnostics.payload;
48
+ } catch (e) {
49
+ const errorDescription = e instanceof Error ? e.message : JSON.stringify(e);
50
+ return { expectedResponse, errorDescription };
51
+ } finally {
52
+ safeClose(channel);
53
+ }
54
+ },
55
+ };
56
+ };
57
+
58
+ export const createCollectDiagnosticsBroadcastHandler = (
59
+ systemService: SystemService,
60
+ ): CollectDiagnosticsBroadcastHandler => {
61
+ let channel: BroadcastChannel | undefined;
62
+ return {
63
+ start: () => {
64
+ channel = new BroadcastChannel(CHANNEL_NAME);
65
+ channel.onmessage = async (message) => {
66
+ try {
67
+ if (message.data.type === MessageType.PROBE) {
68
+ channel?.postMessage({ type: MessageType.PROBE_ACK });
69
+ } else if (message.data.type === MessageType.REQUEST_DIAGNOSTICS) {
70
+ const diagnostics = await systemService.getDiagnostics({});
71
+ channel?.postMessage({
72
+ type: MessageType.RECEIVE_DIAGNOSTICS,
73
+ payload: diagnostics,
74
+ });
75
+ }
76
+ } catch (error) {
77
+ log.catch(error);
78
+ }
79
+ };
80
+ },
81
+ stop: () => {
82
+ safeClose(channel);
83
+ channel = undefined;
84
+ },
85
+ };
86
+ };
87
+
88
+ const safeClose = (channel?: BroadcastChannel) => {
89
+ try {
90
+ channel?.close();
91
+ } catch (e) {
92
+ // ignored
93
+ }
94
+ };
@@ -0,0 +1,20 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+ import { type SystemService } from '@dxos/protocols/proto/dxos/client/services';
5
+
6
+ import {
7
+ type CollectDiagnosticsBroadcastSender,
8
+ type CollectDiagnosticsBroadcastHandler,
9
+ } from './diagnostics-collector';
10
+
11
+ export const createCollectDiagnosticsBroadcastSender = (): CollectDiagnosticsBroadcastSender => {
12
+ return { broadcastDiagnosticsRequest: async () => undefined };
13
+ };
14
+
15
+ export const createCollectDiagnosticsBroadcastHandler = (_: SystemService): CollectDiagnosticsBroadcastHandler => {
16
+ return {
17
+ start: () => {},
18
+ stop: () => {},
19
+ };
20
+ };
@@ -0,0 +1,65 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { type ClientServicesProvider } from '@dxos/client-protocol';
6
+ import { type Config, ConfigResource } from '@dxos/config';
7
+ import { GetDiagnosticsRequest } from '@dxos/protocols/proto/dxos/client/services';
8
+ import { TRACE_PROCESSOR } from '@dxos/tracing';
9
+ import { type JsonKeyOptions, jsonKeyReplacer, nonNullable } from '@dxos/util';
10
+
11
+ import { createCollectDiagnosticsBroadcastSender } from './diagnostics-broadcast';
12
+ import { ClientServicesProviderResource } from '../services';
13
+
14
+ export interface CollectDiagnosticsBroadcastSender {
15
+ broadcastDiagnosticsRequest(): any;
16
+ }
17
+
18
+ export interface CollectDiagnosticsBroadcastHandler {
19
+ start(): void;
20
+ stop(): void;
21
+ }
22
+
23
+ export class DiagnosticsCollector {
24
+ private static broadcastSender = createCollectDiagnosticsBroadcastSender();
25
+
26
+ public static async collect(
27
+ config: Config | Config[] = findConfigs(),
28
+ services: ClientServicesProvider | null = findSystemServiceProvider(),
29
+ options: JsonKeyOptions = {},
30
+ ): Promise<any> {
31
+ const serviceDiagnostics = await services?.services?.SystemService?.getDiagnostics({
32
+ keys: options.humanize
33
+ ? GetDiagnosticsRequest.KEY_OPTION.HUMANIZE
34
+ : options.truncate
35
+ ? GetDiagnosticsRequest.KEY_OPTION.TRUNCATE
36
+ : undefined,
37
+ });
38
+
39
+ const clientDiagnostics = {
40
+ config,
41
+ trace: TRACE_PROCESSOR.getDiagnostics(),
42
+ };
43
+
44
+ const diagnostics =
45
+ serviceDiagnostics != null
46
+ ? { client: clientDiagnostics, services: serviceDiagnostics }
47
+ : {
48
+ client: clientDiagnostics,
49
+ broadcast: await this.broadcastSender.broadcastDiagnosticsRequest(),
50
+ };
51
+
52
+ return JSON.parse(JSON.stringify(diagnostics, jsonKeyReplacer(options)));
53
+ }
54
+ }
55
+
56
+ const findSystemServiceProvider = (): ClientServicesProvider | null => {
57
+ const serviceProviders = TRACE_PROCESSOR.findByAnnotation(ClientServicesProviderResource);
58
+ const providerResource = serviceProviders.find((r) => r.instance.deref()?.services?.SystemService != null);
59
+ return providerResource?.instance?.deref() ?? null;
60
+ };
61
+
62
+ const findConfigs = (): Config[] => {
63
+ const configs = TRACE_PROCESSOR.findByAnnotation(ConfigResource);
64
+ return configs.map((r) => r.instance.deref()).filter(nonNullable);
65
+ };
@@ -25,9 +25,9 @@ import { type Epoch } from '@dxos/protocols/proto/dxos/halo/credentials';
25
25
  import { type Resource, type Span } from '@dxos/protocols/proto/dxos/tracing';
26
26
  import { TRACE_PROCESSOR } from '@dxos/tracing';
27
27
 
28
- import { getPlatform } from './platform';
29
- import { type ServiceContext } from './service-context';
30
28
  import { DXOS_VERSION } from '../../version';
29
+ import { type ServiceContext } from '../services';
30
+ import { getPlatform } from '../services/platform';
31
31
  import { type DataSpace } from '../spaces';
32
32
 
33
33
  const DEFAULT_TIMEOUT = 1_000;
@@ -0,0 +1,7 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ export * from './diagnostics';
6
+ export * from './diagnostics-collector';
7
+ export * from './diagnostics-broadcast';
@@ -3,11 +3,10 @@
3
3
  //
4
4
 
5
5
  import { getHeads } from '@dxos/automerge/automerge';
6
- import { type DocHandle } from '@dxos/automerge/automerge-repo';
7
- import { warnAfterTimeout } from '@dxos/debug';
6
+ import { type DocumentId, type DocHandle } from '@dxos/automerge/automerge-repo';
8
7
  import { type AutomergeHost } from '@dxos/echo-pipeline';
9
8
  import { type ObjectSnapshot } from '@dxos/indexing';
10
- import { idCodec } from '@dxos/protocols';
9
+ import { type ObjectPointerEncoded, idCodec } from '@dxos/protocols';
11
10
 
12
11
  /**
13
12
  * Factory for `loadDocuments` iterator.
@@ -18,11 +17,15 @@ export const createSelectedDocumentsIterator = (automergeHost: AutomergeHost) =>
18
17
  * @param ids
19
18
  */
20
19
  // TODO(mykola): Unload automerge handles after usage.
21
- async function* loadDocuments(ids: string[]) {
20
+ async function* loadDocuments(ids: ObjectPointerEncoded[]) {
22
21
  for (const id of ids) {
23
22
  const { documentId, objectId } = idCodec.decode(id);
24
- const handle = automergeHost.repo.find(documentId as any);
25
- await warnAfterTimeout(5000, 'to long to load doc', () => handle.whenReady());
23
+ const handle =
24
+ automergeHost.repo.handles[documentId as DocumentId] ?? automergeHost.repo.find(documentId as DocumentId);
25
+ if (!handle.isReady()) {
26
+ // `whenReady` creates a timeout so we guard it with an if to skip it if the handle is already ready.
27
+ await handle.whenReady();
28
+ }
26
29
  const doc = handle.docSync();
27
30
  const hash = getHeads(doc).join('');
28
31
  yield doc.objects?.[objectId] ? [{ id, object: doc.objects[objectId], currentHash: hash }] : [];
@@ -47,7 +50,10 @@ export const createDocumentsIterator = (automergeHost: AutomergeHost) =>
47
50
  return;
48
51
  }
49
52
 
50
- await warnAfterTimeout(5000, 'to long to load doc', () => handle.whenReady());
53
+ if (!handle.isReady()) {
54
+ // `whenReady` creates a timeout so we guard it with an if to skip it if the handle is already ready.
55
+ await handle.whenReady();
56
+ }
51
57
  const doc = handle.docSync();
52
58
 
53
59
  const heads = getHeads(doc);
@@ -67,7 +73,7 @@ export const createDocumentsIterator = (automergeHost: AutomergeHost) =>
67
73
  if (visited.has(id)) {
68
74
  continue;
69
75
  }
70
- const linkHandle = automergeHost.repo.find(id as any);
76
+ const linkHandle = automergeHost.repo.handles[id as DocumentId] ?? automergeHost.repo.find(id as DocumentId);
71
77
  for await (const result of getObjectsFromHandle(linkHandle)) {
72
78
  yield result;
73
79
  }
@@ -77,6 +83,7 @@ export const createDocumentsIterator = (automergeHost: AutomergeHost) =>
77
83
  visited.add(handle.documentId);
78
84
  }
79
85
 
86
+ // TODO(mykola): Use list of roots instead of iterating over all handles.
80
87
  for (const handle of Object.values(automergeHost.repo.handles)) {
81
88
  if (visited.has(handle.documentId)) {
82
89
  continue;
@@ -7,3 +7,4 @@ export * from './invitation-protocol';
7
7
  export * from './invitations-handler';
8
8
  export * from './invitations-service';
9
9
  export * from './space-invitation-protocol';
10
+ export * from './invitations-manager';
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { Trigger } from '@dxos/async';
6
6
  import { cancelWithContext, Context } from '@dxos/context';
7
+ import { randomBytes, verify } from '@dxos/crypto';
7
8
  import { invariant } from '@dxos/invariant';
8
9
  import { PublicKey } from '@dxos/keys';
9
10
  import { log } from '@dxos/log';
@@ -51,6 +52,8 @@ export class InvitationHostExtension extends RpcExtension<
51
52
  private _remoteOptions?: Options;
52
53
  private _remoteOptionsTrigger = new Trigger();
53
54
 
55
+ private _challenge?: Buffer = undefined;
56
+
54
57
  public invitation?: Invitation = undefined;
55
58
 
56
59
  public guestProfile?: ProfileDocument = undefined;
@@ -113,13 +116,17 @@ export class InvitationHostExtension extends RpcExtension<
113
116
 
114
117
  this._callbacks.onStateUpdate({ ...this.invitation, state: Invitation.State.READY_FOR_AUTHENTICATION });
115
118
 
119
+ this._challenge =
120
+ this.invitation.authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY ? randomBytes(32) : undefined;
121
+
116
122
  log.trace('dxos.sdk.invitation-handler.host.introduce', trace.end({ id: traceId }));
117
123
  return {
118
124
  authMethod: this.invitation.authMethod,
125
+ challenge: this._challenge,
119
126
  };
120
127
  },
121
128
 
122
- authenticate: async ({ authCode: code }) => {
129
+ authenticate: async ({ authCode: code, signedChallenge }) => {
123
130
  const traceId = PublicKey.random().toHex();
124
131
  log.trace('dxos.sdk.invitation-handler.host.authenticate', trace.begin({ id: traceId }));
125
132
  log('received authentication request', { authCode: code });
@@ -145,6 +152,26 @@ export class InvitationHostExtension extends RpcExtension<
145
152
  break;
146
153
  }
147
154
 
155
+ case Invitation.AuthMethod.KNOWN_PUBLIC_KEY: {
156
+ if (!this.invitation.guestKeypair) {
157
+ status = AuthenticationResponse.Status.INTERNAL_ERROR;
158
+ break;
159
+ }
160
+ const isSignatureValid =
161
+ this._challenge &&
162
+ verify(
163
+ this._challenge,
164
+ Buffer.from(signedChallenge ?? []),
165
+ this.invitation.guestKeypair.publicKey.asBuffer(),
166
+ );
167
+ if (isSignatureValid) {
168
+ this.authenticationPassed = true;
169
+ } else {
170
+ status = AuthenticationResponse.Status.INVALID_SIGNATURE;
171
+ }
172
+ break;
173
+ }
174
+
148
175
  default: {
149
176
  log.error('invalid authentication method', { authMethod: this.invitation.authMethod });
150
177
  status = AuthenticationResponse.Status.INTERNAL_ERROR;
@@ -11,6 +11,7 @@ import {
11
11
  } from '@dxos/client-protocol';
12
12
  import { Context } from '@dxos/context';
13
13
  import { generatePasscode } from '@dxos/credentials';
14
+ import { createKeyPair, sign } from '@dxos/crypto';
14
15
  import { invariant } from '@dxos/invariant';
15
16
  import { PublicKey } from '@dxos/keys';
16
17
  import { log } from '@dxos/log';
@@ -21,9 +22,9 @@ import {
21
22
  type SwarmConnection,
22
23
  } from '@dxos/network-manager';
23
24
  import { InvalidInvitationExtensionRoleError, trace } from '@dxos/protocols';
24
- import { Invitation } from '@dxos/protocols/proto/dxos/client/services';
25
+ import { type AdmissionKeypair, Invitation } from '@dxos/protocols/proto/dxos/client/services';
25
26
  import { type DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';
26
- import { AuthenticationResponse } from '@dxos/protocols/proto/dxos/halo/invitations';
27
+ import { AuthenticationResponse, type IntroductionResponse } from '@dxos/protocols/proto/dxos/halo/invitations';
27
28
 
28
29
  import {
29
30
  InvitationGuestExtension,
@@ -74,9 +75,11 @@ export class InvitationsHandler {
74
75
  state = Invitation.State.INIT,
75
76
  timeout = INVITATION_TIMEOUT,
76
77
  swarmKey = PublicKey.random(),
77
- persistent = true,
78
+ persistent = options?.authMethod !== Invitation.AuthMethod.KNOWN_PUBLIC_KEY, // default no not storing keypairs
78
79
  created = new Date(),
79
- lifetime = 86400, // 1 day
80
+ guestKeypair = undefined,
81
+ lifetime = 86400, // 1 day,
82
+ multiUse = false,
80
83
  } = options ?? {};
81
84
  const authCode =
82
85
  options?.authCode ??
@@ -91,9 +94,12 @@ export class InvitationsHandler {
91
94
  swarmKey,
92
95
  authCode,
93
96
  timeout,
94
- persistent,
97
+ persistent: persistent && type !== Invitation.Type.DELEGATED, // delegated invitations are persisted in control feed
98
+ guestKeypair:
99
+ guestKeypair ?? (authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY ? createAdmissionKeypair() : undefined),
95
100
  created,
96
101
  lifetime,
102
+ multiUse,
97
103
  ...protocol.getInvitationContext(),
98
104
  };
99
105
 
@@ -162,7 +168,7 @@ export class InvitationsHandler {
162
168
  }
163
169
  log.trace('dxos.sdk.invitations-handler.host.onOpen', trace.error({ id: traceId, error: err }));
164
170
  } finally {
165
- if (type !== Invitation.Type.MULTIUSE) {
171
+ if (!multiUse) {
166
172
  // Wait for graceful close before disposing.
167
173
  await swarmConnection.close();
168
174
  await ctx.dispose();
@@ -187,7 +193,7 @@ export class InvitationsHandler {
187
193
  return extension;
188
194
  };
189
195
 
190
- if (invitation.lifetime && invitation.created && invitation.lifetime !== 0) {
196
+ if (invitation.lifetime && invitation.created) {
191
197
  if (invitation.created.getTime() + invitation.lifetime * 1000 < Date.now()) {
192
198
  log.warn('invitation has already expired');
193
199
  } else {
@@ -245,7 +251,6 @@ export class InvitationsHandler {
245
251
  const { timeout = INVITATION_TIMEOUT } = invitation;
246
252
  invariant(protocol);
247
253
 
248
- // TODO(nf): duplicate check in InvitationsService
249
254
  if (deviceProfile) {
250
255
  invariant(invitation.kind === Invitation.Kind.DEVICE, 'deviceProfile provided for non-device invitation');
251
256
  }
@@ -317,26 +322,13 @@ export class InvitationsHandler {
317
322
 
318
323
  // 2. Get authentication code.
319
324
  if (isAuthenticationRequired(invitation)) {
320
- for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {
321
- log('guest waiting for authentication code...');
322
- setState({ state: Invitation.State.READY_FOR_AUTHENTICATION });
323
- const authCode = await authenticated.wait({ timeout });
324
-
325
- log('sending authentication request');
326
- setState({ state: Invitation.State.AUTHENTICATING });
327
- const response = await extension.rpc.InvitationHostService.authenticate({ authCode });
328
- if (response.status === undefined || response.status === AuthenticationResponse.Status.OK) {
325
+ switch (invitation.authMethod) {
326
+ case Invitation.AuthMethod.SHARED_SECRET:
327
+ await this._handleGuestOtpAuth(extension, setState, authenticated, { timeout });
328
+ break;
329
+ case Invitation.AuthMethod.KNOWN_PUBLIC_KEY:
330
+ await this._handleGuestKpkAuth(extension, setState, invitation, introductionResponse);
329
331
  break;
330
- }
331
-
332
- if (response.status === AuthenticationResponse.Status.INVALID_OTP) {
333
- if (attempt === MAX_OTP_ATTEMPTS) {
334
- throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);
335
- } else {
336
- log('retrying invalid code', { attempt });
337
- authenticated.reset();
338
- }
339
- }
340
332
  }
341
333
  }
342
334
 
@@ -423,13 +415,61 @@ export class InvitationsHandler {
423
415
 
424
416
  return observable;
425
417
  }
418
+
419
+ private async _handleGuestOtpAuth(
420
+ extension: InvitationGuestExtension,
421
+ setState: (newState: Partial<Invitation>) => void,
422
+ authenticated: Trigger<string>,
423
+ options: { timeout: number },
424
+ ) {
425
+ for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {
426
+ log('guest waiting for authentication code...');
427
+ setState({ state: Invitation.State.READY_FOR_AUTHENTICATION });
428
+ const authCode = await authenticated.wait(options);
429
+
430
+ log('sending authentication request');
431
+ setState({ state: Invitation.State.AUTHENTICATING });
432
+ const response = await extension.rpc.InvitationHostService.authenticate({ authCode });
433
+ if (response.status === undefined || response.status === AuthenticationResponse.Status.OK) {
434
+ break;
435
+ }
436
+
437
+ if (response.status === AuthenticationResponse.Status.INVALID_OTP) {
438
+ if (attempt === MAX_OTP_ATTEMPTS) {
439
+ throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);
440
+ } else {
441
+ log('retrying invalid code', { attempt });
442
+ authenticated.reset();
443
+ }
444
+ }
445
+ }
446
+ }
447
+
448
+ private async _handleGuestKpkAuth(
449
+ extension: InvitationGuestExtension,
450
+ setState: (newState: Partial<Invitation>) => void,
451
+ invitation: Invitation,
452
+ introductionResponse: IntroductionResponse,
453
+ ) {
454
+ if (invitation.guestKeypair?.privateKey == null) {
455
+ throw new Error('keypair missing in the invitation');
456
+ }
457
+ if (introductionResponse.challenge == null) {
458
+ throw new Error('challenge missing in the introduction');
459
+ }
460
+ log('sending authentication request');
461
+ setState({ state: Invitation.State.AUTHENTICATING });
462
+ const signature = sign(Buffer.from(introductionResponse.challenge), invitation.guestKeypair.privateKey);
463
+ const response = await extension.rpc.InvitationHostService.authenticate({
464
+ signedChallenge: signature,
465
+ });
466
+ if (response.status !== AuthenticationResponse.Status.OK) {
467
+ throw new Error(`Authentication failed with code: ${response.status}`);
468
+ }
469
+ }
426
470
  }
427
471
 
428
- export const invitationExpired = (invitation: Invitation) => {
429
- return (
430
- invitation.created &&
431
- invitation.lifetime &&
432
- invitation.lifetime !== 0 &&
433
- invitation.created.getTime() + invitation.lifetime * 1000 < Date.now()
434
- );
472
+ export const createAdmissionKeypair = (): AdmissionKeypair => {
473
+ const keypair = createKeyPair();
474
+ return { publicKey: PublicKey.from(keypair.publicKey), privateKey: keypair.secretKey };
435
475
  };