@dxos/client-services 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/chunk-client-services-layer.mjs +11425 -0
- package/dist/lib/chunk-client-services-layer.mjs.map +1 -0
- package/dist/lib/chunk-decorate.mjs +9 -0
- package/dist/lib/index.mjs +731 -0
- package/dist/lib/index.mjs.map +1 -0
- package/dist/lib/packlets/diagnostics/browser-diagnostics-broadcast.mjs +72 -0
- package/dist/lib/packlets/diagnostics/browser-diagnostics-broadcast.mjs.map +1 -0
- package/dist/lib/packlets/diagnostics/diagnostics-broadcast.mjs +14 -0
- package/dist/lib/packlets/diagnostics/diagnostics-broadcast.mjs.map +1 -0
- package/dist/lib/packlets/locks/browser.mjs +105 -0
- package/dist/lib/packlets/locks/browser.mjs.map +1 -0
- package/dist/lib/packlets/locks/node.mjs +53 -0
- package/dist/lib/packlets/locks/node.mjs.map +1 -0
- package/dist/lib/testing.mjs +570 -0
- package/dist/lib/testing.mjs.map +1 -0
- package/dist/types/src/index.d.ts +2 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/packlets/agents/edge-agent-manager.d.ts +21 -4
- package/dist/types/src/packlets/agents/edge-agent-manager.d.ts.map +1 -1
- package/dist/types/src/packlets/agents/edge-agent-service.d.ts +8 -7
- package/dist/types/src/packlets/agents/edge-agent-service.d.ts.map +1 -1
- package/dist/types/src/packlets/devices/devices-service.d.ts +7 -5
- package/dist/types/src/packlets/devices/devices-service.d.ts.map +1 -1
- package/dist/types/src/packlets/devtools/devtools.d.ts +30 -29
- package/dist/types/src/packlets/devtools/devtools.d.ts.map +1 -1
- package/dist/types/src/packlets/devtools/feeds.d.ts +1 -1
- package/dist/types/src/packlets/devtools/feeds.d.ts.map +1 -1
- package/dist/types/src/packlets/devtools/network.d.ts +2 -1
- package/dist/types/src/packlets/devtools/network.d.ts.map +1 -1
- package/dist/types/src/packlets/devtools/spaces.d.ts.map +1 -1
- package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts +2 -2
- package/dist/types/src/packlets/diagnostics/diagnostics-broadcast.d.ts.map +1 -1
- package/dist/types/src/packlets/diagnostics/diagnostics-collector.d.ts.map +1 -1
- package/dist/types/src/packlets/diagnostics/diagnostics.d.ts +1 -8
- package/dist/types/src/packlets/diagnostics/diagnostics.d.ts.map +1 -1
- package/dist/types/src/packlets/identity/authenticator.d.ts +1 -1
- package/dist/types/src/packlets/identity/authenticator.d.ts.map +1 -1
- package/dist/types/src/packlets/identity/contacts-service.d.ts +9 -6
- package/dist/types/src/packlets/identity/contacts-service.d.ts.map +1 -1
- package/dist/types/src/packlets/identity/identity-manager.d.ts +32 -3
- package/dist/types/src/packlets/identity/identity-manager.d.ts.map +1 -1
- package/dist/types/src/packlets/identity/identity-recovery-manager.d.ts +23 -4
- package/dist/types/src/packlets/identity/identity-recovery-manager.d.ts.map +1 -1
- package/dist/types/src/packlets/identity/identity-service.d.ts +15 -20
- package/dist/types/src/packlets/identity/identity-service.d.ts.map +1 -1
- package/dist/types/src/packlets/identity/identity.d.ts +2 -2
- package/dist/types/src/packlets/identity/identity.d.ts.map +1 -1
- package/dist/types/src/packlets/invitations/edge-invitation-handler.d.ts.map +1 -1
- package/dist/types/src/packlets/invitations/invitations-handler.d.ts +17 -0
- package/dist/types/src/packlets/invitations/invitations-handler.d.ts.map +1 -1
- package/dist/types/src/packlets/invitations/invitations-manager.d.ts +25 -4
- package/dist/types/src/packlets/invitations/invitations-manager.d.ts.map +1 -1
- package/dist/types/src/packlets/invitations/invitations-service.d.ts +11 -11
- package/dist/types/src/packlets/invitations/invitations-service.d.ts.map +1 -1
- package/dist/types/src/packlets/logging/logging-service.d.ts +14 -12
- package/dist/types/src/packlets/logging/logging-service.d.ts.map +1 -1
- package/dist/types/src/packlets/metadata/index.d.ts +3 -0
- package/dist/types/src/packlets/metadata/index.d.ts.map +1 -0
- package/dist/types/src/packlets/metadata/metadata-store.d.ts +107 -0
- package/dist/types/src/packlets/metadata/metadata-store.d.ts.map +1 -0
- package/dist/types/src/packlets/metadata/metadata-store.test.d.ts +2 -0
- package/dist/types/src/packlets/metadata/metadata-store.test.d.ts.map +1 -0
- package/dist/types/src/packlets/metadata/sqlite-metadata-store.d.ts +65 -0
- package/dist/types/src/packlets/metadata/sqlite-metadata-store.d.ts.map +1 -0
- package/dist/types/src/packlets/network/network-service.d.ts +15 -14
- package/dist/types/src/packlets/network/network-service.d.ts.map +1 -1
- package/dist/types/src/packlets/pipeline/codec.d.ts +11 -0
- package/dist/types/src/packlets/pipeline/codec.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/feeds.d.ts +7 -0
- package/dist/types/src/packlets/pipeline/feeds.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/index.d.ts +5 -0
- package/dist/types/src/packlets/pipeline/index.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/message-selector.d.ts +11 -0
- package/dist/types/src/packlets/pipeline/message-selector.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/pipeline-stress.test.d.ts +2 -0
- package/dist/types/src/packlets/pipeline/pipeline-stress.test.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/pipeline.d.ts +131 -0
- package/dist/types/src/packlets/pipeline/pipeline.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/pipeline.test.d.ts +2 -0
- package/dist/types/src/packlets/pipeline/pipeline.test.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/testing/index.d.ts +2 -0
- package/dist/types/src/packlets/pipeline/testing/index.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/testing/test-feed-builder.d.ts +9 -0
- package/dist/types/src/packlets/pipeline/testing/test-feed-builder.d.ts.map +1 -0
- package/dist/types/src/packlets/pipeline/timeframe-clock.d.ts +31 -0
- package/dist/types/src/packlets/pipeline/timeframe-clock.d.ts.map +1 -0
- package/dist/types/src/packlets/services/client-services-layer.d.ts +21 -0
- package/dist/types/src/packlets/services/client-services-layer.d.ts.map +1 -0
- package/dist/types/src/packlets/services/cross-device-space-synchronizer.d.ts +28 -0
- package/dist/types/src/packlets/services/cross-device-space-synchronizer.d.ts.map +1 -0
- package/dist/types/src/packlets/services/effect-rpc.test.d.ts +2 -0
- package/dist/types/src/packlets/services/effect-rpc.test.d.ts.map +1 -0
- package/dist/types/src/packlets/services/feed-syncer.d.ts +22 -2
- package/dist/types/src/packlets/services/feed-syncer.d.ts.map +1 -1
- package/dist/types/src/packlets/services/index.d.ts +2 -2
- package/dist/types/src/packlets/services/index.d.ts.map +1 -1
- package/dist/types/src/packlets/services/platform.d.ts.map +1 -1
- package/dist/types/src/packlets/services/service-context.d.ts +38 -57
- package/dist/types/src/packlets/services/service-context.d.ts.map +1 -1
- package/dist/types/src/packlets/services/service-host.d.ts +82 -31
- package/dist/types/src/packlets/services/service-host.d.ts.map +1 -1
- package/dist/types/src/packlets/services/sqlite-storage.d.ts +29 -0
- package/dist/types/src/packlets/services/sqlite-storage.d.ts.map +1 -1
- package/dist/types/src/packlets/services/sqlite-storage.test.d.ts +2 -0
- package/dist/types/src/packlets/services/sqlite-storage.test.d.ts.map +1 -0
- package/dist/types/src/packlets/space/admission-discovery-extension.d.ts +30 -0
- package/dist/types/src/packlets/space/admission-discovery-extension.d.ts.map +1 -0
- package/dist/types/src/packlets/space/auth.d.ts +24 -0
- package/dist/types/src/packlets/space/auth.d.ts.map +1 -0
- package/dist/types/src/packlets/space/control-pipeline.d.ts +46 -0
- package/dist/types/src/packlets/space/control-pipeline.d.ts.map +1 -0
- package/dist/types/src/packlets/space/control-pipeline.test.d.ts +2 -0
- package/dist/types/src/packlets/space/control-pipeline.test.d.ts.map +1 -0
- package/dist/types/src/packlets/space/index.d.ts +6 -0
- package/dist/types/src/packlets/space/index.d.ts.map +1 -0
- package/dist/types/src/packlets/space/replication.browser.test.d.ts +2 -0
- package/dist/types/src/packlets/space/replication.browser.test.d.ts.map +1 -0
- package/dist/types/src/packlets/space/space-manager.browser.test.d.ts +2 -0
- package/dist/types/src/packlets/space/space-manager.browser.test.d.ts.map +1 -0
- package/dist/types/src/packlets/space/space-manager.d.ts +72 -0
- package/dist/types/src/packlets/space/space-manager.d.ts.map +1 -0
- package/dist/types/src/packlets/space/space-protocol.browser.test.d.ts +2 -0
- package/dist/types/src/packlets/space/space-protocol.browser.test.d.ts.map +1 -0
- package/dist/types/src/packlets/space/space-protocol.d.ts +99 -0
- package/dist/types/src/packlets/space/space-protocol.d.ts.map +1 -0
- package/dist/types/src/packlets/space/space-protocol.test.d.ts +2 -0
- package/dist/types/src/packlets/space/space-protocol.test.d.ts.map +1 -0
- package/dist/types/src/packlets/space/space.d.ts +65 -0
- package/dist/types/src/packlets/space/space.d.ts.map +1 -0
- package/dist/types/src/packlets/space/space.test.d.ts +2 -0
- package/dist/types/src/packlets/space/space.test.d.ts.map +1 -0
- package/dist/types/src/packlets/space/testing/change-metadata.d.ts +8 -0
- package/dist/types/src/packlets/space/testing/change-metadata.d.ts.map +1 -0
- package/dist/types/src/packlets/space/testing/index.d.ts +4 -0
- package/dist/types/src/packlets/space/testing/index.d.ts.map +1 -0
- package/dist/types/src/packlets/space/testing/test-agent-builder.d.ts +62 -0
- package/dist/types/src/packlets/space/testing/test-agent-builder.d.ts.map +1 -0
- package/dist/types/src/packlets/space-export/serialized-space-reader.d.ts +1 -1
- package/dist/types/src/packlets/space-export/serialized-space-reader.d.ts.map +1 -1
- package/dist/types/src/packlets/space-export/serialized-space-writer.d.ts.map +1 -1
- package/dist/types/src/packlets/spaces/data-space-manager.d.ts +40 -7
- package/dist/types/src/packlets/spaces/data-space-manager.d.ts.map +1 -1
- package/dist/types/src/packlets/spaces/data-space.d.ts +3 -1
- package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
- package/dist/types/src/packlets/spaces/genesis.d.ts +1 -1
- package/dist/types/src/packlets/spaces/genesis.d.ts.map +1 -1
- package/dist/types/src/packlets/spaces/spaces-service.d.ts +25 -23
- package/dist/types/src/packlets/spaces/spaces-service.d.ts.map +1 -1
- package/dist/types/src/packlets/storage/level.d.ts.map +1 -1
- package/dist/types/src/packlets/system/system-service.d.ts +18 -18
- package/dist/types/src/packlets/system/system-service.d.ts.map +1 -1
- package/dist/types/src/packlets/testing/invitation-utils.d.ts +1 -1
- package/dist/types/src/packlets/testing/invitation-utils.d.ts.map +1 -1
- package/dist/types/src/packlets/testing/test-builder.d.ts +7 -6
- package/dist/types/src/packlets/testing/test-builder.d.ts.map +1 -1
- package/dist/types/src/packlets/worker/worker-runtime.d.ts +41 -58
- package/dist/types/src/packlets/worker/worker-runtime.d.ts.map +1 -1
- package/dist/types/src/packlets/worker/worker-session.d.ts +21 -8
- package/dist/types/src/packlets/worker/worker-session.d.ts.map +1 -1
- package/dist/types/src/testing/index.d.ts +1 -0
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/version.d.ts +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +52 -48
- package/src/index.ts +2 -0
- package/src/packlets/agents/edge-agent-manager.ts +56 -15
- package/src/packlets/agents/edge-agent-service.ts +25 -15
- package/src/packlets/devices/devices-service.test.ts +20 -19
- package/src/packlets/devices/devices-service.ts +17 -17
- package/src/packlets/devtools/devtools.ts +133 -75
- package/src/packlets/devtools/feeds.ts +2 -1
- package/src/packlets/devtools/network.ts +42 -12
- package/src/packlets/devtools/spaces.ts +1 -1
- package/src/packlets/diagnostics/diagnostics-broadcast.ts +4 -2
- package/src/packlets/diagnostics/diagnostics-collector.ts +5 -18
- package/src/packlets/diagnostics/diagnostics.ts +0 -11
- package/src/packlets/identity/authenticator.ts +2 -1
- package/src/packlets/identity/contacts-service.ts +46 -37
- package/src/packlets/identity/identity-manager.test.ts +3 -1
- package/src/packlets/identity/identity-manager.ts +73 -5
- package/src/packlets/identity/identity-recovery-manager.ts +56 -7
- package/src/packlets/identity/identity-service.test.ts +27 -18
- package/src/packlets/identity/identity-service.ts +114 -71
- package/src/packlets/identity/identity.test.ts +4 -9
- package/src/packlets/identity/identity.ts +1 -2
- package/src/packlets/invitations/edge-invitation-handler.ts +0 -1
- package/src/packlets/invitations/invitations-handler.ts +39 -3
- package/src/packlets/invitations/invitations-manager.ts +52 -4
- package/src/packlets/invitations/invitations-service.ts +54 -28
- package/src/packlets/logging/logging-service.ts +41 -29
- package/src/packlets/logging/logging.test.ts +28 -15
- package/src/packlets/metadata/index.ts +6 -0
- package/src/packlets/metadata/metadata-store.test.ts +49 -0
- package/src/packlets/metadata/metadata-store.ts +446 -0
- package/src/packlets/metadata/sqlite-metadata-store.ts +409 -0
- package/src/packlets/network/network-service.test.ts +19 -12
- package/src/packlets/network/network-service.ts +96 -29
- package/src/packlets/pipeline/codec.ts +18 -0
- package/src/packlets/pipeline/feeds.ts +22 -0
- package/src/packlets/pipeline/index.ts +8 -0
- package/src/packlets/pipeline/message-selector.ts +35 -0
- package/src/packlets/pipeline/pipeline-stress.test.ts +230 -0
- package/src/packlets/pipeline/pipeline.test.ts +140 -0
- package/src/packlets/pipeline/pipeline.ts +439 -0
- package/src/packlets/pipeline/testing/index.ts +5 -0
- package/src/packlets/pipeline/testing/test-feed-builder.ts +19 -0
- package/src/packlets/pipeline/timeframe-clock.ts +81 -0
- package/src/packlets/services/client-services-layer.ts +186 -0
- package/src/packlets/services/cross-device-space-synchronizer.ts +132 -0
- package/src/packlets/services/effect-rpc.test.ts +314 -0
- package/src/packlets/services/feed-syncer.ts +57 -3
- package/src/packlets/services/index.ts +2 -2
- package/src/packlets/services/platform.ts +0 -6
- package/src/packlets/services/service-context.ts +219 -522
- package/src/packlets/services/service-host.test.ts +34 -11
- package/src/packlets/services/service-host.ts +693 -213
- package/src/packlets/services/spec.md +106 -0
- package/src/packlets/services/sqlite-storage.test.ts +48 -0
- package/src/packlets/services/sqlite-storage.ts +117 -20
- package/src/packlets/space/admission-discovery-extension.ts +91 -0
- package/src/packlets/space/auth.ts +92 -0
- package/src/packlets/space/control-pipeline.test.ts +165 -0
- package/src/packlets/space/control-pipeline.ts +229 -0
- package/src/packlets/space/index.ts +9 -0
- package/src/packlets/space/replication.browser.test.ts +58 -0
- package/src/packlets/space/space-manager.browser.test.ts +40 -0
- package/src/packlets/space/space-manager.ts +224 -0
- package/src/packlets/space/space-protocol.browser.test.ts +129 -0
- package/src/packlets/space/space-protocol.test.ts +158 -0
- package/src/packlets/space/space-protocol.ts +308 -0
- package/src/packlets/space/space.test.ts +181 -0
- package/src/packlets/space/space.ts +196 -0
- package/src/packlets/space/testing/change-metadata.ts +27 -0
- package/src/packlets/space/testing/index.ts +7 -0
- package/src/packlets/space/testing/test-agent-builder.ts +252 -0
- package/src/packlets/space-export/serialized-space-reader.ts +3 -1
- package/src/packlets/space-export/serialized-space-writer.ts +53 -30
- package/src/packlets/space-export/space-archive.test.ts +30 -0
- package/src/packlets/spaces/data-space-manager.test.ts +1 -1
- package/src/packlets/spaces/data-space-manager.ts +148 -33
- package/src/packlets/spaces/data-space.ts +29 -18
- package/src/packlets/spaces/edge-feed-replicator.test.ts +1 -1
- package/src/packlets/spaces/genesis.ts +1 -1
- package/src/packlets/spaces/spaces-service.test.ts +35 -22
- package/src/packlets/spaces/spaces-service.ts +259 -180
- package/src/packlets/storage/level.ts +3 -1
- package/src/packlets/system/system-service.test.ts +31 -13
- package/src/packlets/system/system-service.ts +65 -37
- package/src/packlets/testing/invitation-utils.ts +3 -3
- package/src/packlets/testing/test-builder.ts +35 -20
- package/src/packlets/worker/worker-runtime.ts +222 -260
- package/src/packlets/worker/worker-session.ts +108 -91
- package/src/testing/index.ts +1 -0
- package/src/version.ts +1 -1
- package/dist/lib/browser/chunk-QCWEHHJW.mjs +0 -24
- package/dist/lib/browser/chunk-QCWEHHJW.mjs.map +0 -7
- package/dist/lib/browser/chunk-XJRPB3GA.mjs +0 -22
- package/dist/lib/browser/chunk-XJRPB3GA.mjs.map +0 -7
- package/dist/lib/browser/chunk-XU5R2BMF.mjs +0 -8837
- package/dist/lib/browser/chunk-XU5R2BMF.mjs.map +0 -7
- package/dist/lib/browser/index.mjs +0 -876
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -1
- package/dist/lib/browser/packlets/diagnostics/browser-diagnostics-broadcast.mjs +0 -88
- package/dist/lib/browser/packlets/diagnostics/browser-diagnostics-broadcast.mjs.map +0 -7
- package/dist/lib/browser/packlets/diagnostics/diagnostics-broadcast.mjs +0 -11
- package/dist/lib/browser/packlets/diagnostics/diagnostics-broadcast.mjs.map +0 -7
- package/dist/lib/browser/packlets/locks/browser.mjs +0 -86
- package/dist/lib/browser/packlets/locks/browser.mjs.map +0 -7
- package/dist/lib/browser/packlets/locks/node.mjs +0 -48
- package/dist/lib/browser/packlets/locks/node.mjs.map +0 -7
- package/dist/lib/browser/testing/index.mjs +0 -436
- package/dist/lib/browser/testing/index.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-2DT3MZRL.mjs +0 -22
- package/dist/lib/node-esm/chunk-2DT3MZRL.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-2SZHAWBN.mjs +0 -24
- package/dist/lib/node-esm/chunk-2SZHAWBN.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-H5YTUD35.mjs +0 -8837
- package/dist/lib/node-esm/chunk-H5YTUD35.mjs.map +0 -7
- package/dist/lib/node-esm/index.mjs +0 -876
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
- package/dist/lib/node-esm/packlets/diagnostics/browser-diagnostics-broadcast.mjs +0 -88
- package/dist/lib/node-esm/packlets/diagnostics/browser-diagnostics-broadcast.mjs.map +0 -7
- package/dist/lib/node-esm/packlets/diagnostics/diagnostics-broadcast.mjs +0 -11
- package/dist/lib/node-esm/packlets/diagnostics/diagnostics-broadcast.mjs.map +0 -7
- package/dist/lib/node-esm/packlets/locks/browser.mjs +0 -86
- package/dist/lib/node-esm/packlets/locks/browser.mjs.map +0 -7
- package/dist/lib/node-esm/packlets/locks/node.mjs +0 -48
- package/dist/lib/node-esm/packlets/locks/node.mjs.map +0 -7
- package/dist/lib/node-esm/testing/index.mjs +0 -436
- package/dist/lib/node-esm/testing/index.mjs.map +0 -7
- package/dist/types/src/packlets/services/client-rpc-server.d.ts +0 -24
- package/dist/types/src/packlets/services/client-rpc-server.d.ts.map +0 -1
- package/dist/types/src/packlets/services/service-registry.d.ts +0 -15
- package/dist/types/src/packlets/services/service-registry.d.ts.map +0 -1
- package/dist/types/src/packlets/services/service-registry.test.d.ts +0 -2
- package/dist/types/src/packlets/services/service-registry.test.d.ts.map +0 -1
- package/dist/types/src/testing/setup.d.ts +0 -3
- package/dist/types/src/testing/setup.d.ts.map +0 -1
- package/src/packlets/services/client-rpc-server.ts +0 -111
- package/src/packlets/services/service-registry.test.ts +0 -78
- package/src/packlets/services/service-registry.ts +0 -36
- package/src/testing/setup.ts +0 -11
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chunk-client-services-layer.mjs","names":[],"sources":["../../src/packlets/devtools/feeds.ts","../../src/packlets/devtools/keys.ts","../../src/packlets/devtools/metadata.ts","../../src/packlets/devtools/network.ts","../../src/packlets/devtools/spaces.ts","../../src/packlets/devtools/devtools.ts","../../src/version.ts","../../src/packlets/services/platform.ts","../../src/packlets/diagnostics/diagnostics.ts","../../src/packlets/diagnostics/diagnostics-collector.ts","../../src/packlets/diagnostics/index.ts","../../src/packlets/identity/authenticator.ts","../../src/packlets/invitations/device-invitation-protocol.ts","../../src/packlets/invitations/utils.ts","../../src/packlets/invitations/edge-invitation-handler.ts","../../src/packlets/invitations/invitation-guest-extenstion.ts","../../src/packlets/invitations/invitation-host-extension.ts","../../src/packlets/invitations/invitation-state.ts","../../src/packlets/invitations/invitation-topology.ts","../../src/packlets/invitations/invitations-handler.ts","../../src/packlets/invitations/invitations-service.ts","../../src/packlets/invitations/space-invitation-protocol.ts","../../src/packlets/metadata/metadata-store.ts","../../src/packlets/metadata/sqlite-metadata-store.ts","../../src/packlets/invitations/invitations-manager.ts","../../src/packlets/space/auth.ts","../../src/packlets/pipeline/feeds.ts","../../src/packlets/pipeline/message-selector.ts","../../src/packlets/pipeline/timeframe-clock.ts","../../src/packlets/pipeline/pipeline.ts","../../src/packlets/pipeline/codec.ts","../../src/packlets/space/control-pipeline.ts","../../src/packlets/space/space.ts","../../src/packlets/space/admission-discovery-extension.ts","../../src/packlets/space/space-protocol.ts","../../src/packlets/space/space-manager.ts","../../src/packlets/spaces/automerge-space-state.ts","../../src/packlets/spaces/edge-feed-replicator.ts","../../src/packlets/spaces/epoch-migrations.ts","../../src/packlets/spaces/notarization-plugin.ts","../../src/packlets/spaces/data-space.ts","../../src/packlets/spaces/genesis.ts","../../src/packlets/spaces/data-space-manager.ts","../../src/packlets/space-export/archive-format.ts","../../src/packlets/space-export/serialized-space-reader.ts","../../src/packlets/space-export/serialized-space-writer.ts","../../src/packlets/space-export/space-archive-reader.ts","../../src/packlets/space-export/space-archive-writer.ts","../../src/packlets/spaces/spaces-service.ts","../../src/packlets/identity/identity.ts","../../src/packlets/identity/identity-manager.ts","../../src/packlets/identity/identity-service.ts","../../src/packlets/locks/index.ts","../../src/packlets/agents/edge-agent-manager.ts","../../src/packlets/agents/edge-agent-service.ts","../../src/packlets/devices/devices-service.ts","../../src/packlets/identity/contacts-service.ts","../../src/packlets/identity/identity-recovery-manager.ts","../../src/packlets/network/network-service.ts","../../src/packlets/logging/logging-service.ts","../../src/packlets/system/system-service.ts","../../src/packlets/services/cross-device-space-synchronizer.ts","../../src/packlets/services/feed-syncer.ts","../../src/packlets/services/sqlite-storage.ts","../../src/packlets/services/service-context.ts","../../src/packlets/services/service-host.ts","../../src/packlets/services/client-services-layer.ts"],"sourcesContent":["//\n// Copyright 2021 DXOS.org\n//\n\nimport { SubscriptionList } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf/stream';\nimport { FeedIterator, type FeedStore, type FeedWrapper } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n type SubscribeToFeedBlocksRequest,\n type SubscribeToFeedBlocksResponse,\n type SubscribeToFeedsRequest,\n type SubscribeToFeedsResponse,\n} from '@dxos/protocols/proto/dxos/devtools/host';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { ComplexMap } from '@dxos/util';\n\nimport { type SpaceManager } from '../space';\n\ntype FeedInfo = {\n feed: FeedWrapper<FeedMessage>;\n owner?: SubscribeToFeedsResponse.FeedOwner;\n};\n\nexport const subscribeToFeeds = (\n { feedStore, spaceManager }: { feedStore: FeedStore<FeedMessage>; spaceManager: SpaceManager },\n { feedKeys }: SubscribeToFeedsRequest,\n) => {\n return new Stream<SubscribeToFeedsResponse>(({ next }) => {\n const subscriptions = new SubscriptionList();\n const feedMap = new ComplexMap<PublicKey, FeedInfo>(PublicKey.hash);\n\n const update = () => {\n const { feeds } = feedStore;\n feeds\n .filter((feed) => !feedKeys?.length || feedKeys.some((feedKey) => feedKey.equals(feed.key)))\n .forEach((feed) => {\n if (!feedMap.has(feed.key)) {\n feedMap.set(feed.key, { feed });\n feed.on('close', update);\n subscriptions.add(() => feed.off('close', update));\n }\n if (!feedMap.get(feed.key)?.owner) {\n feedMap.get(feed.key)!.owner = findFeedOwner(spaceManager, feed.key);\n }\n });\n\n next({\n feeds: Array.from(feedMap.values()).map(({ feed, owner }) => ({\n feedKey: feed.key,\n length: feed.properties.length,\n bytes: feed.core.byteLength,\n downloaded: feed.core.bitfield?.data.toBuffer() ?? new Uint8Array(),\n owner,\n })),\n });\n };\n\n subscriptions.add(feedStore.feedOpened.on(update));\n update();\n\n return () => {\n subscriptions.clear();\n };\n });\n};\n\nconst findFeedOwner = (\n spaceManager: SpaceManager,\n feedKey: PublicKey,\n): SubscribeToFeedsResponse.FeedOwner | undefined => {\n const feedInfo = [...spaceManager.spaces.values()]\n .flatMap((space) => [...space.spaceState.feeds.values()])\n .find((feed) => feed.key.equals(feedKey));\n log('feeds', { feedInfo, key: feedKey.truncate(), allSpaces: spaceManager.spaces.size });\n if (!feedInfo) {\n return undefined;\n }\n return {\n identity: feedInfo.assertion.identityKey,\n device: feedInfo.assertion.deviceKey,\n };\n};\n\nexport const subscribeToFeedBlocks = (\n { feedStore }: { feedStore: FeedStore<FeedMessage> },\n { feedKey, maxBlocks = 10 }: SubscribeToFeedBlocksRequest,\n) => {\n return new Stream<SubscribeToFeedBlocksResponse>(({ next }) => {\n if (!feedKey) {\n return;\n }\n\n const subscriptions = new SubscriptionList();\n\n const timeout = setTimeout(async () => {\n const feed = feedStore.getFeed(feedKey);\n if (!feed) {\n return;\n }\n\n const update = async () => {\n if (!feed.properties.length) {\n next({ blocks: [] });\n return;\n }\n\n const iterator = new FeedIterator(feed);\n await iterator.open();\n const blocks = [];\n for await (const block of iterator) {\n blocks.push(block);\n if (blocks.length >= feed.properties.length) {\n break;\n }\n }\n\n next({\n blocks: blocks.slice(-maxBlocks),\n });\n\n await iterator.close();\n };\n\n feed.on('append', update);\n subscriptions.add(() => feed.off('append', update));\n\n feed.on('truncate', update);\n subscriptions.add(() => feed.off('truncate', update));\n await update();\n });\n\n return () => {\n subscriptions.clear();\n clearTimeout(timeout);\n };\n });\n};\n","//\n// Copyright 2020 DXOS.org\n//\n\nimport { scheduleTask } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf/stream';\nimport { type KeyringApi } from '@dxos/keyring';\nimport { type SubscribeToKeyringKeysResponse } from '@dxos/protocols/proto/dxos/devtools/host';\n\nexport const subscribeToKeyringKeys = ({ keyring }: { keyring: KeyringApi }) =>\n new Stream<SubscribeToKeyringKeysResponse>(({ next, ctx }) => {\n const update = async () => {\n next({\n keys: await keyring.list(),\n });\n };\n keyring.keysUpdate.on(ctx, update);\n scheduleTask(ctx, update);\n });\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf/stream';\nimport { type SubscribeToMetadataResponse } from '@dxos/protocols/proto/dxos/devtools/host';\n\nimport { type ServiceContext } from '../services';\n\nexport const subscribeToMetadata = ({ context }: { context: ServiceContext }) =>\n new Stream<SubscribeToMetadataResponse>(({ next, ctx }) => {\n context.metadataStore.update.on(ctx, (data) => next({ metadata: data }));\n next({ metadata: context.metadataStore.metadata });\n });\n","//\n// Copyright 2020 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf/stream';\nimport { Context } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type SignalManager, type UnsubscribeCallback } from '@dxos/messaging';\nimport { type SwarmNetworkManager } from '@dxos/network-manager';\nimport {\n type GetNetworkPeersRequest,\n type GetNetworkPeersResponse,\n type SignalResponse,\n type SubscribeToNetworkTopicsResponse,\n type SubscribeToSignalStatusResponse,\n type SubscribeToSwarmInfoResponse,\n} from '@dxos/protocols/proto/dxos/devtools/host';\n\nexport const subscribeToNetworkStatus = ({ signalManager }: { signalManager: SignalManager }) =>\n new Stream<SubscribeToSignalStatusResponse>(({ next, close }) => {\n const update = () => {\n try {\n const status = signalManager.getStatus?.();\n next({ servers: status });\n } catch (err: any) {\n close(err);\n }\n };\n\n signalManager.statusChanged?.on(() => update());\n update();\n });\n\nexport const subscribeToSignal = ({\n signalManager,\n networkManager,\n}: {\n signalManager: SignalManager;\n networkManager: SwarmNetworkManager;\n}) =>\n new Stream<SignalResponse>(({ next }) => {\n const ctx = new Context();\n\n // Observe point-to-point messages delivered to this node's own peer. The subscription owns its\n // routing and teardown (DX-1125); with no local peer yet there is nothing to observe.\n let unsubscribe: UnsubscribeCallback | undefined;\n const peer = networkManager.getPeerInfo();\n if (peer) {\n void signalManager\n .subscribeMessages({\n peer,\n onMessage: (message) => {\n next({\n message: {\n author: PublicKey.from(message.author.peerKey).asUint8Array(),\n recipient: message.recipient\n ? PublicKey.from(message.recipient.peerKey).asUint8Array()\n : new Uint8Array(),\n payload: message.payload,\n },\n receivedAt: new Date(),\n });\n },\n })\n .then((unsub) => {\n if (ctx.disposed) {\n void unsub();\n } else {\n unsubscribe = unsub;\n }\n })\n .catch((err) => log.catch(err));\n }\n\n signalManager.swarmEvent.on(ctx, (swarmEvent) => {\n next({\n swarmEvent: swarmEvent.peerAvailable\n ? {\n peerAvailable: {\n peer: PublicKey.from(swarmEvent.peerAvailable.peer.peerKey).asUint8Array(),\n since: swarmEvent.peerAvailable.since,\n },\n }\n : { peerLeft: { peer: PublicKey.from(swarmEvent.peerLeft!.peer.peerKey).asUint8Array() } },\n topic: swarmEvent.topic.asUint8Array(),\n receivedAt: new Date(),\n });\n });\n return () => {\n void unsubscribe?.();\n return ctx.dispose();\n };\n });\n\nexport const subscribeToNetworkTopics = ({ networkManager }: { networkManager: SwarmNetworkManager }) =>\n new Stream<SubscribeToNetworkTopicsResponse>(({ next, close }) => {\n const update = () => {\n try {\n const topics = networkManager.topics;\n const labeledTopics = topics.map((topic) => ({\n topic,\n label: networkManager.getSwarm(topic)?.label ?? topic.toHex(),\n }));\n next({ topics: labeledTopics });\n } catch (err: any) {\n close(err);\n }\n };\n networkManager.topicsUpdated.on(update);\n\n update();\n });\n\nexport const subscribeToSwarmInfo = ({ networkManager }: { networkManager: SwarmNetworkManager }) =>\n new Stream<SubscribeToSwarmInfoResponse>(({ next }) => {\n const update = () => {\n const info = networkManager.connectionLog?.swarms;\n if (info) {\n next({ data: info });\n }\n };\n networkManager.connectionLog?.update.on(update);\n update();\n });\n\nexport const getNetworkPeers = (\n { networkManager }: { networkManager: SwarmNetworkManager },\n request: GetNetworkPeersRequest,\n): GetNetworkPeersResponse => {\n if (!request.topic) {\n throw new Error('Expected a network topic');\n }\n\n const map = networkManager.getSwarmMap(PublicKey.from(request.topic));\n return {\n peers: map?.peers.map((peer) => ({\n ...peer,\n connections: peer.connections.map((connection) => connection.asUint8Array()),\n })),\n };\n};\n","//\n// Copyright 2020 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf/stream';\nimport {\n type SubscribeToSpacesRequest,\n type SubscribeToSpacesResponse,\n} from '@dxos/protocols/proto/dxos/devtools/host';\nimport { type SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\n\nimport { type ServiceContext } from '../services';\nimport { type Space } from '../space';\n\nexport const subscribeToSpaces = (context: ServiceContext, { spaceKeys = [] }: SubscribeToSpacesRequest) => {\n return new Stream<SubscribeToSpacesResponse>(({ next }) => {\n let unsubscribe: () => void;\n\n const update = async () => {\n const spaces: Space[] = [...context.spaceManager!.spaces.values()];\n const filteredSpaces = spaces.filter(\n (space) => !spaceKeys?.length || spaceKeys.some((spaceKey) => spaceKey.equals(space.key)),\n );\n\n next({\n spaces: filteredSpaces.map((space): SubscribeToSpacesResponse.SpaceInfo => {\n const spaceMetadata = context.metadataStore.spaces.find((spaceMetadata: SpaceMetadata) =>\n spaceMetadata.key.equals(space.key),\n );\n\n return {\n key: space.key,\n isOpen: space.isOpen,\n timeframe: spaceMetadata?.dataTimeframe,\n genesisFeed: space.genesisFeedKey,\n controlFeed: space.controlFeedKey!, // TODO(dmaretskyi): Those keys may be missing.\n dataFeed: space.dataFeedKey!,\n };\n }),\n });\n };\n\n const timeout = setTimeout(async () => {\n await context.initialized.wait();\n unsubscribe = context.dataSpaceManager!.updated.on(() => update());\n\n // Send initial spaces.\n await update();\n });\n\n return () => {\n unsubscribe?.();\n clearTimeout(timeout);\n };\n });\n};\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { Event as AsyncEvent } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf/stream';\nimport { type Config } from '@dxos/config';\nimport { Context } from '@dxos/context';\nimport {\n type ClearSnapshotsRequest,\n type EnableDebugLoggingRequest,\n type EnableDebugLoggingResponse,\n type Event,\n type ExportSqliteDatabaseResponse,\n type GetBlobsResponse,\n type GetConfigResponse,\n type GetNetworkPeersRequest,\n type GetNetworkPeersResponse,\n type GetSnapshotsResponse,\n type GetSpaceSnapshotRequest,\n type GetSpaceSnapshotResponse,\n type ResetStorageRequest,\n type RunSqliteQueryRequest,\n type RunSqliteQueryResponse,\n type SaveSpaceSnapshotRequest,\n type SaveSpaceSnapshotResponse,\n type SignalResponse,\n type StorageInfo,\n type SubscribeToCredentialMessagesRequest,\n type SubscribeToCredentialMessagesResponse,\n type SubscribeToFeedBlocksRequest,\n type SubscribeToFeedBlocksResponse,\n type SubscribeToFeedsRequest,\n type SubscribeToFeedsResponse,\n type SubscribeToItemsRequest,\n type SubscribeToItemsResponse,\n type SubscribeToKeyringKeysRequest,\n type SubscribeToKeyringKeysResponse,\n type SubscribeToMetadataResponse,\n type SubscribeToNetworkTopicsResponse,\n type SubscribeToSignalStatusResponse,\n type SubscribeToSpacesRequest,\n type SubscribeToSpacesResponse,\n type SubscribeToSwarmInfoRequest,\n type SubscribeToSwarmInfoResponse,\n} from '@dxos/protocols/proto/dxos/devtools/host';\nimport { type DevtoolsHost } from '@dxos/protocols/rpc';\n\nimport { type ServiceContext } from '../services';\nimport { subscribeToFeedBlocks, subscribeToFeeds } from './feeds';\nimport { subscribeToKeyringKeys } from './keys';\nimport { subscribeToMetadata } from './metadata';\nimport { subscribeToNetworkStatus, subscribeToSignal, subscribeToSwarmInfo } from './network';\nimport { subscribeToSpaces } from './spaces';\n\nexport class DevtoolsHostEvents {\n readonly ready = new AsyncEvent();\n}\n\nexport type DevtoolsServiceProps = {\n events: DevtoolsHostEvents;\n config: Config;\n context: ServiceContext;\n exportSqliteDatabase: () => Promise<Uint8Array>;\n runSqliteQuery: (query: string, params?: unknown[]) => Promise<readonly Record<string, unknown>[]>;\n};\n\n/**\n * @deprecated\n */\nexport class DevtoolsServiceImpl implements DevtoolsHost.Handlers {\n 'constructor'(private readonly params: DevtoolsServiceProps) {}\n\n ['DevtoolsHost.events'](): EffectStream.Stream<Event, Error> {\n return EffectStream.async<Event, Error>((emit) => {\n const ctx = Context.default();\n this.params.events.ready.on(ctx, () => {\n void emit.single({ ready: {} });\n });\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['DevtoolsHost.getConfig'](): Effect.Effect<GetConfigResponse, Error> {\n return Effect.sync(() => ({ config: JSON.stringify(this.params.config.values) })); // 😨\n }\n\n ['DevtoolsHost.getStorageInfo'](): Effect.Effect<StorageInfo, Error> {\n return Effect.tryPromise({\n try: async () => {\n const navigatorInfo = typeof navigator === 'object' ? await navigator.storage.estimate() : undefined;\n\n return {\n type: 'sqlite',\n storageUsage: navigatorInfo?.usage ?? 0,\n originUsage: navigatorInfo?.usage ?? 0,\n usageQuota: navigatorInfo?.quota ?? 0,\n };\n },\n catch: (error) => error as Error,\n });\n }\n\n ['DevtoolsHost.getBlobs'](): Effect.Effect<GetBlobsResponse, Error> {\n return Effect.tryPromise({\n try: async () => ({\n blobs: await this.params.context.blobStore.list(),\n }),\n catch: (error) => error as Error,\n });\n }\n\n ['DevtoolsHost.getSnapshots'](): Effect.Effect<GetSnapshotsResponse, Error> {\n return Effect.sync(() => ({\n snapshots: [],\n }));\n }\n\n ['DevtoolsHost.resetStorage'](_request: ResetStorageRequest): Effect.Effect<void, Error> {\n return Effect.fail(new Error());\n }\n\n ['DevtoolsHost.enableDebugLogging'](\n _request: EnableDebugLoggingRequest,\n ): Effect.Effect<EnableDebugLoggingResponse, Error> {\n return Effect.fail(new Error());\n }\n\n ['DevtoolsHost.disableDebugLogging'](\n _request: EnableDebugLoggingRequest,\n ): Effect.Effect<EnableDebugLoggingResponse, Error> {\n return Effect.fail(new Error());\n }\n\n ['DevtoolsHost.subscribeToKeyringKeys'](\n _request: SubscribeToKeyringKeysRequest,\n ): EffectStream.Stream<SubscribeToKeyringKeysResponse, Error> {\n return toEffectStream(subscribeToKeyringKeys({ keyring: this.params.context.keyring }));\n }\n\n ['DevtoolsHost.subscribeToCredentialMessages'](\n _request: SubscribeToCredentialMessagesRequest,\n ): EffectStream.Stream<SubscribeToCredentialMessagesResponse, Error> {\n return EffectStream.fail(new Error());\n }\n\n ['DevtoolsHost.subscribeToSpaces'](\n request: SubscribeToSpacesRequest,\n ): EffectStream.Stream<SubscribeToSpacesResponse, Error> {\n return toEffectStream(subscribeToSpaces(this.params.context, request));\n }\n\n ['DevtoolsHost.subscribeToItems'](\n _request: SubscribeToItemsRequest,\n ): EffectStream.Stream<SubscribeToItemsResponse, Error> {\n return EffectStream.fail(new Error());\n }\n\n ['DevtoolsHost.subscribeToFeeds'](\n request: SubscribeToFeedsRequest,\n ): EffectStream.Stream<SubscribeToFeedsResponse, Error> {\n return toEffectStream(subscribeToFeeds(this.params.context, request));\n }\n\n ['DevtoolsHost.subscribeToFeedBlocks'](\n request: SubscribeToFeedBlocksRequest,\n ): EffectStream.Stream<SubscribeToFeedBlocksResponse, Error> {\n return toEffectStream(subscribeToFeedBlocks({ feedStore: this.params.context.feedStore }, request));\n }\n\n ['DevtoolsHost.subscribeToMetadata'](): EffectStream.Stream<SubscribeToMetadataResponse, Error> {\n return toEffectStream(subscribeToMetadata({ context: this.params.context }));\n }\n\n ['DevtoolsHost.getSpaceSnapshot'](_request: GetSpaceSnapshotRequest): Effect.Effect<GetSpaceSnapshotResponse, Error> {\n return Effect.fail(new Error());\n }\n\n ['DevtoolsHost.saveSpaceSnapshot'](\n _request: SaveSpaceSnapshotRequest,\n ): Effect.Effect<SaveSpaceSnapshotResponse, Error> {\n return Effect.fail(new Error());\n }\n\n ['DevtoolsHost.clearSnapshots'](_request: ClearSnapshotsRequest): Effect.Effect<void, Error> {\n return Effect.fail(new Error());\n }\n\n ['DevtoolsHost.getNetworkPeers'](_request: GetNetworkPeersRequest): Effect.Effect<GetNetworkPeersResponse, Error> {\n return Effect.fail(new Error());\n }\n\n ['DevtoolsHost.subscribeToNetworkTopics'](): EffectStream.Stream<SubscribeToNetworkTopicsResponse, Error> {\n return EffectStream.fail(new Error());\n }\n\n ['DevtoolsHost.subscribeToSignalStatus'](): EffectStream.Stream<SubscribeToSignalStatusResponse, Error> {\n return toEffectStream(subscribeToNetworkStatus({ signalManager: this.params.context.signalManager }));\n }\n\n ['DevtoolsHost.subscribeToSignal'](): EffectStream.Stream<SignalResponse, Error> {\n return toEffectStream(\n subscribeToSignal({\n signalManager: this.params.context.signalManager,\n networkManager: this.params.context.networkManager,\n }),\n );\n }\n\n ['DevtoolsHost.subscribeToSwarmInfo'](\n _request: SubscribeToSwarmInfoRequest,\n ): EffectStream.Stream<SubscribeToSwarmInfoResponse, Error> {\n return toEffectStream(subscribeToSwarmInfo({ networkManager: this.params.context.networkManager }));\n }\n\n ['DevtoolsHost.exportSqliteDatabase'](): Effect.Effect<ExportSqliteDatabaseResponse, Error> {\n return Effect.tryPromise({\n try: async () => ({\n data: await this.params.exportSqliteDatabase(),\n }),\n catch: (error) => error as Error,\n });\n }\n\n ['DevtoolsHost.runSqliteQuery'](request: RunSqliteQueryRequest): Effect.Effect<RunSqliteQueryResponse, Error> {\n return Effect.promise(async () => {\n try {\n const parsedParams = request.params ? JSON.parse(request.params) : undefined;\n if (parsedParams !== undefined && !Array.isArray(parsedParams)) {\n throw new Error('Query params must be a JSON array.');\n }\n const rows = await this.params.runSqliteQuery(request.query, parsedParams);\n return { rows: JSON.stringify(rows) };\n } catch (err) {\n return { rows: '[]', error: err instanceof Error ? err.message : String(err) };\n }\n });\n }\n}\n\n/**\n * Bridges a codec-protobuf {@link Stream} into an Effect {@link EffectStream.Stream}.\n * The underlying stream is closed (disposing its resources) when the Effect stream terminates.\n */\nconst toEffectStream = <T>(stream: Stream<T>): EffectStream.Stream<T, Error> =>\n EffectStream.async<T, Error>((emit) => {\n stream.subscribe(\n (message) => void emit.single(message),\n (error) => (error ? void emit.fail(error) : void emit.end()),\n );\n\n return Effect.promise(() => stream.close());\n });\n","//\n// Copyright 2023 DXOS.org\n//\n\nexport const DXOS_VERSION = '0.11.0';\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { Platform } from '@dxos/protocols/proto/dxos/client/services';\n\nexport const getPlatform = (): Platform => {\n if ((process as any).browser) {\n if (typeof window !== 'undefined') {\n // Browser.\n const { userAgent } = window.navigator;\n return {\n type: Platform.PLATFORM_TYPE.BROWSER,\n userAgent,\n uptime: Math.floor((Date.now() - window.performance.timeOrigin) / 1_000),\n };\n } else {\n // Dedicated worker.\n return {\n type: Platform.PLATFORM_TYPE.DEDICATED_WORKER,\n uptime: Math.floor((Date.now() - performance.timeOrigin) / 1_000),\n };\n }\n } else {\n // Node.\n const { platform, version, arch } = process;\n return {\n type: Platform.PLATFORM_TYPE.NODE,\n platform,\n arch,\n runtime: version,\n uptime: Math.floor(process.uptime()),\n memory: process.memoryUsage(),\n };\n }\n};\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { asyncTimeout } from '@dxos/async';\nimport { type ClientServices } from '@dxos/client-protocol';\nimport { getFirstStreamValue } from '@dxos/codec-protobuf';\nimport { type Config, type ConfigProto } from '@dxos/config';\nimport { createDidFromIdentityKey, credentialTypeFilter } from '@dxos/credentials';\nimport { invariant } from '@dxos/invariant';\nimport { type PublicKey } from '@dxos/keys';\nimport { STORAGE_VERSION } from '@dxos/protocols';\nimport {\n type Device,\n type Identity,\n type Metrics,\n type NetworkStatus,\n type Platform,\n SpaceMember,\n type Space as SpaceProto,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type SubscribeToFeedsResponse } from '@dxos/protocols/proto/dxos/devtools/host';\nimport { type SwarmInfo } from '@dxos/protocols/proto/dxos/devtools/swarm';\nimport { type Epoch } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport { DXOS_VERSION } from '../../version';\nimport { type ServiceContext } from '../services';\nimport { getPlatform } from '../services/platform';\nimport { type DataSpace } from '../spaces';\n\nconst DEFAULT_TIMEOUT = 1_000;\n\nexport type Diagnostics = {\n client: {\n config: ConfigProto;\n };\n services: {\n created: string;\n platform: Platform;\n config?: ConfigProto;\n client: {\n version: string;\n storage: {\n version: number;\n };\n };\n identity?: Identity;\n devices?: Device[];\n spaces?: SpaceStats[];\n networkStatus?: NetworkStatus;\n swarms?: SwarmInfo[];\n feeds?: Partial<SubscribeToFeedsResponse.Feed>[];\n metrics?: Metrics;\n storage?: { file: string; count: number }[];\n };\n};\n\n// TODO(burdon): Normalize for ECHO/HALO.\nexport type SpaceStats = {\n key: PublicKey;\n properties?: {\n name: string;\n };\n db?: {\n objects: number;\n };\n metrics?: SpaceProto.Metrics & {\n startupTime?: number;\n };\n epochs?: (Epoch & { id?: PublicKey })[];\n members?: SpaceMember[];\n pipeline?: SpaceProto.PipelineState;\n};\n\n/**\n * Create diagnostics to provide snapshot of current system state.\n */\nexport const createDiagnostics = async (\n clientServices: Partial<ClientServices>,\n serviceContext: ServiceContext,\n config: Config,\n): Promise<Diagnostics['services']> => {\n const diagnostics: Diagnostics['services'] = {\n created: new Date().toISOString(),\n platform: getPlatform(),\n client: {\n version: DXOS_VERSION,\n storage: {\n version: STORAGE_VERSION,\n },\n },\n };\n\n await Promise.all([\n (async () => {\n // Trace metrics.\n // TODO(burdon): Move here from logging service?\n invariant(clientServices.LoggingService, 'SystemService is not available.');\n diagnostics.metrics = await getFirstStreamValue(clientServices.LoggingService.queryMetrics({}), {\n timeout: DEFAULT_TIMEOUT,\n }).catch(() => undefined);\n })(),\n (async () => {\n diagnostics.storage = await asyncTimeout(getStorageDiagnostics(), DEFAULT_TIMEOUT).catch(() => undefined);\n })(),\n async () => {\n const identity = serviceContext.identityManager.identity;\n if (identity) {\n // Identity.\n diagnostics.identity = {\n did: identity.did,\n identityKey: identity.identityKey,\n spaceKey: identity.space.key,\n profile: identity.profileDocument,\n };\n\n // Devices.\n const { devices } =\n (await getFirstStreamValue(clientServices.DevicesService!.queryDevices(), {\n timeout: DEFAULT_TIMEOUT,\n }).catch(() => undefined)) ?? {};\n diagnostics.devices = devices;\n\n // TODO(dmaretskyi): Add metrics for halo space.\n\n // Spaces.\n if (serviceContext.dataSpaceManager) {\n diagnostics.spaces = await Promise.all(\n Array.from(serviceContext.dataSpaceManager.spaces.values()).map((space) => getSpaceStats(space)) ?? [],\n );\n }\n\n // Feeds.\n const { feeds = [] } =\n (await getFirstStreamValue(clientServices.DevtoolsHost!.subscribeToFeeds({}), {\n timeout: DEFAULT_TIMEOUT,\n }).catch(() => undefined)) ?? {};\n diagnostics.feeds = feeds.map(({ feedKey, bytes, length }) => ({ feedKey, bytes, length }));\n\n // Signal servers.\n\n const status = await getFirstStreamValue(clientServices.NetworkService!.queryStatus(), {\n timeout: DEFAULT_TIMEOUT,\n }).catch(() => undefined);\n diagnostics.networkStatus = status;\n\n // Networking.\n\n diagnostics.swarms = serviceContext.networkManager.connectionLog?.swarms;\n }\n },\n ]);\n\n diagnostics.config = config.values;\n\n return diagnostics;\n};\n\nconst getSpaceStats = async (space: DataSpace): Promise<SpaceStats> => {\n const stats: SpaceStats = {\n key: space.key,\n metrics: space.metrics,\n\n epochs: space.inner.spaceState.credentials\n .filter(credentialTypeFilter('dxos.halo.credentials.Epoch'))\n .map((credential) => ({\n ...credential.subject.assertion,\n id: credential.id,\n })),\n\n members: await Promise.all(\n Array.from(space.inner.spaceState.members.values()).map(async (member) => ({\n role: member.role,\n identity: {\n did: await createDidFromIdentityKey(member.key),\n identityKey: member.key,\n profile: {\n displayName: member.assertion.profile?.displayName,\n },\n },\n presence:\n space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0\n ? SpaceMember.PresenceState.ONLINE\n : SpaceMember.PresenceState.OFFLINE,\n })),\n ),\n\n pipeline: {\n // TODO(burdon): Pick properties from credentials if needed.\n currentEpoch: space.automergeSpaceState.lastEpoch,\n appliedEpoch: space.automergeSpaceState.lastEpoch,\n\n controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),\n currentControlTimeframe: space.inner.controlPipeline.state.timeframe,\n targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,\n totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe,\n },\n };\n\n // TODO(burdon): Factor out.\n if (stats.metrics) {\n const { open, ready } = stats.metrics;\n stats.metrics.startupTime = open && ready && ready.getTime() - open.getTime();\n }\n\n return stats;\n};\n\nconst getStorageDiagnostics = async () => {\n if (typeof navigator === 'undefined' || !navigator.storage) {\n return undefined;\n }\n const map = new Map();\n const dir = await navigator.storage.getDirectory();\n for await (const filename of (dir as any)?.keys()) {\n const idx = filename.indexOf('-', filename.indexOf('-') + 1);\n if (idx === -1) {\n continue;\n }\n\n map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);\n }\n\n return Array.from(map.entries())\n .sort((a, b) => b[1] - a[1])\n .map(([file, count]) => ({ file, count }));\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type ClientServicesProvider } from '@dxos/client-protocol';\nimport { type Config } from '@dxos/config';\nimport { GetDiagnosticsRequest } from '@dxos/protocols/proto/dxos/client/services';\nimport { type JsonKeyOptions, jsonKeyReplacer } from '@dxos/util';\n\nimport { createCollectDiagnosticsBroadcastSender } from './diagnostics-broadcast';\n\nconst GET_DIAGNOSTICS_RPC_TIMEOUT = 10_000;\n\nexport interface CollectDiagnosticsBroadcastSender {\n broadcastDiagnosticsRequest(): any;\n}\n\nexport interface CollectDiagnosticsBroadcastHandler {\n start(): void;\n stop(): void;\n}\n\nexport class DiagnosticsCollector {\n private static broadcastSender = createCollectDiagnosticsBroadcastSender();\n\n public static async collect(\n config: Config | Config[] = [],\n services: ClientServicesProvider | null = null,\n options: JsonKeyOptions = {},\n ): Promise<any> {\n const serviceDiagnostics = await services?.services?.SystemService?.getDiagnostics(\n {\n keys: options.humanize\n ? GetDiagnosticsRequest.KEY_OPTION.HUMANIZE\n : options.truncate\n ? GetDiagnosticsRequest.KEY_OPTION.TRUNCATE\n : undefined,\n },\n { timeout: GET_DIAGNOSTICS_RPC_TIMEOUT },\n );\n\n const clientDiagnostics = {\n config,\n };\n\n const diagnostics =\n serviceDiagnostics != null\n ? { client: clientDiagnostics, services: serviceDiagnostics }\n : {\n client: clientDiagnostics,\n broadcast: await this.broadcastSender.broadcastDiagnosticsRequest(),\n };\n\n return JSON.parse(JSON.stringify(diagnostics, jsonKeyReplacer(options)));\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nexport * from './diagnostics';\nexport * from './diagnostics-collector';\nexport * from '#diagnostics-broadcast';\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Event, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { type CredentialSigner, verifyCredential } from '@dxos/credentials';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols/proto';\nimport { type ComplexSet } from '@dxos/util';\n\nimport { type AuthProvider, type AuthVerifier } from '../space';\n\nconst Credential = schema.getCodecForType('dxos.halo.credentials.Credential');\n\nexport const createAuthProvider =\n (signer: CredentialSigner): AuthProvider =>\n async (nonce) => {\n const credential = await signer.createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n subject: signer.getIssuer(),\n nonce,\n });\n\n return Credential.encode(credential);\n };\n\nexport type TrustedKeySetAuthVerifierProps = {\n // TODO(dmaretskyi): Change to `isTrusted: (key) => bool`.\n trustedKeysProvider: () => ComplexSet<PublicKey>;\n update: Event<void>;\n /**\n * Timeout to wait for the device key to be added to the trusted set.\n */\n authTimeout: number;\n};\n\n/**\n * Verifies credentials of another member in the space based on a set of trusted key.\n * Will wait up to `authTimeout` for the key to be added to the trusted set.\n */\nexport class TrustedKeySetAuthVerifier {\n private _ctx = new Context();\n\n constructor(private readonly _params: TrustedKeySetAuthVerifierProps) {}\n\n async close(): Promise<void> {\n await this._ctx.dispose();\n }\n\n get verifier(): AuthVerifier {\n return async (nonce, auth) => {\n const credential = Credential.decode(auth);\n log('authenticating...', { credential });\n\n const result = await verifyCredential(credential);\n if (result.kind === 'fail') {\n log('Invalid credential', { result });\n return false;\n }\n\n if (!credential.proof!.nonce || !Buffer.from(nonce).equals(credential.proof!.nonce)) {\n log('Invalid nonce', { nonce, credential });\n return false;\n }\n\n if (this._isTrustedKey(credential.issuer)) {\n log('key is trusted -- auth success', { key: credential.issuer });\n return true;\n }\n\n const trigger = new Trigger<boolean>();\n this._ctx.onDispose(() => {\n trigger.wake(false);\n });\n\n const clear = this._params.update.on(this._ctx, () => {\n if (this._isTrustedKey(credential.issuer)) {\n log('auth success', { key: credential.issuer });\n trigger.wake(true);\n } else {\n log('key is not currently in trusted set, waiting...', {\n key: credential.issuer,\n trusted: [...this._params.trustedKeysProvider()],\n });\n }\n });\n\n try {\n return await trigger.wait({ timeout: this._params.authTimeout });\n } catch {\n return false;\n } finally {\n clear();\n }\n };\n }\n\n private _isTrustedKey(deviceKey: PublicKey): boolean {\n const deviceSet = this._params.trustedKeysProvider();\n return deviceSet.has(deviceKey);\n }\n}\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Context } from '@dxos/context';\nimport { getCredentialAssertion } from '@dxos/credentials';\nimport { invariant } from '@dxos/invariant';\nimport { type KeyringApi } from '@dxos/keyring';\nimport { type PublicKey } from '@dxos/keys';\nimport { AlreadyJoinedError } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport type { DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionRequest,\n type AdmissionResponse,\n type IntroductionRequest,\n} from '@dxos/protocols/proto/dxos/halo/invitations';\n\nimport { type Identity, type JoinIdentityProps } from '../identity';\nimport { type InvitationProtocol } from './invitation-protocol';\n\nexport class DeviceInvitationProtocol implements InvitationProtocol {\n constructor(\n private readonly _keyring: KeyringApi,\n private readonly _getIdentity: () => Identity,\n private readonly _acceptIdentity: (identity: JoinIdentityProps) => Promise<Identity>,\n ) {}\n\n toJSON(): object {\n return {\n kind: 'device',\n };\n }\n\n checkCanInviteNewMembers(): Error | undefined {\n return undefined;\n }\n\n getInvitationContext(): Partial<Invitation> & Pick<Invitation, 'kind'> {\n return {\n kind: Invitation.Kind.DEVICE,\n };\n }\n\n async delegate(): Promise<PublicKey> {\n throw new Error('delegation not supported');\n }\n\n async cancelDelegation(): Promise<void> {\n throw new Error('delegation not supported');\n }\n\n async admit(_: Invitation, request: AdmissionRequest): Promise<AdmissionResponse> {\n invariant(request.device);\n const identity = this._getIdentity();\n const credential = await identity.admitDevice(request.device);\n invariant(getCredentialAssertion(credential)['@type'] === 'dxos.halo.credentials.AuthorizedDevice');\n\n return {\n device: {\n identityKey: identity.identityKey,\n haloSpaceKey: identity.haloSpaceKey,\n genesisFeedKey: identity.haloGenesisFeedKey,\n controlTimeframe: identity.controlPipeline.state.timeframe,\n credential,\n },\n };\n }\n\n checkInvitation(invitation: Partial<Invitation>): AlreadyJoinedError | undefined {\n try {\n const identity = this._getIdentity();\n if (identity) {\n return new AlreadyJoinedError({ message: 'Currently only one identity per client is supported.' });\n }\n } catch {\n // No identity.\n }\n }\n\n createIntroduction(): IntroductionRequest {\n return {};\n }\n\n async createAdmissionRequest(deviceProfile?: DeviceProfileDocument): Promise<AdmissionRequest> {\n const deviceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n\n return {\n device: {\n deviceKey,\n controlFeedKey,\n dataFeedKey,\n profile: deviceProfile,\n },\n };\n }\n\n async accept(_ctx: Context, response: AdmissionResponse, request: AdmissionRequest): Promise<Partial<Invitation>> {\n invariant(response.device);\n const { identityKey, haloSpaceKey, genesisFeedKey, controlTimeframe } = response.device;\n\n invariant(request.device);\n const { deviceKey, controlFeedKey, dataFeedKey, profile } = request.device;\n\n // TODO(wittjosiah): When multiple identities are supported, verify identity doesn't already exist before accepting.\n // ctx is unused here because _acceptIdentity uses ServiceContext's lifecycle ctx internally.\n\n await this._acceptIdentity({\n identityKey,\n deviceKey,\n haloSpaceKey,\n haloGenesisFeedKey: genesisFeedKey,\n controlFeedKey,\n dataFeedKey,\n controlTimeframe,\n deviceProfile: profile,\n authorizedDeviceCredential: response.device.credential,\n });\n\n return { identityKey };\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Mutex, type MutexGuard } from '@dxos/async';\nimport { type Context, ContextDisposedError, cancelWithContext } from '@dxos/context';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nexport const stateToString = (state: Invitation.State): string => {\n return Object.entries(Invitation.State).find(([key, val]) => val === state)?.[0] ?? 'unknown';\n};\n\nexport const computeExpirationTime = (invitation: Partial<Invitation>): Date | undefined => {\n if (!invitation.lifetime) {\n return;\n }\n return new Date((invitation.created?.getTime() ?? Date.now()) + invitation.lifetime * 1000);\n};\n\nexport const tryAcquireBeforeContextDisposed = async (ctx: Context, mutex: Mutex): Promise<MutexGuard> => {\n let guard: MutexGuard | undefined;\n return cancelWithContext(\n ctx,\n (async () => {\n guard = await mutex.acquire();\n if (ctx.disposed) {\n guard.release();\n guard = undefined;\n throw new ContextDisposedError();\n }\n return guard;\n })(),\n );\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type MutexGuard, scheduleMicroTask, scheduleTask } from '@dxos/async';\nimport { type Context } from '@dxos/context';\nimport { sign } from '@dxos/crypto';\nimport { type EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n EdgeAuthChallengeError,\n EdgeCallFailedError,\n type JoinSpaceRequest,\n type JoinSpaceResponseBody,\n} from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionRequest,\n type AdmissionResponse,\n type SpaceAdmissionRequest,\n} from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { trace } from '@dxos/tracing';\n\nimport { type InvitationProtocol } from './invitation-protocol';\nimport { type FlowLockHolder, type GuardedInvitationState } from './invitation-state';\nimport { tryAcquireBeforeContextDisposed } from './utils';\n\nexport interface EdgeInvitationHandlerCallbacks {\n onInvitationSuccess(ctx: Context, response: AdmissionResponse, request: AdmissionRequest): Promise<void>;\n}\n\nexport const MAX_RETRIES_PER_INVITATION = 5;\nexport const DEFAULT_REQUEST_RETRY_INTERVAL_MS = 3000;\nexport const DEFAULT_REQUEST_RETRY_JITTER_MS = 500;\n\nexport type EdgeInvitationConfig = {\n retryInterval?: number;\n retryJitter?: number;\n};\n\nexport class EdgeInvitationHandler implements FlowLockHolder {\n private _flowLock: MutexGuard | undefined;\n\n private readonly _retryInterval: number;\n private readonly _retryJitter: number;\n\n constructor(\n config: EdgeInvitationConfig | undefined,\n private readonly _client: EdgeHttpClient | undefined,\n private readonly _callbacks: EdgeInvitationHandlerCallbacks,\n ) {\n this._retryInterval = config?.retryInterval ?? DEFAULT_REQUEST_RETRY_INTERVAL_MS;\n this._retryJitter = config?.retryJitter ?? DEFAULT_REQUEST_RETRY_JITTER_MS;\n }\n\n public handle(\n ctx: Context,\n guardedState: GuardedInvitationState,\n protocol: InvitationProtocol,\n deviceProfile?: DeviceProfileDocument,\n ): void {\n if (!this._client) {\n log('edge disabled');\n return;\n }\n\n const invitation = guardedState.current;\n const spaceId = invitation.spaceId;\n const canBeHandledByEdge =\n invitation.authMethod !== Invitation.AuthMethod.SHARED_SECRET &&\n invitation.type === Invitation.Type.DELEGATED &&\n invitation.kind === Invitation.Kind.SPACE &&\n spaceId != null &&\n SpaceId.isValid(spaceId);\n\n if (!canBeHandledByEdge) {\n log('invitation could not be handled by edge', { invitation });\n return;\n }\n\n ctx.onDispose(() => {\n this._flowLock?.release();\n this._flowLock = undefined;\n });\n\n let requestCount = 0;\n const tryHandleInvitation = async () => {\n requestCount++;\n const admissionRequest = await protocol.createAdmissionRequest(deviceProfile);\n if (admissionRequest.space) {\n try {\n await this._handleSpaceInvitationFlow(ctx, guardedState, admissionRequest.space, spaceId);\n } catch (error) {\n if (error instanceof EdgeCallFailedError) {\n log.info('join space with edge unsuccessful', {\n reason: error.message,\n retryable: error.isRetryable,\n after: error.retryAfterMs ?? this._calculateNextRetryMs(),\n });\n if (error.isRetryable && requestCount < MAX_RETRIES_PER_INVITATION) {\n scheduleTask(ctx, tryHandleInvitation, error.retryAfterMs ?? this._calculateNextRetryMs());\n }\n } else if (requestCount < MAX_RETRIES_PER_INVITATION) {\n log.info('failed to handle invitation with edge', { error });\n scheduleTask(ctx, tryHandleInvitation, this._calculateNextRetryMs());\n }\n }\n }\n };\n scheduleMicroTask(ctx, tryHandleInvitation);\n }\n\n @trace.span({ op: 'invitation.edge' })\n private async _handleSpaceInvitationFlow(\n ctx: Context,\n guardedState: GuardedInvitationState,\n admissionRequest: SpaceAdmissionRequest,\n spaceId: SpaceId,\n ): Promise<void> {\n try {\n log('edge invitation flow');\n this._flowLock = await tryAcquireBeforeContextDisposed(ctx, guardedState.mutex);\n log.verbose('edge invitation flow acquired the lock');\n\n guardedState.set(this, Invitation.State.CONNECTING);\n\n const response = await this._joinSpaceByInvitation(ctx, guardedState, spaceId, {\n identityKey: admissionRequest.identityKey.toHex(),\n invitationId: guardedState.current.invitationId,\n });\n\n const admissionResponse = await this._mapToAdmissionResponse(response);\n await this._callbacks.onInvitationSuccess(ctx, admissionResponse, { space: admissionRequest });\n } catch (error) {\n guardedState.set(this, Invitation.State.ERROR);\n throw error;\n } finally {\n this._flowLock?.release();\n this._flowLock = undefined;\n }\n }\n\n private async _mapToAdmissionResponse(edgeResponse: JoinSpaceResponseBody): Promise<AdmissionResponse> {\n const credentialBytes = Buffer.from(edgeResponse.spaceMemberCredential, 'base64');\n const codec = schema.getCodecForType('dxos.halo.credentials.Credential');\n return {\n space: {\n credential: codec.decode(credentialBytes),\n },\n };\n }\n\n private async _joinSpaceByInvitation(\n ctx: Context,\n guardedState: GuardedInvitationState,\n spaceId: SpaceId,\n request: JoinSpaceRequest,\n ): Promise<JoinSpaceResponseBody> {\n invariant(this._client);\n try {\n return await this._client.joinSpaceByInvitation(ctx, spaceId, request);\n } catch (error: any) {\n if (error instanceof EdgeAuthChallengeError) {\n const publicKey = guardedState.current.guestKeypair?.publicKey;\n const privateKey = guardedState.current.guestKeypair?.privateKey;\n if (!privateKey || !publicKey) {\n throw error;\n }\n const signature = sign(Buffer.from(error.challenge, 'base64'), privateKey);\n return this._client.joinSpaceByInvitation(ctx, spaceId, {\n ...request,\n signature: Buffer.from(signature).toString('base64'),\n });\n } else {\n throw error;\n }\n }\n }\n\n public hasFlowLock(): boolean {\n return this._flowLock != null;\n }\n\n private _calculateNextRetryMs(): number {\n return this._retryInterval + Math.random() * this._retryJitter;\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Mutex, type MutexGuard, Trigger } from '@dxos/async';\nimport { Context, cancelWithContext } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { InvalidInvitationExtensionRoleError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type InvitationHostService, InvitationOptions } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport { type FlowLockHolder } from './invitation-state';\nimport { tryAcquireBeforeContextDisposed } from './utils';\n\nconst OPTIONS_TIMEOUT = 10_000;\n\ntype InvitationGuestExtensionCallbacks = {\n // Deliberately not async to not block the extensions opening.\n onOpen: (ctx: Context, extensionCtx: ExtensionContext) => void;\n onError: (error: Error) => void;\n\n onStateUpdate: (newState: Invitation.State) => void;\n};\n\n/**\n * Guest's side for a connection to a concrete peer in p2p network during invitation.\n */\nexport class InvitationGuestExtension\n extends RpcExtension<\n { InvitationHostService: InvitationHostService },\n { InvitationHostService: InvitationHostService }\n >\n implements FlowLockHolder\n{\n private _ctx = new Context();\n private _remoteOptions?: InvitationOptions;\n private _remoteOptionsTrigger = new Trigger();\n /**\n * Held to allow only one invitation flow at a time to be active.\n */\n private _invitationFlowLock: MutexGuard | null = null;\n\n constructor(\n private readonly _invitationFlowMutex: Mutex,\n private readonly _callbacks: InvitationGuestExtensionCallbacks,\n ) {\n super({\n requested: {\n InvitationHostService: schema.getService('dxos.halo.invitations.InvitationHostService'),\n },\n exposed: {\n InvitationHostService: schema.getService('dxos.halo.invitations.InvitationHostService'),\n },\n });\n }\n\n public hasFlowLock(): boolean {\n return this._invitationFlowLock != null;\n }\n\n protected override async getHandlers(): Promise<{ InvitationHostService: InvitationHostService }> {\n return {\n InvitationHostService: {\n options: async (options) => {\n invariant(!this._remoteOptions, 'Remote options already set.');\n this._remoteOptions = options;\n this._remoteOptionsTrigger.wake();\n },\n introduce: () => {\n throw new Error('Method not allowed.');\n },\n authenticate: () => {\n throw new Error('Method not allowed.');\n },\n admit: () => {\n throw new Error('Method not allowed.');\n },\n },\n };\n }\n\n override async onOpen(context: ExtensionContext): Promise<void> {\n await super.onOpen(context);\n\n try {\n log.verbose('guest acquire lock');\n this._invitationFlowLock = await tryAcquireBeforeContextDisposed(this._ctx, this._invitationFlowMutex);\n log.verbose('guest lock acquired');\n await cancelWithContext(\n this._ctx,\n this.rpc.InvitationHostService.options({ role: InvitationOptions.Role.GUEST }),\n );\n log.verbose('options sent');\n await cancelWithContext(this._ctx, this._remoteOptionsTrigger.wait({ timeout: OPTIONS_TIMEOUT }));\n log.verbose('options received');\n if (this._remoteOptions?.role !== InvitationOptions.Role.HOST) {\n throw new InvalidInvitationExtensionRoleError({\n context: {\n expected: InvitationOptions.Role.HOST,\n remoteOptions: this._remoteOptions,\n remotePeerId: context.remotePeerId,\n },\n });\n }\n\n this._callbacks.onOpen(this._ctx, context);\n } catch (err: any) {\n if (this._invitationFlowLock != null) {\n this._callbacks.onError(err);\n }\n if (!this._ctx.disposed) {\n context.close(err);\n }\n }\n }\n\n override async onClose(): Promise<void> {\n await this._destroy();\n }\n\n override async onAbort(): Promise<void> {\n await this._destroy();\n }\n\n private async _destroy(): Promise<void> {\n await this._ctx.dispose();\n if (this._invitationFlowLock != null) {\n this._invitationFlowLock.release();\n this._invitationFlowLock = null;\n log.verbose('invitation flow lock released');\n }\n }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Mutex, type MutexGuard, Trigger, scheduleTask } from '@dxos/async';\nimport { Context, cancelWithContext } from '@dxos/context';\nimport { randomBytes, verify } from '@dxos/crypto';\nimport { InvariantViolation, invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { InvalidInvitationExtensionRoleError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionRequest,\n type AdmissionResponse,\n AuthenticationResponse,\n type InvitationHostService,\n InvitationOptions,\n} from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport type { FlowLockHolder } from './invitation-state';\nimport { stateToString, tryAcquireBeforeContextDisposed } from './utils';\n\n/// Timeout for the options exchange.\nconst OPTIONS_TIMEOUT = 10_000;\n\nexport const MAX_OTP_ATTEMPTS = 3;\n\ntype InvitationHostExtensionCallbacks = {\n activeInvitation: Invitation | null;\n\n // Deliberately not async to not block the extensions opening.\n onOpen: (ctx: Context, extensionCtx: ExtensionContext) => void;\n onError: (error: Error) => void;\n\n onStateUpdate: (newState: Invitation.State) => void;\n\n admit: (request: AdmissionRequest) => Promise<AdmissionResponse>;\n};\n\n/**\n * Host's side for a connection to a concrete peer in p2p network during invitation.\n */\nexport class InvitationHostExtension\n extends RpcExtension<\n { InvitationHostService: InvitationHostService },\n { InvitationHostService: InvitationHostService }\n >\n implements FlowLockHolder\n{\n /**\n * @internal\n */\n private _ctx = new Context();\n private _remoteOptions?: InvitationOptions;\n private _remoteOptionsTrigger = new Trigger();\n\n private _challenge?: Buffer = undefined;\n\n public guestProfile?: ProfileDocument = undefined;\n\n public authenticationPassed = false;\n\n /**\n * Retry counter for SHARED_SECRET authentication method.\n */\n public authenticationRetry = 0;\n\n /**\n * Resolved when admission is completed.\n */\n public completedTrigger = new Trigger<PublicKey>();\n\n /**\n * Held to allow only one invitation flow at a time to be active.\n */\n private _invitationFlowLock: MutexGuard | null = null;\n\n constructor(\n private readonly _invitationFlowMutex: Mutex,\n private readonly _callbacks: InvitationHostExtensionCallbacks,\n ) {\n super({\n requested: {\n InvitationHostService: schema.getService('dxos.halo.invitations.InvitationHostService'),\n },\n exposed: {\n InvitationHostService: schema.getService('dxos.halo.invitations.InvitationHostService'),\n },\n });\n }\n\n public hasFlowLock(): boolean {\n return this._invitationFlowLock != null;\n }\n\n protected override async getHandlers(): Promise<{ InvitationHostService: InvitationHostService }> {\n return {\n // TODO(dmaretskyi): For now this is just forwarding the data to callbacks since we don't have session-specific logic.\n // Perhaps in the future we will have more complex logic here.\n InvitationHostService: {\n options: async (options) => {\n invariant(!this._remoteOptions, 'Remote options already set.');\n this._remoteOptions = options;\n this._remoteOptionsTrigger.wake();\n },\n\n introduce: async (request) => {\n const { profile, invitationId } = request;\n log('introducing host invitation');\n\n const invitation = this._requireActiveInvitation();\n this._assertInvitationState(Invitation.State.CONNECTED);\n if (invitationId !== invitation?.invitationId) {\n log.warn('incorrect invitationId', { expected: invitation.invitationId, actual: invitationId });\n this._callbacks.onError(new Error('Incorrect invitationId.'));\n scheduleTask(this._ctx, () => this.close());\n // TODO(dmaretskyi): Better error handling.\n return {\n authMethod: Invitation.AuthMethod.NONE,\n };\n }\n\n log.verbose('guest introduced themselves', { guestProfile: profile });\n this.guestProfile = profile;\n this._callbacks.onStateUpdate(Invitation.State.READY_FOR_AUTHENTICATION);\n this._challenge =\n invitation.authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY ? randomBytes(32) : undefined;\n\n log('introduced host invitation');\n return {\n authMethod: invitation.authMethod,\n challenge: this._challenge,\n };\n },\n\n authenticate: async ({ authCode: code, signedChallenge }) => {\n log('authenticating host invitation');\n\n const invitation = this._requireActiveInvitation();\n log.verbose('received authentication request', { authCode: code });\n let status = AuthenticationResponse.Status.OK;\n\n this._assertInvitationState([Invitation.State.AUTHENTICATING, Invitation.State.READY_FOR_AUTHENTICATION]);\n this._callbacks.onStateUpdate(Invitation.State.AUTHENTICATING);\n\n switch (invitation.authMethod) {\n case Invitation.AuthMethod.NONE: {\n log('authentication not required');\n return { status: AuthenticationResponse.Status.OK };\n }\n\n case Invitation.AuthMethod.SHARED_SECRET: {\n if (invitation.authCode) {\n if (this.authenticationRetry++ > MAX_OTP_ATTEMPTS) {\n status = AuthenticationResponse.Status.INVALID_OPT_ATTEMPTS;\n } else if (code !== invitation.authCode) {\n status = AuthenticationResponse.Status.INVALID_OTP;\n } else {\n this.authenticationPassed = true;\n }\n }\n break;\n }\n\n case Invitation.AuthMethod.KNOWN_PUBLIC_KEY: {\n if (!invitation.guestKeypair) {\n status = AuthenticationResponse.Status.INTERNAL_ERROR;\n break;\n }\n const isSignatureValid =\n this._challenge &&\n verify(\n this._challenge,\n Buffer.from(signedChallenge ?? []),\n invitation.guestKeypair.publicKey.asBuffer(),\n );\n if (isSignatureValid) {\n this.authenticationPassed = true;\n } else {\n status = AuthenticationResponse.Status.INVALID_SIGNATURE;\n }\n break;\n }\n\n default: {\n log.error('invalid authentication method', { authMethod: invitation.authMethod });\n status = AuthenticationResponse.Status.INTERNAL_ERROR;\n break;\n }\n }\n\n if (![AuthenticationResponse.Status.OK, AuthenticationResponse.Status.INVALID_OTP].includes(status)) {\n this._callbacks.onError(new Error(`Authentication failed, with status=${status}`));\n scheduleTask(this._ctx, () => this.close());\n return { status };\n }\n\n log('authenticated host invitation', { status });\n return { status };\n },\n\n admit: async (request) => {\n log('admitting guest');\n const invitation = this._requireActiveInvitation();\n\n try {\n // Check authenticated.\n if (isAuthenticationRequired(invitation)) {\n this._assertInvitationState(Invitation.State.AUTHENTICATING);\n if (!this.authenticationPassed) {\n throw new Error('Not authenticated');\n }\n }\n\n const response = await this._callbacks.admit(request);\n\n log('admitted guest');\n return response;\n } catch (err: any) {\n this._callbacks.onError(err);\n throw err;\n }\n },\n },\n };\n }\n\n override async onOpen(context: ExtensionContext): Promise<void> {\n await super.onOpen(context);\n\n try {\n log.verbose('host acquire lock');\n this._invitationFlowLock = await tryAcquireBeforeContextDisposed(this._ctx, this._invitationFlowMutex);\n log.verbose('host lock acquired');\n this._callbacks.onStateUpdate(Invitation.State.CONNECTING);\n await this.rpc.InvitationHostService.options({ role: InvitationOptions.Role.HOST });\n log.verbose('options sent');\n await cancelWithContext(this._ctx, this._remoteOptionsTrigger.wait({ timeout: OPTIONS_TIMEOUT }));\n log.verbose('options received');\n if (this._remoteOptions?.role !== InvitationOptions.Role.GUEST) {\n throw new InvalidInvitationExtensionRoleError({\n context: {\n expected: InvitationOptions.Role.GUEST,\n remoteOptions: this._remoteOptions,\n remotePeerId: context.remotePeerId,\n },\n });\n }\n this._callbacks.onStateUpdate(Invitation.State.CONNECTED);\n this._callbacks.onOpen(this._ctx, context);\n } catch (err: any) {\n if (this._invitationFlowLock != null) {\n this._callbacks.onError(err);\n }\n if (!this._ctx.disposed) {\n context.close(err);\n }\n }\n }\n\n private _requireActiveInvitation(): Invitation {\n const invitation = this._callbacks.activeInvitation;\n if (invitation == null) {\n scheduleTask(this._ctx, () => this.close());\n throw new Error('Active invitation not found');\n }\n return invitation;\n }\n\n private _assertInvitationState(stateOrMany: Invitation.State | Invitation.State[]): void {\n const invitation = this._requireActiveInvitation();\n const validStates = Array.isArray(stateOrMany) ? stateOrMany : [stateOrMany];\n if (!validStates.includes(invitation.state)) {\n scheduleTask(this._ctx, () => this.close());\n throw new InvariantViolation(\n `Expected ${stateToString(invitation.state)} to be one of [${validStates.map(stateToString).join(', ')}]`,\n );\n }\n }\n\n override async onClose(): Promise<void> {\n await this._destroy();\n }\n\n override async onAbort(): Promise<void> {\n await this._destroy();\n }\n\n private async _destroy(): Promise<void> {\n await this._ctx.dispose();\n if (this._invitationFlowLock != null) {\n this._invitationFlowLock?.release();\n this._invitationFlowLock = null;\n log.verbose('invitation flow lock released');\n }\n }\n}\n\nexport const isAuthenticationRequired = (invitation: Invitation) =>\n invitation.authMethod !== Invitation.AuthMethod.NONE;\n","/**\n * A utility object for serializing invitation state changes by multiple concurrent\n * invitation flow connections.\n */\n//\n// Copyright 2024 DXOS.org\n//\n\nimport { Mutex, type PushStream } from '@dxos/async';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { stateToString } from './utils';\n\nexport interface FlowLockHolder {\n hasFlowLock(): boolean;\n}\n\nexport interface GuardedInvitationState {\n mutex: Mutex;\n current: Invitation;\n\n complete(newState: Partial<Invitation>): void;\n set(lockHolder: FlowLockHolder | null, newState: Invitation.State): boolean;\n error(lockHolder: FlowLockHolder | null, error: any): boolean;\n}\n\nexport const createGuardedInvitationState = (\n ctx: Context,\n invitation: Invitation,\n stream: PushStream<Invitation>,\n): GuardedInvitationState => {\n const mutex = new Mutex();\n let lastActiveLockHolder: FlowLockHolder | null = null;\n let currentInvitation = { ...invitation };\n const isStateChangeAllowed = (lockHolder: FlowLockHolder | null) => {\n if (ctx.disposed || (lockHolder !== null && mutex.isLocked() && !lockHolder.hasFlowLock())) {\n return false;\n }\n return lockHolder == null || lastActiveLockHolder !== lockHolder || isNonTerminalState(currentInvitation.state);\n };\n return {\n mutex,\n get current() {\n return currentInvitation;\n },\n complete: (newState: Partial<Invitation>) => {\n logStateUpdate(currentInvitation, undefined, invitation.state);\n currentInvitation = { ...currentInvitation, ...newState };\n stream.next(currentInvitation);\n return ctx.dispose();\n },\n set: (lockHolder: FlowLockHolder | null, newState: Invitation.State): boolean => {\n if (isStateChangeAllowed(lockHolder)) {\n logStateUpdate(currentInvitation, lockHolder, newState);\n currentInvitation = { ...currentInvitation, state: newState };\n stream.next(currentInvitation);\n lastActiveLockHolder = lockHolder;\n return true;\n }\n return false;\n },\n error: (lockHolder: FlowLockHolder | null, error: any): boolean => {\n if (isStateChangeAllowed(lockHolder)) {\n logStateUpdate(currentInvitation, lockHolder, Invitation.State.ERROR, error);\n currentInvitation = { ...currentInvitation, state: Invitation.State.ERROR };\n stream.next(currentInvitation);\n stream.error(error);\n lastActiveLockHolder = lockHolder;\n return true;\n }\n return false;\n },\n };\n};\n\nconst logStateUpdate = (invitation: Invitation, actor: any, newState: Invitation.State, error?: Error) => {\n const logContext = {\n invitationId: invitation.invitationId,\n actor: actor?.constructor.name,\n newState: stateToString(newState),\n oldState: stateToString(invitation.state),\n error: error?.message,\n errorStack: error?.stack,\n };\n log.verbose('dxos.sdk.invitations-handler.state.update', logContext);\n};\n\nconst isNonTerminalState = (currentState: Invitation.State): boolean => {\n return ![\n Invitation.State.SUCCESS,\n Invitation.State.ERROR,\n Invitation.State.CANCELLED,\n Invitation.State.TIMEOUT,\n Invitation.State.EXPIRED,\n ].includes(currentState);\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport type { SwarmController, Topology } from '@dxos/network-manager';\nimport { InvitationOptions } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { ComplexSet } from '@dxos/util';\n\n/**\n * Hosts are listening on an invitation topic.\n * They initiate a connection with any new peer if they are not currently in the invitation flow\n * with another peer (connected.length > 0).\n * When the invitation flow ends guest leaves the swarm and topology is updated once again,\n * so we can connect to the next peer we haven't tried yet.\n * If the peer turns out to be a host or a malicious guest their ID is remembered so that we don't try\n * to establish a connection with them again.\n *\n * Guests don't initiate connections. They accept all connections because if we reject,\n * the host won't retry their offer.\n * Even if we started an invitation flow with one host we might want to try other hosts in case\n * the first one failed due to a network error, so multiple connections are accepted.\n */\nexport class InvitationTopology implements Topology {\n private _controller?: SwarmController;\n\n /**\n * Peers we tried to establish a connection with.\n * In invitation flow peers are assigned random ids when they join the swarm, so we'll retry\n * a peer if they reload an invitation.\n *\n * Consider keeping a separate set for peers we know are hosts and have some retry timeout\n * for guests we failed an invitation flow with (potentially due to a network error).\n */\n private _seenPeers = new ComplexSet<PublicKey>(PublicKey.hash);\n\n constructor(private readonly _role: InvitationOptions.Role) {}\n\n init(controller: SwarmController): void {\n invariant(!this._controller, 'Already initialized.');\n this._controller = controller;\n }\n\n update(): void {\n invariant(this._controller, 'Not initialized.');\n const { ownPeerId, candidates, connected, allPeers } = this._controller.getState();\n\n // guests don't initiate connections\n if (this._role === InvitationOptions.Role.GUEST) {\n return;\n }\n\n // don't start a connection while we have an active invitation flow\n if (connected.length > 0) {\n // update seenPeers here as well in case another host initiated a connection with us\n connected.forEach((c) => this._seenPeers.add(c));\n return;\n }\n\n const firstUnknownPeer = candidates.find((peerId) => !this._seenPeers.has(peerId));\n // cleanup\n this._seenPeers = new ComplexSet<PublicKey>(\n PublicKey.hash,\n allPeers.filter((peerId) => this._seenPeers.has(peerId)),\n );\n if (firstUnknownPeer != null) {\n log('invitation connect', { ownPeerId, remotePeerId: firstUnknownPeer });\n this._controller.connect(firstUnknownPeer);\n this._seenPeers.add(firstUnknownPeer);\n }\n }\n\n async onOffer(peer: PublicKey): Promise<boolean> {\n invariant(this._controller, 'Not initialized.');\n return !this._seenPeers.has(peer);\n }\n\n async destroy(): Promise<void> {\n this._seenPeers.clear();\n }\n\n toString(): string {\n return `InvitationTopology(${this._role === InvitationOptions.Role.GUEST ? 'guest' : 'host'})`;\n }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\n\nimport { type PushStream, TimeoutError, type Trigger, scheduleTask } from '@dxos/async';\nimport { INVITATION_TIMEOUT, getExpirationTime } from '@dxos/client-protocol';\nimport { type Context, ContextDisposedError } from '@dxos/context';\nimport { createKeyPair, sign } from '@dxos/crypto';\nimport { type EdgeHttpClient, EdgeHttpClientService } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n type SwarmConnection,\n type SwarmNetworkManager,\n SwarmNetworkManagerService,\n createTeleportProtocolFactory,\n} from '@dxos/network-manager';\nimport { InvalidInvitationError, InvalidInvitationExtensionRoleError } from '@dxos/protocols';\nimport { type AdmissionKeypair, Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { AuthenticationResponse, type IntroductionResponse } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { InvitationOptions } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type ExtensionContext, type TeleportExtension, type TeleportProps } from '@dxos/teleport';\nimport { trace as _trace } from '@dxos/tracing';\nimport { ComplexSet } from '@dxos/util';\n\nimport { type EdgeInvitationConfig, EdgeInvitationHandler } from './edge-invitation-handler';\nimport { InvitationGuestExtension } from './invitation-guest-extenstion';\nimport { InvitationHostExtension, MAX_OTP_ATTEMPTS, isAuthenticationRequired } from './invitation-host-extension';\nimport { type InvitationProtocol } from './invitation-protocol';\nimport { createGuardedInvitationState } from './invitation-state';\nimport { InvitationTopology } from './invitation-topology';\n\nconst metrics = _trace.metrics;\n\nconst MAX_DELEGATED_INVITATION_HOST_TRIES = 3;\n\nexport type InvitationConnectionProps = {\n teleport: Partial<TeleportProps>;\n edgeInvitations?: EdgeInvitationConfig;\n};\n\n/**\n * Generic handler for Halo and Space invitations.\n * Handles the life-cycle of invitations between peers.\n *\n * Host\n * - Creates an invitation containing a swarm topic (which can be shared via a URL, QR code, or direct message).\n * - Joins the swarm with the topic and waits for guest's introduction.\n * - Wait for guest to authenticate with challenge specified in the invitation.\n * - Waits for guest to present credentials (containing local device and feed keys).\n * - Writes credentials to control feed then exits or waits for more guests (multi use invitations).\n *\n * Guest\n * - Joins the swarm with the topic.\n * - Sends an introduction.\n * - Submits the challenge.\n * - If Space handler then creates a local cloned space (with genesis block).\n * - Sends admission credentials.\n * ```\n * [Guest] [Host]\n * |------------------------------------Introduce-->|\n * |-------------------------------[Authenticate]-->|\n * |----------------------------------------Admit-->|\n * ```\n *\n * TODO: consider refactoring using xstate making the logic separation more explicit:\n * TODO: the flow logic should either be contained in invitations-handler or in extensions, not be split across\n * TODO: potentially re-evaluate host-side API to allow multiple concurrent connection, so that mutex can be removed\n */\n/**\n * Effect service tag for {@link InvitationsHandler}.\n */\nexport class InvitationsHandlerService extends EffectContext.Tag('@dxos/client-services/InvitationsHandler')<\n InvitationsHandlerService,\n InvitationsHandler\n>() {}\n\nexport class InvitationsHandler {\n /**\n * @internal\n */\n constructor(\n private readonly _networkManager: SwarmNetworkManager,\n private readonly _edgeClient?: EdgeHttpClient,\n private readonly _connectionProps?: InvitationConnectionProps,\n ) {}\n\n handleInvitationFlow(\n ctx: Context,\n stream: PushStream<Invitation>,\n protocol: InvitationProtocol,\n invitation: Invitation,\n ): void {\n log.verbose('dxos.sdk.invitations-handler.handleInvitationFlow', {\n state: invitation.state,\n invitationId: invitation.invitationId,\n kind: invitation.kind,\n type: invitation.type,\n });\n metrics.increment('dxos.invitation.host');\n\n const hostSpanId = `invitation-host-${invitation.invitationId}`;\n // Reassign ctx to the child context so downstream `@trace.span` calls stay in the same trace.\n // Link child -> parent disposal so `ctx.dispose()` inside this flow still completes the\n // invitation stream (the caller's ctx owns `stream.complete()` via onDispose).\n // Do NOT await `invitationCtx.dispose()` here: `derive()` registers a parent -> child\n // dispose hook, so awaiting the parent dispose would re-enter the still-pending child\n // dispose promise and deadlock.\n const invitationCtx = ctx;\n ctx =\n _trace.spanStart({\n id: hostSpanId,\n instance: this,\n methodName: 'handleInvitationFlow',\n parentCtx: ctx,\n op: 'invitation.host',\n attributes: {\n 'ctx.dxos.invitation.id': invitation.invitationId,\n 'ctx.dxos.invitation.kind': Invitation.Kind[invitation.kind],\n },\n }) ?? ctx;\n if (ctx !== invitationCtx) {\n ctx.onDispose(() => {\n void invitationCtx.dispose();\n });\n }\n ctx.onDispose(() => _trace.spanEnd(hostSpanId));\n const guardedState = createGuardedInvitationState(ctx, invitation, stream);\n // Called for every connecting peer.\n const createExtension = (): InvitationHostExtension => {\n const extension = new InvitationHostExtension(guardedState.mutex, {\n get activeInvitation() {\n return ctx.disposed ? null : guardedState.current;\n },\n\n onStateUpdate: (newState: Invitation.State): Invitation => {\n if (newState !== Invitation.State.ERROR && newState !== Invitation.State.TIMEOUT) {\n guardedState.set(extension, newState);\n }\n return guardedState.current;\n },\n\n admit: async (admissionRequest) => {\n try {\n log.verbose('dxos.sdk.invitations-handler.host.admit', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n });\n const deviceKey = admissionRequest.device?.deviceKey ?? admissionRequest.space?.deviceKey;\n invariant(deviceKey);\n const admissionResponse = await protocol.admit(invitation, admissionRequest, extension.guestProfile);\n\n // Updating credentials complete.\n extension.completedTrigger.wake(deviceKey);\n\n return admissionResponse;\n } catch (err: any) {\n // TODO(burdon): Generic RPC callback to report error to client.\n guardedState.error(extension, err);\n throw err; // Propagate error to guest.\n }\n },\n\n onOpen: (connectionCtx: Context, extensionsCtx: ExtensionContext) => {\n let admitted = false;\n connectionCtx.onDispose(() => {\n if (!admitted) {\n guardedState.set(extension, Invitation.State.CONNECTING);\n }\n });\n\n scheduleTask(connectionCtx, async () => {\n try {\n log('opening host invitation handler');\n log.verbose('connected', { ...protocol.toJSON() });\n const deviceKey = await extension.completedTrigger.wait({ timeout: invitation.timeout });\n log.verbose('admitted guest', { guest: deviceKey, ...protocol.toJSON() });\n guardedState.set(extension, Invitation.State.SUCCESS);\n metrics.increment('dxos.invitation.success');\n log('host invitation handler opened');\n admitted = true;\n\n if (!invitation.multiUse) {\n await ctx.dispose();\n }\n } catch (err: any) {\n const stateChanged = guardedState.set(extension, Invitation.State.CONNECTING);\n if (err instanceof TimeoutError) {\n if (stateChanged) {\n metrics.increment('dxos.invitation.timeout');\n log.verbose('timeout', { ...protocol.toJSON() });\n }\n } else {\n if (stateChanged) {\n metrics.increment('dxos.invitation.failed');\n log.error('failed', err);\n }\n }\n // Close connection\n extensionsCtx.close(err);\n }\n });\n },\n onError: (err) => {\n const stateChanged = guardedState.set(extension, Invitation.State.CONNECTING);\n if (err instanceof InvalidInvitationExtensionRoleError) {\n log('invalid role', { ...err.context });\n return;\n }\n if (err instanceof TimeoutError) {\n if (stateChanged) {\n metrics.increment('dxos.invitation.timeout');\n log.verbose('timeout', { err });\n }\n } else {\n if (stateChanged) {\n metrics.increment('dxos.invitation.failed');\n log.error('failed', err);\n }\n }\n },\n });\n\n return extension;\n };\n\n const expiresOn = getExpirationTime(invitation);\n if (expiresOn) {\n if (expiresOn.getTime() < Date.now()) {\n log.warn('invitation has already expired');\n guardedState.set(null, Invitation.State.EXPIRED);\n void ctx.dispose().catch((err) => log.catch(err));\n return;\n }\n scheduleTask(\n ctx,\n async () => {\n // ensure the swarm is closed before changing state and closing the stream.\n await swarmConnection.close(ctx);\n guardedState.set(null, Invitation.State.EXPIRED);\n metrics.increment('dxos.invitation.expired');\n await ctx.dispose();\n },\n expiresOn.getTime() - Date.now(),\n );\n }\n\n let swarmConnection: SwarmConnection;\n scheduleTask(ctx, async () => {\n swarmConnection = await this._joinSwarm(ctx, invitation, InvitationOptions.Role.HOST, createExtension);\n guardedState.set(null, Invitation.State.CONNECTING);\n });\n }\n\n acceptInvitation(\n ctx: Context,\n stream: PushStream<Invitation>,\n protocol: InvitationProtocol,\n invitation: Invitation,\n otpEnteredTrigger: Trigger<string>,\n deviceProfile?: DeviceProfileDocument,\n ): void {\n log.verbose('dxos.sdk.invitations-handler.acceptInvitation', {\n state: invitation.state,\n invitationId: invitation.invitationId,\n kind: invitation.kind,\n type: invitation.type,\n });\n const { timeout = INVITATION_TIMEOUT } = invitation;\n\n const guestSpanId = `invitation-guest-${invitation.invitationId}`;\n // Reassign ctx to the child context returned by spanStart so downstream calls\n // (`edgeInvitationHandler.handle`, `_joinSwarm`, etc.) inherit this span as their\n // parent rather than starting a new root trace.\n // Link child -> parent disposal so `ctx.dispose()` inside this flow still completes the\n // invitation stream. See note in `handleInvitationFlow`: must not await the parent\n // dispose here (`derive()` registers a parent -> child dispose hook, so awaiting would\n // re-enter the still-pending child dispose promise and deadlock).\n const invitationCtx = ctx;\n ctx =\n _trace.spanStart({\n id: guestSpanId,\n instance: this,\n methodName: 'acceptInvitation',\n parentCtx: ctx,\n op: 'invitation.guest',\n attributes: {\n 'ctx.dxos.invitation.id': invitation.invitationId,\n 'ctx.dxos.invitation.kind': Invitation.Kind[invitation.kind],\n },\n }) ?? ctx;\n if (ctx !== invitationCtx) {\n ctx.onDispose(() => {\n void invitationCtx.dispose();\n });\n }\n ctx.onDispose(() => _trace.spanEnd(guestSpanId));\n\n if (deviceProfile) {\n invariant(invitation.kind === Invitation.Kind.DEVICE, 'deviceProfile provided for non-device invitation');\n }\n\n const triedPeersIds = new ComplexSet(PublicKey.hash);\n const guardedState = createGuardedInvitationState(ctx, invitation, stream);\n\n const shouldCancelInvitationFlow = (extension: InvitationGuestExtension) => {\n const isLockedByAnotherConnection = guardedState.mutex.isLocked() && !extension.hasFlowLock();\n log('should cancel invitation flow', {\n isLockedByAnotherConnection,\n invitationType: Invitation.Type.DELEGATED,\n triedPeers: triedPeersIds.size,\n });\n if (isLockedByAnotherConnection) {\n return false;\n }\n // for delegated invitations we might try with other hosts and will dispose either after\n // a timeout or when the number of tries was exceeded\n return invitation.type !== Invitation.Type.DELEGATED || triedPeersIds.size >= MAX_DELEGATED_INVITATION_HOST_TRIES;\n };\n\n let admitted = false;\n const createExtension = (): InvitationGuestExtension => {\n const extension = new InvitationGuestExtension(guardedState.mutex, {\n onStateUpdate: (newState: Invitation.State) => {\n guardedState.set(extension, newState);\n },\n onOpen: (connectionCtx: Context, extensionCtx: ExtensionContext) => {\n triedPeersIds.add(extensionCtx.remotePeerId);\n\n if (admitted) {\n extensionCtx.close();\n return;\n }\n\n connectionCtx.onDispose(async () => {\n log.verbose('extension disposed', { admitted, currentState: guardedState.current.state });\n if (!admitted) {\n guardedState.error(extension, new ContextDisposedError());\n if (shouldCancelInvitationFlow(extension)) {\n await ctx.dispose();\n }\n }\n });\n\n scheduleTask(connectionCtx, async () => {\n try {\n log('opening guest invitation handler');\n\n scheduleTask(\n connectionCtx,\n () => {\n guardedState.set(extension, Invitation.State.TIMEOUT);\n extensionCtx.close();\n },\n timeout,\n );\n\n log.verbose('dxos.sdk.invitations-handler.guest.connected', { ...protocol.toJSON() });\n guardedState.set(extension, Invitation.State.CONNECTED);\n\n // 1. Introduce guest to host.\n log.verbose('dxos.sdk.invitations-handler.guest.introduce', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n });\n const introductionResponse = await extension.rpc.InvitationHostService.introduce({\n invitationId: invitation.invitationId,\n ...protocol.createIntroduction(),\n });\n log.verbose('dxos.sdk.invitations-handler.guest.introduce-response', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n authMethod: introductionResponse.authMethod,\n });\n invitation.authMethod = introductionResponse.authMethod;\n\n // 2. Get authentication code.\n if (isAuthenticationRequired(invitation)) {\n switch (invitation.authMethod) {\n case Invitation.AuthMethod.SHARED_SECRET:\n await this._handleGuestOtpAuth(\n extension,\n (state) => guardedState.set(extension, state),\n otpEnteredTrigger,\n { timeout },\n );\n break;\n case Invitation.AuthMethod.KNOWN_PUBLIC_KEY:\n await this._handleGuestKpkAuth(\n extension,\n (state) => guardedState.set(extension, state),\n invitation,\n introductionResponse,\n );\n break;\n }\n }\n\n // 3. Send admission credentials to host (with local space keys).\n log.verbose('dxos.sdk.invitations-handler.guest.request-admission', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n });\n const admissionRequest = await protocol.createAdmissionRequest(deviceProfile);\n const admissionResponse = await extension.rpc.InvitationHostService.admit(admissionRequest);\n\n // Remote connection no longer needed.\n admitted = true;\n\n // 4. Record credential in our HALO.\n const result = await protocol.accept(ctx, admissionResponse, admissionRequest);\n\n // 5. Success.\n log.verbose('dxos.sdk.invitations-handler.guest.admitted-by-host', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n });\n guardedState.complete({\n ...guardedState.current,\n ...result,\n state: Invitation.State.SUCCESS,\n });\n log('guest invitation handler opened');\n } catch (err: any) {\n if (err instanceof TimeoutError) {\n log.verbose('timeout', { ...protocol.toJSON() });\n guardedState.set(extension, Invitation.State.TIMEOUT);\n } else {\n log.verbose('auth failed', err);\n guardedState.error(extension, err);\n }\n extensionCtx.close(err);\n }\n });\n },\n onError: (err) => {\n if (err instanceof InvalidInvitationExtensionRoleError) {\n return;\n }\n if (err instanceof TimeoutError) {\n log.verbose('timeout', { ...protocol.toJSON() });\n guardedState.set(extension, Invitation.State.TIMEOUT);\n } else {\n log.verbose('auth failed', err);\n guardedState.error(extension, err);\n }\n },\n });\n\n return extension;\n };\n\n const edgeInvitationHandler = new EdgeInvitationHandler(this._connectionProps?.edgeInvitations, this._edgeClient, {\n onInvitationSuccess: async (edgeCtx, admissionResponse, admissionRequest) => {\n const result = await protocol.accept(edgeCtx, admissionResponse, admissionRequest);\n log.info('admitted by edge', { ...protocol.toJSON() });\n guardedState.complete({ ...guardedState.current, ...result, state: Invitation.State.SUCCESS });\n },\n });\n edgeInvitationHandler.handle(ctx, guardedState, protocol, deviceProfile);\n\n scheduleTask(ctx, async () => {\n const error = checkInvitation(protocol, invitation);\n if (error) {\n stream.error(error);\n await ctx.dispose();\n } else {\n invariant(invitation.swarmKey);\n\n const timeoutInactive = () => {\n if (guardedState.mutex.isLocked()) {\n scheduleTask(ctx, timeoutInactive, timeout);\n } else {\n guardedState.set(null, Invitation.State.TIMEOUT);\n }\n };\n\n // Timeout if no connection is established.\n scheduleTask(ctx, timeoutInactive, timeout);\n\n await this._joinSwarm(ctx, invitation, InvitationOptions.Role.GUEST, createExtension);\n guardedState.set(null, Invitation.State.CONNECTING);\n }\n });\n }\n\n private async _joinSwarm(\n ctx: Context,\n invitation: Invitation,\n role: InvitationOptions.Role,\n extensionFactory: () => TeleportExtension,\n ): Promise<SwarmConnection> {\n let label: string;\n if (role === InvitationOptions.Role.GUEST) {\n label = 'invitation guest';\n } else if (invitation.kind === Invitation.Kind.DEVICE) {\n label = 'invitation host for device';\n } else {\n label = `invitation host for space ${invitation.spaceKey?.truncate()}`;\n }\n const swarmConnection = await this._networkManager.joinSwarm(ctx, {\n topic: invitation.swarmKey,\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', extensionFactory());\n }, this._connectionProps?.teleport),\n topology: new InvitationTopology(role),\n label,\n });\n ctx.onDispose(() => swarmConnection.close(ctx));\n return swarmConnection;\n }\n\n private async _handleGuestOtpAuth(\n extension: InvitationGuestExtension,\n setState: (newState: Invitation.State) => void,\n authenticated: Trigger<string>,\n options: { timeout: number },\n ): Promise<void> {\n for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {\n log('guest waiting for authentication code...');\n setState(Invitation.State.READY_FOR_AUTHENTICATION);\n const authCode = await authenticated.wait(options);\n\n log('sending authentication request');\n setState(Invitation.State.AUTHENTICATING);\n const response = await extension.rpc.InvitationHostService.authenticate({ authCode });\n if (response.status === undefined || response.status === AuthenticationResponse.Status.OK) {\n break;\n }\n\n if (response.status === AuthenticationResponse.Status.INVALID_OTP) {\n if (attempt === MAX_OTP_ATTEMPTS) {\n throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);\n } else {\n log('retrying invalid code', { attempt });\n authenticated.reset();\n }\n }\n }\n }\n\n private async _handleGuestKpkAuth(\n extension: InvitationGuestExtension,\n setState: (newState: Invitation.State) => void,\n invitation: Invitation,\n introductionResponse: IntroductionResponse,\n ): Promise<void> {\n if (invitation.guestKeypair?.privateKey == null) {\n throw new Error('keypair missing in the invitation');\n }\n if (introductionResponse.challenge == null) {\n throw new Error('challenge missing in the introduction');\n }\n log('sending authentication request');\n const signature = sign(Buffer.from(introductionResponse.challenge), invitation.guestKeypair.privateKey);\n const response = await extension.rpc.InvitationHostService.authenticate({\n signedChallenge: signature,\n });\n if (response.status !== AuthenticationResponse.Status.OK) {\n throw new Error(`Authentication failed with code: ${response.status}`);\n }\n }\n}\n\nconst checkInvitation = (protocol: InvitationProtocol, invitation: Partial<Invitation>) => {\n const expiresOn = getExpirationTime(invitation);\n if (expiresOn && expiresOn.getTime() < Date.now()) {\n return new InvalidInvitationError({ message: 'Invitation already expired.' });\n }\n return protocol.checkInvitation(invitation);\n};\n\nexport const createAdmissionKeypair = (): AdmissionKeypair => {\n const keypair = createKeyPair();\n return { publicKey: PublicKey.from(keypair.publicKey), privateKey: keypair.secretKey };\n};\n\nexport type InvitationsHandlerLayerOptions = {\n connectionProps?: InvitationConnectionProps;\n};\n\n/**\n * Effect Layer constructing an {@link InvitationsHandler}.\n */\nexport const InvitationsHandlerLayer = (\n options: InvitationsHandlerLayerOptions = {},\n): Layer.Layer<InvitationsHandlerService, never, SwarmNetworkManagerService> =>\n Layer.effect(\n InvitationsHandlerService,\n Effect.gen(function* () {\n const networkManager = yield* SwarmNetworkManagerService;\n const edgeClient = yield* Effect.serviceOption(EdgeHttpClientService);\n return new InvitationsHandler(networkManager, Option.getOrUndefined(edgeClient), options.connectionProps);\n }),\n );\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { Context } from '@dxos/context';\nimport {\n type AcceptInvitationRequest,\n type AuthenticationRequest,\n type CancelInvitationRequest,\n type Invitation,\n QueryInvitationsResponse,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type InvitationsService } from '@dxos/protocols/rpc';\nimport { trace } from '@dxos/tracing';\n\nimport { type InvitationsManager } from './invitations-manager';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class InvitationsServiceImpl implements InvitationsService.Handlers {\n 'constructor'(private readonly _invitationsManager: InvitationsManager) {}\n\n // TODO(burdon): Guest/host label.\n 'getLoggingContext'() {\n return {\n // deviceKey: this._identityManager.identity?.deviceKey\n };\n }\n\n ['InvitationsService.createInvitation'](request: Invitation): EffectStream.Stream<Invitation, Error> {\n return EffectStream.async<Invitation, Error>((emit) => {\n const ctx = Context.default();\n void this._invitationsManager\n .createInvitation(ctx, request)\n .then((invitation) => {\n trace.metrics.increment('dxos.invitation.created');\n invitation.subscribe(\n (value) => void emit.single(value),\n (err) => void emit.fail(err),\n () => void emit.end(),\n );\n })\n .catch((err) => void emit.fail(err));\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['InvitationsService.acceptInvitation'](request: AcceptInvitationRequest): EffectStream.Stream<Invitation, Error> {\n return EffectStream.async<Invitation, Error>((emit) => {\n const ctx = Context.default();\n const invitation = this._invitationsManager.acceptInvitation(ctx, request);\n invitation.subscribe(\n (value) => void emit.single(value),\n (err) => void emit.fail(err),\n () => void emit.end(),\n );\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['InvitationsService.authenticate'](request: AuthenticationRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: () => this._invitationsManager.authenticate(request),\n catch: (error) => error as Error,\n });\n }\n\n ['InvitationsService.cancelInvitation'](request: CancelInvitationRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: () => this._invitationsManager.cancelInvitation(request),\n catch: (error) => error as Error,\n });\n }\n\n ['InvitationsService.queryInvitations'](): EffectStream.Stream<QueryInvitationsResponse, Error> {\n return EffectStream.async<QueryInvitationsResponse, Error>((emit) => {\n const ctx = Context.default();\n\n // Push added invitations to the stream.\n this._invitationsManager.invitationCreated.on(ctx, (invitation) => {\n void emit.single({\n action: QueryInvitationsResponse.Action.ADDED,\n type: QueryInvitationsResponse.Type.CREATED,\n invitations: [invitation],\n });\n });\n\n this._invitationsManager.invitationAccepted.on(ctx, (invitation) => {\n void emit.single({\n action: QueryInvitationsResponse.Action.ADDED,\n type: QueryInvitationsResponse.Type.ACCEPTED,\n invitations: [invitation],\n });\n });\n\n // Push removed invitations to the stream.\n this._invitationsManager.removedCreated.on(ctx, (invitation) => {\n void emit.single({\n action: QueryInvitationsResponse.Action.REMOVED,\n type: QueryInvitationsResponse.Type.CREATED,\n invitations: [invitation],\n });\n });\n\n this._invitationsManager.removedAccepted.on(ctx, (invitation) => {\n void emit.single({\n action: QueryInvitationsResponse.Action.REMOVED,\n type: QueryInvitationsResponse.Type.ACCEPTED,\n invitations: [invitation],\n });\n });\n\n // used only for testing\n this._invitationsManager.saved.on(ctx, (invitation) => {\n void emit.single({\n action: QueryInvitationsResponse.Action.SAVED,\n type: QueryInvitationsResponse.Type.CREATED,\n invitations: [invitation],\n });\n });\n\n // Push existing invitations to the stream.\n void emit.single({\n action: QueryInvitationsResponse.Action.ADDED,\n type: QueryInvitationsResponse.Type.CREATED,\n invitations: this._invitationsManager.getCreatedInvitations(),\n existing: true,\n });\n\n void emit.single({\n action: QueryInvitationsResponse.Action.ADDED,\n type: QueryInvitationsResponse.Type.ACCEPTED,\n invitations: this._invitationsManager.getAcceptedInvitations(),\n existing: true,\n });\n\n this._invitationsManager.onPersistentInvitationsLoaded(ctx, () => {\n void emit.single({\n action: QueryInvitationsResponse.Action.LOAD_COMPLETE,\n type: QueryInvitationsResponse.Type.CREATED,\n // TODO(nf): populate with invitations\n });\n });\n // TODO(nf): expired invitations?\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n}\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Context } from '@dxos/context';\nimport {\n createCancelDelegatedSpaceInvitationCredential,\n createDelegatedSpaceInvitationCredential,\n getCredentialAssertion,\n} from '@dxos/credentials';\nimport { writeMessages } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type KeyringApi } from '@dxos/keyring';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { AlreadyJoinedError, AuthorizationError, InvalidInvitationError, SpaceNotFoundError } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type ProfileDocument, SpaceMember } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionRequest,\n type AdmissionResponse,\n type IntroductionRequest,\n} from '@dxos/protocols/proto/dxos/halo/invitations';\n\nimport { type DataSpaceManager, type SigningContext } from '../spaces';\nimport { type InvitationProtocol } from './invitation-protocol';\nimport { computeExpirationTime } from './utils';\n\nexport class SpaceInvitationProtocol implements InvitationProtocol {\n constructor(\n private readonly _spaceManager: DataSpaceManager,\n private readonly _signingContext: SigningContext,\n private readonly _keyring: KeyringApi,\n private readonly _spaceKey?: PublicKey,\n ) {}\n\n toJSON(): object {\n return {\n kind: 'space',\n deviceKey: this._signingContext.deviceKey,\n spaceKey: this._spaceKey,\n };\n }\n\n checkCanInviteNewMembers(): Error | undefined {\n if (this._spaceKey == null) {\n return new InvalidInvitationError({ message: 'No spaceKey was provided for a space invitation.' });\n }\n const space = this._spaceManager.spaces.get(this._spaceKey);\n if (space == null) {\n return new SpaceNotFoundError(this._spaceKey);\n }\n if (!space?.inner.spaceState.hasMembershipManagementPermission(this._signingContext.identityKey)) {\n return new AuthorizationError({ message: 'No member management permission.' });\n }\n return undefined;\n }\n\n getInvitationContext(): Partial<Invitation> & Pick<Invitation, 'kind'> {\n invariant(this._spaceKey);\n const space = this._spaceManager.spaces.get(this._spaceKey);\n invariant(space);\n return {\n kind: Invitation.Kind.SPACE,\n spaceKey: this._spaceKey,\n spaceId: space.id,\n };\n }\n\n async admit(\n invitation: Invitation,\n request: AdmissionRequest,\n guestProfile?: ProfileDocument | undefined,\n ): Promise<AdmissionResponse> {\n invariant(this._spaceKey && request.space);\n log('writing guest credentials', { host: this._signingContext.deviceKey, guest: request.space.deviceKey });\n\n const spaceMemberCredential = await this._spaceManager.admitMember({\n spaceKey: this._spaceKey,\n identityKey: request.space.identityKey,\n role: invitation.role ?? SpaceMember.Role.ADMIN,\n profile: guestProfile,\n delegationCredentialId: invitation.delegationCredentialId,\n });\n\n const space = this._spaceManager.spaces.get(this._spaceKey);\n return {\n space: {\n credential: spaceMemberCredential,\n controlTimeframe: space?.inner.controlPipeline.state.timeframe,\n },\n };\n }\n\n async delegate(invitation: Invitation): Promise<PublicKey> {\n invariant(this._spaceKey);\n const space = this._spaceManager.spaces.get(this._spaceKey);\n invariant(space);\n if (invitation.authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY) {\n invariant(invitation.guestKeypair?.publicKey);\n }\n\n log('writing delegate space invitation', { host: this._signingContext.deviceKey, id: invitation.invitationId });\n const credential = await createDelegatedSpaceInvitationCredential(\n this._signingContext.credentialSigner,\n space.key,\n {\n invitationId: invitation.invitationId,\n authMethod: invitation.authMethod,\n swarmKey: invitation.swarmKey,\n role: invitation.role ?? SpaceMember.Role.ADMIN,\n expiresOn: computeExpirationTime(invitation),\n multiUse: invitation.multiUse ?? false,\n guestKey:\n invitation.authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY\n ? invitation.guestKeypair!.publicKey\n : undefined,\n },\n );\n\n invariant(credential.credential);\n await writeMessages(space.inner.controlPipeline.writer, [credential]);\n return credential.credential.credential.id!;\n }\n\n async cancelDelegation(invitation: Invitation): Promise<void> {\n invariant(this._spaceKey);\n invariant(invitation.type === Invitation.Type.DELEGATED && invitation.delegationCredentialId);\n const space = this._spaceManager.spaces.get(this._spaceKey);\n invariant(space);\n\n log('cancelling delegated space invitation', { host: this._signingContext.deviceKey, id: invitation.invitationId });\n const credential = await createCancelDelegatedSpaceInvitationCredential(\n this._signingContext.credentialSigner,\n space.key,\n invitation.delegationCredentialId,\n );\n\n invariant(credential.credential);\n await writeMessages(space.inner.controlPipeline.writer, [credential]);\n }\n\n checkInvitation(invitation: Partial<Invitation>): InvalidInvitationError | AlreadyJoinedError | undefined {\n if (invitation.spaceKey == null) {\n return new InvalidInvitationError({ message: 'No spaceKey was provided for a space invitation.' });\n }\n if (this._spaceManager.spaces.has(invitation.spaceKey)) {\n return new AlreadyJoinedError({ message: 'Already joined space.' });\n }\n }\n\n createIntroduction(): IntroductionRequest {\n return {\n profile: this._signingContext.getProfile(),\n };\n }\n\n async createAdmissionRequest(): Promise<AdmissionRequest> {\n // Generate a pair of keys for our feeds.\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n\n return {\n space: {\n identityKey: this._signingContext.identityKey,\n deviceKey: this._signingContext.deviceKey,\n controlFeedKey,\n dataFeedKey,\n },\n };\n }\n\n async accept(ctx: Context, response: AdmissionResponse): Promise<Partial<Invitation>> {\n invariant(response.space);\n const { credential, controlTimeframe, dataTimeframe } = response.space;\n const assertion = getCredentialAssertion(credential);\n invariant(assertion['@type'] === 'dxos.halo.credentials.SpaceMember', 'Invalid credential');\n invariant(credential.subject.id.equals(this._signingContext.identityKey));\n\n if (this._spaceManager.spaces.has(assertion.spaceKey)) {\n throw new AlreadyJoinedError({ message: 'Already joined space.' });\n }\n\n // Create local space.\n await this._spaceManager.acceptSpace(ctx, {\n spaceKey: assertion.spaceKey,\n genesisFeedKey: assertion.genesisFeedKey,\n controlTimeframe,\n dataTimeframe,\n tags: assertion.tags,\n });\n\n await this._signingContext.recordCredential(credential);\n\n return { spaceKey: assertion.spaceKey };\n }\n}\n","//\n// Copyright 2021 DXOS.org\n//\n\nimport CRC32 from 'crc-32';\nimport * as EffectContext from 'effect/Context';\n\nimport { Event, scheduleTaskInterval, synchronized } from '@dxos/async';\nimport { type Codec } from '@dxos/codec-protobuf';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { DataCorruptionError, STORAGE_VERSION } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { Invitation, SpaceState } from '@dxos/protocols/proto/dxos/client/services';\nimport {\n type ControlPipelineSnapshot,\n type EchoMetadata,\n type EdgeReplicationSetting,\n type IdentityRecord,\n type LargeSpaceMetadata,\n type SpaceCache,\n type SpaceMetadata,\n} from '@dxos/protocols/proto/dxos/echo/metadata';\nimport { type Directory, type File } from '@dxos/random-access-storage';\nimport { type Timeframe } from '@dxos/timeframe';\nimport { ComplexMap, arrayToBuffer, forEachAsync, isNonNullable } from '@dxos/util';\n\nconst EXPIRED_INVITATION_CLEANUP_INTERVAL = 60 * 60 * 1000; // 1 hour\n\n/**\n * Shared interface for file-based and SQLite-backed metadata stores.\n */\nexport interface IMetadataStore {\n readonly update: Event<EchoMetadata>;\n readonly metadata: EchoMetadata;\n readonly version: number;\n readonly spaces: SpaceMetadata[];\n\n load(): Promise<void>;\n close(): Promise<void>;\n flush(): Promise<void>;\n clear(): Promise<void>;\n hasSpace(spaceKey: PublicKey): boolean;\n\n getIdentityRecord(): IdentityRecord | undefined;\n setIdentityRecord(record: IdentityRecord): Promise<void>;\n\n getInvitations(): Invitation[];\n addInvitation(invitation: Invitation): Promise<void>;\n removeInvitation(invitationId: string): Promise<void>;\n\n addSpace(record: SpaceMetadata): Promise<void>;\n setSpaceDataLatestTimeframe(spaceKey: PublicKey, timeframe: Timeframe): Promise<void>;\n setSpaceControlLatestTimeframe(spaceKey: PublicKey, timeframe: Timeframe): Promise<void>;\n setCache(spaceKey: PublicKey, cache: SpaceCache): Promise<void>;\n setWritableFeedKeys(spaceKey: PublicKey, controlFeedKey: PublicKey, dataFeedKey: PublicKey): Promise<void>;\n setSpaceState(spaceKey: PublicKey, state: SpaceState): Promise<void>;\n\n getSpaceControlPipelineSnapshot(spaceKey: PublicKey): ControlPipelineSnapshot | undefined;\n setSpaceControlPipelineSnapshot(spaceKey: PublicKey, snapshot: ControlPipelineSnapshot): Promise<void>;\n\n getSpaceEdgeReplicationSetting(spaceKey: PublicKey): EdgeReplicationSetting | undefined;\n setSpaceEdgeReplicationSetting(spaceKey: PublicKey, setting: EdgeReplicationSetting): Promise<void>;\n\n readonly deletedSpaces: PublicKey[];\n addDeletedSpace(spaceKey: PublicKey): Promise<void>;\n}\n\n/**\n * Effect service tag for {@link IMetadataStore}.\n */\nexport class IMetadataStoreService extends EffectContext.Tag('@dxos/client-services/IMetadataStore')<\n IMetadataStoreService,\n IMetadataStore\n>() {}\n\nexport interface AddSpaceOptions {\n key: PublicKey;\n genesisFeed: PublicKey;\n}\n\nconst emptyEchoMetadata = (): EchoMetadata => ({\n version: STORAGE_VERSION,\n spaces: [],\n created: new Date(),\n updated: new Date(),\n});\n\nconst emptyLargeSpaceMetadata = (): LargeSpaceMetadata => ({});\n\nconst EchoMetadata = schema.getCodecForType('dxos.echo.metadata.EchoMetadata');\nconst LargeSpaceMetadata = schema.getCodecForType('dxos.echo.metadata.LargeSpaceMetadata');\n\nexport class MetadataStore implements IMetadataStore {\n private _metadata: EchoMetadata = emptyEchoMetadata();\n private _spaceLargeMetadata = new ComplexMap<PublicKey, LargeSpaceMetadata>(PublicKey.hash);\n\n private _metadataFile?: File = undefined;\n\n public readonly update = new Event<EchoMetadata>();\n private readonly _invitationCleanupCtx = new Context();\n\n /**\n * @internal\n */\n readonly _directory: Directory;\n\n constructor(directory: Directory) {\n this._directory = directory;\n }\n\n get metadata(): EchoMetadata {\n return this._metadata;\n }\n\n get version(): number {\n return this._metadata.version ?? 0;\n }\n\n /**\n * Returns a list of currently saved spaces. The list and objects in it can be modified addSpace and\n * addSpaceFeed functions.\n */\n get spaces(): SpaceMetadata[] {\n return this._metadata.spaces ?? [];\n }\n\n /**\n * Returns the keys of spaces that have been tombstoned (soft-deleted).\n */\n get deletedSpaces(): PublicKey[] {\n return this._metadata.deletedSpaces ?? [];\n }\n\n private async _readFile<T>(file: File, codec: Codec<T>): Promise<T | undefined> {\n try {\n const { size: fileLength } = await file.stat();\n if (fileLength < 8) {\n return;\n }\n // Loading file size from first 4 bytes.\n const dataSize = fromBytesInt32(await file.read(0, 4));\n const checksum = fromBytesInt32(await file.read(4, 4));\n log('loaded', { size: dataSize, checksum, name: file.filename });\n\n if (fileLength < dataSize + 8) {\n throw new DataCorruptionError({\n message: 'Metadata size is smaller than expected.',\n context: { fileLength, dataSize },\n });\n }\n\n const data = await file.read(8, dataSize);\n\n const calculatedChecksum = CRC32.buf(data);\n if (calculatedChecksum !== checksum) {\n throw new DataCorruptionError({ message: 'Metadata checksum is invalid.' });\n }\n\n return codec.decode(data);\n } finally {\n await file.close();\n }\n }\n\n /**\n * @internal\n */\n async _writeFile<T>(file: File, codec: Codec<T>, data: T): Promise<void> {\n const encoded = arrayToBuffer(codec.encode(data));\n const checksum = CRC32.buf(encoded);\n\n const result = Buffer.alloc(8 + encoded.length);\n\n result.writeInt32LE(encoded.length, 0);\n result.writeInt32LE(checksum, 4);\n encoded.copy(result, 8);\n\n // NOTE: This must be done in one write operation, otherwise the file can be corrupted.\n await file.write(0, result);\n\n log('saved', { size: encoded.length, checksum });\n }\n\n async close(): Promise<void> {\n await this._invitationCleanupCtx.dispose();\n await this.flush();\n await this._metadataFile?.close();\n this._metadataFile = undefined;\n this._metadata = emptyEchoMetadata();\n this._spaceLargeMetadata.clear();\n }\n\n /**\n * Loads metadata from persistent storage.\n */\n @synchronized\n async load(): Promise<void> {\n if (!this._metadataFile || this._metadataFile.closed) {\n this._metadataFile = this._directory.getOrCreateFile('EchoMetadata');\n }\n\n try {\n const metadata = await this._readFile(this._metadataFile, EchoMetadata);\n if (metadata) {\n this._metadata = metadata;\n }\n\n // post-processing\n this._metadata.spaces?.forEach((space) => {\n space.state ??= SpaceState.SPACE_ACTIVE;\n });\n } catch (err: any) {\n log.error('failed to load metadata', { err });\n this._metadata = emptyEchoMetadata();\n }\n\n await forEachAsync(\n [this._metadata.identity?.haloSpace.key, ...(this._metadata.spaces?.map((space) => space.key) ?? [])].filter(\n isNonNullable,\n ),\n async (key) => {\n try {\n await this._loadSpaceLargeMetadata(key);\n } catch (err: any) {\n log.error('failed to load space large metadata', { err });\n }\n },\n );\n\n // Cleanup expired persistent invitations.\n scheduleTaskInterval(\n this._invitationCleanupCtx,\n async () => {\n for (const invitation of this._metadata.invitations ?? []) {\n if (hasInvitationExpired(invitation) || isLegacyInvitationFormat(invitation)) {\n await this.removeInvitation(invitation.invitationId);\n }\n }\n },\n EXPIRED_INVITATION_CLEANUP_INTERVAL,\n );\n }\n\n @synchronized\n private async _save(): Promise<void> {\n const data: EchoMetadata = {\n ...this._metadata,\n version: STORAGE_VERSION,\n created: this._metadata.created ?? new Date(),\n updated: new Date(),\n };\n this.update.emit(data);\n\n const file = this._directory.getOrCreateFile('EchoMetadata');\n\n await this._writeFile(file, EchoMetadata, data);\n }\n\n private async _loadSpaceLargeMetadata(key: PublicKey): Promise<void> {\n const file = this._directory.getOrCreateFile(`space_${key.toHex()}_large`);\n try {\n const metadata = await this._readFile(file, LargeSpaceMetadata);\n if (metadata) {\n this._spaceLargeMetadata.set(key, metadata);\n }\n } catch (err: any) {\n log.error('failed to load space large metadata', { err });\n }\n }\n\n @synchronized\n private async _saveSpaceLargeMetadata(key: PublicKey): Promise<void> {\n const data = this._getLargeSpaceMetadata(key);\n const file = this._directory.getOrCreateFile(`space_${key.toHex()}_large`);\n await this._writeFile(file, LargeSpaceMetadata, data);\n }\n\n async flush(): Promise<void> {\n await this._directory.flush();\n }\n\n _getSpace(spaceKey: PublicKey): SpaceMetadata {\n if (this._metadata.identity?.haloSpace.key.equals(spaceKey)) {\n // Check if the space is the identity space.\n return this._metadata.identity.haloSpace;\n }\n\n const space = this.spaces.find((space) => space.key.equals(spaceKey));\n invariant(space, 'Space not found');\n return space;\n }\n\n hasSpace(spaceKey: PublicKey): boolean {\n if (this._metadata.identity?.haloSpace.key.equals(spaceKey)) {\n // Check if the space is the identity space.\n return true;\n }\n\n return !!this.spaces.find((space) => space.key.equals(spaceKey));\n }\n\n private _getLargeSpaceMetadata(key: PublicKey): LargeSpaceMetadata {\n let entry = this._spaceLargeMetadata.get(key);\n if (entry) {\n return entry;\n }\n\n entry = emptyLargeSpaceMetadata();\n this._spaceLargeMetadata.set(key, entry);\n return entry;\n }\n\n /**\n * Clears storage - doesn't work for now.\n */\n async clear(): Promise<void> {\n log('clearing all metadata');\n await this._directory.delete();\n this._metadata = emptyEchoMetadata();\n }\n\n getIdentityRecord(): IdentityRecord | undefined {\n return this._metadata.identity;\n }\n\n async setIdentityRecord(record: IdentityRecord): Promise<void> {\n invariant(!this._metadata.identity, 'Cannot overwrite existing identity in metadata');\n\n this._metadata.identity = record;\n await this._save();\n await this.flush();\n }\n\n getInvitations(): Invitation[] {\n return this._metadata.invitations ?? [];\n }\n\n async addInvitation(invitation: Invitation): Promise<void> {\n if (this._metadata.invitations?.find((i) => i.invitationId === invitation.invitationId)) {\n return;\n }\n\n (this._metadata.invitations ??= []).push(invitation);\n await this._save();\n await this.flush();\n }\n\n async removeInvitation(invitationId: string): Promise<void> {\n this._metadata.invitations = (this._metadata.invitations ?? []).filter((i) => i.invitationId !== invitationId);\n await this._save();\n await this.flush();\n }\n\n /**\n * Records a space as tombstoned (soft-deleted) so it is never re-accepted or auto-opened.\n */\n async addDeletedSpace(spaceKey: PublicKey): Promise<void> {\n if ((this._metadata.deletedSpaces ?? []).some((key) => key.equals(spaceKey))) {\n return;\n }\n\n (this._metadata.deletedSpaces ??= []).push(spaceKey);\n await this._save();\n await this.flush();\n }\n\n async addSpace(record: SpaceMetadata): Promise<void> {\n invariant(\n !(this._metadata.spaces ?? []).find((space) => space.key.equals(record.key)),\n 'Cannot overwrite existing space in metadata',\n );\n\n (this._metadata.spaces ??= []).push(record);\n await this._save();\n await this.flush();\n }\n\n async setSpaceDataLatestTimeframe(spaceKey: PublicKey, timeframe: Timeframe): Promise<void> {\n this._getSpace(spaceKey).dataTimeframe = timeframe;\n await this._save();\n }\n\n async setSpaceControlLatestTimeframe(spaceKey: PublicKey, timeframe: Timeframe): Promise<void> {\n this._getSpace(spaceKey).controlTimeframe = timeframe;\n await this._save();\n await this.flush();\n }\n\n async setCache(spaceKey: PublicKey, cache: SpaceCache): Promise<void> {\n this._getSpace(spaceKey).cache = cache;\n await this._save();\n }\n\n async setWritableFeedKeys(spaceKey: PublicKey, controlFeedKey: PublicKey, dataFeedKey: PublicKey): Promise<void> {\n const space = this._getSpace(spaceKey);\n space.controlFeedKey = controlFeedKey;\n space.dataFeedKey = dataFeedKey;\n await this._save();\n await this.flush();\n }\n\n async setSpaceState(spaceKey: PublicKey, state: SpaceState): Promise<void> {\n this._getSpace(spaceKey).state = state;\n await this._save();\n await this.flush();\n }\n\n getSpaceControlPipelineSnapshot(spaceKey: PublicKey): ControlPipelineSnapshot | undefined {\n return this._getLargeSpaceMetadata(spaceKey).controlPipelineSnapshot;\n }\n\n async setSpaceControlPipelineSnapshot(spaceKey: PublicKey, snapshot: ControlPipelineSnapshot): Promise<void> {\n this._getLargeSpaceMetadata(spaceKey).controlPipelineSnapshot = snapshot;\n await this._saveSpaceLargeMetadata(spaceKey);\n await this.flush();\n }\n\n getSpaceEdgeReplicationSetting(spaceKey: PublicKey): EdgeReplicationSetting | undefined {\n return this.hasSpace(spaceKey) ? this._getSpace(spaceKey).edgeReplication : undefined;\n }\n\n async setSpaceEdgeReplicationSetting(spaceKey: PublicKey, setting: EdgeReplicationSetting): Promise<void> {\n this._getSpace(spaceKey).edgeReplication = setting;\n await this._save();\n await this.flush();\n }\n}\n\nconst fromBytesInt32 = (buf: Buffer) => buf.readInt32LE(0);\n\nexport const hasInvitationExpired = (invitation: Invitation): boolean => {\n return Boolean(\n invitation.created &&\n invitation.lifetime &&\n invitation.lifetime !== 0 &&\n invitation.created.getTime() + invitation.lifetime * 1000 < Date.now(),\n );\n};\n\n// TODO: remove once \"multiuse\" type invitations get removed from local metadata of existing profiles\nconst isLegacyInvitationFormat = (invitation: Invitation): boolean => {\n return invitation.type === Invitation.Type.MULTIUSE;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as SqlClient from '@effect/sql/SqlClient';\nimport type * as SqlError from '@effect/sql/SqlError';\nimport CRC32 from 'crc-32';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { Event, scheduleTaskInterval, synchronized } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { RuntimeProvider } from '@dxos/effect';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { DataCorruptionError, STORAGE_VERSION } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { Invitation, SpaceState } from '@dxos/protocols/proto/dxos/client/services';\nimport {\n type ControlPipelineSnapshot,\n type EchoMetadata,\n type EdgeReplicationSetting,\n type IdentityRecord,\n type LargeSpaceMetadata,\n type SpaceCache,\n type SpaceMetadata,\n} from '@dxos/protocols/proto/dxos/echo/metadata';\nimport { SqlTransaction } from '@dxos/sql-sqlite';\nimport { type Timeframe } from '@dxos/timeframe';\nimport { ComplexMap, arrayToBuffer, forEachAsync, isNonNullable } from '@dxos/util';\n\nimport { type IMetadataStore, IMetadataStoreService, hasInvitationExpired } from './metadata-store';\n\n// SqlTransaction.SqlTransaction is the Tag class exported from the SqlTransaction namespace.\ntype SqlTransactionTag = SqlTransaction.SqlTransaction;\n\nconst EXPIRED_INVITATION_CLEANUP_INTERVAL = 60 * 60 * 1000; // 1 hour\n\nconst emptyEchoMetadata = (): EchoMetadata => ({\n version: STORAGE_VERSION,\n spaces: [],\n created: new Date(),\n updated: new Date(),\n});\n\nconst emptyLargeSpaceMetadata = (): LargeSpaceMetadata => ({});\n\nconst EchoMetadataCodec = schema.getCodecForType('dxos.echo.metadata.EchoMetadata');\nconst LargeSpaceMetadataCodec = schema.getCodecForType('dxos.echo.metadata.LargeSpaceMetadata');\n\nconst MAIN_KEY = 'main';\nconst largeKey = (spaceKey: PublicKey) => `large:${spaceKey.toHex()}`;\n\n// Legacy invitation type detection.\nconst isLegacyInvitationFormat = (invitation: Invitation): boolean => invitation.type === Invitation.Type.MULTIUSE;\n\nexport type SqliteMetadataStoreProps = {\n runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient | SqlTransactionTag>;\n};\n\n/**\n * SQLite-backed replacement for MetadataStore.\n * Stores EchoMetadata as a single protobuf blob and LargeSpaceMetadata as per-space blobs.\n */\nexport class SqliteMetadataStore implements IMetadataStore {\n readonly #runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient | SqlTransactionTag>;\n\n #metadata: EchoMetadata = emptyEchoMetadata();\n readonly #spaceLargeMetadata = new ComplexMap<PublicKey, LargeSpaceMetadata>(PublicKey.hash);\n\n readonly update = new Event<EchoMetadata>();\n readonly #invitationCleanupCtx = new Context();\n\n constructor({ runtime }: SqliteMetadataStoreProps) {\n this.#runtime = runtime;\n }\n\n /**\n * Creates the space_metadata and space_large tables if they do not exist.\n */\n readonly migrate: Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient | SqlTransactionTag> = Effect.fn(\n 'SqliteMetadataStore.migrate',\n )(() =>\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`CREATE TABLE IF NOT EXISTS space_metadata (\n key TEXT PRIMARY KEY,\n value BLOB NOT NULL\n )`;\n yield* sql`CREATE TABLE IF NOT EXISTS space_large (\n space_key TEXT PRIMARY KEY,\n value BLOB NOT NULL\n )`;\n log('space_metadata and space_large tables ready');\n }).pipe(Effect.withSpan('SqliteMetadataStore.migrate')),\n )();\n\n get metadata(): EchoMetadata {\n return this.#metadata;\n }\n\n get version(): number {\n return this.#metadata.version ?? 0;\n }\n\n get spaces(): SpaceMetadata[] {\n return this.#metadata.spaces ?? [];\n }\n\n async close(): Promise<void> {\n await this.#invitationCleanupCtx.dispose();\n await this._save();\n this.#metadata = emptyEchoMetadata();\n this.#spaceLargeMetadata.clear();\n }\n\n /**\n * Loads metadata from SQLite.\n */\n @synchronized\n async load(): Promise<void> {\n const rows = await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n return yield* sql<{ value: Uint8Array }>`SELECT value FROM space_metadata WHERE key = ${MAIN_KEY}`;\n }),\n );\n\n if (rows.length > 0) {\n try {\n this.#metadata = this.#decodeWithCrc(rows[0].value, EchoMetadataCodec) ?? emptyEchoMetadata();\n this.#metadata.spaces?.forEach((space) => {\n space.state ??= SpaceState.SPACE_ACTIVE;\n });\n } catch (err: any) {\n log.error('failed to load metadata from SQLite', { err });\n this.#metadata = emptyEchoMetadata();\n }\n }\n\n // Load large metadata for all known spaces.\n const spaceKeys = [\n this.#metadata.identity?.haloSpace.key,\n ...(this.#metadata.spaces?.map((s) => s.key) ?? []),\n ].filter(isNonNullable);\n\n await forEachAsync(spaceKeys, async (key) => {\n try {\n await this.#loadSpaceLargeMetadata(key);\n } catch (err: any) {\n log.error('failed to load large space metadata', { err });\n }\n });\n\n scheduleTaskInterval(\n this.#invitationCleanupCtx,\n async () => {\n for (const invitation of this.#metadata.invitations ?? []) {\n if (hasInvitationExpired(invitation) || isLegacyInvitationFormat(invitation)) {\n await this.removeInvitation(invitation.invitationId);\n }\n }\n },\n EXPIRED_INVITATION_CLEANUP_INTERVAL,\n );\n }\n\n async flush(): Promise<void> {\n // No-op: SQLite writes are immediate.\n }\n\n hasSpace(spaceKey: PublicKey): boolean {\n if (this.#metadata.identity?.haloSpace.key.equals(spaceKey)) {\n return true;\n }\n return !!this.spaces.find((space) => space.key.equals(spaceKey));\n }\n\n getIdentityRecord(): IdentityRecord | undefined {\n return this.#metadata.identity;\n }\n\n async setIdentityRecord(record: IdentityRecord): Promise<void> {\n invariant(!this.#metadata.identity, 'Cannot overwrite existing identity in metadata');\n this.#metadata.identity = record;\n await this._save();\n }\n\n getInvitations(): Invitation[] {\n return this.#metadata.invitations ?? [];\n }\n\n async addInvitation(invitation: Invitation): Promise<void> {\n if (this.#metadata.invitations?.find((i) => i.invitationId === invitation.invitationId)) {\n return;\n }\n (this.#metadata.invitations ??= []).push(invitation);\n await this._save();\n }\n\n async removeInvitation(invitationId: string): Promise<void> {\n this.#metadata.invitations = (this.#metadata.invitations ?? []).filter((i) => i.invitationId !== invitationId);\n await this._save();\n }\n\n async addSpace(record: SpaceMetadata): Promise<void> {\n invariant(\n !(this.#metadata.spaces ?? []).find((space) => space.key.equals(record.key)),\n 'Cannot overwrite existing space in metadata',\n );\n (this.#metadata.spaces ??= []).push(record);\n await this._save();\n }\n\n async setSpaceDataLatestTimeframe(spaceKey: PublicKey, timeframe: Timeframe): Promise<void> {\n this.#getSpace(spaceKey).dataTimeframe = timeframe;\n await this._save();\n }\n\n async setSpaceControlLatestTimeframe(spaceKey: PublicKey, timeframe: Timeframe): Promise<void> {\n this.#getSpace(spaceKey).controlTimeframe = timeframe;\n await this._save();\n }\n\n async setCache(spaceKey: PublicKey, cache: SpaceCache): Promise<void> {\n this.#getSpace(spaceKey).cache = cache;\n await this._save();\n }\n\n async setWritableFeedKeys(spaceKey: PublicKey, controlFeedKey: PublicKey, dataFeedKey: PublicKey): Promise<void> {\n const space = this.#getSpace(spaceKey);\n space.controlFeedKey = controlFeedKey;\n space.dataFeedKey = dataFeedKey;\n await this._save();\n }\n\n async setSpaceState(spaceKey: PublicKey, state: SpaceState): Promise<void> {\n this.#getSpace(spaceKey).state = state;\n await this._save();\n }\n\n getSpaceControlPipelineSnapshot(spaceKey: PublicKey): ControlPipelineSnapshot | undefined {\n return this.#getLargeSpaceMetadata(spaceKey).controlPipelineSnapshot;\n }\n\n async setSpaceControlPipelineSnapshot(spaceKey: PublicKey, snapshot: ControlPipelineSnapshot): Promise<void> {\n this.#getLargeSpaceMetadata(spaceKey).controlPipelineSnapshot = snapshot;\n await this._saveSpaceLargeMetadata(spaceKey);\n }\n\n getSpaceEdgeReplicationSetting(spaceKey: PublicKey): EdgeReplicationSetting | undefined {\n return this.hasSpace(spaceKey) ? this.#getSpace(spaceKey).edgeReplication : undefined;\n }\n\n async setSpaceEdgeReplicationSetting(spaceKey: PublicKey, setting: EdgeReplicationSetting): Promise<void> {\n this.#getSpace(spaceKey).edgeReplication = setting;\n await this._save();\n }\n\n get deletedSpaces(): PublicKey[] {\n return this.#metadata.deletedSpaces ?? [];\n }\n\n async addDeletedSpace(spaceKey: PublicKey): Promise<void> {\n if ((this.#metadata.deletedSpaces ?? []).some((key) => key.equals(spaceKey))) {\n return;\n }\n (this.#metadata.deletedSpaces ??= []).push(spaceKey);\n await this._save();\n }\n\n async clear(): Promise<void> {\n log('clearing all metadata');\n await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`DELETE FROM space_metadata`;\n yield* sql`DELETE FROM space_large`;\n }),\n );\n this.#metadata = emptyEchoMetadata();\n this.#spaceLargeMetadata.clear();\n }\n\n #getSpace(spaceKey: PublicKey): SpaceMetadata {\n if (this.#metadata.identity?.haloSpace.key.equals(spaceKey)) {\n return this.#metadata.identity.haloSpace;\n }\n const space = this.spaces.find((space) => space.key.equals(spaceKey));\n invariant(space, 'Space not found');\n return space;\n }\n\n #getLargeSpaceMetadata(key: PublicKey): LargeSpaceMetadata {\n let entry = this.#spaceLargeMetadata.get(key);\n if (!entry) {\n entry = emptyLargeSpaceMetadata();\n this.#spaceLargeMetadata.set(key, entry);\n }\n return entry;\n }\n\n @synchronized\n private async _save(): Promise<void> {\n const data: EchoMetadata = {\n ...this.#metadata,\n version: STORAGE_VERSION,\n created: this.#metadata.created ?? new Date(),\n updated: new Date(),\n };\n this.update.emit(data);\n const encoded = this.#encodeWithCrc(EchoMetadataCodec, data);\n await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`INSERT OR REPLACE INTO space_metadata (key, value) VALUES (${MAIN_KEY}, ${encoded})`;\n }),\n );\n }\n\n async #loadSpaceLargeMetadata(key: PublicKey): Promise<void> {\n const keyStr = largeKey(key);\n const rows = await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n return yield* sql<{ value: Uint8Array }>`SELECT value FROM space_large WHERE space_key = ${keyStr}`;\n }),\n );\n if (rows.length > 0) {\n try {\n const meta = this.#decodeWithCrc(rows[0].value, LargeSpaceMetadataCodec);\n if (meta) {\n this.#spaceLargeMetadata.set(key, meta);\n }\n } catch (err: any) {\n log.error('failed to decode large space metadata', { err });\n }\n }\n }\n\n @synchronized\n private async _saveSpaceLargeMetadata(key: PublicKey): Promise<void> {\n const data = this.#getLargeSpaceMetadata(key);\n const keyStr = largeKey(key);\n const encoded = this.#encodeWithCrc(LargeSpaceMetadataCodec, data);\n await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`INSERT OR REPLACE INTO space_large (space_key, value) VALUES (${keyStr}, ${encoded})`;\n }),\n );\n }\n\n /** Serialize with CRC32 checksum prefix for integrity checking (matches MetadataStore format). */\n #encodeWithCrc<T>(codec: { encode: (v: T) => Uint8Array }, data: T): Buffer {\n const encoded = arrayToBuffer(codec.encode(data));\n const checksum = CRC32.buf(encoded);\n const result = Buffer.alloc(8 + encoded.length);\n result.writeInt32LE(encoded.length, 0);\n result.writeInt32LE(checksum, 4);\n encoded.copy(result, 8);\n return result;\n }\n\n /** Deserialize with CRC32 integrity check (matches MetadataStore format). */\n #decodeWithCrc<T>(data: Uint8Array, codec: { decode: (v: Uint8Array) => T }): T | undefined {\n const buf = Buffer.from(data);\n if (buf.length < 8) {\n return undefined;\n }\n const dataSize = buf.readInt32LE(0);\n const checksum = buf.readInt32LE(4);\n if (dataSize < 0 || dataSize > buf.length - 8) {\n throw new DataCorruptionError({\n message: 'Metadata size header is invalid.',\n context: { fileLength: buf.length, dataSize },\n });\n }\n if (buf.length !== dataSize + 8) {\n throw new DataCorruptionError({\n message: 'Metadata payload length does not match framing header.',\n context: { fileLength: buf.length, dataSize },\n });\n }\n const payload = buf.subarray(8, dataSize + 8);\n const calculated = CRC32.buf(payload);\n if (calculated !== checksum) {\n throw new DataCorruptionError({ message: 'Metadata checksum is invalid.' });\n }\n return codec.decode(payload);\n }\n}\n\n/**\n * Effect Layer constructing a {@link SqliteMetadataStore} from the ambient SQL runtime.\n */\nexport const SqliteMetadataStoreLayer = (): Layer.Layer<\n IMetadataStoreService,\n never,\n SqlClient.SqlClient | SqlTransactionTag\n> =>\n Layer.effect(\n IMetadataStoreService,\n Effect.gen(function* () {\n const runtime = yield* RuntimeProvider.currentRuntime<SqlClient.SqlClient | SqlTransactionTag>();\n return new SqliteMetadataStore({ runtime });\n }),\n );\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { Event, PushStream, TimeoutError, Trigger } from '@dxos/async';\nimport {\n AuthenticatingInvitation,\n AUTHENTICATION_CODE_LENGTH,\n CancellableInvitation,\n INVITATION_TIMEOUT,\n} from '@dxos/client-protocol';\nimport { Context } from '@dxos/context';\nimport { generatePasscode } from '@dxos/credentials';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n type AcceptInvitationRequest,\n type AuthenticationRequest,\n Invitation,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { SpaceMember } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { trace } from '@dxos/tracing';\n\nimport { type IMetadataStore, IMetadataStoreService, hasInvitationExpired } from '../metadata';\nimport type { InvitationProtocol } from './invitation-protocol';\nimport { type InvitationsHandler, InvitationsHandlerService, createAdmissionKeypair } from './invitations-handler';\n\n/**\n * Effect service tag for {@link InvitationsManager}.\n */\nexport class InvitationsManagerService extends EffectContext.Tag('@dxos/client-services/InvitationsManager')<\n InvitationsManagerService,\n InvitationsManager\n>() {}\n\n/**\n * Entry point for creating and accepting invitations, keeps track of existing invitation set and\n * emits events when the set changes.\n */\nexport class InvitationsManager {\n private readonly _createInvitations = new Map<string, CancellableInvitation>();\n private readonly _acceptInvitations = new Map<string, AuthenticatingInvitation>();\n\n public readonly invitationCreated = new Event<Invitation>();\n public readonly invitationAccepted = new Event<Invitation>();\n public readonly removedCreated = new Event<Invitation>();\n public readonly removedAccepted = new Event<Invitation>();\n public readonly saved = new Event<Invitation>();\n\n private readonly _persistentInvitationsLoadedEvent = new Event();\n private _persistentInvitationsLoaded = false;\n\n private _invitationHandlerFactory?: (\n invitation: Partial<Invitation> & Pick<Invitation, 'kind'>,\n ) => InvitationProtocol;\n\n constructor(\n private readonly _invitationsHandler: InvitationsHandler,\n private readonly _metadataStore: IMetadataStore,\n ) {}\n\n /**\n * Wires the invitation handler factory after the composing stack is fully constructed.\n */\n setInvitationHandlerFactory(\n getHandler: (invitation: Partial<Invitation> & Pick<Invitation, 'kind'>) => InvitationProtocol,\n ): void {\n this._invitationHandlerFactory = getHandler;\n }\n\n private _getHandler(invitation: Partial<Invitation> & Pick<Invitation, 'kind'>): InvitationProtocol {\n invariant(this._invitationHandlerFactory, 'Invitation handler factory not set.');\n return this._invitationHandlerFactory(invitation);\n }\n\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n async createInvitation(\n ctx: Context,\n options: Partial<Invitation> & Pick<Invitation, 'kind'>,\n ): Promise<CancellableInvitation> {\n if (options.invitationId) {\n const existingInvitation = this._createInvitations.get(options.invitationId);\n if (existingInvitation) {\n return existingInvitation;\n }\n }\n\n const handler = this._getHandler(options);\n const invitationError = handler.checkCanInviteNewMembers();\n if (invitationError != null) {\n throw invitationError;\n }\n const invitation = this._createInvitation(handler, options);\n\n const {\n ctx: invitationCtx,\n stream,\n observableInvitation,\n } = this._createObservableInvitation(ctx, handler, invitation);\n\n this._createInvitations.set(invitation.invitationId, observableInvitation);\n this.invitationCreated.emit(invitation);\n // onComplete is called on cancel, expiration, or redemption of a single-use invitation\n this._onInvitationComplete(observableInvitation, async () => {\n this._createInvitations.delete(observableInvitation.get().invitationId);\n this.removedCreated.emit(observableInvitation.get());\n if (observableInvitation.get().persistent) {\n await this._safeDeleteInvitation(observableInvitation.get());\n }\n });\n\n try {\n await this._persistIfRequired(handler, stream, invitation);\n } catch (err) {\n log.catch(err);\n await observableInvitation.cancel();\n return observableInvitation;\n }\n\n this._invitationsHandler.handleInvitationFlow(invitationCtx, stream, handler, observableInvitation.get());\n\n return observableInvitation;\n }\n\n async loadPersistentInvitations(ctx: Context): Promise<{ invitations: Invitation[] }> {\n if (this._persistentInvitationsLoaded) {\n const invitations = this.getCreatedInvitations().filter((i) => i.persistent);\n return { invitations };\n }\n try {\n const persistentInvitations = this._metadataStore.getInvitations();\n // get saved persistent invitations, filter and remove from storage those that have expired.\n const freshInvitations = persistentInvitations.filter((invitation) => !hasInvitationExpired(invitation));\n\n const loadTasks = freshInvitations.map((persistentInvitation) => {\n invariant(!this._createInvitations.get(persistentInvitation.invitationId), 'invitation already exists');\n return this.createInvitation(ctx, { ...persistentInvitation, persistent: false });\n });\n const cInvitations = await Promise.all(loadTasks);\n\n return { invitations: cInvitations.map((invitation) => invitation.get()) };\n } catch (err) {\n log.catch(err);\n return { invitations: [] };\n } finally {\n this._persistentInvitationsLoadedEvent.emit();\n this._persistentInvitationsLoaded = true;\n }\n }\n\n acceptInvitation(ctx: Context, request: AcceptInvitationRequest): AuthenticatingInvitation {\n const options = request.invitation;\n const existingInvitation = this._acceptInvitations.get(options.invitationId);\n if (existingInvitation) {\n return existingInvitation;\n }\n\n const handler = this._getHandler(options);\n const {\n ctx: invitationCtx,\n invitation,\n stream,\n otpEnteredTrigger,\n } = this._createObservableAcceptingInvitation(ctx, handler, options);\n this._invitationsHandler.acceptInvitation(\n invitationCtx,\n stream,\n handler,\n options,\n otpEnteredTrigger,\n request.deviceProfile,\n );\n this._acceptInvitations.set(invitation.get().invitationId, invitation);\n this.invitationAccepted.emit(invitation.get());\n\n this._onInvitationComplete(invitation, () => {\n this._acceptInvitations.delete(invitation.get().invitationId);\n this.removedAccepted.emit(invitation.get());\n });\n\n return invitation;\n }\n\n async authenticate({ invitationId, authCode }: AuthenticationRequest): Promise<void> {\n log('authenticating...');\n invariant(invitationId);\n const observable = this._acceptInvitations.get(invitationId);\n if (!observable) {\n log.warn('invalid invitation', { invitationId });\n } else {\n await observable.authenticate(authCode);\n }\n }\n\n async cancelInvitation({ invitationId }: { invitationId: string }): Promise<void> {\n log('cancelInvitation...', { invitationId });\n invariant(invitationId);\n const created = this._createInvitations.get(invitationId);\n if (created) {\n // remove from storage before modifying in-memory state, higher chance of failing\n if (created.get().persistent) {\n await this._metadataStore.removeInvitation(invitationId);\n }\n if (created.get().type === Invitation.Type.DELEGATED) {\n const handler = this._getHandler(created.get());\n await handler.cancelDelegation(created.get());\n }\n await created.cancel();\n this._createInvitations.delete(invitationId);\n this.removedCreated.emit(created.get());\n return;\n }\n\n const accepted = this._acceptInvitations.get(invitationId);\n if (accepted) {\n await accepted.cancel();\n this._acceptInvitations.delete(invitationId);\n this.removedAccepted.emit(accepted.get());\n }\n }\n\n getCreatedInvitations(): Invitation[] {\n return [...this._createInvitations.values()].map((i) => i.get());\n }\n\n getAcceptedInvitations(): Invitation[] {\n return [...this._acceptInvitations.values()].map((i) => i.get());\n }\n\n onPersistentInvitationsLoaded(ctx: Context, callback: () => void): void {\n if (this._persistentInvitationsLoaded) {\n callback();\n } else {\n this._persistentInvitationsLoadedEvent.once(ctx, () => callback());\n }\n }\n\n private _createInvitation(protocol: InvitationProtocol, _options?: Partial<Invitation>): Invitation {\n const {\n invitationId = PublicKey.random().toHex(),\n type = Invitation.Type.INTERACTIVE,\n authMethod = Invitation.AuthMethod.SHARED_SECRET,\n state = Invitation.State.INIT,\n timeout = INVITATION_TIMEOUT,\n swarmKey = PublicKey.random(),\n persistent = _options?.authMethod !== Invitation.AuthMethod.KNOWN_PUBLIC_KEY,\n created = new Date(),\n guestKeypair = undefined,\n role = SpaceMember.Role.ADMIN,\n lifetime = 86400 * 7, // 7 days,\n multiUse = false,\n ...options\n } = _options ?? {};\n const authCode =\n options?.authCode ??\n (authMethod === Invitation.AuthMethod.SHARED_SECRET ? generatePasscode(AUTHENTICATION_CODE_LENGTH) : undefined);\n\n return {\n invitationId,\n type,\n authMethod,\n state,\n swarmKey,\n authCode,\n timeout,\n persistent: persistent && type !== Invitation.Type.DELEGATED, // delegated invitations are persisted in control feed\n guestKeypair:\n guestKeypair ?? (authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY ? createAdmissionKeypair() : undefined),\n created,\n lifetime,\n role,\n multiUse,\n delegationCredentialId: options?.delegationCredentialId,\n ...options,\n ...protocol.getInvitationContext(),\n } satisfies Invitation;\n }\n\n private _createObservableInvitation(\n ctx: Context,\n handler: InvitationProtocol,\n invitation: Invitation,\n ): { ctx: Context; stream: PushStream<Invitation>; observableInvitation: CancellableInvitation } {\n const stream = new PushStream<Invitation>();\n const invitationCtx = ctx.derive({\n onError: (err) => {\n stream.error(err);\n void invitationCtx.dispose();\n },\n });\n invitationCtx.onDispose(() => {\n log('complete', { ...handler.toJSON() });\n stream.complete();\n });\n const observableInvitation = new CancellableInvitation({\n initialInvitation: invitation,\n subscriber: stream.observable,\n onCancel: async () => {\n stream.next({ ...invitation, state: Invitation.State.CANCELLED });\n await invitationCtx.dispose();\n },\n });\n return { ctx: invitationCtx, stream, observableInvitation };\n }\n\n private _createObservableAcceptingInvitation(\n parentCtx: Context,\n handler: InvitationProtocol,\n initialState: Invitation,\n ): {\n ctx: Context;\n invitation: AuthenticatingInvitation;\n stream: PushStream<Invitation>;\n otpEnteredTrigger: Trigger<string>;\n } {\n const otpEnteredTrigger = new Trigger<string>();\n const stream = new PushStream<Invitation>();\n // Derive from caller ctx so `TRACE_SPAN_ATTRIBUTE` propagates via the parent chain.\n const ctx = parentCtx.derive({\n onError: (err) => {\n if (err instanceof TimeoutError) {\n log('timeout', { ...handler.toJSON() });\n stream.next({ ...initialState, state: Invitation.State.TIMEOUT });\n } else {\n log.warn('auth failed', err);\n stream.next({ ...initialState, state: Invitation.State.ERROR });\n }\n void ctx.dispose();\n },\n });\n ctx.onDispose(() => {\n log('complete', { ...handler.toJSON() });\n stream.complete();\n });\n const invitation = new AuthenticatingInvitation({\n initialInvitation: initialState,\n subscriber: stream.observable,\n onCancel: async () => {\n stream.next({ ...initialState, state: Invitation.State.CANCELLED });\n await ctx.dispose();\n },\n onAuthenticate: async (code: string) => {\n // TODO(burdon): Reset creates a race condition? Event?\n otpEnteredTrigger.wake(code);\n },\n });\n return { ctx, invitation, stream, otpEnteredTrigger };\n }\n\n private async _persistIfRequired(\n handler: InvitationProtocol,\n changeStream: PushStream<Invitation>,\n invitation: Invitation,\n ): Promise<void> {\n if (invitation.type === Invitation.Type.DELEGATED && invitation.delegationCredentialId == null) {\n const delegationCredentialId = await handler.delegate(invitation);\n changeStream.next({ ...invitation, delegationCredentialId });\n } else if (invitation.persistent) {\n await this._metadataStore.addInvitation(invitation);\n this.saved.emit(invitation);\n }\n }\n\n private async _safeDeleteInvitation(invitation: Invitation): Promise<void> {\n try {\n await this._metadataStore.removeInvitation(invitation.invitationId);\n } catch (err) {\n log.catch(err);\n }\n }\n\n private _onInvitationComplete(invitation: CancellableInvitation, callback: () => void): void {\n invitation.subscribe(\n () => {},\n () => {},\n callback,\n );\n }\n}\n\n/**\n * Effect Layer constructing an {@link InvitationsManager}.\n *\n * The invitation handler factory points \"up the stack\" and is wired via\n * {@link InvitationsManager.setInvitationHandlerFactory} after composition.\n */\nexport const InvitationsManagerLayer = (): Layer.Layer<\n InvitationsManagerService,\n never,\n InvitationsHandlerService | IMetadataStoreService\n> =>\n Layer.effect(\n InvitationsManagerService,\n Effect.gen(function* () {\n const invitationsHandler = yield* InvitationsHandlerService;\n const metadataStore = yield* IMetadataStoreService;\n return new InvitationsManager(invitationsHandler, metadataStore);\n }),\n );\n","//\n// Copyright 2019 DXOS.org\n//\n\nimport { runInContext, scheduleTask } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { randomBytes } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols/proto';\nimport { type AuthService } from '@dxos/protocols/proto/dxos/mesh/teleport/auth';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nexport type AuthProvider = (nonce: Uint8Array) => Promise<Uint8Array | undefined>;\n\nexport type AuthVerifier = (nonce: Uint8Array, credential: Uint8Array) => Promise<boolean>;\n\nexport type AuthExtensionProps = {\n provider: AuthProvider;\n verifier: AuthVerifier;\n onAuthSuccess: () => void;\n onAuthFailure: () => void;\n};\n\nexport class AuthExtension extends RpcExtension<Services, Services> {\n private readonly _ctx = new Context({\n onError: (err) => {\n log.catch(err);\n },\n });\n\n constructor(private readonly _authProps: AuthExtensionProps) {\n super({\n requested: {\n AuthService: schema.getService('dxos.mesh.teleport.auth.AuthService'),\n },\n exposed: {\n AuthService: schema.getService('dxos.mesh.teleport.auth.AuthService'),\n },\n timeout: 60 * 1000, // Long timeout because auth can wait for sync in certain cases.\n });\n }\n\n protected async getHandlers(): Promise<Services> {\n return {\n AuthService: {\n authenticate: async ({ challenge }) => {\n try {\n const credential = await this._authProps.provider(challenge);\n if (!credential) {\n throw new Error('auth rejected');\n }\n return { credential };\n } catch (err) {\n log.error('failed to generate auth credentials', err);\n throw new Error('auth rejected');\n }\n },\n },\n };\n }\n\n override async onOpen(context: ExtensionContext): Promise<void> {\n await super.onOpen(context);\n scheduleTask(this._ctx, async () => {\n try {\n const challenge = randomBytes(32);\n const { credential } = await this.rpc.AuthService.authenticate({ challenge });\n invariant(credential?.length > 0, 'invalid credential');\n const success = await this._authProps.verifier(challenge, credential);\n invariant(success, 'credential not verified');\n runInContext(this._ctx, () => this._authProps.onAuthSuccess());\n } catch (err) {\n log('auth failed', err);\n this.close();\n this._authProps.onAuthFailure();\n }\n });\n }\n\n override async onClose(): Promise<void> {\n await this._ctx.dispose();\n await super.onClose();\n }\n\n override async onAbort(): Promise<void> {\n await this._ctx.dispose();\n await super.onAbort();\n }\n}\n\ntype Services = { AuthService: AuthService };\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { type FeedWriter } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type MaybePromise } from '@dxos/util';\n\n/**\n * Maps the written arguments onto a different message type.\n */\nexport const createMappedFeedWriter = <Source extends {}, Target extends {}>(\n mapper: (arg: Source) => MaybePromise<Target>,\n writer: FeedWriter<Target>,\n): FeedWriter<Source> => {\n invariant(mapper);\n invariant(writer);\n\n return {\n write: async (data: Source, options) => await writer.write(await mapper(data), options),\n };\n};\n","//\n// Copyright 2020 DXOS.org\n//\n\nimport { type FeedBlock, type FeedBlockSelector } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\n\nimport { type TimeframeClock } from './timeframe-clock';\n\n/**\n * The MessageSelector makes sure that we read in a trusted order.\n * The first message we wish to process is the SpaceGenesis, which will admit a Feed.\n * As we encounter and process FeedAdmit messages those are added to the Space's trust,\n * and we begin processing messages from them as well.\n */\nexport const createMessageSelector = (timeframeClock: TimeframeClock): FeedBlockSelector<FeedMessage> => {\n return (messages: FeedBlock<FeedMessage>[]) => {\n // Pick the first candidate with a valid timeframe that has no gaps.\n for (let i = 0; i < messages.length; i++) {\n const {\n data: { timeframe },\n } = messages[i];\n invariant(timeframe);\n\n if (!timeframeClock.hasGaps(timeframe)) {\n return i;\n }\n }\n\n // Not ready for this message yet.\n log('Skipping...');\n };\n};\n","//\n// Copyright 2020 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { timed } from '@dxos/debug';\nimport { type FeedIndex } from '@dxos/feed-store';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { Timeframe } from '@dxos/timeframe';\n\nexport const mapTimeframeToFeedIndexes = (timeframe: Timeframe): FeedIndex[] =>\n timeframe.frames().map(([feedKey, index]) => ({ feedKey, index }));\n\nexport const mapFeedIndexesToTimeframe = (indexes: FeedIndex[]): Timeframe =>\n new Timeframe(indexes.map(({ feedKey, index }) => [feedKey, index]));\n\nexport const startAfter = (timeframe: Timeframe): FeedIndex[] =>\n timeframe.frames().map(([feedKey, index]) => ({ feedKey, index: index + 1 }));\n\n/**\n * Keeps state of the last timeframe that was processed by ECHO.\n */\nexport class TimeframeClock {\n readonly update = new Event<Timeframe>();\n\n private _pendingTimeframe: Timeframe;\n\n constructor(private _timeframe = new Timeframe()) {\n this._pendingTimeframe = _timeframe;\n }\n\n /**\n * Timeframe that was processed by ECHO.\n */\n get timeframe() {\n return this._timeframe;\n }\n\n /**\n * Timeframe that is currently being processed by ECHO.\n * Will be equal to `timeframe` after the processing is complete.\n */\n get pendingTimeframe() {\n return this._pendingTimeframe;\n }\n\n setTimeframe(timeframe: Timeframe): void {\n this._timeframe = timeframe;\n this._pendingTimeframe = timeframe;\n this.update.emit(this._timeframe);\n }\n\n updatePendingTimeframe(key: PublicKey, seq: number): void {\n this._pendingTimeframe = Timeframe.merge(this._pendingTimeframe, new Timeframe([[key, seq]]));\n }\n\n updateTimeframe(): void {\n this._timeframe = this._pendingTimeframe;\n this.update.emit(this._timeframe);\n }\n\n hasGaps(timeframe: Timeframe): boolean {\n const gaps = Timeframe.dependencies(timeframe, this._timeframe);\n return !gaps.isEmpty();\n }\n\n @timed(5_000)\n async waitUntilReached(target: Timeframe): Promise<void> {\n log('waitUntilReached', { target, current: this._timeframe });\n await this.update.waitForCondition(() => {\n log('check if reached', {\n target,\n current: this._timeframe,\n deps: Timeframe.dependencies(target, this._timeframe),\n });\n\n return Timeframe.dependencies(target, this._timeframe).isEmpty();\n });\n }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, Trigger, sleepWithContext, synchronized } from '@dxos/async';\nimport { Context, rejectOnDispose } from '@dxos/context';\nimport { failUndefined } from '@dxos/debug';\nimport { FeedSetIterator, type FeedWrapper, type FeedWriter } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type FeedMessageBlock } from '@dxos/protocols';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { Timeframe } from '@dxos/timeframe';\nimport { ComplexMap } from '@dxos/util';\n\nimport { createMappedFeedWriter } from './feeds';\nimport { createMessageSelector } from './message-selector';\nimport { TimeframeClock, mapFeedIndexesToTimeframe, startAfter } from './timeframe-clock';\n\nexport type WaitUntilReachedTargetProps = {\n /**\n * For cancellation.\n */\n ctx?: Context;\n timeout?: number;\n\n /**\n * @default true\n */\n breakOnStall?: boolean;\n};\n\n/**\n * External state accessor.\n */\nexport class PipelineState {\n /**\n * @internal\n */\n _ctx = new Context();\n\n // TODO(dmaretskyi): Remove?. Avoid accessing `_timeframeClock` before constructor initialization.\n public get timeframeUpdate() {\n return this._timeframeClock.update;\n }\n\n public readonly stalled = new Event();\n\n /**\n * @internal\n */\n _startTimeframe: Timeframe = new Timeframe();\n\n /**\n * Target timeframe we are waiting to reach.\n */\n private _targetTimeframe: Timeframe | undefined;\n\n /**\n * @internal\n */\n _reachedTargetPromise: Promise<void> | undefined;\n\n /**\n * @internal\n */\n _reachedTarget: boolean = false;\n\n constructor(\n private _feeds: ComplexMap<PublicKey, FeedWrapper<FeedMessage>>,\n private _timeframeClock: TimeframeClock,\n ) {}\n\n /**\n * Latest theoretical timeframe based on the last mutation in each feed.\n * NOTE: This might never be reached if the mutation dependencies\n */\n // TODO(dmaretskyi): Rename `totalTimeframe`? or `lastTimeframe`.\n get endTimeframe() {\n return mapFeedIndexesToTimeframe(\n Array.from(this._feeds.values())\n .filter((feed) => feed.length > 0)\n .map((feed) => ({\n feedKey: feed.key,\n index: feed.length - 1,\n })),\n );\n }\n\n get startTimeframe() {\n return this._startTimeframe;\n }\n\n get timeframe() {\n return this._timeframeClock.timeframe;\n }\n\n get pendingTimeframe() {\n return this._timeframeClock.pendingTimeframe;\n }\n\n get targetTimeframe() {\n return this._targetTimeframe ? this._targetTimeframe : new Timeframe();\n }\n\n get reachedTarget() {\n return this._reachedTarget;\n }\n\n get feeds() {\n return Array.from(this._feeds.values());\n }\n\n async waitUntilTimeframe(target: Timeframe): Promise<void> {\n await this._timeframeClock.waitUntilReached(target);\n }\n\n setTargetTimeframe(target: Timeframe): void {\n this._targetTimeframe = target;\n }\n\n /**\n * Wait until the pipeline processes all messages in the feed and reaches the target timeframe if that is set.\n *\n * This function will resolve immediately if the pipeline is stalled.\n *\n * @param timeout Timeout in milliseconds to specify the maximum wait time.\n */\n async waitUntilReachedTargetTimeframe({\n ctx = new Context(),\n timeout,\n breakOnStall = true,\n }: WaitUntilReachedTargetProps = {}): Promise<void> {\n log('waitUntilReachedTargetTimeframe', {\n timeout,\n current: this.timeframe,\n target: this.targetTimeframe,\n });\n\n this._reachedTargetPromise ??= Promise.race([\n this._timeframeClock.update.waitForCondition(() => {\n return Timeframe.dependencies(this.targetTimeframe, this.timeframe).isEmpty();\n }),\n ...(breakOnStall ? [this.stalled.discardParameter().waitForCount(1)] : []),\n ]);\n\n let done = false;\n\n if (timeout) {\n return Promise.race([\n rejectOnDispose(ctx),\n rejectOnDispose(this._ctx),\n this._reachedTargetPromise.then(() => {\n done = true;\n this._reachedTarget = true;\n }),\n sleepWithContext(this._ctx, timeout).then(() => {\n if (done) {\n return;\n }\n\n log.warn('waitUntilReachedTargetTimeframe timed out', {\n timeout,\n current: this.timeframe,\n target: this.targetTimeframe,\n dependencies: Timeframe.dependencies(this.targetTimeframe, this.timeframe),\n });\n }),\n ]);\n } else {\n return this._reachedTargetPromise;\n }\n }\n}\n\n// TODO(mykola): Extract to `@dxos/echo-protocol`\nexport interface PipelineAccessor {\n state: PipelineState;\n writer: FeedWriter<FeedMessage.Payload>;\n}\n\n/**\n * A multi-reader pipeline that operates on feeds.\n * Might have a single writable feed.\n * Has a timeframe clock to handle message ordering.\n *\n * NOTE:\n * - Feeds passed in must have value encoding consistent with the type expected by the iterator/writer.\n *\n * # Usage examples\n *\n * ## Create a new space.\n *\n * 1. Generate space key, genesis feed key.\n * 2. Create and open pipeline reading from {}.\n * 3. Create and add the writable genesis feed.\n * 4. Write the initial sequence of control and credential messages.\n *\n * ## Load an existing space from storage\n *\n * 1. Load space key, genesis feed key, get starting timeframe from saved snapshot.\n * 2. Create and open pipeline reading from the initial timeframe.\n * 3. Open and add the genesis feed.\n * 4. Once the writable feed is added, the pipeline becomes writable.\n *\n * ## Join an existing space created by another agent/device.\n *\n * 1. Get the space key, genesis feed key from another agent.\n * 2. (optionally) Download the snapshot from another agent.\n * 3. Create and open pipeline.\n * 4. Generate the writable feed key.\n * 5. Wait for the writable feed to be added.\n */\nexport class Pipeline implements PipelineAccessor {\n private readonly _timeframeClock = new TimeframeClock(new Timeframe());\n private readonly _feeds = new ComplexMap<PublicKey, FeedWrapper<FeedMessage>>(PublicKey.hash);\n\n // External state accessor.\n private readonly _state: PipelineState = new PipelineState(this._feeds, this._timeframeClock);\n\n // Waits for the message consumer to process the message and yield control back to the pipeline.\n private readonly _processingTrigger = new Trigger().wake();\n private readonly _pauseTrigger = new Trigger().wake();\n\n // Pending downloads.\n private readonly _downloads = new ComplexMap<FeedWrapper<FeedMessage>, any>((value) => PublicKey.hash(value.key));\n\n // Inbound feed stream.\n private _feedSetIterator?: FeedSetIterator<FeedMessage>;\n\n // Outbound feed writer.\n private _writer: FeedWriter<FeedMessage.Payload> | undefined;\n\n private _isStopping = false;\n private _isStarted = false;\n private _isBeingConsumed = false;\n private _isPaused = false;\n\n get state() {\n return this._state;\n }\n\n get writer(): FeedWriter<FeedMessage.Payload> {\n invariant(this._writer, 'Writer not set.');\n return this._writer;\n }\n\n hasFeed(feedKey: PublicKey): boolean {\n return this._feeds.has(feedKey);\n }\n\n getFeeds(): FeedWrapper<FeedMessage>[] {\n return this._feedSetIterator!.feeds;\n }\n\n // NOTE: This cannot be synchronized with `stop` because stop waits for the mutation processing to complete,\n // which might be opening feeds during the mutation processing, which w\n async addFeed(feed: FeedWrapper<FeedMessage>): Promise<void> {\n this._feeds.set(feed.key, feed);\n\n if (this._feedSetIterator) {\n await this._feedSetIterator.addFeed(feed);\n }\n\n if (this._isStarted && !this._isPaused) {\n this._setFeedDownloadState(feed);\n }\n }\n\n setWriteFeed(feed: FeedWrapper<FeedMessage>): void {\n invariant(!this._writer, 'Writer already set.');\n invariant(feed.properties.writable, 'Feed must be writable.');\n\n this._writer = createMappedFeedWriter<FeedMessage.Payload, FeedMessage>(\n (payload: FeedMessage.Payload) => ({\n timeframe: this._timeframeClock.timeframe,\n payload,\n }),\n feed.createFeedWriter(),\n );\n }\n\n @synchronized\n async start(): Promise<void> {\n invariant(!this._isStarted, 'Pipeline is already started.');\n log('starting...');\n await this._initIterator();\n await this._feedSetIterator!.open();\n this._isStarted = true;\n log('started');\n\n if (!this._isPaused) {\n for (const feed of this._feeds.values()) {\n this._setFeedDownloadState(feed);\n }\n }\n }\n\n @synchronized\n async stop(): Promise<void> {\n log('stopping...');\n this._isStopping = true;\n for (const [feed, handle] of this._downloads.entries()) {\n feed.undownload(handle);\n }\n this._downloads.clear();\n await this._feedSetIterator?.close();\n await this._processingTrigger.wait(); // Wait for the in-flight message to be processed.\n await this._state._ctx.dispose();\n this._state._ctx = new Context();\n this._state._reachedTargetPromise = undefined;\n this._state._reachedTarget = false;\n this._isStarted = false;\n log('stopped');\n }\n\n /**\n * @param timeframe Timeframe of already processed messages.\n * The pipeline will start processing messages AFTER this timeframe.\n */\n @synchronized\n async setCursor(timeframe: Timeframe): Promise<void> {\n invariant(!this._isStarted || this._isPaused, 'Invalid state.');\n\n this._state._startTimeframe = timeframe;\n this._timeframeClock.setTimeframe(timeframe);\n\n // Cancel downloads of mutations before the cursor.\n if (this._feedSetIterator) {\n await this._feedSetIterator.close();\n await this._initIterator();\n await this._feedSetIterator.open();\n }\n }\n\n /**\n * Calling pause while processing will cause a deadlock.\n */\n @synchronized\n async pause(): Promise<void> {\n if (this._isPaused) {\n return;\n }\n\n this._pauseTrigger.reset();\n await this._processingTrigger.wait();\n this._isPaused = true;\n }\n\n @synchronized\n async unpause(): Promise<void> {\n invariant(this._isPaused, 'Pipeline is not paused.');\n\n this._pauseTrigger.wake();\n this._isPaused = false;\n\n for (const feed of this._feeds.values()) {\n this._setFeedDownloadState(feed);\n }\n }\n\n /**\n * Starts to iterate over the ordered messages from the added feeds.\n * Updates the timeframe clock after the message has bee processed.\n */\n async *consume(): AsyncIterable<FeedMessageBlock> {\n invariant(!this._isBeingConsumed, 'Pipeline is already being consumed.');\n this._isBeingConsumed = true;\n\n invariant(this._feedSetIterator, 'Iterator not initialized.');\n let lastFeedSetIterator = this._feedSetIterator;\n let iterable = lastFeedSetIterator[Symbol.asyncIterator]();\n\n while (!this._isStopping) {\n await this._pauseTrigger.wait();\n\n // Iterator might have been changed while we were waiting for the processing to complete.\n if (lastFeedSetIterator !== this._feedSetIterator) {\n invariant(this._feedSetIterator, 'Iterator not initialized.');\n lastFeedSetIterator = this._feedSetIterator;\n iterable = lastFeedSetIterator[Symbol.asyncIterator]();\n }\n\n // Will be canceled when the iterator gets closed.\n const { done, value } = await iterable.next();\n if (!done) {\n const block = value ?? failUndefined();\n this._processingTrigger.reset();\n this._timeframeClock.updatePendingTimeframe(PublicKey.from(block.feedKey), block.seq);\n yield block;\n this._processingTrigger.wake();\n this._timeframeClock.updateTimeframe();\n }\n }\n\n // TODO(burdon): Test re-entrant?\n this._isBeingConsumed = false;\n }\n\n private _setFeedDownloadState(feed: FeedWrapper<FeedMessage>): void {\n let handle = this._downloads.get(feed); // TODO(burdon): Always undefined?\n if (handle) {\n feed.undownload(handle);\n }\n\n const timeframe = this._state._startTimeframe;\n const seq = timeframe.get(feed.key) ?? -1;\n log('download', { feed: feed.key.truncate(), seq, length: feed.length });\n handle = feed.download({ start: seq + 1, linear: true }, (err: any, data: any) => {\n if (err) {\n // log.warn(err); // TODO(burdon): Feed is closed/Download was cancelled.\n } else {\n log('downloaded', { data }); // TODO(burdon): Never called.\n }\n });\n\n this._downloads.set(feed, handle);\n }\n\n private async _initIterator(): Promise<void> {\n this._feedSetIterator = new FeedSetIterator<FeedMessage>(createMessageSelector(this._timeframeClock), {\n start: startAfter(this._timeframeClock.timeframe),\n stallTimeout: 1000,\n });\n\n this._feedSetIterator.stalled.on((iterator) => {\n log.warn(`Stalled after ${iterator.options.stallTimeout}ms with ${iterator.size} feeds.`, {\n currentTimeframe: this._timeframeClock.timeframe,\n targetTimeframe: this._state.targetTimeframe,\n });\n this._state.stalled.emit();\n });\n\n for (const feed of this._feeds.values()) {\n await this._feedSetIterator.addFeed(feed);\n }\n }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Codec } from '@dxos/codec-protobuf';\nimport { createCodecEncoding } from '@dxos/hypercore';\nimport { schema } from '@dxos/protocols/proto';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\n\n/**\n * Codec for feed messages.\n */\nexport const codec: Codec<FeedMessage> = schema.getCodecForType('dxos.echo.feed.FeedMessage');\n\n/**\n * Value encoding used by feed store.\n */\nexport const valueEncoding = createCodecEncoding(codec);\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { DeferredTask, scheduleMicroTask, sleepWithContext, trackLeaks } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport {\n type DelegateInvitationCredential,\n type FeedInfo,\n type MemberInfo,\n type SpaceState,\n SpaceStateMachine,\n} from '@dxos/credentials';\nimport { type FeedWrapper } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type FeedMessageBlock } from '@dxos/protocols';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type ControlPipelineSnapshot } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport { AdmittedFeed, type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { Timeframe } from '@dxos/timeframe';\nimport { trace } from '@dxos/tracing';\nimport { type AsyncCallback, Callback, tracer } from '@dxos/util';\n\nimport { type IMetadataStore } from '../metadata';\nimport { Pipeline, type PipelineAccessor } from '../pipeline';\n\nexport type ControlPipelineProps = {\n spaceKey: PublicKey;\n genesisFeed: FeedWrapper<FeedMessage>;\n feedProvider: (feedKey: PublicKey) => Promise<FeedWrapper<FeedMessage>>;\n metadataStore: IMetadataStore;\n};\n\nconst TIMEFRAME_SAVE_DEBOUNCE_INTERVAL = 500;\n\nconst CONTROL_PIPELINE_SNAPSHOT_DELAY = 10_000;\n\nconst USE_SNAPSHOTS = true;\n\n/**\n * Processes HALO credentials, which include genesis and invitations.\n */\n@trackLeaks('start', 'stop')\nexport class ControlPipeline {\n private readonly _ctx = new Context();\n private readonly _pipeline: Pipeline;\n private readonly _spaceStateMachine: SpaceStateMachine;\n\n private readonly _spaceKey: PublicKey;\n private readonly _metadata: IMetadataStore;\n private _targetTimeframe?: Timeframe;\n private _lastTimeframeSaveTime: number = Date.now();\n\n public readonly onFeedAdmitted = new Callback<AsyncCallback<FeedInfo>>();\n public readonly onMemberRoleChanged: Callback<AsyncCallback<MemberInfo[]>>;\n public readonly onCredentialProcessed: Callback<AsyncCallback<Credential>>;\n public readonly onDelegatedInvitation: Callback<AsyncCallback<DelegateInvitationCredential>>;\n public readonly onDelegatedInvitationRemoved: Callback<AsyncCallback<DelegateInvitationCredential>>;\n\n private _snapshotTask = new DeferredTask(this._ctx, async () => {\n await sleepWithContext(this._ctx, CONTROL_PIPELINE_SNAPSHOT_DELAY);\n await this._saveSnapshot();\n });\n\n constructor({ spaceKey, genesisFeed, feedProvider, metadataStore }: ControlPipelineProps) {\n this._spaceKey = spaceKey;\n this._metadata = metadataStore;\n this._pipeline = new Pipeline();\n void this._pipeline.addFeed(genesisFeed); // TODO(burdon): Require async open/close?\n\n this._spaceStateMachine = new SpaceStateMachine(spaceKey);\n this._spaceStateMachine.onFeedAdmitted.set(async (info) => {\n // log('feed admitted', { info });\n log('feed admitted', { key: info.key });\n\n // TODO(burdon): Check not stopping.\n if (info.assertion.designation === AdmittedFeed.Designation.CONTROL && !info.key.equals(genesisFeed.key)) {\n scheduleMicroTask(this._ctx, async () => {\n try {\n const feed = await feedProvider(info.key);\n if (this._ctx.disposed) {\n return;\n }\n if (!this._pipeline.hasFeed(feed.key)) {\n await this._pipeline.addFeed(feed);\n }\n } catch (err: any) {\n log.catch(err);\n }\n });\n }\n\n await this.onFeedAdmitted.callIfSet(info);\n });\n\n this.onMemberRoleChanged = this._spaceStateMachine.onMemberRoleChanged;\n this.onCredentialProcessed = this._spaceStateMachine.onCredentialProcessed;\n this.onDelegatedInvitation = this._spaceStateMachine.onDelegatedInvitation;\n this.onDelegatedInvitationRemoved = this._spaceStateMachine.onDelegatedInvitationRemoved;\n }\n\n get spaceState(): SpaceState {\n return this._spaceStateMachine;\n }\n\n get pipeline(): PipelineAccessor {\n return this._pipeline;\n }\n\n async setWriteFeed(feed: FeedWrapper<FeedMessage>): Promise<void> {\n await this._pipeline.addFeed(feed);\n this._pipeline.setWriteFeed(feed);\n }\n\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n async start(ctx: Context): Promise<void> {\n const snapshot = this._metadata.getSpaceControlPipelineSnapshot(this._spaceKey);\n log('load snapshot', { key: this._spaceKey, present: !!snapshot, tf: snapshot?.timeframe });\n if (USE_SNAPSHOTS && snapshot) {\n await this._processSnapshot(snapshot);\n }\n\n log('starting...');\n setTimeout(async () => {\n void this._consumePipeline(ctx);\n });\n\n await this._pipeline.start();\n log('started');\n }\n\n private async _processSnapshot(snapshot: ControlPipelineSnapshot): Promise<void> {\n await this._pipeline.setCursor(snapshot.timeframe);\n\n for (const message of snapshot.messages ?? []) {\n const result = await this._spaceStateMachine.process(message.credential, {\n sourceFeed: message.feedKey,\n skipVerification: true,\n });\n\n if (!result) {\n log.warn('credential processing failed from snapshot', { message });\n }\n }\n }\n\n private async _saveSnapshot(): Promise<void> {\n await this._pipeline.pause();\n const snapshot: ControlPipelineSnapshot = {\n timeframe: this._pipeline.state.timeframe,\n messages: this._spaceStateMachine.credentialEntries.map((entry) => ({\n feedKey: entry.sourceFeed,\n credential: entry.credential,\n })),\n };\n await this._pipeline.unpause();\n\n log('save snapshot', { key: this._spaceKey, snapshot: getSnapshotLoggerContext(snapshot) });\n await this._metadata.setSpaceControlPipelineSnapshot(this._spaceKey, snapshot);\n }\n\n private async _consumePipeline(ctx: Context): Promise<void> {\n for await (const msg of this._pipeline.consume()) {\n try {\n await this._processMessage(ctx, msg);\n } catch (err: any) {\n log.catch(err);\n }\n }\n }\n\n @trace.span({ showInBrowserTimeline: true, showInRemoteTracing: false })\n private async _processMessage(ctx: Context, msg: FeedMessageBlock): Promise<void> {\n log('processing', { key: msg.feedKey, seq: msg.seq });\n if (msg.data.payload.credential) {\n const timer = tracer.mark('dxos.echo.pipeline.control');\n const result = await this._spaceStateMachine.process(msg.data.payload.credential.credential, {\n sourceFeed: PublicKey.from(msg.feedKey),\n });\n\n timer.end();\n if (!result) {\n log.warn('processing failed', { msg });\n } else {\n await this._noteTargetStateIfNeeded(this._pipeline.state.pendingTimeframe);\n }\n\n this._snapshotTask.schedule();\n }\n }\n\n private async _noteTargetStateIfNeeded(timeframe: Timeframe): Promise<void> {\n // TODO(dmaretskyi): Replace this with a proper debounce/throttle.\n\n if (Date.now() - this._lastTimeframeSaveTime > TIMEFRAME_SAVE_DEBOUNCE_INTERVAL) {\n this._lastTimeframeSaveTime = Date.now();\n\n await this._saveTargetTimeframe(timeframe);\n }\n }\n\n async stop(): Promise<void> {\n log('stopping...');\n await this._ctx.dispose();\n await this._pipeline.stop();\n await this._saveTargetTimeframe(this._pipeline.state.timeframe);\n log('stopped');\n }\n\n private async _saveTargetTimeframe(timeframe: Timeframe): Promise<void> {\n try {\n const newTimeframe = Timeframe.merge(this._targetTimeframe ?? new Timeframe(), timeframe);\n await this._metadata.setSpaceControlLatestTimeframe(this._spaceKey, newTimeframe);\n this._targetTimeframe = newTimeframe;\n } catch (err: any) {\n log(err);\n }\n }\n}\n\nconst getSnapshotLoggerContext = (snapshot: ControlPipelineSnapshot) => {\n return snapshot.messages?.map((msg) => {\n const issuer = msg.credential.issuer;\n const subject = msg.credential.subject.id;\n const type = msg.credential.subject.assertion['@type'];\n return { issuer, subject, type };\n });\n};\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, scheduleMicroTask, synchronized, trackLeaks } from '@dxos/async';\nimport { type Context, Resource } from '@dxos/context';\nimport { type DelegateInvitationCredential, type FeedInfo, type MemberInfo } from '@dxos/credentials';\nimport { type FeedOptions, type FeedWrapper } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type PublicKey, type SpaceId } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { AdmittedFeed, type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type Timeframe } from '@dxos/timeframe';\nimport { trace } from '@dxos/tracing';\nimport { type AsyncCallback, Callback } from '@dxos/util';\n\nimport { type IMetadataStore } from '../metadata';\nimport { type PipelineAccessor } from '../pipeline';\nimport { ControlPipeline } from './control-pipeline';\nimport { type SpaceProtocol } from './space-protocol';\n\n// TODO(burdon): Factor out?\ntype FeedProvider = (feedKey: PublicKey, opts?: FeedOptions) => Promise<FeedWrapper<FeedMessage>>;\n\nexport type SpaceProps = {\n id: SpaceId;\n spaceKey: PublicKey;\n protocol: SpaceProtocol;\n genesisFeed: FeedWrapper<FeedMessage>;\n feedProvider: FeedProvider;\n metadataStore: IMetadataStore;\n memberKey: PublicKey;\n\n // TODO(dmaretskyi): Superseded by epochs.\n snapshotId?: string | undefined;\n\n onDelegatedInvitationStatusChange: (invitation: DelegateInvitationCredential, isActive: boolean) => Promise<void>;\n onMemberRolesChanged: (member: MemberInfo[]) => Promise<void>;\n};\n\nexport type CreatePipelineProps = {\n start: Timeframe;\n // designation: AdmittedFeed.Designation;\n};\n\n/**\n * Spaces are globally addressable databases with access control.\n */\n// TODO(dmaretskyi): Extract database stuff.\n// TODO(dmaretskyi): Rename HaloGraph move to HALO.\n@trackLeaks('open', 'close')\nexport class Space extends Resource {\n public readonly onCredentialProcessed = new Callback<AsyncCallback<Credential>>();\n public readonly stateUpdate = new Event();\n public readonly protocol: SpaceProtocol;\n\n private readonly _id: SpaceId;\n private readonly _key: PublicKey;\n private readonly _genesisFeedKey: PublicKey;\n private readonly _feedProvider: FeedProvider;\n private readonly _controlPipeline: ControlPipeline;\n\n private _controlFeed?: FeedWrapper<FeedMessage>;\n private _dataFeed?: FeedWrapper<FeedMessage>;\n\n constructor(params: SpaceProps) {\n super();\n invariant(params.spaceKey && params.feedProvider);\n this._id = params.id;\n this._key = params.spaceKey;\n this._genesisFeedKey = params.genesisFeed.key;\n this._feedProvider = params.feedProvider;\n\n this._controlPipeline = new ControlPipeline({\n spaceKey: params.spaceKey,\n genesisFeed: params.genesisFeed,\n feedProvider: params.feedProvider,\n metadataStore: params.metadataStore,\n });\n\n // TODO(dmaretskyi): Feed set abstraction.\n this._controlPipeline.onFeedAdmitted.set(async (info) => {\n // Enable sparse replication to not download mutations covered by prior epochs.\n const sparse = info.assertion.designation === AdmittedFeed.Designation.DATA;\n\n if (!info.key.equals(params.genesisFeed.key)) {\n scheduleMicroTask(this._ctx, async () => {\n await this.protocol.addFeed(await params.feedProvider(info.key, { sparse }));\n });\n }\n });\n\n this._controlPipeline.onCredentialProcessed.set(async (credential) => {\n await this.onCredentialProcessed.callIfSet(credential);\n log('onCredentialProcessed', { credential });\n this.stateUpdate.emit();\n });\n this._controlPipeline.onDelegatedInvitation.set(async (invitation) => {\n log('onDelegatedInvitation', { invitation });\n await params.onDelegatedInvitationStatusChange(invitation, true);\n });\n this._controlPipeline.onDelegatedInvitationRemoved.set(async (invitation) => {\n log('onDelegatedInvitationRemoved', { invitation });\n await params.onDelegatedInvitationStatusChange(invitation, false);\n });\n this._controlPipeline.onMemberRoleChanged.set(async (changedMembers) => {\n log('onMemberRoleChanged', () => ({ changedMembers: changedMembers.map((m) => [m.key, m.role]) }));\n await params.onMemberRolesChanged(changedMembers);\n });\n\n // Start replicating the genesis feed.\n this.protocol = params.protocol;\n }\n\n @logInfo\n get id() {\n return this._id;\n }\n\n @logInfo\n get key() {\n return this._key;\n }\n\n get genesisFeedKey(): PublicKey {\n return this._genesisFeedKey;\n }\n\n get controlFeedKey() {\n return this._controlFeed?.key;\n }\n\n get dataFeedKey() {\n return this._dataFeed?.key;\n }\n\n get spaceState() {\n return this._controlPipeline.spaceState;\n }\n\n /**\n * @test-only\n */\n get controlPipeline(): PipelineAccessor {\n return this._controlPipeline.pipeline;\n }\n\n async setControlFeed(feed: FeedWrapper<FeedMessage>): Promise<this> {\n invariant(!this._controlFeed, 'Control feed already set.');\n this._controlFeed = feed;\n await this._controlPipeline.setWriteFeed(feed);\n return this;\n }\n\n async setDataFeed(feed: FeedWrapper<FeedMessage>): Promise<this> {\n invariant(!this._dataFeed, 'Data feed already set.');\n this._dataFeed = feed;\n return this;\n }\n\n /**\n * Use for diagnostics.\n */\n getControlFeeds(): FeedInfo[] {\n return Array.from(this._controlPipeline.spaceState.feeds.values());\n }\n\n @trace.span({ op: 'lifecycle' })\n protected override async _open(ctx: Context): Promise<void> {\n log('opening...');\n\n // Order is important.\n await this._controlPipeline.start(ctx);\n\n log('opened');\n }\n\n @synchronized\n public async startProtocol(ctx: Context): Promise<void> {\n invariant(this.isOpen);\n await this.protocol.start(ctx);\n await this.protocol.addFeed(await this._feedProvider(this._genesisFeedKey));\n }\n\n @synchronized\n protected override async _close(ctx: Context): Promise<void> {\n log('closing...', { key: this._key });\n\n // Closes in reverse order to open.\n await this.protocol.stop(ctx);\n await this._controlPipeline.stop();\n\n log('closed');\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Trigger, scheduleTask } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { ProtocolError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionDiscoveryService,\n type GetAdmissionCredentialRequest,\n type GetAdmissionCredentialResponse,\n} from '@dxos/protocols/proto/dxos/mesh/teleport';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport { type Space } from './space';\n\n/**\n * Guest's side for a connection to a concrete peer in p2p network during invitation.\n */\nexport class CredentialRetrieverExtension extends RpcExtension<\n { AdmissionDiscoveryService: AdmissionDiscoveryService },\n {}\n> {\n private _ctx = new Context();\n\n constructor(\n private readonly _request: GetAdmissionCredentialRequest,\n private readonly _onResult: Trigger<Credential>,\n ) {\n super({\n requested: {\n AdmissionDiscoveryService: schema.getService('dxos.mesh.teleport.AdmissionDiscoveryService'),\n },\n });\n }\n\n protected override async getHandlers(): Promise<{}> {\n return {};\n }\n\n override async onOpen(context: ExtensionContext): Promise<void> {\n await super.onOpen(context);\n scheduleTask(this._ctx, async () => {\n try {\n const result = await this.rpc.AdmissionDiscoveryService.getAdmissionCredential(this._request);\n this._onResult.wake(result.admissionCredential);\n } catch (err: any) {\n context.close(err);\n }\n });\n }\n\n override async onClose(): Promise<void> {\n await this._ctx.dispose();\n }\n\n override async onAbort(): Promise<void> {\n await this._ctx.dispose();\n }\n}\n\nexport class CredentialServerExtension extends RpcExtension<\n {},\n { AdmissionDiscoveryService: AdmissionDiscoveryService }\n> {\n constructor(private readonly _space: Space) {\n super({\n exposed: {\n AdmissionDiscoveryService: schema.getService('dxos.mesh.teleport.AdmissionDiscoveryService'),\n },\n });\n }\n\n protected override async getHandlers(): Promise<{ AdmissionDiscoveryService: AdmissionDiscoveryService }> {\n return {\n AdmissionDiscoveryService: {\n getAdmissionCredential: async (\n request: GetAdmissionCredentialRequest,\n ): Promise<GetAdmissionCredentialResponse> => {\n const memberInfo = this._space.spaceState.members.get(request.memberKey);\n if (!memberInfo?.credential) {\n throw new ProtocolError({ message: 'Space member not found.', context: { ...request } });\n }\n return { admissionCredential: memberInfo.credential };\n },\n },\n };\n }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Event } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { createIdFromSpaceKey } from '@dxos/echo-protocol';\nimport { type FeedWrapper } from '@dxos/feed-store';\nimport { PublicKey, SpaceId } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport {\n MMSTTopology,\n type SwarmConnection,\n type SwarmNetworkManager,\n type WireProtocol,\n type WireProtocolProps,\n type WireProtocolProvider,\n} from '@dxos/network-manager';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type MuxerStats, Teleport } from '@dxos/teleport';\nimport { type BlobStoreApi, BlobSync } from '@dxos/teleport-extension-object-sync';\nimport { ReplicatorExtension } from '@dxos/teleport-extension-replicator';\nimport { type AsyncCallback, CallbackCollection, ComplexMap } from '@dxos/util';\n\nimport { AuthExtension, type AuthProvider, type AuthVerifier } from './auth';\n\nexport const MOCK_AUTH_PROVIDER: AuthProvider = async (nonce: Uint8Array) => Buffer.from('mock');\nexport const MOCK_AUTH_VERIFIER: AuthVerifier = async (nonce: Uint8Array, credential: Uint8Array) => true;\n\n// TODO(burdon): Reconcile with SigningContext (define types together).\nexport interface SwarmIdentity {\n peerKey: PublicKey;\n identityKey: PublicKey;\n credentialProvider: AuthProvider;\n credentialAuthenticator: AuthVerifier;\n}\n\nexport type SpaceProtocolOptions = {\n topic: PublicKey; // TODO(burdon): Rename?\n swarmIdentity: SwarmIdentity;\n networkManager: SwarmNetworkManager;\n\n blobStore: BlobStoreApi;\n\n onFeed?: (feed: FeedWrapper<FeedMessage>) => Promise<void>;\n\n /**\n * Called when new session is authenticated.\n * Additional extensions can be added here.\n */\n onSessionAuth?: (session: Teleport) => void;\n onAuthFailure?: (session: Teleport) => void;\n\n disableP2pReplication?: boolean;\n};\n\n/**\n * Manages Teleport protocol stream creation and joining swarms with replication and presence extensions.\n */\nexport class SpaceProtocol {\n private readonly _networkManager: SwarmNetworkManager;\n private readonly _swarmIdentity: SwarmIdentity;\n private readonly _onSessionAuth?: (session: Teleport) => void;\n private readonly _onAuthFailure?: (session: Teleport) => void;\n\n public readonly blobSync: BlobSync;\n\n private readonly _disableP2pReplication: boolean;\n\n @logInfo\n private readonly _topic: Promise<PublicKey>;\n\n private readonly _spaceKey: PublicKey;\n\n private readonly _feeds = new Set<FeedWrapper<FeedMessage>>();\n private readonly _sessions = new ComplexMap<PublicKey, SpaceProtocolSession>(PublicKey.hash);\n // TODO(burdon): Move to config (with sensible defaults).\n private readonly _topology = new MMSTTopology({\n originateConnections: 4,\n maxPeers: 10,\n sampleSize: 20,\n });\n\n private _connection?: SwarmConnection;\n\n public readonly feedAdded = new CallbackCollection<AsyncCallback<FeedWrapper<FeedMessage>>>();\n\n get sessions(): ReadonlyMap<PublicKey, SpaceProtocolSession> {\n return this._sessions;\n }\n\n get feeds(): ReadonlySet<FeedWrapper<FeedMessage>> {\n return this._feeds;\n }\n\n @logInfo\n private get _ownPeerKey() {\n return this._swarmIdentity.peerKey;\n }\n\n constructor({\n topic,\n swarmIdentity,\n networkManager,\n onSessionAuth,\n onAuthFailure,\n blobStore,\n disableP2pReplication,\n }: SpaceProtocolOptions) {\n this._spaceKey = topic;\n this._networkManager = networkManager;\n this._swarmIdentity = swarmIdentity;\n this._onSessionAuth = onSessionAuth;\n this._onAuthFailure = onAuthFailure;\n this.blobSync = new BlobSync({ blobStore });\n\n // Space swarm topic contract (DX-1125): the SpaceId bytes (first 20 bytes of SHA-256(spaceKey)).\n // Both peers and the edge must derive the identical swarm key; SpaceId is the only derivation\n // computable on workerd (pure subtle-crypto — the previous hypercore `discoveryKey` needs keyed\n // BLAKE2b, unavailable there). Edge counterpart: `TraceFeedWriter.getSpaceSwarmKey`.\n this._topic = createIdFromSpaceKey(topic).then((spaceId) => PublicKey.from(SpaceId.decode(spaceId)));\n\n this._disableP2pReplication = disableP2pReplication ?? false;\n }\n\n // TODO(burdon): Create abstraction for Space (e.g., add keys and have provider).\n async addFeed(feed: FeedWrapper<FeedMessage>): Promise<void> {\n log('addFeed', { key: feed.key });\n\n this._feeds.add(feed);\n for (const session of this._sessions.values()) {\n session.replicator.addFeed(feed);\n }\n\n await this.feedAdded.callSerial(feed);\n }\n\n // TODO(burdon): Rename open? Common open/close interfaces for all services?\n async start(ctx: Context): Promise<void> {\n if (this._connection) {\n return;\n }\n\n // TODO(burdon): Document why empty buffer.\n const credentials = await this._swarmIdentity.credentialProvider(Buffer.from(''));\n\n await this.blobSync.open();\n\n log('starting...');\n const topic = await this._topic;\n this._connection = await this._networkManager.joinSwarm(ctx, {\n protocolProvider: this._createProtocolProvider(credentials),\n topic,\n topology: this._topology,\n label: `swarm ${topic.truncate()} for space ${this._spaceKey.truncate()}`,\n });\n\n log('started');\n }\n\n public updateTopology(): void {\n this._topology.forceUpdate();\n }\n\n async stop(ctx: Context): Promise<void> {\n await this.blobSync.close();\n\n if (this._connection) {\n log('stopping...');\n await this._connection.close(ctx);\n log('stopped');\n }\n }\n\n private _createProtocolProvider(credentials: Uint8Array | undefined): WireProtocolProvider {\n return (wireProps) => {\n const session = new SpaceProtocolSession({\n wireProps,\n swarmIdentity: this._swarmIdentity,\n onSessionAuth: this._onSessionAuth,\n onAuthFailure: this._onAuthFailure,\n blobSync: this.blobSync,\n disableP2pReplication: this._disableP2pReplication,\n });\n this._sessions.set(wireProps.remotePeerId, session);\n\n for (const feed of this._feeds) {\n session.replicator.addFeed(feed);\n }\n\n return session;\n };\n }\n}\n\nexport type SpaceProtocolSessionProps = {\n wireProps: WireProtocolProps;\n swarmIdentity: SwarmIdentity;\n\n blobSync: BlobSync;\n\n /**\n * Called when new session is authenticated.\n * Additional extensions can be added here.\n */\n onSessionAuth?: (session: Teleport) => void;\n\n onAuthFailure?: (session: Teleport) => void;\n\n disableP2pReplication?: boolean;\n};\n\nexport enum AuthStatus {\n INITIAL = 'INITIAL',\n SUCCESS = 'SUCCESS',\n FAILURE = 'FAILURE',\n}\n\n// TODO(dmaretskyi): Move to a separate file.\n/**\n * Represents a single connection to a remote peer\n */\nexport class SpaceProtocolSession implements WireProtocol {\n @logInfo\n private readonly _wireProps: WireProtocolProps;\n\n private readonly _disableP2pReplication: boolean;\n\n private readonly _onSessionAuth?: (session: Teleport) => void;\n private readonly _onAuthFailure?: (session: Teleport) => void;\n private readonly _swarmIdentity: SwarmIdentity;\n private readonly _blobSync: BlobSync;\n\n private readonly _teleport: Teleport;\n\n // TODO(dmaretskyi): Start with upload=false when switching it on the fly works.\n public readonly replicator = new ReplicatorExtension().setOptions({ upload: true });\n\n private _authStatus = AuthStatus.INITIAL;\n\n @logInfo\n get authStatus() {\n return this._authStatus;\n }\n\n get stats(): Event<MuxerStats> {\n return this._teleport.stats;\n }\n\n // TODO(dmaretskyi): Allow to pass in extra extensions.\n constructor({\n wireProps,\n swarmIdentity,\n onSessionAuth,\n onAuthFailure,\n blobSync,\n disableP2pReplication,\n }: SpaceProtocolSessionProps) {\n this._wireProps = wireProps;\n this._swarmIdentity = swarmIdentity;\n this._onSessionAuth = onSessionAuth;\n this._onAuthFailure = onAuthFailure;\n this._blobSync = blobSync;\n\n this._teleport = new Teleport(wireProps);\n\n this._disableP2pReplication = disableP2pReplication ?? false;\n }\n\n get stream() {\n return this._teleport.stream;\n }\n\n async open(sessionId?: PublicKey): Promise<void> {\n await this._teleport.open(sessionId);\n this._teleport.addExtension(\n 'dxos.mesh.teleport.auth',\n new AuthExtension({\n provider: this._swarmIdentity.credentialProvider,\n verifier: this._swarmIdentity.credentialAuthenticator,\n onAuthSuccess: () => {\n log('Peer authenticated');\n this._authStatus = AuthStatus.SUCCESS;\n this._onSessionAuth?.(this._teleport);\n // TODO(dmaretskyi): Configure replicator to upload.\n },\n onAuthFailure: () => {\n this._authStatus = AuthStatus.FAILURE;\n this._onAuthFailure?.(this._teleport);\n },\n }),\n );\n\n if (!this._disableP2pReplication) {\n this._teleport.addExtension('dxos.mesh.teleport.replicator', this.replicator);\n }\n this._teleport.addExtension('dxos.mesh.teleport.blobsync', this._blobSync.createExtension());\n }\n\n async close(): Promise<void> {\n log('close');\n await this._teleport.close();\n }\n\n async abort(): Promise<void> {\n await this._teleport.abort();\n }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { type AutomergeUrl, parseAutomergeUrl } from '@automerge/automerge-repo';\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { Trigger, synchronized, trackLeaks } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { type DelegateInvitationCredential, type MemberInfo, getCredentialAssertion } from '@dxos/credentials';\nimport { failUndefined } from '@dxos/debug';\nimport { createIdFromSpaceKey } from '@dxos/echo-protocol';\nimport { type FeedStore, FeedStoreService } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type SwarmNetworkManager, SwarmNetworkManagerService } from '@dxos/network-manager';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport type { Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type Teleport } from '@dxos/teleport';\nimport { type BlobStoreApi, BlobStoreApiService } from '@dxos/teleport-extension-object-sync';\nimport { ComplexMap } from '@dxos/util';\n\nimport { type IMetadataStore, IMetadataStoreService } from '../metadata';\nimport { CredentialRetrieverExtension } from './admission-discovery-extension';\nimport { Space } from './space';\nimport { SpaceProtocol, type SwarmIdentity } from './space-protocol';\n\nexport type SpaceManagerProps = {\n feedStore: FeedStore<FeedMessage>;\n networkManager: SwarmNetworkManager;\n metadataStore: IMetadataStore;\n\n blobStore: BlobStoreApi;\n\n disableP2pReplication?: boolean;\n};\n\nexport type ConstructSpaceProps = {\n metadata: SpaceMetadata;\n swarmIdentity: SwarmIdentity;\n memberKey: PublicKey;\n /**\n * Called when connection auth passed successful.\n */\n onAuthorizedConnection: (session: Teleport) => void;\n onAuthFailure?: (session: Teleport) => void;\n onDelegatedInvitationStatusChange: (invitation: DelegateInvitationCredential, isActive: boolean) => Promise<void>;\n onMemberRolesChanged: (member: MemberInfo[]) => Promise<void>;\n};\n\nexport type RequestSpaceAdmissionCredentialProps = {\n spaceKey: PublicKey;\n identityKey: PublicKey;\n swarmIdentity: SwarmIdentity;\n timeout: number;\n};\n\n/**\n * Effect service tag for {@link SpaceManager}.\n */\nexport class SpaceManagerService extends EffectContext.Tag('@dxos/client-services/SpaceManager')<\n SpaceManagerService,\n SpaceManager\n>() {}\n\n/**\n * Manages a collection of ECHO (Data) Spaces.\n */\n@trackLeaks('open', 'close')\nexport class SpaceManager {\n private readonly _spaces = new ComplexMap<PublicKey, Space>(PublicKey.hash);\n private readonly _feedStore: FeedStore<FeedMessage>;\n private readonly _networkManager: SwarmNetworkManager;\n private readonly _metadataStore: IMetadataStore;\n private readonly _blobStore: BlobStoreApi;\n private readonly _disableP2pReplication: boolean;\n\n constructor({ feedStore, networkManager, metadataStore, blobStore, disableP2pReplication }: SpaceManagerProps) {\n // TODO(burdon): Assert.\n this._feedStore = feedStore;\n this._networkManager = networkManager;\n this._metadataStore = metadataStore;\n this._blobStore = blobStore;\n this._disableP2pReplication = disableP2pReplication ?? false;\n }\n\n // TODO(burdon): Remove.\n get spaces() {\n return this._spaces;\n }\n\n @synchronized\n async open(): Promise<void> {}\n\n @synchronized\n async close(): Promise<void> {\n await Promise.all([...this._spaces.values()].map((space) => space.close()));\n }\n\n async constructSpace({\n metadata,\n swarmIdentity,\n onAuthorizedConnection,\n onAuthFailure,\n onDelegatedInvitationStatusChange,\n onMemberRolesChanged,\n memberKey,\n }: ConstructSpaceProps): Promise<Space> {\n log('constructing space...', { spaceKey: metadata.genesisFeedKey });\n\n // The genesis feed will be the same as the control feed if the space was created by the local agent.\n const genesisFeed = await this._feedStore.openFeed(metadata.genesisFeedKey ?? failUndefined());\n\n const spaceKey = metadata.key;\n const spaceId = await createIdFromSpaceKey(spaceKey);\n const protocol = new SpaceProtocol({\n topic: spaceKey,\n swarmIdentity,\n networkManager: this._networkManager,\n onSessionAuth: onAuthorizedConnection,\n onAuthFailure,\n blobStore: this._blobStore,\n disableP2pReplication: this._disableP2pReplication,\n });\n\n const space = new Space({\n id: spaceId,\n spaceKey,\n protocol,\n genesisFeed,\n feedProvider: (feedKey, opts) => this._feedStore.openFeed(feedKey, opts),\n metadataStore: this._metadataStore,\n memberKey,\n onDelegatedInvitationStatusChange,\n onMemberRolesChanged,\n });\n this._spaces.set(space.key, space);\n\n return space;\n }\n\n public async requestSpaceAdmissionCredential(\n ctx: Context,\n params: RequestSpaceAdmissionCredentialProps,\n ): Promise<Credential> {\n log('requesting space admission credential...', { spaceKey: params.spaceKey });\n\n const onCredentialResolved = new Trigger<Credential>();\n const protocol = new SpaceProtocol({\n topic: params.spaceKey,\n swarmIdentity: params.swarmIdentity,\n networkManager: this._networkManager,\n onSessionAuth: (session: Teleport) => {\n session.addExtension(\n 'dxos.mesh.teleport.admission-discovery',\n new CredentialRetrieverExtension(\n { spaceKey: params.spaceKey, memberKey: params.identityKey },\n onCredentialResolved,\n ),\n );\n },\n onAuthFailure: (session: Teleport) => session.close(),\n blobStore: this._blobStore,\n disableP2pReplication: this._disableP2pReplication,\n });\n\n try {\n await protocol.start(ctx);\n const credential = await onCredentialResolved.wait({ timeout: params.timeout });\n return credential;\n } catch (err: any) {\n throw err;\n } finally {\n await protocol.stop(ctx);\n }\n }\n\n public findSpaceByRootDocumentId(documentId: string): Space | undefined {\n return [...this._spaces.values()].find((space) => {\n return space.spaceState.credentials.some((credential) => {\n const assertion = getCredentialAssertion(credential);\n if (assertion['@type'] !== 'dxos.halo.credentials.Epoch') {\n return false;\n }\n if (!assertion?.automergeRoot) {\n return false;\n }\n return parseAutomergeUrl(assertion.automergeRoot as AutomergeUrl).documentId === documentId;\n });\n });\n }\n}\n\nexport type SpaceManagerLayerOptions = Pick<SpaceManagerProps, 'disableP2pReplication'>;\n\n/**\n * Effect Layer constructing a {@link SpaceManager} from ambient service dependencies.\n */\nexport const SpaceManagerLayer = (\n options: SpaceManagerLayerOptions = {},\n): Layer.Layer<\n SpaceManagerService,\n never,\n FeedStoreService | SwarmNetworkManagerService | IMetadataStoreService | BlobStoreApiService\n> =>\n Layer.effect(\n SpaceManagerService,\n Effect.gen(function* () {\n const feedStore = yield* FeedStoreService;\n const networkManager = yield* SwarmNetworkManagerService;\n const metadataStore = yield* IMetadataStoreService;\n const blobStore = yield* BlobStoreApiService;\n return new SpaceManager({\n feedStore,\n networkManager,\n metadataStore,\n blobStore,\n disableP2pReplication: options.disableP2pReplication,\n });\n }),\n );\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Context, Resource } from '@dxos/context';\nimport { type CredentialProcessor, type SpecificCredential, checkCredentialType } from '@dxos/credentials';\nimport { type Credential, type Epoch } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nexport class AutomergeSpaceState extends Resource implements CredentialProcessor {\n public rootUrl: string | undefined = undefined;\n public lastEpoch: SpecificCredential<Epoch> | undefined = undefined;\n\n public readonly onNewEpoch = new Event<SpecificCredential<Epoch>>();\n\n private _isProcessingRootDocs = false;\n\n constructor(private readonly _onNewRoot: (rootUrl: string) => void) {\n super();\n }\n\n protected override async _open(ctx: Context): Promise<void> {}\n\n protected override async _close(ctx: Context): Promise<void> {\n this._isProcessingRootDocs = false;\n }\n\n async processCredential(credential: Credential): Promise<void> {\n if (!checkCredentialType(credential, 'dxos.halo.credentials.Epoch')) {\n return;\n }\n\n this.lastEpoch = credential;\n if (credential.subject.assertion.automergeRoot) {\n this.rootUrl = credential.subject.assertion.automergeRoot;\n\n if (this._isProcessingRootDocs) {\n this._onNewRoot(this.rootUrl);\n }\n }\n\n this.onNewEpoch.emit(credential);\n }\n\n startProcessingRootDocs(): void {\n if (this._isProcessingRootDocs) {\n return;\n }\n\n if (this.rootUrl) {\n this._onNewRoot(this.rootUrl);\n }\n this._isProcessingRootDocs = true;\n }\n\n async ensureEpochInitialized(): Promise<void> {\n await this.onNewEpoch.waitForCondition(() => !!this.lastEpoch);\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { decode as decodeCbor, encode as encodeCbor } from 'cbor-x';\n\nimport { Event, Mutex, scheduleMicroTask } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { EdgeConnectionClosedError, EdgeIdentityChangedError } from '@dxos/edge-client';\nimport { type FeedWrapper } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey, type SpaceId } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport { EdgeService } from '@dxos/protocols';\nimport { buf } from '@dxos/protocols/buf';\nimport {\n type Message as RouterMessage,\n MessageSchema as RouterMessageSchema,\n} from '@dxos/protocols/buf/dxos/edge/messenger_pb';\nimport type { FeedBlock, ProtocolMessage } from '@dxos/protocols/feed-replication';\nimport { EdgeStatus } from '@dxos/protocols/proto/dxos/client/services';\nimport { ComplexMap, arrayToBuffer, bufferToArray, defaultMap, rangeFromTo } from '@dxos/util';\n\nexport type EdgeFeedReplicatorProps = {\n messenger: EdgeConnection;\n spaceId: SpaceId;\n};\n\nexport class EdgeFeedReplicator extends Resource {\n private readonly _messenger: EdgeConnection;\n\n @logInfo\n private readonly _spaceId: SpaceId;\n\n private readonly _feeds = new ComplexMap<PublicKey, FeedWrapper<any>>(PublicKey.hash);\n\n private _connectionCtx?: Context = undefined;\n private _connected = false;\n /**\n * Feed length at service.\n */\n private _remoteLength = new ComplexMap<PublicKey, number>(PublicKey.hash);\n\n /**\n * Protects against concurrent pushes so that remote length is updated consistently.\n */\n private _pushMutex = new ComplexMap<PublicKey, Mutex>(PublicKey.hash);\n\n constructor({ messenger, spaceId }: EdgeFeedReplicatorProps) {\n super();\n this._messenger = messenger;\n this._spaceId = spaceId;\n }\n\n protected override async _open(): Promise<void> {\n log('open');\n // TODO: handle reconnects\n this._ctx.onDispose(\n this._messenger.onMessage((message: RouterMessage) => {\n if (!message.serviceId) {\n return;\n }\n const [service, ...rest] = message.serviceId.split(':');\n if (service !== EdgeService.FEED_REPLICATOR) {\n return;\n }\n\n const [spaceId] = rest;\n if (spaceId !== this._spaceId) {\n log('spaceID mismatch', { spaceId, _spaceId: this._spaceId });\n return;\n }\n\n const payload = decodeCbor(message.payload!.value) as ProtocolMessage;\n log('receive', { from: message.source, feedKey: payload.feedKey, type: payload.type });\n this._onMessage(payload);\n }),\n );\n\n this._ctx.onDispose(\n this._messenger.onReconnected(() => {\n scheduleMicroTask(this._ctx, () => this._handleReconnect());\n }),\n );\n }\n\n private async _handleReconnect(): Promise<void> {\n await this._resetConnection();\n if (this._messenger.status.state === EdgeStatus.ConnectionState.CONNECTED) {\n this._startReplication();\n }\n }\n\n protected override async _close(): Promise<void> {\n log('close');\n await this._resetConnection();\n }\n\n private _startReplication(): void {\n this._connected = true;\n const connectionCtx = this._createConnectionContext();\n this._connectionCtx = connectionCtx;\n log('connection context created');\n scheduleMicroTask(connectionCtx, async () => {\n for (const feed of this._feeds.values()) {\n await this._replicateFeed(connectionCtx, feed);\n }\n });\n }\n\n private async _resetConnection(): Promise<void> {\n log('resetConnection');\n this._connected = false;\n await this._connectionCtx?.dispose();\n this._connectionCtx = undefined;\n this._remoteLength.clear();\n }\n\n async addFeed(feed: FeedWrapper<any>): Promise<void> {\n log('addFeed', { key: feed.key, connected: this._connected, hasConnectionCtx: !!this._connectionCtx });\n this._feeds.set(feed.key, feed);\n\n if (this._connected && this._connectionCtx) {\n await this._replicateFeed(this._connectionCtx, feed);\n }\n }\n\n private _getPushMutex(key: PublicKey): Mutex {\n return defaultMap(this._pushMutex, key, () => new Mutex());\n }\n\n private async _replicateFeed(ctx: Context, feed: FeedWrapper<any>): Promise<void> {\n log('replicateFeed', { key: feed.key });\n await this._sendMessage(ctx, {\n type: 'get-metadata',\n feedKey: feed.key.toHex(),\n });\n\n Event.wrap(feed.core as any, 'append').on(ctx, async () => {\n await this._pushBlocksIfNeeded(feed);\n });\n }\n\n private async _sendMessage(ctx: Context, message: ProtocolMessage): Promise<void> {\n if (!this._connectionCtx) {\n log('message dropped because connection was disposed');\n return;\n }\n\n if (message.type === 'data') {\n log('sending blocks', {\n feedKey: message.feedKey,\n blocks: message.blocks.map((b) => b.index),\n });\n }\n\n invariant(message.feedKey);\n const payloadValue = bufferToArray(encodeCbor(message));\n\n log('send', { type: message.type });\n await this._messenger.send(\n ctx,\n buf.create(RouterMessageSchema, {\n source: {\n identityDid: this._messenger.identityDid,\n peerKey: this._messenger.peerKey,\n },\n serviceId: `${EdgeService.FEED_REPLICATOR}:${this._spaceId}`,\n payload: { value: payloadValue },\n }),\n );\n }\n\n private _onMessage(message: ProtocolMessage): void {\n if (!this._connectionCtx) {\n log.warn('received message after connection context was disposed');\n return;\n }\n scheduleMicroTask(this._connectionCtx, async () => {\n switch (message.type) {\n case 'metadata': {\n const feedKey = PublicKey.fromHex(message.feedKey);\n const feed = this._feeds.get(feedKey);\n if (!feed) {\n log.warn('Feed not found', { feedKey });\n return;\n }\n\n using _guard = await this._getPushMutex(feed.key).acquire();\n\n this._remoteLength.set(feedKey, message.length);\n\n const logMeta = { localLength: feed.length, remoteLength: message.length, feedKey };\n if (message.length > feed.length) {\n log('requesting missing blocks', logMeta);\n\n await this._sendMessage(this._connectionCtx!, {\n type: 'request',\n feedKey: feedKey.toHex(),\n range: { from: feed.length, to: message.length },\n });\n } else if (message.length < feed.length) {\n log('pushing blocks to remote', logMeta);\n\n await this._pushBlocks(this._connectionCtx!, feed, message.length, feed.length);\n }\n\n break;\n }\n\n case 'data': {\n log('received data', { feed: message.feedKey, blocks: message.blocks.map((b) => b.index) });\n\n const feedKey = PublicKey.fromHex(message.feedKey);\n const feed = this._feeds.get(feedKey);\n if (!feed) {\n log.warn('Feed not found', { feedKey });\n return;\n }\n\n await this._integrateBlocks(feed, message.blocks);\n break;\n }\n\n default: {\n log.warn('Unknown message', { ...message });\n }\n }\n });\n }\n\n private async _pushBlocks(ctx: Context, feed: FeedWrapper<any>, from: number, to: number): Promise<void> {\n log('pushing blocks', { feed: feed.key.toHex(), from, to });\n\n const blocks: FeedBlock[] = await Promise.all(\n rangeFromTo(from, to).map(async (index) => {\n const data = await feed.get(index, { valueEncoding: 'binary' });\n invariant(data instanceof Uint8Array);\n const proof = await feed.proof(index);\n\n return {\n index,\n data,\n nodes: proof.nodes,\n signature: proof.signature,\n } satisfies FeedBlock;\n }),\n );\n\n await this._sendMessage(ctx, {\n type: 'data',\n feedKey: feed.key.toHex(),\n blocks,\n });\n this._remoteLength.set(feed.key, to);\n }\n\n private async _integrateBlocks(feed: FeedWrapper<any>, blocks: FeedBlock[]): Promise<void> {\n log('integrating blocks', { feed: feed.key.toHex(), blocks: blocks.length });\n\n for (const block of blocks) {\n if (feed.has(block.index)) {\n continue;\n }\n const blockBuffer = bufferizeBlock(block);\n\n await feed.putBuffer(\n block.index,\n blockBuffer.data,\n { nodes: blockBuffer.nodes, signature: blockBuffer.signature },\n null,\n );\n }\n }\n\n private async _pushBlocksIfNeeded(feed: FeedWrapper<any>): Promise<void> {\n using _ = await this._getPushMutex(feed.key).acquire();\n\n if (!this._remoteLength.has(feed.key)) {\n log('blocks not pushed because remote length is unknown');\n return;\n }\n\n const remoteLength = this._remoteLength.get(feed.key)!;\n if (remoteLength < feed.length) {\n await this._pushBlocks(this._connectionCtx!, feed, remoteLength, feed.length);\n }\n }\n\n private _createConnectionContext(): Context {\n const connectionCtx = new Context({\n parent: this._ctx,\n onError: async (err: any) => {\n if (connectionCtx !== this._connectionCtx) {\n return;\n }\n if (err instanceof EdgeIdentityChangedError || err instanceof EdgeConnectionClosedError) {\n log('resetting on reconnect');\n await this._resetConnection();\n } else {\n this._ctx.raise(err);\n }\n },\n });\n return connectionCtx;\n }\n}\n\n// hypercore requires buffers\nconst bufferizeBlock = (block: FeedBlock) => ({\n index: block.index,\n data: arrayToBuffer(block.data),\n nodes: block.nodes.map((node) => ({\n index: node.index,\n hash: arrayToBuffer(node.hash),\n size: node.size,\n })),\n signature: arrayToBuffer(block.signature),\n});\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport type { AutomergeUrl } from '@automerge/automerge-repo';\n\nimport { type Context } from '@dxos/context';\nimport { type EchoHost } from '@dxos/echo-host';\nimport { invariant } from '@dxos/invariant';\nimport type { PublicKey, SpaceId } from '@dxos/keys';\nimport { CreateEpochRequest } from '@dxos/protocols/proto/dxos/client/services';\n\nexport type MigrationContext = {\n echoHost: EchoHost;\n\n spaceId: SpaceId;\n /**\n * @deprecated Remove.\n */\n spaceKey: PublicKey;\n migration: CreateEpochRequest.Migration;\n currentRoot: string | null;\n\n /**\n * For set automerge root migration type.\n */\n newAutomergeRoot?: string;\n};\n\nexport type MigrationResult = {\n newRoot?: string;\n};\n\nconst LOAD_DOC_TIMEOUT = 10_000;\n\nexport const runEpochMigration = async (ctx: Context, context: MigrationContext): Promise<MigrationResult> => {\n switch (context.migration) {\n case CreateEpochRequest.Migration.INIT_AUTOMERGE: {\n const document = await context.echoHost.createDoc();\n await context.echoHost.flush(ctx);\n return { newRoot: document.url };\n }\n case CreateEpochRequest.Migration.PRUNE_AUTOMERGE_ROOT_HISTORY: {\n if (!context.currentRoot) {\n throw new Error('Space does not have an automerge root');\n }\n const rootHandle = await context.echoHost.loadDoc(ctx, context.currentRoot as AutomergeUrl, {\n timeout: LOAD_DOC_TIMEOUT,\n });\n invariant(rootHandle, 'Automerge root document must load for history prune migration.');\n\n const newRoot = await context.echoHost.createDoc(rootHandle.doc());\n await context.echoHost.flush(ctx);\n return { newRoot: newRoot.url };\n }\n case CreateEpochRequest.Migration.FRAGMENT_AUTOMERGE_ROOT: {\n throw new Error('Migration not available');\n }\n case CreateEpochRequest.Migration.MIGRATE_REFERENCES_TO_DXN: {\n throw new Error('Migration not available');\n }\n // TODO(dmaretskyi): This path doesn't seem to fit here. This is not a migration.\n case CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT: {\n invariant(context.newAutomergeRoot);\n\n // Defensive programming - it should be the responsibility of the caller to flush the new root.\n await context.echoHost.flush(ctx);\n return {\n newRoot: context.newAutomergeRoot,\n };\n }\n }\n\n return {};\n};\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport { DeferredTask, Event, TimeoutError, Trigger, scheduleMicroTask, scheduleTask, sleep } from '@dxos/async';\nimport { type Context, Resource, rejectOnDispose } from '@dxos/context';\nimport { type CredentialProcessor, verifyCredential } from '@dxos/credentials';\nimport { type EdgeHttpClient } from '@dxos/edge-client';\nimport { type FeedWriter } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { type SpaceId } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport { EdgeCallFailedError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type NotarizationService, type NotarizeRequest } from '@dxos/protocols/proto/dxos/mesh/teleport/notarization';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\nimport { ComplexMap, ComplexSet, entry } from '@dxos/util';\n\nconst DEFAULT_RETRY_TIMEOUT = 1_000;\n\nconst DEFAULT_SUCCESS_DELAY = 1_000;\n\nconst DEFAULT_NOTARIZE_TIMEOUT = 10_000;\n\nconst DEFAULT_ACTIVE_EDGE_POLLING_INTERVAL = 3_000;\n\nconst MAX_EDGE_RETRIES = 2;\n\nconst WRITER_NOT_SET_ERROR_CODE = 'WRITER_NOT_SET';\n\nconst credentialCodec = schema.getCodecForType('dxos.halo.credentials.Credential');\n\nexport type NotarizationPluginProps = {\n spaceId: SpaceId;\n edgeClient?: EdgeHttpClient;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n activeEdgePollingInterval?: number;\n};\n\nexport type NotarizeProps = {\n /**\n * For cancellation.\n */\n ctx?: Context;\n\n /**\n * Credentials to notarize.\n */\n credentials: Credential[];\n\n /**\n * Timeout for the whole notarization process.\n * Set to 0 to disable.\n * @default {@link DEFAULT_NOTARIZE_TIMEOUT}\n */\n timeout?: number;\n\n /**\n * Retry timeout.\n * @default {@link DEFAULT_RETRY_TIMEOUT}\n */\n retryTimeout?: number;\n\n /**\n * Minimum wait time after a peer confirms successful notarization before attempting with a new peer.\n * This is to avoid spamming peers with notarization requests.\n * @default {@link DEFAULT_SUCCESS_DELAY}\n */\n successDelay?: number;\n\n /**\n * A random amount of time before making or retrying an edge request to help prevent large bursts of requests.\n */\n edgeRetryJitter?: number;\n};\n\n/**\n * See NotarizationService proto.\n */\nexport class NotarizationPlugin extends Resource implements CredentialProcessor {\n private readonly _extensionOpened = new Event();\n\n private _writer: FeedWriter<Credential> | undefined;\n private readonly _extensions = new Set<NotarizationTeleportExtension>();\n private readonly _processedCredentials = new ComplexSet<PublicKey>(PublicKey.hash);\n private readonly _processCredentialsTriggers = new ComplexMap<PublicKey, Trigger>(PublicKey.hash);\n\n private _activeEdgePollingIntervalHandle: any | undefined = undefined;\n private readonly _activeEdgePollingInterval: number;\n private _activeEdgePollingEnabled = false;\n\n @logInfo\n private readonly _spaceId: SpaceId;\n\n private readonly _edgeClient: EdgeHttpClient | undefined;\n\n constructor(params: NotarizationPluginProps) {\n super();\n this._spaceId = params.spaceId;\n this._activeEdgePollingInterval = params.activeEdgePollingInterval ?? DEFAULT_ACTIVE_EDGE_POLLING_INTERVAL;\n if (params.edgeClient && params.edgeFeatures?.feedReplicator) {\n this._edgeClient = params.edgeClient;\n }\n }\n\n setActiveEdgePollingEnabled(enabled: boolean): void {\n const client = this._edgeClient;\n invariant(client);\n this._activeEdgePollingEnabled = enabled;\n if (this.isOpen) {\n if (enabled && !this._activeEdgePollingIntervalHandle) {\n this._startPeriodicEdgePolling(client);\n } else if (!enabled && this._activeEdgePollingIntervalHandle) {\n this._stopPeriodicEdgePolling();\n }\n }\n }\n\n get hasWriter() {\n return !!this._writer;\n }\n\n protected override async _open(): Promise<void> {\n if (this._edgeClient) {\n if (this._activeEdgePollingEnabled) {\n this._startPeriodicEdgePolling(this._edgeClient);\n }\n if (this._writer) {\n this._notarizePendingEdgeCredentials(this._edgeClient, this._writer);\n }\n }\n }\n\n protected override async _close(): Promise<void> {\n this._stopPeriodicEdgePolling();\n await this._ctx.dispose();\n }\n\n /**\n * Request credentials to be notarized.\n */\n async notarize({\n ctx: opCtx,\n credentials,\n timeout = DEFAULT_NOTARIZE_TIMEOUT,\n retryTimeout = DEFAULT_RETRY_TIMEOUT,\n successDelay = DEFAULT_SUCCESS_DELAY,\n edgeRetryJitter,\n }: NotarizeProps): Promise<void> {\n log('notarize', { credentials });\n invariant(\n credentials.every((credential) => credential.id),\n 'Credentials must have an id',\n );\n\n const errors = new Trigger();\n const ctx = this._ctx.derive({\n onError: (err) => {\n log.warn('Notarization error', { err });\n void ctx.dispose();\n errors.throw(err);\n },\n });\n opCtx?.onDispose(() => ctx.dispose());\n\n if (timeout !== 0) {\n this._scheduleTimeout(ctx, errors, timeout);\n }\n\n const allNotarized = Promise.all(credentials.map((credential) => this._waitUntilProcessed(credential.id!)));\n\n this._tryNotarizeCredentialsWithPeers(ctx, credentials, { retryTimeout, successDelay });\n\n if (this._edgeClient) {\n this._tryNotarizeCredentialsWithEdge(ctx, this._edgeClient, credentials, {\n retryTimeout,\n successDelay,\n jitter: edgeRetryJitter,\n });\n }\n\n try {\n await Promise.race([rejectOnDispose(ctx), allNotarized, errors.wait()]);\n log('done');\n } finally {\n await ctx.dispose();\n }\n }\n\n private _tryNotarizeCredentialsWithPeers(\n ctx: Context,\n credentials: Credential[],\n { retryTimeout, successDelay }: NotarizationTimeouts,\n ): void {\n const peersTried = new Set<NotarizationTeleportExtension>();\n\n // Repeatable task that tries to notarize credentials with one of the available peers.\n const notarizeTask = new DeferredTask(ctx, async () => {\n try {\n if (this._extensions.size === 0) {\n return; // No peers to try.\n }\n\n // Pick a peer that we haven't tried yet.\n const peer = [...this._extensions].find((peer) => !peersTried.has(peer));\n if (!peer) {\n log.info('Exhausted all peers to notarize with', { retryIn: retryTimeout });\n peersTried.clear();\n scheduleTask(ctx, () => notarizeTask.schedule(), retryTimeout); // retry with all peers again\n return;\n }\n\n peersTried.add(peer);\n log('try notarizing', { peer: peer.localPeerId, credentialId: credentials.map((credential) => credential.id) });\n await peer.rpc.NotarizationService.notarize({\n credentials: credentials.filter((credential) => !this._processedCredentials.has(credential.id!)),\n });\n log('success');\n\n await sleep(successDelay); // wait before trying with a new peer\n } catch (err: any) {\n if (!ctx.disposed && !err.message.includes(WRITER_NOT_SET_ERROR_CODE)) {\n log.info('error notarizing (recoverable)', err);\n }\n notarizeTask.schedule(); // retry immediately with next peer\n }\n });\n\n notarizeTask.schedule();\n this._extensionOpened.on(ctx, () => notarizeTask.schedule());\n }\n\n private _tryNotarizeCredentialsWithEdge(\n ctx: Context,\n client: EdgeHttpClient,\n credentials: Credential[],\n timeouts: NotarizationTimeouts & { jitter?: number },\n ): void {\n const encodedCredentials = credentials.map((credential) => {\n const binary = credentialCodec.encode(credential);\n return Buffer.from(binary).toString('base64');\n });\n scheduleTask(ctx, async () => {\n try {\n await client.notarizeCredentials(\n ctx,\n this._spaceId,\n { credentials: encodedCredentials },\n { retry: { count: MAX_EDGE_RETRIES, timeout: timeouts.retryTimeout, jitter: timeouts.jitter } },\n );\n\n log('edge notarization success');\n } catch (error: any) {\n handleEdgeError(error);\n }\n });\n }\n\n /**\n * Called with credentials arriving from the control pipeline.\n */\n async processCredential(credential: Credential): Promise<void> {\n if (!credential.id) {\n return;\n }\n this._processCredentialsTriggers.get(credential.id)?.wake();\n this._processedCredentials.add(credential.id);\n this._processCredentialsTriggers.delete(credential.id);\n }\n\n setWriter(writer: FeedWriter<Credential>): void {\n invariant(!this._writer, 'Writer already set.');\n this._writer = writer;\n if (this._edgeClient && this.isOpen) {\n this._notarizePendingEdgeCredentials(this._edgeClient, writer);\n }\n }\n\n private _startPeriodicEdgePolling(client: EdgeHttpClient): void {\n this._activeEdgePollingIntervalHandle = setInterval(() => {\n if (this._writer) {\n this._notarizePendingEdgeCredentials(client, this._writer);\n }\n }, this._activeEdgePollingInterval);\n }\n\n private _stopPeriodicEdgePolling(): void {\n if (this._activeEdgePollingIntervalHandle) {\n clearInterval(this._activeEdgePollingIntervalHandle);\n this._activeEdgePollingIntervalHandle = undefined;\n }\n }\n\n /**\n * The method is used only for adding agent feeds to spaces.\n * When an agent is created we can admit them into all the existing spaces. In case the operation fails\n * this method will fix it on the next space open.\n * Given how rarely this happens there's no need to poll the endpoint.\n */\n private _notarizePendingEdgeCredentials(client: EdgeHttpClient, writer: FeedWriter<Credential>): void {\n scheduleMicroTask(this._ctx, async () => {\n try {\n const response = await client.getCredentialsForNotarization(this._ctx, this._spaceId, {\n retry: { count: MAX_EDGE_RETRIES },\n });\n\n const credentials = response.awaitingNotarization.credentials;\n if (!credentials.length) {\n log('edge did not return credentials for notarization');\n return;\n }\n\n log('got edge credentials for notarization', { count: credentials.length });\n\n const decodedCredentials = credentials.map((credential) => {\n const binary = Buffer.from(credential, 'base64');\n return credentialCodec.decode(binary);\n });\n\n await this._notarizeCredentials(writer, decodedCredentials);\n\n log.info('notarized edge credentials', { count: decodedCredentials.length });\n } catch (error: any) {\n handleEdgeError(error);\n }\n });\n }\n\n private async _waitUntilProcessed(id: PublicKey): Promise<void> {\n if (this._processedCredentials.has(id)) {\n return;\n }\n await entry(this._processCredentialsTriggers, id).orInsert(new Trigger()).value.wait();\n }\n\n /**\n * Requests from other peers to notarize credentials.\n */\n private async _onNotarize(request: NotarizeRequest): Promise<void> {\n if (!this._writer) {\n throw new Error(WRITER_NOT_SET_ERROR_CODE);\n }\n await this._notarizeCredentials(this._writer, request.credentials ?? []);\n }\n\n private async _notarizeCredentials(writer: FeedWriter<Credential>, credentials: Credential[]): Promise<void> {\n for (const credential of credentials) {\n invariant(credential.id, 'Credential must have an id');\n if (this._processedCredentials.has(credential.id)) {\n continue;\n }\n const verificationResult = await verifyCredential(credential);\n if (verificationResult.kind === 'fail') {\n throw new Error(`Credential verification failed: ${verificationResult.errors.join('\\n')}.`);\n }\n await writer.write(credential);\n }\n }\n\n createExtension(): NotarizationTeleportExtension {\n const extension = new NotarizationTeleportExtension({\n onOpen: async () => {\n log('extension opened', { peer: extension.localPeerId });\n this._extensions.add(extension);\n this._extensionOpened.emit();\n },\n onClose: async () => {\n log('extension closed', { peer: extension.localPeerId });\n this._extensions.delete(extension);\n },\n onNotarize: this._onNotarize.bind(this),\n });\n return extension;\n }\n\n private _scheduleTimeout(ctx: Context, errors: Trigger, timeout: number): void {\n scheduleTask(\n ctx,\n () => {\n log.warn('Notarization timeout', {\n timeout,\n peers: Array.from(this._extensions).map((extension) => extension.remotePeerId),\n });\n void ctx.dispose();\n errors.throw(new TimeoutError(timeout, 'Notarization timed out'));\n },\n timeout,\n );\n }\n}\n\nconst handleEdgeError = (error: any) => {\n if (!(error instanceof EdgeCallFailedError) || error.data) {\n log.catch(error);\n } else {\n log.info('Edge notarization failure', { message: error.message });\n }\n};\n\nexport type NotarizationTeleportExtensionProps = {\n onOpen: () => Promise<void>;\n onClose: () => Promise<void>;\n onNotarize: (request: NotarizeRequest) => Promise<void>;\n};\n\nexport class NotarizationTeleportExtension extends RpcExtension<Services, Services> {\n constructor(private readonly _params: NotarizationTeleportExtensionProps) {\n super({\n requested: {\n NotarizationService: schema.getService('dxos.mesh.teleport.notarization.NotarizationService'),\n },\n exposed: {\n NotarizationService: schema.getService('dxos.mesh.teleport.notarization.NotarizationService'),\n },\n });\n }\n\n protected async getHandlers(): Promise<Services> {\n return {\n NotarizationService: {\n notarize: async (request) => {\n await this._params.onNotarize(request);\n },\n },\n };\n }\n\n override async onOpen(ctx: ExtensionContext): Promise<void> {\n await super.onOpen(ctx);\n await this._params.onOpen();\n }\n\n override async onClose(err?: Error | undefined): Promise<void> {\n await this._params.onClose();\n await super.onClose(err);\n }\n}\n\ntype NotarizationTimeouts = {\n retryTimeout: number;\n successDelay: number;\n};\n\ntype Services = {\n NotarizationService: NotarizationService;\n};\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { save } from '@automerge/automerge';\nimport { type AutomergeUrl, type DocHandle } from '@automerge/automerge-repo';\n\nimport { Event, Mutex, scheduleTask, sleep, synchronized, trackLeaks } from '@dxos/async';\nimport { AUTH_TIMEOUT } from '@dxos/client-protocol';\nimport { Context, ContextDisposedError, cancelWithContext } from '@dxos/context';\nimport type { SpecificCredential } from '@dxos/credentials';\nimport { timed, warnAfterTimeout } from '@dxos/debug';\nimport { type DatabaseRoot, type EchoHost } from '@dxos/echo-host';\nimport { type DatabaseDirectory, SpaceDocVersion } from '@dxos/echo-protocol';\nimport type { EdgeConnection, EdgeHttpClient } from '@dxos/edge-client';\nimport { type FeedStore, type FeedWrapper } from '@dxos/feed-store';\nimport { failedInvariant, invariant } from '@dxos/invariant';\nimport { type KeyringApi } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { CancelledError, type FeedProtocol, SystemError } from '@dxos/protocols';\nimport {\n type CreateEpochRequest,\n type Space as SpaceProto,\n SpaceState,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type SpaceCache } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport {\n AdmittedFeed,\n type Credential,\n type Epoch,\n MembershipPolicy,\n type ProfileDocument,\n SpaceMember,\n} from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type GossipMessage } from '@dxos/protocols/proto/dxos/mesh/teleport/gossip';\nimport { type Gossip, type Presence } from '@dxos/teleport-extension-gossip';\nimport { Timeframe } from '@dxos/timeframe';\nimport { trace } from '@dxos/tracing';\nimport { type AsyncCallback, CallbackCollection, ComplexSet } from '@dxos/util';\n\nimport { TrustedKeySetAuthVerifier } from '../identity';\nimport { type IMetadataStore } from '../metadata';\nimport { createMappedFeedWriter } from '../pipeline';\nimport { type Space } from '../space';\nimport { AutomergeSpaceState } from './automerge-space-state';\nimport { type SigningContext } from './data-space-manager';\nimport { EdgeFeedReplicator } from './edge-feed-replicator';\nimport { runEpochMigration } from './epoch-migrations';\nimport { NotarizationPlugin } from './notarization-plugin';\n\nexport type DataSpaceCallbacks = {\n /**\n * Called before transitioning to the ready state.\n */\n beforeReady?: () => Promise<void>;\n\n /**\n * Called after transitioning to the ready state.\n */\n afterReady?: () => Promise<void>;\n\n /**\n * Called before space gets closed.\n */\n beforeClose?: () => Promise<void>;\n};\n\nexport type DataSpaceProps = {\n initialState: SpaceState;\n inner: Space;\n metadataStore: IMetadataStore;\n gossip: Gossip;\n presence: Presence;\n keyring: KeyringApi;\n feedStore: FeedStore<FeedMessage>;\n echoHost: EchoHost;\n signingContext: SigningContext;\n callbacks?: DataSpaceCallbacks;\n cache?: SpaceCache;\n tags?: string[];\n edgeConnection?: EdgeConnection;\n edgeHttpClient?: EdgeHttpClient;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n activeEdgeNotarizationPollingInterval?: number;\n};\n\nexport type CreateEpochOptions = {\n migration?: CreateEpochRequest.Migration;\n newAutomergeRoot?: string;\n};\n\n@trackLeaks('open', 'close')\nexport class DataSpace {\n private _ctx = new Context();\n private readonly _inner: Space;\n\n private readonly _gossip: Gossip;\n private readonly _presence: Presence;\n private readonly _keyring: KeyringApi;\n private readonly _feedStore: FeedStore<FeedMessage>;\n private readonly _metadataStore: IMetadataStore;\n private readonly _signingContext: SigningContext;\n private readonly _notarizationPlugin: NotarizationPlugin;\n private readonly _callbacks: DataSpaceCallbacks;\n private readonly _cache?: SpaceCache = undefined;\n private readonly _echoHost: EchoHost;\n private readonly _edgeFeedReplicator?: EdgeFeedReplicator = undefined;\n\n // TODO(dmaretskyi): Move into Space?\n private readonly _automergeSpaceState = new AutomergeSpaceState((rootUrl) => this._onNewAutomergeRoot(rootUrl));\n\n private readonly _epochProcessingMutex = new Mutex();\n\n private _state = SpaceState.SPACE_CLOSED;\n\n /** Immutable tags from space metadata, available immediately. */\n readonly tags: string[];\n\n private _databaseRoot: DatabaseRoot | null = null;\n\n /**\n * Error for _state === SpaceState.SPACE_ERROR.\n */\n public error: Error | undefined = undefined;\n\n public readonly authVerifier: TrustedKeySetAuthVerifier;\n public readonly stateUpdate = new Event();\n\n public readonly postOpen = new CallbackCollection<AsyncCallback<void>>();\n public readonly preClose = new CallbackCollection<AsyncCallback<void>>();\n\n public metrics: SpaceProto.Metrics = {};\n\n constructor(params: DataSpaceProps) {\n this._inner = params.inner;\n this._inner.stateUpdate.on(this._ctx, () => this.stateUpdate.emit());\n\n this._gossip = params.gossip;\n this._presence = params.presence;\n this._keyring = params.keyring;\n this._feedStore = params.feedStore;\n this._metadataStore = params.metadataStore;\n this._signingContext = params.signingContext;\n this._callbacks = params.callbacks ?? {};\n this._echoHost = params.echoHost;\n this._notarizationPlugin = new NotarizationPlugin({\n spaceId: this._inner.id,\n edgeClient: params.edgeHttpClient,\n edgeFeatures: params.edgeFeatures,\n activeEdgePollingInterval: params.activeEdgeNotarizationPollingInterval,\n });\n\n this.authVerifier = new TrustedKeySetAuthVerifier({\n trustedKeysProvider: () =>\n new ComplexSet(\n PublicKey.hash,\n Array.from(this._inner.spaceState.members.values())\n .filter((member) => member.role !== SpaceMember.Role.REMOVED)\n .map((member) => member.key),\n ),\n update: this._inner.stateUpdate,\n authTimeout: AUTH_TIMEOUT,\n });\n\n this._cache = params.cache;\n this.tags = params.tags ?? [];\n\n if (params.edgeConnection && params.edgeFeatures?.feedReplicator) {\n this._edgeFeedReplicator = new EdgeFeedReplicator({ messenger: params.edgeConnection, spaceId: this.id });\n }\n\n this._state = params.initialState;\n log('new state', { state: SpaceState[this._state] });\n }\n\n get id() {\n return this._inner.id;\n }\n\n get key() {\n return this._inner.key;\n }\n\n get isOpen() {\n return this._inner.isOpen;\n }\n\n get state(): SpaceState {\n return this._state;\n }\n\n // TODO(burdon): Can we mark this for debugging only?\n get inner() {\n return this._inner;\n }\n\n get presence() {\n return this._presence;\n }\n\n get notarizationPlugin() {\n return this._notarizationPlugin;\n }\n\n get cache() {\n return this._cache;\n }\n\n /** Membership policy from the genesis credential, defaults to INVITE. */\n get membershipPolicy(): MembershipPolicy {\n return this._inner.spaceState.genesisCredential ? this._inner.spaceState.membershipPolicy : MembershipPolicy.INVITE;\n }\n\n get automergeSpaceState() {\n return this._automergeSpaceState;\n }\n\n get databaseRoot(): DatabaseRoot | null {\n return this._databaseRoot;\n }\n\n private get _automergeInfo() {\n return {\n rootUrl: this._automergeSpaceState.rootUrl,\n lastEpoch: this._automergeSpaceState.lastEpoch,\n };\n }\n\n @synchronized\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n async open(ctx: Context): Promise<void> {\n if (this._state === SpaceState.SPACE_CLOSED) {\n await this._open(ctx);\n }\n }\n\n private async _open(ctx: Context): Promise<void> {\n await this._presence.open();\n await this._gossip.open();\n await this._notarizationPlugin.open();\n await this._inner.spaceState.addCredentialProcessor(this._notarizationPlugin);\n await this._automergeSpaceState.open();\n await this._inner.spaceState.addCredentialProcessor(this._automergeSpaceState);\n\n if (this._edgeFeedReplicator) {\n this.inner.protocol.feedAdded.append(this._onFeedAdded);\n }\n\n await this._inner.open(ctx);\n await this._inner.startProtocol(ctx);\n\n await this._edgeFeedReplicator?.open();\n\n this._state = SpaceState.SPACE_CONTROL_ONLY;\n log('new state', { state: SpaceState[this._state] });\n this.stateUpdate.emit();\n this.metrics = {};\n this.metrics.open = new Date();\n\n await this.postOpen.callSerial();\n }\n\n @synchronized\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n async close(ctx: Context): Promise<void> {\n await this._close(ctx);\n }\n\n private async _close(ctx: Context): Promise<void> {\n await this._callbacks.beforeClose?.();\n\n await this.preClose.callSerial();\n\n this._state = SpaceState.SPACE_CLOSED;\n log('new state', { state: SpaceState[this._state] });\n await this._ctx.dispose();\n this._ctx = new Context();\n\n if (this._edgeFeedReplicator) {\n this.inner.protocol.feedAdded.remove(this._onFeedAdded);\n }\n\n await this._edgeFeedReplicator?.close();\n\n await this.authVerifier.close();\n\n await this._inner.close(ctx);\n await this._inner.spaceState.removeCredentialProcessor(this._automergeSpaceState);\n await this._automergeSpaceState.close();\n await this._inner.spaceState.removeCredentialProcessor(this._notarizationPlugin);\n await this._notarizationPlugin.close();\n\n await this._presence.close();\n await this._gossip.close();\n }\n\n async postMessage(channel: string, message: any): Promise<void> {\n return this._gossip.postMessage(channel, message);\n }\n\n listen(channel: string, callback: (message: GossipMessage) => void): { unsubscribe: () => void } {\n return this._gossip.listen(channel, callback);\n }\n\n /**\n * Initialize the data pipeline in a separate task.\n * @param callerCtx - Trace context from the caller (e.g., activate or createSpace) for span parenting.\n */\n initializeDataPipelineAsync(callerCtx?: Context): void {\n const traceCtx = callerCtx ?? this._ctx;\n scheduleTask(this._ctx, async () => {\n try {\n this.metrics.pipelineInitBegin = new Date();\n await this.initializeDataPipeline(traceCtx);\n } catch (err) {\n if (err instanceof CancelledError || err instanceof ContextDisposedError) {\n log('data pipeline initialization cancelled', err);\n return;\n }\n\n log.error('Error initializing data pipeline', err);\n this._state = SpaceState.SPACE_ERROR;\n log('new state', { state: SpaceState[this._state] });\n this.error = err as Error;\n this.stateUpdate.emit();\n } finally {\n this.metrics.ready = new Date();\n }\n });\n }\n\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n async initializeDataPipeline(ctx: Context): Promise<void> {\n if (this._state !== SpaceState.SPACE_CONTROL_ONLY) {\n throw new SystemError({ message: 'Invalid operation' });\n }\n\n this._state = SpaceState.SPACE_INITIALIZING;\n log('new state', { state: SpaceState[this._state] });\n\n log('initializing control pipeline');\n await this._initializeAndReadControlPipeline(ctx);\n\n // Allow other tasks to run before loading the data pipeline.\n await sleep(1);\n\n const ready = this.stateUpdate.waitForCondition(() => this._state === SpaceState.SPACE_READY);\n\n log('initializing automerge root');\n const isPersisted = this._echoHost.spaces.some((s) => s.spaceId === this.id);\n if (isPersisted) {\n try {\n log('opening persisted space root', { spaceId: this.id });\n const root = await this._echoHost.openSpaceRoot(ctx, this.id);\n this._databaseRoot = root;\n if (root.getVersion() !== SpaceDocVersion.CURRENT) {\n this._state = SpaceState.SPACE_REQUIRES_MIGRATION;\n this.stateUpdate.emit();\n } else {\n await this._enterReadyState();\n }\n } catch (err) {\n log.warn('failed to open persisted space root, will wait for credentials', { spaceId: this.id, err });\n }\n }\n\n this._automergeSpaceState.startProcessingRootDocs();\n\n // TODO(dmaretskyi): Change so `initializeDataPipeline` doesn't wait for the space to be READY, but rather any state with a valid root.\n log('waiting for space to be ready');\n await ready;\n log('space is ready');\n }\n\n async *getAllDocuments(): AsyncIterable<[string, Uint8Array]> {\n invariant(this._databaseRoot, 'Space is not ready');\n const doc = this._databaseRoot.doc() ?? failedInvariant();\n const root = save(doc);\n yield [this._databaseRoot.documentId, root];\n\n for (const documentUrl of this._databaseRoot.getAllLinkedDocuments()) {\n const data = await this._echoHost.exportDoc(documentUrl);\n yield [documentUrl.replace(/^automerge:/, ''), data];\n }\n }\n\n /**\n * Get all feeds and their blocks for this space.\n * Used for space archive export.\n */\n async getAllFeeds(): Promise<Array<{ feedId: string; feedNamespace: string; blocks: FeedProtocol.Block[] }>> {\n return this._echoHost.getAllFeedsForSpace(this.id);\n }\n\n private async _enterReadyState(): Promise<void> {\n await this._callbacks.beforeReady?.();\n\n this._state = SpaceState.SPACE_READY;\n log('new state', { state: SpaceState[this._state] });\n this.stateUpdate.emit();\n\n await this._callbacks.afterReady?.();\n }\n\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n private async _initializeAndReadControlPipeline(ctx: Context): Promise<void> {\n await this._inner.controlPipeline.state.waitUntilReachedTargetTimeframe({\n ctx,\n timeout: 10_000,\n breakOnStall: false,\n });\n\n this.metrics.controlPipelineReady = new Date();\n\n await this._createWritableFeeds();\n log('writable feeds created');\n this.stateUpdate.emit();\n\n if (!this.notarizationPlugin.hasWriter) {\n this.notarizationPlugin.setWriter(\n createMappedFeedWriter<Credential, FeedMessage.Payload>(\n (credential) => ({\n credential: { credential },\n }),\n this._inner.controlPipeline.writer,\n ),\n );\n }\n }\n\n @timed(10_000)\n private async _createWritableFeeds(): Promise<void> {\n const credentials: Credential[] = [];\n if (!this.inner.controlFeedKey) {\n const controlFeed = await this._feedStore.openFeed(await this._keyring.createKey(), { writable: true });\n await this.inner.setControlFeed(controlFeed);\n\n credentials.push(\n await this._signingContext.credentialSigner.createCredential({\n subject: controlFeed.key,\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n 'spaceKey': this.key,\n 'deviceKey': this._signingContext.deviceKey,\n 'identityKey': this._signingContext.identityKey,\n 'designation': AdmittedFeed.Designation.CONTROL,\n },\n }),\n );\n }\n if (!this.inner.dataFeedKey) {\n const dataFeed = await this._feedStore.openFeed(await this._keyring.createKey(), {\n writable: true,\n sparse: true,\n });\n await this.inner.setDataFeed(dataFeed);\n\n credentials.push(\n await this._signingContext.credentialSigner.createCredential({\n subject: dataFeed.key,\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n 'spaceKey': this.key,\n 'deviceKey': this._signingContext.deviceKey,\n 'identityKey': this._signingContext.identityKey,\n 'designation': AdmittedFeed.Designation.DATA,\n },\n }),\n );\n }\n\n if (credentials.length > 0) {\n try {\n log('will notarize credentials for feed admission', { count: credentials.length });\n // Never times out\n await this.notarizationPlugin.notarize({ ctx: this._ctx, credentials, timeout: 0 });\n\n log('credentials notarized');\n } catch (err) {\n if (err instanceof ContextDisposedError) {\n return;\n }\n log.error('error notarizing credentials for feed admission', err);\n throw err;\n }\n\n // Set this after credentials are notarized so that on failure we will retry.\n await this._metadataStore.setWritableFeedKeys(this.key, this.inner.controlFeedKey!, this.inner.dataFeedKey!);\n }\n }\n\n private _onNewAutomergeRoot(rootUrl: string): void {\n log('loading automerge root doc for space', { space: this.key, rootUrl });\n\n let handle: DocHandle<DatabaseDirectory> | null = null;\n\n // TODO(dmaretskyi): Make this single-threaded (but doc loading should still be parallel to not block epoch processing).\n queueMicrotask(async () => {\n try {\n await warnAfterTimeout(5_000, 'Automerge root doc load timeout (DataSpace)', async () => {\n handle = await cancelWithContext(\n this._ctx,\n this._echoHost.loadDoc<DatabaseDirectory>(this._ctx, rootUrl as AutomergeUrl, {\n fetchFromNetwork: true,\n }),\n );\n });\n if (this._ctx.disposed) {\n return;\n }\n if (!handle) {\n log.warn('automerge root doc not available yet', { space: this.key, rootUrl });\n return;\n }\n\n // Ensure only one root is processed at a time.\n using _guard = await this._epochProcessingMutex.acquire();\n\n // Attaching space identifiers to legacy documents.\n const doc = handle.doc();\n if (!doc.access?.spaceId || !doc.access?.spaceKey) {\n handle.change((doc: DatabaseDirectory) => {\n doc.access ??= {};\n doc.access.spaceId ??= this.id;\n // spaceKey is deprecated but still written so older clients can resolve the owning space.\n doc.access.spaceKey ??= this.key.toHex();\n });\n }\n\n // TODO(dmaretskyi): Close roots.\n // TODO(dmaretskyi): How do we handle changing to the next EPOCH?\n const root = await this._echoHost.updateSpaceRoot(this._ctx, this.id, handle.url);\n\n // NOTE: Make sure this assignment happens synchronously together with the state change.\n this._databaseRoot = root;\n if (root.getVersion() !== SpaceDocVersion.CURRENT) {\n this._state = SpaceState.SPACE_REQUIRES_MIGRATION;\n this.stateUpdate.emit();\n } else if (this._state !== SpaceState.SPACE_READY) {\n await this._enterReadyState();\n } else {\n this.stateUpdate.emit();\n }\n } catch (err) {\n if (err instanceof ContextDisposedError) {\n return;\n }\n log.warn('error loading automerge root doc', { space: this.key, rootUrl, err });\n }\n });\n }\n\n // TODO(dmaretskyi): Use profile from signing context.\n async updateOwnProfile(profile: ProfileDocument): Promise<void> {\n const credential = await this._signingContext.credentialSigner.createCredential({\n subject: this._signingContext.identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.MemberProfile',\n profile,\n },\n });\n await this.inner.controlPipeline.writer.write({ credential: { credential } });\n }\n\n async createEpoch(options?: CreateEpochOptions): Promise<CreateEpochResult | null> {\n const ctx = this._ctx.derive();\n\n // Preserving existing behavior.\n if (!options?.migration) {\n return null;\n }\n\n const { newRoot } = await runEpochMigration(ctx, {\n echoHost: this._echoHost,\n spaceId: this.id,\n spaceKey: this.key,\n migration: options.migration,\n currentRoot: this._automergeSpaceState.rootUrl ?? null,\n newAutomergeRoot: options.newAutomergeRoot,\n });\n\n const epoch: Epoch = {\n previousId: this._automergeSpaceState.lastEpoch?.id,\n number: (this._automergeSpaceState.lastEpoch?.subject.assertion.number ?? -1) + 1,\n timeframe: this._automergeSpaceState.lastEpoch?.subject.assertion.timeframe ?? new Timeframe(),\n automergeRoot: newRoot ?? this._automergeSpaceState.rootUrl,\n };\n\n const credential = (await this._signingContext.credentialSigner.createCredential({\n subject: this.key,\n assertion: {\n '@type': 'dxos.halo.credentials.Epoch',\n ...epoch,\n },\n })) as SpecificCredential<Epoch>;\n\n const receipt = await this.inner.controlPipeline.writer.write({\n credential: { credential },\n });\n\n const timeframe = new Timeframe([[receipt.feedKey, receipt.seq]]);\n await this.inner.controlPipeline.state.waitUntilTimeframe(timeframe);\n await this._echoHost.updateIndexes();\n\n return { credential, timeframe };\n }\n\n @synchronized\n async activate(ctx: Context): Promise<void> {\n if (![SpaceState.SPACE_CLOSED, SpaceState.SPACE_INACTIVE].includes(this._state)) {\n return;\n }\n\n await this._metadataStore.setSpaceState(this.key, SpaceState.SPACE_ACTIVE);\n await this._open(ctx);\n this.initializeDataPipelineAsync(ctx);\n }\n\n @synchronized\n async deactivate(ctx: Context): Promise<void> {\n if (this._state === SpaceState.SPACE_INACTIVE) {\n return;\n }\n await this._metadataStore.setSpaceState(this.key, SpaceState.SPACE_INACTIVE);\n if (this._state !== SpaceState.SPACE_CLOSED) {\n await this._close(ctx);\n }\n this._state = SpaceState.SPACE_INACTIVE;\n log('new state', { state: SpaceState[this._state] });\n this.stateUpdate.emit();\n }\n\n /**\n * Tombstones (soft-deletes) the space by moving it to a terminal state.\n * This is intentionally separate from teardown: the caller is responsible for {@link close}-ing the\n * space (teardown uses the resource lifecycle, distinct from this state transition).\n * Terminal: {@link activate} will not re-open a deleted space. Data is not removed until garbage\n * collection (future work).\n */\n @synchronized\n async delete(): Promise<void> {\n if (this._state === SpaceState.SPACE_DELETED) {\n return;\n }\n await this._metadataStore.setSpaceState(this.key, SpaceState.SPACE_DELETED);\n this._state = SpaceState.SPACE_DELETED;\n log('new state', { state: SpaceState[this._state] });\n this.stateUpdate.emit();\n }\n\n getEdgeReplicationSetting() {\n return this._metadataStore.getSpaceEdgeReplicationSetting(this.key);\n }\n\n private _onFeedAdded = async (feed: FeedWrapper<any>) => {\n await this._edgeFeedReplicator!.addFeed(feed);\n };\n}\n\ntype CreateEpochResult = {\n credential: SpecificCredential<Epoch>;\n timeframe: Timeframe;\n};\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { createCredential } from '@dxos/credentials';\nimport { failUndefined } from '@dxos/debug';\nimport { type KeyringApi } from '@dxos/keyring';\nimport { AdmittedFeed, MembershipPolicy, SpaceMember } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { Timeframe } from '@dxos/timeframe';\n\nimport { type Space } from '../space';\nimport { type SigningContext } from './data-space-manager';\n\nexport const spaceGenesis = async (\n keyring: KeyringApi,\n signingContext: SigningContext,\n space: Space,\n automergeRoot?: string,\n tags?: string[],\n membershipPolicy?: MembershipPolicy,\n) => {\n // TODO(dmaretskyi): Find a way to reconcile with credential generator.\n const credentials = [\n await createCredential({\n signer: keyring,\n issuer: space.key,\n subject: space.key,\n assertion: {\n '@type': 'dxos.halo.credentials.SpaceGenesis',\n 'spaceKey': space.key,\n 'tags': tags ?? [],\n 'membershipPolicy': membershipPolicy ?? MembershipPolicy.INVITE,\n },\n }),\n\n await createCredential({\n signer: keyring,\n issuer: space.key,\n subject: signingContext.identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.SpaceMember',\n 'spaceKey': space.key,\n 'role': SpaceMember.Role.OWNER,\n 'profile': signingContext.getProfile(),\n 'genesisFeedKey': space.controlFeedKey ?? failUndefined(),\n 'tags': tags ?? [],\n },\n }),\n\n await signingContext.credentialSigner.createCredential({\n subject: space.controlFeedKey ?? failUndefined(),\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n 'spaceKey': space.key,\n 'identityKey': signingContext.identityKey,\n 'deviceKey': signingContext.deviceKey,\n 'designation': AdmittedFeed.Designation.CONTROL,\n },\n }),\n\n await signingContext.credentialSigner.createCredential({\n subject: space.dataFeedKey ?? failUndefined(),\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n 'spaceKey': space.key,\n 'identityKey': signingContext.identityKey,\n 'deviceKey': signingContext.deviceKey,\n 'designation': AdmittedFeed.Designation.DATA,\n },\n }),\n\n await signingContext.credentialSigner.createCredential({\n subject: space.key ?? failUndefined(),\n assertion: {\n '@type': 'dxos.halo.credentials.Epoch',\n 'number': 0,\n 'previousId': undefined,\n 'timeframe': new Timeframe(),\n 'snapshotCid': undefined,\n automergeRoot,\n },\n }),\n ];\n\n for (const credential of credentials) {\n await space.controlPipeline.writer.write({\n credential: { credential },\n });\n }\n\n return credentials;\n};\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Doc } from '@automerge/automerge';\nimport { type AutomergeUrl, type DocumentId, interpretAsDocumentId } from '@automerge/automerge-repo';\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\n\nimport { Event, synchronized, trackLeaks } from '@dxos/async';\nimport { SpaceProperties } from '@dxos/client-protocol';\nimport { Context, LifecycleState, Resource, cancelWithContext } from '@dxos/context';\nimport {\n type CredentialSigner,\n type DelegateInvitationCredential,\n type MemberInfo,\n createAdmissionCredentials,\n getCredentialAssertion,\n} from '@dxos/credentials';\nimport { Type } from '@dxos/echo';\nimport {\n DatabaseRoot,\n type EchoHost,\n EchoHostService,\n type EdgeAutomergeReplicator,\n EdgeAutomergeReplicatorService,\n type MeshEchoReplicator,\n MeshEchoReplicatorService,\n findInlineObjectOfType,\n} from '@dxos/echo-host';\nimport { type DatabaseDirectory, createIdFromSpaceKey } from '@dxos/echo-protocol';\nimport {\n type EdgeConnection,\n EdgeConnectionService,\n type EdgeHttpClient,\n EdgeHttpClientService,\n} from '@dxos/edge-client';\nimport { type FeedStore, FeedStoreService, writeMessages } from '@dxos/feed-store';\nimport { assertArgument, assertState, failedInvariant, invariant } from '@dxos/invariant';\nimport { type KeyringApi, KeyringApiService } from '@dxos/keyring';\nimport { PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { AlreadyJoinedError } from '@dxos/protocols';\nimport { Invitation, SpaceState } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { EdgeReplicationSetting, type SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport {\n type Credential,\n MembershipPolicy,\n type ProfileDocument,\n SpaceMember,\n} from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type DelegateSpaceInvitation } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type PeerState } from '@dxos/protocols/proto/dxos/mesh/presence';\nimport { type Teleport } from '@dxos/teleport';\nimport { Gossip, Presence } from '@dxos/teleport-extension-gossip';\nimport { type Timeframe } from '@dxos/timeframe';\nimport { trace } from '@dxos/tracing';\nimport { ComplexMap, deferFunction, forEachAsync } from '@dxos/util';\n\nimport { type Identity, IdentityProviderService, createAuthProvider } from '../identity';\nimport { type InvitationsManager, InvitationsManagerService } from '../invitations';\nimport { type IMetadataStore, IMetadataStoreService } from '../metadata';\nimport {\n AuthStatus,\n CredentialServerExtension,\n type Space,\n type SpaceManager,\n SpaceManagerService,\n type SpaceProtocol,\n type SpaceProtocolSession,\n} from '../space';\nimport { DataSpace } from './data-space';\nimport { spaceGenesis } from './genesis';\n\nconst PRESENCE_ANNOUNCE_INTERVAL = 10_000;\nconst PRESENCE_OFFLINE_TIMEOUT = 20_000;\n\nexport interface SigningContext {\n identityKey: PublicKey;\n deviceKey: PublicKey;\n credentialSigner: CredentialSigner; // TODO(burdon): Already has keyring.\n recordCredential: (credential: Credential) => Promise<void>;\n // TODO(dmaretskyi): Should be a getter.\n getProfile: () => ProfileDocument | undefined;\n}\n\n/**\n * Resolves signing context when identity becomes available.\n */\nexport type SigningContextProvider = () => SigningContext;\n\n/**\n * Effect service tag for {@link SigningContextProvider}.\n */\nexport class SigningContextProviderService extends EffectContext.Tag('@dxos/client-services/SigningContextProvider')<\n SigningContextProviderService,\n SigningContextProvider\n>() {}\n\n/**\n * Builds a {@link SigningContextProvider} from an identity resolver.\n */\nexport const createSigningContextProvider =\n (getIdentity: () => Identity): SigningContextProvider =>\n () => {\n const identity = getIdentity();\n return {\n credentialSigner: identity.getIdentityCredentialSigner(),\n identityKey: identity.identityKey,\n deviceKey: identity.deviceKey,\n getProfile: () => identity.profileDocument,\n recordCredential: async (credential) => {\n await identity.controlPipeline.writer.write({ credential: { credential } });\n },\n };\n };\n\n/**\n * Effect Layer providing {@link SigningContextProvider} from {@link IdentityProviderService}.\n */\nexport const SigningContextProviderLayer = Layer.effect(\n SigningContextProviderService,\n Effect.gen(function* () {\n const identityProvider = yield* IdentityProviderService;\n return createSigningContextProvider(identityProvider);\n }),\n);\n\nexport type AcceptSpaceOptions = {\n spaceKey: PublicKey;\n genesisFeedKey: PublicKey;\n\n /**\n * Latest known timeframe for the control pipeline.\n * We will try to catch up to this timeframe before starting the data pipeline.\n */\n controlTimeframe?: Timeframe;\n\n /**\n * Latest known timeframe for the data pipeline.\n * We will try to catch up to this timeframe before initializing the database.\n */\n dataTimeframe?: Timeframe;\n\n /** Tags assigned to the space member. */\n tags?: string[];\n};\n\nexport type AdmitMemberOptions = {\n spaceKey: PublicKey;\n identityKey: PublicKey;\n role: SpaceMember.Role;\n profile?: ProfileDocument;\n delegationCredentialId?: PublicKey;\n tags?: string[];\n};\n\nexport type DataSpaceManagerProps = {\n spaceManager: SpaceManager;\n metadataStore: IMetadataStore;\n keyring: KeyringApi;\n signingContextProvider: SigningContextProvider;\n feedStore: FeedStore<FeedMessage>;\n echoHost: EchoHost;\n invitationsManager: InvitationsManager;\n edgeConnection?: EdgeConnection;\n edgeHttpClient?: EdgeHttpClient;\n meshReplicator?: MeshEchoReplicator;\n echoEdgeReplicator?: EdgeAutomergeReplicator;\n runtimeProps?: DataSpaceManagerRuntimeProps;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n};\n\nexport type DataSpaceManagerRuntimeProps = {\n spaceMemberPresenceAnnounceInterval?: number;\n spaceMemberPresenceOfflineTimeout?: number;\n activeEdgeNotarizationPollingInterval?: number;\n disableP2pReplication?: boolean;\n /**\n * If true, spaces that were previously SPACE_ACTIVE will be automatically activated on startup.\n * This is used in dedicated worker mode to restore space state after leader changeover.\n */\n autoActivateSpaces?: boolean;\n};\n\nexport type CreateSpaceOptions = {\n rootUrl?: AutomergeUrl;\n documents?: Record<DocumentId, Uint8Array>;\n tags?: string[];\n membershipPolicy?: MembershipPolicy;\n};\n\n@trackLeaks('open', 'close')\nexport class DataSpaceManager extends Resource {\n public readonly updated = new Event();\n\n private readonly _spaces = new ComplexMap<PublicKey, DataSpace>(PublicKey.hash);\n\n private readonly _spaceManager: SpaceManager;\n private readonly _metadataStore: IMetadataStore;\n private readonly _keyring: KeyringApi;\n private readonly _signingContextProvider: SigningContextProvider;\n private readonly _feedStore: FeedStore<FeedMessage>;\n private readonly _echoHost: EchoHost;\n private readonly _invitationsManager: InvitationsManager;\n private readonly _edgeConnection?: EdgeConnection = undefined;\n private readonly _edgeHttpClient?: EdgeHttpClient = undefined;\n private readonly _edgeFeatures?: Runtime.Client.EdgeFeatures = undefined;\n private readonly _meshReplicator?: MeshEchoReplicator = undefined;\n private readonly _echoEdgeReplicator?: EdgeAutomergeReplicator = undefined;\n private readonly _runtimeProps?: DataSpaceManagerRuntimeProps = undefined;\n\n constructor(params: DataSpaceManagerProps) {\n super();\n\n this._spaceManager = params.spaceManager;\n this._metadataStore = params.metadataStore;\n this._keyring = params.keyring;\n this._signingContextProvider = params.signingContextProvider;\n this._feedStore = params.feedStore;\n this._echoHost = params.echoHost;\n this._meshReplicator = params.meshReplicator;\n this._invitationsManager = params.invitationsManager;\n this._edgeConnection = params.edgeConnection;\n this._edgeFeatures = params.edgeFeatures;\n this._echoEdgeReplicator = params.echoEdgeReplicator;\n this._edgeHttpClient = params.edgeHttpClient;\n this._runtimeProps = params.runtimeProps;\n\n trace.diagnostic({\n id: 'spaces',\n name: 'Spaces',\n fetch: async () => {\n return Promise.all(\n Array.from(this._spaces.values()).map(async (space) => {\n const rootUrl = space.automergeSpaceState.rootUrl;\n const rootHandle = rootUrl\n ? await this._echoHost.loadDoc<Doc<DatabaseDirectory>>(this._ctx, rootUrl as AutomergeUrl)\n : undefined;\n const rootDoc = rootHandle?.doc();\n\n const properties = rootDoc && findInlineObjectOfType(rootDoc, Type.getTypename(SpaceProperties));\n\n return {\n key: space.key.toHex(),\n state: SpaceState[space.state],\n name: properties?.[1].data.name ?? null,\n inlineObjects: rootDoc ? Object.keys(rootDoc.objects ?? {}).length : null,\n linkedObjects: rootDoc ? Object.keys(rootDoc.links ?? {}).length : null,\n credentials: space.inner.spaceState.credentials.length,\n members: space.inner.spaceState.members.size,\n rootUrl,\n };\n }),\n );\n },\n });\n }\n\n private get signingContext(): SigningContext {\n return this._signingContextProvider();\n }\n\n // TODO(burdon): Remove.\n get spaces() {\n return this._spaces;\n }\n\n getSpaceById(spaceId: SpaceId): DataSpace | undefined {\n return [...this._spaces.values()].find((space) => space.id === spaceId);\n }\n\n @synchronized\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n protected override async _open(ctx: Context): Promise<void> {\n log('open');\n log('metadata loaded', { spaces: this._metadataStore.spaces.length });\n\n const spacesToActivate: DataSpace[] = [];\n await forEachAsync(this._metadataStore.spaces, async (spaceMetadata) => {\n try {\n // Tombstoned spaces are never constructed, opened, or replicated.\n if (spaceMetadata.state === SpaceState.SPACE_DELETED || this.isSpaceDeleted(spaceMetadata.key)) {\n log('skipping deleted space', { spaceKey: spaceMetadata.key });\n return;\n }\n log('load space', { spaceMetadata });\n const space = await this._constructSpace(ctx, spaceMetadata);\n // Track spaces that were previously active for auto-activation (used in dedicated worker mode).\n if (this._runtimeProps?.autoActivateSpaces && spaceMetadata.state === SpaceState.SPACE_ACTIVE) {\n spacesToActivate.push(space);\n }\n } catch (err) {\n log.error('Error loading space', { spaceMetadata, err });\n }\n });\n\n // Auto-activate spaces that were previously active (used in dedicated worker mode after leader changeover).\n for (const space of spacesToActivate) {\n log('auto-activating space', { spaceKey: space.key });\n space.activate(ctx).catch((err) => {\n log.error('Error auto-activating space', { spaceKey: space.key, err });\n });\n }\n\n this.updated.emit();\n }\n\n @synchronized\n protected override async _close(ctx: Context): Promise<void> {\n log('close');\n for (const space of this._spaces.values()) {\n await space.close(ctx);\n }\n this._spaces.clear();\n }\n\n /**\n * Creates a new space writing the genesis credentials to the control feed.\n */\n @synchronized\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n async createSpace(ctx: Context, options: CreateSpaceOptions = {}): Promise<DataSpace> {\n assertArgument(\n !!options.rootUrl === !!options.documents,\n 'options',\n 'root url must be required when providing documents',\n );\n\n assertState(this._lifecycleState === LifecycleState.OPEN, 'Not open.');\n\n const tags = options.tags ? Array.from(options.tags) : [];\n const spaceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n\n const spaceId = await createIdFromSpaceKey(spaceKey);\n\n const metadata: SpaceMetadata = {\n key: spaceKey,\n genesisFeedKey: controlFeedKey,\n controlFeedKey,\n dataFeedKey,\n state: SpaceState.SPACE_ACTIVE,\n tags,\n };\n\n log('creating space...', { spaceId, spaceKey });\n\n // New document IDs for the space.\n const documentIdMapping: Record<DocumentId, DocumentId> = {};\n if (options.documents) {\n invariant(\n Object.keys(options.documents).every((documentId) => /^[a-zA-Z0-9]+$/.test(documentId)),\n 'Invalid document IDs',\n );\n\n await Promise.all(\n Object.entries(options.documents).map(async ([documentId, data]) => {\n log('creating document...', { documentId });\n // TODO(dmaretskyi): Broken types -- the bytes get interpreted as CRDT data.\n const newDoc = await this._echoHost.createDoc(data as any as DatabaseDirectory, {\n preserveHistory: true,\n });\n\n // The archived documents might have the spaceKey from the space they were expored from, we need to update it to the new spaceKey.\n if (newDoc.doc().access !== undefined && newDoc.doc().access!.spaceKey !== spaceKey.toHex()) {\n newDoc.change((doc) => {\n doc.access!.spaceKey = spaceKey.toHex();\n });\n }\n\n documentIdMapping[documentId as DocumentId] = newDoc.documentId;\n }),\n );\n }\n\n log('opening space...', { spaceKey });\n\n let root: DatabaseRoot;\n if (options.rootUrl) {\n const newRootDocId = documentIdMapping[interpretAsDocumentId(options.rootUrl)] ?? failedInvariant();\n const rootDocHandle = await this._echoHost.loadDoc<DatabaseDirectory>(ctx, newRootDocId);\n invariant(rootDocHandle, 'Root document must be available after import.');\n DatabaseRoot.mapLinks(rootDocHandle, documentIdMapping);\n\n root = await this._echoHost.updateSpaceRoot(ctx, spaceId, `automerge:${newRootDocId}` as AutomergeUrl);\n } else {\n root = await this._echoHost.createSpaceRoot(ctx, spaceKey);\n }\n await this._echoHost.flush(ctx);\n\n log('constructing space...', { spaceKey });\n\n const space = await this._constructSpace(ctx, metadata);\n await space.open(ctx);\n\n log('adding space...', { spaceKey });\n\n const credentials = await spaceGenesis(\n this._keyring,\n this.signingContext,\n space.inner,\n root.url,\n tags,\n options.membershipPolicy,\n );\n await this._metadataStore.addSpace(metadata);\n\n const memberCredential = credentials[1];\n invariant(getCredentialAssertion(memberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember');\n await this.signingContext.recordCredential(memberCredential);\n\n await space.initializeDataPipeline(ctx);\n\n log('space ready.', { spaceId, spaceKey });\n\n this.updated.emit();\n return space;\n }\n\n /**\n * Accepts an existing space by joining its swarm and initializing the data pipeline.\n * @param ctx - Caller context for cancellation and tracing.\n * @param opts - Space keys and optional timeframes for catch-up.\n */\n // TODO(burdon): Rename join space.\n @synchronized\n @trace.span({ showInBrowserTimeline: true, op: 'lifecycle' })\n async acceptSpace(ctx: Context, opts: AcceptSpaceOptions): Promise<DataSpace> {\n log('accept space', { opts });\n invariant(this._lifecycleState === LifecycleState.OPEN, 'Not open.');\n invariant(!this._spaces.has(opts.spaceKey), 'Space already exists.');\n invariant(!this.isSpaceDeleted(opts.spaceKey), 'Cannot accept a deleted space.');\n\n const tags = opts.tags ? Array.from(opts.tags) : [];\n const metadata: SpaceMetadata = {\n key: opts.spaceKey,\n genesisFeedKey: opts.genesisFeedKey,\n controlTimeframe: opts.controlTimeframe,\n dataTimeframe: opts.dataTimeframe,\n tags,\n };\n\n const space = await this._constructSpace(ctx, metadata);\n await space.open(ctx);\n await this._metadataStore.addSpace(metadata);\n // Use DSM lifecycle ctx: the invitation accept flow disposes `ctx` as soon as\n // `acceptSpace` returns (guardedState.complete -> ctx.dispose). Detached data-pipeline\n // initialization must outlive the invitation flow, and its span must be parented to a\n // long-lived context.\n space.initializeDataPipelineAsync(this._ctx);\n\n this.updated.emit();\n return space;\n }\n\n /**\n * Whether the space has been tombstoned (soft-deleted). Deleted spaces are never opened or replicated.\n */\n isSpaceDeleted(spaceKey: PublicKey): boolean {\n // Mirror the deletion predicate used in `_open`: the tombstone list or a persisted SPACE_DELETED state.\n return (\n this._metadataStore.deletedSpaces.some((key) => key.equals(spaceKey)) ||\n this._metadataStore.spaces.some(\n (spaceMetadata) => spaceMetadata.key.equals(spaceKey) && spaceMetadata.state === SpaceState.SPACE_DELETED,\n )\n );\n }\n\n /**\n * Tombstones (soft-deletes) a space initiated locally on this device.\n * Records a SpaceDeleted credential in the HALO so the deletion replicates to the user's other devices,\n * then unloads the space locally. Data is not removed until garbage collection (future work).\n */\n @synchronized\n async markSpaceDeleted(ctx: Context, spaceKey: PublicKey): Promise<void> {\n if (this.isSpaceDeleted(spaceKey)) {\n return;\n }\n\n // Replicates to the user's other devices via the HALO control feed.\n const credential = await this.signingContext.credentialSigner.createCredential({\n subject: spaceKey,\n assertion: {\n '@type': 'dxos.halo.credentials.SpaceDeleted',\n spaceKey,\n 'deletedAt': new Date(),\n },\n });\n await this.signingContext.recordCredential(credential);\n\n await this._tombstoneSpace(ctx, spaceKey);\n }\n\n /**\n * Tombstones a space in response to a SpaceDeleted credential replicated from another device.\n * Does not write a credential (one already exists in the HALO).\n */\n @synchronized\n async handleRemoteSpaceDeleted(ctx: Context, spaceKey: PublicKey): Promise<void> {\n if (this.isSpaceDeleted(spaceKey)) {\n return;\n }\n\n await this._tombstoneSpace(ctx, spaceKey);\n }\n\n /**\n * Persists the tombstone and unloads the space if it is currently loaded.\n * Must be called while holding the DataSpaceManager lock (see callers).\n */\n private async _tombstoneSpace(ctx: Context, spaceKey: PublicKey): Promise<void> {\n await this._metadataStore.addDeletedSpace(spaceKey);\n\n const space = this._spaces.get(spaceKey);\n if (space) {\n // Separate teardown (resource lifecycle) from the terminal state transition.\n if (space.isOpen) {\n await space.close(ctx);\n }\n await space.delete();\n this._spaces.delete(spaceKey);\n }\n\n this.updated.emit();\n }\n\n async admitMember(options: AdmitMemberOptions): Promise<Credential> {\n const space = this._spaceManager.spaces.get(options.spaceKey);\n invariant(space);\n\n if (space.spaceState.getMemberRole(options.identityKey) !== SpaceMember.Role.REMOVED) {\n throw new AlreadyJoinedError();\n }\n\n // TODO(burdon): Check if already admitted.\n const credentials: FeedMessage.Payload[] = await createAdmissionCredentials(\n this.signingContext.credentialSigner,\n options.identityKey,\n space.key,\n space.genesisFeedKey,\n options.role,\n space.spaceState.membershipChainHeads,\n options.profile,\n options.delegationCredentialId,\n space.spaceState.tags,\n );\n\n // TODO(dmaretskyi): Refactor.\n invariant(credentials[0].credential);\n const spaceMemberCredential = credentials[0].credential.credential;\n invariant(getCredentialAssertion(spaceMemberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember');\n await writeMessages(space.controlPipeline.writer, credentials);\n\n return spaceMemberCredential;\n }\n\n /**\n * Wait until the space data pipeline is fully initialized.\n * Used by invitation handler.\n * TODO(dmaretskyi): Consider removing.\n */\n async waitUntilSpaceReady(spaceKey: PublicKey): Promise<void> {\n await cancelWithContext(\n this._ctx,\n this.updated.waitForCondition(() => {\n const space = this._spaces.get(spaceKey);\n return !!space && space.state === SpaceState.SPACE_READY;\n }),\n );\n }\n\n public async requestSpaceAdmissionCredential(ctx: Context, spaceKey: PublicKey): Promise<Credential> {\n return this._spaceManager.requestSpaceAdmissionCredential(ctx, {\n spaceKey,\n identityKey: this.signingContext.identityKey,\n timeout: 15_000,\n swarmIdentity: {\n identityKey: this.signingContext.identityKey,\n peerKey: this.signingContext.deviceKey,\n credentialProvider: createAuthProvider(this.signingContext.credentialSigner),\n credentialAuthenticator: async () => true,\n },\n });\n }\n\n async setSpaceEdgeReplicationSetting(\n ctx: Context,\n spaceKey: PublicKey,\n setting: EdgeReplicationSetting,\n ): Promise<void> {\n const space = this._spaces.get(spaceKey);\n invariant(space, 'Space not found.');\n\n await this._metadataStore.setSpaceEdgeReplicationSetting(spaceKey, setting);\n\n if (space.isOpen) {\n switch (setting) {\n case EdgeReplicationSetting.DISABLED:\n await this._echoEdgeReplicator?.disconnectFromSpace(space.id);\n break;\n case EdgeReplicationSetting.ENABLED:\n await this._echoEdgeReplicator?.connectToSpace(ctx, space.id);\n break;\n }\n }\n\n space.stateUpdate.emit();\n }\n\n private async _constructSpace(ctx: Context, metadata: SpaceMetadata): Promise<DataSpace> {\n log('construct space', { metadata });\n const gossip = new Gossip({\n localPeerId: this.signingContext.deviceKey,\n });\n const presence = new Presence({\n announceInterval: this._runtimeProps?.spaceMemberPresenceAnnounceInterval ?? PRESENCE_ANNOUNCE_INTERVAL,\n offlineTimeout: this._runtimeProps?.spaceMemberPresenceOfflineTimeout ?? PRESENCE_OFFLINE_TIMEOUT,\n identityKey: this.signingContext.identityKey,\n gossip,\n });\n\n const controlFeed =\n metadata.controlFeedKey && (await this._feedStore.openFeed(metadata.controlFeedKey, { writable: true }));\n const dataFeed =\n metadata.dataFeedKey &&\n (await this._feedStore.openFeed(metadata.dataFeedKey, {\n writable: true,\n sparse: true,\n }));\n\n const space: Space = await this._spaceManager.constructSpace({\n metadata,\n swarmIdentity: {\n identityKey: this.signingContext.identityKey,\n peerKey: this.signingContext.deviceKey,\n credentialProvider: createAuthProvider(this.signingContext.credentialSigner),\n credentialAuthenticator: deferFunction(() => dataSpace.authVerifier.verifier),\n },\n onAuthorizedConnection: (session) =>\n queueMicrotask(async () => {\n try {\n if (!session.isOpen) {\n return;\n }\n session.addExtension('dxos.mesh.teleport.admission-discovery', new CredentialServerExtension(space));\n session.addExtension(\n 'dxos.mesh.teleport.gossip',\n gossip.createExtension({ remotePeerId: session.remotePeerId }),\n );\n session.addExtension('dxos.mesh.teleport.notarization', dataSpace.notarizationPlugin.createExtension());\n await this._connectEchoMeshReplicator(space, session);\n } catch (err: any) {\n log.warn('error on authorized connection', { err });\n await session.close(err);\n }\n }),\n onAuthFailure: () => {\n log.warn('auth failure');\n },\n onMemberRolesChanged: async (members: MemberInfo[]) => {\n if (dataSpace?.state === SpaceState.SPACE_READY) {\n this._handleMemberRoleChanges(presence, space.protocol, members);\n }\n },\n memberKey: this.signingContext.identityKey,\n onDelegatedInvitationStatusChange: (invitation, isActive) => {\n return this._handleInvitationStatusChange(dataSpace, invitation, isActive);\n },\n });\n controlFeed && (await space.setControlFeed(controlFeed));\n dataFeed && (await space.setDataFeed(dataFeed));\n\n const dataSpace = new DataSpace({\n inner: space,\n initialState: metadata.state === SpaceState.SPACE_INACTIVE ? SpaceState.SPACE_INACTIVE : SpaceState.SPACE_CLOSED,\n metadataStore: this._metadataStore,\n gossip,\n presence,\n keyring: this._keyring,\n feedStore: this._feedStore,\n echoHost: this._echoHost,\n signingContext: this.signingContext,\n callbacks: {\n beforeReady: async () => {\n log('before space ready', { space: space.key });\n },\n afterReady: async () => {\n log('after space ready', { space: space.key, open: this._lifecycleState === LifecycleState.OPEN });\n if (this._lifecycleState === LifecycleState.OPEN) {\n await this._createDelegatedInvitations(dataSpace, [...space.spaceState.invitations.entries()]);\n this._handleMemberRoleChanges(presence, space.protocol, [...space.spaceState.members.values()]);\n this.updated.emit();\n }\n },\n beforeClose: async () => {\n log('before space close', { space: space.key });\n },\n },\n cache: metadata.cache,\n tags: metadata.tags,\n edgeConnection: this._edgeConnection,\n edgeHttpClient: this._edgeHttpClient,\n edgeFeatures: this._edgeFeatures,\n activeEdgeNotarizationPollingInterval: this._runtimeProps?.activeEdgeNotarizationPollingInterval,\n });\n dataSpace.postOpen.append(async () => {\n const setting = dataSpace.getEdgeReplicationSetting();\n if (!setting || setting === EdgeReplicationSetting.ENABLED) {\n // Use lifecycle ctx: the caller ctx from _constructSpace may be disposed by the time postOpen fires.\n await this._echoEdgeReplicator?.connectToSpace(this._ctx, dataSpace.id);\n } else if (this._echoEdgeReplicator) {\n log('not connecting edge replicator because of EdgeReplicationSetting', { spaceId: dataSpace.id });\n }\n });\n dataSpace.preClose.append(async () => {\n const setting = dataSpace.getEdgeReplicationSetting();\n if (!setting || setting === EdgeReplicationSetting.ENABLED) {\n await this._echoEdgeReplicator?.disconnectFromSpace(dataSpace.id);\n }\n });\n\n presence.newPeer.on((peerState) => {\n if (dataSpace.state === SpaceState.SPACE_READY) {\n this._handleNewPeerConnected(space, peerState);\n }\n });\n\n if (metadata.controlTimeframe) {\n dataSpace.inner.controlPipeline.state.setTargetTimeframe(metadata.controlTimeframe);\n }\n\n this._spaces.set(metadata.key, dataSpace);\n return dataSpace;\n }\n\n private async _connectEchoMeshReplicator(space: Space, session: Teleport): Promise<void> {\n const replicator = this._meshReplicator;\n if (!replicator) {\n log.warn('p2p automerge replication disabled', { space: space.key });\n return;\n }\n await replicator.authorizeDevice(space.key, session.remotePeerId);\n // session ended during device authorization\n if (session.isOpen) {\n session.addExtension('dxos.mesh.teleport.automerge', replicator.createExtension());\n }\n }\n\n private _handleMemberRoleChanges(presence: Presence, spaceProtocol: SpaceProtocol, memberInfo: MemberInfo[]): void {\n let closedSessions = 0;\n for (const member of memberInfo) {\n if (member.key.equals(presence.getLocalState().identityKey)) {\n continue;\n }\n const peers = presence.getPeersByIdentityKey(member.key);\n const sessions = peers.map((p) => p.peerId && spaceProtocol.sessions.get(p.peerId));\n const sessionsToClose = sessions.filter((s): s is SpaceProtocolSession => {\n return (s && (member.role === SpaceMember.Role.REMOVED) !== (s.authStatus === AuthStatus.FAILURE)) ?? false;\n });\n sessionsToClose.forEach((session) => {\n void session.close().catch(log.error);\n });\n closedSessions += sessionsToClose.length;\n }\n log('processed member role changes', {\n roleChangeCount: memberInfo.length,\n peersOnline: presence.getPeersOnline().length,\n closedSessions,\n });\n // Handle the case when there was a removed peer online, we can now establish a connection with them\n spaceProtocol.updateTopology();\n }\n\n private _handleNewPeerConnected(space: Space, peerState: PeerState): void {\n const role = space.spaceState.getMemberRole(peerState.identityKey);\n if (role === SpaceMember.Role.REMOVED) {\n const session = peerState.peerId && space.protocol.sessions.get(peerState.peerId);\n if (session != null) {\n log('closing a session with a removed peer', { peerId: peerState.peerId });\n void session.close().catch(log.error);\n }\n }\n }\n\n private async _handleInvitationStatusChange(\n dataSpace: DataSpace | undefined,\n delegatedInvitation: DelegateInvitationCredential,\n isActive: boolean,\n ): Promise<void> {\n if (dataSpace?.state !== SpaceState.SPACE_READY) {\n return;\n }\n if (isActive) {\n await this._createDelegatedInvitations(dataSpace, [\n [delegatedInvitation.credentialId, delegatedInvitation.invitation],\n ]);\n } else {\n await this._invitationsManager.cancelInvitation(delegatedInvitation.invitation);\n }\n }\n\n private async _createDelegatedInvitations(\n space: DataSpace,\n invitations: Array<[PublicKey, DelegateSpaceInvitation]>,\n ): Promise<void> {\n const tasks = invitations.map(([credentialId, invitation]) => {\n return this._invitationsManager.createInvitation(this._ctx, {\n type: Invitation.Type.DELEGATED,\n kind: Invitation.Kind.SPACE,\n spaceKey: space.key,\n authMethod: invitation.authMethod,\n invitationId: invitation.invitationId,\n swarmKey: invitation.swarmKey,\n guestKeypair: invitation.guestKey ? { publicKey: invitation.guestKey } : undefined,\n lifetime: invitation.expiresOn ? (invitation.expiresOn.getTime() - Date.now()) / 1000 : undefined,\n multiUse: invitation.multiUse,\n delegationCredentialId: credentialId,\n persistent: false,\n });\n });\n await Promise.all(tasks);\n }\n}\n\nexport class DataSpaceManagerService extends EffectContext.Tag('@dxos/client-services/DataSpaceManager')<\n DataSpaceManagerService,\n DataSpaceManager\n>() {}\n\nexport type DataSpaceManagerLayerOptions = Pick<DataSpaceManagerProps, 'runtimeProps' | 'edgeFeatures'>;\n\n/**\n * Effect Layer constructing a dormant {@link DataSpaceManager}.\n */\nexport const DataSpaceManagerLayer = (\n options: DataSpaceManagerLayerOptions = {},\n): Layer.Layer<\n DataSpaceManagerService,\n never,\n | SpaceManagerService\n | IMetadataStoreService\n | KeyringApiService\n | SigningContextProviderService\n | FeedStoreService\n | EchoHostService\n | InvitationsManagerService\n> =>\n Layer.effect(\n DataSpaceManagerService,\n Effect.gen(function* () {\n const spaceManager = yield* SpaceManagerService;\n const metadataStore = yield* IMetadataStoreService;\n const keyring = yield* KeyringApiService;\n const signingContextProvider = yield* SigningContextProviderService;\n const feedStore = yield* FeedStoreService;\n const echoHost = yield* EchoHostService;\n const invitationsManager = yield* InvitationsManagerService;\n const edgeConnection = yield* Effect.serviceOption(EdgeConnectionService);\n const edgeHttpClient = yield* Effect.serviceOption(EdgeHttpClientService);\n const meshReplicator = yield* Effect.serviceOption(MeshEchoReplicatorService);\n const echoEdgeReplicator = yield* Effect.serviceOption(EdgeAutomergeReplicatorService);\n\n return new DataSpaceManager({\n spaceManager,\n metadataStore,\n keyring,\n signingContextProvider,\n feedStore,\n echoHost,\n invitationsManager,\n edgeConnection: Option.getOrUndefined(edgeConnection),\n edgeHttpClient: Option.getOrUndefined(edgeHttpClient),\n meshReplicator: Option.getOrUndefined(meshReplicator),\n echoEdgeReplicator: Option.getOrUndefined(echoEdgeReplicator),\n ...options,\n });\n }),\n );\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { SpaceArchive } from '@dxos/protocols/proto/dxos/client/services';\n\nconst JSON_EXTENSIONS = ['.dx.json', '.dx.json.gz', '.json'];\nconst BINARY_EXTENSIONS = ['.tar', '.tar.gz'];\n\n/**\n * Detect the format of a space archive.\n *\n * Uses filename extension as the primary signal, and falls back to sniffing\n * the first bytes of the archive contents to distinguish JSON from tar.\n */\nexport const detectSpaceArchiveFormat = (archive: Pick<SpaceArchive, 'filename' | 'contents'>): SpaceArchive.Format => {\n const filename = archive.filename?.toLowerCase() ?? '';\n if (JSON_EXTENSIONS.some((ext) => filename.endsWith(ext))) {\n return SpaceArchive.Format.JSON;\n }\n if (BINARY_EXTENSIONS.some((ext) => filename.endsWith(ext))) {\n return SpaceArchive.Format.BINARY;\n }\n\n // Fall back to byte sniffing: JSON archives start with '{' (0x7B) or whitespace.\n const bytes = archive.contents;\n if (bytes && bytes.length > 0) {\n for (let i = 0; i < Math.min(bytes.length, 16); i++) {\n const byte = bytes[i];\n // Skip whitespace.\n if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {\n continue;\n }\n if (byte === 0x7b /* '{' */) {\n return SpaceArchive.Format.JSON;\n }\n break;\n }\n }\n\n return SpaceArchive.Format.BINARY;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { type Obj, Type } from '@dxos/echo';\nimport { type SerializedSpace } from '@dxos/echo-client';\nimport { type DatabaseDirectory, type EntityStructure } from '@dxos/echo-protocol';\nimport { assertArgument } from '@dxos/invariant';\nimport { URI } from '@dxos/keys';\nimport { type SpaceArchive } from '@dxos/protocols/proto/dxos/client/services';\n\nconst ATTR_TYPE = '@type';\nconst ATTR_META = '@meta';\nconst ATTR_DELETED = '@deleted';\nconst ATTR_PARENT = '@parent';\nconst ATTR_RELATION_SOURCE = '@relationSource';\nconst ATTR_RELATION_TARGET = '@relationTarget';\n\n/**\n * Type URI of the meta-schema (`TypeSchema` / `Type.Type`). Objects with this\n * `@type` represent persisted ECHO type definitions and must be branded\n * `system.kind = 'type'` so `Filter.type(Type.Type)` and `Type.isType` recognize\n * them after import. Anything else defaults to `'object'` (or `'relation'` when\n * source/target attrs are present).\n */\nconst TYPE_KIND_SCHEMA_URI = Type.getURI(Type.Type).toString();\n\nconst INTERNAL_KEYS: ReadonlySet<string> = new Set([\n 'id',\n ATTR_TYPE,\n ATTR_META,\n ATTR_DELETED,\n ATTR_PARENT,\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n]);\n\n/**\n * Parse a JSON space archive.\n *\n * The archive contents are expected to be the UTF-8 encoding of\n * `JSON.stringify(serializedSpace)`.\n */\nexport const readSerializedSpaceArchive = (archive: SpaceArchive): SerializedSpace => {\n const text = new TextDecoder().decode(archive.contents);\n const parsed = JSON.parse(text) as SerializedSpace;\n assertArgument(typeof parsed === 'object' && parsed !== null, 'archive', 'Invalid JSON archive payload');\n assertArgument(typeof parsed.version === 'number', 'archive', 'Missing SerializedSpace.version');\n assertArgument(Array.isArray(parsed.objects), 'archive', 'Missing SerializedSpace.objects');\n return parsed;\n};\n\n/**\n * Convert an {@link Obj.JSON} back into an internal {@link EntityStructure} suitable\n * for embedding into a {@link DatabaseDirectory}.\n */\nexport const objJsonToObjectStructure = (obj: Obj.JSON): EntityStructure => {\n const data: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (INTERNAL_KEYS.has(key)) {\n continue;\n }\n data[key] = value;\n }\n\n const system: NonNullable<EntityStructure['system']> = {};\n\n const type = obj[ATTR_TYPE];\n if (type) {\n system.type = { '/': URI.make(type) };\n }\n\n const parent = (obj as any)[ATTR_PARENT];\n if (typeof parent === 'string') {\n system.parent = { '/': URI.make(parent) };\n }\n\n const relationSource = (obj as any)[ATTR_RELATION_SOURCE];\n const relationTarget = (obj as any)[ATTR_RELATION_TARGET];\n if (typeof relationSource === 'string' || typeof relationTarget === 'string') {\n system.kind = 'relation';\n if (typeof relationSource === 'string') {\n system.source = { '/': URI.make(relationSource) };\n }\n if (typeof relationTarget === 'string') {\n system.target = { '/': URI.make(relationTarget) };\n }\n // TODO(wittjosiah): This is fragile, will break if the type URI changes.\n } else if (type === TYPE_KIND_SCHEMA_URI) {\n system.kind = 'type';\n } else {\n system.kind = 'object';\n }\n\n if ((obj as any)[ATTR_DELETED]) {\n system.deleted = true;\n }\n\n const meta = (obj as any)[ATTR_META];\n return {\n system,\n meta: {\n keys: meta?.keys ?? [],\n ...(meta?.tags ? { tags: meta.tags } : {}),\n // Preserve registry-provenance fields so persisted `Type.Type` entities\n // round-trip with their typename / semver (see the symmetric write in\n // `objectStructureToObjJson`).\n ...(meta?.key !== undefined ? { key: meta.key } : {}),\n ...(meta?.version !== undefined ? { version: meta.version } : {}),\n // Preserve annotations (see the symmetric write in `objectStructureToObjJson`).\n ...(meta?.annotations ? { annotations: meta.annotations } : {}),\n },\n data,\n };\n};\n\n/**\n * Build a new {@link DatabaseDirectory} containing every object from the archive,\n * keyed by object id. The caller is responsible for stamping the `access` (space id/key)\n * and version fields after the document is created.\n */\nexport const buildDatabaseDirectoryFromObjects = (objects: readonly Obj.JSON[]): DatabaseDirectory => {\n const map: Record<string, EntityStructure> = {};\n for (const obj of objects) {\n map[obj.id] = objJsonToObjectStructure(obj);\n }\n return {\n objects: map,\n links: {},\n };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { type AutomergeUrl } from '@automerge/automerge-repo';\nimport * as Effect from 'effect/Effect';\nimport * as Exit from 'effect/Exit';\nimport * as Scope from 'effect/Scope';\n\nimport { Context } from '@dxos/context';\nimport { type Obj } from '@dxos/echo';\nimport { type SerializedFeed, type SerializedSpace } from '@dxos/echo-client';\nimport { type EchoHost } from '@dxos/echo-host';\nimport { type DatabaseDirectory, type EntityStructure } from '@dxos/echo-protocol';\nimport { EffectEx } from '@dxos/effect';\nimport { assertState, invariant } from '@dxos/invariant';\nimport { DXN, type EntityId, type IdentityDid, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { FeedProtocol, makeInProcessClient } from '@dxos/protocols';\nimport { SpaceArchive } from '@dxos/protocols/proto/dxos/client/services';\nimport { FeedService } from '@dxos/protocols/rpc';\nimport { createFilename } from '@dxos/util';\n\nimport { type DataSpace } from '../spaces/data-space';\n\nconst SERIALIZED_SPACE_VERSION = 1;\n\nconst FEED_TYPENAME = 'org.dxos.type.feed';\n\nconst ATTR_ID = 'id';\nconst ATTR_TYPE = '@type';\nconst ATTR_META = '@meta';\nconst ATTR_DELETED = '@deleted';\nconst ATTR_PARENT = '@parent';\nconst ATTR_RELATION_SOURCE = '@relationSource';\nconst ATTR_RELATION_TARGET = '@relationTarget';\n\n/**\n * Canonical order of well-known system fields in a serialized object.\n * All remaining `@*` fields follow in the order they appear on the source\n * object, and finally the data fields are appended in their existing order.\n */\nconst SYSTEM_FIELD_ORDER: readonly string[] = [\n ATTR_ID,\n ATTR_TYPE,\n ATTR_META,\n ATTR_DELETED,\n ATTR_PARENT,\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n];\n\n/**\n * Reorder the keys of an {@link Obj.JSON} so that system fields appear first\n * (`id`, `@type`, `@meta`, then any other `@*` attributes), followed by data\n * fields. The returned object has identical values to the input — only the key\n * iteration order changes.\n */\nexport const orderObjJsonFields = (obj: Obj.JSON): Obj.JSON => {\n const source = obj as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const key of SYSTEM_FIELD_ORDER) {\n if (key in source) {\n result[key] = source[key];\n }\n }\n for (const key of Object.keys(source)) {\n if (key.startsWith('@') && !(key in result)) {\n result[key] = source[key];\n }\n }\n for (const key of Object.keys(source)) {\n if (!(key in result)) {\n result[key] = source[key];\n }\n }\n return result as Obj.JSON;\n};\n\nexport type WriteSerializedSpaceArchiveOptions = {\n space: DataSpace;\n echoHost: EchoHost;\n exportedBy?: IdentityDid;\n};\n\n/**\n * Write a JSON space archive from a live {@link DataSpace}.\n *\n * This runs entirely inside the worker and walks automerge documents directly —\n * it does not require a client-side {@link EchoDatabase}. The output conforms to\n * {@link SerializedSpace} and is compatible with the JSON format consumed by the\n * importer in {@link readSerializedSpaceArchive}.\n */\nexport const writeSerializedSpaceArchive = async (\n options: WriteSerializedSpaceArchiveOptions,\n): Promise<SpaceArchive> => {\n const { space, echoHost, exportedBy } = options;\n\n const rootUrl = space.automergeSpaceState.lastEpoch?.subject.assertion.automergeRoot;\n assertState(rootUrl, 'Space does not have a root URL');\n const databaseRoot = space.databaseRoot;\n assertState(databaseRoot, 'Space database root is not ready');\n\n const rootDoc = databaseRoot.doc();\n invariant(rootDoc, 'Space database root document is not loaded');\n\n // Collect all object structures across the root doc and any linked docs.\n const objects: Obj.JSON[] = [];\n collectObjectsFromDoc(rootDoc, objects);\n\n for (const linkedUrl of databaseRoot.getAllLinkedDocuments()) {\n const handle = await echoHost.loadDoc<DatabaseDirectory>(Context.default(), linkedUrl as AutomergeUrl);\n if (!handle) {\n log.warn('linked document handle not available; skipping', { url: linkedUrl });\n continue;\n }\n const doc = handle.doc();\n collectObjectsFromDoc(doc, objects);\n }\n\n // Export queue/feed messages for every Feed object in the space.\n const feeds = await exportFeedData(space, echoHost, objects);\n\n const serialized: SerializedSpace = {\n version: SERIALIZED_SPACE_VERSION,\n timestamp: new Date().toISOString(),\n originalSpaceId: space.id,\n exportedBy,\n createdAt: Date.now(),\n objects,\n ...(feeds.length > 0 ? { feeds } : {}),\n };\n\n const encoded = new TextEncoder().encode(JSON.stringify(serialized));\n return {\n filename: createFilename({ parts: [space.id], ext: 'dx.json' }),\n contents: encoded,\n format: SpaceArchive.Format.JSON,\n };\n};\n\nconst collectObjectsFromDoc = (doc: DatabaseDirectory, out: Obj.JSON[]): void => {\n const docObjects = doc.objects ?? {};\n for (const [objectId, structure] of Object.entries(docObjects)) {\n out.push(objectStructureToObjJson(objectId, structure));\n }\n};\n\n/**\n * Convert an internal {@link EntityStructure} into an {@link Obj.JSON}.\n *\n * Unlike the equivalent helper used for indexing, this preserves the object's\n * `@meta` section so archives produced by this writer can be round-tripped\n * through {@link Obj.fromJSON}.\n */\nexport const objectStructureToObjJson = (objectId: string, structure: EntityStructure): Obj.JSON => {\n const result: Record<string, unknown> = {\n [ATTR_ID]: objectId,\n [ATTR_TYPE]: (structure.system?.type?.['/'] ?? '') as any,\n };\n\n if (structure.meta) {\n result[ATTR_META] = {\n keys: structure.meta.keys ?? [],\n ...(structure.meta.tags ? { tags: structure.meta.tags } : {}),\n // Preserve the registry-provenance fields (typename / semver) so persisted\n // `Type.Type` entities round-trip with their `meta.key` / `meta.version`\n // intact — `Type.getTypename` / `Type.getVersion` read these. Without them\n // a type loaded from an archive would fall back to its object id.\n ...(structure.meta.key !== undefined ? { key: structure.meta.key } : {}),\n ...(structure.meta.version !== undefined ? { version: structure.meta.version } : {}),\n // Preserve annotations (e.g. `AppAnnotation.RootCollectionAnnotation` on a space's\n // properties object) so archives round-trip app-level metadata, not just schema data.\n ...(structure.meta.annotations && Object.keys(structure.meta.annotations).length > 0\n ? { annotations: structure.meta.annotations }\n : {}),\n };\n }\n if (structure.system?.deleted) {\n result[ATTR_DELETED] = true;\n }\n if (structure.system?.parent) {\n result[ATTR_PARENT] = structure.system.parent['/'];\n }\n if (structure.system?.source) {\n result[ATTR_RELATION_SOURCE] = structure.system.source['/'];\n }\n if (structure.system?.target) {\n result[ATTR_RELATION_TARGET] = structure.system.target['/'];\n }\n Object.assign(result, structure.data);\n\n return result as Obj.JSON;\n};\n\nconst exportFeedData = async (space: DataSpace, echoHost: EchoHost, objects: Obj.JSON[]): Promise<SerializedFeed[]> => {\n const feeds: SerializedFeed[] = [];\n const spaceId: SpaceId = space.id;\n\n for (const obj of objects) {\n if (obj[ATTR_TYPE] == null) {\n continue;\n }\n\n const typeDxn = obj[ATTR_TYPE];\n const typeDxnNsid = DXN.isDXN(typeDxn) ? DXN.getName(typeDxn) : undefined;\n if (typeDxnNsid !== FEED_TYPENAME) {\n continue;\n }\n\n const namespace = (obj as any).namespace === 'trace' ? 'trace' : 'data';\n\n try {\n const messages = await collectFeedMessages(echoHost, spaceId, obj.id, namespace);\n if (messages.length > 0) {\n feeds.push({\n feedObjectId: obj.id,\n namespace,\n messages,\n });\n }\n } catch (err) {\n log.warn('failed to export feed data', { feedObjectId: obj.id, error: err });\n }\n }\n\n return feeds;\n};\n\nconst collectFeedMessages = async (\n echoHost: EchoHost,\n spaceId: SpaceId,\n feedId: EntityId,\n namespace: string,\n): Promise<Obj.JSON[]> => {\n const feedNamespace =\n namespace === 'trace' ? FeedProtocol.WellKnownNamespaces.trace : FeedProtocol.WellKnownNamespaces.data;\n\n const messages: Obj.JSON[] = [];\n let cursor: string | undefined;\n\n // Bridge the host feed Handlers to a client to call it in-process (Handlers are served, not\n // called directly). The scope owns the client for the duration of the read.\n const scope = Effect.runSync(Scope.make());\n const feedClient = await EffectEx.runPromise(\n makeInProcessClient(FeedService.Rpcs, echoHost.feedService).pipe(Effect.provideService(Scope.Scope, scope)),\n );\n try {\n while (true) {\n const result = await EffectEx.runPromise(\n feedClient.FeedService.queryFeed({\n query: {\n spaceId,\n feedIds: [feedId],\n feedNamespace,\n after: cursor,\n },\n }),\n );\n const batch = (result.objects ?? []).flatMap((encoded): Obj.JSON[] => {\n try {\n return [JSON.parse(encoded) as Obj.JSON];\n } catch (err) {\n log.verbose('feed object JSON parse failed; object ignored', { encoded, error: err });\n return [];\n }\n });\n if (batch.length === 0) {\n break;\n }\n for (const message of batch) {\n messages.push(orderObjJsonFields(message));\n }\n if (!result.nextCursor || result.nextCursor === cursor) {\n break;\n }\n cursor = result.nextCursor;\n }\n } finally {\n await EffectEx.runPromise(Scope.close(scope, Exit.void));\n }\n return messages;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type { DocumentId } from '@automerge/automerge-repo';\n\nimport { assertArgument, failedInvariant, invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport {\n type FeedArchiveBlock,\n type FeedArchiveMetadata,\n SpaceArchiveFileStructure,\n type SpaceArchiveMetadata,\n} from '@dxos/protocols';\nimport type { SpaceArchive } from '@dxos/protocols/proto/dxos/client/services';\n\n/**\n * Extracted feed data from the archive.\n */\nexport type ExtractedFeed = {\n metadata: FeedArchiveMetadata;\n blocks: FeedArchiveBlock[];\n};\n\nexport type ExtractedSpaceArchive = {\n metadata: SpaceArchiveMetadata;\n documents: Record<DocumentId, Uint8Array>;\n feeds: Record<string, ExtractedFeed>;\n};\n\nexport const extractSpaceArchive = async (archive: SpaceArchive): Promise<ExtractedSpaceArchive> => {\n const { Archive } = await import('@obsidize/tar-browserify');\n const { entries } = await Archive.extract(archive.contents);\n const metadataEntry = entries.find((entry) => entry.fileName === SpaceArchiveFileStructure.metadata);\n assertArgument(metadataEntry, 'metadataEntry', 'Metadata entry not found');\n const metadata = JSON.parse(metadataEntry.getContentAsText());\n const documents: Record<DocumentId, Uint8Array> = {};\n for (const entry of entries.filter((entry) => entry.fileName.startsWith(`${SpaceArchiveFileStructure.documents}/`))) {\n const documentId = entry.fileName\n .replace(`${SpaceArchiveFileStructure.documents}/`, '')\n .replace(/\\.bin$/, '') as DocumentId;\n invariant(!documentId.includes('/'));\n documents[documentId] = entry.content ?? failedInvariant();\n }\n\n const feeds: Record<string, ExtractedFeed> = {};\n const feedsPrefix = `${SpaceArchiveFileStructure.feeds}/`;\n const feedEntries = entries.filter((entry) => entry.fileName.startsWith(feedsPrefix));\n\n const feedMetadataByFeedId = new Map<string, FeedArchiveMetadata>();\n const feedBlocksByFeedId = new Map<string, Map<number, FeedArchiveBlock[]>>();\n\n for (const entry of feedEntries) {\n const relativePath = entry.fileName.slice(feedsPrefix.length);\n const pathParts = relativePath.split('/');\n if (pathParts.length !== 2) {\n continue;\n }\n\n const [feedId, fileName] = pathParts;\n invariant(feedId, 'Feed ID is required');\n invariant(fileName, 'File name is required');\n\n if (fileName === SpaceArchiveFileStructure.feedMetadata) {\n const feedMetadata = JSON.parse(entry.getContentAsText()) as FeedArchiveMetadata;\n feedMetadataByFeedId.set(feedId, feedMetadata);\n } else if (fileName.startsWith(SpaceArchiveFileStructure.feedBlocksPrefix) && fileName.endsWith('.json')) {\n const chunkIndexStr = fileName.slice(SpaceArchiveFileStructure.feedBlocksPrefix.length).replace(/\\.json$/, '');\n const chunkIndex = parseInt(chunkIndexStr, 10);\n invariant(!isNaN(chunkIndex), `Invalid chunk index: ${chunkIndexStr}`);\n\n const blocks = JSON.parse(entry.getContentAsText()) as FeedArchiveBlock[];\n if (!feedBlocksByFeedId.has(feedId)) {\n feedBlocksByFeedId.set(feedId, new Map());\n }\n feedBlocksByFeedId.get(feedId)!.set(chunkIndex, blocks);\n }\n }\n\n for (const [feedId, feedMetadata] of feedMetadataByFeedId) {\n const blockChunks = feedBlocksByFeedId.get(feedId) ?? new Map<number, FeedArchiveBlock[]>();\n const sortedChunkIndices = Array.from(blockChunks.keys()).sort((a, b) => a - b);\n const allBlocks: FeedArchiveBlock[] = [];\n for (const chunkIndex of sortedChunkIndices) {\n allBlocks.push(...blockChunks.get(chunkIndex)!);\n }\n feeds[feedId] = {\n metadata: feedMetadata,\n blocks: allBlocks,\n };\n }\n\n log('extracted space archive', { metadata, documents, feedCount: Object.keys(feeds).length });\n return { metadata, documents, feeds };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as tar from '@obsidize/tar-browserify';\n\nimport { type Context, Resource } from '@dxos/context';\nimport { assertArgument, assertState } from '@dxos/invariant';\nimport type { IdentityDid, SpaceId } from '@dxos/keys';\nimport {\n FEED_ARCHIVE_BLOCKS_PER_CHUNK,\n type FeedArchiveBlock,\n type FeedArchiveMetadata,\n SpaceArchiveFileStructure,\n type SpaceArchiveMetadata,\n SpaceArchiveVersion,\n} from '@dxos/protocols';\nimport { SpaceArchive } from '@dxos/protocols/proto/dxos/client/services';\nimport { createFilename } from '@dxos/util';\n\nexport type SpaceArchiveBeginProps = {\n spaceId?: SpaceId;\n\n /**\n * DID of the identity that exported the space.\n */\n exportedBy?: IdentityDid;\n};\n\nconst CURRENT_VERSION = SpaceArchiveVersion.V1;\n\nexport class SpaceArchiveWriter extends Resource {\n private _tar?: typeof tar;\n private _archive?: tar.Archive;\n\n private _meta?: SpaceArchiveBeginProps = undefined;\n private _currentRootUrl?: string = undefined;\n\n protected override async _open(ctx: Context): Promise<void> {\n this._tar = await import('@obsidize/tar-browserify');\n }\n\n protected override async _close(): Promise<void> {\n return Promise.resolve();\n }\n\n async begin(meta: SpaceArchiveBeginProps): Promise<void> {\n assertState(this._tar, 'Not open');\n assertState(!this._meta, 'Already started');\n this._meta = meta;\n this._archive = new this._tar.Archive();\n }\n\n async setCurrentRootUrl(url: string): Promise<void> {\n assertArgument(url.startsWith('automerge:'), 'url', 'Invalid root URL');\n assertState(this._tar, 'Not open');\n assertState(this._meta, 'Not started');\n this._currentRootUrl = url;\n }\n\n async writeDocument(documentId: string, data: Uint8Array): Promise<void> {\n assertArgument(!documentId.startsWith('automerge:'), 'documentId', 'Invalid document ID');\n assertState(this._archive, 'Not open');\n this._archive.addBinaryFile(`${SpaceArchiveFileStructure.documents}/${documentId}.bin`, data);\n }\n\n /**\n * Writes a feed with its metadata and blocks to the archive.\n * Blocks are written in chunks of {@link FEED_ARCHIVE_BLOCKS_PER_CHUNK}.\n */\n async writeFeed(feedId: string, namespace: string, blocks: FeedArchiveBlock[]): Promise<void> {\n assertArgument(feedId, 'feedId', 'Feed ID is required');\n assertArgument(namespace, 'namespace', 'Namespace is required');\n assertState(this._archive, 'Not open');\n\n const feedPath = `${SpaceArchiveFileStructure.feeds}/${feedId}`;\n\n const metadata: FeedArchiveMetadata = {\n id: feedId,\n namespace,\n };\n this._archive.addTextFile(`${feedPath}/${SpaceArchiveFileStructure.feedMetadata}`, JSON.stringify(metadata));\n\n for (let chunkIndex = 0; chunkIndex * FEED_ARCHIVE_BLOCKS_PER_CHUNK < blocks.length; chunkIndex++) {\n const start = chunkIndex * FEED_ARCHIVE_BLOCKS_PER_CHUNK;\n const end = Math.min(start + FEED_ARCHIVE_BLOCKS_PER_CHUNK, blocks.length);\n const chunk = blocks.slice(start, end);\n this._archive.addTextFile(\n `${feedPath}/${SpaceArchiveFileStructure.feedBlocksPrefix}${chunkIndex}.json`,\n JSON.stringify(chunk),\n );\n }\n }\n\n async finish(): Promise<SpaceArchive> {\n assertState(this._archive, 'Not open');\n assertState(this._meta, 'Not started');\n assertState(this._meta.spaceId, 'No space ID set');\n assertState(this._currentRootUrl, 'No root URL set');\n\n const metadata: SpaceArchiveMetadata = {\n version: CURRENT_VERSION,\n createdAt: Date.now(),\n exportedBy: this._meta.exportedBy,\n originalSpaceId: this._meta.spaceId,\n echo: {\n currentRootUrl: this._currentRootUrl,\n },\n };\n\n this._archive.addTextFile(SpaceArchiveFileStructure.metadata, JSON.stringify(metadata));\n\n const binary = this._archive.toUint8Array();\n\n return {\n filename: createFilename({ parts: [this._meta.spaceId], ext: 'tar' }),\n contents: binary,\n format: SpaceArchive.Format.BINARY,\n };\n }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport type { AutomergeUrl } from '@automerge/automerge-repo';\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { SubscriptionList, UpdateScheduler, scheduleTask } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport {\n type CredentialProcessor,\n createAdmissionCredentials,\n createDidFromIdentityKey,\n getCredentialAssertion,\n} from '@dxos/credentials';\nimport { raise } from '@dxos/debug';\nimport { type EchoHost } from '@dxos/echo-host';\nimport { type DatabaseDirectory } from '@dxos/echo-protocol';\nimport { EffectEx } from '@dxos/effect';\nimport { writeMessages } from '@dxos/feed-store';\nimport { assertArgument, assertState, invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n ApiError,\n AuthorizationError,\n FeedProtocol,\n IdentityNotInitializedError,\n SpaceNotFoundError,\n encodeError,\n makeInProcessClient,\n} from '@dxos/protocols';\nimport {\n type AdmitContactRequest,\n type ContactAdmission,\n type CreateEpochRequest,\n type CreateEpochResponse,\n type CreateSpaceRequest,\n type ExportSpaceRequest,\n type ExportSpaceResponse,\n type ImportSpaceRequest,\n type ImportSpaceResponse,\n type JoinBySpaceKeyRequest,\n type JoinSpaceResponse,\n type PostMessageRequest,\n type QueryCredentialsRequest,\n type QuerySpacesResponse,\n type Space,\n SpaceArchive,\n SpaceMember,\n SpaceState,\n type SubscribeMessagesRequest,\n type UpdateMemberRoleRequest,\n type UpdateSpaceRequest,\n type WriteCredentialsRequest,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type GossipMessage } from '@dxos/protocols/proto/dxos/mesh/teleport/gossip';\nimport { FeedService, type SpacesService } from '@dxos/protocols/rpc';\nimport { trace } from '@dxos/tracing';\nimport { type Provider } from '@dxos/util';\n\nimport { type IdentityManager } from '../identity';\nimport { type SpaceManager } from '../space';\nimport {\n SpaceArchiveWriter,\n detectSpaceArchiveFormat,\n extractSpaceArchive,\n objJsonToObjectStructure,\n readSerializedSpaceArchive,\n writeSerializedSpaceArchive,\n} from '../space-export';\nimport { type DataSpace } from './data-space';\nimport { type DataSpaceManager } from './data-space-manager';\n\nexport class SpacesServiceImpl implements SpacesService.Handlers {\n 'constructor'(\n private readonly _identityManager: IdentityManager,\n private readonly _spaceManager: SpaceManager,\n private readonly _echoHost: EchoHost,\n private readonly _getDataSpaceManager: Provider<Promise<DataSpaceManager>>,\n ) {}\n\n ['SpacesService.createSpace'](request: CreateSpaceRequest): Effect.Effect<Space, Error> {\n return Effect.tryPromise({\n try: async () => {\n this._requireIdentity();\n const ctx = new Context();\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = await dataSpaceManager.createSpace(ctx, {\n tags: request?.tags,\n membershipPolicy: request?.membershipPolicy,\n });\n await this._updateMetrics();\n return this._serializeSpace(space);\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.updateSpace']({ spaceKey, state, edgeReplication }: UpdateSpaceRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n const ctx = Context.default();\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n\n if (state) {\n switch (state) {\n case SpaceState.SPACE_ACTIVE:\n await space.activate(ctx);\n break;\n\n case SpaceState.SPACE_INACTIVE:\n await space.deactivate(ctx);\n break;\n\n case SpaceState.SPACE_DELETED:\n await dataSpaceManager.markSpaceDeleted(ctx, spaceKey);\n // The space is removed from the manager; skip any further mutations (e.g. edgeReplication).\n return;\n default:\n throw new ApiError({ message: 'Invalid space state' });\n }\n }\n\n if (edgeReplication !== undefined) {\n await dataSpaceManager.setSpaceEdgeReplicationSetting(ctx, spaceKey, edgeReplication);\n }\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.updateMemberRole'](request: UpdateMemberRoleRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n const identity = this._requireIdentity();\n const space = this._spaceManager.spaces.get(request.spaceKey);\n if (space == null) {\n throw new SpaceNotFoundError(request.spaceKey);\n }\n if (!space.spaceState.hasMembershipManagementPermission(identity.identityKey)) {\n throw new AuthorizationError({\n message: 'No member management permission.',\n context: {\n spaceKey: space.key,\n role: space.spaceState.getMemberRole(identity.identityKey),\n },\n });\n }\n const credentials = await createAdmissionCredentials(\n identity.getIdentityCredentialSigner(),\n request.memberKey,\n space.key,\n space.genesisFeedKey,\n request.newRole,\n space.spaceState.membershipChainHeads,\n );\n invariant(credentials[0].credential);\n const spaceMemberCredential = credentials[0].credential.credential;\n invariant(getCredentialAssertion(spaceMemberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember');\n await writeMessages(space.controlPipeline.writer, credentials);\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.querySpaces'](): EffectStream.Stream<QuerySpacesResponse, Error> {\n return EffectStream.async<QuerySpacesResponse, Error>((emit) => {\n const ctx = Context.default();\n const scheduler = new UpdateScheduler(\n ctx,\n async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n const spaces = await Promise.all(\n Array.from(dataSpaceManager.spaces.values()).map((space) => this._serializeSpace(space)),\n );\n log('update', () => ({ ids: spaces.map((space) => space.id) }));\n await this._updateMetrics();\n void emit.single({ spaces });\n },\n { maxFrequency: process.env.NODE_ENV === 'test' ? undefined : 2 },\n );\n\n scheduleTask(ctx, async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n\n const subscriptions = new SubscriptionList();\n ctx.onDispose(() => subscriptions.clear());\n\n // TODO(dmaretskyi): Create a pattern for subscribing to a set of objects.\n const subscribeSpaces = () => {\n subscriptions.clear();\n\n for (const space of dataSpaceManager.spaces.values()) {\n let lastState: SpaceState | undefined;\n subscriptions.add(\n space.stateUpdate.on(ctx, () => {\n // Always send a separate update if the space state has changed.\n if (space.state !== lastState) {\n scheduler.forceTrigger();\n } else {\n scheduler.trigger();\n }\n lastState = space.state;\n }),\n );\n\n subscriptions.add(space.presence.updated.on(ctx, () => scheduler.trigger()));\n subscriptions.add(space.automergeSpaceState.onNewEpoch.on(ctx, () => scheduler.trigger()));\n\n // Pipeline progress.\n subscriptions.add(space.inner.controlPipeline.state.timeframeUpdate.on(ctx, () => scheduler.trigger()));\n }\n };\n\n dataSpaceManager.updated.on(ctx, () => {\n subscribeSpaces();\n scheduler.trigger();\n });\n subscribeSpaces();\n\n scheduler.trigger();\n });\n\n if (!this._identityManager.identity) {\n void emit.single({ spaces: [] });\n }\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['SpacesService.postMessage']({ spaceKey, channel, message }: PostMessageRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n await space.postMessage(getChannelId(channel), message);\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.subscribeMessages']({\n spaceKey,\n channel,\n }: SubscribeMessagesRequest): EffectStream.Stream<GossipMessage, Error> {\n return EffectStream.async<GossipMessage, Error>((emit) => {\n const ctx = Context.default();\n scheduleTask(ctx, async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n const handle = space.listen(getChannelId(channel), (message) => {\n void emit.single(message);\n });\n ctx.onDispose(() => handle.unsubscribe());\n });\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['SpacesService.queryCredentials']({\n spaceKey,\n noTail,\n }: QueryCredentialsRequest): EffectStream.Stream<Credential, Error> {\n return EffectStream.async<Credential, Error>((emit) => {\n const ctx = Context.default();\n const space = this._spaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n\n const processor: CredentialProcessor = {\n processCredential: async (credential) => {\n void emit.single(credential);\n },\n };\n ctx.onDispose(() => space.spaceState.removeCredentialProcessor(processor));\n scheduleTask(ctx, async () => {\n await space.spaceState.addCredentialProcessor(processor);\n if (noTail) {\n void emit.end();\n }\n });\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['SpacesService.writeCredentials']({ spaceKey, credentials }: WriteCredentialsRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n const space = this._spaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n for (const credential of credentials ?? []) {\n if (credential.proof) {\n await space.controlPipeline.writer.write({ credential: { credential } });\n } else {\n invariant(!credential.id, 'Id on unsigned credentials is not allowed');\n invariant(this._identityManager.identity, 'Identity is not available');\n const signer = this._identityManager.identity.getIdentityCredentialSigner();\n invariant(credential.issuer.equals(signer.getIssuer()));\n const signedCredential = await signer.createCredential({\n subject: credential.subject.id,\n assertion: credential.subject.assertion,\n });\n await space.controlPipeline.writer.write({ credential: { credential: signedCredential } });\n }\n }\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.createEpoch']({\n spaceKey,\n migration,\n automergeRootUrl,\n }: CreateEpochRequest): Effect.Effect<CreateEpochResponse, Error> {\n return Effect.tryPromise({\n try: async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n const result = await space.createEpoch({ migration, newAutomergeRoot: automergeRootUrl });\n return { epochCredential: result?.credential, controlTimeframe: result?.timeframe };\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.admitContact'](request: AdmitContactRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n await dataSpaceManager.admitMember({\n spaceKey: request.spaceKey,\n identityKey: request.contact.identityKey,\n role: request.role,\n });\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.joinBySpaceKey']({ spaceKey }: JoinBySpaceKeyRequest): Effect.Effect<JoinSpaceResponse, Error> {\n return Effect.tryPromise({\n try: async () => {\n const ctx = Context.default();\n const dataSpaceManager = await this._getDataSpaceManager();\n const credential = await dataSpaceManager.requestSpaceAdmissionCredential(ctx, spaceKey);\n return this._joinByAdmission(ctx, { credential });\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.exportSpace'](request: ExportSpaceRequest): Effect.Effect<ExportSpaceResponse, Error> {\n return Effect.tryPromise({\n try: async () => {\n assertArgument(SpaceId.isValid(request.spaceId), 'spaceId', 'Invalid space ID');\n\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.getSpaceById(request.spaceId) ?? raise(new Error('Space not found'));\n\n const format = request.format ?? SpaceArchive.Format.BINARY;\n if (format === SpaceArchive.Format.JSON) {\n const archive = await writeSerializedSpaceArchive({ space, echoHost: this._echoHost });\n return { archive };\n }\n\n await using writer = await new SpaceArchiveWriter().open();\n await writer.begin({ spaceId: space.id });\n const rootUrl = space.automergeSpaceState.lastEpoch?.subject.assertion.automergeRoot;\n assertState(rootUrl, 'Space does not have a root URL');\n await writer.setCurrentRootUrl(rootUrl);\n\n for await (const [documentId, data] of space.getAllDocuments()) {\n await writer.writeDocument(documentId, data);\n }\n\n const feeds = await space.getAllFeeds();\n for (const feed of feeds) {\n const archiveBlocks = feed.blocks.map((block) => ({\n actorId: block.actorId,\n sequence: block.sequence,\n prevActorId: block.prevActorId,\n prevSequence: block.prevSequence,\n position: block.position,\n timestamp: block.timestamp,\n data: Buffer.from(block.data).toString('base64'),\n }));\n await writer.writeFeed(feed.feedId, feed.feedNamespace, archiveBlocks);\n }\n\n const archive = await writer.finish();\n return { archive };\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SpacesService.importSpace'](request: ImportSpaceRequest): Effect.Effect<ImportSpaceResponse, Error> {\n return Effect.tryPromise({\n try: async () => {\n const ctx = Context.default();\n const dataSpaceManager = await this._getDataSpaceManager();\n\n const format = request.archive.format ?? detectSpaceArchiveFormat(request.archive);\n if (format === SpaceArchive.Format.JSON) {\n const serialized = readSerializedSpaceArchive(request.archive);\n const space = await dataSpaceManager.createSpace(ctx, { tags: request.tags });\n await this._hydrateSpaceFromSerialized(space, serialized);\n await this._updateMetrics();\n return { newSpaceId: space.id };\n }\n\n const extracted = await extractSpaceArchive(request.archive);\n invariant(extracted.metadata.echo?.currentRootUrl, 'Space archive does not contain a root URL');\n const space = await dataSpaceManager.createSpace(ctx, {\n documents: extracted.documents,\n rootUrl: extracted.metadata.echo?.currentRootUrl as AutomergeUrl,\n tags: request.tags,\n });\n await this._updateMetrics();\n return { newSpaceId: space.id };\n },\n catch: (error) => error as Error,\n });\n }\n\n /**\n * Populate a freshly-created space with the objects and feed messages described in a {@link SerializedSpace}.\n *\n * Objects are written directly into the space's automerge root document as inline\n * {@link EntityStructure} entries; feed messages are appended to the appropriate feed\n * via {@link EchoHost.feedService}.\n */\n private async '_hydrateSpaceFromSerialized'(\n space: DataSpace,\n serialized: ReturnType<typeof readSerializedSpaceArchive>,\n ): Promise<void> {\n const databaseRoot = space.databaseRoot;\n assertState(databaseRoot, 'Space database root is not ready');\n\n databaseRoot.handle.change((doc: DatabaseDirectory) => {\n if (!doc.objects) {\n doc.objects = {};\n }\n for (const obj of serialized.objects) {\n doc.objects[obj.id] = objJsonToObjectStructure(obj);\n }\n });\n\n for (const feed of serialized.feeds ?? []) {\n if (feed.messages.length === 0) {\n continue;\n }\n\n const namespace =\n feed.namespace === 'trace' ? FeedProtocol.WellKnownNamespaces.trace : FeedProtocol.WellKnownNamespaces.data;\n try {\n // Handlers are served, not called directly; bridge to a client in-process for this write.\n const feedService = this._echoHost.feedService;\n await EffectEx.runPromise(\n Effect.gen(function* () {\n const feedClient = yield* makeInProcessClient(FeedService.Rpcs, feedService);\n yield* feedClient.FeedService.insertIntoFeed({\n spaceId: space.id,\n feedId: feed.feedObjectId,\n subspaceTag: namespace,\n objects: feed.messages.map((message) => JSON.stringify(message)),\n });\n }).pipe(Effect.scoped),\n );\n } catch (err) {\n log.warn('failed to import feed data', { feedObjectId: feed.feedObjectId, error: err });\n }\n }\n }\n\n private async '_joinByAdmission'(ctx: Context, { credential }: ContactAdmission): Promise<JoinSpaceResponse> {\n const assertion = getCredentialAssertion(credential);\n invariant(assertion['@type'] === 'dxos.halo.credentials.SpaceMember', 'Invalid credential');\n const myIdentity = this._identityManager.identity;\n invariant(myIdentity && credential.subject.id.equals(myIdentity.identityKey));\n\n const dataSpaceManager = await this._getDataSpaceManager();\n let dataSpace = dataSpaceManager.spaces.get(assertion.spaceKey);\n if (!dataSpace) {\n dataSpace = await dataSpaceManager.acceptSpace(ctx, {\n spaceKey: assertion.spaceKey,\n genesisFeedKey: assertion.genesisFeedKey,\n tags: assertion.tags,\n });\n await myIdentity.controlPipeline.writer.write({ credential: { credential } });\n }\n\n return { space: await this._serializeSpace(dataSpace) };\n }\n\n private async '_serializeSpace'(space: DataSpace): Promise<Space> {\n return {\n id: space.id,\n spaceKey: space.key,\n state: space.state,\n error: space.error ? encodeError(space.error) : undefined,\n pipeline: {\n currentEpoch: space.automergeSpaceState.lastEpoch,\n appliedEpoch: space.automergeSpaceState.lastEpoch,\n\n controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),\n currentControlTimeframe: space.inner.controlPipeline.state.timeframe,\n targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,\n totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe,\n\n dataFeeds: undefined,\n startDataTimeframe: undefined,\n currentDataTimeframe: undefined,\n targetDataTimeframe: undefined,\n totalDataTimeframe: undefined,\n\n spaceRootUrl: space.databaseRoot?.url,\n },\n members: await Promise.all(\n Array.from(space.inner.spaceState.members.values()).map(async (member) => {\n const peers = space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key));\n const isMe = this._identityManager.identity?.identityKey.equals(member.key);\n\n if (isMe) {\n peers.push(space.presence.getLocalState());\n }\n\n return {\n identity: {\n did: await createDidFromIdentityKey(member.key),\n identityKey: member.key,\n profile: member.profile ?? {},\n },\n role: member.role,\n presence: peers.length > 0 ? SpaceMember.PresenceState.ONLINE : SpaceMember.PresenceState.OFFLINE,\n peerStates: peers,\n };\n }),\n ),\n creator: space.inner.spaceState.creator?.key,\n tags: space.tags,\n membershipPolicy: space.membershipPolicy,\n cache: space.cache,\n metrics: space.metrics,\n edgeReplication: space.getEdgeReplicationSetting(),\n };\n }\n\n private '_requireIdentity'() {\n if (!this._identityManager.identity) {\n throw new IdentityNotInitializedError({\n message: 'This device has no HALO identity available. See https://docs.dxos.org/guide/platform/halo',\n });\n }\n return this._identityManager.identity;\n }\n\n private async '_updateMetrics'(): Promise<void> {\n const dataSpaceManager = await this._getDataSpaceManager();\n const identity = this._identityManager.identity?.identityKey.truncate();\n if (identity) {\n trace.metrics.gauge('dxos.echo.space.count', dataSpaceManager.spaces.size, {\n tags: { identity },\n });\n }\n }\n}\n\n// Add `user-channel` prefix to the channel name, so that it doesn't collide with the internal channels.\nconst getChannelId = (channel: string): string => `user-channel/${channel}`;\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { AUTH_TIMEOUT, LOAD_CONTROL_FEEDS_TIMEOUT } from '@dxos/client-protocol';\nimport { type Context as DxosContext } from '@dxos/context';\nimport {\n type CredentialSigner,\n DeviceStateMachine,\n ProfileStateMachine,\n createCredentialSignerWithChain,\n createCredentialSignerWithKey,\n} from '@dxos/credentials';\nimport { type Signer } from '@dxos/crypto';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { type FeedWrapper, writeMessages } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type IdentityDid, PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport {\n AdmittedFeed,\n type Credential,\n type DeviceProfileDocument,\n type ProfileDocument,\n} from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type DeviceAdmissionRequest } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type Presence } from '@dxos/teleport-extension-gossip';\nimport { trace } from '@dxos/tracing';\nimport { type ComplexMap, ComplexSet } from '@dxos/util';\n\nimport { type Space } from '../space';\nimport { EdgeFeedReplicator } from '../spaces';\nimport { TrustedKeySetAuthVerifier } from './authenticator';\n\nexport type IdentityProps = {\n did: IdentityDid;\n identityKey: PublicKey;\n deviceKey: PublicKey;\n signer: Signer;\n space: Space;\n presence?: Presence;\n\n edgeConnection?: EdgeConnection;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n};\n\n/**\n * Agent identity manager, which includes the agent's Halo space.\n */\nexport class Identity {\n public readonly space: Space;\n private readonly _signer: Signer;\n private readonly _presence?: Presence;\n private readonly _deviceStateMachine: DeviceStateMachine;\n private readonly _profileStateMachine: ProfileStateMachine;\n private readonly _edgeFeedReplicator?: EdgeFeedReplicator = undefined;\n\n public readonly authVerifier: TrustedKeySetAuthVerifier;\n\n public readonly did: IdentityDid;\n public readonly identityKey: PublicKey;\n public readonly deviceKey: PublicKey;\n\n public readonly stateUpdate = new Event();\n\n constructor(params: IdentityProps) {\n this.space = params.space;\n this._signer = params.signer;\n this._presence = params.presence;\n\n this.did = params.did;\n this.identityKey = params.identityKey;\n this.deviceKey = params.deviceKey;\n\n log.trace('dxos.halo.device', { deviceKey: params.deviceKey });\n\n this._deviceStateMachine = new DeviceStateMachine({\n identityKey: this.identityKey,\n deviceKey: this.deviceKey,\n onUpdate: () => this.stateUpdate.emit(),\n });\n this._profileStateMachine = new ProfileStateMachine({\n identityKey: this.identityKey,\n onUpdate: () => this.stateUpdate.emit(),\n });\n\n this.authVerifier = new TrustedKeySetAuthVerifier({\n trustedKeysProvider: () => new ComplexSet(PublicKey.hash, this.authorizedDeviceKeys.keys()),\n update: this.stateUpdate,\n authTimeout: AUTH_TIMEOUT,\n });\n\n if (params.edgeConnection && params.edgeFeatures?.feedReplicator) {\n this._edgeFeedReplicator = new EdgeFeedReplicator({ messenger: params.edgeConnection, spaceId: this.space.id });\n }\n }\n\n // TODO(burdon): Expose state object?\n get authorizedDeviceKeys(): ComplexMap<PublicKey, DeviceProfileDocument> {\n return this._deviceStateMachine.authorizedDeviceKeys;\n }\n\n @trace.span({ op: 'lifecycle' })\n async open(ctx: DxosContext): Promise<void> {\n await this._presence?.open();\n await this.space.spaceState.addCredentialProcessor(this._deviceStateMachine);\n await this.space.spaceState.addCredentialProcessor(this._profileStateMachine);\n if (this._edgeFeedReplicator) {\n this.space.protocol.feedAdded.append(this._onFeedAdded);\n }\n await this.space.open(ctx);\n }\n\n public async joinNetwork(ctx: DxosContext): Promise<void> {\n await this.space.startProtocol(ctx);\n await this._edgeFeedReplicator?.open();\n }\n\n @trace.span({ op: 'lifecycle' })\n async close(ctx: DxosContext): Promise<void> {\n await this._presence?.close();\n await this.authVerifier.close();\n await this.space.spaceState.removeCredentialProcessor(this._profileStateMachine);\n await this.space.spaceState.removeCredentialProcessor(this._deviceStateMachine);\n\n if (this._edgeFeedReplicator) {\n this.space.protocol.feedAdded.remove(this._onFeedAdded);\n }\n\n await this._edgeFeedReplicator?.close();\n\n await this.space.close(ctx);\n }\n\n async ready(): Promise<void> {\n await this._deviceStateMachine.deviceChainReady.wait();\n\n await this.controlPipeline.state.waitUntilReachedTargetTimeframe({ timeout: LOAD_CONTROL_FEEDS_TIMEOUT });\n }\n\n get profileDocument(): ProfileDocument | undefined {\n return this._profileStateMachine.profile;\n }\n\n /**\n * @test-only\n */\n get controlPipeline() {\n return this.space.controlPipeline;\n }\n\n get haloSpaceId() {\n return this.space.id;\n }\n\n get haloSpaceKey() {\n return this.space.key;\n }\n\n get haloGenesisFeedKey() {\n return this.space.genesisFeedKey;\n }\n\n get deviceCredentialChain() {\n return this._deviceStateMachine.deviceCredentialChain;\n }\n\n get presence() {\n return this._presence;\n }\n\n get signer() {\n return this._signer;\n }\n\n /**\n * Issues credentials as identity.\n * Requires identity to be ready.\n */\n getIdentityCredentialSigner(): CredentialSigner {\n invariant(this._deviceStateMachine.deviceCredentialChain, 'Device credential chain is not ready.');\n return createCredentialSignerWithChain(\n this._signer,\n this._deviceStateMachine.deviceCredentialChain,\n this.deviceKey,\n );\n }\n\n /**\n * Issues credentials as device.\n */\n getDeviceCredentialSigner(): CredentialSigner {\n return createCredentialSignerWithKey(this._signer, this.deviceKey);\n }\n\n async admitDevice({ deviceKey, controlFeedKey, dataFeedKey }: DeviceAdmissionRequest): Promise<Credential> {\n log('Admitting device:', {\n identityKey: this.identityKey,\n hostDevice: this.deviceKey,\n deviceKey,\n controlFeedKey,\n dataFeedKey,\n });\n const signer = this.getIdentityCredentialSigner();\n const deviceCredential = await signer.createCredential({\n subject: deviceKey,\n assertion: {\n '@type': 'dxos.halo.credentials.AuthorizedDevice',\n 'identityKey': this.identityKey,\n deviceKey,\n },\n });\n await writeMessages(\n this.controlPipeline.writer,\n [\n deviceCredential,\n await signer.createCredential({\n subject: controlFeedKey,\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n 'spaceKey': this.haloSpaceKey,\n deviceKey,\n 'identityKey': this.identityKey,\n 'designation': AdmittedFeed.Designation.CONTROL,\n },\n }),\n await signer.createCredential({\n subject: dataFeedKey,\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n 'spaceKey': this.haloSpaceKey,\n deviceKey,\n 'identityKey': this.identityKey,\n 'designation': AdmittedFeed.Designation.DATA,\n },\n }),\n ].map((credential): FeedMessage.Payload => ({ credential: { credential } })),\n );\n\n return deviceCredential;\n }\n\n private _onFeedAdded = async (feed: FeedWrapper<any>) => {\n await this._edgeFeedReplicator!.addFeed(feed);\n };\n}\n","import * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\n//\n// Copyright 2022 DXOS.org\n//\nimport platform from 'platform';\n\nimport { Event } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { CredentialGenerator, createCredentialSignerWithKey, createDidFromIdentityKey } from '@dxos/credentials';\nimport { failUndefined } from '@dxos/debug';\nimport { type EdgeConnection, EdgeConnectionService } from '@dxos/edge-client';\nimport { type FeedStore, FeedStoreService } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type KeyringApi, KeyringApiService } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { Device, DeviceKind } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type IdentityRecord, type SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport {\n AdmittedFeed,\n type Credential,\n type DeviceProfileDocument,\n DeviceType,\n type ProfileDocument,\n} from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { Gossip, Presence } from '@dxos/teleport-extension-gossip';\nimport { Timeframe } from '@dxos/timeframe';\nimport { trace as Trace } from '@dxos/tracing';\nimport { deferFunction, isNode, isTauri } from '@dxos/util';\n\nimport { type IMetadataStore, IMetadataStoreService } from '../metadata';\nimport { type SpaceManager, SpaceManagerService, type SwarmIdentity } from '../space';\nimport { createAuthProvider } from './authenticator';\nimport { Identity } from './identity';\n\nconst DEVICE_PRESENCE_ANNOUNCE_INTERVAL = 10_000;\nconst DEVICE_PRESENCE_OFFLINE_TIMEOUT = 20_000;\n\ninterface ConstructSpaceProps {\n spaceRecord: SpaceMetadata;\n swarmIdentity: SwarmIdentity;\n identityKey: PublicKey;\n gossip: Gossip;\n}\n\nexport type JoinIdentityProps = {\n identityKey: PublicKey;\n deviceKey: PublicKey;\n haloSpaceKey: PublicKey;\n haloGenesisFeedKey: PublicKey;\n controlFeedKey: PublicKey;\n dataFeedKey: PublicKey;\n authorizedDeviceCredential: Credential;\n\n /**\n * Latest known timeframe for the control pipeline.\n * We will try to catch up to this timeframe before starting the data pipeline.\n */\n controlTimeframe?: Timeframe;\n // Custom device profile, merged with defaults, to be applied once the identity is accepted.\n deviceProfile?: DeviceProfileDocument;\n};\n\nexport type CreateIdentityOptions = {\n profile?: ProfileDocument;\n // device profile for device creating the identity.\n deviceProfile?: DeviceProfileDocument;\n};\n\nexport type IdentityManagerProps = {\n metadataStore: IMetadataStore;\n keyring: KeyringApi;\n feedStore: FeedStore<FeedMessage>;\n spaceManager: SpaceManager;\n edgeConnection?: EdgeConnection;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n devicePresenceAnnounceInterval?: number;\n devicePresenceOfflineTimeout?: number;\n};\n\n/**\n * Resolves the active identity when it becomes available.\n */\nexport type IdentityProvider = () => Identity;\n\n/**\n * Effect service tag for {@link IdentityProvider}.\n */\nexport class IdentityProviderService extends EffectContext.Tag('@dxos/client-services/IdentityProvider')<\n IdentityProviderService,\n IdentityProvider\n>() {}\n\n/**\n * Builds an {@link IdentityProvider} from an {@link IdentityManager}.\n */\nexport const identityProviderFromManager =\n (identityManager: IdentityManager): IdentityProvider =>\n () =>\n identityManager.identity ?? failUndefined();\n\n/**\n * Effect service tag for {@link IdentityManager}.\n */\nexport class IdentityManagerService extends EffectContext.Tag('@dxos/client-services/IdentityManager')<\n IdentityManagerService,\n IdentityManager\n>() {}\n\n// TODO(dmaretskyi): Rename: represents the peer's state machine.\nexport class IdentityManager {\n readonly stateUpdate = new Event();\n\n private readonly _metadataStore: IMetadataStore;\n private readonly _keyring: KeyringApi;\n private readonly _feedStore: FeedStore<FeedMessage>;\n private readonly _spaceManager: SpaceManager;\n private readonly _devicePresenceAnnounceInterval: number;\n private readonly _devicePresenceOfflineTimeout: number;\n private readonly _edgeConnection: EdgeConnection | undefined;\n private readonly _edgeFeatures: Runtime.Client.EdgeFeatures | undefined;\n\n private _identity?: Identity;\n\n // TODO(dmaretskyi): Perhaps this should take/generate the peerKey outside of an initialized identity.\n constructor(params: IdentityManagerProps) {\n this._metadataStore = params.metadataStore;\n this._keyring = params.keyring;\n this._feedStore = params.feedStore;\n this._spaceManager = params.spaceManager;\n this._edgeConnection = params.edgeConnection;\n this._edgeFeatures = params.edgeFeatures;\n this._devicePresenceAnnounceInterval = params.devicePresenceAnnounceInterval ?? DEVICE_PRESENCE_ANNOUNCE_INTERVAL;\n this._devicePresenceOfflineTimeout = params.devicePresenceOfflineTimeout ?? DEVICE_PRESENCE_OFFLINE_TIMEOUT;\n }\n\n get identity() {\n return this._identity;\n }\n\n @Trace.span({ showInBrowserTimeline: true })\n async open(ctx: Context): Promise<void> {\n log('opening identity manager');\n\n const identityRecord = this._metadataStore.getIdentityRecord();\n log('identity record', { identityRecord });\n if (identityRecord) {\n this._identity = await this._constructIdentity(identityRecord);\n await this._identity.open(ctx);\n await this._identity.ready();\n log.trace('dxos.halo.identity', {\n identityKey: identityRecord.identityKey,\n displayName: this._identity.profileDocument?.displayName,\n });\n\n this.stateUpdate.emit();\n }\n log('opened identity manager');\n }\n\n async close(ctx: Context): Promise<void> {\n await this._identity?.close(ctx);\n }\n\n async createIdentity({ profile, deviceProfile }: CreateIdentityOptions = {}, ctx?: Context): Promise<Identity> {\n invariant(!this._identity, 'Identity already exists.');\n log('creating identity...');\n\n const controlFeedKey = await this._keyring.createKey();\n const identityRecord: IdentityRecord = {\n identityKey: await this._keyring.createKey(),\n deviceKey: await this._keyring.createKey(),\n haloSpace: {\n key: await this._keyring.createKey(),\n genesisFeedKey: controlFeedKey,\n controlFeedKey,\n dataFeedKey: await this._keyring.createKey(),\n },\n };\n\n const identity = await this._constructIdentity(identityRecord);\n await identity.open(ctx ?? Context.default());\n\n {\n const generator = new CredentialGenerator(this._keyring, identityRecord.identityKey, identityRecord.deviceKey);\n invariant(identityRecord.haloSpace.genesisFeedKey, 'Genesis feed key is required.');\n invariant(identityRecord.haloSpace.dataFeedKey, 'Data feed key is required.');\n const credentials = [\n // Space genesis.\n ...(await generator.createSpaceGenesis(identityRecord.haloSpace.key, identityRecord.haloSpace.genesisFeedKey)),\n\n // Feed admission.\n await generator.createFeedAdmission(\n identityRecord.haloSpace.key,\n identityRecord.haloSpace.dataFeedKey,\n AdmittedFeed.Designation.DATA,\n ),\n ];\n\n if (profile) {\n credentials.push(await generator.createProfileCredential(profile));\n }\n\n // Device authorization (writes device chain).\n // NOTE: This credential is written last. This is a hack to make sure that display name is set before identity is \"ready\".\n credentials.push(await generator.createDeviceAuthorization(identityRecord.deviceKey));\n\n // Write device metadata to profile.\n credentials.push(\n await generator.createDeviceProfile({\n ...this.createDefaultDeviceProfile(),\n ...deviceProfile,\n }),\n );\n for (const credential of credentials) {\n await identity.controlPipeline.writer.write({\n credential: { credential },\n });\n }\n }\n\n await this._metadataStore.setIdentityRecord(identityRecord);\n this._identity = identity;\n await this._identity.ready();\n log.trace('dxos.halo.identity', {\n identityKey: identityRecord.identityKey,\n displayName: this._identity.profileDocument?.displayName,\n });\n this.stateUpdate.emit();\n\n log('created identity', {\n identityKey: identity.identityKey,\n deviceKey: identity.deviceKey,\n profile: identity.profileDocument,\n });\n\n return identity;\n }\n\n createDefaultDeviceProfile(): DeviceProfileDocument {\n // See TODOs in credentials.proto.\n let type: DeviceType;\n if (isNode()) {\n type = DeviceType.AGENT;\n } else {\n if (platform.name?.startsWith('iOS') || platform.name?.startsWith('Android')) {\n type = DeviceType.MOBILE;\n } else if (isTauri() || !platform.name) {\n // Tauri's __TAURI__ global isn't available in web workers. Fallback: WKWebView\n // (Tauri on macOS) reports null for platform.name; all standard browsers don't.\n type = DeviceType.NATIVE;\n } else {\n type = DeviceType.BROWSER;\n }\n }\n\n const os = platform.os?.family === 'OS X' ? 'macOS' : platform.os?.family;\n const name = type === DeviceType.NATIVE || type === DeviceType.MOBILE ? 'App' : platform.name;\n\n return {\n type,\n platform: name,\n platformVersion: platform.version,\n architecture: typeof platform.os?.architecture === 'number' ? String(platform.os.architecture) : undefined,\n os,\n osVersion: platform.os?.version,\n };\n }\n\n /**\n * Prepare an identity object as the first step of acceptIdentity flow.\n */\n async prepareIdentity(params: JoinIdentityProps, ctx?: Context) {\n log('accepting identity', { params });\n invariant(!this._identity, 'Identity already exists.');\n\n const identityRecord: IdentityRecord = {\n identityKey: params.identityKey,\n deviceKey: params.deviceKey,\n haloSpace: {\n key: params.haloSpaceKey,\n genesisFeedKey: params.haloGenesisFeedKey,\n controlFeedKey: params.controlFeedKey,\n dataFeedKey: params.dataFeedKey,\n controlTimeframe: params.controlTimeframe,\n },\n };\n const identity = await this._constructIdentity(identityRecord);\n await identity.open(ctx ?? Context.default());\n return { identity, identityRecord };\n }\n\n /**\n * Accept an existing identity. Expects its device key to be authorized (now or later).\n */\n public async acceptIdentity(\n identity: Identity,\n identityRecord: IdentityRecord,\n profile?: DeviceProfileDocument,\n ): Promise<void> {\n this._identity = identity;\n\n // Identity becomes ready after device chain is replicated. Wait for it before storing the record.\n await this._identity.ready();\n await this._metadataStore.setIdentityRecord(identityRecord);\n\n log.trace('dxos.halo.identity', {\n identityKey: this._identity!.identityKey,\n displayName: this._identity.profileDocument?.displayName,\n });\n\n await this.updateDeviceProfile({\n ...this.createDefaultDeviceProfile(),\n ...profile,\n });\n this.stateUpdate.emit();\n\n log('accepted identity', { identityKey: identity.identityKey, deviceKey: identity.deviceKey });\n }\n\n /**\n * Update the profile document of an existing identity.\n */\n async updateProfile(profile: ProfileDocument): Promise<ProfileDocument> {\n invariant(this._identity, 'Identity not initialized.');\n // TODO(wittjosiah): Use CredentialGenerator.\n const credential = await this._identity.getIdentityCredentialSigner().createCredential({\n subject: this._identity.identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.IdentityProfile',\n profile,\n },\n });\n\n const receipt = await this._identity.controlPipeline.writer.write({ credential: { credential } });\n await this._identity.controlPipeline.state.waitUntilTimeframe(new Timeframe([[receipt.feedKey, receipt.seq]]));\n this.stateUpdate.emit();\n return profile;\n }\n\n async updateDeviceProfile(profile: DeviceProfileDocument): Promise<Device> {\n invariant(this._identity, 'Identity not initialized.');\n\n // TODO(nf): CredentialGenerator doesn't work when not updating own device.\n // const generator = new CredentialGenerator(this._keyring, this._identity.identityKey, this._identity.deviceKey);\n // const credential = await generator.createDeviceProfile(profile);\n\n const credential = await this._identity.getDeviceCredentialSigner().createCredential({\n subject: this._identity.deviceKey,\n assertion: {\n '@type': 'dxos.halo.credentials.DeviceProfile',\n profile,\n },\n });\n\n const receipt = await this._identity.controlPipeline.writer.write({ credential: { credential } });\n await this._identity.controlPipeline.state.waitUntilTimeframe(new Timeframe([[receipt.feedKey, receipt.seq]]));\n this.stateUpdate.emit();\n return {\n deviceKey: this._identity.deviceKey,\n kind: DeviceKind.CURRENT,\n presence: Device.PresenceState.ONLINE,\n profile,\n };\n }\n\n private async _constructIdentity(identityRecord: IdentityRecord): Promise<Identity> {\n invariant(!this._identity);\n log('constructing identity', { identityRecord });\n\n const gossip = new Gossip({\n localPeerId: identityRecord.deviceKey,\n });\n const presence = new Presence({\n announceInterval: this._devicePresenceAnnounceInterval,\n offlineTimeout: this._devicePresenceOfflineTimeout,\n identityKey: identityRecord.deviceKey,\n gossip,\n });\n\n // Must be created before the space so the feeds are writable.\n invariant(identityRecord.haloSpace.controlFeedKey);\n const controlFeed = await this._feedStore.openFeed(identityRecord.haloSpace.controlFeedKey, {\n writable: true,\n });\n invariant(identityRecord.haloSpace.dataFeedKey);\n const dataFeed = await this._feedStore.openFeed(identityRecord.haloSpace.dataFeedKey, {\n writable: true,\n sparse: true,\n });\n\n const space = await this._constructSpace({\n spaceRecord: identityRecord.haloSpace,\n swarmIdentity: {\n identityKey: identityRecord.identityKey,\n peerKey: identityRecord.deviceKey,\n credentialProvider: createAuthProvider(createCredentialSignerWithKey(this._keyring, identityRecord.deviceKey)),\n credentialAuthenticator: deferFunction(() => identity.authVerifier.verifier),\n },\n gossip,\n identityKey: identityRecord.identityKey,\n });\n await space.setControlFeed(controlFeed);\n await space.setDataFeed(dataFeed);\n\n const did = await createDidFromIdentityKey(identityRecord.identityKey);\n const identity: Identity = new Identity({\n space,\n presence,\n signer: this._keyring,\n did,\n identityKey: identityRecord.identityKey,\n deviceKey: identityRecord.deviceKey,\n edgeConnection: this._edgeConnection,\n edgeFeatures: this._edgeFeatures,\n });\n log('done', { identityKey: identityRecord.identityKey });\n\n // TODO(mykola): Set new timeframe on a write to a feed.\n if (identityRecord.haloSpace.controlTimeframe) {\n identity.controlPipeline.state.setTargetTimeframe(identityRecord.haloSpace.controlTimeframe);\n }\n\n identity.stateUpdate.on(() => this.stateUpdate.emit());\n return identity;\n }\n\n private async _constructSpace({ spaceRecord, swarmIdentity, identityKey, gossip }: ConstructSpaceProps) {\n return this._spaceManager.constructSpace({\n metadata: {\n key: spaceRecord.key,\n genesisFeedKey: spaceRecord.genesisFeedKey,\n },\n swarmIdentity,\n onAuthorizedConnection: (session) => {\n session.addExtension(\n 'dxos.mesh.teleport.gossip',\n gossip.createExtension({ remotePeerId: session.remotePeerId }),\n );\n },\n onAuthFailure: () => {\n log.warn('auth failure');\n },\n memberKey: identityKey,\n onDelegatedInvitationStatusChange: async () => {}, // TODO: will be used for recovery keys\n onMemberRolesChanged: async () => {}, // TODO: will be used for device revocation\n });\n }\n}\n\nexport type IdentityManagerLayerOptions = Pick<\n IdentityManagerProps,\n 'devicePresenceAnnounceInterval' | 'devicePresenceOfflineTimeout' | 'edgeFeatures'\n>;\n\n/**\n * Effect Layer constructing an {@link IdentityManager} from ambient service dependencies.\n */\nexport const IdentityManagerLayer = (\n options: IdentityManagerLayerOptions = {},\n): Layer.Layer<\n IdentityManagerService,\n never,\n IMetadataStoreService | KeyringApiService | FeedStoreService | SpaceManagerService\n> =>\n Layer.effect(\n IdentityManagerService,\n Effect.gen(function* () {\n const metadataStore = yield* IMetadataStoreService;\n const keyring = yield* KeyringApiService;\n const feedStore = yield* FeedStoreService;\n const spaceManager = yield* SpaceManagerService;\n const edgeConnection = yield* Effect.serviceOption(EdgeConnectionService);\n return new IdentityManager({\n metadataStore,\n keyring,\n feedStore,\n spaceManager,\n edgeConnection: Option.getOrUndefined(edgeConnection),\n ...options,\n });\n }),\n );\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { Context, Resource } from '@dxos/context';\nimport { createCredential, signPresentation } from '@dxos/credentials';\nimport { invariant } from '@dxos/invariant';\nimport { type KeyringApi } from '@dxos/keyring';\nimport {\n type CreateIdentityRequest,\n type CreateRecoveryCredentialRequest,\n type CreateRecoveryCredentialResponse,\n type Identity as IdentityProto,\n type QueryIdentityResponse,\n type RecoverIdentityRequest,\n type RequestRecoveryChallengeResponse,\n type SignPresentationRequest,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type Credential, type Presentation, type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type IdentityService } from '@dxos/protocols/rpc';\n\nimport { type Identity } from './identity';\nimport { type CreateIdentityOptions, type IdentityManager } from './identity-manager';\nimport { type EdgeIdentityRecoveryManager } from './identity-recovery-manager';\n\nexport class IdentityServiceImpl extends Resource implements IdentityService.Handlers {\n 'constructor'(\n private readonly _identityManager: IdentityManager,\n private readonly _recoveryManager: EdgeIdentityRecoveryManager,\n private readonly _keyring: KeyringApi,\n private readonly _createIdentity: (params: CreateIdentityOptions, ctx?: Context) => Promise<Identity>,\n private readonly _onProfileUpdate?: (profile: ProfileDocument | undefined) => Promise<void>,\n ) {\n super();\n }\n\n ['IdentityService.createIdentity'](request: CreateIdentityRequest): Effect.Effect<IdentityProto, Error> {\n return Effect.tryPromise({\n try: async () => {\n const ctx = Context.default();\n await this._createIdentity({ profile: request.profile, deviceProfile: request.deviceProfile }, ctx);\n return this._getIdentity()!;\n },\n catch: (error) => error as Error,\n });\n }\n\n ['IdentityService.queryIdentity'](): EffectStream.Stream<QueryIdentityResponse, Error> {\n return EffectStream.async<QueryIdentityResponse, Error>((emit) => {\n // Omit `identity` entirely when absent: an explicit `undefined` would still drive the optional\n // protobuf codec, which dereferences the missing message and throws.\n const emitNext = () => {\n const identity = this._getIdentity();\n void emit.single(identity ? { identity } : {});\n };\n\n emitNext();\n const unsubscribe = this._identityManager.stateUpdate.on(emitNext);\n return Effect.sync(() => unsubscribe());\n });\n }\n\n ['IdentityService.updateProfile'](profile: ProfileDocument): Effect.Effect<IdentityProto, Error> {\n return Effect.tryPromise({\n try: async () => {\n invariant(this._identityManager.identity, 'Identity not initialized.');\n await this._identityManager.updateProfile(profile);\n await this._onProfileUpdate?.(this._identityManager.identity.profileDocument);\n return this._getIdentity()!;\n },\n catch: (error) => error as Error,\n });\n }\n\n ['IdentityService.createRecoveryCredential'](\n request: CreateRecoveryCredentialRequest,\n ): Effect.Effect<CreateRecoveryCredentialResponse, Error> {\n return Effect.tryPromise({\n try: async () => this._recoveryManager.createRecoveryCredential(request),\n catch: (error) => error as Error,\n });\n }\n\n ['IdentityService.requestRecoveryChallenge'](): Effect.Effect<RequestRecoveryChallengeResponse, Error> {\n return Effect.tryPromise({\n try: async () => this._recoveryManager.requestRecoveryChallenge(Context.default()),\n catch: (error) => error as Error,\n });\n }\n\n ['IdentityService.recoverIdentity'](request: RecoverIdentityRequest): Effect.Effect<IdentityProto, Error> {\n return Effect.tryPromise({\n try: async () => {\n const ctx = Context.default();\n if (request.recoveryCode) {\n await this._recoveryManager.recoverIdentity(ctx, { recoveryCode: request.recoveryCode });\n } else if (request.external) {\n await this._recoveryManager.recoverIdentityWithExternalSignature(ctx, request.external);\n } else if (request.token) {\n await this._recoveryManager.recoverIdentityWithToken(ctx, { token: request.token });\n } else if (request.recoveryProof) {\n await this._recoveryManager.recoverIdentityWithToken(ctx, { recoveryProof: request.recoveryProof });\n } else {\n throw new Error('Invalid request.');\n }\n\n return this._getIdentity()!;\n },\n catch: (error) => error as Error,\n });\n }\n\n // TODO(burdon): Rename createPresentation?\n ['IdentityService.signPresentation'](request: SignPresentationRequest): Effect.Effect<Presentation, Error> {\n return Effect.tryPromise({\n try: async () => {\n const { presentation, nonce } = request;\n invariant(this._identityManager.identity, 'Identity not initialized.');\n\n return await signPresentation({\n presentation,\n signer: this._keyring,\n signerKey: this._identityManager.identity.deviceKey,\n chain: this._identityManager.identity.deviceCredentialChain,\n nonce,\n });\n },\n catch: (error) => error as Error,\n });\n }\n\n ['IdentityService.createAuthCredential'](): Effect.Effect<Credential, Error> {\n return Effect.tryPromise({\n try: async () => {\n const identity = this._identityManager.identity;\n\n invariant(identity, 'Identity not initialized.');\n\n return await createCredential({\n assertion: { '@type': 'dxos.halo.credentials.Auth' },\n issuer: identity.identityKey,\n subject: identity.identityKey,\n chain: identity.deviceCredentialChain,\n signingKey: identity.deviceKey,\n signer: this._keyring,\n });\n },\n catch: (error) => error as Error,\n });\n }\n\n private '_getIdentity'(): IdentityProto | undefined {\n if (!this._identityManager.identity) {\n return undefined;\n }\n\n return {\n did: this._identityManager.identity.did,\n identityKey: this._identityManager.identity.identityKey,\n spaceKey: this._identityManager.identity.space.key,\n profile: this._identityManager.identity.profileDocument,\n };\n }\n}\n","//\n// Copyright 2023 DXOS.org\n//\n\nexport type * from './resource-lock';\nexport * from '#locks-platform';\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\n\nimport { DeferredTask, Event, scheduleTask, synchronized } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { Resource } from '@dxos/context';\nimport { type EdgeHttpClient, EdgeHttpClientService } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { EdgeAgentStatus, EdgeCallFailedError } from '@dxos/protocols';\nimport { SpaceState } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { EdgeReplicationSetting } from '@dxos/protocols/proto/dxos/echo/metadata';\n\nimport { type Identity, type IdentityProvider, IdentityProviderService } from '../identity';\nimport { type DataSpaceManager, DataSpaceManagerService } from '../spaces';\nconst AGENT_STATUS_QUERY_RETRY_INTERVAL = 5000;\nconst AGENT_STATUS_QUERY_RETRY_JITTER = 1000;\nconst AGENT_FEED_ADDED_CHECK_INTERVAL_MS = 3000;\n\nexport type EdgeAgentManagerConfig = {};\n\n/**\n * Effect service tag for {@link EdgeAgentManager}.\n */\nexport class EdgeAgentManagerService extends EffectContext.Tag('@dxos/client-services/EdgeAgentManager')<\n EdgeAgentManagerService,\n EdgeAgentManager\n>() {}\n\nexport class EdgeAgentManager extends Resource {\n public agentStatusChanged = new Event<EdgeAgentStatus>();\n\n private _agentDeviceKey: PublicKey | undefined;\n private _agentStatus: EdgeAgentStatus | undefined;\n\n private _lastKnownDeviceCount = 0;\n\n private _fetchAgentStatusTask: DeferredTask | undefined;\n\n constructor(\n private readonly _edgeFeatures: Runtime.Client.EdgeFeatures | undefined,\n private readonly _edgeHttpClient: EdgeHttpClient | undefined,\n private readonly _dataSpaceManager: DataSpaceManager,\n private readonly _identityProvider: IdentityProvider,\n ) {\n super();\n }\n\n private get identity(): Identity {\n return this._identityProvider();\n }\n\n public get agentStatus(): EdgeAgentStatus | undefined {\n return this._agentStatus;\n }\n\n public get agentExists() {\n return this._agentStatus && this._agentStatus !== EdgeAgentStatus.NOT_FOUND;\n }\n\n @synchronized\n public async createAgent(ctx: Context): Promise<void> {\n invariant(this.isOpen);\n invariant(this._edgeHttpClient);\n invariant(this._edgeFeatures?.agents);\n\n const response = await this._edgeHttpClient.createAgent(ctx, {\n identityDid: this.identity.did,\n haloSpaceId: this.identity.haloSpaceId,\n haloSpaceKey: this.identity.haloSpaceKey.toHex(),\n });\n\n const deviceKey = PublicKey.fromHex(response.deviceKey);\n\n if (await this.identity.authorizedDeviceKeys.has(deviceKey)) {\n log.info('agent was already added to HALO, ignoring response', { response });\n this._updateStatus(EdgeAgentStatus.ACTIVE, deviceKey);\n return;\n }\n\n await this.identity.admitDevice({\n deviceKey,\n controlFeedKey: PublicKey.fromHex(response.feedKey),\n // TODO: agents don't have data feed, should be removed\n dataFeedKey: PublicKey.random(),\n });\n\n log('agent created', response);\n\n this._updateStatus(EdgeAgentStatus.ACTIVE, deviceKey);\n }\n\n protected override async _open(): Promise<void> {\n const isEnabled = this._edgeHttpClient && this._edgeFeatures?.agents;\n\n log('edge agent manager open', { isEnabled });\n\n if (!isEnabled) {\n return;\n }\n\n this._lastKnownDeviceCount = this.identity.authorizedDeviceKeys.size;\n this._fetchAgentStatusTask = new DeferredTask(this._ctx, async () => {\n await this._fetchAgentStatus(this._ctx);\n });\n this._fetchAgentStatusTask.schedule();\n\n this._dataSpaceManager.updated.on(this._ctx, () => {\n if (this._agentDeviceKey) {\n this._ensureAgentIsInSpaces(this._agentDeviceKey);\n }\n });\n\n this.identity.stateUpdate.on(this._ctx, () => {\n const maybeAgentWasCreated = this.identity.authorizedDeviceKeys.size > this._lastKnownDeviceCount;\n if (this.agentExists || !maybeAgentWasCreated) {\n return;\n }\n this._lastKnownDeviceCount = this.identity.authorizedDeviceKeys.size;\n this._fetchAgentStatusTask?.schedule();\n });\n }\n\n protected override async _close(): Promise<void> {\n this._fetchAgentStatusTask = undefined;\n this._lastKnownDeviceCount = 0;\n }\n\n protected async _fetchAgentStatus(ctx: Context): Promise<void> {\n invariant(this._edgeHttpClient);\n try {\n log('fetching agent status');\n const { agent } = await this._edgeHttpClient.getAgentStatus(ctx, {\n ownerIdentityDid: this.identity.did,\n });\n const wasAgentCreatedDuringQuery = this._agentStatus === EdgeAgentStatus.ACTIVE;\n if (!wasAgentCreatedDuringQuery) {\n const deviceKey = agent.deviceKey ? PublicKey.fromHex(agent.deviceKey) : undefined;\n this._updateStatus(agent.status, deviceKey);\n }\n } catch (err) {\n if (err instanceof EdgeCallFailedError) {\n if (!err.isRetryable) {\n log.warn('non retryable error on agent status fetch attempt', { err });\n return;\n }\n }\n const retryAfterMs = AGENT_STATUS_QUERY_RETRY_INTERVAL + Math.random() * AGENT_STATUS_QUERY_RETRY_JITTER;\n log.info('agent status fetching failed', { err, retryAfterMs });\n scheduleTask(this._ctx, () => this._fetchAgentStatusTask?.schedule(), retryAfterMs);\n }\n }\n\n /**\n * We don't want notarization plugin to always actively poll edge looking for credentials to notarize,\n * because most of the time we'll be getting an empty response.\n * Instead, we stay in active polling mode while there are spaces where we don't see our agent's feed.\n */\n protected _ensureAgentIsInSpaces(agentDeviceKey: PublicKey): void {\n let activePollingEnabled = false;\n for (const space of this._dataSpaceManager.spaces.values()) {\n if (space.getEdgeReplicationSetting() === EdgeReplicationSetting.DISABLED) {\n space.notarizationPlugin.setActiveEdgePollingEnabled(false);\n continue;\n }\n if ([SpaceState.SPACE_INACTIVE, SpaceState.SPACE_CLOSED].includes(space.state)) {\n space.notarizationPlugin.setActiveEdgePollingEnabled(false);\n continue;\n }\n const agentFeedNeedsNotarization = ![...space.inner.spaceState.feeds.values()].some((feed) =>\n feed.assertion.deviceKey.equals(agentDeviceKey),\n );\n space.notarizationPlugin.setActiveEdgePollingEnabled(agentFeedNeedsNotarization);\n activePollingEnabled = activePollingEnabled || agentFeedNeedsNotarization;\n\n log.verbose('set active edge polling', { enabled: agentFeedNeedsNotarization, spaceId: space.id });\n }\n\n if (activePollingEnabled) {\n // Check again to see if active edge polling can be disabled (agent feed is notarized in all the spaces)\n scheduleTask(this._ctx, () => this._ensureAgentIsInSpaces(agentDeviceKey), AGENT_FEED_ADDED_CHECK_INTERVAL_MS);\n }\n }\n\n private _updateStatus(status: EdgeAgentStatus, deviceKey: PublicKey | undefined): void {\n this._agentStatus = status;\n this._agentDeviceKey = deviceKey;\n this.agentStatusChanged.emit(status);\n if (deviceKey) {\n this._ensureAgentIsInSpaces(deviceKey);\n }\n log.verbose('agent status update', { status });\n }\n}\n\nexport type EdgeAgentManagerLayerOptions = {\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n};\n\n/**\n * Effect Layer constructing a dormant {@link EdgeAgentManager}.\n */\nexport const EdgeAgentManagerLayer = (\n options: EdgeAgentManagerLayerOptions = {},\n): Layer.Layer<EdgeAgentManagerService, never, DataSpaceManagerService | IdentityProviderService> =>\n Layer.effect(\n EdgeAgentManagerService,\n Effect.gen(function* () {\n const dataSpaceManager = yield* DataSpaceManagerService;\n const identityProvider = yield* IdentityProviderService;\n const edgeHttpClient = yield* Effect.serviceOption(EdgeHttpClientService);\n return new EdgeAgentManager(\n options.edgeFeatures,\n Option.getOrUndefined(edgeHttpClient),\n dataSpaceManager,\n identityProvider,\n );\n }),\n );\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { Context } from '@dxos/context';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { EdgeAgentStatus } from '@dxos/protocols';\nimport {\n EdgeStatus,\n QueryAgentStatusResponse,\n type QueryEdgeStatusResponse,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type EdgeAgentService } from '@dxos/protocols/rpc';\n\nimport { type EdgeAgentManager } from './edge-agent-manager';\n\n// TODO(wittjosiah): This service is not currently exposed on the client api, it must be called directly.\nexport class EdgeAgentServiceImpl implements EdgeAgentService.Handlers {\n 'constructor'(\n private readonly _agentManagerProvider: () => Promise<EdgeAgentManager>,\n private readonly _edgeConnection?: EdgeConnection,\n ) {}\n\n // TODO(mykola): Reconcile with NetworkService.queryStatus.\n ['EdgeAgentService.queryEdgeStatus'](): EffectStream.Stream<QueryEdgeStatusResponse, Error> {\n return EffectStream.async<QueryEdgeStatusResponse, Error>((emit) => {\n const ctx = Context.default();\n const update = () => {\n void emit.single({\n status: this._edgeConnection?.status ?? {\n state: EdgeStatus.ConnectionState.NOT_CONNECTED,\n rtt: 0,\n uptime: 0,\n rateBytesUp: 0,\n rateBytesDown: 0,\n messagesSent: 0,\n messagesReceived: 0,\n },\n });\n };\n\n this._edgeConnection?.statusChanged.on(ctx, update);\n update();\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['EdgeAgentService.createAgent'](): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => (await this._agentManagerProvider()).createAgent(Context.default()),\n catch: (error) => error as Error,\n });\n }\n\n ['EdgeAgentService.queryAgentStatus'](): EffectStream.Stream<QueryAgentStatusResponse, Error> {\n return EffectStream.async<QueryAgentStatusResponse, Error>((emit) => {\n const ctx = Context.default();\n void emit.single({ status: QueryAgentStatusResponse.AgentStatus.UNKNOWN });\n void this._agentManagerProvider().then((agentManager) => {\n void emit.single({ status: mapStatus(agentManager.agentStatus) });\n agentManager.agentStatusChanged.on(ctx, (newStatus) => {\n void emit.single({ status: mapStatus(newStatus) });\n });\n });\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n}\n\nconst mapStatus = (agentStatus: EdgeAgentStatus | undefined): QueryAgentStatusResponse.AgentStatus => {\n switch (agentStatus) {\n case EdgeAgentStatus.ACTIVE:\n return QueryAgentStatusResponse.AgentStatus.ACTIVE;\n case EdgeAgentStatus.INACTIVE:\n return QueryAgentStatusResponse.AgentStatus.INACTIVE;\n case EdgeAgentStatus.NOT_FOUND:\n return QueryAgentStatusResponse.AgentStatus.NOT_FOUND;\n case undefined:\n return QueryAgentStatusResponse.AgentStatus.UNKNOWN;\n }\n};\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { SubscriptionList } from '@dxos/async';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { Device, DeviceKind, EdgeStatus, type QueryDevicesResponse } from '@dxos/protocols/proto/dxos/client/services';\nimport { type DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type DevicesService } from '@dxos/protocols/rpc';\n\nimport { type IdentityManager } from '../identity';\n\nexport class DevicesServiceImpl implements DevicesService.Handlers {\n 'constructor'(\n private readonly _identityManager: IdentityManager,\n private readonly _edgeConnection?: EdgeConnection,\n ) {}\n\n ['DevicesService.updateDevice'](request: DeviceProfileDocument): Effect.Effect<Device, Error> {\n return Effect.tryPromise({\n try: async () => this._identityManager.updateDeviceProfile(request),\n catch: (error) => error as Error,\n });\n }\n\n ['DevicesService.queryDevices'](): EffectStream.Stream<QueryDevicesResponse, Error> {\n return EffectStream.async<QueryDevicesResponse, Error>((emit) => {\n const update = () => {\n const deviceKeys = this._identityManager.identity?.authorizedDeviceKeys;\n if (!deviceKeys) {\n void emit.single({ devices: [] });\n } else {\n invariant(this._identityManager.identity?.presence, 'presence not present');\n const peers = this._identityManager.identity.presence.getPeersOnline();\n void emit.single({\n devices: Array.from(deviceKeys.entries()).map(([key, profile]) => {\n const isMe = this._identityManager.identity?.deviceKey.equals(key);\n let presence;\n if (isMe) {\n presence = Device.PresenceState.ONLINE;\n } else if (profile.os?.toUpperCase() === 'EDGE') {\n presence =\n this._edgeConnection?.status.state === EdgeStatus.ConnectionState.CONNECTED\n ? Device.PresenceState.ONLINE\n : Device.PresenceState.OFFLINE;\n } else {\n presence = peers.some((peer) => peer.identityKey.equals(key))\n ? Device.PresenceState.ONLINE\n : Device.PresenceState.OFFLINE;\n }\n\n return {\n deviceKey: key,\n kind: this._identityManager.identity?.deviceKey.equals(key) ? DeviceKind.CURRENT : DeviceKind.TRUSTED,\n profile,\n presence,\n };\n }),\n });\n }\n };\n\n let identitySubscribed = false;\n let presenceSubscribed = false;\n const subscribeIdentity = () => {\n if (!identitySubscribed) {\n this._identityManager.identity?.stateUpdate.on(() => {\n update();\n });\n identitySubscribed = true;\n }\n };\n\n const subscribePresence = () => {\n if (!presenceSubscribed) {\n this._identityManager.identity?.presence?.updated.on(() => {\n update();\n });\n presenceSubscribed = true;\n }\n };\n\n const subscriptions = new SubscriptionList();\n\n if (this._identityManager.identity) {\n subscribeIdentity();\n subscribePresence();\n }\n\n subscriptions.add(\n this._identityManager.stateUpdate.on(() => {\n update();\n\n if (this._identityManager.identity) {\n subscribeIdentity();\n subscribePresence();\n }\n }),\n );\n\n update();\n\n return Effect.sync(() => subscriptions.clear());\n });\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { SubscriptionList, UpdateScheduler, scheduleTask } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { type MemberInfo } from '@dxos/credentials';\nimport { PublicKey } from '@dxos/keys';\nimport { type Contact, type ContactBook } from '@dxos/protocols/proto/dxos/client/services';\nimport { type ContactsService } from '@dxos/protocols/rpc';\nimport { ComplexMap, ComplexSet } from '@dxos/util';\n\nimport { type SpaceManager } from '../space';\nimport { type DataSpaceManager } from '../spaces';\nimport { type IdentityManager } from './identity-manager';\n\nexport class ContactsServiceImpl implements ContactsService.Handlers {\n 'constructor'(\n private readonly _identityManager: IdentityManager,\n private readonly _spaceManager: SpaceManager,\n private readonly _dataSpaceManagerProvider: () => Promise<DataSpaceManager>,\n ) {}\n\n ['ContactsService.getContacts'](): Effect.Effect<ContactBook, Error> {\n return Effect.sync(() => this.#getContacts());\n }\n\n ['ContactsService.queryContacts'](): EffectStream.Stream<ContactBook, Error> {\n const subscribedSpaceKeySet = new ComplexSet(PublicKey.hash);\n return EffectStream.async<ContactBook, Error>((emit) => {\n const ctx = Context.default();\n const pushUpdateTask = new UpdateScheduler(\n ctx,\n async () => {\n void emit.single(this.#getContacts());\n },\n { maxFrequency: 2 },\n );\n scheduleTask(ctx, async () => {\n const subscriptions = new SubscriptionList();\n ctx.onDispose(() => subscriptions.clear());\n const subscribeToSpaceAndUpdate = () => {\n const oldSetSize = subscribedSpaceKeySet.size;\n for (const space of this._spaceManager.spaces.values()) {\n if (!subscribedSpaceKeySet.has(space.key)) {\n subscriptions.add(space.stateUpdate.on(ctx, () => pushUpdateTask.trigger()));\n subscribedSpaceKeySet.add(space.key);\n }\n }\n if (oldSetSize !== subscribedSpaceKeySet.size) {\n pushUpdateTask.trigger();\n }\n };\n const unsubscribe = (await this._dataSpaceManagerProvider()).updated.on(ctx, subscribeToSpaceAndUpdate);\n ctx.onDispose(unsubscribe);\n subscribeToSpaceAndUpdate();\n });\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n #getContacts(): ContactBook {\n const identity = this._identityManager.identity;\n if (identity == null) {\n return { contacts: [] };\n }\n const contacts = [...this._spaceManager.spaces.values()]\n .flatMap((s) => [...s.spaceState.members.values()].map((m) => [s.key, m]))\n .reduce((acc, v) => {\n const [spaceKey, memberInfo] = v as [PublicKey, MemberInfo];\n if (memberInfo.key.equals(identity.identityKey)) {\n return acc;\n }\n const existing = acc.get(memberInfo.key);\n if (existing != null) {\n existing.profile ??= memberInfo.profile;\n existing.commonSpaces?.push(spaceKey);\n } else {\n acc.set(memberInfo.key, {\n identityKey: memberInfo.key,\n profile: memberInfo.profile,\n commonSpaces: [spaceKey],\n });\n }\n return acc;\n }, new ComplexMap<PublicKey, Contact>(PublicKey.hash));\n return {\n contacts: [...contacts.values()],\n };\n }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\n\nimport { type Context } from '@dxos/context';\nimport { generateSeedPhrase, keyPairFromSeedPhrase } from '@dxos/credentials';\nimport { sign } from '@dxos/crypto';\nimport { type EdgeHttpClient, EdgeHttpClientService } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { type KeyringApi, KeyringApiService } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n EdgeAuthChallengeError,\n type RecoverIdentityRequest as EdgeRecoverIdentityRequest,\n type RecoverIdentityResponseBody,\n} from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport {\n type CreateRecoveryCredentialRequest,\n type RecoverIdentityRequest,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { Timeframe } from '@dxos/timeframe';\n\nimport { type Identity } from './identity';\nimport { IdentityManagerService, type JoinIdentityProps } from './identity-manager';\n\n/**\n * Effect service tag for {@link EdgeIdentityRecoveryManager}.\n */\nexport class EdgeIdentityRecoveryManagerService extends EffectContext.Tag(\n '@dxos/client-services/EdgeIdentityRecoveryManager',\n)<EdgeIdentityRecoveryManagerService, EdgeIdentityRecoveryManager>() {}\n\nexport type AcceptRecoveredIdentity = (params: JoinIdentityProps) => Promise<Identity>;\n\nexport class EdgeIdentityRecoveryManager {\n private _acceptRecoveredIdentity?: AcceptRecoveredIdentity;\n\n constructor(\n private readonly _keyring: KeyringApi,\n private readonly _edgeClient: EdgeHttpClient | undefined,\n private readonly _identityProvider: () => Identity | undefined,\n ) {}\n\n /**\n * Wires identity acceptance after the composing stack is fully constructed.\n */\n setAcceptRecoveredIdentity(acceptRecoveredIdentity: AcceptRecoveredIdentity): void {\n this._acceptRecoveredIdentity = acceptRecoveredIdentity;\n }\n\n public async createRecoveryCredential({\n data,\n }: CreateRecoveryCredentialRequest): Promise<{ recoveryCode: string | undefined }> {\n const identity = this._identityProvider();\n invariant(identity);\n\n let recoveryKey: PublicKey;\n let lookupKey: PublicKey;\n let algorithm: string;\n let recoveryCode: string | undefined;\n if (data) {\n recoveryKey = data.recoveryKey;\n lookupKey = data.lookupKey;\n algorithm = data.algorithm;\n } else {\n recoveryCode = generateSeedPhrase();\n const keypair = keyPairFromSeedPhrase(recoveryCode);\n recoveryKey = PublicKey.from(keypair.publicKey);\n lookupKey = PublicKey.from(keypair.publicKey);\n algorithm = 'ED25519';\n }\n\n const identityKey = identity.identityKey;\n const credential = await identity.getIdentityCredentialSigner().createCredential({\n subject: identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.IdentityRecovery',\n recoveryKey,\n identityKey,\n algorithm,\n lookupKey,\n },\n });\n\n const receipt = await identity.controlPipeline.writer.write({ credential: { credential } });\n await identity.controlPipeline.state.waitUntilTimeframe(new Timeframe([[receipt.feedKey, receipt.seq]]));\n\n return { recoveryCode };\n }\n\n public async requestRecoveryChallenge(ctx: Context) {\n invariant(this._edgeClient, 'Not connected to EDGE.');\n\n const deviceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const request: EdgeRecoverIdentityRequest = {\n deviceKey: deviceKey.toHex(),\n controlFeedKey: controlFeedKey.toHex(),\n };\n\n try {\n await this._edgeClient.recoverIdentity(ctx, request);\n throw new Error('No challenge received.');\n } catch (error: any) {\n if (!(error instanceof EdgeAuthChallengeError)) {\n throw error;\n }\n return {\n deviceKey,\n controlFeedKey,\n challenge: error.challenge,\n };\n }\n }\n\n public async recoverIdentityWithExternalSignature(\n ctx: Context,\n {\n lookupKey,\n deviceKey,\n controlFeedKey,\n signature,\n clientDataJson,\n authenticatorData,\n }: RecoverIdentityRequest.ExternalSignature,\n ): Promise<void> {\n invariant(this._edgeClient, 'Not connected to EDGE.');\n\n const request: EdgeRecoverIdentityRequest = {\n lookupKey: lookupKey.toHex(),\n deviceKey: deviceKey.toHex(),\n controlFeedKey: controlFeedKey.toHex(),\n signature:\n clientDataJson && authenticatorData\n ? {\n signature: Buffer.from(signature).toString('base64'),\n clientDataJson: Buffer.from(clientDataJson).toString('base64'),\n authenticatorData: Buffer.from(authenticatorData).toString('base64'),\n }\n : Buffer.from(signature).toString('base64'),\n };\n\n const response = await this._edgeClient.recoverIdentity(ctx, request);\n\n await this.#acceptRecoveredIdentity({\n authorizedDeviceCredential: decodeCredential(response.deviceAuthCredential),\n haloGenesisFeedKey: PublicKey.fromHex(response.genesisFeedKey),\n haloSpaceKey: PublicKey.fromHex(response.haloSpaceKey),\n identityKey: PublicKey.fromHex(response.identityKey),\n deviceKey,\n controlFeedKey,\n dataFeedKey: await this._keyring.createKey(),\n });\n }\n\n /**\n * Recover an identity using an opaque one-time token. Accepts either an email magic-link\n * `token` (validated by hub-service) or an OAuth `recoveryProof` (redeemed by kms-service).\n * The two fields are routed to different backends by db-service and must not be conflated.\n */\n public async recoverIdentityWithToken(\n ctx: Context,\n fields: { token: string } | { recoveryProof: string },\n ): Promise<void> {\n invariant(this._edgeClient, 'Not connected to EDGE.');\n\n const deviceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const request: EdgeRecoverIdentityRequest = {\n deviceKey: deviceKey.toHex(),\n controlFeedKey: controlFeedKey.toHex(),\n ...fields,\n };\n\n const response = await this._edgeClient.recoverIdentity(ctx, request);\n\n await this.#acceptRecoveredIdentity({\n authorizedDeviceCredential: decodeCredential(response.deviceAuthCredential),\n haloGenesisFeedKey: PublicKey.fromHex(response.genesisFeedKey),\n haloSpaceKey: PublicKey.fromHex(response.haloSpaceKey),\n identityKey: PublicKey.fromHex(response.identityKey),\n deviceKey,\n controlFeedKey,\n dataFeedKey: await this._keyring.createKey(),\n });\n }\n\n public async recoverIdentity(ctx: Context, { recoveryCode }: { recoveryCode: string }): Promise<void> {\n invariant(this._edgeClient, 'Not connected to EDGE.');\n\n const recoveryKeypair = keyPairFromSeedPhrase(recoveryCode);\n const recoveryKey = PublicKey.from(recoveryKeypair.publicKey);\n const deviceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const request: EdgeRecoverIdentityRequest = {\n lookupKey: recoveryKey.toHex(),\n deviceKey: deviceKey.toHex(),\n controlFeedKey: controlFeedKey.toHex(),\n };\n\n let response: RecoverIdentityResponseBody;\n try {\n response = await this._edgeClient.recoverIdentity(ctx, request);\n } catch (error: any) {\n if (!(error instanceof EdgeAuthChallengeError)) {\n throw error;\n }\n const signature = sign(Buffer.from(error.challenge, 'base64'), recoveryKeypair.secretKey);\n response = await this._edgeClient.recoverIdentity(ctx, {\n ...request,\n signature: Buffer.from(signature).toString('base64'),\n });\n }\n\n log.info('recovering identity', response);\n\n await this.#acceptRecoveredIdentity({\n authorizedDeviceCredential: decodeCredential(response.deviceAuthCredential),\n haloGenesisFeedKey: PublicKey.fromHex(response.genesisFeedKey),\n haloSpaceKey: PublicKey.fromHex(response.haloSpaceKey),\n identityKey: PublicKey.fromHex(response.identityKey),\n deviceKey,\n controlFeedKey,\n dataFeedKey: await this._keyring.createKey(),\n });\n }\n\n #acceptRecoveredIdentity(params: JoinIdentityProps): Promise<Identity> {\n invariant(this._acceptRecoveredIdentity, 'acceptRecoveredIdentity not set');\n return this._acceptRecoveredIdentity(params);\n }\n}\n\nconst decodeCredential = (credentialBase64: string) => {\n const credentialBytes = Buffer.from(credentialBase64, 'base64');\n const codec = schema.getCodecForType('dxos.halo.credentials.Credential');\n return codec.decode(credentialBytes);\n};\n\n/**\n * Effect Layer constructing a dormant {@link EdgeIdentityRecoveryManager}.\n */\nexport const EdgeIdentityRecoveryManagerLayer = (): Layer.Layer<\n EdgeIdentityRecoveryManagerService,\n never,\n KeyringApiService | IdentityManagerService\n> =>\n Layer.effect(\n EdgeIdentityRecoveryManagerService,\n Effect.gen(function* () {\n const keyring = yield* KeyringApiService;\n const edgeClient = yield* Effect.serviceOption(EdgeHttpClientService);\n const identityManager = yield* IdentityManagerService;\n return new EdgeIdentityRecoveryManager(\n keyring,\n Option.getOrUndefined(edgeClient),\n () => identityManager.identity,\n );\n }),\n );\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { Context } from '@dxos/context';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { type SignalManager, type UnsubscribeCallback } from '@dxos/messaging';\nimport { type SwarmNetworkManager } from '@dxos/network-manager';\nimport {\n type NetworkStatus,\n type SubscribeSwarmStateRequest,\n type UpdateConfigRequest,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type SwarmResponse } from '@dxos/protocols/proto/dxos/edge/messenger';\nimport {\n type JoinRequest,\n type LeaveRequest,\n type Message,\n type QueryRequest,\n type SubscribeMessagesRequest,\n} from '@dxos/protocols/proto/dxos/edge/signal';\nimport { type NetworkService } from '@dxos/protocols/rpc';\n\nexport class NetworkServiceImpl implements NetworkService.Handlers {\n 'constructor'(\n private readonly networkManager: SwarmNetworkManager,\n private readonly signalManager: SignalManager,\n private readonly edgeConnection?: EdgeConnection,\n ) {}\n\n ['NetworkService.queryStatus'](): EffectStream.Stream<NetworkStatus, Error> {\n return EffectStream.async<NetworkStatus, Error>((emit) => {\n const ctx = Context.default();\n const update = () => {\n void emit.single({\n swarm: this.networkManager.connectionState,\n connectionInfo: this.networkManager.connectionLog?.swarms,\n signaling: this.signalManager.getStatus?.().map(({ host, state }) => ({ server: host, state })),\n });\n };\n\n this.networkManager.connectionStateChanged.on(ctx, () => update());\n this.signalManager.statusChanged?.on(ctx, () => update());\n update();\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['NetworkService.updateConfig'](request: UpdateConfigRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n await this.networkManager.setConnectionState(request.swarm);\n },\n catch: (error) => error as Error,\n });\n }\n\n ['NetworkService.joinSwarm'](request: JoinRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n await this.signalManager.join(Context.default(), request);\n },\n catch: (error) => error as Error,\n });\n }\n\n ['NetworkService.leaveSwarm'](request: LeaveRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n await this.signalManager.leave(Context.default(), request);\n },\n catch: (error) => error as Error,\n });\n }\n\n ['NetworkService.querySwarm'](request: QueryRequest): Effect.Effect<SwarmResponse, Error> {\n return Effect.tryPromise({\n try: async () => {\n return this.signalManager.query(Context.default(), request);\n },\n catch: (error) => error as Error,\n });\n }\n\n ['NetworkService.subscribeSwarmState'](\n request: SubscribeSwarmStateRequest,\n ): EffectStream.Stream<SwarmResponse, Error> {\n return EffectStream.async<SwarmResponse, Error>((emit) => {\n const ctx = Context.default();\n this.signalManager.swarmState?.on(ctx, (state) => {\n if (request.topic.equals(state.swarmKey)) {\n void emit.single(state);\n }\n });\n\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n ['NetworkService.sendMessage'](message: Message): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n await this.signalManager.sendMessage(Context.default(), message);\n },\n catch: (error) => error as Error,\n });\n }\n\n ['NetworkService.subscribeMessages'](request: SubscribeMessagesRequest): EffectStream.Stream<Message, Error> {\n const { peer, tags = [] } = request;\n return EffectStream.async<Message, Error>((emit) => {\n const ctx = Context.default();\n\n // This stream crosses the client-services RPC (protobufjs codec, e.g. dedicated worker → main\n // thread). Its `Message.payload` is a `google.protobuf.Any` without `preserve_any`, and the\n // codec refuses to encode an Any lacking '@type' — stamping the opaque form\n // ('@type': 'google.protobuf.Any' + type_url/value) makes it pass through verbatim.\n const encodableAny = (payload: Message['payload']): Message['payload'] => ({\n ...payload,\n '@type': 'google.protobuf.Any',\n });\n\n // The subscription encapsulates routing (DX-1125): point-to-point messages addressed to `peer`,\n // plus — when `tags` are set — swarm broadcasts whose tags intersect. The returned callback owns\n // teardown, refcounted so it releases only this stream's tag registration.\n let unsubscribe: UnsubscribeCallback | undefined;\n void this.signalManager\n .subscribeMessages({\n peer,\n tags,\n onMessage: (message) => {\n void emit.single({ ...message, payload: encodableAny(message.payload) });\n },\n })\n .then((unsub) => {\n if (ctx.disposed) {\n void unsub();\n } else {\n unsubscribe = unsub;\n }\n })\n .catch((err) => emit.fail(err instanceof Error ? err : new Error(String(err))));\n\n return Effect.promise(async () => {\n await unsubscribe?.();\n await ctx.dispose();\n });\n });\n }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { Event } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { type LogLevel, type LogProcessor, type LogEntry as NaturalLogEntry, log } from '@dxos/log';\nimport {\n type ControlMetricsRequest,\n type ControlMetricsResponse,\n type LogEntry,\n type Metrics,\n QueryLogsRequest,\n type QueryMetricsRequest,\n type QueryMetricsResponse,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type LoggingService } from '@dxos/protocols/rpc';\nimport { numericalValues, tracer } from '@dxos/util';\n\n/**\n * Logging service used to spy on logs of the host.\n *\n * @deprecated This was created so that logs from the shared worker (WorkerClientServices) could be\n * seen in the main window console without opening the shared worker DevTools. Shared worker client\n * services is deprecated; dedicated worker logs already show in the main window console.\n */\nexport class LoggingServiceImpl implements LoggingService.Handlers {\n private readonly '_logs' = new Event<NaturalLogEntry>();\n private readonly '_started' = Date.now();\n private readonly '_sessionId' = PublicKey.random().toHex();\n\n async 'open'(): Promise<void> {\n log.runtimeConfig.processors.push(this._logProcessor);\n }\n\n async 'close'(): Promise<void> {\n const index = log.runtimeConfig.processors.findIndex((processor: LogProcessor) => processor === this._logProcessor);\n log.runtimeConfig.processors.splice(index, 1);\n }\n\n ['LoggingService.controlMetrics']({\n reset,\n record,\n }: ControlMetricsRequest): Effect.Effect<ControlMetricsResponse, Error> {\n return Effect.sync(() => {\n if (reset) {\n tracer.clear();\n }\n\n if (record === true) {\n tracer.start();\n } else if (record === false) {\n tracer.stop();\n }\n\n return { recording: tracer.recording };\n });\n }\n\n /**\n * @deprecated (Move to diagnostics).\n */\n ['LoggingService.queryMetrics']({\n interval = 5_000,\n }: QueryMetricsRequest): EffectStream.Stream<QueryMetricsResponse, Error> {\n // TODO(burdon): Map all traces; how to bind to reducer/metrics shape (e.g., numericalValues)?\n const getNumericalValues = (key: string) => {\n const events = tracer.get(key) ?? [];\n return { key, stats: numericalValues(events, 'duration') };\n };\n\n return EffectStream.async<QueryMetricsResponse, Error>((emit) => {\n const update = () => {\n const metrics: Metrics = {\n timestamp: new Date(),\n values: [\n getNumericalValues('dxos.echo.pipeline.control'),\n getNumericalValues('dxos.echo.pipeline.data'),\n ].filter(Boolean) as Metrics.KeyPair[],\n };\n\n void emit.single({\n timestamp: new Date(),\n metrics,\n });\n };\n\n update();\n const i = setInterval(update, Math.max(interval, 1_000));\n return Effect.sync(() => {\n clearInterval(i);\n });\n });\n }\n\n ['LoggingService.queryLogs'](request: QueryLogsRequest): EffectStream.Stream<LogEntry, Error> {\n return EffectStream.async<LogEntry, Error>((emit) => {\n const ctx = Context.default();\n const handler = (entry: NaturalLogEntry) => {\n // This call was caused by the logging service itself.\n if (LOG_PROCESSING > 0) {\n return;\n }\n\n // Prevent logging feedback loop from logging service.\n if (\n entry.meta?.F.includes('logging-service') ||\n (entry.context &&\n Object.values(entry.context).some((value) => typeof value === 'string' && value.includes('LoggingService')))\n ) {\n return;\n }\n\n if (!shouldLog(entry, request)) {\n return;\n }\n\n const { filename, line, context: scopeName } = entry.computedMeta;\n const recordContext: Record<string, any> = { ...entry.computedContext };\n if (entry.computedError !== undefined) {\n recordContext.error = entry.computedError;\n }\n\n const record: LogEntry = {\n level: entry.level,\n message: entry.message ?? entry.computedError ?? '',\n context: recordContext,\n timestamp: new Date(entry.timestamp),\n meta: {\n // TODO(dmaretskyi): Fix proto.\n file: filename ?? '',\n line: line ?? 0,\n scope: {\n hostSessionId: this._sessionId,\n uptimeSeconds: (Date.now() - this._started) / 1000,\n name: scopeName ?? '',\n },\n },\n };\n\n try {\n LOG_PROCESSING++;\n void emit.single(record);\n } finally {\n LOG_PROCESSING--;\n }\n };\n\n this._logs.on(ctx, handler);\n return Effect.promise(() => ctx.dispose());\n });\n }\n\n private '_logProcessor': LogProcessor = (_config, entry) => {\n this._logs.emit(entry);\n };\n}\n\nconst matchFilter = (\n filter: QueryLogsRequest.Filter,\n level: LogLevel,\n path: string,\n options: QueryLogsRequest.MatchingOptions,\n) => {\n switch (options) {\n case QueryLogsRequest.MatchingOptions.INCLUSIVE:\n return level >= filter.level && (!filter.pattern || path.includes(filter.pattern));\n case QueryLogsRequest.MatchingOptions.EXPLICIT:\n return level === filter.level && (!filter.pattern || path.includes(filter.pattern));\n }\n};\n\n/**\n * Determines if the current line should be logged (called by the processor).\n */\nconst shouldLog = (entry: NaturalLogEntry, request: QueryLogsRequest): boolean => {\n const options = request.options ?? QueryLogsRequest.MatchingOptions.INCLUSIVE;\n if (request.filters === undefined) {\n return options === QueryLogsRequest.MatchingOptions.INCLUSIVE;\n } else {\n return request.filters.some((filter) => matchFilter(filter, entry.level, entry.meta?.F ?? '', options));\n }\n};\n\n/**\n * Counter that is used to track whether we are processing a log entry.\n */\nlet LOG_PROCESSING = 0;\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { type Event } from '@dxos/async';\nimport { type Config } from '@dxos/config';\nimport {\n GetDiagnosticsRequest,\n type GetDiagnosticsResponse,\n type Platform,\n type QueryStatusRequest,\n type QueryStatusResponse,\n type SystemStatus,\n type UpdateStatusRequest,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type Config as ConfigProto } from '@dxos/protocols/proto/dxos/config';\nimport { type SystemService } from '@dxos/protocols/rpc';\nimport { type MaybePromise, jsonKeyReplacer } from '@dxos/util';\n\nimport { type Diagnostics } from '../diagnostics';\nimport { getPlatform } from '../services/platform';\n\nexport type SystemServiceOptions = {\n config?: () => MaybePromise<Config | undefined>;\n statusUpdate: Event<void>;\n getCurrentStatus: () => SystemStatus;\n getDiagnostics: () => Promise<Partial<Diagnostics['services']>>;\n onUpdateStatus: (status: SystemStatus) => MaybePromise<void>;\n onReset: () => MaybePromise<void>;\n};\n\nexport class SystemServiceImpl implements SystemService.Handlers {\n private readonly '_config'?: SystemServiceOptions['config'];\n private readonly '_statusUpdate': SystemServiceOptions['statusUpdate'];\n private readonly '_getCurrentStatus': SystemServiceOptions['getCurrentStatus'];\n private readonly '_onUpdateStatus': SystemServiceOptions['onUpdateStatus'];\n private readonly '_onReset': SystemServiceOptions['onReset'];\n private readonly '_getDiagnostics': SystemServiceOptions['getDiagnostics'];\n\n 'constructor'({\n config,\n statusUpdate,\n getDiagnostics,\n onUpdateStatus,\n getCurrentStatus,\n onReset,\n }: SystemServiceOptions) {\n this._config = config;\n this._statusUpdate = statusUpdate;\n this._getCurrentStatus = getCurrentStatus;\n this._getDiagnostics = getDiagnostics;\n this._onUpdateStatus = onUpdateStatus;\n this._onReset = onReset;\n }\n\n ['SystemService.getConfig'](): Effect.Effect<ConfigProto, Error> {\n return Effect.tryPromise({\n try: async () => (await this._config?.())?.values ?? {},\n catch: (error) => error as Error,\n });\n }\n\n /**\n * NOTE: Since this is serialized as a JSON object, we allow the option to serialize keys.\n */\n ['SystemService.getDiagnostics']({ keys }: GetDiagnosticsRequest = {}): Effect.Effect<GetDiagnosticsResponse, Error> {\n return Effect.tryPromise({\n try: async () => {\n const diagnostics = await this._getDiagnostics();\n return {\n timestamp: new Date(),\n diagnostics: JSON.parse(\n JSON.stringify(\n diagnostics,\n jsonKeyReplacer({\n truncate: keys === GetDiagnosticsRequest.KEY_OPTION.TRUNCATE,\n humanize: keys === GetDiagnosticsRequest.KEY_OPTION.HUMANIZE,\n }),\n ),\n ),\n };\n },\n catch: (error) => error as Error,\n });\n }\n\n ['SystemService.getPlatform'](): Effect.Effect<Platform, Error> {\n return Effect.tryPromise({\n try: async () => getPlatform(),\n catch: (error) => error as Error,\n });\n }\n\n ['SystemService.updateStatus']({ status }: UpdateStatusRequest): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n await this._onUpdateStatus(status);\n },\n catch: (error) => error as Error,\n });\n }\n\n // TODO(burdon): Standardize interval option in stream request?\n ['SystemService.queryStatus']({ interval = 3_000 }: QueryStatusRequest = {}): EffectStream.Stream<\n QueryStatusResponse,\n Error\n > {\n return EffectStream.async<QueryStatusResponse, Error>((emit) => {\n const update = () => {\n void emit.single({ status: this._getCurrentStatus() });\n };\n\n update();\n const unsubscribe = this._statusUpdate.on(() => update());\n const i = setInterval(update, interval);\n return Effect.sync(() => {\n clearInterval(i);\n unsubscribe();\n });\n });\n }\n\n ['SystemService.reset'](): Effect.Effect<void, Error> {\n return Effect.tryPromise({\n try: async () => {\n await this._onReset();\n },\n catch: (error) => error as Error,\n });\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { type Context, type Lifecycle, Resource } from '@dxos/context';\nimport { type CredentialProcessor, getCredentialAssertion } from '@dxos/credentials';\nimport { assertState } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport { type Identity } from '../identity';\nimport { DataSpaceManager, DataSpaceManagerService } from '../spaces';\n\n/**\n * Replicates cross-device space membership and deletion credentials from the halo space.\n */\nexport interface CrossDeviceSpaceSynchronizer extends CredentialProcessor, Lifecycle {\n setIdentity(identity: Identity): void;\n}\n\n/**\n * Effect service tag for {@link CrossDeviceSpaceSynchronizer}.\n */\nexport class CrossDeviceSpaceSynchronizerService extends EffectContext.Tag(\n '@dxos/client-services/CrossDeviceSpaceSynchronizer',\n)<CrossDeviceSpaceSynchronizerService, CrossDeviceSpaceSynchronizer>() {}\n\nclass CrossDeviceSpaceSynchronizerImpl extends Resource implements CrossDeviceSpaceSynchronizer {\n private _identity?: Identity;\n\n constructor(private readonly dataSpaceManager: DataSpaceManager) {\n super();\n }\n\n setIdentity(identity: Identity): void {\n this._identity = identity;\n }\n\n protected override async _open(ctx: Context): Promise<void> {\n assertState(this._identity, 'identity not set');\n await this._identity.space.spaceState.addCredentialProcessor(this);\n }\n\n protected override async _close(ctx: Context): Promise<void> {\n if (!this._identity) {\n return;\n }\n await this._identity.space.spaceState.removeCredentialProcessor(this);\n }\n\n async processCredential(credential: Credential): Promise<void> {\n assertState(this._identity, 'identity not set');\n const assertion = getCredentialAssertion(credential);\n\n // A space was tombstoned on another device: replicate the deletion locally.\n if (assertion['@type'] === 'dxos.halo.credentials.SpaceDeleted') {\n if (assertion.spaceKey.equals(this._identity.space.key)) {\n // ignore halo space\n return;\n }\n if (!this.dataSpaceManager) {\n log('dataSpaceManager not initialized yet, ignoring space deletion', { details: assertion });\n return;\n }\n\n try {\n log('tombstoning space recorded in halo', { details: assertion });\n await this.dataSpaceManager.handleRemoteSpaceDeleted(this._ctx, assertion.spaceKey);\n } catch (err) {\n log.catch(err);\n }\n return;\n }\n\n if (assertion['@type'] !== 'dxos.halo.credentials.SpaceMember') {\n return;\n }\n if (assertion.spaceKey.equals(this._identity.space.key)) {\n // ignore halo space\n return;\n }\n if (!this.dataSpaceManager) {\n log('dataSpaceManager not initialized yet, ignoring space admission', { details: assertion });\n return;\n }\n // Do not re-accept a space that has been tombstoned (handles out-of-order credential replay).\n if (this.dataSpaceManager.isSpaceDeleted(assertion.spaceKey)) {\n log('space is deleted, ignoring space admission', { details: assertion });\n return;\n }\n if (this.dataSpaceManager.spaces.has(assertion.spaceKey)) {\n log('space already exists, ignoring space admission', { details: assertion });\n return;\n }\n\n try {\n log('accepting space recorded in halo', { details: assertion });\n await this.dataSpaceManager.acceptSpace(this._ctx, {\n spaceKey: assertion.spaceKey,\n genesisFeedKey: assertion.genesisFeedKey,\n tags: assertion.tags,\n });\n } catch (err) {\n log.catch(err);\n }\n }\n}\n\n/**\n * Creates a dormant {@link CrossDeviceSpaceSynchronizer} bound to the given data space manager.\n */\nexport const createCrossDeviceSpaceSynchronizer = (dataSpaceManager: DataSpaceManager): CrossDeviceSpaceSynchronizer =>\n new CrossDeviceSpaceSynchronizerImpl(dataSpaceManager);\n\n/**\n * Effect Layer constructing a dormant {@link CrossDeviceSpaceSynchronizer}.\n */\nexport const CrossDeviceSpaceSynchronizerLayer: Layer.Layer<\n CrossDeviceSpaceSynchronizerService,\n never,\n DataSpaceManagerService\n> = Layer.effect(\n CrossDeviceSpaceSynchronizerService,\n Effect.gen(function* () {\n const dataSpaceManager = yield* DataSpaceManagerService;\n return createCrossDeviceSpaceSynchronizer(dataSpaceManager);\n }),\n);\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as SqlClient from '@effect/sql/SqlClient';\nimport { Encoder, decode as cborXdecode } from 'cbor-x';\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\n\nimport { AsyncTask, Mutex, scheduleTask } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { EchoHostService } from '@dxos/echo-host';\nimport { type EdgeConnection, EdgeConnectionService, MessageSchema } from '@dxos/edge-client';\nimport { RuntimeProvider } from '@dxos/effect';\nimport { type FeedStore, SyncClient } from '@dxos/feed';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { EdgeService } from '@dxos/protocols';\nimport { createBuf } from '@dxos/protocols/buf';\nimport { type Message as RouterMessage } from '@dxos/protocols/buf/dxos/edge/messenger_pb';\nimport type { GetSyncStateRequest, GetSyncStateResponse } from '@dxos/protocols/proto/dxos/client/services';\nimport type { SqlTransaction } from '@dxos/sql-sqlite';\nimport { bufferToArray } from '@dxos/util';\n\nconst encoder = new Encoder({ tagUint8Array: false, useRecords: false });\n\nconst DEFAULT_MESSAGE_BLOCKS_LIMIT = 50;\nconst DEFAULT_SYNC_CONCURRENCY = 5;\nconst DEFAULT_POLLING_INTERVAL = 5_000;\nconst DEFAULT_POLL_REQUEST_THROTTLE_MS = 250;\nconst DEFAULT_PUSH_FAILURE_BACKOFF_MS = 250;\nconst MAX_PUSH_FAILURE_BACKOFF_MS = 30_000;\nconst MAX_BLOCKING_SYNC_ITERATIONS = 100;\n\nexport type FeedSyncerOptions = {\n runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient | SqlTransaction.SqlTransaction>;\n feedStore: FeedStore;\n edgeClient: EdgeConnection;\n peerId: string;\n getSpaceIds: () => SpaceId[];\n\n /**\n * Namespaces to sync.\n */\n syncNamespaces: string[];\n\n /**\n * Maximum number of blocks to sync in a single message.\n * @default 50\n */\n messageBlocksLimit?: number;\n\n /**\n * Maximum number of spaces to sync concurrently.\n * @default 5\n */\n syncConcurrency?: number;\n\n /**\n * Interval between full polls.\n * @default 10 seconds\n */\n pollingInterval?: number;\n\n /**\n * Minimum delay between externally requested best-effort polls.\n * @default 250 ms\n */\n pollRequestThrottleMs?: number;\n\n /**\n * When false, only wires the edge message handler; poll/push background tasks and\n * `feedStore.onNewBlocks` auto-push are disabled. Use for tests that call `syncBlocking` explicitly.\n * @default true\n */\n backgroundSync?: boolean;\n\n /**\n * Max time to wait for a feed sync RPC response from edge, in milliseconds.\n * @default 30000 (see `DEFAULT_SYNC_RPC_TIMEOUT_MS` in `@dxos/feed`).\n */\n syncRpcTimeoutMs?: number;\n};\n\n/**\n * Effect service tag for {@link FeedSyncer}.\n *\n * undefined if not initialized.\n */\nexport class FeedSyncerService extends EffectContext.Tag('@dxos/client-services/FeedSyncer')<\n FeedSyncerService,\n FeedSyncer | undefined\n>() {}\n\nexport class FeedSyncer extends Resource {\n readonly #syncNamespaces: string[];\n readonly #messageBlocksLimit: number;\n readonly #syncConcurrency: number;\n readonly #pollingInterval: number;\n readonly #pollRequestThrottleMs: number;\n readonly #backgroundSync: boolean;\n\n readonly #runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient | SqlTransaction.SqlTransaction>;\n readonly #feedStore: FeedStore;\n readonly #edgeClient: EdgeConnection;\n readonly #syncClient: SyncClient;\n readonly #getSpaceIds: () => SpaceId[];\n\n #spacesToPoll = new Set<SpaceId>();\n /** Last time full poll was completed. */\n #lastFullPoll: number | null = null;\n #throttledPollScheduled = false;\n #lastRequestedPollAt: number | null = null;\n readonly #feedStoreMutex = new Mutex();\n #pushFailureBackoffMs = DEFAULT_PUSH_FAILURE_BACKOFF_MS;\n\n constructor(options: FeedSyncerOptions) {\n super();\n this.#runtime = options.runtime;\n this.#feedStore = options.feedStore;\n this.#edgeClient = options.edgeClient;\n this.#syncClient = new SyncClient({\n peerId: options.peerId,\n feedStore: options.feedStore,\n sendMessage: this.#sendMessage.bind(this),\n rpcTimeoutMs: options.syncRpcTimeoutMs,\n });\n this.#getSpaceIds = options.getSpaceIds;\n this.#syncNamespaces = options.syncNamespaces;\n this.#messageBlocksLimit = options.messageBlocksLimit ?? DEFAULT_MESSAGE_BLOCKS_LIMIT;\n this.#syncConcurrency = options.syncConcurrency ?? DEFAULT_SYNC_CONCURRENCY;\n this.#pollingInterval = options.pollingInterval ?? DEFAULT_POLLING_INTERVAL;\n this.#pollRequestThrottleMs = options.pollRequestThrottleMs ?? DEFAULT_POLL_REQUEST_THROTTLE_MS;\n this.#backgroundSync = options.backgroundSync ?? true;\n }\n\n protected override async _open(): Promise<void> {\n this._ctx.onDispose(\n this.#edgeClient.onMessage((msg: RouterMessage) => {\n if (!msg.serviceId) {\n return;\n }\n const service = msg.serviceId.split(':')[0];\n if (service !== EdgeService.QUEUE_REPLICATOR) {\n return;\n }\n log('feed sync edge ingress', {\n serviceId: msg.serviceId,\n payloadByteLength: msg.payload?.value?.byteLength,\n });\n const handleMessageEffect = Effect.gen(this, function* () {\n const decoded = yield* Effect.try({\n try: () => cborXdecode(msg.payload!.value),\n catch: (error) => new Error(`Failed to decode feed sync message: ${error}`),\n });\n const payload = yield* Schema.validate(FeedProtocol.ProtocolMessage)(decoded);\n yield* this.#syncClient.handleMessage(payload);\n }).pipe(\n Effect.tapError((cause) =>\n Effect.sync(() =>\n log('feed sync edge message handling failed', {\n serviceId: msg.serviceId,\n payloadByteLength: msg.payload?.value?.byteLength,\n cause: cause instanceof Error ? cause.message : String(cause),\n }),\n ),\n ),\n );\n\n void this.#runSerialized(() => RuntimeProvider.runPromise(this.#runtime)(handleMessageEffect));\n }),\n );\n\n if (this.#backgroundSync) {\n // Tasks must be opened before registering listeners that call `schedule()`:\n // * `onNewBlocks` can fire from any `feedStore.append` happening on a separate\n // microtask while `_open()` is still awaiting.\n // * The edge client invokes `onReconnected` as a microtask when already connected.\n // `AsyncTask.schedule()` throws if the task is not yet open.\n await this.#pollTask.open();\n await this.#pushTask.open();\n\n this.#feedStore.onNewBlocks.on(this._ctx, () => {\n this.#pushTask.schedule();\n });\n }\n\n this._ctx.onDispose(\n // NOTE: Fires immediately (as a microtask) if the connection is already open, and again\n // on every subsequent reconnect.\n this.#edgeClient.onReconnected(async () => {\n log('feed sync edge reconnected', {\n peerKey: this.#edgeClient.peerKey,\n identityDid: this.#edgeClient.identityDid,\n });\n if (this.#backgroundSync) {\n this.#resetSpacesToPoll();\n this.#pollTask.schedule();\n this.#pushTask.schedule();\n }\n }),\n );\n\n if (this.#backgroundSync) {\n this.#resetSpacesToPoll();\n this.#pollTask.schedule();\n // Flush blocks written before the syncer opened: `onNewBlocks` only fires on append,\n // so existing unpositioned blocks would otherwise never be pushed.\n this.#pushTask.schedule();\n }\n }\n\n protected override async _close(): Promise<void> {\n if (this.#backgroundSync) {\n await this.#pollTask.close();\n await this.#pushTask.close();\n }\n }\n\n /**\n * Schedules a best-effort pull without blocking the caller.\n */\n schedulePoll(): void {\n if (!this.#backgroundSync) {\n return;\n }\n this.#resetSpacesToPoll();\n if (this.#throttledPollScheduled) {\n return;\n }\n\n const now = Date.now();\n const delay =\n this.#lastRequestedPollAt == null\n ? 0\n : Math.max(this.#pollRequestThrottleMs - (now - this.#lastRequestedPollAt), 0);\n this.#throttledPollScheduled = true;\n scheduleTask(\n this._ctx,\n () => {\n this.#throttledPollScheduled = false;\n this.#lastRequestedPollAt = Date.now();\n this.#pollTask.schedule();\n },\n delay,\n );\n }\n\n /**\n * Returns per-namespace queue sync backlog for a space.\n * `blocksToPull` and `blocksToPush` of 0 mean caught up for that namespace.\n */\n async getSyncState(ctx: Context, request: GetSyncStateRequest): Promise<GetSyncStateResponse> {\n const spaceId = request.spaceId as SpaceId;\n invariant(SpaceId.isValid(spaceId));\n const namespaces =\n request.namespaces != null && request.namespaces.length > 0 ? request.namespaces : this.#syncNamespaces;\n for (const feedNamespace of namespaces) {\n invariant(FeedProtocol.isWellKnownNamespace(feedNamespace));\n }\n\n return this.#runSerialized(() =>\n RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(this, function* () {\n const namespaceStates = yield* Effect.forEach(\n namespaces,\n (feedNamespace) =>\n Effect.gen(this, function* () {\n const blocksToPush = yield* this.#feedStore.countUnpositionedBlocks({\n spaceId,\n feedNamespace,\n });\n const totalBlocks = yield* this.#feedStore.countNamespaceBlocks({\n spaceId,\n feedNamespace,\n });\n const { blocksToPull } = yield* this.#syncClient\n .peekPull(ctx, {\n spaceId,\n feedNamespace,\n limit: this.#messageBlocksLimit,\n })\n .pipe(\n Effect.catchAll((cause) =>\n Effect.gen(this, function* () {\n this.#logSyncFailure('peekPull', { spaceId, feedNamespace, cause });\n return { blocksToPull: 0 };\n }),\n ),\n );\n return {\n namespace: feedNamespace,\n blocksToPull: String(blocksToPull),\n blocksToPush: String(blocksToPush),\n totalBlocks: String(totalBlocks),\n };\n }),\n { concurrency: 'unbounded' },\n );\n return { namespaces: namespaceStates };\n }),\n ),\n );\n }\n\n /**\n * Performs queue sync and blocks until there are no pending sync batches.\n */\n async syncBlocking(\n ctx: Context,\n {\n spaceId,\n subspaceTag,\n shouldPush = true,\n shouldPull = true,\n }: {\n spaceId: SpaceId;\n subspaceTag: string;\n shouldPush?: boolean;\n shouldPull?: boolean;\n },\n ): Promise<void> {\n invariant(SpaceId.isValid(spaceId));\n invariant(FeedProtocol.isWellKnownNamespace(subspaceTag));\n if (!shouldPush && !shouldPull) {\n return;\n }\n\n await this.#runSerialized(() =>\n RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(this, function* () {\n let done = false;\n let iterations = 0;\n while (!done) {\n done = true;\n if (shouldPull) {\n const pullResult = yield* this.#syncClient.pull(ctx, {\n spaceId,\n feedNamespace: subspaceTag,\n limit: this.#messageBlocksLimit,\n });\n done &&= pullResult.done;\n }\n\n if (shouldPush) {\n const pushResult = yield* this.#syncClient.push(ctx, {\n spaceId,\n feedNamespace: subspaceTag,\n limit: this.#messageBlocksLimit,\n });\n done &&= pushResult.done;\n }\n iterations++;\n if (iterations > MAX_BLOCKING_SYNC_ITERATIONS) {\n throw new Error('Blocking sync exceeded max iterations.');\n }\n }\n }),\n ),\n );\n }\n\n async #runSerialized<A>(run: () => Promise<A>): Promise<A> {\n using _guard = await this.#feedStoreMutex.acquire('feed-sync');\n return run();\n }\n\n #schedulePushRetry({ hadFailure, needsMore }: { hadFailure: boolean; needsMore: boolean }): void {\n if (!needsMore) {\n this.#pushFailureBackoffMs = DEFAULT_PUSH_FAILURE_BACKOFF_MS;\n return;\n }\n if (hadFailure) {\n const delayMs = this.#pushFailureBackoffMs;\n this.#pushFailureBackoffMs = Math.min(this.#pushFailureBackoffMs * 2, MAX_PUSH_FAILURE_BACKOFF_MS);\n log('feed sync push retry scheduled with backoff', { delayMs });\n scheduleTask(this._ctx, () => this.#pushTask.schedule(), delayMs);\n return;\n }\n this.#pushFailureBackoffMs = DEFAULT_PUSH_FAILURE_BACKOFF_MS;\n this.#pushTask.schedule();\n }\n\n #resetSpacesToPoll(): void {\n this.#spacesToPoll.clear();\n this.#getSpaceIds().forEach((spaceId) => {\n this.#spacesToPoll.add(spaceId);\n });\n this.#lastFullPoll = Date.now();\n }\n\n #sendMessage(\n ctx: Context,\n message: FeedProtocol.QueryRequest | FeedProtocol.AppendRequest,\n ): Effect.Effect<void, unknown, never> {\n return Effect.gen(this, function* () {\n const encoded = encoder.encode(message);\n const serviceId = this.#getTargetServiceId(message);\n const rpcTag = 'blocks' in message ? 'AppendRequest' : 'QueryRequest';\n log('feed sync edge rpc outgoing', {\n tag: rpcTag,\n serviceId,\n payloadByteLength: encoded.byteLength,\n spaceId: message.spaceId,\n feedNamespace: message.feedNamespace,\n requestId: message.requestId,\n });\n yield* Effect.tryPromise(async () =>\n this.#edgeClient.send(\n ctx,\n createBuf(MessageSchema, {\n source: {\n identityDid: this.#edgeClient.identityDid,\n peerKey: this.#edgeClient.peerKey,\n },\n serviceId,\n payload: { value: bufferToArray(encoded) },\n }),\n ),\n ).pipe(\n Effect.tapError((cause) =>\n Effect.sync(() =>\n log('feed sync edge send failed', {\n serviceId,\n tag: rpcTag,\n cause: cause instanceof Error ? cause.message : String(cause),\n }),\n ),\n ),\n );\n });\n }\n\n #logSyncFailure(\n operation: 'pull' | 'push' | 'peekPull',\n { spaceId, feedNamespace, cause }: { spaceId: SpaceId; feedNamespace: string; cause: unknown },\n ): void {\n log('feed sync operation failed', {\n operation,\n spaceId,\n feedNamespace,\n cause: cause instanceof Error ? cause.message : String(cause),\n errorTag: cause instanceof Error ? cause.name : undefined,\n });\n }\n\n #getTargetServiceId(message: FeedProtocol.QueryRequest | FeedProtocol.AppendRequest): string {\n // TODO(dmaretskyi): Perhaps in the future we will want to include the queue namespace here as well.\n // This would require putting it at the top level of the message.\n // For now, we let the edge router handle it.\n return FeedProtocol.encodeServiceId(message.feedNamespace, message.spaceId as SpaceId);\n }\n\n readonly #pollTask = new AsyncTask(async () =>\n Effect.gen(this, function* () {\n yield* Effect.forEach(\n this.#spacesToPoll,\n (spaceId) =>\n Effect.gen(this, function* () {\n let doneForAllNamespaces = true;\n for (const feedNamespace of this.#syncNamespaces) {\n const { done } = yield* this.#syncClient\n .pull(this._ctx, {\n spaceId,\n feedNamespace,\n limit: this.#messageBlocksLimit,\n })\n .pipe(\n Effect.catchAll((cause) =>\n Effect.gen(this, function* () {\n this.#logSyncFailure('pull', { spaceId, feedNamespace, cause });\n return { done: false };\n }),\n ),\n );\n if (!done) {\n doneForAllNamespaces = false;\n }\n }\n if (doneForAllNamespaces) {\n this.#spacesToPoll.delete(spaceId);\n }\n }),\n { concurrency: this.#syncConcurrency },\n );\n\n // If its time to do a full poll, reset the spaces to poll and schedule the next poll immediately.\n if (this.#lastFullPoll == null || Date.now() - this.#lastFullPoll > this.#pollingInterval) {\n this.#resetSpacesToPoll();\n this.#pollTask.schedule();\n } else if (this.#spacesToPoll.size > 0) {\n // If there are some spaces still syncing, poll them immediately.\n this.#pollTask.schedule();\n } else {\n // All spaces sync, and there's time before the next full poll, schedule it later.\n this.#resetSpacesToPoll();\n scheduleTask(\n this._ctx,\n () => this.#pollTask.schedule(),\n Math.max(this.#pollingInterval - (Date.now() - (this.#lastFullPoll ?? 0)), 0),\n );\n }\n }).pipe((effect) => this.#runSerialized(() => RuntimeProvider.runPromise(this.#runtime)(effect))),\n );\n\n readonly #pushTask = new AsyncTask(async () =>\n Effect.gen(this, function* () {\n yield* Effect.forEach(\n this.#getSpaceIds(),\n (spaceId) =>\n Effect.gen(this, function* () {\n let needsMorePush = false;\n let hadPushFailure = false;\n for (const feedNamespace of this.#syncNamespaces) {\n const { done } = yield* this.#syncClient\n .push(this._ctx, {\n spaceId,\n feedNamespace,\n limit: this.#messageBlocksLimit,\n })\n .pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n this.#pushFailureBackoffMs = DEFAULT_PUSH_FAILURE_BACKOFF_MS;\n }),\n ),\n Effect.catchAll((cause) =>\n Effect.gen(this, function* () {\n this.#logSyncFailure('push', { spaceId, feedNamespace, cause });\n hadPushFailure = true;\n return { done: false };\n }),\n ),\n );\n if (!done) {\n needsMorePush = true;\n }\n }\n this.#schedulePushRetry({ hadFailure: hadPushFailure, needsMore: needsMorePush });\n }),\n { concurrency: this.#syncConcurrency },\n );\n }).pipe((effect) => this.#runSerialized(() => RuntimeProvider.runPromise(this.#runtime)(effect))),\n );\n}\n\nexport type FeedSyncerLayerOptions = Pick<\n FeedSyncerOptions,\n | 'peerId'\n | 'syncNamespaces'\n | 'messageBlocksLimit'\n | 'syncConcurrency'\n | 'pollingInterval'\n | 'pollRequestThrottleMs'\n | 'backgroundSync'\n | 'syncRpcTimeoutMs'\n>;\n\n/**\n * Effect Layer constructing a {@link FeedSyncer} from ambient SQL, echo host, and edge services.\n *\n * The feed store is sourced from the {@link EchoHostService} (breaking the EchoHost <-> FeedSyncer\n * cycle). Only included when an edge connection is configured, so it resolves the edge tag directly.\n */\nexport const FeedSyncerLayer = (\n options: FeedSyncerLayerOptions,\n): Layer.Layer<\n FeedSyncerService,\n never,\n SqlClient.SqlClient | SqlTransaction.SqlTransaction | EchoHostService | EdgeConnectionService\n> =>\n Layer.effect(\n FeedSyncerService,\n Effect.gen(function* () {\n const runtime = yield* RuntimeProvider.currentRuntime<SqlClient.SqlClient | SqlTransaction.SqlTransaction>();\n const echoHost = yield* EchoHostService;\n const edgeClient = yield* EdgeConnectionService;\n return new FeedSyncer({\n runtime,\n feedStore: echoHost.feedStore,\n edgeClient,\n getSpaceIds: () => echoHost.spaceIds,\n ...options,\n });\n }),\n );\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as SqlClient from '@effect/sql/SqlClient';\nimport type * as SqlError from '@effect/sql/SqlError';\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport type { Callback, FileStat, RandomAccessStorage } from 'random-access-storage';\n\nimport { RuntimeProvider } from '@dxos/effect';\nimport { FeedStorageDirectoryService } from '@dxos/feed-store';\nimport { log } from '@dxos/log';\nimport { Directory, type File, type Storage, StorageType, wrapFile } from '@dxos/random-access-storage';\nimport { SqlTransaction } from '@dxos/sql-sqlite';\n\n// SqlTransaction.SqlTransaction is the Tag class exported from the SqlTransaction namespace.\ntype SqlTransactionTag = SqlTransaction.SqlTransaction;\n\n/**\n * True when a rejected SQL op failed because its connection was already closed — the message\n * `The database connection is not open` (raised by `@effect/sql-sqlite-node`), which arrives\n * wrapped as an effect `SqlError`, so walk the `cause` chain. Signals teardown, not a real fault.\n */\nexport const isClosedConnectionError = (err: unknown): boolean => {\n for (let cur: any = err, depth = 0; cur != null && depth < 5; cur = cur.cause, depth++) {\n const message = typeof cur === 'string' ? cur : cur.message;\n if (typeof message === 'string' && /connection is not open/i.test(message)) {\n return true;\n }\n }\n return false;\n};\n\nexport type SqliteStorageOptions = {\n runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient | SqlTransactionTag>;\n};\n\n/**\n * Effect service tag for {@link SqliteStorage}.\n */\nexport class SqliteStorageService extends EffectContext.Tag('@dxos/client-services/SqliteStorage')<\n SqliteStorageService,\n SqliteStorage\n>() {}\n\n/** Minimal cross-platform EventEmitter needed by the RandomAccessStorage contract. */\nclass BaseEventEmitter {\n readonly #events: Record<string, ((...args: unknown[]) => void)[]> = Object.create(null);\n\n on(event: string, listener: (...args: unknown[]) => void): this {\n (this.#events[event] ??= []).push(listener);\n return this;\n }\n off(event: string, listener: (...args: unknown[]) => void): this {\n const list = this.#events[event];\n if (list) {\n const idx = list.indexOf(listener);\n if (idx !== -1) {\n list.splice(idx, 1);\n }\n }\n return this;\n }\n emit(event: string, ...args: unknown[]): boolean {\n const list = this.#events[event];\n if (!list?.length) {\n return false;\n }\n for (const fn of [...list]) {\n fn(...args);\n }\n return true;\n }\n addListener = this.on;\n removeListener = this.off;\n once(event: string, listener: (...args: unknown[]) => void): this {\n const wrapper = (...args: unknown[]) => {\n this.off(event, wrapper);\n listener(...args);\n };\n return this.on(event, wrapper);\n }\n removeAllListeners(event?: string): this {\n if (event) {\n delete this.#events[event];\n } else {\n for (const key of Object.keys(this.#events)) {\n delete this.#events[key];\n }\n }\n return this;\n }\n listeners(event: string): ((...args: unknown[]) => void)[] {\n return this.#events[event] ?? [];\n }\n rawListeners(event: string): ((...args: unknown[]) => void)[] {\n return this.#events[event] ?? [];\n }\n listenerCount(event: string): number {\n return this.#events[event]?.length ?? 0;\n }\n prependListener(event: string, listener: (...args: unknown[]) => void): this {\n (this.#events[event] ??= []).unshift(listener);\n return this;\n }\n prependOnceListener(event: string, listener: (...args: unknown[]) => void): this {\n const wrapper = (...args: unknown[]) => {\n this.off(event, wrapper);\n listener(...args);\n };\n return this.prependListener(event, wrapper);\n }\n eventNames(): string[] {\n return Object.keys(this.#events);\n }\n getMaxListeners(): number {\n return 0;\n }\n setMaxListeners(): this {\n return this;\n }\n}\n\n/**\n * SQLite-backed random-access file for hypercore storage.\n * Stores each file as a blob in `hypercore_files`. Read-modify-write for writes.\n */\nclass SqliteRandomAccessFile extends BaseEventEmitter implements RandomAccessStorage {\n readonly opened: boolean = false;\n readonly suspended: boolean = false;\n readonly writing: boolean = false;\n readonly readable: boolean = true;\n readonly writable: boolean = true;\n readonly deletable: boolean = true;\n readonly truncatable: boolean = false;\n // Setting statable=false prevents hypercore's statAndReadAll() from computing a negative\n // read-size (stat.size - offset) for new empty files, which causes an infinite async loop.\n readonly statable: boolean = false;\n\n #closed = false;\n #unlinked = false;\n #destroyed = false;\n\n get closed(): boolean {\n return this.#closed;\n }\n\n get unlinked(): boolean {\n return this.#unlinked;\n }\n\n get destroyed(): boolean {\n return this.#destroyed;\n }\n\n // Filesystem-like metadata for compatibility with wrapFile.\n readonly directory: string;\n readonly filename: string;\n\n #buffer: Buffer = Buffer.alloc(0);\n #loaded = false;\n // The one-shot initial DB read (populates `#buffer`); set once, on first access.\n #loading: Promise<void> | null = null;\n // The latest in-flight DB write (from `write`/`del`); replaced on each save, so it always\n // tracks the most recent one. `close()` drains both before reporting closed.\n #saving: Promise<void> | null = null;\n\n constructor(\n private readonly filePath: string,\n private readonly runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient | SqlTransactionTag>,\n ) {\n super();\n const parts = filePath.split('/');\n this.filename = parts.pop() ?? '';\n this.directory = parts.join('/');\n }\n\n private _ensureLoaded(): Promise<void> {\n if (this.#loaded) {\n return Promise.resolve();\n }\n // If the file was closed (e.g. the storage was torn down during shutdown) before its initial\n // load completed, don't start the DB read. The underlying SQL connection may already be\n // closing, and the read would reject with \"database connection is not open\" as an unhandled\n // rejection — a background read racing teardown. #buffer already defaults to empty, so reads\n // resolve against an empty file.\n if (this.#closed) {\n return Promise.resolve();\n }\n if (!this.#loading) {\n this.#loading = this._loadFromDb();\n // Mark the cached load promise as handled so that if it rejects after every awaiter is gone\n // (e.g. the SQL runtime is disposed at teardown without close() being called on this file),\n // the rejection is never surfaced as an unhandled rejection. Legitimate awaiters still observe\n // the error through their own `.then`/`.catch` on the same promise returned below.\n this.#loading.catch(() => {});\n }\n return this.#loading;\n }\n\n private async _loadFromDb(): Promise<void> {\n const filePath = this.filePath;\n try {\n const rows = await RuntimeProvider.runPromise(this.runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n return yield* sql<{ data: Uint8Array }>`SELECT data FROM hypercore_files WHERE path = ${filePath}`;\n }),\n );\n this.#buffer = rows.length > 0 ? Buffer.from(rows[0].data) : Buffer.alloc(0);\n } catch (err) {\n // A read racing teardown rejects with \"database connection is not open\". The `#closed` guard\n // in `_ensureLoaded` only catches reads not yet started, and `#closed` covers only this file\n // being closed — during client disposal the shared SQL connection can be torn down while this\n // file's `#closed` is still false (the container closed the connection without closing every\n // file first). In either case a closed connection means there is nothing to load, so fall back\n // to the empty `#buffer`; rethrow only a genuine error against a live connection. Swallowing an\n // unhandled rejection here otherwise crashes the whole test worker (exit 1, no test failure).\n if (!this.#closed && !isClosedConnectionError(err)) {\n throw err;\n }\n }\n this.#loaded = true;\n }\n\n private async _saveToDb(): Promise<void> {\n const filePath = this.filePath;\n const data = this.#buffer;\n try {\n await RuntimeProvider.runPromise(this.runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`INSERT OR REPLACE INTO hypercore_files (path, data) VALUES (${filePath}, ${data})`;\n }),\n );\n } catch (err) {\n // Symmetric with `_loadFromDb`: a write racing teardown rejects (as `SqlError: Failed to\n // execute statement` wrapping \"connection is not open\") when the shared SQL connection is\n // torn down before this file's `#closed` flips. Persisting to a dead connection is moot\n // during disposal, so swallow it; rethrow only a genuine failure against a live connection.\n // An unswallowed rejection here surfaces as an unhandled rejection that fails the test worker.\n if (!this.#closed && !isClosedConnectionError(err)) {\n throw err;\n }\n }\n }\n\n write(offset: number, data: Buffer, cb: Callback<any>): void {\n const saving = this._ensureLoaded()\n .then(() => {\n const end = offset + data.length;\n if (end > this.#buffer.length) {\n const enlarged = Buffer.alloc(end);\n this.#buffer.copy(enlarged);\n this.#buffer = enlarged;\n }\n data.copy(this.#buffer, offset);\n return this._saveToDb();\n })\n .then(\n () => cb(null),\n (err) => cb(err),\n );\n // Track the in-flight save so `close()` can drain it before reporting closed — otherwise a\n // write racing `close()` (e.g. a background sync write racing `client.reset()`'s teardown)\n // keeps running against a connection the container may tear down immediately after.\n this.#saving = saving.catch(() => {});\n }\n\n read(offset: number, size: number, cb: Callback<Buffer>): void {\n this._ensureLoaded()\n .then(() => {\n if (size === 0) {\n cb(null, Buffer.alloc(0));\n return;\n }\n if (offset + size > this.#buffer.length) {\n cb(new Error(`Could not satisfy length ${size} at offset ${offset} (file size: ${this.#buffer.length})`));\n return;\n }\n cb(null, Buffer.from(this.#buffer.subarray(offset, offset + size)));\n })\n .catch((err) => cb(err));\n }\n\n del(offset: number, size: number, cb: Callback<any>): void {\n const saving = this._ensureLoaded()\n .then(() => {\n const end = Math.min(offset + size, this.#buffer.length);\n if (offset < end) {\n this.#buffer.fill(0, offset, end);\n }\n return this._saveToDb();\n })\n .then(\n () => cb(null),\n (err) => cb(err),\n );\n // See `write()`: track the in-flight save so `close()` can drain it before reporting closed.\n this.#saving = saving.catch(() => {});\n }\n\n stat(cb: Callback<FileStat>): void {\n this._ensureLoaded()\n .then(() => {\n cb(null, { size: this.#buffer.length });\n })\n .catch((err) => cb(err));\n }\n\n close(cb: Callback<Error>): void {\n this.#closed = true;\n // Drain any in-flight initial load and any in-flight write/del before reporting closed, so\n // neither races a torn-down SQL connection (avoids \"database connection is not open\" errors,\n // and the resulting stall in callers — e.g. `client.reset()`'s feed teardown — that wait on\n // this file's `close()` to settle before tearing down the connection itself).\n Promise.all([this.#loading ?? Promise.resolve(), this.#saving ?? Promise.resolve()]).then(\n () => cb(null),\n () => cb(null),\n );\n }\n\n destroy(cb: Callback<Error>): void {\n const filePath = this.filePath;\n RuntimeProvider.runPromise(this.runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`DELETE FROM hypercore_files WHERE path = ${filePath}`;\n }),\n )\n .then(() => {\n this.#buffer = Buffer.alloc(0);\n this.#destroyed = true;\n this.#unlinked = true;\n this.#closed = true;\n cb(null);\n })\n .catch((err) => cb(err));\n }\n}\n\n/**\n * SQLite-backed Storage implementation for hypercore feeds.\n * Table: hypercore_files(path TEXT PRIMARY KEY, data BLOB NOT NULL DEFAULT x'').\n */\nexport class SqliteStorage implements Storage {\n readonly path: string;\n readonly type = StorageType.NODE;\n\n readonly #runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient | SqlTransactionTag>;\n readonly #files = new Map<string, File>();\n readonly #nativeFiles = new Map<string, SqliteRandomAccessFile>();\n #closed = false;\n\n constructor({ runtime }: SqliteStorageOptions, path = '/sqlite-feeds') {\n this.#runtime = runtime;\n this.path = path;\n }\n\n readonly migrate: Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient | SqlTransactionTag> = Effect.fn(\n 'SqliteStorage.migrate',\n )(() =>\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`CREATE TABLE IF NOT EXISTS hypercore_files (\n path TEXT PRIMARY KEY,\n data BLOB NOT NULL DEFAULT x''\n )`;\n log('hypercore_files table ready');\n }).pipe(Effect.withSpan('SqliteStorage.migrate')),\n )();\n\n get size(): number {\n return this.#files.size;\n }\n\n createDirectory(sub = ''): Directory {\n const dirPath = sub ? `${this.path}/${sub}` : this.path;\n const runtime = this.#runtime;\n const files = this.#files;\n const nativeFiles = this.#nativeFiles;\n\n const getOrCreateFile = (path: string, filename: string): File => {\n const fullPath = `${path}/${filename}`;\n const existingNative = nativeFiles.get(fullPath);\n if (existingNative && !existingNative.destroyed) {\n return files.get(fullPath)!;\n }\n const native = new SqliteRandomAccessFile(fullPath, runtime);\n const file = wrapFile(native, StorageType.NODE);\n files.set(fullPath, file);\n nativeFiles.set(fullPath, native);\n return file;\n };\n\n const list = async (path: string): Promise<string[]> => {\n const prefix = path.endsWith('/') ? path : path + '/';\n const rows = await RuntimeProvider.runPromise(runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n return yield* sql<{\n path: string;\n }>`SELECT path FROM hypercore_files WHERE path = ${path} OR path LIKE ${prefix + '%'}`;\n }),\n );\n return rows.map((row) => row.path.replace(path + '/', '').replace(path, ''));\n };\n\n const remove = async (): Promise<void> => {\n const prefix = dirPath.endsWith('/') ? dirPath : dirPath + '/';\n await RuntimeProvider.runPromise(runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`DELETE FROM hypercore_files WHERE path = ${dirPath} OR path LIKE ${prefix + '%'}`;\n }),\n );\n // Clean up in-memory file cache.\n for (const [filePath] of files) {\n if (filePath === dirPath || filePath.startsWith(prefix)) {\n files.delete(filePath);\n }\n }\n };\n\n return new Directory({\n type: StorageType.NODE,\n path: dirPath,\n list,\n getOrCreateFile,\n remove,\n });\n }\n\n async reset(): Promise<void> {\n log('SqliteStorage: clearing all hypercore files');\n await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`DELETE FROM hypercore_files`;\n }),\n );\n this.#files.clear();\n }\n\n async close(): Promise<void> {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n // Close each native file before the SQL connection is torn down. `close()` marks the file\n // closed (so any subsequent read skips the DB) and drains its in-flight initial load —\n // preventing \"database connection is not open\" unhandled rejections from background reads\n // that race shutdown (e.g. a test client closing while a background sync read is in flight).\n const natives = [...this.#nativeFiles.values()];\n await Promise.all(natives.map((native) => new Promise<void>((resolve) => native.close(() => resolve()))));\n this.#files.clear();\n this.#nativeFiles.clear();\n }\n}\n\nexport type SqliteStorageLayerOptions = {\n path?: string;\n};\n\n/**\n * Effect Layer constructing a {@link SqliteStorage} from the ambient SQL runtime.\n */\nexport const SqliteStorageLayer = (\n options: SqliteStorageLayerOptions = {},\n): Layer.Layer<SqliteStorageService, never, SqlClient.SqlClient | SqlTransactionTag> =>\n Layer.effect(\n SqliteStorageService,\n Effect.gen(function* () {\n const runtime = yield* RuntimeProvider.currentRuntime<SqlClient.SqlClient | SqlTransactionTag>();\n return new SqliteStorage({ runtime }, options.path);\n }),\n );\n\nexport type FeedStorageDirectoryLayerOptions = {\n sub?: string;\n};\n\n/**\n * Effect Layer providing the hypercore feeds root directory from {@link SqliteStorage}.\n */\nexport const FeedStorageDirectoryLayer = (\n options: FeedStorageDirectoryLayerOptions = {},\n): Layer.Layer<FeedStorageDirectoryService, never, SqliteStorageService> =>\n Layer.effect(\n FeedStorageDirectoryService,\n Effect.gen(function* () {\n const storage = yield* SqliteStorageService;\n return storage.createDirectory(options.sub ?? 'feeds');\n }),\n );\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport * as SqlClient from '@effect/sql/SqlClient';\nimport type * as SqlError from '@effect/sql/SqlError';\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport {\n EchoEdgeReplicatorLayer,\n EchoEdgeSubductionReplicatorLayer,\n EchoHostLayer,\n EchoHostService,\n MeshEchoReplicatorLayer,\n} from '@dxos/echo-host';\nimport {\n type EdgeConnection,\n EdgeConnectionService,\n type EdgeHttpClient,\n EdgeHttpClientService,\n} from '@dxos/edge-client';\nimport { RuntimeProvider } from '@dxos/effect';\nimport { FeedFactoryLayer, FeedStoreLayer, FeedStoreService } from '@dxos/feed-store';\nimport { KeyringApiService, SqliteKeyring, SqliteKeyringLayer } from '@dxos/keyring';\nimport { SignalManagerService } from '@dxos/messaging';\nimport { SwarmNetworkManagerService } from '@dxos/network-manager';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { SqlTransaction } from '@dxos/sql-sqlite';\nimport { BlobStoreApiService, SqliteBlobStore, SqliteBlobStoreLayer } from '@dxos/teleport-extension-object-sync';\n\nimport { EdgeAgentManagerLayer, EdgeAgentManagerService } from '../agents';\nimport {\n IdentityManagerLayer,\n type IdentityManagerProps,\n IdentityManagerService,\n IdentityProviderService,\n identityProviderFromManager,\n} from '../identity';\nimport {\n EdgeIdentityRecoveryManagerLayer,\n EdgeIdentityRecoveryManagerService,\n} from '../identity/identity-recovery-manager';\nimport {\n type InvitationConnectionProps,\n InvitationsHandlerLayer,\n InvitationsHandlerService,\n InvitationsManagerLayer,\n InvitationsManagerService,\n} from '../invitations';\nimport { IMetadataStoreService, SqliteMetadataStore, SqliteMetadataStoreLayer } from '../metadata';\nimport { valueEncoding } from '../pipeline';\nimport { SpaceManagerLayer, SpaceManagerService } from '../space';\nimport {\n DataSpaceManagerLayer,\n type DataSpaceManagerRuntimeProps,\n DataSpaceManagerService,\n SigningContextProviderLayer,\n SigningContextProviderService,\n} from '../spaces';\nimport {\n CrossDeviceSpaceSynchronizerLayer,\n CrossDeviceSpaceSynchronizerService,\n} from './cross-device-space-synchronizer';\nimport { FeedSyncerLayer } from './feed-syncer';\nimport { FeedStorageDirectoryLayer, SqliteStorage, SqliteStorageLayer } from './sqlite-storage';\n\n// SqlTransaction.SqlTransaction is the Tag class exported from the SqlTransaction namespace.\ntype SqlTransactionTag = SqlTransaction.SqlTransaction;\n\nexport type ServiceContextRuntimeProps = Pick<\n IdentityManagerProps,\n 'devicePresenceOfflineTimeout' | 'devicePresenceAnnounceInterval'\n> &\n DataSpaceManagerRuntimeProps & {\n invitationConnectionDefaultProps?: InvitationConnectionProps;\n disableP2pReplication?: boolean;\n enableVectorIndexing?: boolean;\n };\n\n/**\n * Combined storage migration effect gathered from the concrete SQLite stores.\n * Run by {@link ClientServicesHost} during open (storage migration stage).\n */\nexport class StorageMigrationService extends EffectContext.Tag('@dxos/client-services/StorageMigration')<\n StorageMigrationService,\n Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient | SqlTransactionTag>\n>() {}\n\nexport type ServiceContextLayerOptions = ServiceContextRuntimeProps & {\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n edgeConnection?: EdgeConnection;\n edgeHttpClient?: EdgeHttpClient;\n};\n\n/**\n * Component tags the composed stack exposes so {@link ClientServicesHost} and the client RPC service\n * layers can depend on each component directly.\n */\nexport type ServiceContextStackContext =\n | EchoHostService\n | IdentityManagerService\n | IdentityProviderService\n | SpaceManagerService\n | InvitationsManagerService\n | InvitationsHandlerService\n | EdgeIdentityRecoveryManagerService\n | KeyringApiService\n | DataSpaceManagerService\n | EdgeAgentManagerService\n | CrossDeviceSpaceSynchronizerService\n | SigningContextProviderService\n | IMetadataStoreService\n | BlobStoreApiService\n | FeedStoreService\n | StorageMigrationService;\n\n/**\n * Effect Layer composing the dormant client-stack components, constructed before identity is ready.\n * {@link ClientServicesHost} resolves these tags and drives their lifecycle.\n */\nexport const ServiceContextLayer = (\n options: ServiceContextLayerOptions,\n): Layer.Layer<\n ServiceContextStackContext,\n never,\n SwarmNetworkManagerService | SignalManagerService | SqlClient.SqlClient | SqlTransactionTag\n> => {\n const { edgeConnection, edgeHttpClient } = options;\n\n // Core stack, flattened into a single pipe. Optional replicators expose their service via\n // `provideMerge` and are read with `serviceOption` down the stack; their absence is modelled by\n // not wiring the layer, not by a null value.\n const core = CrossDeviceSpaceSynchronizerLayer.pipe(\n Layer.provideMerge(EdgeAgentManagerLayer({ edgeFeatures: options.edgeFeatures })),\n Layer.provideMerge(DataSpaceManagerLayer({ runtimeProps: options, edgeFeatures: options.edgeFeatures })),\n Layer.provideMerge(SigningContextProviderLayer),\n Layer.provideMerge(identityProviderLayer),\n Layer.provideMerge(options.disableP2pReplication ? Layer.empty : MeshEchoReplicatorLayer()),\n Layer.provideMerge(echoHostLayer({ useSubduction: options.edgeFeatures?.subductionReplicator })),\n Layer.provideMerge(InvitationsManagerLayer()),\n Layer.provideMerge(InvitationsHandlerLayer({ connectionProps: options.invitationConnectionDefaultProps })),\n Layer.provideMerge(EdgeIdentityRecoveryManagerLayer()),\n Layer.provideMerge(\n IdentityManagerLayer({\n devicePresenceOfflineTimeout: options.devicePresenceOfflineTimeout,\n devicePresenceAnnounceInterval: options.devicePresenceAnnounceInterval,\n edgeFeatures: options.edgeFeatures,\n }),\n ),\n Layer.provideMerge(SpaceManagerLayer({ disableP2pReplication: options.disableP2pReplication })),\n Layer.provideMerge(storageLayer),\n );\n\n // Non-edge: just the core.\n if (!edgeConnection || !edgeHttpClient) {\n return core;\n }\n\n // Edge: the feed syncer sits above the core for its `EchoHostService` requirement; the edge\n // replicator sits below — it needs only the edge inputs, resolved via `serviceOption` inside the\n // core. Edge inputs are provided internally so they never surface as stack requirements.\n return FeedSyncerLayer({\n peerId: '',\n syncNamespaces: [FeedProtocol.WellKnownNamespaces.data, FeedProtocol.WellKnownNamespaces.trace],\n }).pipe(\n Layer.provideMerge(core),\n Layer.provideMerge(\n options.edgeFeatures?.subductionReplicator\n ? EchoEdgeSubductionReplicatorLayer()\n : options.edgeFeatures?.echoReplicator\n ? EchoEdgeReplicatorLayer()\n : Layer.empty,\n ),\n Layer.provideMerge(\n Layer.mergeAll(\n Layer.succeed(EdgeConnectionService, edgeConnection),\n Layer.succeed(EdgeHttpClientService, edgeHttpClient),\n ),\n ),\n );\n};\n\n/**\n * Provides the {@link IdentityProviderService} from the resolved {@link IdentityManager}.\n */\nconst identityProviderLayer = Layer.effect(\n IdentityProviderService,\n Effect.gen(function* () {\n const identityManager = yield* IdentityManagerService;\n return identityProviderFromManager(identityManager);\n }),\n);\n\n/**\n * Combined storage migration effect. Storage migrations are idempotent `CREATE TABLE` effects that\n * do not depend on store instance state, so they are extracted from throwaway instances to keep the\n * store layers individual. Run by {@link ClientServicesHost} during open.\n */\nconst storageMigrationLayer = Layer.effect(\n StorageMigrationService,\n Effect.gen(function* () {\n const runtime = yield* RuntimeProvider.currentRuntime<SqlClient.SqlClient | SqlTransactionTag>();\n return Effect.all(\n [\n new SqliteMetadataStore({ runtime }).migrate,\n new SqliteBlobStore({ runtime }).migrate,\n new SqliteKeyring({ runtime }).migrate,\n new SqliteStorage({ runtime }).migrate,\n ],\n { discard: true },\n );\n }),\n);\n\n/**\n * Storage / feed layers composed from the individual store layers plus the combined migration.\n */\nconst storageLayer = Layer.empty.pipe(\n Layer.provideMerge(FeedStoreLayer()),\n Layer.provideMerge(FeedFactoryLayer({ hypercore: { valueEncoding, stats: true } })),\n Layer.provideMerge(FeedStorageDirectoryLayer()),\n Layer.provideMerge(SqliteMetadataStoreLayer()),\n Layer.provideMerge(SqliteBlobStoreLayer()),\n Layer.provideMerge(SqliteKeyringLayer()),\n Layer.provideMerge(SqliteStorageLayer()),\n Layer.provideMerge(storageMigrationLayer),\n);\n\n/**\n * Constructs the {@link EchoHost}, resolving the identity/space callbacks that point down the stack.\n * The feed sync handlers (which point up) are wired later via `EchoHost.setFeedSyncHandlers`.\n *\n * The host is self-contained (runs its own migrations, owns its feed/automerge stores), so its\n * open/close is owned by the layer scope: it opens when the stack is built and closes when the\n * runtime is disposed. Identity-, network-, and storage-bound lifecycle stays in `ClientServicesHost`.\n */\nconst echoHostLayer = (options: { useSubduction?: boolean }) =>\n Layer.scopedDiscard(\n Effect.gen(function* () {\n const echoHost = yield* EchoHostService;\n yield* Effect.acquireRelease(\n Effect.promise(() => echoHost.open()),\n () => Effect.promise(() => echoHost.close()),\n );\n }),\n ).pipe(\n Layer.provideMerge(\n Layer.unwrapEffect(\n Effect.gen(function* () {\n const identityManager = yield* IdentityManagerService;\n const spaceManager = yield* SpaceManagerService;\n return EchoHostLayer({\n peerIdProvider: () => identityManager.identity?.deviceKey?.toHex(),\n getSpaceKeyByRootDocumentId: (documentId) => spaceManager.findSpaceByRootDocumentId(documentId)?.key,\n useSubduction: options.useSubduction,\n });\n }),\n ),\n ),\n );\n","//\n// Copyright 2021 DXOS.org\n//\n\nimport * as SqlClient from '@effect/sql/SqlClient';\nimport type * as SqlError from '@effect/sql/SqlError';\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Exit from 'effect/Exit';\nimport * as Layer from 'effect/Layer';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\nimport * as Option from 'effect/Option';\nimport * as Runtime from 'effect/Runtime';\nimport * as Scope from 'effect/Scope';\n\nimport { Event, Mutex, Trigger, synchronized } from '@dxos/async';\nimport {\n type ClientServices,\n type ClientServicesHandlers,\n makeInProcessClientServicesRpc,\n makeServicesFromRpc,\n} from '@dxos/client-protocol';\nimport { type Config, resolveTelemetryTag } from '@dxos/config';\nimport { Context } from '@dxos/context';\nimport { failUndefined, warnAfterTimeout } from '@dxos/debug';\nimport {\n type AutomergeReplicator,\n type EchoHost,\n EchoHostService,\n type EdgeAutomergeReplicator,\n EdgeAutomergeReplicatorService,\n MeshEchoReplicatorService,\n runSqliteHealthCheck,\n} from '@dxos/echo-host';\nimport {\n EdgeClient,\n type EdgeConnection,\n EdgeHttpClient,\n type EdgeIdentity,\n createChainEdgeIdentity,\n createEphemeralEdgeIdentity,\n createStubEdgeIdentity,\n} from '@dxos/edge-client';\nimport { EffectEx, RuntimeProvider } from '@dxos/effect';\nimport { type FeedStore, FeedStoreService } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type KeyringApi, KeyringApiService } from '@dxos/keyring';\nimport { type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n EdgeSignalManager,\n MemorySignalManager,\n MemorySignalManagerContext,\n type SignalManager,\n SignalManagerService,\n} from '@dxos/messaging';\nimport {\n SwarmNetworkManager,\n SwarmNetworkManagerService,\n type TransportFactory,\n createIceProvider,\n createRtcTransportFactory,\n} from '@dxos/network-manager';\nimport { InvalidStorageVersionError, STORAGE_VERSION } from '@dxos/protocols';\nimport { Invitation, SystemStatus } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Credential, type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n ContactsService,\n DataService,\n DevicesService,\n EdgeAgentService,\n FeedService,\n IdentityService,\n InvitationsService,\n NetworkService,\n QueryService,\n SpacesService,\n} from '@dxos/protocols/rpc';\nimport * as SqlExport from '@dxos/sql-sqlite/SqlExport';\nimport type * as SqlTransaction from '@dxos/sql-sqlite/SqlTransaction';\nimport { type BlobStoreApi, BlobStoreApiService } from '@dxos/teleport-extension-object-sync';\nimport { trace as Trace } from '@dxos/tracing';\nimport { WebsocketRpcClient } from '@dxos/websocket-rpc';\n\nimport { type EdgeAgentManager, EdgeAgentManagerService } from '../agents';\nimport { DevtoolsHostEvents, DevtoolsServiceImpl } from '../devtools';\nimport {\n type CollectDiagnosticsBroadcastHandler,\n createCollectDiagnosticsBroadcastHandler,\n createDiagnostics,\n} from '../diagnostics';\nimport {\n type CreateIdentityOptions,\n type Identity,\n type IdentityManager,\n IdentityManagerService,\n type JoinIdentityProps,\n} from '../identity';\nimport {\n type EdgeIdentityRecoveryManager,\n EdgeIdentityRecoveryManagerService,\n} from '../identity/identity-recovery-manager';\nimport {\n DeviceInvitationProtocol,\n type InvitationProtocol,\n type InvitationsHandler,\n InvitationsHandlerService,\n type InvitationsManager,\n InvitationsManagerService,\n SpaceInvitationProtocol,\n} from '../invitations';\nimport { Lock, type ResourceLock } from '../locks';\nimport { LoggingServiceImpl } from '../logging';\nimport { type IMetadataStore, IMetadataStoreService } from '../metadata';\nimport { type SpaceManager, SpaceManagerService } from '../space';\nimport {\n type DataSpaceManager,\n DataSpaceManagerService,\n type SigningContextProvider,\n SigningContextProviderService,\n} from '../spaces';\nimport { SystemServiceImpl } from '../system';\nimport { type ClientServicesRpcContext, ClientServicesRpcLayer } from './client-services-layer';\nimport {\n type CrossDeviceSpaceSynchronizer,\n CrossDeviceSpaceSynchronizerService,\n} from './cross-device-space-synchronizer';\nimport { type FeedSyncer, FeedSyncerService } from './feed-syncer';\nimport {\n ServiceContextLayer,\n type ServiceContextRuntimeProps,\n type ServiceContextStackContext,\n StorageMigrationService,\n} from './service-context';\n\nexport type ClientServicesHostProps = {\n /**\n * Can be omitted if `initialize` is later called.\n */\n config?: Config;\n transportFactory?: TransportFactory;\n signalManager?: SignalManager;\n connectionLog?: boolean;\n lockKey?: string;\n callbacks?: ClientServicesHostCallbacks;\n runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient | SqlExport.SqlExport | SqlTransaction.SqlTransaction>;\n runtimeProps?: ServiceContextRuntimeProps;\n};\n\nexport type ClientServicesHostCallbacks = {\n onReset?: () => Promise<void>;\n};\n\nexport type InitializeOptions = {\n config?: Config;\n transportFactory?: TransportFactory;\n signalManager?: SignalManager;\n connectionLog?: boolean;\n};\n\n// Alias for consumers (tests, devtools, diagnostics) that referred to the former `ServiceContext`\n// orchestrator; its lifecycle and API now live on {@link ClientServicesHost} directly.\nexport type ServiceContext = ClientServicesHost;\n\n/**\n * Shared backend for all client services.\n *\n * Owns the full client stack and its lifecycle: it builds the layer-composed components (keyring,\n * feed store, echo host, identity/space managers, …) plus the client RPC handlers, then drives the\n * open sequence (migrate → identity → network → space initialization) and teardown. It reads or\n * creates the identity, propagates it outward (`_setNetworkIdentity`), and opens the identity-bound\n * services once an identity is available (`_initialize`). The host provides itself into the stack\n * (via {@link ClientServicesHostService}) so the RPC handler layers can resolve the orchestration\n * entry points they need without a separate `ServiceContext` service.\n */\nexport class ClientServicesHost {\n readonly #resourceLock?: ResourceLock;\n // Effect-rpc handlers served over each connection, resolved from the Layer stack on open and reset\n // to the host-local set on close. Held directly (no separate registry indirection).\n #handlers: Partial<ClientServicesHandlers>;\n readonly #systemService: SystemServiceImpl;\n readonly #loggingService: LoggingServiceImpl;\n readonly #statusUpdate = new Event<void>();\n\n #config?: Config;\n #signalManager?: SignalManager;\n #networkManager?: SwarmNetworkManager;\n #callbacks?: ClientServicesHostCallbacks;\n #devtoolsProxy?: WebsocketRpcClient<{}, ClientServices>;\n #edgeConnection?: EdgeConnection = undefined;\n #edgeHttpClient?: EdgeHttpClient = undefined;\n\n #stackRuntime?: ManagedRuntime.ManagedRuntime<\n ClientServicesHostService | ClientServicesRpcContext | ServiceContextStackContext,\n never\n >;\n readonly #runtime: RuntimeProvider.RuntimeProvider<\n SqlClient.SqlClient | SqlExport.SqlExport | SqlTransaction.SqlTransaction\n >;\n readonly #runtimeProps: ServiceContextRuntimeProps;\n #diagnosticsBroadcastHandler: CollectDiagnosticsBroadcastHandler;\n\n #opening = false;\n #open = false;\n #resetting = false;\n\n // Stack components, resolved from the layer runtime on open. Present after `open` starts.\n #ctx?: Context;\n #metadataStore?: IMetadataStore;\n #blobStore?: BlobStoreApi;\n #keyring?: KeyringApi;\n #feedStore?: FeedStore<any>;\n #spaceManager?: SpaceManager;\n #identityManager?: IdentityManager;\n #recoveryManager?: EdgeIdentityRecoveryManager;\n #invitations?: InvitationsHandler;\n #invitationsManager?: InvitationsManager;\n #echoHost?: EchoHost;\n #signingContextProvider?: SigningContextProvider;\n #dataSpaceManager?: DataSpaceManager;\n #edgeAgentManager?: EdgeAgentManager;\n #deviceSpaceSync?: CrossDeviceSpaceSynchronizer;\n #meshReplicator?: AutomergeReplicator;\n #echoEdgeReplicator?: EdgeAutomergeReplicator;\n #feedSyncer?: FeedSyncer;\n #storageMigrate?: Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction>;\n\n // Orchestration state (formerly on `ServiceContext`).\n readonly #initialized = new Trigger();\n readonly #edgeIdentityUpdateMutex = new Mutex();\n readonly #handlerFactories = new Map<Invitation.Kind, (invitation: Partial<Invitation>) => InvitationProtocol>();\n\n constructor({\n config,\n transportFactory,\n signalManager,\n // TODO(wittjosiah): Turn this on by default.\n lockKey,\n callbacks,\n runtime,\n runtimeProps,\n }: ClientServicesHostProps) {\n this.#callbacks = callbacks;\n this.#runtime = runtime;\n this.#runtimeProps = runtimeProps ?? {};\n\n if (config) {\n this.initialize({ config, transportFactory, signalManager });\n }\n\n if (lockKey) {\n this.#resourceLock = new Lock({\n lockKey,\n onAcquire: () => {\n if (!this.#opening) {\n void this.open(new Context());\n }\n },\n onRelease: () => this.close(Context.default()),\n });\n }\n\n // TODO(wittjosiah): If config is not defined here, system service will always have undefined config.\n this.#systemService = new SystemServiceImpl({\n config: () => this.#config,\n statusUpdate: this.#statusUpdate,\n getCurrentStatus: () => (this.isOpen && !this.#resetting ? SystemStatus.ACTIVE : SystemStatus.INACTIVE),\n getDiagnostics: async () => {\n // Bridge the host Handlers to the proto services surface that diagnostics collection consumes.\n const scope = Effect.runSync(Scope.make());\n try {\n const rpc = await EffectEx.runPromise(\n makeInProcessClientServicesRpc(() => this.#handlers).pipe(Effect.provideService(Scope.Scope, scope)),\n );\n const services = makeServicesFromRpc(rpc, Runtime.defaultRuntime);\n return await createDiagnostics(services, this, this.#config!);\n } finally {\n await EffectEx.runPromise(Scope.close(scope, Exit.void));\n }\n },\n onUpdateStatus: async (status: SystemStatus) => {\n if (!this.isOpen && status === SystemStatus.ACTIVE) {\n await this.#resourceLock?.acquire();\n } else if (this.isOpen && status === SystemStatus.INACTIVE) {\n await this.#resourceLock?.release();\n }\n },\n onReset: async () => {\n await this.reset();\n },\n });\n\n this.#diagnosticsBroadcastHandler = createCollectDiagnosticsBroadcastHandler(this.#systemService);\n this.#loggingService = new LoggingServiceImpl();\n\n this.#handlers = {\n SystemService: this.#systemService,\n };\n }\n\n get isOpen() {\n return this.#open;\n }\n\n get config() {\n return this.#config;\n }\n\n // Self-reference retained for the former `host.context` accessor.\n get context(): ClientServicesHost {\n return this;\n }\n\n get services() {\n return this.#handlers;\n }\n\n get initialized() {\n return this.#initialized;\n }\n\n get identityManager(): IdentityManager {\n return this.#identityManager ?? failUndefined();\n }\n\n get spaceManager(): SpaceManager {\n return this.#spaceManager ?? failUndefined();\n }\n\n get metadataStore(): IMetadataStore {\n return this.#metadataStore ?? failUndefined();\n }\n\n get blobStore(): BlobStoreApi {\n return this.#blobStore ?? failUndefined();\n }\n\n get recoveryManager(): EdgeIdentityRecoveryManager {\n return this.#recoveryManager ?? failUndefined();\n }\n\n get keyring(): KeyringApi {\n return this.#keyring ?? failUndefined();\n }\n\n get feedStore(): FeedStore<any> {\n return this.#feedStore ?? failUndefined();\n }\n\n get echoHost(): EchoHost {\n return this.#echoHost ?? failUndefined();\n }\n\n get invitations(): InvitationsHandler {\n return this.#invitations ?? failUndefined();\n }\n\n get invitationsManager(): InvitationsManager {\n return this.#invitationsManager ?? failUndefined();\n }\n\n get networkManager(): SwarmNetworkManager {\n return this.#networkManager ?? failUndefined();\n }\n\n get signalManager(): SignalManager {\n return this.#signalManager ?? failUndefined();\n }\n\n // Present after the stack constructs it; usable once `initialized` wakes.\n get dataSpaceManager(): DataSpaceManager | undefined {\n return this.#dataSpaceManager;\n }\n\n get edgeAgentManager(): EdgeAgentManager | undefined {\n return this.#edgeAgentManager;\n }\n\n get edgeConnection(): EdgeConnection | undefined {\n return this.#edgeConnection;\n }\n\n /**\n * Debugging util.\n */\n async exportSqliteDatabase(): Promise<Uint8Array> {\n return await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlExport.SqlExport;\n return yield* sql.export;\n }),\n );\n }\n\n /**\n * Debugging util.\n */\n async runSqliteQuery(query: string, params?: unknown[]): Promise<readonly Record<string, unknown>[]> {\n return await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n return yield* sql`${sql.unsafe(query, params)}`;\n }),\n );\n }\n\n /**\n * Initialize the service host with the config.\n * Config can also be provided in the constructor.\n * Can only be called once.\n */\n initialize({ config, ...options }: InitializeOptions): void {\n invariant(!this.#open, 'service host is open');\n log('initializing...');\n\n if (config) {\n if (this.#runtimeProps.disableP2pReplication === undefined) {\n this.#runtimeProps.disableP2pReplication = config?.get('runtime.client.disableP2pReplication', false);\n }\n if (this.#runtimeProps.enableVectorIndexing === undefined) {\n this.#runtimeProps.enableVectorIndexing = config?.get('runtime.client.enableVectorIndexing', false);\n }\n\n invariant(!this.#config, 'config already set');\n this.#config = config;\n }\n\n const endpoint = config?.get('runtime.services.edge.url');\n if (endpoint) {\n const clientTag = resolveTelemetryTag(config);\n this.#edgeConnection = new EdgeClient(createStubEdgeIdentity(), { socketEndpoint: endpoint, clientTag });\n this.#edgeHttpClient = new EdgeHttpClient(endpoint, { clientTag });\n }\n\n const {\n connectionLog = true,\n transportFactory = createRtcTransportFactory(\n { iceServers: this.#config?.get('runtime.services.ice') },\n this.#config?.get('runtime.services.iceProviders') &&\n createIceProvider(this.#config!.get('runtime.services.iceProviders')!),\n ),\n // Edge is the only real signaling transport; without it fall back to an isolated in-memory\n // manager (no cross-process signaling). The former KUBE `WebsocketSignalManager` is removed.\n signalManager = this.#edgeConnection && this.#config?.get('runtime.client.edgeFeatures')?.signaling\n ? new EdgeSignalManager({ edgeConnection: this.#edgeConnection })\n : new MemorySignalManager(new MemorySignalManagerContext()),\n } = options;\n this.#signalManager = signalManager;\n\n invariant(!this.#networkManager, 'network manager already set');\n this.#networkManager = new SwarmNetworkManager({\n enableDevtoolsLogging: connectionLog,\n transportFactory,\n signalManager,\n peerInfo: this.#edgeConnection\n ? {\n identityDid: this.#edgeConnection.identityDid,\n peerKey: this.#edgeConnection.peerKey,\n }\n : undefined,\n });\n\n log('initialized');\n }\n\n @synchronized\n @Trace.span()\n async open(ctx: Context = new Context()): Promise<void> {\n if (this.#open) {\n return;\n }\n\n log('opening service host');\n\n invariant(this.#config, 'config not set');\n invariant(this.#signalManager, 'signal manager not set');\n invariant(this.#networkManager, 'network manager not set');\n const config = this.#config;\n const signalManager = this.#signalManager;\n const networkManager = this.#networkManager;\n\n this.#opening = true;\n this.#ctx = ctx;\n log('opening...', { lockKey: this.#resourceLock?.lockKey });\n\n await this.#resourceLock?.acquire();\n\n await this.#loggingService.open();\n\n // Build a single runtime from the component layer stack plus the client RPC handlers, providing\n // the host itself so the handler layers can resolve their orchestration entry points.\n const stackLayer = ClientServicesRpcLayer.pipe(\n Layer.provideMerge(Layer.succeed(ClientServicesHostService, this)),\n Layer.provideMerge(\n ServiceContextLayer({\n ...this.#runtimeProps,\n edgeFeatures: config.get('runtime.client.edgeFeatures'),\n edgeConnection: this.#edgeConnection,\n edgeHttpClient: this.#edgeHttpClient,\n }),\n ),\n Layer.provideMerge(Layer.succeed(SwarmNetworkManagerService, networkManager)),\n Layer.provideMerge(Layer.succeed(SignalManagerService, signalManager)),\n Layer.provideMerge(RuntimeProvider.toLayer(this.#runtime)),\n Layer.orDie,\n );\n this.#stackRuntime = ManagedRuntime.make(stackLayer);\n const resolved = await this.#stackRuntime.runPromise(\n Effect.all({\n // Components.\n metadataStore: IMetadataStoreService,\n blobStore: BlobStoreApiService,\n keyring: KeyringApiService,\n feedStore: FeedStoreService,\n spaceManager: SpaceManagerService,\n identityManager: IdentityManagerService,\n recoveryManager: EdgeIdentityRecoveryManagerService,\n invitations: InvitationsHandlerService,\n invitationsManager: InvitationsManagerService,\n echoHost: EchoHostService,\n signingContextProvider: SigningContextProviderService,\n dataSpaceManager: DataSpaceManagerService,\n edgeAgentManager: EdgeAgentManagerService,\n deviceSpaceSync: CrossDeviceSpaceSynchronizerService,\n storageMigrate: StorageMigrationService,\n meshReplicator: Effect.serviceOption(MeshEchoReplicatorService),\n echoEdgeReplicator: Effect.serviceOption(EdgeAutomergeReplicatorService),\n feedSyncer: Effect.serviceOption(FeedSyncerService),\n // Handlers.\n identityService: IdentityService.Tag,\n contactsService: ContactsService.Tag,\n invitationsService: InvitationsService.Tag,\n devicesService: DevicesService.Tag,\n spacesService: SpacesService.Tag,\n networkService: NetworkService.Tag,\n edgeAgentService: EdgeAgentService.Tag,\n dataService: DataService.Tag,\n queryService: QueryService.Tag,\n feedService: FeedService.Tag,\n }),\n );\n\n this.#metadataStore = resolved.metadataStore;\n this.#blobStore = resolved.blobStore;\n this.#keyring = resolved.keyring;\n this.#feedStore = resolved.feedStore;\n this.#spaceManager = resolved.spaceManager;\n this.#identityManager = resolved.identityManager;\n this.#recoveryManager = resolved.recoveryManager;\n this.#invitations = resolved.invitations;\n this.#invitationsManager = resolved.invitationsManager;\n this.#echoHost = resolved.echoHost;\n this.#signingContextProvider = resolved.signingContextProvider;\n this.#dataSpaceManager = resolved.dataSpaceManager;\n this.#edgeAgentManager = resolved.edgeAgentManager;\n this.#deviceSpaceSync = resolved.deviceSpaceSync;\n this.#storageMigrate = resolved.storageMigrate;\n this.#meshReplicator = Option.getOrUndefined(resolved.meshReplicator);\n this.#echoEdgeReplicator = Option.getOrUndefined(resolved.echoEdgeReplicator);\n this.#feedSyncer = Option.getOrUndefined(resolved.feedSyncer);\n\n // Wire the setters for components that point \"up the stack\".\n this.#handlerFactories.set(\n Invitation.Kind.DEVICE,\n () =>\n new DeviceInvitationProtocol(\n this.#keyring!,\n () => this.#identityManager!.identity ?? failUndefined(),\n this._acceptIdentity.bind(this),\n ),\n );\n this.#recoveryManager.setAcceptRecoveredIdentity((params) => this._acceptIdentity(params));\n this.#invitationsManager.setInvitationHandlerFactory((invitation) => this.getInvitationHandler(invitation));\n this.#echoHost.setFeedSyncHandlers({\n syncFeed: async (feedSyncCtx, request) =>\n this.#feedSyncer?.syncBlocking(feedSyncCtx, {\n spaceId: request.spaceId as SpaceId,\n subspaceTag: request.subspaceTag,\n shouldPush: request.shouldPush,\n shouldPull: request.shouldPull,\n }),\n getSyncState: async (feedSyncCtx, request) => {\n if (!this.#feedSyncer) {\n return { namespaces: [] };\n }\n return this.#feedSyncer.getSyncState(feedSyncCtx, request);\n },\n });\n\n this.#handlers = {\n SystemService: this.#systemService,\n IdentityService: resolved.identityService,\n ContactsService: resolved.contactsService,\n InvitationsService: resolved.invitationsService,\n DevicesService: resolved.devicesService,\n SpacesService: resolved.spacesService,\n DataService: resolved.dataService,\n QueryService: resolved.queryService,\n FeedService: resolved.feedService,\n NetworkService: resolved.networkService,\n LoggingService: this.#loggingService,\n // TODO(burdon): Move to new protobuf definitions.\n DevtoolsHost: new DevtoolsServiceImpl({\n events: new DevtoolsHostEvents(),\n config: this.#config,\n context: this,\n exportSqliteDatabase: () => this.exportSqliteDatabase(),\n runSqliteQuery: (query, params) => this.runSqliteQuery(query, params),\n }),\n EdgeAgentService: resolved.edgeAgentService,\n };\n\n // Run the open lifecycle stages (formerly ServiceContext._open).\n // The identity service impl's open/close lifecycle is owned by its layer scope in\n // {@link ClientServicesRpcLayer} and runs when the stack runtime is disposed.\n await this._openStack(ctx);\n\n const devtoolsProxy = this.#config?.get('runtime.client.devtoolsProxy');\n if (devtoolsProxy) {\n // TODO(dxos): The devtools websocket proxy serves the protobuf service bundle, which is\n // incompatible with the effect-rpc Handlers the host now provides. Re-enable once this legacy\n // transport is migrated to effect-rpc (or bridged via makeInProcessClient + a proto adapter).\n log.warn('devtoolsProxy is not supported with effect-rpc services; skipping', { devtoolsProxy });\n }\n this.#diagnosticsBroadcastHandler.start();\n\n this.#opening = false;\n this.#open = true;\n this.#statusUpdate.emit();\n const deviceKey = this.#identityManager?.identity?.deviceKey;\n log('opened', { deviceKey });\n }\n\n @synchronized\n @Trace.span()\n async close(ctx: Context = Context.default()): Promise<void> {\n if (!this.#open) {\n return;\n }\n\n const deviceKey = this.#identityManager?.identity?.deviceKey;\n log('closing...', { deviceKey });\n this.#diagnosticsBroadcastHandler.stop();\n await this.#devtoolsProxy?.close();\n this.#handlers = { SystemService: this.#systemService };\n await this.#loggingService.close();\n await this._closeStack(ctx);\n await this.#stackRuntime?.dispose();\n this.#stackRuntime = undefined;\n this.#open = false;\n this.#statusUpdate.emit();\n log('closed', { deviceKey });\n }\n\n async reset(): Promise<void> {\n log.info('resetting...');\n // Emit this status update immediately so app returns to fallback.\n // This state is never cleared because the app reloads.\n this.#resetting = true;\n this.#statusUpdate.emit();\n if (this.#open) {\n await this._closeStack(this.#ctx ?? Context.default());\n }\n // Wipe all SQLite tables so next open starts fresh.\n await RuntimeProvider.runPromise(this.#runtime)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n // Echo metadata + large space data.\n yield* sql`DELETE FROM space_metadata`;\n yield* sql`DELETE FROM space_large`;\n // Blob store.\n yield* sql`DELETE FROM blobs_meta`;\n yield* sql`DELETE FROM blobs_data`;\n // Keyring.\n yield* sql`DELETE FROM keyring`;\n // Automerge chunks + heads.\n yield* sql`DELETE FROM automerge_chunks`;\n yield* sql`DELETE FROM automerge_heads`;\n // Hypercore feed files.\n yield* sql`DELETE FROM hypercore_files`;\n // Feed store (queue feeds, blocks, etc.).\n yield* sql`DELETE FROM feeds`;\n yield* sql`DELETE FROM blocks`;\n yield* sql`DELETE FROM subscriptions`;\n yield* sql`DELETE FROM cursor_tokens`;\n yield* sql`DELETE FROM sync_state`;\n // Index tables.\n yield* sql`DELETE FROM indexCursor`;\n yield* sql`DELETE FROM objectMeta`;\n yield* sql`DELETE FROM reverseRef`;\n yield* sql`DELETE FROM ftsIndex`;\n }),\n );\n log.info('reset');\n await this.#callbacks?.onReset?.();\n }\n\n //\n // Orchestration (formerly ServiceContext).\n //\n\n async createIdentity(params: CreateIdentityOptions = {}, ctx?: Context): Promise<Identity> {\n ctx ??= this.#ctx ?? Context.default();\n const identity = await this.identityManager.createIdentity(params, ctx);\n await this._setNetworkIdentity({ identity });\n await identity.joinNetwork(ctx);\n await this._initialize(ctx);\n return identity;\n }\n\n getInvitationHandler(invitation: Partial<Invitation> & Pick<Invitation, 'kind'>): InvitationProtocol {\n if (this.identityManager.identity == null && invitation.kind === Invitation.Kind.SPACE) {\n throw new Error('Identity must be created before joining a space.');\n }\n const factory = this.#handlerFactories.get(invitation.kind);\n invariant(factory, `Unknown invitation kind: ${invitation.kind}`);\n return factory(invitation);\n }\n\n async broadcastProfileUpdate(profile: ProfileDocument | undefined): Promise<void> {\n if (!profile || !this.#dataSpaceManager) {\n return;\n }\n for (const space of this.#dataSpaceManager.spaces.values()) {\n await space.updateOwnProfile(profile);\n }\n }\n\n /**\n * Resolves the {@link DataSpaceManager} once identity-bound services have opened (`initialized`).\n */\n async whenDataSpaceManagerReady(): Promise<DataSpaceManager> {\n await this.#initialized.wait();\n return this.#dataSpaceManager ?? failUndefined();\n }\n\n /**\n * Resolves the {@link EdgeAgentManager} once identity-bound services have opened (`initialized`).\n */\n async whenEdgeAgentManagerReady(): Promise<EdgeAgentManager> {\n await this.#initialized.wait();\n return this.#edgeAgentManager ?? failUndefined();\n }\n\n private async _acceptIdentity(params: JoinIdentityProps): Promise<Identity> {\n const ctx = this.#ctx ?? Context.default();\n const { identity, identityRecord } = await this.identityManager.prepareIdentity(params, ctx);\n await this._setNetworkIdentity({ deviceCredential: params.authorizedDeviceCredential!, identity });\n await identity.joinNetwork(ctx);\n await this.identityManager.acceptIdentity(identity, identityRecord, params.deviceProfile);\n await this._initialize(ctx);\n return identity;\n }\n\n private async _checkStorageVersion(): Promise<void> {\n await this.metadataStore.load();\n if (this.metadataStore.version !== STORAGE_VERSION) {\n throw new InvalidStorageVersionError(STORAGE_VERSION, this.metadataStore.version);\n // TODO(mykola): Migrate storage to a new version if incompatibility is detected.\n }\n }\n\n /**\n * Opens the identity-bound services once an identity is available.\n */\n @Trace.span()\n private async _initialize(ctx: Context): Promise<void> {\n log('_initialize: start');\n const identity = this.identityManager.identity ?? failUndefined();\n\n await this.#dataSpaceManager!.open(ctx);\n log('_initialize: DataSpaceManager opened');\n\n await this.#edgeAgentManager!.open(ctx);\n log('_initialize: EdgeAgentManager opened');\n\n this.#handlerFactories.set(\n Invitation.Kind.SPACE,\n (invitation) =>\n new SpaceInvitationProtocol(\n this.#dataSpaceManager!,\n this.#signingContextProvider!(),\n this.#keyring!,\n invitation.spaceKey,\n ),\n );\n this.#initialized.wake();\n\n this.#deviceSpaceSync!.setIdentity(identity);\n await this.#deviceSpaceSync!.open?.(ctx);\n }\n\n private async _setNetworkIdentity(params?: { deviceCredential?: Credential; identity?: Identity }): Promise<void> {\n log('_setNetworkIdentity: acquiring mutex...');\n using _ = await this.#edgeIdentityUpdateMutex.acquire();\n log('_setNetworkIdentity: mutex acquired');\n\n let edgeIdentity: EdgeIdentity;\n const identity = params?.identity;\n if (identity) {\n if (params?.deviceCredential) {\n edgeIdentity = await createChainEdgeIdentity(\n identity.signer,\n identity.identityKey,\n identity.deviceKey,\n { credential: params.deviceCredential },\n [], // TODO(dmaretskyi): Service access credentials.\n );\n } else {\n // TODO: throw here or from identity if device chain can't be loaded, to avoid indefinite hangup\n await warnAfterTimeout(10_000, 'Waiting for identity to be ready for edge connection', async () => {\n await identity.ready();\n });\n\n invariant(identity.deviceCredentialChain);\n\n edgeIdentity = await createChainEdgeIdentity(\n identity.signer,\n identity.identityKey,\n identity.deviceKey,\n identity.deviceCredentialChain,\n [], // TODO(dmaretskyi): Service access credentials.\n );\n }\n } else {\n edgeIdentity = await createEphemeralEdgeIdentity();\n }\n\n this.#edgeConnection?.setIdentity(edgeIdentity);\n this.#edgeHttpClient?.setIdentity(edgeIdentity);\n this.networkManager.setPeerInfo({\n identityDid: edgeIdentity.identityDid,\n peerKey: edgeIdentity.peerKey,\n });\n log('_setNetworkIdentity: done');\n }\n\n /**\n * Open lifecycle stages over the resolved stack components (formerly ServiceContext._open).\n */\n private async _openStack(ctx: Context): Promise<void> {\n log('running storage migrations...');\n await RuntimeProvider.runPromise(this.#runtime)(this.#storageMigrate!);\n\n await this._checkStorageVersion();\n\n log('running sqlite health check...');\n await runSqliteHealthCheck(this.#runtime);\n log('sqlite health check passed');\n\n log('opening identityManager...');\n await this.#identityManager!.open(ctx);\n log('identityManager opened', { hasIdentity: !!this.#identityManager!.identity });\n\n log('setting network identity...');\n await this._setNetworkIdentity({ identity: this.#identityManager!.identity });\n\n log('opening edge connection...');\n await this.#edgeConnection?.open(ctx);\n\n log('opening signal manager...');\n await this.#signalManager!.open(ctx);\n\n log('opening network manager...');\n await this.#networkManager!.open();\n\n // EchoHost open/close is owned by its layer scope; the host is already open here.\n if (this.#meshReplicator) {\n log('adding mesh replicator...');\n await this.#echoHost!.addReplicator(ctx, this.#meshReplicator);\n }\n if (this.#echoEdgeReplicator) {\n log('adding edge replicator...');\n await this.#echoHost!.addReplicator(ctx, this.#echoEdgeReplicator);\n }\n\n log('loading metadata store...');\n await this.#metadataStore!.load();\n\n log('opening space manager...');\n await this.#spaceManager!.open();\n\n if (this.#identityManager!.identity) {\n log('joining network...');\n await this.#identityManager!.identity.joinNetwork(ctx);\n\n log('initializing spaces...');\n await this._initialize(ctx);\n } else {\n log('no identity, skipping network join and space initialization');\n }\n\n log('opening feed syncer...');\n await this.#feedSyncer?.open(ctx);\n\n log('loading persistent invitations...');\n const loadedInvitations = await this.#invitationsManager!.loadPersistentInvitations(ctx);\n log('loaded persistent invitations', { count: loadedInvitations.invitations?.length });\n\n log('stack opened');\n }\n\n /**\n * Close lifecycle stages (formerly ServiceContext._close).\n */\n private async _closeStack(ctx: Context): Promise<void> {\n log('closing stack...');\n await this.#feedSyncer?.close();\n await this.#deviceSpaceSync?.close?.();\n await this.#dataSpaceManager?.close(ctx);\n await this.#edgeAgentManager?.close();\n await this.#identityManager?.close(ctx);\n await this.#spaceManager?.close();\n // EchoHost close is owned by its layer scope and runs when the runtime is disposed.\n\n await this.#networkManager?.close(ctx);\n await this.#signalManager?.close();\n await this.#edgeConnection?.close();\n await this.#feedStore?.close();\n await this.#metadataStore?.close();\n log('stack closed');\n }\n}\n\n/**\n * Context tag for the {@link ClientServicesHost}. The host provides itself under this tag when it\n * builds its component stack, so client RPC handler layers can resolve the orchestration entry\n * points (`createIdentity`, readiness gates, …) they need.\n */\nexport class ClientServicesHostService extends EffectContext.Tag('@dxos/client-services/ClientServicesHost')<\n ClientServicesHostService,\n ClientServicesHost\n>() {}\n\n/**\n * Layer that constructs a {@link ClientServicesHost} from its props and exposes it under\n * {@link ClientServicesHostService}. Host lifecycle (`open` / `close`) stays caller-driven.\n */\nexport const layerClientServicesHost = (props: ClientServicesHostProps): Layer.Layer<ClientServicesHostService> =>\n Layer.sync(ClientServicesHostService, () => new ClientServicesHost(props));\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\n\nimport { EchoHostService } from '@dxos/echo-host';\nimport { EdgeConnectionService } from '@dxos/edge-client';\nimport { KeyringApiService } from '@dxos/keyring';\nimport { SignalManagerService } from '@dxos/messaging';\nimport { SwarmNetworkManagerService } from '@dxos/network-manager';\nimport {\n ContactsService,\n DataService,\n DevicesService,\n EdgeAgentService,\n FeedService,\n IdentityService,\n InvitationsService,\n NetworkService,\n QueryService,\n SpacesService,\n} from '@dxos/protocols/rpc';\n\nimport { EdgeAgentServiceImpl } from '../agents';\nimport { DevicesServiceImpl } from '../devices';\nimport { IdentityManagerService, IdentityServiceImpl } from '../identity';\nimport { ContactsServiceImpl } from '../identity/contacts-service';\nimport { EdgeIdentityRecoveryManagerService } from '../identity/identity-recovery-manager';\nimport { InvitationsManagerService, InvitationsServiceImpl } from '../invitations';\nimport { NetworkServiceImpl } from '../network';\nimport { SpaceManagerService } from '../space';\nimport { SpacesServiceImpl } from '../spaces';\nimport { ClientServicesHostService } from './service-host';\n\n//\n// Each client RPC service handler is exposed as an individual Effect service tag. Handlers depend\n// directly on the lower-level component tags they consume (EchoHostService, IdentityManagerService,\n// …); only handlers that need lifecycle orchestration (identity creation, readiness gates)\n// additionally depend on {@link ClientServicesHostService} (the host provides itself into the stack).\n//\n\n/**\n * Union of every client RPC service tag resolved from the stack.\n */\nexport type ClientServicesRpcContext =\n | IdentityService.Tag\n | ContactsService.Tag\n | InvitationsService.Tag\n | DevicesService.Tag\n | SpacesService.Tag\n | NetworkService.Tag\n | EdgeAgentService.Tag\n | DataService.Tag\n | QueryService.Tag\n | FeedService.Tag;\n\n// Identity creation is a lifecycle sequence and profile broadcast iterates live spaces, so both\n// remain orchestrator responsibilities resolved from {@link ClientServicesHostService}.\n// The impl is a {@link Resource}; its open/close lifecycle is bound to the layer scope.\nconst identityServiceLayer = Layer.scoped(\n IdentityService.Tag,\n Effect.gen(function* () {\n const identityManager = yield* IdentityManagerService;\n const recoveryManager = yield* EdgeIdentityRecoveryManagerService;\n const keyring = yield* KeyringApiService;\n const host = yield* ClientServicesHostService;\n const service = new IdentityServiceImpl(\n identityManager,\n recoveryManager,\n keyring,\n async (params, ctx) => {\n const identity = await host.createIdentity(params, ctx);\n await host.initialized.wait();\n return identity;\n },\n (profile) => host.broadcastProfileUpdate(profile),\n );\n yield* Effect.acquireRelease(\n Effect.promise(() => service.open()),\n () => Effect.promise(() => service.close()),\n );\n return service;\n }),\n);\n\nconst contactsServiceLayer = Layer.effect(\n ContactsService.Tag,\n Effect.gen(function* () {\n const identityManager = yield* IdentityManagerService;\n const spaceManager = yield* SpaceManagerService;\n const host = yield* ClientServicesHostService;\n return new ContactsServiceImpl(identityManager, spaceManager, () => host.whenDataSpaceManagerReady());\n }),\n);\n\nconst invitationsServiceLayer = Layer.effect(\n InvitationsService.Tag,\n Effect.map(InvitationsManagerService, (invitationsManager) => new InvitationsServiceImpl(invitationsManager)),\n);\n\nconst devicesServiceLayer = Layer.effect(\n DevicesService.Tag,\n Effect.gen(function* () {\n const identityManager = yield* IdentityManagerService;\n // Edge connection is absent in the non-edge stack, so resolve it optionally.\n const edgeConnection = Option.getOrUndefined(yield* Effect.serviceOption(EdgeConnectionService));\n return new DevicesServiceImpl(identityManager, edgeConnection);\n }),\n);\n\nconst spacesServiceLayer = Layer.effect(\n SpacesService.Tag,\n Effect.gen(function* () {\n const identityManager = yield* IdentityManagerService;\n const spaceManager = yield* SpaceManagerService;\n const echoHost = yield* EchoHostService;\n const host = yield* ClientServicesHostService;\n return new SpacesServiceImpl(identityManager, spaceManager, echoHost, () => host.whenDataSpaceManagerReady());\n }),\n);\n\nconst networkServiceLayer = Layer.effect(\n NetworkService.Tag,\n Effect.gen(function* () {\n const networkManager = yield* SwarmNetworkManagerService;\n const signalManager = yield* SignalManagerService;\n const edgeConnection = Option.getOrUndefined(yield* Effect.serviceOption(EdgeConnectionService));\n return new NetworkServiceImpl(networkManager, signalManager, edgeConnection);\n }),\n);\n\nconst edgeAgentServiceLayer = Layer.effect(\n EdgeAgentService.Tag,\n Effect.gen(function* () {\n const edgeConnection = Option.getOrUndefined(yield* Effect.serviceOption(EdgeConnectionService));\n const host = yield* ClientServicesHostService;\n return new EdgeAgentServiceImpl(() => host.whenEdgeAgentManagerReady(), edgeConnection);\n }),\n);\n\nconst dataServiceLayer = Layer.effect(\n DataService.Tag,\n Effect.map(EchoHostService, (echoHost) => echoHost.dataService),\n);\n\nconst queryServiceLayer = Layer.effect(\n QueryService.Tag,\n Effect.map(EchoHostService, (echoHost) => echoHost.queryService),\n);\n\nconst feedServiceLayer = Layer.effect(\n FeedService.Tag,\n Effect.map(EchoHostService, (echoHost) => echoHost.feedService),\n);\n\n/**\n * Composes every client RPC service handler on top of the component tags exposed by the stack.\n * Each handler keeps its own tag so callers resolve them individually from the stack runtime.\n */\nexport const ClientServicesRpcLayer: Layer.Layer<\n ClientServicesRpcContext,\n never,\n | EchoHostService\n | IdentityManagerService\n | SpaceManagerService\n | InvitationsManagerService\n | EdgeIdentityRecoveryManagerService\n | KeyringApiService\n | SwarmNetworkManagerService\n | SignalManagerService\n | ClientServicesHostService\n> = Layer.mergeAll(\n identityServiceLayer,\n contactsServiceLayer,\n invitationsServiceLayer,\n devicesServiceLayer,\n spacesServiceLayer,\n networkServiceLayer,\n edgeAgentServiceLayer,\n dataServiceLayer,\n queryServiceLayer,\n feedServiceLayer,\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,oBACX,EAAE,WAAW,gBACb,EAAE,eACC;CACH,OAAO,IAAI,QAAkC,EAAE,WAAW;EACxD,MAAM,gBAAgB,IAAI,iBAAiB;EAC3C,MAAM,UAAU,IAAI,WAAgC,UAAU,IAAI;EAElE,MAAM,eAAe;GACnB,MAAM,EAAE,UAAU;GAClB,MACG,QAAQ,SAAS,CAAC,UAAU,UAAU,SAAS,MAAM,YAAY,QAAQ,OAAO,KAAK,GAAG,CAAC,CAAC,CAAA,CAC1F,SAAS,SAAS;IACjB,IAAI,CAAC,QAAQ,IAAI,KAAK,GAAG,GAAG;KAC1B,QAAQ,IAAI,KAAK,KAAK,EAAE,KAAK,CAAC;KAC9B,KAAK,GAAG,SAAS,MAAM;KACvB,cAAc,UAAU,KAAK,IAAI,SAAS,MAAM,CAAC;IACnD;IACA,IAAI,CAAC,QAAQ,IAAI,KAAK,GAAG,CAAC,EAAE,OAC1B,QAAQ,IAAI,KAAK,GAAG,CAAC,CAAE,QAAQ,cAAc,cAAc,KAAK,GAAG;GAEvE,CAAC;GAEH,KAAK,EACH,OAAO,MAAM,KAAK,QAAQ,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,aAAa;IAC5D,SAAS,KA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