@dxos/client-services 0.1.21 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/browser/index.mjs +79 -38
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +82 -41
- package/dist/lib/node/index.cjs.map +3 -3
- package/dist/lib/node/meta.json +1 -1
- package/dist/types/src/packlets/identity/authenticator.d.ts +8 -8
- package/dist/types/src/packlets/identity/authenticator.d.ts.map +1 -1
- package/dist/types/src/packlets/identity/identity-manager.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/services/service-context.d.ts.map +1 -1
- package/dist/types/src/packlets/spaces/data-space-manager.d.ts.map +1 -1
- package/dist/types/src/packlets/spaces/data-space-manager.test.d.ts +2 -0
- package/dist/types/src/packlets/spaces/data-space-manager.test.d.ts.map +1 -0
- package/dist/types/src/packlets/spaces/data-space.d.ts +2 -0
- package/dist/types/src/packlets/spaces/data-space.d.ts.map +1 -1
- package/dist/types/src/packlets/testing/test-builder.d.ts +30 -1
- package/dist/types/src/packlets/testing/test-builder.d.ts.map +1 -1
- package/package.json +28 -28
- package/src/packlets/identity/authenticator.test.ts +4 -4
- package/src/packlets/identity/authenticator.ts +18 -13
- package/src/packlets/identity/identity-manager.ts +2 -4
- package/src/packlets/identity/identity.ts +4 -4
- package/src/packlets/services/service-context.ts +0 -4
- package/src/packlets/spaces/data-space-manager.test.ts +74 -0
- package/src/packlets/spaces/data-space-manager.ts +8 -3
- package/src/packlets/spaces/data-space.ts +12 -0
- package/src/packlets/testing/test-builder.ts +87 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/packlets/deprecated/space.ts", "../../../src/packlets/deprecated/profile.ts", "../../../src/packlets/deprecated/system.ts", "../../../src/packlets/deprecated/tracing.ts", "../../../src/packlets/devtools/devtools.ts", "../../../src/packlets/devtools/feeds.ts", "../../../src/packlets/devtools/keys.ts", "../../../src/packlets/devtools/network.ts", "../../../src/packlets/devtools/spaces.ts", "../../../src/packlets/identity/authenticator.ts", "../../../src/packlets/identity/identity.ts", "../../../src/packlets/identity/identity-manager.ts", "../../../src/packlets/invitations/encoder.ts", "../../../src/packlets/invitations/halo-invitations-handler.ts", "../../../src/packlets/invitations/invitations.ts", "../../../src/packlets/invitations/invitations-handler.ts", "../../../src/packlets/invitations/invitations-proxy.ts", "../../../src/packlets/invitations/halo-invitations-proxy.ts", "../../../src/packlets/invitations/invitations-service.ts", "../../../src/packlets/invitations/halo-invitations-service.ts", "../../../src/packlets/invitations/space-invitations-handler.ts", "../../../src/packlets/invitations/space-invitations-proxy.ts", "../../../src/packlets/invitations/space-invitations-service.ts", "../../../src/packlets/services/service-context.ts", "../../../src/packlets/spaces/data-space-manager.ts", "../../../src/packlets/spaces/data-space.ts", "../../../src/packlets/services/service-definitions.ts", "../../../src/packlets/services/service-host.ts", "../../../src/packlets/identity/devices-service-impl.ts", "../../../src/packlets/network/network-service.ts", "../../../src/packlets/spaces/spaces-service.ts", "../../../src/packlets/storage/storage.ts", "../../../src/packlets/services/service-registry.ts", "../../../src/packlets/services/service-proxy.ts", "../../../src/packlets/vault/iframe-runtime.ts", "../../../src/packlets/vault/services.ts", "../../../src/packlets/vault/worker-runtime.ts", "../../../src/packlets/vault/worker-session.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { EventSubscriptions } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { todo } from '@dxos/debug';\nimport { log } from '@dxos/log';\nimport {\n AuthenticateInvitationRequest,\n CreateSnapshotRequest,\n GetSpaceDetailsRequest,\n Space,\n SpaceMember,\n SpaceDetails,\n SpaceService,\n SetSpaceStateRequest,\n SubscribeMembersRequest,\n SubscribeMembersResponse,\n SubscribeSpacesResponse,\n SubscribeSpaceRequest,\n SubscribeSpaceResponse\n} from '@dxos/protocols/proto/dxos/client';\nimport { SpaceSnapshot } from '@dxos/protocols/proto/dxos/echo/snapshot';\nimport { humanize } from '@dxos/util';\n\nimport { ServiceContext } from '../services';\nimport { InviteeInvitations } from './invitations';\n\n/**\n * Space service implementation.\n * @deprecated\n */\nexport class SpaceServiceImpl implements SpaceService {\n private inviteeInvitations: InviteeInvitations = new Map();\n\n constructor(private readonly serviceContext: ServiceContext) {}\n\n subscribeToSpace(request: SubscribeSpaceRequest): Stream<SubscribeSpaceResponse> {\n return new Stream(({ next }) => {\n next({\n space: {\n publicKey: request.spaceKey,\n isOpen: true,\n isActive: true,\n members: []\n }\n });\n });\n\n // const update = (next: (message: SubscribeSpaceResponse) => void) => {\n // try {\n // const space = this.echo.getSpace(request.space_key);\n // next({\n // space: space && {\n // public_key: space.key,\n // is_open: space.is_open,\n // is_active: space.is_active,\n // members: space.queryMembers().value\n // }\n // });\n // } catch (err) {\n // if (err instanceof InvalidStateError) {\n // // Do nothing.\n // } else {\n // throw err;\n // }\n // }\n // };\n\n // const space = this.serviceContext.brane.getSpace(request.space_key);\n // if (space) {\n // return new Stream(({ next }) => space.update.on(() => update(next)));\n // } else {\n // return new Stream(({ next }) => {\n // let unsubscribeSpace: () => void;\n // const unsubscribeSpaces = this.echo.querySpaces().subscribe((spaces) => {\n // const space = spaces.find((space) => space.key.equals(request.space_key));\n // if (space && !unsubscribeSpace) {\n // unsubscribeSpace = space.update.on(() => update(next));\n // }\n // });\n\n // update(next);\n\n // return () => {\n // unsubscribeSpaces();\n // unsubscribeSpace?.();\n // };\n // });\n // }\n }\n\n subscribeSpaces() {\n return new Stream<SubscribeSpacesResponse>(({ next }) => {\n const subscriptions = new EventSubscriptions();\n\n const onUpdate = () => {\n const spaces = Array.from(this.serviceContext.dataSpaceManager!.spaces.values()).map(\n (space): Space => ({\n publicKey: space.key,\n isOpen: true,\n isActive: true,\n members: Array.from(space.inner.spaceState.members.values()).map((member) => ({\n identityKey: member.key,\n profile: {\n identityKey: member.key,\n displayName: member.assertion.profile?.displayName ?? humanize(member.key)\n },\n presence:\n this.serviceContext.identityManager.identity?.identityKey.equals(member.key) ||\n space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0\n ? SpaceMember.PresenceState.ONLINE\n : SpaceMember.PresenceState.OFFLINE\n }))\n })\n );\n log('update', { spaces });\n next({ spaces });\n };\n\n setTimeout(async () => {\n if (!this.serviceContext.dataSpaceManager) {\n next({ spaces: [] });\n }\n\n await this.serviceContext.initialized.wait();\n\n subscriptions.add(\n this.serviceContext.dataSpaceManager!.updated.on(() => {\n this.serviceContext.dataSpaceManager!.spaces.forEach((space) => {\n subscriptions.add(space.stateUpdate.on(onUpdate));\n subscriptions.add(space.presence.updated.on(onUpdate));\n });\n onUpdate();\n })\n );\n\n this.serviceContext.dataSpaceManager!.spaces.forEach((space) => {\n subscriptions.add(space.stateUpdate.on(onUpdate));\n subscriptions.add(space.presence.updated.on(onUpdate));\n });\n\n onUpdate();\n });\n\n return () => subscriptions.clear();\n });\n }\n\n async getSpaceDetails(request: GetSpaceDetailsRequest): Promise<SpaceDetails> {\n return todo();\n // const space = this.echo.getSpace(request.space_key) ?? raise(new SpaceNotFoundError(request.space_key));\n // return {\n // processedTimeframe: space.timeframe\n // };\n }\n\n async createSpace(): Promise<Space> {\n await this.serviceContext.initialized.wait();\n const space = await this.serviceContext.dataSpaceManager!.createSpace();\n return {\n publicKey: space.key,\n isOpen: true,\n isActive: true\n };\n }\n\n async cloneSpace(snapshot: SpaceSnapshot): Promise<Space> {\n return todo();\n // const space = await this.echo.cloneSpace(snapshot);\n // return {\n // public_key: space.key,\n // is_open: space.is_open,\n // is_active: space.is_active\n // };\n }\n\n async setSpaceState(request: SetSpaceStateRequest) {\n return todo();\n // const space = this.echo.getSpace(request.space_key);\n // if (!space) {\n // throw new Error('Space not found');\n // }\n\n // if (request.open === true) {\n // await space.open();\n // } else if (request.open === false) {\n // await space.close();\n // } // Undefined preserves previous state.\n\n // if (request.active_global === true) {\n // await space.activate({ global: true });\n // } else if (request.active_global === false) {\n // await space.deactivate({ global: true });\n // } // Undefined preserves previous state.\n\n // if (request.active_device === true) {\n // await space.activate({ device: true });\n // } else if (request.active_device === false) {\n // await space.deactivate({ device: true });\n // } // Undefined preserves previous state.\n // return {\n // public_key: space.key,\n // is_open: space.is_open,\n // is_active: space.is_active\n // };\n }\n\n async authenticateInvitation(request: AuthenticateInvitationRequest) {\n assert(request.processId, 'Process ID is missing.');\n const invitation = this.inviteeInvitations.get(request.processId);\n assert(invitation, 'Invitation not found.');\n assert(request.secret, 'Secret not provided.');\n\n // Supply the secret, and move the internal invitation process by triggering the secretTrigger.\n invitation.secret = request.secret;\n invitation.secretTrigger?.();\n }\n\n subscribeMembers(request: SubscribeMembersRequest): Stream<SubscribeMembersResponse> {\n return todo();\n // const space = this.echo.getSpace(request.space_key);\n // if (space) {\n // return resultSetToStream(space.queryMembers(), (members): SubscribeMembersResponse => ({ members }));\n // } else {\n // return new Stream(({ next }) => {\n // let unsubscribeMembers: () => void;\n // const unsubscribeSpaces = this.echo.querySpaces().subscribe((spaces) => {\n // const space = spaces.find((space) => space.key.equals(request.space_key));\n // if (!unsubscribeMembers && space) {\n // const resultSet = space.queryMembers();\n // next({ members: resultSet.value });\n // unsubscribeMembers = resultSet.update.on(() => next({ members: resultSet.value }));\n // }\n // });\n\n // return () => {\n // unsubscribeSpaces();\n // unsubscribeMembers();\n // };\n // });\n // }\n }\n\n async createSnapshot(request: CreateSnapshotRequest): Promise<SpaceSnapshot> {\n return todo();\n // assert(request.space_key);\n // const space = this.echo.getSpace(request.space_key) ?? raise(new SpaceNotFoundError(request.space_key));\n // return space.createSnapshot();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { todo } from '@dxos/debug';\nimport {\n CreateProfileRequest,\n Profile,\n ProfileService,\n RecoverProfileRequest,\n SubscribeProfileResponse\n} from '@dxos/protocols/proto/dxos/client';\n\nimport { ServiceContext } from '../services';\nimport { InviteeInvitations } from './invitations';\n\n/**\n * Profile service implementation.\n * @deprecated\n */\nexport class ProfileServiceImpl implements ProfileService {\n private inviteeInvitations: InviteeInvitations = new Map();\n\n constructor(private readonly context: ServiceContext) {}\n\n subscribeProfile(): Stream<SubscribeProfileResponse> {\n return new Stream(({ next }) => {\n const emitNext = () =>\n next({\n profile: this.context.identityManager.identity\n ? {\n identityKey: this.context.identityManager.identity.identityKey,\n deviceKey: this.context.identityManager.identity.deviceKey,\n displayName: this.context.identityManager.identity.profileDocument?.displayName\n }\n : undefined\n });\n\n emitNext();\n return this.context.identityManager.stateUpdate.on(emitNext);\n });\n }\n\n async createProfile(request: CreateProfileRequest): Promise<Profile> {\n await this.context.createIdentity({\n displayName: request.displayName\n });\n return {\n identityKey: this.context.identityManager.identity!.identityKey,\n deviceKey: this.context.identityManager.identity!.deviceKey,\n displayName: this.context.identityManager.identity!.profileDocument?.displayName\n };\n }\n\n async recoverProfile(request: RecoverProfileRequest): Promise<Profile> {\n return todo();\n if (!request.seedPhrase) {\n throw new Error('Recovery SeedPhrase not provided.');\n }\n // await this.echo.open();\n // await this.echo.halo.recover(request.seed_phrase);\n // const profile = this.echo.halo.getProfile();\n // assert(profile, 'Recovering profile failed.');\n // return profile;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Config } from '@dxos/config';\nimport { SystemService } from '@dxos/protocols/proto/dxos/client';\n\nimport { ServiceContext } from '../services';\n\n/**\n * @deprecated\n */\nexport class SystemServiceImpl implements SystemService {\n constructor(private readonly _config: Config, private readonly _serviceContext: ServiceContext) {}\n\n // TODO(burdon): Remove.\n async initSession() {\n // Ok.\n }\n\n async getConfig(request: void) {\n return this._config.values;\n }\n\n // TODO(burdon): Connect to iframe RPC heartbeat for network status?\n async getStatus(request: void) {\n return {\n message: `ok: ${Date.now()}`\n };\n }\n\n async reset(request: any) {\n await this._serviceContext.reset();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Config } from '@dxos/config';\nimport { TracingService } from '@dxos/protocols/proto/dxos/devtools/host';\n\n/**\n * @deprecated\n */\nexport class TracingServiceImpl implements TracingService {\n constructor(private readonly _config: Config) {}\n\n async setTracingOptions() {\n throw new Error('Tracing not available.');\n }\n\n subscribeToRpcTrace(): any {\n throw new Error('Tracing not available.');\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event as AsyncEvent } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { Config } from '@dxos/config';\nimport {\n ClearSnapshotsRequest,\n DevtoolsHost, // TODO(burdon): Rename DevtoolsService\n EnableDebugLoggingRequest,\n EnableDebugLoggingResponse,\n Event,\n GetConfigResponse,\n GetNetworkPeersRequest,\n GetNetworkPeersResponse,\n GetSpaceSnapshotRequest,\n GetSpaceSnapshotResponse,\n ResetStorageRequest,\n SaveSpaceSnapshotRequest,\n SaveSpaceSnapshotResponse,\n SubscribeToCredentialMessagesRequest,\n SubscribeToCredentialMessagesResponse,\n SubscribeToFeedBlocksRequest,\n SubscribeToFeedBlocksResponse,\n SubscribeToFeedsRequest,\n SubscribeToFeedsResponse,\n SubscribeToItemsRequest,\n SubscribeToItemsResponse,\n SubscribeToKeyringKeysRequest,\n SubscribeToKeyringKeysResponse,\n SubscribeToNetworkTopicsResponse,\n SubscribeToSpacesRequest,\n SubscribeToSpacesResponse,\n SubscribeToSignalStatusResponse,\n SubscribeToSignalTraceResponse,\n SubscribeToSwarmInfoResponse\n} from '@dxos/protocols/proto/dxos/devtools/host';\n\nimport { ServiceContext } from '../services';\nimport { subscribeToFeedBlocks, subscribeToFeeds } from './feeds';\nimport { subscribeToKeyringKeys } from './keys';\nimport { subscribeToNetworkStatus, subscribeToSignalTrace, subscribeToSwarmInfo } from './network';\nimport { subscribeToSpaces } from './spaces';\n\nexport class DevtoolsHostEvents {\n readonly ready = new AsyncEvent();\n}\n\nexport type DevtoolsServiceParams = {\n events: DevtoolsHostEvents;\n config: Config;\n context: ServiceContext;\n};\n\n/**\n * @deprecated\n */\nexport class DevtoolsServiceImpl implements DevtoolsHost {\n constructor(private readonly params: DevtoolsServiceParams) {}\n\n events(request: void): Stream<Event> {\n return new Stream<Event>(({ next }) => {\n this.params.events.ready.on(() => {\n next({ ready: {} });\n });\n });\n }\n\n getConfig(request: void): Promise<GetConfigResponse> {\n throw new Error();\n }\n\n resetStorage(request: ResetStorageRequest): Promise<void> {\n throw new Error();\n }\n\n enableDebugLogging(request: EnableDebugLoggingRequest): Promise<EnableDebugLoggingResponse> {\n throw new Error();\n }\n\n disableDebugLogging(request: EnableDebugLoggingRequest): Promise<EnableDebugLoggingResponse> {\n throw new Error();\n }\n\n subscribeToKeyringKeys(request: SubscribeToKeyringKeysRequest): Stream<SubscribeToKeyringKeysResponse> {\n return subscribeToKeyringKeys({ keyring: this.params.context.keyring });\n }\n\n subscribeToCredentialMessages(\n request: SubscribeToCredentialMessagesRequest\n ): Stream<SubscribeToCredentialMessagesResponse> {\n throw new Error();\n }\n\n subscribeToSpaces(request: SubscribeToSpacesRequest): Stream<SubscribeToSpacesResponse> {\n return subscribeToSpaces(this.params.context, request);\n }\n\n subscribeToItems(request: SubscribeToItemsRequest): Stream<SubscribeToItemsResponse> {\n throw new Error();\n }\n\n subscribeToFeeds(request: SubscribeToFeedsRequest): Stream<SubscribeToFeedsResponse> {\n return subscribeToFeeds({ feedStore: this.params.context.feedStore }, request);\n }\n\n subscribeToFeedBlocks(request: SubscribeToFeedBlocksRequest): Stream<SubscribeToFeedBlocksResponse> {\n return subscribeToFeedBlocks({ feedStore: this.params.context.feedStore }, request);\n }\n\n getSpaceSnapshot(request: GetSpaceSnapshotRequest): Promise<GetSpaceSnapshotResponse> {\n throw new Error();\n }\n\n saveSpaceSnapshot(request: SaveSpaceSnapshotRequest): Promise<SaveSpaceSnapshotResponse> {\n throw new Error();\n }\n\n clearSnapshots(request: ClearSnapshotsRequest): Promise<void> {\n throw new Error();\n }\n\n getNetworkPeers(request: GetNetworkPeersRequest): Promise<GetNetworkPeersResponse> {\n throw new Error();\n }\n\n subscribeToNetworkTopics(request: void): Stream<SubscribeToNetworkTopicsResponse> {\n throw new Error();\n }\n\n subscribeToSignalStatus(request: void): Stream<SubscribeToSignalStatusResponse> {\n return subscribeToNetworkStatus({ networkManager: this.params.context.networkManager });\n }\n\n subscribeToSignalTrace(): Stream<SubscribeToSignalTraceResponse> {\n return subscribeToSignalTrace({ networkManager: this.params.context.networkManager });\n }\n\n subscribeToSwarmInfo(): Stream<SubscribeToSwarmInfoResponse> {\n return subscribeToSwarmInfo({ networkManager: this.params.context.networkManager });\n }\n}\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { EventSubscriptions } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { FeedIterator, FeedStore, FeedWrapper } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport {\n SubscribeToFeedsRequest,\n SubscribeToFeedsResponse,\n SubscribeToFeedBlocksRequest,\n SubscribeToFeedBlocksResponse\n} from '@dxos/protocols/proto/dxos/devtools/host';\nimport { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { ComplexMap } from '@dxos/util';\n\nexport const subscribeToFeeds = (\n { feedStore }: { feedStore: FeedStore<FeedMessage> },\n { feedKeys }: SubscribeToFeedsRequest\n) =>\n new Stream<SubscribeToFeedsResponse>(({ next }) => {\n if (feedKeys?.length === 0) {\n return;\n }\n\n const feedMap = new ComplexMap<PublicKey, FeedWrapper<FeedMessage>>(PublicKey.hash);\n const subscriptions = new EventSubscriptions();\n\n const update = () => {\n const feeds = feedStore.feeds;\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 });\n next({\n feeds: Array.from(feedMap.values()).map((feed) => ({ feedKey: feed.key, length: feed.properties.length }))\n });\n };\n\n subscriptions.add(feedStore.feedOpened.on(update));\n update();\n\n return () => {\n subscriptions.clear();\n };\n });\n\nexport const subscribeToFeedBlocks = (\n { feedStore }: { feedStore: FeedStore<FeedMessage> },\n { feedKey, maxBlocks = 10 }: SubscribeToFeedBlocksRequest\n) =>\n new Stream<SubscribeToFeedBlocksResponse>(({ next }) => {\n if (!feedKey) {\n return;\n }\n const subscriptions = new EventSubscriptions();\n\n const timeout = setTimeout(async () => {\n const feed = feedStore.getFeed(feedKey);\n if (!feed) {\n return;\n }\n\n const update = async () => {\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 next({\n blocks: blocks.slice(-maxBlocks)\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// Copyright 2020 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { Keyring } from '@dxos/keyring';\nimport { SubscribeToKeyringKeysResponse } from '@dxos/protocols/proto/dxos/devtools/host';\n\nexport const subscribeToKeyringKeys = ({ keyring }: { keyring: Keyring }) =>\n new Stream<SubscribeToKeyringKeysResponse>(({ next }) => {\n const update = () => {\n next({\n keys: keyring.list()\n });\n };\n const unsubscribe = keyring.keysUpdate.on(update);\n update();\n return unsubscribe;\n });\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { PublicKey } from '@dxos/keys';\nimport { CommandTrace } from '@dxos/messaging';\nimport { NetworkManager } from '@dxos/network-manager';\nimport {\n GetNetworkPeersRequest,\n GetNetworkPeersResponse,\n SubscribeToNetworkTopicsResponse,\n SubscribeToSignalStatusResponse,\n SubscribeToSignalTraceResponse,\n SubscribeToSwarmInfoResponse\n} from '@dxos/protocols/proto/dxos/devtools/host';\n\nexport const subscribeToNetworkStatus = ({ networkManager }: { networkManager: NetworkManager }) =>\n new Stream<SubscribeToSignalStatusResponse>(({ next, close }) => {\n const update = () => {\n try {\n const status = networkManager.signalManager.getStatus();\n next({ servers: status });\n } catch (err: any) {\n close(err);\n }\n };\n\n networkManager.signalManager.statusChanged.on(update);\n update();\n });\n\nexport const subscribeToSignalTrace = ({ networkManager }: { networkManager: NetworkManager }) =>\n new Stream<SubscribeToSignalTraceResponse>(({ next }) => {\n next({ events: [] });\n const trace: CommandTrace[] = [];\n networkManager.signalManager.commandTrace.on((msg) => {\n trace.push(msg);\n next({ events: trace.map((msg) => JSON.stringify(msg)) });\n });\n });\n\nexport const subscribeToNetworkTopics = ({ networkManager }: { networkManager: NetworkManager }) =>\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: NetworkManager }) =>\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: NetworkManager },\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';\nimport { Space } from '@dxos/echo-db';\nimport { SubscribeToSpacesRequest, SubscribeToSpacesResponse } from '@dxos/protocols/proto/dxos/devtools/host';\nimport { SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\n\nimport { ServiceContext } from '../services';\n\nexport const subscribeToSpaces = (context: ServiceContext, { spaceKeys = [] }: SubscribeToSpacesRequest) =>\n 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) => {\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?.latestTimeframe,\n genesisFeed: space.genesisFeedKey,\n controlFeed: space.controlFeedKey,\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// Copyright 2022 DXOS.org\n//\n\nimport { Event, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { verifyCredential, CredentialSigner } from '@dxos/credentials';\nimport { AuthProvider, AuthVerifier } from '@dxos/echo-db';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols';\nimport { ComplexSet } from '@dxos/util';\n\nexport const createHaloAuthProvider =\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 schema.getCodecForType('dxos.halo.credentials.Credential').encode(credential);\n };\n\nexport type HaloAuthVerifierParams = {\n trustedDevicesProvider: () => 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 device of the same identity in the HALO space.\n * Will wait up to `authTimeout` for the device key to be added to the trusted set.\n */\nexport class HaloAuthVerifier {\n private _ctx = new Context();\n\n constructor(private readonly _params: HaloAuthVerifierParams) {}\n\n async close() {\n await this._ctx.dispose();\n }\n\n private _isTrustedDevice(deviceKey: PublicKey) {\n const deviceSet = this._params.trustedDevicesProvider();\n return deviceSet.has(deviceKey);\n }\n\n get verifier(): AuthVerifier {\n return async (nonce, auth) => {\n const credential = schema.getCodecForType('dxos.halo.credentials.Credential').decode(auth);\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._isTrustedDevice(credential.issuer)) {\n return true;\n }\n\n const trigger = new Trigger<boolean>();\n this._ctx.onDispose(() => {\n trigger.wake(false);\n });\n const clear = this._params.update.on(this._ctx, () => {\n if (this._isTrustedDevice(credential.issuer)) {\n trigger.wake(true);\n }\n });\n try {\n await trigger.wait({ timeout: this._params.authTimeout });\n return true;\n } catch {\n return false;\n } finally {\n clear();\n }\n };\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Event } from '@dxos/async';\nimport {\n DeviceStateMachine,\n CredentialSigner,\n createCredentialSignerWithKey,\n createCredentialSignerWithChain,\n ProfileStateMachine,\n CredentialConsumer\n} from '@dxos/credentials';\nimport { Signer } from '@dxos/crypto';\nimport { Space } from '@dxos/echo-db';\nimport { writeMessages } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { TypedMessage } from '@dxos/protocols';\nimport { AdmittedFeed, ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { HaloAdmissionCredentials } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { ComplexSet } from '@dxos/util';\n\nimport { HaloAuthVerifier } from './authenticator';\n\n/**\n * Timeout for the device to be added to the trusted set during auth.\n */\nconst AUTH_TIMEOUT = 30000;\n\nexport type IdentityParams = {\n identityKey: PublicKey;\n deviceKey: PublicKey;\n signer: Signer;\n space: Space;\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 _deviceStateMachine: CredentialConsumer<DeviceStateMachine>;\n private readonly _profileStateMachine: CredentialConsumer<ProfileStateMachine>;\n public readonly authVerifier: HaloAuthVerifier;\n\n public readonly identityKey: PublicKey;\n public readonly deviceKey: PublicKey;\n\n public readonly stateUpdate = new Event();\n\n constructor({ space, signer, identityKey, deviceKey }: IdentityParams) {\n this.space = space;\n this._signer = signer;\n\n this.identityKey = identityKey;\n this.deviceKey = deviceKey;\n\n this._deviceStateMachine = this.space.spaceState.registerProcessor(\n new DeviceStateMachine({\n identityKey: this.identityKey,\n deviceKey: this.deviceKey,\n onUpdate: () => this.stateUpdate.emit()\n })\n );\n this._profileStateMachine = this.space.spaceState.registerProcessor(\n new ProfileStateMachine({\n identityKey: this.identityKey,\n onUpdate: () => this.stateUpdate.emit()\n })\n );\n\n this.authVerifier = new HaloAuthVerifier({\n trustedDevicesProvider: () => this.authorizedDeviceKeys,\n update: this.stateUpdate,\n authTimeout: AUTH_TIMEOUT\n });\n }\n\n // TODO(burdon): Expose state object?\n get authorizedDeviceKeys(): ComplexSet<PublicKey> {\n return this._deviceStateMachine.processor.authorizedDeviceKeys;\n }\n\n async open() {\n await this._deviceStateMachine.open();\n await this._profileStateMachine.open();\n await this.space.open();\n }\n\n async close() {\n await this.authVerifier.close();\n await this._deviceStateMachine.close();\n await this._profileStateMachine.close();\n await this.space.close();\n }\n\n async ready() {\n await this._deviceStateMachine.processor.deviceChainReady.wait();\n\n // TODO(dmaretskyi): Should we also wait for our feeds to be admitted?\n }\n\n get profileDocument(): ProfileDocument | undefined {\n return this._profileStateMachine.processor.profile;\n }\n\n /**\n * @test-only\n */\n get controlPipeline() {\n return this.space.controlPipeline;\n }\n\n get haloSpaceKey() {\n return this.space.key;\n }\n\n get haloGenesisFeedKey() {\n return this.space.genesisFeedKey;\n }\n\n getAdmissionCredentials(): HaloAdmissionCredentials {\n return {\n deviceKey: this.deviceKey,\n controlFeedKey: this.space.controlFeedKey,\n dataFeedKey: this.space.dataFeedKey\n };\n }\n\n /**\n * Issues credentials as identity.\n * Requires identity to be ready.\n */\n getIdentityCredentialSigner(): CredentialSigner {\n assert(this._deviceStateMachine.processor.deviceCredentialChain, 'Device credential chain is not ready.');\n return createCredentialSignerWithChain(\n this._signer,\n this._deviceStateMachine.processor.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 }: HaloAdmissionCredentials) {\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 await writeMessages(\n this.controlPipeline.writer,\n [\n await signer.createCredential({\n subject: deviceKey,\n assertion: {\n '@type': 'dxos.halo.credentials.AuthorizedDevice',\n identityKey: this.identityKey,\n deviceKey\n }\n }),\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): TypedMessage => ({ '@type': 'dxos.echo.feed.CredentialsMessage', credential }))\n );\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Event } from '@dxos/async';\nimport { createCredentialSignerWithKey, CredentialGenerator } from '@dxos/credentials';\nimport { MetadataStore, SpaceManager, SwarmIdentity } from '@dxos/echo-db';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { AdmittedFeed, IdentityRecord, SpaceRecord } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { deferFunction } from '@dxos/util';\n\nimport { Identity } from '../identity';\nimport { createHaloAuthProvider } from './authenticator';\n\ninterface ConstructSpaceParams {\n spaceRecord: SpaceRecord;\n swarmIdentity: SwarmIdentity;\n identityKey: PublicKey;\n}\n\nexport type JoinIdentityParams = {\n identityKey: PublicKey;\n haloSpaceKey: PublicKey;\n haloGenesisFeedKey: PublicKey;\n};\n\nexport type CreateIdentityOptions = {\n displayName?: string;\n};\n\n// TODO(dmaretskyi): Rename: represents the peer's state machine.\nexport class IdentityManager {\n readonly stateUpdate = new Event();\n\n private _identity?: Identity;\n\n // TODO(burdon): IdentityManagerParams.\n // TODO(dmaretskyi): Perhaps this should take/generate the peerKey outside of an initialized identity.\n constructor(\n private readonly _metadataStore: MetadataStore,\n private readonly _keyring: Keyring,\n private readonly _spaceManager: SpaceManager\n ) {}\n\n get identity() {\n return this._identity;\n }\n\n async open() {\n await this._metadataStore.load();\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();\n await this._identity.ready();\n this.stateUpdate.emit();\n }\n }\n\n async close() {\n await this._identity?.close();\n }\n\n async createIdentity({ displayName }: CreateIdentityOptions = {}) {\n assert(!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 spaceKey: await this._keyring.createKey(),\n genesisFeedKey: controlFeedKey,\n writeControlFeedKey: controlFeedKey,\n writeDataFeedKey: await this._keyring.createKey()\n }\n };\n\n const identity = await this._constructIdentity(identityRecord);\n await identity.open();\n\n {\n const generator = new CredentialGenerator(this._keyring, identityRecord.identityKey, identityRecord.deviceKey);\n const credentials = [\n // Space genesis.\n ...(await generator.createSpaceGenesis(\n identityRecord.haloSpace.spaceKey,\n identityRecord.haloSpace.genesisFeedKey\n )),\n\n // Feed admission.\n await generator.createFeedAdmission(\n identityRecord.haloSpace.spaceKey,\n identityRecord.haloSpace.writeDataFeedKey,\n AdmittedFeed.Designation.DATA\n )\n ];\n\n if (displayName) {\n credentials.push(await generator.createProfileCredential({ displayName }));\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 for (const credential of credentials) {\n await identity.controlPipeline.writer.write({\n '@type': 'dxos.echo.feed.CredentialsMessage',\n credential\n });\n }\n }\n\n // TODO(burdon): ???\n // await this._keyring.deleteKey(identityRecord.identity_key);\n // await this._keyring.deleteKey(identityRecord.halo_space.space_key);\n\n await this._metadataStore.setIdentityRecord(identityRecord);\n this._identity = identity;\n await this._identity.ready();\n this.stateUpdate.emit();\n\n log('created identity', { identityKey: identity.identityKey, deviceKey: identity.deviceKey });\n return identity;\n }\n\n /**\n * Accept an existing identity. Expects it's device key to be authorized (now or later).\n */\n async acceptIdentity(params: JoinIdentityParams) {\n log('accepting identity', { params });\n assert(!this._identity, 'Identity already exists.');\n\n const identityRecord: IdentityRecord = {\n identityKey: params.identityKey,\n deviceKey: await this._keyring.createKey(),\n haloSpace: {\n spaceKey: params.haloSpaceKey,\n genesisFeedKey: params.haloGenesisFeedKey,\n writeControlFeedKey: await this._keyring.createKey(),\n writeDataFeedKey: await this._keyring.createKey()\n }\n };\n const identity = await this._constructIdentity(identityRecord);\n\n await identity.open();\n this._identity = identity;\n await this._metadataStore.setIdentityRecord(identityRecord);\n this.stateUpdate.emit();\n return identity;\n }\n\n private async _constructIdentity(identityRecord: IdentityRecord) {\n assert(!this._identity);\n log('constructing identity', { identityRecord });\n\n const space = await this._constructSpace({\n spaceRecord: identityRecord.haloSpace,\n swarmIdentity: {\n peerKey: identityRecord.deviceKey,\n credentialProvider: createHaloAuthProvider(\n createCredentialSignerWithKey(this._keyring, identityRecord.deviceKey)\n ),\n credentialAuthenticator: deferFunction(() => identity.authVerifier.verifier)\n },\n identityKey: identityRecord.identityKey\n });\n const identity: Identity = new Identity({\n space,\n signer: this._keyring,\n identityKey: identityRecord.identityKey,\n deviceKey: identityRecord.deviceKey\n });\n log('done', { identityKey: identityRecord.identityKey });\n\n return identity;\n }\n\n private async _constructSpace({ spaceRecord, swarmIdentity, identityKey }: ConstructSpaceParams) {\n return this._spaceManager.constructSpace({\n metadata: {\n key: spaceRecord.spaceKey,\n genesisFeedKey: spaceRecord.genesisFeedKey,\n controlFeedKey: spaceRecord.writeControlFeedKey,\n dataFeedKey: spaceRecord.writeDataFeedKey\n },\n swarmIdentity,\n onNetworkConnection: () => {}\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport base from 'base-x';\n\nimport { schema } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\n// Encode with URL-safe alpha-numeric characters.\nconst base62 = base('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');\n\nconst codec = schema.getCodecForType('dxos.client.services.Invitation');\n\n/**\n * Encodes and decodes an invitation proto into/from alphanumeric chars.\n */\nexport class InvitationEncoder {\n static decode(text: string): Invitation {\n return codec.decode(base62.decode(text));\n }\n\n static encode(invitation: Invitation): string {\n return base62.encode(codec.encode(invitation));\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { scheduleTask, sleep, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { generatePasscode } from '@dxos/credentials';\nimport { failUndefined } from '@dxos/debug';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { createTeleportProtocolFactory, NetworkManager, StarTopology } from '@dxos/network-manager';\nimport { schema } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport {\n AuthenticationRequest,\n AuthenticationResponse,\n HaloAdmissionCredentials,\n HaloAdmissionOffer,\n HaloHostService\n} from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport { IdentityManager } from '../identity';\nimport {\n AuthenticatingInvitationProvider,\n AUTHENTICATION_CODE_LENGTH,\n CancellableInvitationObservable,\n InvitationObservableProvider,\n INVITATION_TIMEOUT,\n ON_CLOSE_DELAY\n} from './invitations';\nimport { AbstractInvitationsHandler, InvitationsOptions } from './invitations-handler';\n\n/**\n * Handles the life-cycle of Halo invitations between peers.\n */\n// TODO(dmaretskyi): Split into Host and Guest parts.\nexport class HaloInvitationsHandler extends AbstractInvitationsHandler {\n // prettier-ignore\n constructor(\n networkManager: NetworkManager,\n private readonly _identityManager: IdentityManager\n ) {\n super(networkManager);\n }\n\n /**\n * Creates an invitation and listens for a join request from the invited (guest) peer.\n */\n createInvitation(context: void, options?: InvitationsOptions): CancellableInvitationObservable {\n const { type, timeout = INVITATION_TIMEOUT, swarmKey } = options ?? {};\n assert(type !== Invitation.Type.OFFLINE);\n const identity = this._identityManager.identity ?? failUndefined();\n\n // TODO(dmaretskyi): Add invitation kind: halo/space.\n const invitation: Invitation = {\n type,\n invitationId: PublicKey.random().toHex(),\n swarmKey: swarmKey ?? PublicKey.random(),\n authenticationCode: generatePasscode(AUTHENTICATION_CODE_LENGTH)\n };\n\n const ctx = new Context({\n onError: (err) => {\n void ctx.dispose();\n observable.callback.onError(err);\n }\n });\n\n // TODO(burdon): Stop anything pending.\n const observable = new InvitationObservableProvider(async () => {\n await ctx.dispose();\n });\n\n let authenticationCode: string;\n const complete = new Trigger<PublicKey>();\n\n // Called for every connecting peer.\n const createExtension = (): HostHaloInvitationExtension => {\n const hostInvitationExtension = new HostHaloInvitationExtension({\n requestAdmission: async () => {\n log('responding with admission offer', {\n host: identity.deviceKey\n });\n\n // TODO(burdon): Is this the right place to set this state?\n observable.callback.onAuthenticating?.(invitation);\n return {\n identityKey: identity.identityKey,\n haloSpaceKey: identity.haloSpaceKey,\n genesisFeedKey: identity.haloGenesisFeedKey\n };\n },\n\n authenticate: async ({ authenticationCode: code }) => {\n log('received authentication request', { authenticationCode: code });\n authenticationCode = code;\n return { status: AuthenticationResponse.Status.OK };\n },\n\n // TODO(burdon): Not used: controlFeedKey, dataFeedKey.\n presentAdmissionCredentials: async (credentials) => {\n try {\n // Check authenticated.\n if (invitation.type !== Invitation.Type.INTERACTIVE_TESTING) {\n if (invitation.authenticationCode === undefined || invitation.authenticationCode !== authenticationCode) {\n throw new Error(`invalid authentication code: ${authenticationCode}`);\n }\n }\n\n log('writing guest credentials', { host: identity.deviceKey, guest: credentials.deviceKey });\n // TODO(burdon): Check if already admitted.\n await identity.admitDevice(credentials);\n\n // Updating credentials complete.\n complete.wake(credentials.deviceKey);\n } catch (err) {\n // TODO(burdon): Generic RPC callback to report error to client.\n observable.callback.onError(err);\n throw err; // Propagate error to guest.\n }\n },\n\n onOpen: () => {\n scheduleTask(ctx, async () => {\n try {\n log('connected', { host: identity.deviceKey });\n observable.callback.onConnected?.(invitation);\n const deviceKey = await complete.wait({ timeout });\n log('admitted guest', { host: identity.deviceKey, guest: deviceKey });\n observable.callback.onSuccess(invitation);\n } catch (err) {\n if (!observable.cancelled) {\n log.error('failed', err);\n observable.callback.onError(err);\n }\n } finally {\n // NOTE: If we close immediately after `complete` trigger finishes, Guest won't receive the reply to the last RPC.\n // TODO(dmaretskyi): Implement a soft-close which waits for the last connection to terminate before closing.\n await sleep(ON_CLOSE_DELAY);\n await ctx.dispose();\n }\n });\n }\n });\n return hostInvitationExtension;\n };\n\n scheduleTask(ctx, async () => {\n const topic = invitation.swarmKey!;\n const swarmConnection = await this._networkManager.joinSwarm({\n topic,\n peerId: topic,\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', createExtension());\n }),\n topology: new StarTopology(topic)\n });\n ctx.onDispose(() => swarmConnection.close());\n\n observable.callback.onConnecting?.(invitation);\n });\n\n return observable;\n }\n\n /**\n * Waits for the host peer (inviter) to accept our join request.\n * The local guest peer (invitee) then sends the local halo invitation to the host,\n * which then writes the guest's credentials to the halo.\n */\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationProvider {\n const { timeout = INVITATION_TIMEOUT } = options ?? {};\n\n const ctx = new Context({\n onError: (err) => {\n void ctx.dispose();\n observable.callback.onError(err);\n }\n });\n\n const authenticated = new Trigger<string>();\n const observable = new AuthenticatingInvitationProvider({\n onCancel: async () => {\n await ctx.dispose();\n },\n\n // TODO(burdon): Consider retry.\n onAuthenticate: async (code: string) => {\n authenticated.wake(code);\n }\n });\n\n let connectionCount = 0;\n const complete = new Trigger<PublicKey>();\n\n const createExtension = (): GuestHaloInvitationExtension => {\n const extension = new GuestHaloInvitationExtension({\n onOpen: () => {\n scheduleTask(ctx, async () => {\n try {\n // TODO(burdon): Bug where guest may create multiple connections.\n if (++connectionCount > 1) {\n throw new Error(`multiple connections detected: ${connectionCount}`);\n }\n\n log('connected');\n observable.callback.onConnected?.(invitation);\n\n // 1. Send request.\n log('sending admission request');\n const { identityKey, haloSpaceKey, genesisFeedKey } =\n await extension.rpc.HaloHostService.requestAdmission();\n\n // 2. Get authentication code.\n // TODO(burdon): Test timeout (options for timeouts at different steps).\n if (invitation.type === undefined || invitation.type === Invitation.Type.INTERACTIVE) {\n log('guest waiting for authentication code...');\n observable.callback.onAuthenticating?.(invitation);\n const authenticationCode = await authenticated.wait({ timeout });\n log('sending authentication request');\n await extension.rpc.HaloHostService.authenticate({ authenticationCode });\n }\n\n // 3. Create local identity.\n // TODO(burdon): Abandon if does not complete (otherwise retry will fail).\n const identity = await this._identityManager.acceptIdentity({\n identityKey,\n haloSpaceKey,\n haloGenesisFeedKey: genesisFeedKey\n });\n\n // 4. Send admission credentials to host (with local identity keys).\n log('presenting admission credentials', { guest: identity.deviceKey, identityKey });\n await extension.rpc.HaloHostService.presentAdmissionCredentials(identity.getAdmissionCredentials());\n\n // 5. Success.\n log('admitted by host', { guest: identity.deviceKey, identityKey });\n complete.wake(identityKey);\n } catch (err) {\n if (!observable.cancelled) {\n log.warn('auth failed', err);\n observable.callback.onError(err);\n }\n } finally {\n await ctx.dispose();\n }\n });\n }\n });\n return extension;\n };\n\n scheduleTask(ctx, async () => {\n assert(invitation.swarmKey);\n const topic = invitation.swarmKey;\n const swarmConnection = await this._networkManager.joinSwarm({\n topic,\n peerId: PublicKey.random(),\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', createExtension());\n }),\n topology: new StarTopology(topic)\n });\n ctx.onDispose(() => swarmConnection.close());\n\n observable.callback.onConnecting?.(invitation);\n invitation.identityKey = await complete.wait();\n observable.callback.onSuccess(invitation);\n await ctx.dispose();\n });\n\n return observable;\n }\n}\n\ntype HostHaloInvitationExtensionCallbacks = {\n requestAdmission: () => Promise<HaloAdmissionOffer>;\n authenticate: (request: AuthenticationRequest) => Promise<AuthenticationResponse>;\n presentAdmissionCredentials: (request: HaloAdmissionCredentials) => Promise<void>;\n // Deliberately not async to not block the extensions opening.\n onOpen: () => void;\n};\n\n/**\n * Host's side for a connection to a concrete peer in p2p network during invitation.\n */\nclass HostHaloInvitationExtension extends RpcExtension<{}, { HaloHostService: HaloHostService }> {\n constructor(private readonly _callbacks: HostHaloInvitationExtensionCallbacks) {\n super({\n exposed: {\n HaloHostService: schema.getService('dxos.halo.invitations.HaloHostService')\n }\n });\n }\n\n protected override async getHandlers(): Promise<{ HaloHostService: HaloHostService }> {\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 HaloHostService: {\n requestAdmission: async () => {\n return this._callbacks.requestAdmission();\n },\n\n authenticate: async (credentials) => {\n return this._callbacks.authenticate(credentials);\n },\n\n // TODO(burdon): Not used: controlFeedKey, dataFeedKey.\n presentAdmissionCredentials: async (credentials) => {\n return this._callbacks.presentAdmissionCredentials(credentials);\n }\n }\n };\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n this._callbacks.onOpen();\n }\n}\n\ntype GuestHaloInvitationExtensionCallbacks = {\n // Deliberately not async to not block the extensions opening.\n onOpen: () => void;\n};\n\n/**\n * Guest's side for a connection to a concrete peer in p2p network during invitation.\n */\nclass GuestHaloInvitationExtension extends RpcExtension<{ HaloHostService: HaloHostService }, {}> {\n constructor(private readonly _callbacks: GuestHaloInvitationExtensionCallbacks) {\n super({\n requested: {\n HaloHostService: schema.getService('dxos.halo.invitations.HaloHostService')\n }\n });\n }\n\n protected override async getHandlers() {\n return {};\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n this._callbacks.onOpen();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport {\n AsyncEvents,\n CancellableObservable,\n CancellableObservableEvents,\n CancellableObservableProvider\n} from '@dxos/async';\nimport type { Stream } from '@dxos/codec-protobuf';\nimport { AuthenticationRequest, CancelInvitationRequest, Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nexport const AUTHENTICATION_CODE_LENGTH = 6;\n\nexport const INVITATION_TIMEOUT = 3 * 60_000; // 3 mins.\n\n// TODO(burdon): Don't close until RPC has complete (bug).\nexport const ON_CLOSE_DELAY = 500;\n\nexport interface InvitationsService {\n createInvitation(invitation: Invitation): Stream<Invitation>;\n authenticate(request: AuthenticationRequest): Promise<void>;\n acceptInvitation(invitation: Invitation): Stream<Invitation>;\n cancelInvitation(request: CancelInvitationRequest): Promise<void>;\n}\n\n/**\n * Common invitation events (callbacks) for creating and accepting invitations.\n */\n// TODO(burdon): Remove optionals.\nexport interface InvitationEvents extends AsyncEvents, CancellableObservableEvents {\n onConnecting?(invitation: Invitation): void;\n onConnected?(invitation: Invitation): void;\n onAuthenticating?(invitation: Invitation): void;\n onSuccess(invitation: Invitation): void; // TODO(burdon): Collides with AsyncEvents.\n}\n\n/**\n * Base class for all invitation observables and providers.\n * Observable that supports inspection of the current value.\n */\nexport interface CancellableInvitationObservable extends CancellableObservable<InvitationEvents> {\n get invitation(): Invitation | undefined;\n}\n\nexport class InvitationObservableProvider\n extends CancellableObservableProvider<InvitationEvents>\n implements CancellableInvitationObservable\n{\n private _invitation?: Invitation;\n\n get invitation(): Invitation | undefined {\n return this._invitation;\n }\n\n setInvitation(invitation: Invitation) {\n this._invitation = invitation;\n }\n}\n\n/**\n * Cancelable observer that relays authentication requests.\n */\nexport interface AuthenticatingInvitationObservable extends CancellableInvitationObservable {\n authenticate(code: string): Promise<void>;\n}\n\nexport interface AuthenticatingInvitationProviderActions {\n onCancel(): Promise<void>;\n onAuthenticate(code: string): Promise<void>;\n}\n\nexport class AuthenticatingInvitationProvider\n extends InvitationObservableProvider\n implements AuthenticatingInvitationObservable\n{\n // prettier-ignore\n constructor(\n private readonly _actions: AuthenticatingInvitationProviderActions\n ) {\n super(() => this._actions.onCancel());\n }\n\n async authenticate(authenticationCode: string): Promise<void> {\n return this._actions.onAuthenticate(authenticationCode);\n }\n}\n\n/**\n * Testing util to wrap non-authenticating observable with promise.\n * Don't use this in production code.\n * @deprecated\n */\n// TODO(burdon): Throw error if auth requested.\nexport const wrapObservable = async (observable: CancellableInvitationObservable): Promise<Invitation> => {\n return new Promise((resolve, reject) => {\n const unsubscribe = observable.subscribe({\n onSuccess: (invitation: Invitation) => {\n assert(invitation.state === Invitation.State.SUCCESS);\n unsubscribe();\n resolve(invitation);\n },\n onError: (err: Error) => {\n unsubscribe();\n reject(err);\n }\n });\n });\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { PublicKey } from '@dxos/keys';\nimport { NetworkManager } from '@dxos/network-manager';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { AuthenticatingInvitationObservable, CancellableInvitationObservable } from './invitations';\n\nexport type InvitationsOptions = {\n type?: Invitation.Type;\n timeout?: number;\n // Used for debugging.\n swarmKey?: PublicKey;\n};\n\n/**\n * Common interface for Halo and Space invitation proxies and handlers.\n * Handles the life-cycle of Space 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 admission request.\n * - Wait for guest to authenticate with OTP.\n * - Waits for guest to present credentials (containing local device and feed keys).\n * - Writes credentials to control feed then exits.\n *\n * Guest\n * - Joins the swarm with the topic.\n * - Sends an admission request.\n * - Sends authentication OTP.\n * - If Space handler then creates a local cloned space (with genesis block).\n * - Sends admission credentials.\n *\n * TODO(burdon): Show proxy/service relationship and reference design doc/diagram.\n *\n * ```\n * [Guest] [Host]\n * |-----------------------------RequestAdmission-->|\n * |-------------------------------[Authenticate]-->|\n * |------------------PresentAdmissionCredentials-->|\n * ```\n */\nexport interface InvitationsHandler<T = void> {\n createInvitation(context: T, options?: InvitationsOptions): CancellableInvitationObservable;\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationObservable;\n}\n\n/**\n * Base class for Halo/Space invitations handlers.\n */\n// TODO(burdon): Extract common functionality.\nexport abstract class AbstractInvitationsHandler<T = void> implements InvitationsHandler<T> {\n // prettier-ignore\n protected constructor(\n protected readonly _networkManager: NetworkManager\n ) {}\n\n abstract createInvitation(context: T, options?: InvitationsOptions): CancellableInvitationObservable;\n abstract acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationObservable;\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { observableError } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { log } from '@dxos/log';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nimport {\n AuthenticatingInvitationObservable,\n AuthenticatingInvitationProvider,\n CancellableInvitationObservable,\n InvitationObservableProvider,\n InvitationsService\n} from './invitations';\nimport { InvitationsOptions, InvitationsHandler } from './invitations-handler';\n\n/**\n * Adapts invitations service observable to client/service stream.\n * Common base class for HALO and Spaces implementations.\n */\nexport interface InvitationsProxy<T = void> extends InvitationsHandler<T> {\n getInvitationOptions(context: T): Invitation;\n}\n\nexport abstract class AbstractInvitationsProxy<T = void> implements InvitationsProxy<T> {\n // prettier-ignore\n constructor(\n private readonly _invitationsService: InvitationsService\n ) {}\n\n abstract getInvitationOptions(context: T): Invitation;\n\n createInvitation(context: T, options?: InvitationsOptions): CancellableInvitationObservable {\n let invitationId: string;\n const observable = new InvitationObservableProvider(async () => {\n if (invitationId) {\n await this._invitationsService.cancelInvitation({ invitationId });\n }\n });\n\n const invitation: Invitation = { ...this.getInvitationOptions(context), ...options };\n const stream: Stream<Invitation> = this._invitationsService.createInvitation(invitation);\n\n stream.subscribe(\n (invitation: Invitation) => {\n observable.setInvitation(invitation);\n\n switch (invitation.state) {\n case Invitation.State.CONNECTING: {\n assert(invitation.invitationId);\n invitationId = invitation.invitationId;\n observable.callback.onConnecting?.(invitation);\n break;\n }\n\n case Invitation.State.CONNECTED: {\n observable.callback.onConnected?.(invitation);\n break;\n }\n\n case Invitation.State.AUTHENTICATING: {\n observable.callback.onAuthenticating?.(invitation);\n break;\n }\n\n case Invitation.State.SUCCESS: {\n observable.callback.onSuccess?.(invitation);\n break;\n }\n\n case Invitation.State.CANCELLED: {\n observable.callback.onCancelled?.();\n break;\n }\n\n default: {\n log.error(`Invalid state: ${invitation.state}`);\n }\n }\n },\n (err) => {\n if (err) {\n observableError(observable, err);\n }\n }\n );\n\n return observable;\n }\n\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationObservable {\n assert(invitation && invitation.swarmKey);\n\n const observable = new AuthenticatingInvitationProvider({\n onCancel: async () => {\n const invitationId = observable.invitation?.invitationId;\n assert(invitationId);\n await this._invitationsService.cancelInvitation({ invitationId });\n },\n\n onAuthenticate: async (authenticationCode: string) => {\n const invitationId = observable.invitation?.invitationId;\n assert(invitationId);\n await this._invitationsService.authenticate({ invitationId, authenticationCode });\n }\n });\n\n const stream: Stream<Invitation> = this._invitationsService.acceptInvitation({ ...invitation, ...options });\n\n stream.subscribe(\n (invitation: Invitation) => {\n assert(invitation.invitationId);\n observable.setInvitation(invitation);\n\n switch (invitation.state) {\n case Invitation.State.CONNECTING: {\n observable.callback.onConnecting?.(invitation);\n break;\n }\n\n case Invitation.State.CONNECTED: {\n observable.callback.onConnected?.(invitation);\n break;\n }\n\n case Invitation.State.AUTHENTICATING: {\n observable.callback.onAuthenticating?.(invitation);\n break;\n }\n\n case Invitation.State.SUCCESS: {\n observable.callback.onSuccess?.(invitation);\n break;\n }\n\n case Invitation.State.CANCELLED: {\n observable.callback.onCancelled?.();\n break;\n }\n\n default: {\n log.error(`Invalid state: ${invitation.state}`);\n }\n }\n },\n (err) => {\n if (err) {\n observableError(observable, err);\n }\n }\n );\n\n return observable;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { AbstractInvitationsProxy } from './invitations-proxy';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class HaloInvitationsProxy extends AbstractInvitationsProxy {\n getInvitationOptions() {\n return {};\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { TimeoutError } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { log } from '@dxos/log';\nimport { AuthenticationRequest, Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { Provider } from '@dxos/util';\n\nimport { IdentityManager } from '../identity';\nimport { AuthenticatingInvitationObservable, CancellableInvitationObservable, InvitationsService } from './invitations';\nimport { InvitationsHandler, InvitationsOptions } from './invitations-handler';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport abstract class AbstractInvitationsService<T = void> implements InvitationsService {\n private readonly _createInvitations = new Map<string, CancellableInvitationObservable>();\n private readonly _acceptInvitations = new Map<string, AuthenticatingInvitationObservable>();\n\n // prettier-ignore\n protected constructor (\n private readonly _identityManager: IdentityManager,\n private readonly _getInvitationsHandler: Provider<InvitationsHandler<T>>\n ) {}\n\n // TODO(burdon): Guest/host label.\n getLoggingContext() {\n return {\n deviceKey: this._identityManager.identity?.deviceKey\n };\n }\n\n abstract getContext(invitation: Invitation): T;\n\n createInvitation(invitation: Invitation): Stream<Invitation> {\n return new Stream<Invitation>(({ next, close }) => {\n const invitationsHandler: InvitationsHandler<T> = this._getInvitationsHandler();\n const context = this.getContext(invitation);\n log('stream opened', this.getLoggingContext());\n\n let invitationId: string;\n const { type, swarmKey } = invitation;\n const observable = invitationsHandler.createInvitation(context, { type, swarmKey });\n observable.subscribe({\n onConnecting: (invitation) => {\n assert(invitation.invitationId);\n invitationId = invitation.invitationId;\n this._createInvitations.set(invitation.invitationId, observable);\n invitation.state = Invitation.State.CONNECTING;\n next(invitation);\n },\n onConnected: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.CONNECTED;\n next(invitation);\n },\n onAuthenticating: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.AUTHENTICATING;\n next(invitation);\n },\n onSuccess: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.SUCCESS;\n next(invitation);\n close();\n },\n onCancelled: () => {\n assert(invitationId);\n invitation.invitationId = invitationId;\n invitation.state = Invitation.State.CANCELLED;\n next(invitation);\n close();\n },\n onTimeout: (err: TimeoutError) => {\n invitation.state = Invitation.State.TIMEOUT;\n close(err);\n },\n onError: (err: any) => {\n invitation.state = Invitation.State.ERROR;\n close(err);\n }\n });\n\n return (err?: Error) => {\n const context = this.getLoggingContext();\n if (err) {\n log.warn('stream closed', { ...context, err });\n } else {\n log('stream closed', context);\n }\n\n this._createInvitations.delete(invitation.invitationId!);\n };\n });\n }\n\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): Stream<Invitation> {\n return new Stream<Invitation>(({ next, close }) => {\n log('stream opened', this.getLoggingContext());\n const invitationsHandler = this._getInvitationsHandler();\n\n let invitationId: string;\n const observable = invitationsHandler.acceptInvitation(invitation, options);\n observable.subscribe({\n onConnecting: (invitation) => {\n assert(invitation.invitationId);\n invitationId = invitation.invitationId;\n this._acceptInvitations.set(invitation.invitationId, observable);\n invitation.state = Invitation.State.CONNECTING;\n next(invitation);\n },\n onConnected: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.CONNECTED;\n next(invitation);\n },\n onAuthenticating: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.AUTHENTICATING;\n next(invitation);\n },\n onSuccess: (invitation) => {\n invitation.state = Invitation.State.SUCCESS;\n next(invitation);\n close();\n },\n onCancelled: () => {\n assert(invitationId);\n invitation.invitationId = invitationId;\n invitation.state = Invitation.State.CANCELLED;\n next(invitation);\n close();\n },\n onTimeout: (err: TimeoutError) => {\n invitation.state = Invitation.State.TIMEOUT;\n close(err);\n },\n onError: (err: any) => {\n invitation.state = Invitation.State.ERROR;\n close(err);\n }\n });\n\n return (err?: Error) => {\n const context = this.getLoggingContext();\n if (err) {\n log.warn('stream closed', { ...context, err });\n } else {\n log('stream closed', context);\n }\n\n this._acceptInvitations.delete(invitation.invitationId!);\n };\n });\n }\n\n async authenticate({ invitationId, authenticationCode }: AuthenticationRequest): Promise<void> {\n log('authenticating...');\n assert(invitationId);\n const observable = this._acceptInvitations.get(invitationId);\n if (!observable) {\n log.warn('invalid invitation', { invitationId });\n } else {\n await observable.authenticate(authenticationCode);\n }\n }\n\n async cancelInvitation(invitation: Invitation): Promise<void> {\n log('cancelling...');\n assert(invitation.invitationId);\n const observable =\n this._createInvitations.get(invitation.invitationId) ?? this._acceptInvitations.get(invitation.invitationId);\n if (!observable) {\n log.warn('invalid invitation', { invitationId: invitation.invitationId });\n } else {\n await observable?.cancel();\n }\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { IdentityManager } from '../identity';\nimport { InvitationsHandler } from './invitations-handler';\nimport { AbstractInvitationsService } from './invitations-service';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class HaloInvitationsServiceImpl extends AbstractInvitationsService {\n // prettier-ignore\n constructor (\n identityManager: IdentityManager,\n private readonly invitationsHandler: InvitationsHandler\n ) {\n super(identityManager, () => invitationsHandler);\n }\n\n override getContext(invitation: Invitation) {}\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { scheduleTask, sleep, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { createAdmissionCredentials, generatePasscode, getCredentialAssertion } from '@dxos/credentials';\nimport { SigningContext } from '@dxos/echo-db';\nimport { writeMessages } from '@dxos/feed-store';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { createTeleportProtocolFactory, NetworkManager, StarTopology, SwarmConnection } from '@dxos/network-manager';\nimport { schema } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n AuthenticationRequest,\n AuthenticationResponse,\n Introduction,\n SpaceAdmissionCredentials,\n SpaceAdmissionRequest,\n SpaceHostService\n} from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport { DataSpace } from '../spaces/data-space';\nimport { DataSpaceManager } from '../spaces/data-space-manager';\nimport {\n AuthenticatingInvitationProvider,\n AUTHENTICATION_CODE_LENGTH,\n CancellableInvitationObservable,\n InvitationObservableProvider,\n INVITATION_TIMEOUT,\n ON_CLOSE_DELAY\n} from './invitations';\nimport { AbstractInvitationsHandler, InvitationsOptions } from './invitations-handler';\n\nconst MAX_OTP_ATTEMPTS = 3;\n\n/**\n * Handles the life-cycle of Space invitations between peers.\n */\n// TODO(dmaretskyi): Split into Host and Guest parts.\nexport class SpaceInvitationsHandler extends AbstractInvitationsHandler<DataSpace> {\n constructor(\n networkManager: NetworkManager,\n private readonly _spaceManager: DataSpaceManager,\n private readonly _signingContext: SigningContext,\n private readonly _keyring: Keyring\n ) {\n super(networkManager);\n }\n\n /**\n * Creates an invitation and listens for a join request from the invited (guest) peer.\n */\n createInvitation(space: DataSpace, options?: InvitationsOptions): CancellableInvitationObservable {\n let swarmConnection: SwarmConnection | undefined;\n const { type, timeout = INVITATION_TIMEOUT, swarmKey } = options ?? {};\n assert(type !== Invitation.Type.OFFLINE);\n assert(space);\n\n // TODO(dmaretskyi): Add invitation kind: halo/space.\n const invitation: Invitation = {\n type,\n invitationId: PublicKey.random().toHex(),\n swarmKey: swarmKey ?? PublicKey.random(),\n spaceKey: space.key,\n authenticationCode: generatePasscode(AUTHENTICATION_CODE_LENGTH)\n };\n\n const ctx = new Context({\n onError: (err) => {\n void ctx.dispose();\n observable.callback.onError(err);\n }\n });\n\n // TODO(burdon): Stop anything pending.\n const observable = new InvitationObservableProvider(async () => {\n await swarmConnection?.close();\n });\n\n let authenticationCode: string;\n let authenticationRetry = 0;\n\n // Called for every connecting peer.\n const createExtension = (): HostSpaceInvitationExtension => {\n const complete = new Trigger<PublicKey>();\n let guestProfile: ProfileDocument | undefined;\n\n const hostInvitationExtension = new HostSpaceInvitationExtension({\n introduce: async ({ profile }) => {\n log('guest introduced itself', {\n guestProfile: profile,\n host: this._signingContext.deviceKey,\n spaceKey: space.key\n });\n\n guestProfile = profile;\n\n // TODO(burdon): Is this the right place to set this state?\n // TODO(dmaretskyi): Should we expose guest's profile in this callback?\n observable.callback.onAuthenticating?.(invitation);\n },\n\n authenticate: async ({ authenticationCode: code }) => {\n log('received authentication request', { authenticationCode: code });\n let status = AuthenticationResponse.Status.OK;\n if (invitation.authenticationCode) {\n if (authenticationRetry++ > MAX_OTP_ATTEMPTS) {\n status = AuthenticationResponse.Status.INVALID_OPT_ATTEMPTS;\n } else if (code !== invitation.authenticationCode) {\n status = AuthenticationResponse.Status.INVALID_OTP;\n } else {\n authenticationCode = code;\n }\n }\n\n return { status };\n },\n\n requestAdmission: async ({ identityKey, deviceKey, controlFeedKey, dataFeedKey }) => {\n try {\n // Check authenticated.\n if (\n invitation.type !== Invitation.Type.INTERACTIVE_TESTING &&\n invitation.type !== Invitation.Type.MULTIUSE_TESTING\n ) {\n if (invitation.authenticationCode === undefined || invitation.authenticationCode !== authenticationCode) {\n throw new Error(`invalid authentication code: ${authenticationCode}`);\n }\n }\n\n log('writing guest credentials', { host: this._signingContext.deviceKey, guest: deviceKey });\n // TODO(burdon): Check if already admitted.\n const credentials = await createAdmissionCredentials(\n this._signingContext.credentialSigner,\n identityKey,\n deviceKey,\n space.key,\n controlFeedKey,\n dataFeedKey,\n space.inner.genesisFeedKey,\n guestProfile\n );\n\n // TODO(dmaretskyi): Refactor.\n assert(credentials[0]['@type'] === 'dxos.echo.feed.CredentialsMessage');\n const spaceMemberCredential = credentials[0].credential;\n assert(getCredentialAssertion(spaceMemberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember');\n\n await writeMessages(space.inner.controlPipeline.writer, credentials);\n\n // Updating credentials complete.\n complete.wake(deviceKey);\n\n return { credential: spaceMemberCredential };\n } catch (err) {\n // TODO(burdon): Generic RPC callback to report error to client.\n observable.callback.onError(err);\n throw err; // Propagate error to guest.\n }\n },\n\n onOpen: () => {\n scheduleTask(ctx, async () => {\n try {\n log('connected', { host: this._signingContext.deviceKey });\n observable.callback.onConnected?.(invitation);\n const deviceKey = await complete.wait({ timeout });\n log('admitted guest', { host: this._signingContext.deviceKey, guest: deviceKey });\n observable.callback.onSuccess(invitation);\n } catch (err) {\n if (!observable.cancelled) {\n log.error('failed', err);\n observable.callback.onError(err);\n }\n } finally {\n if (type !== Invitation.Type.MULTIUSE_TESTING) {\n await sleep(ON_CLOSE_DELAY);\n await ctx.dispose();\n }\n }\n });\n }\n });\n return hostInvitationExtension;\n };\n\n scheduleTask(ctx, async () => {\n const topic = invitation.swarmKey!;\n const swarmConnection = await this._networkManager.joinSwarm({\n topic,\n peerId: topic,\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', createExtension());\n }),\n topology: new StarTopology(topic)\n });\n ctx.onDispose(() => swarmConnection.close());\n\n observable.callback.onConnecting?.(invitation);\n });\n\n return observable;\n }\n\n /**\n * Waits for the host peer (inviter) to accept our join request.\n * The local guest peer (invitee) then sends the local space invitation to the host,\n * which then writes the guest's credentials to the space.\n */\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationProvider {\n const { timeout = INVITATION_TIMEOUT } = options ?? {};\n\n const ctx = new Context({\n onError: (err) => {\n void ctx.dispose();\n observable.callback.onError(err);\n }\n });\n\n const authenticated = new Trigger<string>();\n const observable = new AuthenticatingInvitationProvider({\n onCancel: async () => {\n await ctx.dispose();\n },\n\n onAuthenticate: async (code: string) => {\n // TODO(burdon): Reset creates a race condition? Event?\n authenticated.wake(code);\n }\n });\n\n let connectionCount = 0;\n const complete = new Trigger();\n\n const createExtension = (): GuestSpaceInvitationExtension => {\n const extension = new GuestSpaceInvitationExtension({\n onOpen: () => {\n scheduleTask(ctx, async () => {\n try {\n // TODO(burdon): Bug where guest may create multiple connections.\n if (++connectionCount > 1) {\n throw new Error(`multiple connections detected: ${connectionCount}`);\n }\n\n log('connected', { guest: this._signingContext.deviceKey });\n observable.callback.onConnected?.(invitation);\n\n // 1. Introduce guest to host.\n log('introduce', { guest: this._signingContext.deviceKey });\n await extension.rpc.SpaceHostService.introduce({\n profile: this._signingContext.profile\n });\n\n // 2. Get authentication code.\n // TODO(burdon): Test timeout (options for timeouts at different steps).\n if (invitation.type === undefined || invitation.type === Invitation.Type.INTERACTIVE) {\n for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {\n log('guest waiting for authentication code...');\n observable.callback.onAuthenticating?.(invitation);\n const authenticationCode = await authenticated.wait({ timeout });\n\n log('sending authentication request');\n const response = await extension.rpc.SpaceHostService.authenticate({ authenticationCode });\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 // 3. Generate a pair of keys for our feeds.\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n\n // 4. Send admission credentials to host (with local space keys).\n log('request admission', { guest: this._signingContext.deviceKey });\n const { credential } = await extension.rpc.SpaceHostService.requestAdmission({\n identityKey: this._signingContext.identityKey,\n deviceKey: this._signingContext.deviceKey,\n controlFeedKey,\n dataFeedKey\n });\n\n // TODO(dmaretskyi): Record credential in our HALO.\n\n // 4. Create local space.\n const assertion = getCredentialAssertion(credential);\n assert(assertion['@type'] === 'dxos.halo.credentials.SpaceMember', 'Invalid credential');\n assert(credential.subject.id.equals(this._signingContext.identityKey));\n\n const space = await this._spaceManager.acceptSpace({\n spaceKey: assertion.spaceKey,\n genesisFeedKey: assertion.genesisFeedKey,\n controlFeedKey,\n dataFeedKey\n });\n\n // 5. Success.\n log('admitted by host', { guest: this._signingContext.deviceKey, spaceKey: space.key });\n complete.wake();\n } catch (err) {\n if (!observable.cancelled) {\n log.warn('auth failed', err);\n observable.callback.onError(err);\n }\n } finally {\n await ctx.dispose();\n }\n });\n }\n });\n return extension;\n };\n\n scheduleTask(ctx, async () => {\n assert(invitation.swarmKey);\n const topic = invitation.swarmKey;\n const swarmConnection = await this._networkManager.joinSwarm({\n topic,\n peerId: PublicKey.random(),\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', createExtension());\n }),\n topology: new StarTopology(topic)\n });\n ctx.onDispose(() => swarmConnection.close());\n\n observable.callback.onConnecting?.(invitation);\n await complete.wait();\n observable.callback.onSuccess(invitation);\n await ctx.dispose();\n });\n\n return observable;\n }\n}\n\ntype HostSpaceInvitationExtensionCallbacks = {\n // Deliberately not async to not block the extensions opening.\n onOpen: () => void;\n\n introduce: (introduction: Introduction) => Promise<void>;\n authenticate: (request: AuthenticationRequest) => Promise<AuthenticationResponse>;\n requestAdmission: (request: SpaceAdmissionRequest) => Promise<SpaceAdmissionCredentials>;\n};\n\n/**\n * Host's side for a connection to a concrete peer in p2p network during invitation.\n */\nclass HostSpaceInvitationExtension extends RpcExtension<{}, { SpaceHostService: SpaceHostService }> {\n constructor(private readonly _callbacks: HostSpaceInvitationExtensionCallbacks) {\n super({\n exposed: {\n SpaceHostService: schema.getService('dxos.halo.invitations.SpaceHostService')\n }\n });\n }\n\n protected override async getHandlers(): Promise<{ SpaceHostService: SpaceHostService }> {\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 SpaceHostService: {\n introduce: async (params) => {\n return this._callbacks.introduce(params);\n },\n\n authenticate: async (credentials) => {\n return this._callbacks.authenticate(credentials);\n },\n\n requestAdmission: async (credentials) => {\n return this._callbacks.requestAdmission(credentials);\n }\n }\n };\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n this._callbacks.onOpen();\n }\n}\n\ntype GuestSpaceInvitationExtensionCallbacks = {\n // Deliberately not async to not block the extensions opening.\n onOpen: () => void;\n};\n\n/**\n * Guest's side for a connection to a concrete peer in p2p network during invitation.\n */\nclass GuestSpaceInvitationExtension extends RpcExtension<{ SpaceHostService: SpaceHostService }, {}> {\n constructor(private readonly _callbacks: GuestSpaceInvitationExtensionCallbacks) {\n super({\n requested: {\n SpaceHostService: schema.getService('dxos.halo.invitations.SpaceHostService')\n }\n });\n }\n\n protected override async getHandlers() {\n return {};\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n this._callbacks.onOpen();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { PublicKey } from '@dxos/keys';\n\nimport { AbstractInvitationsProxy } from './invitations-proxy';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class SpaceInvitationsProxy extends AbstractInvitationsProxy<PublicKey> {\n getInvitationOptions(context: PublicKey) {\n return { spaceKey: context };\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { Provider } from '@dxos/util';\n\nimport { IdentityManager } from '../identity';\nimport { DataSpace } from '../spaces/data-space';\nimport { DataSpaceManager } from '../spaces/data-space-manager';\nimport { InvitationsHandler } from './invitations-handler';\nimport { AbstractInvitationsService } from './invitations-service';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class SpaceInvitationsServiceImpl extends AbstractInvitationsService<DataSpace> {\n // prettier-ignore\n constructor (\n identityManager: IdentityManager,\n private readonly invitationsHandler: Provider<InvitationsHandler<DataSpace>>,\n private readonly _getSpaceManager: Provider<DataSpaceManager>\n ) {\n super(identityManager, invitationsHandler);\n }\n\n override getContext(invitation: Invitation): DataSpace {\n assert(invitation.spaceKey);\n const spaceManager = this._getSpaceManager();\n const space = spaceManager.spaces.get(invitation.spaceKey!);\n assert(space);\n return space;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Trigger } from '@dxos/async';\nimport { failUndefined } from '@dxos/debug';\nimport {\n MOCK_AUTH_PROVIDER,\n MOCK_AUTH_VERIFIER,\n valueEncoding,\n DataServiceSubscriptions,\n MetadataStore,\n SpaceManager,\n SigningContext,\n SnapshotStore\n} from '@dxos/echo-db';\nimport { FeedFactory, FeedStore } from '@dxos/feed-store';\nimport { Keyring } from '@dxos/keyring';\nimport { log } from '@dxos/log';\nimport { ModelFactory } from '@dxos/model-factory';\nimport { NetworkManager } from '@dxos/network-manager';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { Storage } from '@dxos/random-access-storage';\n\nimport { CreateIdentityOptions, IdentityManager } from '../identity';\nimport { HaloInvitationsHandler, SpaceInvitationsHandler } from '../invitations';\nimport { DataSpaceManager } from '../spaces/data-space-manager';\n\n/**\n * Shared backend for all client services.\n */\n\n// TODO(burdon): Rename/break-up into smaller components. And/or make members private.\nexport class ServiceContext {\n public readonly initialized = new Trigger();\n public readonly dataServiceSubscriptions = new DataServiceSubscriptions();\n public readonly metadataStore: MetadataStore;\n public readonly snapshotStore: SnapshotStore;\n public readonly feedStore: FeedStore<FeedMessage>;\n public readonly keyring: Keyring;\n public readonly spaceManager: SpaceManager;\n public readonly identityManager: IdentityManager;\n public readonly haloInvitations: HaloInvitationsHandler;\n\n // Initialized after identity is initialized.\n public dataSpaceManager?: DataSpaceManager;\n public spaceInvitations?: SpaceInvitationsHandler;\n\n // prettier-ignore\n constructor(\n public readonly storage: Storage,\n public readonly networkManager: NetworkManager,\n public readonly modelFactory: ModelFactory\n ) {\n // TODO(burdon): Move strings to constants.\n this.metadataStore = new MetadataStore(storage.createDirectory('metadata'));\n this.snapshotStore = new SnapshotStore(storage.createDirectory('snapshots'));\n\n this.keyring = new Keyring(storage.createDirectory('keyring'));\n this.feedStore = new FeedStore<FeedMessage>({\n factory: new FeedFactory<FeedMessage>({\n root: storage.createDirectory('feeds'),\n signer: this.keyring,\n hypercore: {\n valueEncoding\n }\n })\n });\n this.spaceManager = new SpaceManager({\n feedStore: this.feedStore,\n networkManager: this.networkManager\n });\n this.identityManager = new IdentityManager(\n this.metadataStore,\n this.keyring,\n this.spaceManager\n );\n\n // TODO(burdon): _initialize called in multiple places.\n // TODO(burdon): Call _initialize on success.\n this.haloInvitations = new HaloInvitationsHandler(this.networkManager, this.identityManager);\n }\n\n async open() {\n log('opening...');\n await this.networkManager.open();\n await this.spaceManager.open();\n await this.identityManager.open();\n if (this.identityManager.identity) {\n await this._initialize();\n }\n log('opened');\n }\n\n async close() {\n log('closing...');\n await this.dataSpaceManager?.close();\n await this.identityManager.close();\n await this.spaceManager.close();\n await this.feedStore.close();\n await this.networkManager.close();\n this.dataServiceSubscriptions.clear();\n log('closed');\n }\n\n async reset() {\n log('resetting...');\n await this.close();\n await this.storage.reset();\n log('reset');\n }\n\n async createIdentity(params: CreateIdentityOptions = {}) {\n const identity = await this.identityManager.createIdentity(params);\n\n await this._initialize();\n return identity;\n }\n\n // Called when identity is created.\n private async _initialize() {\n log('initializing spaces...');\n const identity = this.identityManager.identity ?? failUndefined();\n const signingContext: SigningContext = {\n credentialProvider: MOCK_AUTH_PROVIDER,\n credentialAuthenticator: MOCK_AUTH_VERIFIER,\n credentialSigner: identity.getIdentityCredentialSigner(),\n identityKey: identity.identityKey,\n deviceKey: identity.deviceKey,\n profile: identity.profileDocument\n };\n\n this.dataSpaceManager = new DataSpaceManager(\n this.spaceManager,\n this.metadataStore,\n this.dataServiceSubscriptions,\n this.keyring,\n signingContext,\n this.modelFactory,\n this.snapshotStore\n );\n await this.dataSpaceManager.open();\n this.spaceInvitations = new SpaceInvitationsHandler(\n this.networkManager,\n this.dataSpaceManager,\n signingContext,\n this.keyring\n );\n this.initialized.wake();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, synchronized, trackLeaks } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport {\n AcceptSpaceOptions,\n DataServiceSubscriptions,\n MetadataStore,\n SigningContext,\n SnapshotStore,\n Space,\n spaceGenesis,\n SpaceManager,\n SnapshotManager\n} from '@dxos/echo-db';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ModelFactory } from '@dxos/model-factory';\nimport { SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport { Presence } from '@dxos/teleport-extension-presence';\nimport { ComplexMap } from '@dxos/util';\n\nimport { DataSpace } from './data-space';\n\n@trackLeaks('open', 'close')\nexport class DataSpaceManager {\n private readonly _ctx = new Context();\n\n public readonly updated = new Event();\n\n private readonly _spaces = new ComplexMap<PublicKey, DataSpace>(PublicKey.hash);\n\n constructor(\n private readonly _spaceManager: SpaceManager,\n private readonly _metadataStore: MetadataStore,\n private readonly _dataServiceSubscriptions: DataServiceSubscriptions,\n private readonly _keyring: Keyring,\n private readonly _signingContext: SigningContext,\n private readonly _modelFactory: ModelFactory,\n private readonly _snapshotStore: SnapshotStore\n ) {}\n\n // TODO(burdon): Remove.\n get spaces() {\n return this._spaces;\n }\n\n @synchronized\n async open() {\n await this._metadataStore.load();\n log('metadata loaded', { spaces: this._metadataStore.spaces.length });\n\n for (const spaceMetadata of this._metadataStore.spaces) {\n log('load space', { spaceMetadata });\n const space = await this._constructSpace(spaceMetadata);\n if (spaceMetadata.latestTimeframe) {\n log('waiting for latest timeframe', { spaceMetadata });\n await space.dataPipelineController.waitUntilTimeframe(spaceMetadata.latestTimeframe);\n }\n }\n }\n\n @synchronized\n async close() {\n await this._ctx.dispose();\n for (const space of this._spaces.values()) {\n await space.close();\n }\n }\n\n /**\n * Creates a new space writing the genesis credentials to the control feed.\n */\n @synchronized\n async createSpace() {\n const spaceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n const metadata: SpaceMetadata = {\n key: spaceKey,\n genesisFeedKey: controlFeedKey,\n controlFeedKey,\n dataFeedKey\n };\n\n log('creating space...', { spaceKey });\n const space = await this._constructSpace(metadata);\n\n await spaceGenesis(this._keyring, this._signingContext, space.inner);\n await this._metadataStore.addSpace(metadata);\n\n this.updated.emit();\n return space;\n }\n\n // TODO(burdon): Rename join space.\n @synchronized\n async acceptSpace(opts: AcceptSpaceOptions): Promise<DataSpace> {\n const metadata: SpaceMetadata = {\n key: opts.spaceKey,\n genesisFeedKey: opts.genesisFeedKey,\n controlFeedKey: opts.controlFeedKey,\n dataFeedKey: opts.dataFeedKey\n };\n\n const space = await this._constructSpace(metadata);\n await this._metadataStore.addSpace(metadata);\n this.updated.emit();\n return space;\n }\n\n private async _constructSpace(metadata: SpaceMetadata) {\n const presence = new Presence({\n localPeerId: this._signingContext.deviceKey,\n announceInterval: 1_000,\n offlineTimeout: 30_000,\n identityKey: this._signingContext.identityKey\n });\n const snapshotManager = new SnapshotManager(this._snapshotStore);\n\n const space: Space = await this._spaceManager.constructSpace({\n metadata,\n swarmIdentity: {\n peerKey: this._signingContext.deviceKey,\n credentialProvider: this._signingContext.credentialProvider,\n credentialAuthenticator: this._signingContext.credentialAuthenticator\n },\n onNetworkConnection: (session) => {\n session.addExtension(\n 'dxos.mesh.teleport.presence',\n presence.createExtension({ remotePeerId: session.remotePeerId })\n );\n session.addExtension('dxos.mesh.teleport.objectsync', snapshotManager.objectSync.createExtension());\n }\n });\n\n const dataSpace = new DataSpace({\n inner: space,\n modelFactory: this._modelFactory,\n metadataStore: this._metadataStore,\n snapshotManager,\n presence,\n memberKey: this._signingContext.identityKey,\n snapshotId: metadata.snapshot\n });\n\n await dataSpace.open();\n this._dataServiceSubscriptions.registerSpace(space.key, dataSpace.database.createDataServiceHost());\n this._spaces.set(metadata.key, dataSpace);\n return dataSpace;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { trackLeaks } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { Database, DataPipelineControllerImpl, ISpace, MetadataStore, Space, SnapshotManager } from '@dxos/echo-db';\nimport { PublicKey } from '@dxos/keys';\nimport { ModelFactory } from '@dxos/model-factory';\nimport { Presence } from '@dxos/teleport-extension-presence';\n\nexport type DataSpaceParams = {\n inner: Space;\n modelFactory: ModelFactory;\n metadataStore: MetadataStore;\n snapshotManager: SnapshotManager;\n presence: Presence;\n memberKey: PublicKey;\n snapshotId?: string | undefined;\n};\n\n@trackLeaks('open', 'close')\nexport class DataSpace implements ISpace {\n private readonly _ctx = new Context();\n private readonly _dataPipelineController: DataPipelineControllerImpl;\n private readonly _inner: Space;\n private readonly _presence: Presence;\n\n constructor(params: DataSpaceParams) {\n this._inner = params.inner;\n this._presence = params.presence;\n this._dataPipelineController = new DataPipelineControllerImpl({\n modelFactory: params.modelFactory,\n metadataStore: params.metadataStore,\n snapshotManager: params.snapshotManager,\n memberKey: params.memberKey,\n spaceKey: this._inner.key,\n feedInfoProvider: (feedKey) => this._inner.spaceState.feeds.get(feedKey),\n snapshotId: params.snapshotId\n });\n }\n\n get key() {\n return this._inner.key;\n }\n\n get inner() {\n return this._inner;\n }\n\n get isOpen() {\n return this._inner.isOpen;\n }\n\n get dataPipelineController(): DataPipelineControllerImpl {\n return this._dataPipelineController;\n }\n\n get database(): Database {\n assert(this._dataPipelineController.database);\n return this._dataPipelineController.database;\n }\n\n get stateUpdate() {\n return this._inner.stateUpdate;\n }\n\n get presence() {\n return this._presence;\n }\n\n async open() {\n await this._inner.open();\n await this._inner.initDataPipeline(this._dataPipelineController);\n }\n\n async close() {\n await this._ctx.dispose();\n await this._inner.close();\n await this._presence.destroy();\n }\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { schema } from '@dxos/protocols';\nimport { ProfileService, SystemService, SpaceService } from '@dxos/protocols/proto/dxos/client';\nimport {\n HaloInvitationsService,\n SpaceInvitationsService,\n SpacesService,\n DevicesService,\n NetworkService\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { DevtoolsHost, TracingService } from '@dxos/protocols/proto/dxos/devtools/host';\nimport { DataService } from '@dxos/protocols/proto/dxos/echo/service';\nimport { createServiceBundle, ServiceBundle } from '@dxos/rpc';\n\n//\n// NOTE: Should contain client/proxy dependencies only.\n//\n\nexport type ClientServices = {\n HaloInvitationsService: HaloInvitationsService;\n DevicesService: DevicesService;\n\n SpaceInvitationsService: SpaceInvitationsService;\n SpacesService: SpacesService;\n\n NetworkService: NetworkService;\n\n // TODO(burdon): Deprecated.\n SpaceService: SpaceService;\n DataService: DataService;\n ProfileService: ProfileService;\n SystemService: SystemService;\n DevtoolsHost: DevtoolsHost;\n TracingService: TracingService;\n};\n\n/**\n * Provide access to client services definitions and service handler.\n */\nexport interface ClientServicesProvider {\n descriptors: ServiceBundle<ClientServices>;\n services: ClientServices;\n\n open(): Promise<void>;\n close(): Promise<void>;\n}\n\n/**\n * Services supported by host.\n */\nexport const clientServiceBundle = createServiceBundle<ClientServices>({\n HaloInvitationsService: schema.getService('dxos.client.services.HaloInvitationsService'),\n DevicesService: schema.getService('dxos.client.services.DevicesService'),\n SpaceInvitationsService: schema.getService('dxos.client.services.SpaceInvitationsService'),\n SpacesService: schema.getService('dxos.client.services.SpacesService'),\n NetworkService: schema.getService('dxos.client.services.NetworkService'),\n\n // TODO(burdon): Deprecated.\n SpaceService: schema.getService('dxos.client.SpaceService'),\n DataService: schema.getService('dxos.echo.service.DataService'),\n ProfileService: schema.getService('dxos.client.ProfileService'),\n SystemService: schema.getService('dxos.client.SystemService'),\n DevtoolsHost: schema.getService('dxos.devtools.host.DevtoolsHost'),\n TracingService: schema.getService('dxos.devtools.host.TracingService')\n});\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { Config } from '@dxos/config';\nimport { raise } from '@dxos/debug';\nimport { DataServiceImpl } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\nimport { ModelFactory } from '@dxos/model-factory';\nimport { NetworkManager } from '@dxos/network-manager';\nimport { ObjectModel } from '@dxos/object-model';\nimport { Storage } from '@dxos/random-access-storage';\nimport { TextModel } from '@dxos/text-model';\n\nimport { SpaceServiceImpl, ProfileServiceImpl, SystemServiceImpl, TracingServiceImpl } from '../deprecated';\nimport { DevtoolsServiceImpl, DevtoolsHostEvents } from '../devtools';\nimport { DevicesServiceImpl } from '../identity/devices-service-impl';\nimport { HaloInvitationsServiceImpl, SpaceInvitationsServiceImpl } from '../invitations';\nimport { NetworkServiceImpl } from '../network';\nimport { SpacesServiceImpl } from '../spaces';\nimport { createStorageObjects } from '../storage';\nimport { ServiceContext } from './service-context';\nimport { ClientServicesProvider, ClientServices, clientServiceBundle } from './service-definitions';\nimport { ServiceRegistry } from './service-registry';\n\n// TODO(burdon): Factor out to spaces.\n// TODO(burdon): Defaults (with TextModel).\nexport const createDefaultModelFactory = () => {\n return new ModelFactory().registerModel(ObjectModel).registerModel(TextModel);\n};\n\ntype ClientServicesHostParams = {\n config: Config;\n modelFactory?: ModelFactory;\n networkManager: NetworkManager;\n storage?: Storage;\n};\n\n/**\n * Remote service implementation.\n */\nexport class ClientServicesHost implements ClientServicesProvider {\n private _serviceContext!: ServiceContext;\n private _serviceRegistry!: ServiceRegistry<ClientServices>;\n\n private readonly _config: Config;\n private readonly _modelFactory: ModelFactory;\n private readonly _networkManager: NetworkManager;\n private _storage: Storage;\n\n constructor({\n config,\n modelFactory = createDefaultModelFactory(),\n // TODO(burdon): Create ApolloLink abstraction (see Client).\n networkManager,\n storage = createStorageObjects(config.get('runtime.client.storage', {})!).storage\n }: ClientServicesHostParams) {\n this._config = config;\n this._modelFactory = modelFactory;\n this._networkManager = networkManager;\n this._storage = storage;\n }\n\n get descriptors() {\n return this._serviceRegistry.descriptors;\n }\n\n get services() {\n return this._serviceRegistry.services;\n }\n\n async open() {\n log('opening...');\n await this._initialize();\n await this._serviceContext.open();\n const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;\n log('opened', { deviceKey });\n }\n\n async close() {\n const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;\n log('closing...', { deviceKey });\n await this._serviceContext.close();\n log('closed', { deviceKey });\n }\n\n // TODO(burdon): Move into open.\n async _initialize() {\n // TODO(burdon): Break into components.\n this._serviceContext = new ServiceContext(this._storage, this._networkManager, this._modelFactory);\n\n // TODO(burdon): Start to think of DMG (dynamic services).\n this._serviceRegistry = new ServiceRegistry<ClientServices>(clientServiceBundle, {\n HaloInvitationsService: new HaloInvitationsServiceImpl(\n this._serviceContext.identityManager,\n this._serviceContext.haloInvitations\n ),\n\n DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),\n\n SpaceInvitationsService: new SpaceInvitationsServiceImpl(\n this._serviceContext.identityManager,\n () => this._serviceContext.spaceInvitations ?? raise(new Error('SpaceInvitations not initialized')),\n () => this._serviceContext.dataSpaceManager ?? raise(new Error('SpaceManager not initialized'))\n ),\n\n SpacesService: new SpacesServiceImpl(this._serviceContext.spaceManager),\n\n DataService: new DataServiceImpl(this._serviceContext.dataServiceSubscriptions),\n\n NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager),\n\n // TODO(burdon): Move to new protobuf definitions.\n ProfileService: new ProfileServiceImpl(this._serviceContext),\n SpaceService: new SpaceServiceImpl(this._serviceContext),\n SystemService: new SystemServiceImpl(this._config, this._serviceContext),\n TracingService: new TracingServiceImpl(this._config),\n DevtoolsHost: new DevtoolsServiceImpl({\n events: new DevtoolsHostEvents(),\n config: this._config,\n context: this._serviceContext\n })\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { EventSubscriptions } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { Device, DevicesService, QueryDevicesResponse } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { IdentityManager } from './identity-manager';\n\nexport class DevicesServiceImpl implements DevicesService {\n constructor(private readonly _identityManager: IdentityManager) {}\n\n updateDevice(): Promise<Device> {\n throw new Error('Method not implemented.');\n }\n\n queryDevices(): Stream<QueryDevicesResponse> {\n return new Stream(({ next }) => {\n const update = () => {\n const deviceKeys = this._identityManager.identity?.authorizedDeviceKeys;\n if (!deviceKeys) {\n next({ devices: [] });\n } else {\n next({\n devices: Array.from(deviceKeys.values()).map((key) => ({\n deviceKey: key\n }))\n });\n }\n };\n\n const dispose = new EventSubscriptions();\n dispose.add(\n this._identityManager.stateUpdate.on(() => {\n update();\n\n if (this._identityManager.identity) {\n dispose.add(\n this._identityManager.identity.stateUpdate.on(() => {\n update();\n })\n );\n }\n })\n );\n\n update();\n\n return () => dispose.clear();\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { NetworkManager } from '@dxos/network-manager';\nimport { NetworkService, NetworkStatus, SetNetworkOptionsRequest } from '@dxos/protocols/proto/dxos/client/services';\n\nexport class NetworkServiceImpl implements NetworkService {\n constructor(private readonly networkManager: NetworkManager) {}\n\n subscribeToNetworkStatus() {\n return new Stream<NetworkStatus>(({ next }) => {\n const unsubscribe = this.networkManager.connectionStateChanged.on((state) => next({ state }));\n next({ state: this.networkManager.connectionState });\n\n return unsubscribe;\n });\n }\n\n async setNetworkOptions(request: SetNetworkOptionsRequest) {\n await this.networkManager.setConnectionState(request.state);\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { scheduleTask } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { raise } from '@dxos/debug';\nimport { SpaceManager, SpaceNotFoundError } from '@dxos/echo-db';\nimport {\n QueryCredentialsRequest,\n QueryMembersRequest,\n QueryMembersResponse,\n Space,\n SpacesService\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\n/**\n *\n */\nexport class SpacesServiceImpl implements SpacesService {\n constructor(private readonly _spaceManager: SpaceManager) {}\n\n async createSpace(): Promise<Space> {\n throw new Error();\n }\n\n querySpaces(): Stream<Space> {\n throw new Error();\n }\n\n queryMembers(query: QueryMembersRequest): Stream<QueryMembersResponse> {\n throw new Error();\n }\n\n queryCredentials({ spaceKey }: QueryCredentialsRequest): Stream<Credential> {\n return new Stream(({ ctx, next }) => {\n const space = this._spaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n\n const processor = space.spaceState.registerProcessor({\n process: async (credential) => {\n next(credential);\n }\n });\n ctx.onDispose(() => processor.close());\n scheduleTask(ctx, () => processor.open());\n });\n }\n}\n", "//\n\n//\n// Copyright 2023 DXOS.org\n//\n\nimport { InvalidConfigError } from '@dxos/errors';\nimport { Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { createStorage, StorageType } from '@dxos/random-access-storage';\n\nimport StorageDriver = Runtime.Client.Storage.StorageDriver;\n\n// TODO(burdon): Factor out.\nexport const createStorageObjects = (config: Runtime.Client.Storage) => {\n const {\n path = 'dxos/storage', // TODO(burdon): Factor out const.\n storageType,\n keyStorage,\n persistent = false\n } = config ?? {};\n\n if (persistent && storageType === StorageDriver.RAM) {\n throw new InvalidConfigError('RAM storage cannot be used in persistent mode.');\n }\n if (!persistent && storageType !== undefined && storageType !== StorageDriver.RAM) {\n throw new InvalidConfigError('Cannot use a persistent storage in not persistent mode.');\n }\n if (persistent && keyStorage === StorageDriver.RAM) {\n throw new InvalidConfigError('RAM key storage cannot be used in persistent mode.');\n }\n if (!persistent && keyStorage !== StorageDriver.RAM && keyStorage !== undefined) {\n throw new InvalidConfigError('Cannot use a persistent key storage in not persistent mode.');\n }\n\n return {\n storage: createStorage({\n type: persistent ? toStorageType(storageType) : StorageType.RAM,\n root: `${path}/`\n })\n };\n};\n\nconst toStorageType = (type: StorageDriver | undefined): StorageType | undefined => {\n switch (type) {\n case undefined:\n return undefined;\n case StorageDriver.RAM:\n return StorageType.RAM;\n case StorageDriver.CHROME:\n return StorageType.CHROME;\n case StorageDriver.FIREFOX:\n return StorageType.FIREFOX;\n case StorageDriver.IDB:\n return StorageType.IDB;\n case StorageDriver.NODE:\n return StorageType.NODE;\n default:\n throw new Error(`Invalid storage type: ${StorageDriver[type]}`);\n }\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { ServiceBundle } from '@dxos/rpc';\n\n/**\n * Registry of operational services.\n */\nexport class ServiceRegistry<Services> {\n // prettier-ignore\n constructor (\n private readonly _serviceBundle: ServiceBundle<Services>,\n private readonly _handlers: Services\n ) {}\n\n get descriptors() {\n return this._serviceBundle;\n }\n\n get services() {\n return this._handlers;\n }\n}\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { asyncTimeout } from '@dxos/async';\nimport { RemoteServiceConnectionTimeout } from '@dxos/errors';\nimport { createProtoRpcPeer, ProtoRpcPeer, RpcPort } from '@dxos/rpc';\n\nimport { ClientServicesProvider, ClientServices, clientServiceBundle } from './service-definitions';\n\n/**\n * Implements services that are not local to the app.\n * For example, the services can be located in Wallet Extension.\n */\n// TODO(burdon): Separate construction of port from availability of services.\n// TODO(burdon): Create `@dxos/client-proxy` package with thin-client only dependencies (for code-splitting).\nexport class ClientServicesProxy implements ClientServicesProvider {\n private readonly _proxy: ProtoRpcPeer<ClientServices>;\n\n // prettier-ignore\n constructor(\n port: RpcPort,\n // NOTE: With lower timeout the shared worker does not have enough time to start.\n // TODO(dmaretskyi): Find better ways to detected when the worker has finished loading. It might take a while on slow connections.\n private readonly _timeout = 30_000\n ) {\n this._proxy = createProtoRpcPeer({\n requested: clientServiceBundle,\n exposed: {},\n handlers: {},\n port\n });\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get descriptors() {\n return clientServiceBundle;\n }\n\n get services() {\n return this._proxy.rpc;\n }\n\n async open() {\n await asyncTimeout(this._proxy.open(), this._timeout, new RemoteServiceConnectionTimeout());\n }\n\n async close() {\n await this._proxy.close();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { WebRTCTransportService } from '@dxos/network-manager';\nimport { BridgeService } from '@dxos/protocols/proto/dxos/mesh/bridge';\nimport { createProtoRpcPeer, ProtoRpcPeer, RpcPort } from '@dxos/rpc';\n\nimport { iframeServiceBundle, WorkerServiceBundle, workerServiceBundle } from './services';\n\n// NOTE: Keep as RpcPorts to avoid dependency on @dxos/rpc-tunnel so we don't depend on browser-specific apis.\nexport type IframeRuntimeParams = {\n systemPort: RpcPort;\n workerAppPort: RpcPort;\n windowAppPort: RpcPort;\n};\n\n/**\n * Manages the client connection to the shared worker.\n */\nexport class IFrameRuntime {\n private readonly _systemPort: RpcPort;\n private readonly _windowAppPort: RpcPort;\n private readonly _workerAppPort: RpcPort;\n private readonly _systemRpc: ProtoRpcPeer<WorkerServiceBundle>;\n private readonly _transportService = new WebRTCTransportService();\n\n constructor({ systemPort, workerAppPort, windowAppPort }: IframeRuntimeParams) {\n this._systemPort = systemPort;\n this._windowAppPort = windowAppPort;\n this._workerAppPort = workerAppPort;\n\n this._systemRpc = createProtoRpcPeer({\n requested: workerServiceBundle,\n exposed: iframeServiceBundle,\n handlers: {\n BridgeService: this._transportService as BridgeService,\n IframeService: {\n async heartbeat() {\n // Ok.\n }\n }\n },\n port: this._systemPort,\n timeout: 200\n });\n\n this._workerAppPort.subscribe((msg) => this._windowAppPort.send(msg));\n this._windowAppPort.subscribe((msg) => this._workerAppPort.send(msg));\n }\n\n async open(origin: string) {\n await this._systemRpc.open();\n await this._systemRpc.rpc.WorkerService.start({ origin });\n }\n\n async close() {\n await this._systemRpc.rpc.WorkerService.stop();\n await this._systemRpc.close();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { schema } from '@dxos/protocols';\nimport type { IframeService, WorkerService } from '@dxos/protocols/proto/dxos/iframe';\nimport type { BridgeService } from '@dxos/protocols/proto/dxos/mesh/bridge';\nimport { ServiceBundle } from '@dxos/rpc';\n\nexport type IframeServiceBundle = {\n IframeService: IframeService;\n BridgeService: BridgeService;\n};\n\nexport const iframeServiceBundle: ServiceBundle<IframeServiceBundle> = {\n IframeService: schema.getService('dxos.iframe.IframeService'),\n BridgeService: schema.getService('dxos.mesh.bridge.BridgeService')\n};\n\nexport type WorkerServiceBundle = {\n WorkerService: WorkerService;\n};\n\nexport const workerServiceBundle: ServiceBundle<WorkerServiceBundle> = {\n WorkerService: schema.getService('dxos.iframe.WorkerService')\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Trigger } from '@dxos/async';\nimport { Config } from '@dxos/config';\nimport { MemorySignalManager, MemorySignalManagerContext, WebsocketSignalManager } from '@dxos/messaging';\nimport { NetworkManager, WebRTCTransportProxyFactory } from '@dxos/network-manager';\nimport { RpcPort } from '@dxos/rpc';\nimport { MaybePromise } from '@dxos/util';\n\nimport { ClientServicesHost } from '../services';\nimport { WorkerSession } from './worker-session';\n\n// NOTE: Keep as RpcPorts to avoid dependency on @dxos/rpc-tunnel so we don't depend on browser-specific apis.\nexport type CreateSessionParams = {\n appPort: RpcPort;\n systemPort: RpcPort;\n};\n\n/**\n * Runtime for the shared worker.\n * Manages connections from proxies (in tabs).\n * Tabs make requests to the `ClientServicesHost`, and provide a WebRTC gateway.\n */\nexport class WorkerRuntime {\n private readonly _transportFactory = new WebRTCTransportProxyFactory();\n private readonly _ready = new Trigger<Error | undefined>();\n private readonly sessions = new Set<WorkerSession>();\n private _sessionForNetworking?: WorkerSession;\n private _clientServices!: ClientServicesHost;\n private _config!: Config;\n\n // prettier-ignore\n constructor(\n private readonly _configProvider: () => MaybePromise<Config>\n ) { }\n\n async start() {\n try {\n this._config = await this._configProvider();\n const signalServer = this._config.get('runtime.services.signal.server');\n this._clientServices = new ClientServicesHost({\n config: this._config,\n networkManager: new NetworkManager({\n log: true,\n signalManager: signalServer\n ? new WebsocketSignalManager([signalServer])\n : new MemorySignalManager(new MemorySignalManagerContext()), // TODO(dmaretskyi): Inject this context.\n transportFactory: this._transportFactory\n })\n });\n\n await this._clientServices.open();\n this._ready.wake(undefined);\n } catch (err: any) {\n this._ready.wake(err);\n }\n }\n\n async stop() {\n // TODO(dmaretskyi): Terminate active sessions.\n await this._clientServices.close();\n }\n\n /**\n * Create a new session.\n */\n async createSession({ appPort, systemPort }: CreateSessionParams) {\n const session = new WorkerSession({\n getServices: async () => {\n const error = await this._ready.wait();\n if (error !== undefined) {\n throw error;\n }\n return this._clientServices;\n },\n appPort,\n systemPort,\n readySignal: this._ready\n });\n\n // When tab is closed.\n session.onClose.set(async () => {\n this.sessions.delete(session);\n this._reconnectWebrtc();\n });\n\n await session.open();\n this.sessions.add(session);\n\n this._reconnectWebrtc();\n }\n\n /**\n * Selects one of the existing session fro WebRTC networking.\n */\n private _reconnectWebrtc() {\n // Check if current session is already closed.\n if (this._sessionForNetworking) {\n if (!this.sessions.has(this._sessionForNetworking)) {\n this._sessionForNetworking = undefined;\n }\n }\n\n // Select existing session.\n if (!this._sessionForNetworking) {\n const selected = Array.from(this.sessions).find((session) => session.bridgeService);\n if (selected) {\n this._sessionForNetworking = selected;\n this._transportFactory.setBridgeService(selected.bridgeService);\n } else {\n this._transportFactory.setBridgeService(undefined);\n }\n }\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Trigger } from '@dxos/async';\nimport { log, logInfo } from '@dxos/log';\nimport { BridgeService } from '@dxos/protocols/proto/dxos/mesh/bridge';\nimport { createProtoRpcPeer, ProtoRpcPeer, RpcPort } from '@dxos/rpc';\nimport { Callback } from '@dxos/util';\n\nimport { clientServiceBundle, ClientServices, ClientServicesHost } from '../services';\nimport { IframeServiceBundle, iframeServiceBundle, workerServiceBundle } from './services';\n\nexport type WorkerSessionParams = {\n getServices: () => Promise<ClientServicesHost>;\n systemPort: RpcPort;\n appPort: RpcPort;\n readySignal: Trigger<Error | undefined>;\n options?: {\n heartbeatInterval: number;\n };\n};\n\n/**\n * Represents a tab connection within the worker.\n */\nexport class WorkerSession {\n private readonly _clientRpc: ProtoRpcPeer<ClientServices>;\n private readonly _iframeRpc: ProtoRpcPeer<IframeServiceBundle>;\n private readonly _startTrigger = new Trigger();\n private readonly _getServices: () => Promise<ClientServicesHost>;\n private readonly _options: NonNullable<WorkerSessionParams['options']>;\n private _heartbeatTimer?: NodeJS.Timeout;\n\n public readonly onClose = new Callback<() => Promise<void>>();\n\n @logInfo\n public origin?: string;\n\n public bridgeService?: BridgeService;\n\n constructor({\n getServices,\n systemPort,\n appPort,\n options = {\n heartbeatInterval: 1_000\n }\n }: WorkerSessionParams) {\n assert(options);\n assert(getServices);\n this._options = options;\n this._getServices = getServices;\n\n this._clientRpc = createProtoRpcPeer({\n exposed: clientServiceBundle,\n handlers: {\n HaloInvitationsService: async () => (await this._getServices()).services.HaloInvitationsService,\n DevicesService: async () => (await this._getServices()).services.DevicesService,\n SpaceInvitationsService: async () => (await this._getServices()).services.SpaceInvitationsService,\n SpacesService: async () => (await this._getServices()).services.SpacesService,\n NetworkService: async () => (await this._getServices()).services.NetworkService,\n SpaceService: async () => (await this._getServices()).services.SpaceService,\n DataService: async () => (await this._getServices()).services.DataService,\n ProfileService: async () => (await this._getServices()).services.ProfileService,\n SystemService: async () => (await this._getServices()).services.SystemService,\n DevtoolsHost: async () => (await this._getServices()).services.DevtoolsHost,\n TracingService: async () => (await this._getServices()).services.TracingService\n },\n port: appPort\n });\n\n this._iframeRpc = createProtoRpcPeer({\n requested: iframeServiceBundle,\n exposed: workerServiceBundle,\n handlers: {\n WorkerService: {\n start: async (request) => {\n this.origin = request.origin;\n this._startTrigger.wake();\n },\n\n stop: async () => {\n setTimeout(async () => {\n try {\n await this.close();\n } catch (err: any) {\n log.catch(err);\n }\n });\n }\n }\n },\n port: systemPort,\n timeout: 1000 // With low timeout heartbeat may fail if the tab's thread is saturated.\n });\n\n this.bridgeService = this._iframeRpc.rpc.BridgeService;\n }\n\n async open() {\n log.info('opening..');\n await Promise.all([this._clientRpc.open(), this._iframeRpc.open()]);\n\n await this._startTrigger.wait({ timeout: 3_000 });\n\n // Detect if bridge is present.\n // TODO(burdon): Add heartbeat to client's System service.\n // How do we detect if the client's tab closed?\n this._heartbeatTimer = setInterval(async () => {\n try {\n await this._iframeRpc.rpc.IframeService.heartbeat();\n } catch (err) {\n log.warn('Heartbeat failed', { err });\n try {\n await this.close();\n } catch (err: any) {\n log.catch(err);\n }\n }\n }, this._options.heartbeatInterval);\n }\n\n async close() {\n log.info('closing..');\n try {\n await this.onClose.callIfSet();\n } catch (err: any) {\n log.catch(err);\n }\n\n if (this._heartbeatTimer !== undefined) {\n clearInterval(this._heartbeatTimer);\n }\n\n await Promise.all([this._clientRpc.close(), this._iframeRpc.close()]);\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;AAIA,OAAOA,YAAY;AAEnB,SAASC,0BAA0B;AACnC,SAASC,cAAc;AACvB,SAASC,YAAY;AACrB,SAASC,WAAW;AACpB,SAKEC,mBASK;AAEP,SAASC,gBAAgB;AASlB,IAAMC,mBAAN,MAAMA;EAGXC,YAA6BC,gBAAgC;0BAAhCA;SAFrBC,qBAAyC,oBAAIC,IAAAA;EAES;EAE9DC,iBAAiBC,SAAgE;AAC/E,WAAO,IAAIX,OAAO,CAAC,EAAEY,KAAI,MAAO;AAC9BA,WAAK;QACHC,OAAO;UACLC,WAAWH,QAAQI;UACnBC,QAAQ;UACRC,UAAU;UACVC,SAAS,CAAA;QACX;MACF,CAAA;IACF,CAAA;EA2CF;EAEAC,kBAAkB;AAChB,WAAO,IAAInB,OAAgC,CAAC,EAAEY,KAAI,MAAO;AACvD,YAAMQ,gBAAgB,IAAIrB,mBAAAA;AAE1B,YAAMsB,WAAW,MAAM;AACrB,cAAMC,SAASC,MAAMC,KAAK,KAAKjB,eAAekB,iBAAkBH,OAAOI,OAAM,CAAA,EAAIC,IAC/E,CAACd,WAAkB;UACjBC,WAAWD,MAAMe;UACjBZ,QAAQ;UACRC,UAAU;UACVC,SAASK,MAAMC,KAAKX,MAAMgB,MAAMC,WAAWZ,QAAQQ,OAAM,CAAA,EAAIC,IAAI,CAACI,WAAAA;AAzG9E;AAyG0F;cAC5EC,aAAaD,OAAOH;cACpBK,SAAS;gBACPD,aAAaD,OAAOH;gBACpBM,cAAaH,kBAAOI,UAAUF,YAAjBF,mBAA0BG,gBAA1BH,YAAyC3B,SAAS2B,OAAOH,GAAG;cAC3E;cACAQ,YACE,UAAK7B,eAAe8B,gBAAgBC,aAApC,mBAA8CN,YAAYO,OAAOR,OAAOH,SACxEf,MAAMuB,SAASI,eAAc,EAAGC,OAAO,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UAChCC,kBAAkB,KAAKpB;QACzB,CAAA;MACF,CAAA;AAEA,YAAM,KAAKU,gBAAgBW,KAAI;AAC/B,WAAKnB,OAAOoB,KAAKC,MAAAA;IACnB,SAASC,KAAP;AACA,WAAKtB,OAAOoB,KAAKE,GAAAA;IACnB;EACF;EAEA,MAAMC,OAAO;AAEX,UAAM,KAAKf,gBAAgBgB,MAAK;EAClC;;;;EAKA,MAAMC,cAAc,EAAEC,SAASC,WAAU,GAAyB;AAChE,UAAMC,UAAU,IAAIC,cAAc;MAChCC,aAAa,YAAY;AACvB,cAAMC,QAAQ,MAAM,KAAK/B,OAAOgC,KAAI;AACpC,YAAID,UAAUV,QAAW;AACvB,gBAAMU;QACR;AACA,eAAO,KAAKvB;MACd;MACAkB;MACAC;MACAM,aAAa,KAAKjC;IACpB,CAAA;AAGA4B,YAAQM,QAAQC,IAAI,YAAY;AAC9B,WAAKjC,SAASkC,OAAOR,OAAAA;AACrB,WAAKS,iBAAgB;IACvB,CAAA;AAEA,UAAMT,QAAQT,KAAI;AAClB,SAAKjB,SAASoC,IAAIV,OAAAA;AAElB,SAAKS,iBAAgB;EACvB;;;;EAKQA,mBAAmB;AAEzB,QAAI,KAAKE,uBAAuB;AAC9B,UAAI,CAAC,KAAKrC,SAASsC,IAAI,KAAKD,qBAAqB,GAAG;AAClD,aAAKA,wBAAwBlB;MAC/B;IACF;AAGA,QAAI,CAAC,KAAKkB,uBAAuB;AAC/B,YAAME,WAAWC,MAAMC,KAAK,KAAKzC,QAAQ,EAAE0C,KAAK,CAAChB,YAAYA,QAAQiB,aAAa;AAClF,UAAIJ,UAAU;AACZ,aAAKF,wBAAwBE;AAC7B,aAAK3C,kBAAkBgD,iBAAiBL,SAASI,aAAa;MAChE,OAAO;AACL,aAAK/C,kBAAkBgD,iBAAiBzB,MAAAA;MAC1C;IACF;EACF;AACF;",
|
|
6
|
-
"names": ["assert", "EventSubscriptions", "Stream", "todo", "log", "SpaceMember", "humanize", "SpaceServiceImpl", "constructor", "serviceContext", "inviteeInvitations", "Map", "subscribeToSpace", "request", "next", "space", "publicKey", "spaceKey", "isOpen", "isActive", "members", "subscribeSpaces", "subscriptions", "onUpdate", "spaces", "Array", "from", "dataSpaceManager", "values", "map", "key", "inner", "spaceState", "member", "identityKey", "profile", "displayName", "assertion", "presence", "identityManager", "identity", "equals", "getPeersOnline", "filter", "length", "PresenceState", "ONLINE", "OFFLINE", "setTimeout", "initialized", "wait", "add", "updated", "on", "forEach", "stateUpdate", "clear", "getSpaceDetails", "createSpace", "cloneSpace", "snapshot", "setSpaceState", "authenticateInvitation", "processId", "invitation", "get", "secret", "secretTrigger", "subscribeMembers", "createSnapshot", "Stream", "todo", "ProfileServiceImpl", "constructor", "context", "inviteeInvitations", "Map", "subscribeProfile", "next", "emitNext", "profile", "identityManager", "identity", "identityKey", "deviceKey", "displayName", "profileDocument", "undefined", "stateUpdate", "on", "createProfile", "request", "createIdentity", "recoverProfile", "seedPhrase", "Error", "SystemServiceImpl", "constructor", "_config", "_serviceContext", "initSession", "getConfig", "request", "values", "getStatus", "message", "Date", "now", "reset", "TracingServiceImpl", "constructor", "_config", "setTracingOptions", "Error", "subscribeToRpcTrace", "Event", "AsyncEvent", "Stream", "EventSubscriptions", "Stream", "FeedIterator", "PublicKey", "ComplexMap", "subscribeToFeeds", "feedStore", "feedKeys", "next", "length", "feedMap", "hash", "subscriptions", "update", "feeds", "filter", "feed", "some", "feedKey", "equals", "key", "forEach", "has", "set", "on", "add", "off", "Array", "from", "values", "map", "properties", "feedOpened", "clear", "subscribeToFeedBlocks", "maxBlocks", "timeout", "setTimeout", "getFeed", "iterator", "open", "blocks", "block", "push", "slice", "close", "clearTimeout", "Stream", "subscribeToKeyringKeys", "keyring", "next", "update", "keys", "list", "unsubscribe", "keysUpdate", "on", "Stream", "PublicKey", "subscribeToNetworkStatus", "networkManager", "next", "close", "update", "status", "signalManager", "getStatus", "servers", "err", "statusChanged", "on", "subscribeToSignalTrace", "events", "trace", "commandTrace", "msg", "push", "map", "JSON", "stringify", "subscribeToNetworkTopics", "topics", "labeledTopics", "topic", "label", "getSwarm", "toHex", "topicsUpdated", "subscribeToSwarmInfo", "_a", "info", "connectionLog", "swarms", "data", "getNetworkPeers", "request", "Error", "getSwarmMap", "from", "peers", "peer", "connections", "connection", "asUint8Array", "Stream", "subscribeToSpaces", "context", "spaceKeys", "next", "unsubscribe", "update", "spaces", "spaceManager", "values", "filteredSpaces", "filter", "space", "length", "some", "spaceKey", "equals", "key", "map", "spaceMetadata", "metadataStore", "find", "isOpen", "timeframe", "latestTimeframe", "genesisFeed", "genesisFeedKey", "controlFeed", "controlFeedKey", "dataFeed", "dataFeedKey", "timeout", "setTimeout", "initialized", "wait", "dataSpaceManager", "updated", "on", "clearTimeout", "DevtoolsHostEvents", "ready", "AsyncEvent", "DevtoolsServiceImpl", "constructor", "params", "events", "request", "Stream", "next", "on", "getConfig", "Error", "resetStorage", "enableDebugLogging", "disableDebugLogging", "subscribeToKeyringKeys", "keyring", "context", "subscribeToCredentialMessages", "subscribeToSpaces", "subscribeToItems", "subscribeToFeeds", "feedStore", "subscribeToFeedBlocks", "getSpaceSnapshot", "saveSpaceSnapshot", "clearSnapshots", "getNetworkPeers", "subscribeToNetworkTopics", "subscribeToSignalStatus", "subscribeToNetworkStatus", "networkManager", "subscribeToSignalTrace", "subscribeToSwarmInfo", "Trigger", "Context", "verifyCredential", "log", "schema", "createHaloAuthProvider", "signer", "nonce", "credential", "createCredential", "assertion", "subject", "getIssuer", "getCodecForType", "encode", "HaloAuthVerifier", "constructor", "_params", "_ctx", "close", "dispose", "_isTrustedDevice", "deviceKey", "deviceSet", "trustedDevicesProvider", "has", "verifier", "auth", "decode", "result", "kind", "proof", "Buffer", "from", "equals", "issuer", "trigger", "onDispose", "wake", "clear", "update", "on", "wait", "timeout", "authTimeout", "assert", "Event", "DeviceStateMachine", "createCredentialSignerWithKey", "createCredentialSignerWithChain", "ProfileStateMachine", "writeMessages", "log", "AdmittedFeed", "AUTH_TIMEOUT", "Identity", "constructor", "space", "signer", "identityKey", "deviceKey", "stateUpdate", "Event", "_signer", "_deviceStateMachine", "spaceState", "registerProcessor", "DeviceStateMachine", "onUpdate", "emit", "_profileStateMachine", "ProfileStateMachine", "authVerifier", "HaloAuthVerifier", "trustedDevicesProvider", "authorizedDeviceKeys", "update", "authTimeout", "processor", "open", "close", "ready", "deviceChainReady", "wait", "profileDocument", "profile", "controlPipeline", "haloSpaceKey", "key", "haloGenesisFeedKey", "genesisFeedKey", "getAdmissionCredentials", "controlFeedKey", "dataFeedKey", "getIdentityCredentialSigner", "assert", "deviceCredentialChain", "createCredentialSignerWithChain", "getDeviceCredentialSigner", "createCredentialSignerWithKey", "admitDevice", "log", "hostDevice", "writeMessages", "writer", "createCredential", "subject", "assertion", "spaceKey", "designation", "AdmittedFeed", "Designation", "CONTROL", "DATA", "map", "credential", "assert", "Event", "createCredentialSignerWithKey", "CredentialGenerator", "log", "AdmittedFeed", "deferFunction", "IdentityManager", "constructor", "_metadataStore", "_keyring", "_spaceManager", "stateUpdate", "Event", "identity", "_identity", "open", "load", "identityRecord", "getIdentityRecord", "log", "_constructIdentity", "ready", "emit", "close", "createIdentity", "displayName", "assert", "controlFeedKey", "createKey", "identityKey", "deviceKey", "haloSpace", "spaceKey", "genesisFeedKey", "writeControlFeedKey", "writeDataFeedKey", "generator", "CredentialGenerator", "credentials", "createSpaceGenesis", "createFeedAdmission", "AdmittedFeed", "Designation", "DATA", "push", "createProfileCredential", "createDeviceAuthorization", "credential", "controlPipeline", "writer", "write", "setIdentityRecord", "acceptIdentity", "params", "haloSpaceKey", "haloGenesisFeedKey", "space", "_constructSpace", "spaceRecord", "swarmIdentity", "peerKey", "credentialProvider", "createHaloAuthProvider", "createCredentialSignerWithKey", "credentialAuthenticator", "deferFunction", "authVerifier", "verifier", "Identity", "signer", "constructSpace", "metadata", "key", "dataFeedKey", "onNetworkConnection", "base", "schema", "base62", "codec", "getCodecForType", "InvitationEncoder", "decode", "text", "encode", "invitation", "assert", "scheduleTask", "sleep", "Trigger", "Context", "generatePasscode", "failUndefined", "PublicKey", "log", "createTeleportProtocolFactory", "StarTopology", "schema", "Invitation", "AuthenticationResponse", "RpcExtension", "assert", "CancellableObservableProvider", "Invitation", "AUTHENTICATION_CODE_LENGTH", "INVITATION_TIMEOUT", "ON_CLOSE_DELAY", "InvitationObservableProvider", "invitation", "_invitation", "setInvitation", "AuthenticatingInvitationProvider", "constructor", "_actions", "onCancel", "authenticate", "authenticationCode", "onAuthenticate", "wrapObservable", "observable", "Promise", "resolve", "reject", "unsubscribe", "subscribe", "onSuccess", "state", "State", "SUCCESS", "onError", "err", "AbstractInvitationsHandler", "_networkManager", "HaloInvitationsHandler", "AbstractInvitationsHandler", "constructor", "networkManager", "_identityManager", "createInvitation", "context", "options", "type", "timeout", "INVITATION_TIMEOUT", "swarmKey", "assert", "Invitation", "Type", "OFFLINE", "identity", "failUndefined", "invitation", "invitationId", "PublicKey", "random", "toHex", "authenticationCode", "generatePasscode", "AUTHENTICATION_CODE_LENGTH", "ctx", "Context", "onError", "err", "dispose", "observable", "callback", "InvitationObservableProvider", "complete", "Trigger", "createExtension", "hostInvitationExtension", "HostHaloInvitationExtension", "requestAdmission", "_a", "log", "host", "deviceKey", "onAuthenticating", "identityKey", "haloSpaceKey", "genesisFeedKey", "haloGenesisFeedKey", "authenticate", "code", "status", "AuthenticationResponse", "Status", "OK", "presentAdmissionCredentials", "credentials", "INTERACTIVE_TESTING", "undefined", "Error", "guest", "admitDevice", "wake", "onOpen", "scheduleTask", "onConnected", "wait", "onSuccess", "cancelled", "error", "sleep", "ON_CLOSE_DELAY", "topic", "swarmConnection", "_networkManager", "joinSwarm", "peerId", "protocolProvider", "createTeleportProtocolFactory", "teleport", "addExtension", "topology", "StarTopology", "onDispose", "close", "onConnecting", "acceptInvitation", "authenticated", "AuthenticatingInvitationProvider", "onCancel", "onAuthenticate", "connectionCount", "extension", "GuestHaloInvitationExtension", "rpc", "HaloHostService", "INTERACTIVE", "acceptIdentity", "getAdmissionCredentials", "warn", "RpcExtension", "_callbacks", "exposed", "schema", "getService", "getHandlers", "requested", "assert", "observableError", "log", "Invitation", "AbstractInvitationsProxy", "constructor", "_invitationsService", "createInvitation", "context", "options", "invitationId", "observable", "InvitationObservableProvider", "cancelInvitation", "invitation", "getInvitationOptions", "stream", "subscribe", "setInvitation", "state", "Invitation", "State", "CONNECTING", "assert", "callback", "onConnecting", "CONNECTED", "onConnected", "AUTHENTICATING", "onAuthenticating", "SUCCESS", "onSuccess", "CANCELLED", "onCancelled", "log", "error", "err", "observableError", "acceptInvitation", "swarmKey", "AuthenticatingInvitationProvider", "onCancel", "onAuthenticate", "authenticationCode", "authenticate", "HaloInvitationsProxy", "AbstractInvitationsProxy", "getInvitationOptions", "assert", "Stream", "log", "Invitation", "AbstractInvitationsService", "_identityManager", "_getInvitationsHandler", "_createInvitations", "Map", "_acceptInvitations", "getLoggingContext", "deviceKey", "identity", "createInvitation", "invitation", "next", "close", "invitationsHandler", "context", "getContext", "invitationId", "type", "swarmKey", "observable", "subscribe", "onConnecting", "set", "state", "State", "CONNECTING", "onConnected", "CONNECTED", "onAuthenticating", "AUTHENTICATING", "onSuccess", "SUCCESS", "onCancelled", "CANCELLED", "onTimeout", "err", "TIMEOUT", "onError", "ERROR", "warn", "delete", "acceptInvitation", "options", "authenticate", "authenticationCode", "get", "cancelInvitation", "cancel", "HaloInvitationsServiceImpl", "AbstractInvitationsService", "constructor", "identityManager", "invitationsHandler", "getContext", "invitation", "assert", "scheduleTask", "sleep", "Trigger", "Context", "createAdmissionCredentials", "generatePasscode", "getCredentialAssertion", "writeMessages", "PublicKey", "log", "createTeleportProtocolFactory", "StarTopology", "schema", "Invitation", "AuthenticationResponse", "RpcExtension", "MAX_OTP_ATTEMPTS", "SpaceInvitationsHandler", "AbstractInvitationsHandler", "constructor", "networkManager", "_spaceManager", "_signingContext", "_keyring", "createInvitation", "space", "options", "swarmConnection", "type", "timeout", "INVITATION_TIMEOUT", "swarmKey", "assert", "Invitation", "Type", "OFFLINE", "invitation", "invitationId", "PublicKey", "random", "toHex", "spaceKey", "key", "authenticationCode", "generatePasscode", "AUTHENTICATION_CODE_LENGTH", "ctx", "Context", "onError", "err", "dispose", "observable", "callback", "InvitationObservableProvider", "close", "authenticationRetry", "createExtension", "complete", "Trigger", "guestProfile", "hostInvitationExtension", "HostSpaceInvitationExtension", "introduce", "profile", "log", "host", "deviceKey", "onAuthenticating", "authenticate", "code", "status", "AuthenticationResponse", "Status", "OK", "INVALID_OPT_ATTEMPTS", "INVALID_OTP", "requestAdmission", "identityKey", "controlFeedKey", "dataFeedKey", "INTERACTIVE_TESTING", "MULTIUSE_TESTING", "undefined", "Error", "guest", "credentials", "createAdmissionCredentials", "credentialSigner", "inner", "genesisFeedKey", "spaceMemberCredential", "credential", "getCredentialAssertion", "writeMessages", "controlPipeline", "writer", "wake", "onOpen", "scheduleTask", "onConnected", "wait", "onSuccess", "cancelled", "error", "sleep", "ON_CLOSE_DELAY", "topic", "_networkManager", "joinSwarm", "peerId", "protocolProvider", "createTeleportProtocolFactory", "teleport", "addExtension", "topology", "StarTopology", "onDispose", "onConnecting", "acceptInvitation", "authenticated", "AuthenticatingInvitationProvider", "onCancel", "onAuthenticate", "connectionCount", "extension", "GuestSpaceInvitationExtension", "rpc", "SpaceHostService", "INTERACTIVE", "attempt", "response", "reset", "createKey", "assertion", "subject", "id", "equals", "acceptSpace", "warn", "RpcExtension", "_callbacks", "exposed", "schema", "getService", "getHandlers", "params", "context", "requested", "SpaceInvitationsProxy", "AbstractInvitationsProxy", "getInvitationOptions", "context", "spaceKey", "assert", "SpaceInvitationsServiceImpl", "AbstractInvitationsService", "constructor", "identityManager", "invitationsHandler", "_getSpaceManager", "getContext", "invitation", "assert", "spaceKey", "spaceManager", "space", "spaces", "get", "Trigger", "failUndefined", "MOCK_AUTH_PROVIDER", "MOCK_AUTH_VERIFIER", "valueEncoding", "DataServiceSubscriptions", "MetadataStore", "SpaceManager", "SnapshotStore", "FeedFactory", "FeedStore", "Keyring", "log", "Event", "synchronized", "trackLeaks", "Context", "spaceGenesis", "SnapshotManager", "PublicKey", "log", "Presence", "ComplexMap", "assert", "trackLeaks", "Context", "DataPipelineControllerImpl", "DataSpace", "constructor", "params", "_ctx", "_inner", "inner", "_presence", "presence", "_dataPipelineController", "modelFactory", "metadataStore", "snapshotManager", "memberKey", "spaceKey", "key", "feedInfoProvider", "feedKey", "spaceState", "feeds", "get", "snapshotId", "isOpen", "dataPipelineController", "database", "stateUpdate", "open", "initDataPipeline", "close", "dispose", "destroy", "__decorate", "DataSpaceManager", "constructor", "_spaceManager", "_metadataStore", "_dataServiceSubscriptions", "_keyring", "_signingContext", "_modelFactory", "_snapshotStore", "_ctx", "Context", "updated", "Event", "_spaces", "ComplexMap", "PublicKey", "hash", "spaces", "open", "load", "log", "length", "spaceMetadata", "space", "_constructSpace", "latestTimeframe", "dataPipelineController", "waitUntilTimeframe", "close", "dispose", "values", "createSpace", "spaceKey", "createKey", "controlFeedKey", "dataFeedKey", "metadata", "key", "genesisFeedKey", "spaceGenesis", "inner", "addSpace", "emit", "acceptSpace", "opts", "presence", "Presence", "localPeerId", "deviceKey", "announceInterval", "offlineTimeout", "identityKey", "snapshotManager", "SnapshotManager", "constructSpace", "swarmIdentity", "peerKey", "credentialProvider", "credentialAuthenticator", "onNetworkConnection", "session", "addExtension", "createExtension", "remotePeerId", "objectSync", "dataSpace", "DataSpace", "modelFactory", "metadataStore", "memberKey", "snapshotId", "snapshot", "registerSpace", "database", "createDataServiceHost", "set", "synchronized", "trackLeaks", "ServiceContext", "constructor", "storage", "networkManager", "modelFactory", "initialized", "Trigger", "dataServiceSubscriptions", "DataServiceSubscriptions", "metadataStore", "MetadataStore", "createDirectory", "snapshotStore", "SnapshotStore", "keyring", "Keyring", "feedStore", "FeedStore", "factory", "FeedFactory", "root", "signer", "hypercore", "valueEncoding", "spaceManager", "SpaceManager", "identityManager", "IdentityManager", "haloInvitations", "HaloInvitationsHandler", "open", "log", "identity", "_initialize", "close", "dataSpaceManager", "clear", "reset", "createIdentity", "params", "failUndefined", "signingContext", "credentialProvider", "MOCK_AUTH_PROVIDER", "credentialAuthenticator", "MOCK_AUTH_VERIFIER", "credentialSigner", "getIdentityCredentialSigner", "identityKey", "deviceKey", "profile", "profileDocument", "DataSpaceManager", "spaceInvitations", "SpaceInvitationsHandler", "wake", "schema", "createServiceBundle", "clientServiceBundle", "HaloInvitationsService", "getService", "DevicesService", "SpaceInvitationsService", "SpacesService", "NetworkService", "SpaceService", "DataService", "ProfileService", "SystemService", "DevtoolsHost", "TracingService", "raise", "DataServiceImpl", "log", "ModelFactory", "ObjectModel", "TextModel", "EventSubscriptions", "Stream", "DevicesServiceImpl", "constructor", "_identityManager", "updateDevice", "Error", "queryDevices", "next", "update", "deviceKeys", "identity", "authorizedDeviceKeys", "devices", "Array", "from", "values", "map", "key", "deviceKey", "dispose", "add", "stateUpdate", "on", "clear", "Stream", "NetworkServiceImpl", "constructor", "networkManager", "subscribeToNetworkStatus", "next", "unsubscribe", "connectionStateChanged", "on", "state", "connectionState", "setNetworkOptions", "request", "setConnectionState", "scheduleTask", "Stream", "raise", "SpaceNotFoundError", "SpacesServiceImpl", "constructor", "_spaceManager", "createSpace", "Error", "querySpaces", "queryMembers", "query", "queryCredentials", "spaceKey", "ctx", "next", "space", "spaces", "get", "processor", "spaceState", "registerProcessor", "process", "credential", "onDispose", "close", "open", "InvalidConfigError", "Runtime", "createStorage", "StorageType", "StorageDriver", "createStorageObjects", "config", "path", "storageType", "keyStorage", "persistent", "RAM", "undefined", "storage", "type", "toStorageType", "root", "CHROME", "FIREFOX", "IDB", "NODE", "Error", "ServiceRegistry", "constructor", "_serviceBundle", "_handlers", "descriptors", "services", "createDefaultModelFactory", "ModelFactory", "registerModel", "ObjectModel", "TextModel", "ClientServicesHost", "constructor", "config", "modelFactory", "networkManager", "storage", "createStorageObjects", "get", "_config", "_modelFactory", "_networkManager", "_storage", "descriptors", "_serviceRegistry", "services", "open", "log", "_initialize", "_serviceContext", "deviceKey", "identityManager", "identity", "close", "ServiceContext", "ServiceRegistry", "clientServiceBundle", "HaloInvitationsService", "HaloInvitationsServiceImpl", "haloInvitations", "DevicesService", "DevicesServiceImpl", "SpaceInvitationsService", "SpaceInvitationsServiceImpl", "spaceInvitations", "raise", "Error", "dataSpaceManager", "SpacesService", "SpacesServiceImpl", "spaceManager", "DataService", "DataServiceImpl", "dataServiceSubscriptions", "NetworkService", "NetworkServiceImpl", "ProfileService", "ProfileServiceImpl", "SpaceService", "SpaceServiceImpl", "SystemService", "SystemServiceImpl", "TracingService", "TracingServiceImpl", "DevtoolsHost", "DevtoolsServiceImpl", "events", "DevtoolsHostEvents", "context", "asyncTimeout", "RemoteServiceConnectionTimeout", "createProtoRpcPeer", "ClientServicesProxy", "constructor", "port", "_timeout", "_proxy", "createProtoRpcPeer", "requested", "clientServiceBundle", "exposed", "handlers", "proxy", "descriptors", "services", "rpc", "open", "asyncTimeout", "RemoteServiceConnectionTimeout", "close", "WebRTCTransportService", "createProtoRpcPeer", "schema", "iframeServiceBundle", "IframeService", "getService", "BridgeService", "workerServiceBundle", "WorkerService", "IFrameRuntime", "constructor", "systemPort", "workerAppPort", "windowAppPort", "_transportService", "WebRTCTransportService", "_systemPort", "_windowAppPort", "_workerAppPort", "_systemRpc", "createProtoRpcPeer", "requested", "workerServiceBundle", "exposed", "iframeServiceBundle", "handlers", "BridgeService", "IframeService", "heartbeat", "port", "timeout", "subscribe", "msg", "send", "open", "origin", "rpc", "WorkerService", "start", "close", "stop", "Trigger", "MemorySignalManager", "MemorySignalManagerContext", "WebsocketSignalManager", "NetworkManager", "WebRTCTransportProxyFactory", "assert", "Trigger", "log", "logInfo", "createProtoRpcPeer", "Callback", "__decorate", "WorkerSession", "constructor", "getServices", "systemPort", "appPort", "options", "heartbeatInterval", "_startTrigger", "Trigger", "onClose", "Callback", "assert", "_options", "_getServices", "_clientRpc", "createProtoRpcPeer", "exposed", "clientServiceBundle", "handlers", "HaloInvitationsService", "services", "DevicesService", "SpaceInvitationsService", "SpacesService", "NetworkService", "SpaceService", "DataService", "ProfileService", "SystemService", "DevtoolsHost", "TracingService", "port", "_iframeRpc", "requested", "iframeServiceBundle", "workerServiceBundle", "WorkerService", "start", "request", "origin", "wake", "stop", "setTimeout", "close", "err", "log", "catch", "timeout", "bridgeService", "rpc", "BridgeService", "open", "info", "Promise", "all", "wait", "_heartbeatTimer", "setInterval", "IframeService", "heartbeat", "warn", "callIfSet", "undefined", "clearInterval", "logInfo", "WorkerRuntime", "constructor", "_configProvider", "_transportFactory", "WebRTCTransportProxyFactory", "_ready", "Trigger", "sessions", "Set", "start", "_config", "signalServer", "get", "_clientServices", "ClientServicesHost", "config", "networkManager", "NetworkManager", "log", "signalManager", "WebsocketSignalManager", "MemorySignalManager", "MemorySignalManagerContext", "transportFactory", "open", "wake", "undefined", "err", "stop", "close", "createSession", "appPort", "systemPort", "session", "WorkerSession", "getServices", "error", "wait", "readySignal", "onClose", "set", "delete", "_reconnectWebrtc", "add", "_sessionForNetworking", "has", "selected", "Array", "from", "find", "bridgeService", "setBridgeService"]
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { EventSubscriptions } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { todo } from '@dxos/debug';\nimport { log } from '@dxos/log';\nimport {\n AuthenticateInvitationRequest,\n CreateSnapshotRequest,\n GetSpaceDetailsRequest,\n Space,\n SpaceMember,\n SpaceDetails,\n SpaceService,\n SetSpaceStateRequest,\n SubscribeMembersRequest,\n SubscribeMembersResponse,\n SubscribeSpacesResponse,\n SubscribeSpaceRequest,\n SubscribeSpaceResponse\n} from '@dxos/protocols/proto/dxos/client';\nimport { SpaceSnapshot } from '@dxos/protocols/proto/dxos/echo/snapshot';\nimport { humanize } from '@dxos/util';\n\nimport { ServiceContext } from '../services';\nimport { InviteeInvitations } from './invitations';\n\n/**\n * Space service implementation.\n * @deprecated\n */\nexport class SpaceServiceImpl implements SpaceService {\n private inviteeInvitations: InviteeInvitations = new Map();\n\n constructor(private readonly serviceContext: ServiceContext) {}\n\n subscribeToSpace(request: SubscribeSpaceRequest): Stream<SubscribeSpaceResponse> {\n return new Stream(({ next }) => {\n next({\n space: {\n publicKey: request.spaceKey,\n isOpen: true,\n isActive: true,\n members: []\n }\n });\n });\n\n // const update = (next: (message: SubscribeSpaceResponse) => void) => {\n // try {\n // const space = this.echo.getSpace(request.space_key);\n // next({\n // space: space && {\n // public_key: space.key,\n // is_open: space.is_open,\n // is_active: space.is_active,\n // members: space.queryMembers().value\n // }\n // });\n // } catch (err) {\n // if (err instanceof InvalidStateError) {\n // // Do nothing.\n // } else {\n // throw err;\n // }\n // }\n // };\n\n // const space = this.serviceContext.brane.getSpace(request.space_key);\n // if (space) {\n // return new Stream(({ next }) => space.update.on(() => update(next)));\n // } else {\n // return new Stream(({ next }) => {\n // let unsubscribeSpace: () => void;\n // const unsubscribeSpaces = this.echo.querySpaces().subscribe((spaces) => {\n // const space = spaces.find((space) => space.key.equals(request.space_key));\n // if (space && !unsubscribeSpace) {\n // unsubscribeSpace = space.update.on(() => update(next));\n // }\n // });\n\n // update(next);\n\n // return () => {\n // unsubscribeSpaces();\n // unsubscribeSpace?.();\n // };\n // });\n // }\n }\n\n subscribeSpaces() {\n return new Stream<SubscribeSpacesResponse>(({ next }) => {\n const subscriptions = new EventSubscriptions();\n\n const onUpdate = () => {\n const spaces = Array.from(this.serviceContext.dataSpaceManager!.spaces.values()).map(\n (space): Space => ({\n publicKey: space.key,\n isOpen: true,\n isActive: true,\n members: Array.from(space.inner.spaceState.members.values()).map((member) => ({\n identityKey: member.key,\n profile: {\n identityKey: member.key,\n displayName: member.assertion.profile?.displayName ?? humanize(member.key)\n },\n presence:\n this.serviceContext.identityManager.identity?.identityKey.equals(member.key) ||\n space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0\n ? SpaceMember.PresenceState.ONLINE\n : SpaceMember.PresenceState.OFFLINE\n }))\n })\n );\n log('update', { spaces });\n next({ spaces });\n };\n\n setTimeout(async () => {\n if (!this.serviceContext.dataSpaceManager) {\n next({ spaces: [] });\n }\n\n await this.serviceContext.initialized.wait();\n\n subscriptions.add(\n this.serviceContext.dataSpaceManager!.updated.on(() => {\n this.serviceContext.dataSpaceManager!.spaces.forEach((space) => {\n subscriptions.add(space.stateUpdate.on(onUpdate));\n subscriptions.add(space.presence.updated.on(onUpdate));\n });\n onUpdate();\n })\n );\n\n this.serviceContext.dataSpaceManager!.spaces.forEach((space) => {\n subscriptions.add(space.stateUpdate.on(onUpdate));\n subscriptions.add(space.presence.updated.on(onUpdate));\n });\n\n onUpdate();\n });\n\n return () => subscriptions.clear();\n });\n }\n\n async getSpaceDetails(request: GetSpaceDetailsRequest): Promise<SpaceDetails> {\n return todo();\n // const space = this.echo.getSpace(request.space_key) ?? raise(new SpaceNotFoundError(request.space_key));\n // return {\n // processedTimeframe: space.timeframe\n // };\n }\n\n async createSpace(): Promise<Space> {\n await this.serviceContext.initialized.wait();\n const space = await this.serviceContext.dataSpaceManager!.createSpace();\n return {\n publicKey: space.key,\n isOpen: true,\n isActive: true\n };\n }\n\n async cloneSpace(snapshot: SpaceSnapshot): Promise<Space> {\n return todo();\n // const space = await this.echo.cloneSpace(snapshot);\n // return {\n // public_key: space.key,\n // is_open: space.is_open,\n // is_active: space.is_active\n // };\n }\n\n async setSpaceState(request: SetSpaceStateRequest) {\n return todo();\n // const space = this.echo.getSpace(request.space_key);\n // if (!space) {\n // throw new Error('Space not found');\n // }\n\n // if (request.open === true) {\n // await space.open();\n // } else if (request.open === false) {\n // await space.close();\n // } // Undefined preserves previous state.\n\n // if (request.active_global === true) {\n // await space.activate({ global: true });\n // } else if (request.active_global === false) {\n // await space.deactivate({ global: true });\n // } // Undefined preserves previous state.\n\n // if (request.active_device === true) {\n // await space.activate({ device: true });\n // } else if (request.active_device === false) {\n // await space.deactivate({ device: true });\n // } // Undefined preserves previous state.\n // return {\n // public_key: space.key,\n // is_open: space.is_open,\n // is_active: space.is_active\n // };\n }\n\n async authenticateInvitation(request: AuthenticateInvitationRequest) {\n assert(request.processId, 'Process ID is missing.');\n const invitation = this.inviteeInvitations.get(request.processId);\n assert(invitation, 'Invitation not found.');\n assert(request.secret, 'Secret not provided.');\n\n // Supply the secret, and move the internal invitation process by triggering the secretTrigger.\n invitation.secret = request.secret;\n invitation.secretTrigger?.();\n }\n\n subscribeMembers(request: SubscribeMembersRequest): Stream<SubscribeMembersResponse> {\n return todo();\n // const space = this.echo.getSpace(request.space_key);\n // if (space) {\n // return resultSetToStream(space.queryMembers(), (members): SubscribeMembersResponse => ({ members }));\n // } else {\n // return new Stream(({ next }) => {\n // let unsubscribeMembers: () => void;\n // const unsubscribeSpaces = this.echo.querySpaces().subscribe((spaces) => {\n // const space = spaces.find((space) => space.key.equals(request.space_key));\n // if (!unsubscribeMembers && space) {\n // const resultSet = space.queryMembers();\n // next({ members: resultSet.value });\n // unsubscribeMembers = resultSet.update.on(() => next({ members: resultSet.value }));\n // }\n // });\n\n // return () => {\n // unsubscribeSpaces();\n // unsubscribeMembers();\n // };\n // });\n // }\n }\n\n async createSnapshot(request: CreateSnapshotRequest): Promise<SpaceSnapshot> {\n return todo();\n // assert(request.space_key);\n // const space = this.echo.getSpace(request.space_key) ?? raise(new SpaceNotFoundError(request.space_key));\n // return space.createSnapshot();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { todo } from '@dxos/debug';\nimport {\n CreateProfileRequest,\n Profile,\n ProfileService,\n RecoverProfileRequest,\n SubscribeProfileResponse\n} from '@dxos/protocols/proto/dxos/client';\n\nimport { ServiceContext } from '../services';\nimport { InviteeInvitations } from './invitations';\n\n/**\n * Profile service implementation.\n * @deprecated\n */\nexport class ProfileServiceImpl implements ProfileService {\n private inviteeInvitations: InviteeInvitations = new Map();\n\n constructor(private readonly context: ServiceContext) {}\n\n subscribeProfile(): Stream<SubscribeProfileResponse> {\n return new Stream(({ next }) => {\n const emitNext = () =>\n next({\n profile: this.context.identityManager.identity\n ? {\n identityKey: this.context.identityManager.identity.identityKey,\n deviceKey: this.context.identityManager.identity.deviceKey,\n displayName: this.context.identityManager.identity.profileDocument?.displayName\n }\n : undefined\n });\n\n emitNext();\n return this.context.identityManager.stateUpdate.on(emitNext);\n });\n }\n\n async createProfile(request: CreateProfileRequest): Promise<Profile> {\n await this.context.createIdentity({\n displayName: request.displayName\n });\n return {\n identityKey: this.context.identityManager.identity!.identityKey,\n deviceKey: this.context.identityManager.identity!.deviceKey,\n displayName: this.context.identityManager.identity!.profileDocument?.displayName\n };\n }\n\n async recoverProfile(request: RecoverProfileRequest): Promise<Profile> {\n return todo();\n if (!request.seedPhrase) {\n throw new Error('Recovery SeedPhrase not provided.');\n }\n // await this.echo.open();\n // await this.echo.halo.recover(request.seed_phrase);\n // const profile = this.echo.halo.getProfile();\n // assert(profile, 'Recovering profile failed.');\n // return profile;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Config } from '@dxos/config';\nimport { SystemService } from '@dxos/protocols/proto/dxos/client';\n\nimport { ServiceContext } from '../services';\n\n/**\n * @deprecated\n */\nexport class SystemServiceImpl implements SystemService {\n constructor(private readonly _config: Config, private readonly _serviceContext: ServiceContext) {}\n\n // TODO(burdon): Remove.\n async initSession() {\n // Ok.\n }\n\n async getConfig(request: void) {\n return this._config.values;\n }\n\n // TODO(burdon): Connect to iframe RPC heartbeat for network status?\n async getStatus(request: void) {\n return {\n message: `ok: ${Date.now()}`\n };\n }\n\n async reset(request: any) {\n await this._serviceContext.reset();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Config } from '@dxos/config';\nimport { TracingService } from '@dxos/protocols/proto/dxos/devtools/host';\n\n/**\n * @deprecated\n */\nexport class TracingServiceImpl implements TracingService {\n constructor(private readonly _config: Config) {}\n\n async setTracingOptions() {\n throw new Error('Tracing not available.');\n }\n\n subscribeToRpcTrace(): any {\n throw new Error('Tracing not available.');\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event as AsyncEvent } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { Config } from '@dxos/config';\nimport {\n ClearSnapshotsRequest,\n DevtoolsHost, // TODO(burdon): Rename DevtoolsService\n EnableDebugLoggingRequest,\n EnableDebugLoggingResponse,\n Event,\n GetConfigResponse,\n GetNetworkPeersRequest,\n GetNetworkPeersResponse,\n GetSpaceSnapshotRequest,\n GetSpaceSnapshotResponse,\n ResetStorageRequest,\n SaveSpaceSnapshotRequest,\n SaveSpaceSnapshotResponse,\n SubscribeToCredentialMessagesRequest,\n SubscribeToCredentialMessagesResponse,\n SubscribeToFeedBlocksRequest,\n SubscribeToFeedBlocksResponse,\n SubscribeToFeedsRequest,\n SubscribeToFeedsResponse,\n SubscribeToItemsRequest,\n SubscribeToItemsResponse,\n SubscribeToKeyringKeysRequest,\n SubscribeToKeyringKeysResponse,\n SubscribeToNetworkTopicsResponse,\n SubscribeToSpacesRequest,\n SubscribeToSpacesResponse,\n SubscribeToSignalStatusResponse,\n SubscribeToSignalTraceResponse,\n SubscribeToSwarmInfoResponse\n} from '@dxos/protocols/proto/dxos/devtools/host';\n\nimport { ServiceContext } from '../services';\nimport { subscribeToFeedBlocks, subscribeToFeeds } from './feeds';\nimport { subscribeToKeyringKeys } from './keys';\nimport { subscribeToNetworkStatus, subscribeToSignalTrace, subscribeToSwarmInfo } from './network';\nimport { subscribeToSpaces } from './spaces';\n\nexport class DevtoolsHostEvents {\n readonly ready = new AsyncEvent();\n}\n\nexport type DevtoolsServiceParams = {\n events: DevtoolsHostEvents;\n config: Config;\n context: ServiceContext;\n};\n\n/**\n * @deprecated\n */\nexport class DevtoolsServiceImpl implements DevtoolsHost {\n constructor(private readonly params: DevtoolsServiceParams) {}\n\n events(request: void): Stream<Event> {\n return new Stream<Event>(({ next }) => {\n this.params.events.ready.on(() => {\n next({ ready: {} });\n });\n });\n }\n\n getConfig(request: void): Promise<GetConfigResponse> {\n throw new Error();\n }\n\n resetStorage(request: ResetStorageRequest): Promise<void> {\n throw new Error();\n }\n\n enableDebugLogging(request: EnableDebugLoggingRequest): Promise<EnableDebugLoggingResponse> {\n throw new Error();\n }\n\n disableDebugLogging(request: EnableDebugLoggingRequest): Promise<EnableDebugLoggingResponse> {\n throw new Error();\n }\n\n subscribeToKeyringKeys(request: SubscribeToKeyringKeysRequest): Stream<SubscribeToKeyringKeysResponse> {\n return subscribeToKeyringKeys({ keyring: this.params.context.keyring });\n }\n\n subscribeToCredentialMessages(\n request: SubscribeToCredentialMessagesRequest\n ): Stream<SubscribeToCredentialMessagesResponse> {\n throw new Error();\n }\n\n subscribeToSpaces(request: SubscribeToSpacesRequest): Stream<SubscribeToSpacesResponse> {\n return subscribeToSpaces(this.params.context, request);\n }\n\n subscribeToItems(request: SubscribeToItemsRequest): Stream<SubscribeToItemsResponse> {\n throw new Error();\n }\n\n subscribeToFeeds(request: SubscribeToFeedsRequest): Stream<SubscribeToFeedsResponse> {\n return subscribeToFeeds({ feedStore: this.params.context.feedStore }, request);\n }\n\n subscribeToFeedBlocks(request: SubscribeToFeedBlocksRequest): Stream<SubscribeToFeedBlocksResponse> {\n return subscribeToFeedBlocks({ feedStore: this.params.context.feedStore }, request);\n }\n\n getSpaceSnapshot(request: GetSpaceSnapshotRequest): Promise<GetSpaceSnapshotResponse> {\n throw new Error();\n }\n\n saveSpaceSnapshot(request: SaveSpaceSnapshotRequest): Promise<SaveSpaceSnapshotResponse> {\n throw new Error();\n }\n\n clearSnapshots(request: ClearSnapshotsRequest): Promise<void> {\n throw new Error();\n }\n\n getNetworkPeers(request: GetNetworkPeersRequest): Promise<GetNetworkPeersResponse> {\n throw new Error();\n }\n\n subscribeToNetworkTopics(request: void): Stream<SubscribeToNetworkTopicsResponse> {\n throw new Error();\n }\n\n subscribeToSignalStatus(request: void): Stream<SubscribeToSignalStatusResponse> {\n return subscribeToNetworkStatus({ networkManager: this.params.context.networkManager });\n }\n\n subscribeToSignalTrace(): Stream<SubscribeToSignalTraceResponse> {\n return subscribeToSignalTrace({ networkManager: this.params.context.networkManager });\n }\n\n subscribeToSwarmInfo(): Stream<SubscribeToSwarmInfoResponse> {\n return subscribeToSwarmInfo({ networkManager: this.params.context.networkManager });\n }\n}\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { EventSubscriptions } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { FeedIterator, FeedStore, FeedWrapper } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport {\n SubscribeToFeedsRequest,\n SubscribeToFeedsResponse,\n SubscribeToFeedBlocksRequest,\n SubscribeToFeedBlocksResponse\n} from '@dxos/protocols/proto/dxos/devtools/host';\nimport { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { ComplexMap } from '@dxos/util';\n\nexport const subscribeToFeeds = (\n { feedStore }: { feedStore: FeedStore<FeedMessage> },\n { feedKeys }: SubscribeToFeedsRequest\n) =>\n new Stream<SubscribeToFeedsResponse>(({ next }) => {\n if (feedKeys?.length === 0) {\n return;\n }\n\n const feedMap = new ComplexMap<PublicKey, FeedWrapper<FeedMessage>>(PublicKey.hash);\n const subscriptions = new EventSubscriptions();\n\n const update = () => {\n const feeds = feedStore.feeds;\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 });\n next({\n feeds: Array.from(feedMap.values()).map((feed) => ({ feedKey: feed.key, length: feed.properties.length }))\n });\n };\n\n subscriptions.add(feedStore.feedOpened.on(update));\n update();\n\n return () => {\n subscriptions.clear();\n };\n });\n\nexport const subscribeToFeedBlocks = (\n { feedStore }: { feedStore: FeedStore<FeedMessage> },\n { feedKey, maxBlocks = 10 }: SubscribeToFeedBlocksRequest\n) =>\n new Stream<SubscribeToFeedBlocksResponse>(({ next }) => {\n if (!feedKey) {\n return;\n }\n const subscriptions = new EventSubscriptions();\n\n const timeout = setTimeout(async () => {\n const feed = feedStore.getFeed(feedKey);\n if (!feed) {\n return;\n }\n\n const update = async () => {\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 next({\n blocks: blocks.slice(-maxBlocks)\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// Copyright 2020 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { Keyring } from '@dxos/keyring';\nimport { SubscribeToKeyringKeysResponse } from '@dxos/protocols/proto/dxos/devtools/host';\n\nexport const subscribeToKeyringKeys = ({ keyring }: { keyring: Keyring }) =>\n new Stream<SubscribeToKeyringKeysResponse>(({ next }) => {\n const update = () => {\n next({\n keys: keyring.list()\n });\n };\n const unsubscribe = keyring.keysUpdate.on(update);\n update();\n return unsubscribe;\n });\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { PublicKey } from '@dxos/keys';\nimport { CommandTrace } from '@dxos/messaging';\nimport { NetworkManager } from '@dxos/network-manager';\nimport {\n GetNetworkPeersRequest,\n GetNetworkPeersResponse,\n SubscribeToNetworkTopicsResponse,\n SubscribeToSignalStatusResponse,\n SubscribeToSignalTraceResponse,\n SubscribeToSwarmInfoResponse\n} from '@dxos/protocols/proto/dxos/devtools/host';\n\nexport const subscribeToNetworkStatus = ({ networkManager }: { networkManager: NetworkManager }) =>\n new Stream<SubscribeToSignalStatusResponse>(({ next, close }) => {\n const update = () => {\n try {\n const status = networkManager.signalManager.getStatus();\n next({ servers: status });\n } catch (err: any) {\n close(err);\n }\n };\n\n networkManager.signalManager.statusChanged.on(update);\n update();\n });\n\nexport const subscribeToSignalTrace = ({ networkManager }: { networkManager: NetworkManager }) =>\n new Stream<SubscribeToSignalTraceResponse>(({ next }) => {\n next({ events: [] });\n const trace: CommandTrace[] = [];\n networkManager.signalManager.commandTrace.on((msg) => {\n trace.push(msg);\n next({ events: trace.map((msg) => JSON.stringify(msg)) });\n });\n });\n\nexport const subscribeToNetworkTopics = ({ networkManager }: { networkManager: NetworkManager }) =>\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: NetworkManager }) =>\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: NetworkManager },\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';\nimport { Space } from '@dxos/echo-db';\nimport { SubscribeToSpacesRequest, SubscribeToSpacesResponse } from '@dxos/protocols/proto/dxos/devtools/host';\nimport { SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\n\nimport { ServiceContext } from '../services';\n\nexport const subscribeToSpaces = (context: ServiceContext, { spaceKeys = [] }: SubscribeToSpacesRequest) =>\n 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) => {\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?.latestTimeframe,\n genesisFeed: space.genesisFeedKey,\n controlFeed: space.controlFeedKey,\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// Copyright 2022 DXOS.org\n//\n\nimport { Event, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { verifyCredential, CredentialSigner } from '@dxos/credentials';\nimport { AuthProvider, AuthVerifier } from '@dxos/echo-db';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols';\nimport { ComplexSet } from '@dxos/util';\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 schema.getCodecForType('dxos.halo.credentials.Credential').encode(credential);\n };\n\nexport type TrustedKeySetAuthVerifierParams = {\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: TrustedKeySetAuthVerifierParams) {}\n\n async close() {\n await this._ctx.dispose();\n }\n\n private _isTrustedKey(deviceKey: PublicKey) {\n const deviceSet = this._params.trustedKeysProvider();\n return deviceSet.has(deviceKey);\n }\n\n get verifier(): AuthVerifier {\n return async (nonce, auth) => {\n const credential = schema.getCodecForType('dxos.halo.credentials.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 not currently in trusted set, waiting...', { key: credential.issuer });\n return true;\n }\n\n const trigger = new Trigger<boolean>();\n this._ctx.onDispose(() => {\n trigger.wake(false);\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...', { key: credential.issuer });\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", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Event } from '@dxos/async';\nimport {\n DeviceStateMachine,\n CredentialSigner,\n createCredentialSignerWithKey,\n createCredentialSignerWithChain,\n ProfileStateMachine,\n CredentialConsumer\n} from '@dxos/credentials';\nimport { Signer } from '@dxos/crypto';\nimport { Space } from '@dxos/echo-db';\nimport { writeMessages } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { TypedMessage } from '@dxos/protocols';\nimport { AdmittedFeed, ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { HaloAdmissionCredentials } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { ComplexSet } from '@dxos/util';\n\nimport { TrustedKeySetAuthVerifier } from './authenticator';\n\n/**\n * Timeout for the device to be added to the trusted set during auth.\n */\nconst AUTH_TIMEOUT = 30000;\n\nexport type IdentityParams = {\n identityKey: PublicKey;\n deviceKey: PublicKey;\n signer: Signer;\n space: Space;\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 _deviceStateMachine: CredentialConsumer<DeviceStateMachine>;\n private readonly _profileStateMachine: CredentialConsumer<ProfileStateMachine>;\n public readonly authVerifier: TrustedKeySetAuthVerifier;\n\n public readonly identityKey: PublicKey;\n public readonly deviceKey: PublicKey;\n\n public readonly stateUpdate = new Event();\n\n constructor({ space, signer, identityKey, deviceKey }: IdentityParams) {\n this.space = space;\n this._signer = signer;\n\n this.identityKey = identityKey;\n this.deviceKey = deviceKey;\n\n this._deviceStateMachine = this.space.spaceState.registerProcessor(\n new DeviceStateMachine({\n identityKey: this.identityKey,\n deviceKey: this.deviceKey,\n onUpdate: () => this.stateUpdate.emit()\n })\n );\n this._profileStateMachine = this.space.spaceState.registerProcessor(\n new ProfileStateMachine({\n identityKey: this.identityKey,\n onUpdate: () => this.stateUpdate.emit()\n })\n );\n\n this.authVerifier = new TrustedKeySetAuthVerifier({\n trustedKeysProvider: () => this.authorizedDeviceKeys,\n update: this.stateUpdate,\n authTimeout: AUTH_TIMEOUT\n });\n }\n\n // TODO(burdon): Expose state object?\n get authorizedDeviceKeys(): ComplexSet<PublicKey> {\n return this._deviceStateMachine.processor.authorizedDeviceKeys;\n }\n\n async open() {\n await this._deviceStateMachine.open();\n await this._profileStateMachine.open();\n await this.space.open();\n }\n\n async close() {\n await this.authVerifier.close();\n await this._deviceStateMachine.close();\n await this._profileStateMachine.close();\n await this.space.close();\n }\n\n async ready() {\n await this._deviceStateMachine.processor.deviceChainReady.wait();\n\n // TODO(dmaretskyi): Should we also wait for our feeds to be admitted?\n }\n\n get profileDocument(): ProfileDocument | undefined {\n return this._profileStateMachine.processor.profile;\n }\n\n /**\n * @test-only\n */\n get controlPipeline() {\n return this.space.controlPipeline;\n }\n\n get haloSpaceKey() {\n return this.space.key;\n }\n\n get haloGenesisFeedKey() {\n return this.space.genesisFeedKey;\n }\n\n getAdmissionCredentials(): HaloAdmissionCredentials {\n return {\n deviceKey: this.deviceKey,\n controlFeedKey: this.space.controlFeedKey,\n dataFeedKey: this.space.dataFeedKey\n };\n }\n\n /**\n * Issues credentials as identity.\n * Requires identity to be ready.\n */\n getIdentityCredentialSigner(): CredentialSigner {\n assert(this._deviceStateMachine.processor.deviceCredentialChain, 'Device credential chain is not ready.');\n return createCredentialSignerWithChain(\n this._signer,\n this._deviceStateMachine.processor.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 }: HaloAdmissionCredentials) {\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 await writeMessages(\n this.controlPipeline.writer,\n [\n await signer.createCredential({\n subject: deviceKey,\n assertion: {\n '@type': 'dxos.halo.credentials.AuthorizedDevice',\n identityKey: this.identityKey,\n deviceKey\n }\n }),\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): TypedMessage => ({ '@type': 'dxos.echo.feed.CredentialsMessage', credential }))\n );\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Event } from '@dxos/async';\nimport { createCredentialSignerWithKey, CredentialGenerator } from '@dxos/credentials';\nimport { MetadataStore, SpaceManager, SwarmIdentity } from '@dxos/echo-db';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { AdmittedFeed, IdentityRecord, SpaceRecord } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { deferFunction } from '@dxos/util';\n\nimport { Identity } from '../identity';\nimport { createAuthProvider } from './authenticator';\n\ninterface ConstructSpaceParams {\n spaceRecord: SpaceRecord;\n swarmIdentity: SwarmIdentity;\n identityKey: PublicKey;\n}\n\nexport type JoinIdentityParams = {\n identityKey: PublicKey;\n haloSpaceKey: PublicKey;\n haloGenesisFeedKey: PublicKey;\n};\n\nexport type CreateIdentityOptions = {\n displayName?: string;\n};\n\n// TODO(dmaretskyi): Rename: represents the peer's state machine.\nexport class IdentityManager {\n readonly stateUpdate = new Event();\n\n private _identity?: Identity;\n\n // TODO(burdon): IdentityManagerParams.\n // TODO(dmaretskyi): Perhaps this should take/generate the peerKey outside of an initialized identity.\n constructor(\n private readonly _metadataStore: MetadataStore,\n private readonly _keyring: Keyring,\n private readonly _spaceManager: SpaceManager\n ) {}\n\n get identity() {\n return this._identity;\n }\n\n async open() {\n await this._metadataStore.load();\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();\n await this._identity.ready();\n this.stateUpdate.emit();\n }\n }\n\n async close() {\n await this._identity?.close();\n }\n\n async createIdentity({ displayName }: CreateIdentityOptions = {}) {\n assert(!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 spaceKey: await this._keyring.createKey(),\n genesisFeedKey: controlFeedKey,\n writeControlFeedKey: controlFeedKey,\n writeDataFeedKey: await this._keyring.createKey()\n }\n };\n\n const identity = await this._constructIdentity(identityRecord);\n await identity.open();\n\n {\n const generator = new CredentialGenerator(this._keyring, identityRecord.identityKey, identityRecord.deviceKey);\n const credentials = [\n // Space genesis.\n ...(await generator.createSpaceGenesis(\n identityRecord.haloSpace.spaceKey,\n identityRecord.haloSpace.genesisFeedKey\n )),\n\n // Feed admission.\n await generator.createFeedAdmission(\n identityRecord.haloSpace.spaceKey,\n identityRecord.haloSpace.writeDataFeedKey,\n AdmittedFeed.Designation.DATA\n )\n ];\n\n if (displayName) {\n credentials.push(await generator.createProfileCredential({ displayName }));\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 for (const credential of credentials) {\n await identity.controlPipeline.writer.write({\n '@type': 'dxos.echo.feed.CredentialsMessage',\n credential\n });\n }\n }\n\n // TODO(burdon): ???\n // await this._keyring.deleteKey(identityRecord.identity_key);\n // await this._keyring.deleteKey(identityRecord.halo_space.space_key);\n\n await this._metadataStore.setIdentityRecord(identityRecord);\n this._identity = identity;\n await this._identity.ready();\n this.stateUpdate.emit();\n\n log('created identity', { identityKey: identity.identityKey, deviceKey: identity.deviceKey });\n return identity;\n }\n\n /**\n * Accept an existing identity. Expects it's device key to be authorized (now or later).\n */\n async acceptIdentity(params: JoinIdentityParams) {\n log('accepting identity', { params });\n assert(!this._identity, 'Identity already exists.');\n\n const identityRecord: IdentityRecord = {\n identityKey: params.identityKey,\n deviceKey: await this._keyring.createKey(),\n haloSpace: {\n spaceKey: params.haloSpaceKey,\n genesisFeedKey: params.haloGenesisFeedKey,\n writeControlFeedKey: await this._keyring.createKey(),\n writeDataFeedKey: await this._keyring.createKey()\n }\n };\n const identity = await this._constructIdentity(identityRecord);\n\n await identity.open();\n this._identity = identity;\n await this._metadataStore.setIdentityRecord(identityRecord);\n this.stateUpdate.emit();\n return identity;\n }\n\n private async _constructIdentity(identityRecord: IdentityRecord) {\n assert(!this._identity);\n log('constructing identity', { identityRecord });\n\n const space = await this._constructSpace({\n spaceRecord: identityRecord.haloSpace,\n swarmIdentity: {\n peerKey: identityRecord.deviceKey,\n credentialProvider: createAuthProvider(createCredentialSignerWithKey(this._keyring, identityRecord.deviceKey)),\n credentialAuthenticator: deferFunction(() => identity.authVerifier.verifier)\n },\n identityKey: identityRecord.identityKey\n });\n const identity: Identity = new Identity({\n space,\n signer: this._keyring,\n identityKey: identityRecord.identityKey,\n deviceKey: identityRecord.deviceKey\n });\n log('done', { identityKey: identityRecord.identityKey });\n\n return identity;\n }\n\n private async _constructSpace({ spaceRecord, swarmIdentity, identityKey }: ConstructSpaceParams) {\n return this._spaceManager.constructSpace({\n metadata: {\n key: spaceRecord.spaceKey,\n genesisFeedKey: spaceRecord.genesisFeedKey,\n controlFeedKey: spaceRecord.writeControlFeedKey,\n dataFeedKey: spaceRecord.writeDataFeedKey\n },\n swarmIdentity,\n onNetworkConnection: () => {}\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport base from 'base-x';\n\nimport { schema } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\n// Encode with URL-safe alpha-numeric characters.\nconst base62 = base('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');\n\nconst codec = schema.getCodecForType('dxos.client.services.Invitation');\n\n/**\n * Encodes and decodes an invitation proto into/from alphanumeric chars.\n */\nexport class InvitationEncoder {\n static decode(text: string): Invitation {\n return codec.decode(base62.decode(text));\n }\n\n static encode(invitation: Invitation): string {\n return base62.encode(codec.encode(invitation));\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { scheduleTask, sleep, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { generatePasscode } from '@dxos/credentials';\nimport { failUndefined } from '@dxos/debug';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { createTeleportProtocolFactory, NetworkManager, StarTopology } from '@dxos/network-manager';\nimport { schema } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport {\n AuthenticationRequest,\n AuthenticationResponse,\n HaloAdmissionCredentials,\n HaloAdmissionOffer,\n HaloHostService\n} from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport { IdentityManager } from '../identity';\nimport {\n AuthenticatingInvitationProvider,\n AUTHENTICATION_CODE_LENGTH,\n CancellableInvitationObservable,\n InvitationObservableProvider,\n INVITATION_TIMEOUT,\n ON_CLOSE_DELAY\n} from './invitations';\nimport { AbstractInvitationsHandler, InvitationsOptions } from './invitations-handler';\n\n/**\n * Handles the life-cycle of Halo invitations between peers.\n */\n// TODO(dmaretskyi): Split into Host and Guest parts.\nexport class HaloInvitationsHandler extends AbstractInvitationsHandler {\n // prettier-ignore\n constructor(\n networkManager: NetworkManager,\n private readonly _identityManager: IdentityManager\n ) {\n super(networkManager);\n }\n\n /**\n * Creates an invitation and listens for a join request from the invited (guest) peer.\n */\n createInvitation(context: void, options?: InvitationsOptions): CancellableInvitationObservable {\n const { type, timeout = INVITATION_TIMEOUT, swarmKey } = options ?? {};\n assert(type !== Invitation.Type.OFFLINE);\n const identity = this._identityManager.identity ?? failUndefined();\n\n // TODO(dmaretskyi): Add invitation kind: halo/space.\n const invitation: Invitation = {\n type,\n invitationId: PublicKey.random().toHex(),\n swarmKey: swarmKey ?? PublicKey.random(),\n authenticationCode: generatePasscode(AUTHENTICATION_CODE_LENGTH)\n };\n\n const ctx = new Context({\n onError: (err) => {\n void ctx.dispose();\n observable.callback.onError(err);\n }\n });\n\n // TODO(burdon): Stop anything pending.\n const observable = new InvitationObservableProvider(async () => {\n await ctx.dispose();\n });\n\n let authenticationCode: string;\n const complete = new Trigger<PublicKey>();\n\n // Called for every connecting peer.\n const createExtension = (): HostHaloInvitationExtension => {\n const hostInvitationExtension = new HostHaloInvitationExtension({\n requestAdmission: async () => {\n log('responding with admission offer', {\n host: identity.deviceKey\n });\n\n // TODO(burdon): Is this the right place to set this state?\n observable.callback.onAuthenticating?.(invitation);\n return {\n identityKey: identity.identityKey,\n haloSpaceKey: identity.haloSpaceKey,\n genesisFeedKey: identity.haloGenesisFeedKey\n };\n },\n\n authenticate: async ({ authenticationCode: code }) => {\n log('received authentication request', { authenticationCode: code });\n authenticationCode = code;\n return { status: AuthenticationResponse.Status.OK };\n },\n\n // TODO(burdon): Not used: controlFeedKey, dataFeedKey.\n presentAdmissionCredentials: async (credentials) => {\n try {\n // Check authenticated.\n if (invitation.type !== Invitation.Type.INTERACTIVE_TESTING) {\n if (invitation.authenticationCode === undefined || invitation.authenticationCode !== authenticationCode) {\n throw new Error(`invalid authentication code: ${authenticationCode}`);\n }\n }\n\n log('writing guest credentials', { host: identity.deviceKey, guest: credentials.deviceKey });\n // TODO(burdon): Check if already admitted.\n await identity.admitDevice(credentials);\n\n // Updating credentials complete.\n complete.wake(credentials.deviceKey);\n } catch (err) {\n // TODO(burdon): Generic RPC callback to report error to client.\n observable.callback.onError(err);\n throw err; // Propagate error to guest.\n }\n },\n\n onOpen: () => {\n scheduleTask(ctx, async () => {\n try {\n log('connected', { host: identity.deviceKey });\n observable.callback.onConnected?.(invitation);\n const deviceKey = await complete.wait({ timeout });\n log('admitted guest', { host: identity.deviceKey, guest: deviceKey });\n observable.callback.onSuccess(invitation);\n } catch (err) {\n if (!observable.cancelled) {\n log.error('failed', err);\n observable.callback.onError(err);\n }\n } finally {\n // NOTE: If we close immediately after `complete` trigger finishes, Guest won't receive the reply to the last RPC.\n // TODO(dmaretskyi): Implement a soft-close which waits for the last connection to terminate before closing.\n await sleep(ON_CLOSE_DELAY);\n await ctx.dispose();\n }\n });\n }\n });\n return hostInvitationExtension;\n };\n\n scheduleTask(ctx, async () => {\n const topic = invitation.swarmKey!;\n const swarmConnection = await this._networkManager.joinSwarm({\n topic,\n peerId: topic,\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', createExtension());\n }),\n topology: new StarTopology(topic)\n });\n ctx.onDispose(() => swarmConnection.close());\n\n observable.callback.onConnecting?.(invitation);\n });\n\n return observable;\n }\n\n /**\n * Waits for the host peer (inviter) to accept our join request.\n * The local guest peer (invitee) then sends the local halo invitation to the host,\n * which then writes the guest's credentials to the halo.\n */\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationProvider {\n const { timeout = INVITATION_TIMEOUT } = options ?? {};\n\n const ctx = new Context({\n onError: (err) => {\n void ctx.dispose();\n observable.callback.onError(err);\n }\n });\n\n const authenticated = new Trigger<string>();\n const observable = new AuthenticatingInvitationProvider({\n onCancel: async () => {\n await ctx.dispose();\n },\n\n // TODO(burdon): Consider retry.\n onAuthenticate: async (code: string) => {\n authenticated.wake(code);\n }\n });\n\n let connectionCount = 0;\n const complete = new Trigger<PublicKey>();\n\n const createExtension = (): GuestHaloInvitationExtension => {\n const extension = new GuestHaloInvitationExtension({\n onOpen: () => {\n scheduleTask(ctx, async () => {\n try {\n // TODO(burdon): Bug where guest may create multiple connections.\n if (++connectionCount > 1) {\n throw new Error(`multiple connections detected: ${connectionCount}`);\n }\n\n log('connected');\n observable.callback.onConnected?.(invitation);\n\n // 1. Send request.\n log('sending admission request');\n const { identityKey, haloSpaceKey, genesisFeedKey } =\n await extension.rpc.HaloHostService.requestAdmission();\n\n // 2. Get authentication code.\n // TODO(burdon): Test timeout (options for timeouts at different steps).\n if (invitation.type === undefined || invitation.type === Invitation.Type.INTERACTIVE) {\n log('guest waiting for authentication code...');\n observable.callback.onAuthenticating?.(invitation);\n const authenticationCode = await authenticated.wait({ timeout });\n log('sending authentication request');\n await extension.rpc.HaloHostService.authenticate({ authenticationCode });\n }\n\n // 3. Create local identity.\n // TODO(burdon): Abandon if does not complete (otherwise retry will fail).\n const identity = await this._identityManager.acceptIdentity({\n identityKey,\n haloSpaceKey,\n haloGenesisFeedKey: genesisFeedKey\n });\n\n // 4. Send admission credentials to host (with local identity keys).\n log('presenting admission credentials', { guest: identity.deviceKey, identityKey });\n await extension.rpc.HaloHostService.presentAdmissionCredentials(identity.getAdmissionCredentials());\n\n // 5. Success.\n log('admitted by host', { guest: identity.deviceKey, identityKey });\n complete.wake(identityKey);\n } catch (err) {\n if (!observable.cancelled) {\n log.warn('auth failed', err);\n observable.callback.onError(err);\n }\n } finally {\n await ctx.dispose();\n }\n });\n }\n });\n return extension;\n };\n\n scheduleTask(ctx, async () => {\n assert(invitation.swarmKey);\n const topic = invitation.swarmKey;\n const swarmConnection = await this._networkManager.joinSwarm({\n topic,\n peerId: PublicKey.random(),\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', createExtension());\n }),\n topology: new StarTopology(topic)\n });\n ctx.onDispose(() => swarmConnection.close());\n\n observable.callback.onConnecting?.(invitation);\n invitation.identityKey = await complete.wait();\n observable.callback.onSuccess(invitation);\n await ctx.dispose();\n });\n\n return observable;\n }\n}\n\ntype HostHaloInvitationExtensionCallbacks = {\n requestAdmission: () => Promise<HaloAdmissionOffer>;\n authenticate: (request: AuthenticationRequest) => Promise<AuthenticationResponse>;\n presentAdmissionCredentials: (request: HaloAdmissionCredentials) => Promise<void>;\n // Deliberately not async to not block the extensions opening.\n onOpen: () => void;\n};\n\n/**\n * Host's side for a connection to a concrete peer in p2p network during invitation.\n */\nclass HostHaloInvitationExtension extends RpcExtension<{}, { HaloHostService: HaloHostService }> {\n constructor(private readonly _callbacks: HostHaloInvitationExtensionCallbacks) {\n super({\n exposed: {\n HaloHostService: schema.getService('dxos.halo.invitations.HaloHostService')\n }\n });\n }\n\n protected override async getHandlers(): Promise<{ HaloHostService: HaloHostService }> {\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 HaloHostService: {\n requestAdmission: async () => {\n return this._callbacks.requestAdmission();\n },\n\n authenticate: async (credentials) => {\n return this._callbacks.authenticate(credentials);\n },\n\n // TODO(burdon): Not used: controlFeedKey, dataFeedKey.\n presentAdmissionCredentials: async (credentials) => {\n return this._callbacks.presentAdmissionCredentials(credentials);\n }\n }\n };\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n this._callbacks.onOpen();\n }\n}\n\ntype GuestHaloInvitationExtensionCallbacks = {\n // Deliberately not async to not block the extensions opening.\n onOpen: () => void;\n};\n\n/**\n * Guest's side for a connection to a concrete peer in p2p network during invitation.\n */\nclass GuestHaloInvitationExtension extends RpcExtension<{ HaloHostService: HaloHostService }, {}> {\n constructor(private readonly _callbacks: GuestHaloInvitationExtensionCallbacks) {\n super({\n requested: {\n HaloHostService: schema.getService('dxos.halo.invitations.HaloHostService')\n }\n });\n }\n\n protected override async getHandlers() {\n return {};\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n this._callbacks.onOpen();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport {\n AsyncEvents,\n CancellableObservable,\n CancellableObservableEvents,\n CancellableObservableProvider\n} from '@dxos/async';\nimport type { Stream } from '@dxos/codec-protobuf';\nimport { AuthenticationRequest, CancelInvitationRequest, Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nexport const AUTHENTICATION_CODE_LENGTH = 6;\n\nexport const INVITATION_TIMEOUT = 3 * 60_000; // 3 mins.\n\n// TODO(burdon): Don't close until RPC has complete (bug).\nexport const ON_CLOSE_DELAY = 500;\n\nexport interface InvitationsService {\n createInvitation(invitation: Invitation): Stream<Invitation>;\n authenticate(request: AuthenticationRequest): Promise<void>;\n acceptInvitation(invitation: Invitation): Stream<Invitation>;\n cancelInvitation(request: CancelInvitationRequest): Promise<void>;\n}\n\n/**\n * Common invitation events (callbacks) for creating and accepting invitations.\n */\n// TODO(burdon): Remove optionals.\nexport interface InvitationEvents extends AsyncEvents, CancellableObservableEvents {\n onConnecting?(invitation: Invitation): void;\n onConnected?(invitation: Invitation): void;\n onAuthenticating?(invitation: Invitation): void;\n onSuccess(invitation: Invitation): void; // TODO(burdon): Collides with AsyncEvents.\n}\n\n/**\n * Base class for all invitation observables and providers.\n * Observable that supports inspection of the current value.\n */\nexport interface CancellableInvitationObservable extends CancellableObservable<InvitationEvents> {\n get invitation(): Invitation | undefined;\n}\n\nexport class InvitationObservableProvider\n extends CancellableObservableProvider<InvitationEvents>\n implements CancellableInvitationObservable\n{\n private _invitation?: Invitation;\n\n get invitation(): Invitation | undefined {\n return this._invitation;\n }\n\n setInvitation(invitation: Invitation) {\n this._invitation = invitation;\n }\n}\n\n/**\n * Cancelable observer that relays authentication requests.\n */\nexport interface AuthenticatingInvitationObservable extends CancellableInvitationObservable {\n authenticate(code: string): Promise<void>;\n}\n\nexport interface AuthenticatingInvitationProviderActions {\n onCancel(): Promise<void>;\n onAuthenticate(code: string): Promise<void>;\n}\n\nexport class AuthenticatingInvitationProvider\n extends InvitationObservableProvider\n implements AuthenticatingInvitationObservable\n{\n // prettier-ignore\n constructor(\n private readonly _actions: AuthenticatingInvitationProviderActions\n ) {\n super(() => this._actions.onCancel());\n }\n\n async authenticate(authenticationCode: string): Promise<void> {\n return this._actions.onAuthenticate(authenticationCode);\n }\n}\n\n/**\n * Testing util to wrap non-authenticating observable with promise.\n * Don't use this in production code.\n * @deprecated\n */\n// TODO(burdon): Throw error if auth requested.\nexport const wrapObservable = async (observable: CancellableInvitationObservable): Promise<Invitation> => {\n return new Promise((resolve, reject) => {\n const unsubscribe = observable.subscribe({\n onSuccess: (invitation: Invitation) => {\n assert(invitation.state === Invitation.State.SUCCESS);\n unsubscribe();\n resolve(invitation);\n },\n onError: (err: Error) => {\n unsubscribe();\n reject(err);\n }\n });\n });\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { PublicKey } from '@dxos/keys';\nimport { NetworkManager } from '@dxos/network-manager';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { AuthenticatingInvitationObservable, CancellableInvitationObservable } from './invitations';\n\nexport type InvitationsOptions = {\n type?: Invitation.Type;\n timeout?: number;\n // Used for debugging.\n swarmKey?: PublicKey;\n};\n\n/**\n * Common interface for Halo and Space invitation proxies and handlers.\n * Handles the life-cycle of Space 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 admission request.\n * - Wait for guest to authenticate with OTP.\n * - Waits for guest to present credentials (containing local device and feed keys).\n * - Writes credentials to control feed then exits.\n *\n * Guest\n * - Joins the swarm with the topic.\n * - Sends an admission request.\n * - Sends authentication OTP.\n * - If Space handler then creates a local cloned space (with genesis block).\n * - Sends admission credentials.\n *\n * TODO(burdon): Show proxy/service relationship and reference design doc/diagram.\n *\n * ```\n * [Guest] [Host]\n * |-----------------------------RequestAdmission-->|\n * |-------------------------------[Authenticate]-->|\n * |------------------PresentAdmissionCredentials-->|\n * ```\n */\nexport interface InvitationsHandler<T = void> {\n createInvitation(context: T, options?: InvitationsOptions): CancellableInvitationObservable;\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationObservable;\n}\n\n/**\n * Base class for Halo/Space invitations handlers.\n */\n// TODO(burdon): Extract common functionality.\nexport abstract class AbstractInvitationsHandler<T = void> implements InvitationsHandler<T> {\n // prettier-ignore\n protected constructor(\n protected readonly _networkManager: NetworkManager\n ) {}\n\n abstract createInvitation(context: T, options?: InvitationsOptions): CancellableInvitationObservable;\n abstract acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationObservable;\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { observableError } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { log } from '@dxos/log';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nimport {\n AuthenticatingInvitationObservable,\n AuthenticatingInvitationProvider,\n CancellableInvitationObservable,\n InvitationObservableProvider,\n InvitationsService\n} from './invitations';\nimport { InvitationsOptions, InvitationsHandler } from './invitations-handler';\n\n/**\n * Adapts invitations service observable to client/service stream.\n * Common base class for HALO and Spaces implementations.\n */\nexport interface InvitationsProxy<T = void> extends InvitationsHandler<T> {\n getInvitationOptions(context: T): Invitation;\n}\n\nexport abstract class AbstractInvitationsProxy<T = void> implements InvitationsProxy<T> {\n // prettier-ignore\n constructor(\n private readonly _invitationsService: InvitationsService\n ) {}\n\n abstract getInvitationOptions(context: T): Invitation;\n\n createInvitation(context: T, options?: InvitationsOptions): CancellableInvitationObservable {\n let invitationId: string;\n const observable = new InvitationObservableProvider(async () => {\n if (invitationId) {\n await this._invitationsService.cancelInvitation({ invitationId });\n }\n });\n\n const invitation: Invitation = { ...this.getInvitationOptions(context), ...options };\n const stream: Stream<Invitation> = this._invitationsService.createInvitation(invitation);\n\n stream.subscribe(\n (invitation: Invitation) => {\n observable.setInvitation(invitation);\n\n switch (invitation.state) {\n case Invitation.State.CONNECTING: {\n assert(invitation.invitationId);\n invitationId = invitation.invitationId;\n observable.callback.onConnecting?.(invitation);\n break;\n }\n\n case Invitation.State.CONNECTED: {\n observable.callback.onConnected?.(invitation);\n break;\n }\n\n case Invitation.State.AUTHENTICATING: {\n observable.callback.onAuthenticating?.(invitation);\n break;\n }\n\n case Invitation.State.SUCCESS: {\n observable.callback.onSuccess?.(invitation);\n break;\n }\n\n case Invitation.State.CANCELLED: {\n observable.callback.onCancelled?.();\n break;\n }\n\n default: {\n log.error(`Invalid state: ${invitation.state}`);\n }\n }\n },\n (err) => {\n if (err) {\n observableError(observable, err);\n }\n }\n );\n\n return observable;\n }\n\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationObservable {\n assert(invitation && invitation.swarmKey);\n\n const observable = new AuthenticatingInvitationProvider({\n onCancel: async () => {\n const invitationId = observable.invitation?.invitationId;\n assert(invitationId);\n await this._invitationsService.cancelInvitation({ invitationId });\n },\n\n onAuthenticate: async (authenticationCode: string) => {\n const invitationId = observable.invitation?.invitationId;\n assert(invitationId);\n await this._invitationsService.authenticate({ invitationId, authenticationCode });\n }\n });\n\n const stream: Stream<Invitation> = this._invitationsService.acceptInvitation({ ...invitation, ...options });\n\n stream.subscribe(\n (invitation: Invitation) => {\n assert(invitation.invitationId);\n observable.setInvitation(invitation);\n\n switch (invitation.state) {\n case Invitation.State.CONNECTING: {\n observable.callback.onConnecting?.(invitation);\n break;\n }\n\n case Invitation.State.CONNECTED: {\n observable.callback.onConnected?.(invitation);\n break;\n }\n\n case Invitation.State.AUTHENTICATING: {\n observable.callback.onAuthenticating?.(invitation);\n break;\n }\n\n case Invitation.State.SUCCESS: {\n observable.callback.onSuccess?.(invitation);\n break;\n }\n\n case Invitation.State.CANCELLED: {\n observable.callback.onCancelled?.();\n break;\n }\n\n default: {\n log.error(`Invalid state: ${invitation.state}`);\n }\n }\n },\n (err) => {\n if (err) {\n observableError(observable, err);\n }\n }\n );\n\n return observable;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { AbstractInvitationsProxy } from './invitations-proxy';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class HaloInvitationsProxy extends AbstractInvitationsProxy {\n getInvitationOptions() {\n return {};\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { TimeoutError } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { log } from '@dxos/log';\nimport { AuthenticationRequest, Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { Provider } from '@dxos/util';\n\nimport { IdentityManager } from '../identity';\nimport { AuthenticatingInvitationObservable, CancellableInvitationObservable, InvitationsService } from './invitations';\nimport { InvitationsHandler, InvitationsOptions } from './invitations-handler';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport abstract class AbstractInvitationsService<T = void> implements InvitationsService {\n private readonly _createInvitations = new Map<string, CancellableInvitationObservable>();\n private readonly _acceptInvitations = new Map<string, AuthenticatingInvitationObservable>();\n\n // prettier-ignore\n protected constructor (\n private readonly _identityManager: IdentityManager,\n private readonly _getInvitationsHandler: Provider<InvitationsHandler<T>>\n ) {}\n\n // TODO(burdon): Guest/host label.\n getLoggingContext() {\n return {\n deviceKey: this._identityManager.identity?.deviceKey\n };\n }\n\n abstract getContext(invitation: Invitation): T;\n\n createInvitation(invitation: Invitation): Stream<Invitation> {\n return new Stream<Invitation>(({ next, close }) => {\n const invitationsHandler: InvitationsHandler<T> = this._getInvitationsHandler();\n const context = this.getContext(invitation);\n log('stream opened', this.getLoggingContext());\n\n let invitationId: string;\n const { type, swarmKey } = invitation;\n const observable = invitationsHandler.createInvitation(context, { type, swarmKey });\n observable.subscribe({\n onConnecting: (invitation) => {\n assert(invitation.invitationId);\n invitationId = invitation.invitationId;\n this._createInvitations.set(invitation.invitationId, observable);\n invitation.state = Invitation.State.CONNECTING;\n next(invitation);\n },\n onConnected: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.CONNECTED;\n next(invitation);\n },\n onAuthenticating: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.AUTHENTICATING;\n next(invitation);\n },\n onSuccess: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.SUCCESS;\n next(invitation);\n close();\n },\n onCancelled: () => {\n assert(invitationId);\n invitation.invitationId = invitationId;\n invitation.state = Invitation.State.CANCELLED;\n next(invitation);\n close();\n },\n onTimeout: (err: TimeoutError) => {\n invitation.state = Invitation.State.TIMEOUT;\n close(err);\n },\n onError: (err: any) => {\n invitation.state = Invitation.State.ERROR;\n close(err);\n }\n });\n\n return (err?: Error) => {\n const context = this.getLoggingContext();\n if (err) {\n log.warn('stream closed', { ...context, err });\n } else {\n log('stream closed', context);\n }\n\n this._createInvitations.delete(invitation.invitationId!);\n };\n });\n }\n\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): Stream<Invitation> {\n return new Stream<Invitation>(({ next, close }) => {\n log('stream opened', this.getLoggingContext());\n const invitationsHandler = this._getInvitationsHandler();\n\n let invitationId: string;\n const observable = invitationsHandler.acceptInvitation(invitation, options);\n observable.subscribe({\n onConnecting: (invitation) => {\n assert(invitation.invitationId);\n invitationId = invitation.invitationId;\n this._acceptInvitations.set(invitation.invitationId, observable);\n invitation.state = Invitation.State.CONNECTING;\n next(invitation);\n },\n onConnected: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.CONNECTED;\n next(invitation);\n },\n onAuthenticating: (invitation) => {\n assert(invitation.invitationId);\n invitation.state = Invitation.State.AUTHENTICATING;\n next(invitation);\n },\n onSuccess: (invitation) => {\n invitation.state = Invitation.State.SUCCESS;\n next(invitation);\n close();\n },\n onCancelled: () => {\n assert(invitationId);\n invitation.invitationId = invitationId;\n invitation.state = Invitation.State.CANCELLED;\n next(invitation);\n close();\n },\n onTimeout: (err: TimeoutError) => {\n invitation.state = Invitation.State.TIMEOUT;\n close(err);\n },\n onError: (err: any) => {\n invitation.state = Invitation.State.ERROR;\n close(err);\n }\n });\n\n return (err?: Error) => {\n const context = this.getLoggingContext();\n if (err) {\n log.warn('stream closed', { ...context, err });\n } else {\n log('stream closed', context);\n }\n\n this._acceptInvitations.delete(invitation.invitationId!);\n };\n });\n }\n\n async authenticate({ invitationId, authenticationCode }: AuthenticationRequest): Promise<void> {\n log('authenticating...');\n assert(invitationId);\n const observable = this._acceptInvitations.get(invitationId);\n if (!observable) {\n log.warn('invalid invitation', { invitationId });\n } else {\n await observable.authenticate(authenticationCode);\n }\n }\n\n async cancelInvitation(invitation: Invitation): Promise<void> {\n log('cancelling...');\n assert(invitation.invitationId);\n const observable =\n this._createInvitations.get(invitation.invitationId) ?? this._acceptInvitations.get(invitation.invitationId);\n if (!observable) {\n log.warn('invalid invitation', { invitationId: invitation.invitationId });\n } else {\n await observable?.cancel();\n }\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { IdentityManager } from '../identity';\nimport { InvitationsHandler } from './invitations-handler';\nimport { AbstractInvitationsService } from './invitations-service';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class HaloInvitationsServiceImpl extends AbstractInvitationsService {\n // prettier-ignore\n constructor (\n identityManager: IdentityManager,\n private readonly invitationsHandler: InvitationsHandler\n ) {\n super(identityManager, () => invitationsHandler);\n }\n\n override getContext(invitation: Invitation) {}\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { scheduleTask, sleep, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { createAdmissionCredentials, generatePasscode, getCredentialAssertion } from '@dxos/credentials';\nimport { SigningContext } from '@dxos/echo-db';\nimport { writeMessages } from '@dxos/feed-store';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { createTeleportProtocolFactory, NetworkManager, StarTopology, SwarmConnection } from '@dxos/network-manager';\nimport { schema } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n AuthenticationRequest,\n AuthenticationResponse,\n Introduction,\n SpaceAdmissionCredentials,\n SpaceAdmissionRequest,\n SpaceHostService\n} from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport { DataSpace } from '../spaces/data-space';\nimport { DataSpaceManager } from '../spaces/data-space-manager';\nimport {\n AuthenticatingInvitationProvider,\n AUTHENTICATION_CODE_LENGTH,\n CancellableInvitationObservable,\n InvitationObservableProvider,\n INVITATION_TIMEOUT,\n ON_CLOSE_DELAY\n} from './invitations';\nimport { AbstractInvitationsHandler, InvitationsOptions } from './invitations-handler';\n\nconst MAX_OTP_ATTEMPTS = 3;\n\n/**\n * Handles the life-cycle of Space invitations between peers.\n */\n// TODO(dmaretskyi): Split into Host and Guest parts.\nexport class SpaceInvitationsHandler extends AbstractInvitationsHandler<DataSpace> {\n constructor(\n networkManager: NetworkManager,\n private readonly _spaceManager: DataSpaceManager,\n private readonly _signingContext: SigningContext,\n private readonly _keyring: Keyring\n ) {\n super(networkManager);\n }\n\n /**\n * Creates an invitation and listens for a join request from the invited (guest) peer.\n */\n createInvitation(space: DataSpace, options?: InvitationsOptions): CancellableInvitationObservable {\n let swarmConnection: SwarmConnection | undefined;\n const { type, timeout = INVITATION_TIMEOUT, swarmKey } = options ?? {};\n assert(type !== Invitation.Type.OFFLINE);\n assert(space);\n\n // TODO(dmaretskyi): Add invitation kind: halo/space.\n const invitation: Invitation = {\n type,\n invitationId: PublicKey.random().toHex(),\n swarmKey: swarmKey ?? PublicKey.random(),\n spaceKey: space.key,\n authenticationCode: generatePasscode(AUTHENTICATION_CODE_LENGTH)\n };\n\n const ctx = new Context({\n onError: (err) => {\n void ctx.dispose();\n observable.callback.onError(err);\n }\n });\n\n // TODO(burdon): Stop anything pending.\n const observable = new InvitationObservableProvider(async () => {\n await swarmConnection?.close();\n });\n\n let authenticationCode: string;\n let authenticationRetry = 0;\n\n // Called for every connecting peer.\n const createExtension = (): HostSpaceInvitationExtension => {\n const complete = new Trigger<PublicKey>();\n let guestProfile: ProfileDocument | undefined;\n\n const hostInvitationExtension = new HostSpaceInvitationExtension({\n introduce: async ({ profile }) => {\n log('guest introduced itself', {\n guestProfile: profile,\n host: this._signingContext.deviceKey,\n spaceKey: space.key\n });\n\n guestProfile = profile;\n\n // TODO(burdon): Is this the right place to set this state?\n // TODO(dmaretskyi): Should we expose guest's profile in this callback?\n observable.callback.onAuthenticating?.(invitation);\n },\n\n authenticate: async ({ authenticationCode: code }) => {\n log('received authentication request', { authenticationCode: code });\n let status = AuthenticationResponse.Status.OK;\n if (invitation.authenticationCode) {\n if (authenticationRetry++ > MAX_OTP_ATTEMPTS) {\n status = AuthenticationResponse.Status.INVALID_OPT_ATTEMPTS;\n } else if (code !== invitation.authenticationCode) {\n status = AuthenticationResponse.Status.INVALID_OTP;\n } else {\n authenticationCode = code;\n }\n }\n\n return { status };\n },\n\n requestAdmission: async ({ identityKey, deviceKey, controlFeedKey, dataFeedKey }) => {\n try {\n // Check authenticated.\n if (\n invitation.type !== Invitation.Type.INTERACTIVE_TESTING &&\n invitation.type !== Invitation.Type.MULTIUSE_TESTING\n ) {\n if (invitation.authenticationCode === undefined || invitation.authenticationCode !== authenticationCode) {\n throw new Error(`invalid authentication code: ${authenticationCode}`);\n }\n }\n\n log('writing guest credentials', { host: this._signingContext.deviceKey, guest: deviceKey });\n // TODO(burdon): Check if already admitted.\n const credentials = await createAdmissionCredentials(\n this._signingContext.credentialSigner,\n identityKey,\n deviceKey,\n space.key,\n controlFeedKey,\n dataFeedKey,\n space.inner.genesisFeedKey,\n guestProfile\n );\n\n // TODO(dmaretskyi): Refactor.\n assert(credentials[0]['@type'] === 'dxos.echo.feed.CredentialsMessage');\n const spaceMemberCredential = credentials[0].credential;\n assert(getCredentialAssertion(spaceMemberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember');\n\n await writeMessages(space.inner.controlPipeline.writer, credentials);\n\n // Updating credentials complete.\n complete.wake(deviceKey);\n\n return { credential: spaceMemberCredential };\n } catch (err) {\n // TODO(burdon): Generic RPC callback to report error to client.\n observable.callback.onError(err);\n throw err; // Propagate error to guest.\n }\n },\n\n onOpen: () => {\n scheduleTask(ctx, async () => {\n try {\n log('connected', { host: this._signingContext.deviceKey });\n observable.callback.onConnected?.(invitation);\n const deviceKey = await complete.wait({ timeout });\n log('admitted guest', { host: this._signingContext.deviceKey, guest: deviceKey });\n observable.callback.onSuccess(invitation);\n } catch (err) {\n if (!observable.cancelled) {\n log.error('failed', err);\n observable.callback.onError(err);\n }\n } finally {\n if (type !== Invitation.Type.MULTIUSE_TESTING) {\n await sleep(ON_CLOSE_DELAY);\n await ctx.dispose();\n }\n }\n });\n }\n });\n return hostInvitationExtension;\n };\n\n scheduleTask(ctx, async () => {\n const topic = invitation.swarmKey!;\n const swarmConnection = await this._networkManager.joinSwarm({\n topic,\n peerId: topic,\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', createExtension());\n }),\n topology: new StarTopology(topic)\n });\n ctx.onDispose(() => swarmConnection.close());\n\n observable.callback.onConnecting?.(invitation);\n });\n\n return observable;\n }\n\n /**\n * Waits for the host peer (inviter) to accept our join request.\n * The local guest peer (invitee) then sends the local space invitation to the host,\n * which then writes the guest's credentials to the space.\n */\n acceptInvitation(invitation: Invitation, options?: InvitationsOptions): AuthenticatingInvitationProvider {\n const { timeout = INVITATION_TIMEOUT } = options ?? {};\n\n const ctx = new Context({\n onError: (err) => {\n void ctx.dispose();\n observable.callback.onError(err);\n }\n });\n\n const authenticated = new Trigger<string>();\n const observable = new AuthenticatingInvitationProvider({\n onCancel: async () => {\n await ctx.dispose();\n },\n\n onAuthenticate: async (code: string) => {\n // TODO(burdon): Reset creates a race condition? Event?\n authenticated.wake(code);\n }\n });\n\n let connectionCount = 0;\n const complete = new Trigger();\n\n const createExtension = (): GuestSpaceInvitationExtension => {\n const extension = new GuestSpaceInvitationExtension({\n onOpen: () => {\n scheduleTask(ctx, async () => {\n try {\n // TODO(burdon): Bug where guest may create multiple connections.\n if (++connectionCount > 1) {\n throw new Error(`multiple connections detected: ${connectionCount}`);\n }\n\n log('connected', { guest: this._signingContext.deviceKey });\n observable.callback.onConnected?.(invitation);\n\n // 1. Introduce guest to host.\n log('introduce', { guest: this._signingContext.deviceKey });\n await extension.rpc.SpaceHostService.introduce({\n profile: this._signingContext.profile\n });\n\n // 2. Get authentication code.\n // TODO(burdon): Test timeout (options for timeouts at different steps).\n if (invitation.type === undefined || invitation.type === Invitation.Type.INTERACTIVE) {\n for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {\n log('guest waiting for authentication code...');\n observable.callback.onAuthenticating?.(invitation);\n const authenticationCode = await authenticated.wait({ timeout });\n\n log('sending authentication request');\n const response = await extension.rpc.SpaceHostService.authenticate({ authenticationCode });\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 // 3. Generate a pair of keys for our feeds.\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n\n // 4. Send admission credentials to host (with local space keys).\n log('request admission', { guest: this._signingContext.deviceKey });\n const { credential } = await extension.rpc.SpaceHostService.requestAdmission({\n identityKey: this._signingContext.identityKey,\n deviceKey: this._signingContext.deviceKey,\n controlFeedKey,\n dataFeedKey\n });\n\n // TODO(dmaretskyi): Record credential in our HALO.\n\n // 4. Create local space.\n const assertion = getCredentialAssertion(credential);\n assert(assertion['@type'] === 'dxos.halo.credentials.SpaceMember', 'Invalid credential');\n assert(credential.subject.id.equals(this._signingContext.identityKey));\n\n const space = await this._spaceManager.acceptSpace({\n spaceKey: assertion.spaceKey,\n genesisFeedKey: assertion.genesisFeedKey,\n controlFeedKey,\n dataFeedKey\n });\n\n // 5. Success.\n log('admitted by host', { guest: this._signingContext.deviceKey, spaceKey: space.key });\n complete.wake();\n } catch (err) {\n if (!observable.cancelled) {\n log.warn('auth failed', err);\n observable.callback.onError(err);\n }\n } finally {\n await ctx.dispose();\n }\n });\n }\n });\n return extension;\n };\n\n scheduleTask(ctx, async () => {\n assert(invitation.swarmKey);\n const topic = invitation.swarmKey;\n const swarmConnection = await this._networkManager.joinSwarm({\n topic,\n peerId: PublicKey.random(),\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', createExtension());\n }),\n topology: new StarTopology(topic)\n });\n ctx.onDispose(() => swarmConnection.close());\n\n observable.callback.onConnecting?.(invitation);\n await complete.wait();\n observable.callback.onSuccess(invitation);\n await ctx.dispose();\n });\n\n return observable;\n }\n}\n\ntype HostSpaceInvitationExtensionCallbacks = {\n // Deliberately not async to not block the extensions opening.\n onOpen: () => void;\n\n introduce: (introduction: Introduction) => Promise<void>;\n authenticate: (request: AuthenticationRequest) => Promise<AuthenticationResponse>;\n requestAdmission: (request: SpaceAdmissionRequest) => Promise<SpaceAdmissionCredentials>;\n};\n\n/**\n * Host's side for a connection to a concrete peer in p2p network during invitation.\n */\nclass HostSpaceInvitationExtension extends RpcExtension<{}, { SpaceHostService: SpaceHostService }> {\n constructor(private readonly _callbacks: HostSpaceInvitationExtensionCallbacks) {\n super({\n exposed: {\n SpaceHostService: schema.getService('dxos.halo.invitations.SpaceHostService')\n }\n });\n }\n\n protected override async getHandlers(): Promise<{ SpaceHostService: SpaceHostService }> {\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 SpaceHostService: {\n introduce: async (params) => {\n return this._callbacks.introduce(params);\n },\n\n authenticate: async (credentials) => {\n return this._callbacks.authenticate(credentials);\n },\n\n requestAdmission: async (credentials) => {\n return this._callbacks.requestAdmission(credentials);\n }\n }\n };\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n this._callbacks.onOpen();\n }\n}\n\ntype GuestSpaceInvitationExtensionCallbacks = {\n // Deliberately not async to not block the extensions opening.\n onOpen: () => void;\n};\n\n/**\n * Guest's side for a connection to a concrete peer in p2p network during invitation.\n */\nclass GuestSpaceInvitationExtension extends RpcExtension<{ SpaceHostService: SpaceHostService }, {}> {\n constructor(private readonly _callbacks: GuestSpaceInvitationExtensionCallbacks) {\n super({\n requested: {\n SpaceHostService: schema.getService('dxos.halo.invitations.SpaceHostService')\n }\n });\n }\n\n protected override async getHandlers() {\n return {};\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n this._callbacks.onOpen();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { PublicKey } from '@dxos/keys';\n\nimport { AbstractInvitationsProxy } from './invitations-proxy';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class SpaceInvitationsProxy extends AbstractInvitationsProxy<PublicKey> {\n getInvitationOptions(context: PublicKey) {\n return { spaceKey: context };\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { Provider } from '@dxos/util';\n\nimport { IdentityManager } from '../identity';\nimport { DataSpace } from '../spaces/data-space';\nimport { DataSpaceManager } from '../spaces/data-space-manager';\nimport { InvitationsHandler } from './invitations-handler';\nimport { AbstractInvitationsService } from './invitations-service';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class SpaceInvitationsServiceImpl extends AbstractInvitationsService<DataSpace> {\n // prettier-ignore\n constructor (\n identityManager: IdentityManager,\n private readonly invitationsHandler: Provider<InvitationsHandler<DataSpace>>,\n private readonly _getSpaceManager: Provider<DataSpaceManager>\n ) {\n super(identityManager, invitationsHandler);\n }\n\n override getContext(invitation: Invitation): DataSpace {\n assert(invitation.spaceKey);\n const spaceManager = this._getSpaceManager();\n const space = spaceManager.spaces.get(invitation.spaceKey!);\n assert(space);\n return space;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Trigger } from '@dxos/async';\nimport { failUndefined } from '@dxos/debug';\nimport {\n valueEncoding,\n DataServiceSubscriptions,\n MetadataStore,\n SpaceManager,\n SigningContext,\n SnapshotStore\n} from '@dxos/echo-db';\nimport { FeedFactory, FeedStore } from '@dxos/feed-store';\nimport { Keyring } from '@dxos/keyring';\nimport { log } from '@dxos/log';\nimport { ModelFactory } from '@dxos/model-factory';\nimport { NetworkManager } from '@dxos/network-manager';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { Storage } from '@dxos/random-access-storage';\n\nimport { CreateIdentityOptions, IdentityManager } from '../identity';\nimport { HaloInvitationsHandler, SpaceInvitationsHandler } from '../invitations';\nimport { DataSpaceManager } from '../spaces/data-space-manager';\n\n/**\n * Shared backend for all client services.\n */\n\n// TODO(burdon): Rename/break-up into smaller components. And/or make members private.\nexport class ServiceContext {\n public readonly initialized = new Trigger();\n public readonly dataServiceSubscriptions = new DataServiceSubscriptions();\n public readonly metadataStore: MetadataStore;\n public readonly snapshotStore: SnapshotStore;\n public readonly feedStore: FeedStore<FeedMessage>;\n public readonly keyring: Keyring;\n public readonly spaceManager: SpaceManager;\n public readonly identityManager: IdentityManager;\n public readonly haloInvitations: HaloInvitationsHandler;\n\n // Initialized after identity is initialized.\n public dataSpaceManager?: DataSpaceManager;\n public spaceInvitations?: SpaceInvitationsHandler;\n\n // prettier-ignore\n constructor(\n public readonly storage: Storage,\n public readonly networkManager: NetworkManager,\n public readonly modelFactory: ModelFactory\n ) {\n // TODO(burdon): Move strings to constants.\n this.metadataStore = new MetadataStore(storage.createDirectory('metadata'));\n this.snapshotStore = new SnapshotStore(storage.createDirectory('snapshots'));\n\n this.keyring = new Keyring(storage.createDirectory('keyring'));\n this.feedStore = new FeedStore<FeedMessage>({\n factory: new FeedFactory<FeedMessage>({\n root: storage.createDirectory('feeds'),\n signer: this.keyring,\n hypercore: {\n valueEncoding\n }\n })\n });\n this.spaceManager = new SpaceManager({\n feedStore: this.feedStore,\n networkManager: this.networkManager\n });\n this.identityManager = new IdentityManager(\n this.metadataStore,\n this.keyring,\n this.spaceManager\n );\n\n // TODO(burdon): _initialize called in multiple places.\n // TODO(burdon): Call _initialize on success.\n this.haloInvitations = new HaloInvitationsHandler(this.networkManager, this.identityManager);\n }\n\n async open() {\n log('opening...');\n await this.networkManager.open();\n await this.spaceManager.open();\n await this.identityManager.open();\n if (this.identityManager.identity) {\n await this._initialize();\n }\n log('opened');\n }\n\n async close() {\n log('closing...');\n await this.dataSpaceManager?.close();\n await this.identityManager.close();\n await this.spaceManager.close();\n await this.feedStore.close();\n await this.networkManager.close();\n this.dataServiceSubscriptions.clear();\n log('closed');\n }\n\n async reset() {\n log('resetting...');\n await this.close();\n await this.storage.reset();\n log('reset');\n }\n\n async createIdentity(params: CreateIdentityOptions = {}) {\n const identity = await this.identityManager.createIdentity(params);\n\n await this._initialize();\n return identity;\n }\n\n // Called when identity is created.\n private async _initialize() {\n log('initializing spaces...');\n const identity = this.identityManager.identity ?? failUndefined();\n const signingContext: SigningContext = {\n credentialSigner: identity.getIdentityCredentialSigner(),\n identityKey: identity.identityKey,\n deviceKey: identity.deviceKey,\n profile: identity.profileDocument\n };\n\n this.dataSpaceManager = new DataSpaceManager(\n this.spaceManager,\n this.metadataStore,\n this.dataServiceSubscriptions,\n this.keyring,\n signingContext,\n this.modelFactory,\n this.snapshotStore\n );\n await this.dataSpaceManager.open();\n this.spaceInvitations = new SpaceInvitationsHandler(\n this.networkManager,\n this.dataSpaceManager,\n signingContext,\n this.keyring\n );\n this.initialized.wake();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Event, synchronized, trackLeaks } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport {\n AcceptSpaceOptions,\n DataServiceSubscriptions,\n MetadataStore,\n SigningContext,\n SnapshotStore,\n Space,\n spaceGenesis,\n SpaceManager,\n SnapshotManager\n} from '@dxos/echo-db';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ModelFactory } from '@dxos/model-factory';\nimport { SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport { Presence } from '@dxos/teleport-extension-presence';\nimport { ComplexMap, deferFunction } from '@dxos/util';\n\nimport { createAuthProvider } from '../identity';\nimport { DataSpace } from './data-space';\n\n@trackLeaks('open', 'close')\nexport class DataSpaceManager {\n private readonly _ctx = new Context();\n\n public readonly updated = new Event();\n\n private readonly _spaces = new ComplexMap<PublicKey, DataSpace>(PublicKey.hash);\n\n constructor(\n private readonly _spaceManager: SpaceManager,\n private readonly _metadataStore: MetadataStore,\n private readonly _dataServiceSubscriptions: DataServiceSubscriptions,\n private readonly _keyring: Keyring,\n private readonly _signingContext: SigningContext,\n private readonly _modelFactory: ModelFactory,\n private readonly _snapshotStore: SnapshotStore\n ) {}\n\n // TODO(burdon): Remove.\n get spaces() {\n return this._spaces;\n }\n\n @synchronized\n async open() {\n await this._metadataStore.load();\n log('metadata loaded', { spaces: this._metadataStore.spaces.length });\n\n for (const spaceMetadata of this._metadataStore.spaces) {\n log('load space', { spaceMetadata });\n const space = await this._constructSpace(spaceMetadata);\n if (spaceMetadata.latestTimeframe) {\n log('waiting for latest timeframe', { spaceMetadata });\n await space.dataPipelineController.waitUntilTimeframe(spaceMetadata.latestTimeframe);\n }\n }\n }\n\n @synchronized\n async close() {\n await this._ctx.dispose();\n for (const space of this._spaces.values()) {\n await space.close();\n }\n }\n\n /**\n * Creates a new space writing the genesis credentials to the control feed.\n */\n @synchronized\n async createSpace() {\n const spaceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n const metadata: SpaceMetadata = {\n key: spaceKey,\n genesisFeedKey: controlFeedKey,\n controlFeedKey,\n dataFeedKey\n };\n\n log('creating space...', { spaceKey });\n const space = await this._constructSpace(metadata);\n\n await spaceGenesis(this._keyring, this._signingContext, space.inner);\n await this._metadataStore.addSpace(metadata);\n\n this.updated.emit();\n return space;\n }\n\n // TODO(burdon): Rename join space.\n @synchronized\n async acceptSpace(opts: AcceptSpaceOptions): Promise<DataSpace> {\n assert(!this._spaces.has(opts.spaceKey), 'Space already exists.');\n\n const metadata: SpaceMetadata = {\n key: opts.spaceKey,\n genesisFeedKey: opts.genesisFeedKey,\n controlFeedKey: opts.controlFeedKey,\n dataFeedKey: opts.dataFeedKey\n };\n\n const space = await this._constructSpace(metadata);\n await this._metadataStore.addSpace(metadata);\n this.updated.emit();\n return space;\n }\n\n private async _constructSpace(metadata: SpaceMetadata) {\n const presence = new Presence({\n localPeerId: this._signingContext.deviceKey,\n announceInterval: 1_000,\n offlineTimeout: 30_000,\n identityKey: this._signingContext.identityKey\n });\n const snapshotManager = new SnapshotManager(this._snapshotStore);\n\n const space: Space = await this._spaceManager.constructSpace({\n metadata,\n swarmIdentity: {\n peerKey: this._signingContext.deviceKey,\n credentialProvider: createAuthProvider(this._signingContext.credentialSigner),\n credentialAuthenticator: deferFunction(() => dataSpace.authVerifier.verifier)\n },\n onNetworkConnection: (session) => {\n session.addExtension(\n 'dxos.mesh.teleport.presence',\n presence.createExtension({ remotePeerId: session.remotePeerId })\n );\n session.addExtension('dxos.mesh.teleport.objectsync', snapshotManager.objectSync.createExtension());\n }\n });\n\n const dataSpace = new DataSpace({\n inner: space,\n modelFactory: this._modelFactory,\n metadataStore: this._metadataStore,\n snapshotManager,\n presence,\n memberKey: this._signingContext.identityKey,\n snapshotId: metadata.snapshot\n });\n\n await dataSpace.open();\n this._dataServiceSubscriptions.registerSpace(space.key, dataSpace.database.createDataServiceHost());\n this._spaces.set(metadata.key, dataSpace);\n return dataSpace;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { trackLeaks } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { Database, DataPipelineControllerImpl, ISpace, MetadataStore, Space, SnapshotManager } from '@dxos/echo-db';\nimport { PublicKey } from '@dxos/keys';\nimport { ModelFactory } from '@dxos/model-factory';\nimport { Presence } from '@dxos/teleport-extension-presence';\nimport { ComplexSet } from '@dxos/util';\n\nimport { TrustedKeySetAuthVerifier } from '../identity';\n\nconst AUTH_TIMEOUT = 30000;\n\nexport type DataSpaceParams = {\n inner: Space;\n modelFactory: ModelFactory;\n metadataStore: MetadataStore;\n snapshotManager: SnapshotManager;\n presence: Presence;\n memberKey: PublicKey;\n snapshotId?: string | undefined;\n};\n\n@trackLeaks('open', 'close')\nexport class DataSpace implements ISpace {\n private readonly _ctx = new Context();\n private readonly _dataPipelineController: DataPipelineControllerImpl;\n private readonly _inner: Space;\n private readonly _presence: Presence;\n public readonly authVerifier: TrustedKeySetAuthVerifier;\n\n constructor(params: DataSpaceParams) {\n this._inner = params.inner;\n this._presence = params.presence;\n this._dataPipelineController = new DataPipelineControllerImpl({\n modelFactory: params.modelFactory,\n metadataStore: params.metadataStore,\n snapshotManager: params.snapshotManager,\n memberKey: params.memberKey,\n spaceKey: this._inner.key,\n feedInfoProvider: (feedKey) => this._inner.spaceState.feeds.get(feedKey),\n snapshotId: params.snapshotId\n });\n this.authVerifier = new TrustedKeySetAuthVerifier({\n trustedKeysProvider: () => new ComplexSet(PublicKey.hash, Array.from(this._inner.spaceState.members.keys())),\n update: this._inner.stateUpdate,\n authTimeout: AUTH_TIMEOUT\n });\n }\n\n get key() {\n return this._inner.key;\n }\n\n get inner() {\n return this._inner;\n }\n\n get isOpen() {\n return this._inner.isOpen;\n }\n\n get dataPipelineController(): DataPipelineControllerImpl {\n return this._dataPipelineController;\n }\n\n get database(): Database {\n assert(this._dataPipelineController.database);\n return this._dataPipelineController.database;\n }\n\n get stateUpdate() {\n return this._inner.stateUpdate;\n }\n\n get presence() {\n return this._presence;\n }\n\n async open() {\n await this._inner.open();\n await this._inner.initDataPipeline(this._dataPipelineController);\n }\n\n async close() {\n await this._ctx.dispose();\n await this.authVerifier.close();\n await this._inner.close();\n await this._presence.destroy();\n }\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { schema } from '@dxos/protocols';\nimport { ProfileService, SystemService, SpaceService } from '@dxos/protocols/proto/dxos/client';\nimport {\n HaloInvitationsService,\n SpaceInvitationsService,\n SpacesService,\n DevicesService,\n NetworkService\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { DevtoolsHost, TracingService } from '@dxos/protocols/proto/dxos/devtools/host';\nimport { DataService } from '@dxos/protocols/proto/dxos/echo/service';\nimport { createServiceBundle, ServiceBundle } from '@dxos/rpc';\n\n//\n// NOTE: Should contain client/proxy dependencies only.\n//\n\nexport type ClientServices = {\n HaloInvitationsService: HaloInvitationsService;\n DevicesService: DevicesService;\n\n SpaceInvitationsService: SpaceInvitationsService;\n SpacesService: SpacesService;\n\n NetworkService: NetworkService;\n\n // TODO(burdon): Deprecated.\n SpaceService: SpaceService;\n DataService: DataService;\n ProfileService: ProfileService;\n SystemService: SystemService;\n DevtoolsHost: DevtoolsHost;\n TracingService: TracingService;\n};\n\n/**\n * Provide access to client services definitions and service handler.\n */\nexport interface ClientServicesProvider {\n descriptors: ServiceBundle<ClientServices>;\n services: ClientServices;\n\n open(): Promise<void>;\n close(): Promise<void>;\n}\n\n/**\n * Services supported by host.\n */\nexport const clientServiceBundle = createServiceBundle<ClientServices>({\n HaloInvitationsService: schema.getService('dxos.client.services.HaloInvitationsService'),\n DevicesService: schema.getService('dxos.client.services.DevicesService'),\n SpaceInvitationsService: schema.getService('dxos.client.services.SpaceInvitationsService'),\n SpacesService: schema.getService('dxos.client.services.SpacesService'),\n NetworkService: schema.getService('dxos.client.services.NetworkService'),\n\n // TODO(burdon): Deprecated.\n SpaceService: schema.getService('dxos.client.SpaceService'),\n DataService: schema.getService('dxos.echo.service.DataService'),\n ProfileService: schema.getService('dxos.client.ProfileService'),\n SystemService: schema.getService('dxos.client.SystemService'),\n DevtoolsHost: schema.getService('dxos.devtools.host.DevtoolsHost'),\n TracingService: schema.getService('dxos.devtools.host.TracingService')\n});\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { Config } from '@dxos/config';\nimport { raise } from '@dxos/debug';\nimport { DataServiceImpl } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\nimport { ModelFactory } from '@dxos/model-factory';\nimport { NetworkManager } from '@dxos/network-manager';\nimport { ObjectModel } from '@dxos/object-model';\nimport { Storage } from '@dxos/random-access-storage';\nimport { TextModel } from '@dxos/text-model';\n\nimport { SpaceServiceImpl, ProfileServiceImpl, SystemServiceImpl, TracingServiceImpl } from '../deprecated';\nimport { DevtoolsServiceImpl, DevtoolsHostEvents } from '../devtools';\nimport { DevicesServiceImpl } from '../identity/devices-service-impl';\nimport { HaloInvitationsServiceImpl, SpaceInvitationsServiceImpl } from '../invitations';\nimport { NetworkServiceImpl } from '../network';\nimport { SpacesServiceImpl } from '../spaces';\nimport { createStorageObjects } from '../storage';\nimport { ServiceContext } from './service-context';\nimport { ClientServicesProvider, ClientServices, clientServiceBundle } from './service-definitions';\nimport { ServiceRegistry } from './service-registry';\n\n// TODO(burdon): Factor out to spaces.\n// TODO(burdon): Defaults (with TextModel).\nexport const createDefaultModelFactory = () => {\n return new ModelFactory().registerModel(ObjectModel).registerModel(TextModel);\n};\n\ntype ClientServicesHostParams = {\n config: Config;\n modelFactory?: ModelFactory;\n networkManager: NetworkManager;\n storage?: Storage;\n};\n\n/**\n * Remote service implementation.\n */\nexport class ClientServicesHost implements ClientServicesProvider {\n private _serviceContext!: ServiceContext;\n private _serviceRegistry!: ServiceRegistry<ClientServices>;\n\n private readonly _config: Config;\n private readonly _modelFactory: ModelFactory;\n private readonly _networkManager: NetworkManager;\n private _storage: Storage;\n\n constructor({\n config,\n modelFactory = createDefaultModelFactory(),\n // TODO(burdon): Create ApolloLink abstraction (see Client).\n networkManager,\n storage = createStorageObjects(config.get('runtime.client.storage', {})!).storage\n }: ClientServicesHostParams) {\n this._config = config;\n this._modelFactory = modelFactory;\n this._networkManager = networkManager;\n this._storage = storage;\n }\n\n get descriptors() {\n return this._serviceRegistry.descriptors;\n }\n\n get services() {\n return this._serviceRegistry.services;\n }\n\n async open() {\n log('opening...');\n await this._initialize();\n await this._serviceContext.open();\n const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;\n log('opened', { deviceKey });\n }\n\n async close() {\n const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;\n log('closing...', { deviceKey });\n await this._serviceContext.close();\n log('closed', { deviceKey });\n }\n\n // TODO(burdon): Move into open.\n async _initialize() {\n // TODO(burdon): Break into components.\n this._serviceContext = new ServiceContext(this._storage, this._networkManager, this._modelFactory);\n\n // TODO(burdon): Start to think of DMG (dynamic services).\n this._serviceRegistry = new ServiceRegistry<ClientServices>(clientServiceBundle, {\n HaloInvitationsService: new HaloInvitationsServiceImpl(\n this._serviceContext.identityManager,\n this._serviceContext.haloInvitations\n ),\n\n DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager),\n\n SpaceInvitationsService: new SpaceInvitationsServiceImpl(\n this._serviceContext.identityManager,\n () => this._serviceContext.spaceInvitations ?? raise(new Error('SpaceInvitations not initialized')),\n () => this._serviceContext.dataSpaceManager ?? raise(new Error('SpaceManager not initialized'))\n ),\n\n SpacesService: new SpacesServiceImpl(this._serviceContext.spaceManager),\n\n DataService: new DataServiceImpl(this._serviceContext.dataServiceSubscriptions),\n\n NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager),\n\n // TODO(burdon): Move to new protobuf definitions.\n ProfileService: new ProfileServiceImpl(this._serviceContext),\n SpaceService: new SpaceServiceImpl(this._serviceContext),\n SystemService: new SystemServiceImpl(this._config, this._serviceContext),\n TracingService: new TracingServiceImpl(this._config),\n DevtoolsHost: new DevtoolsServiceImpl({\n events: new DevtoolsHostEvents(),\n config: this._config,\n context: this._serviceContext\n })\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { EventSubscriptions } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { Device, DevicesService, QueryDevicesResponse } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { IdentityManager } from './identity-manager';\n\nexport class DevicesServiceImpl implements DevicesService {\n constructor(private readonly _identityManager: IdentityManager) {}\n\n updateDevice(): Promise<Device> {\n throw new Error('Method not implemented.');\n }\n\n queryDevices(): Stream<QueryDevicesResponse> {\n return new Stream(({ next }) => {\n const update = () => {\n const deviceKeys = this._identityManager.identity?.authorizedDeviceKeys;\n if (!deviceKeys) {\n next({ devices: [] });\n } else {\n next({\n devices: Array.from(deviceKeys.values()).map((key) => ({\n deviceKey: key\n }))\n });\n }\n };\n\n const dispose = new EventSubscriptions();\n dispose.add(\n this._identityManager.stateUpdate.on(() => {\n update();\n\n if (this._identityManager.identity) {\n dispose.add(\n this._identityManager.identity.stateUpdate.on(() => {\n update();\n })\n );\n }\n })\n );\n\n update();\n\n return () => dispose.clear();\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { NetworkManager } from '@dxos/network-manager';\nimport { NetworkService, NetworkStatus, SetNetworkOptionsRequest } from '@dxos/protocols/proto/dxos/client/services';\n\nexport class NetworkServiceImpl implements NetworkService {\n constructor(private readonly networkManager: NetworkManager) {}\n\n subscribeToNetworkStatus() {\n return new Stream<NetworkStatus>(({ next }) => {\n const unsubscribe = this.networkManager.connectionStateChanged.on((state) => next({ state }));\n next({ state: this.networkManager.connectionState });\n\n return unsubscribe;\n });\n }\n\n async setNetworkOptions(request: SetNetworkOptionsRequest) {\n await this.networkManager.setConnectionState(request.state);\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { scheduleTask } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { raise } from '@dxos/debug';\nimport { SpaceManager, SpaceNotFoundError } from '@dxos/echo-db';\nimport {\n QueryCredentialsRequest,\n QueryMembersRequest,\n QueryMembersResponse,\n Space,\n SpacesService\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\n/**\n *\n */\nexport class SpacesServiceImpl implements SpacesService {\n constructor(private readonly _spaceManager: SpaceManager) {}\n\n async createSpace(): Promise<Space> {\n throw new Error();\n }\n\n querySpaces(): Stream<Space> {\n throw new Error();\n }\n\n queryMembers(query: QueryMembersRequest): Stream<QueryMembersResponse> {\n throw new Error();\n }\n\n queryCredentials({ spaceKey }: QueryCredentialsRequest): Stream<Credential> {\n return new Stream(({ ctx, next }) => {\n const space = this._spaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n\n const processor = space.spaceState.registerProcessor({\n process: async (credential) => {\n next(credential);\n }\n });\n ctx.onDispose(() => processor.close());\n scheduleTask(ctx, () => processor.open());\n });\n }\n}\n", "//\n\n//\n// Copyright 2023 DXOS.org\n//\n\nimport { InvalidConfigError } from '@dxos/errors';\nimport { Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { createStorage, StorageType } from '@dxos/random-access-storage';\n\nimport StorageDriver = Runtime.Client.Storage.StorageDriver;\n\n// TODO(burdon): Factor out.\nexport const createStorageObjects = (config: Runtime.Client.Storage) => {\n const {\n path = 'dxos/storage', // TODO(burdon): Factor out const.\n storageType,\n keyStorage,\n persistent = false\n } = config ?? {};\n\n if (persistent && storageType === StorageDriver.RAM) {\n throw new InvalidConfigError('RAM storage cannot be used in persistent mode.');\n }\n if (!persistent && storageType !== undefined && storageType !== StorageDriver.RAM) {\n throw new InvalidConfigError('Cannot use a persistent storage in not persistent mode.');\n }\n if (persistent && keyStorage === StorageDriver.RAM) {\n throw new InvalidConfigError('RAM key storage cannot be used in persistent mode.');\n }\n if (!persistent && keyStorage !== StorageDriver.RAM && keyStorage !== undefined) {\n throw new InvalidConfigError('Cannot use a persistent key storage in not persistent mode.');\n }\n\n return {\n storage: createStorage({\n type: persistent ? toStorageType(storageType) : StorageType.RAM,\n root: `${path}/`\n })\n };\n};\n\nconst toStorageType = (type: StorageDriver | undefined): StorageType | undefined => {\n switch (type) {\n case undefined:\n return undefined;\n case StorageDriver.RAM:\n return StorageType.RAM;\n case StorageDriver.CHROME:\n return StorageType.CHROME;\n case StorageDriver.FIREFOX:\n return StorageType.FIREFOX;\n case StorageDriver.IDB:\n return StorageType.IDB;\n case StorageDriver.NODE:\n return StorageType.NODE;\n default:\n throw new Error(`Invalid storage type: ${StorageDriver[type]}`);\n }\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { ServiceBundle } from '@dxos/rpc';\n\n/**\n * Registry of operational services.\n */\nexport class ServiceRegistry<Services> {\n // prettier-ignore\n constructor (\n private readonly _serviceBundle: ServiceBundle<Services>,\n private readonly _handlers: Services\n ) {}\n\n get descriptors() {\n return this._serviceBundle;\n }\n\n get services() {\n return this._handlers;\n }\n}\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { asyncTimeout } from '@dxos/async';\nimport { RemoteServiceConnectionTimeout } from '@dxos/errors';\nimport { createProtoRpcPeer, ProtoRpcPeer, RpcPort } from '@dxos/rpc';\n\nimport { ClientServicesProvider, ClientServices, clientServiceBundle } from './service-definitions';\n\n/**\n * Implements services that are not local to the app.\n * For example, the services can be located in Wallet Extension.\n */\n// TODO(burdon): Separate construction of port from availability of services.\n// TODO(burdon): Create `@dxos/client-proxy` package with thin-client only dependencies (for code-splitting).\nexport class ClientServicesProxy implements ClientServicesProvider {\n private readonly _proxy: ProtoRpcPeer<ClientServices>;\n\n // prettier-ignore\n constructor(\n port: RpcPort,\n // NOTE: With lower timeout the shared worker does not have enough time to start.\n // TODO(dmaretskyi): Find better ways to detected when the worker has finished loading. It might take a while on slow connections.\n private readonly _timeout = 30_000\n ) {\n this._proxy = createProtoRpcPeer({\n requested: clientServiceBundle,\n exposed: {},\n handlers: {},\n port\n });\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get descriptors() {\n return clientServiceBundle;\n }\n\n get services() {\n return this._proxy.rpc;\n }\n\n async open() {\n await asyncTimeout(this._proxy.open(), this._timeout, new RemoteServiceConnectionTimeout());\n }\n\n async close() {\n await this._proxy.close();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { WebRTCTransportService } from '@dxos/network-manager';\nimport { BridgeService } from '@dxos/protocols/proto/dxos/mesh/bridge';\nimport { createProtoRpcPeer, ProtoRpcPeer, RpcPort } from '@dxos/rpc';\n\nimport { iframeServiceBundle, WorkerServiceBundle, workerServiceBundle } from './services';\n\n// NOTE: Keep as RpcPorts to avoid dependency on @dxos/rpc-tunnel so we don't depend on browser-specific apis.\nexport type IframeRuntimeParams = {\n systemPort: RpcPort;\n workerAppPort: RpcPort;\n windowAppPort: RpcPort;\n};\n\n/**\n * Manages the client connection to the shared worker.\n */\nexport class IFrameRuntime {\n private readonly _systemPort: RpcPort;\n private readonly _windowAppPort: RpcPort;\n private readonly _workerAppPort: RpcPort;\n private readonly _systemRpc: ProtoRpcPeer<WorkerServiceBundle>;\n private readonly _transportService = new WebRTCTransportService();\n\n constructor({ systemPort, workerAppPort, windowAppPort }: IframeRuntimeParams) {\n this._systemPort = systemPort;\n this._windowAppPort = windowAppPort;\n this._workerAppPort = workerAppPort;\n\n this._systemRpc = createProtoRpcPeer({\n requested: workerServiceBundle,\n exposed: iframeServiceBundle,\n handlers: {\n BridgeService: this._transportService as BridgeService,\n IframeService: {\n async heartbeat() {\n // Ok.\n }\n }\n },\n port: this._systemPort,\n timeout: 200\n });\n\n this._workerAppPort.subscribe((msg) => this._windowAppPort.send(msg));\n this._windowAppPort.subscribe((msg) => this._workerAppPort.send(msg));\n }\n\n async open(origin: string) {\n await this._systemRpc.open();\n await this._systemRpc.rpc.WorkerService.start({ origin });\n }\n\n async close() {\n await this._systemRpc.rpc.WorkerService.stop();\n await this._systemRpc.close();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { schema } from '@dxos/protocols';\nimport type { IframeService, WorkerService } from '@dxos/protocols/proto/dxos/iframe';\nimport type { BridgeService } from '@dxos/protocols/proto/dxos/mesh/bridge';\nimport { ServiceBundle } from '@dxos/rpc';\n\nexport type IframeServiceBundle = {\n IframeService: IframeService;\n BridgeService: BridgeService;\n};\n\nexport const iframeServiceBundle: ServiceBundle<IframeServiceBundle> = {\n IframeService: schema.getService('dxos.iframe.IframeService'),\n BridgeService: schema.getService('dxos.mesh.bridge.BridgeService')\n};\n\nexport type WorkerServiceBundle = {\n WorkerService: WorkerService;\n};\n\nexport const workerServiceBundle: ServiceBundle<WorkerServiceBundle> = {\n WorkerService: schema.getService('dxos.iframe.WorkerService')\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Trigger } from '@dxos/async';\nimport { Config } from '@dxos/config';\nimport { MemorySignalManager, MemorySignalManagerContext, WebsocketSignalManager } from '@dxos/messaging';\nimport { NetworkManager, WebRTCTransportProxyFactory } from '@dxos/network-manager';\nimport { RpcPort } from '@dxos/rpc';\nimport { MaybePromise } from '@dxos/util';\n\nimport { ClientServicesHost } from '../services';\nimport { WorkerSession } from './worker-session';\n\n// NOTE: Keep as RpcPorts to avoid dependency on @dxos/rpc-tunnel so we don't depend on browser-specific apis.\nexport type CreateSessionParams = {\n appPort: RpcPort;\n systemPort: RpcPort;\n};\n\n/**\n * Runtime for the shared worker.\n * Manages connections from proxies (in tabs).\n * Tabs make requests to the `ClientServicesHost`, and provide a WebRTC gateway.\n */\nexport class WorkerRuntime {\n private readonly _transportFactory = new WebRTCTransportProxyFactory();\n private readonly _ready = new Trigger<Error | undefined>();\n private readonly sessions = new Set<WorkerSession>();\n private _sessionForNetworking?: WorkerSession;\n private _clientServices!: ClientServicesHost;\n private _config!: Config;\n\n // prettier-ignore\n constructor(\n private readonly _configProvider: () => MaybePromise<Config>\n ) { }\n\n async start() {\n try {\n this._config = await this._configProvider();\n const signalServer = this._config.get('runtime.services.signal.server');\n this._clientServices = new ClientServicesHost({\n config: this._config,\n networkManager: new NetworkManager({\n log: true,\n signalManager: signalServer\n ? new WebsocketSignalManager([signalServer])\n : new MemorySignalManager(new MemorySignalManagerContext()), // TODO(dmaretskyi): Inject this context.\n transportFactory: this._transportFactory\n })\n });\n\n await this._clientServices.open();\n this._ready.wake(undefined);\n } catch (err: any) {\n this._ready.wake(err);\n }\n }\n\n async stop() {\n // TODO(dmaretskyi): Terminate active sessions.\n await this._clientServices.close();\n }\n\n /**\n * Create a new session.\n */\n async createSession({ appPort, systemPort }: CreateSessionParams) {\n const session = new WorkerSession({\n getServices: async () => {\n const error = await this._ready.wait();\n if (error !== undefined) {\n throw error;\n }\n return this._clientServices;\n },\n appPort,\n systemPort,\n readySignal: this._ready\n });\n\n // When tab is closed.\n session.onClose.set(async () => {\n this.sessions.delete(session);\n this._reconnectWebrtc();\n });\n\n await session.open();\n this.sessions.add(session);\n\n this._reconnectWebrtc();\n }\n\n /**\n * Selects one of the existing session fro WebRTC networking.\n */\n private _reconnectWebrtc() {\n // Check if current session is already closed.\n if (this._sessionForNetworking) {\n if (!this.sessions.has(this._sessionForNetworking)) {\n this._sessionForNetworking = undefined;\n }\n }\n\n // Select existing session.\n if (!this._sessionForNetworking) {\n const selected = Array.from(this.sessions).find((session) => session.bridgeService);\n if (selected) {\n this._sessionForNetworking = selected;\n this._transportFactory.setBridgeService(selected.bridgeService);\n } else {\n this._transportFactory.setBridgeService(undefined);\n }\n }\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { Trigger } from '@dxos/async';\nimport { log, logInfo } from '@dxos/log';\nimport { BridgeService } from '@dxos/protocols/proto/dxos/mesh/bridge';\nimport { createProtoRpcPeer, ProtoRpcPeer, RpcPort } from '@dxos/rpc';\nimport { Callback } from '@dxos/util';\n\nimport { clientServiceBundle, ClientServices, ClientServicesHost } from '../services';\nimport { IframeServiceBundle, iframeServiceBundle, workerServiceBundle } from './services';\n\nexport type WorkerSessionParams = {\n getServices: () => Promise<ClientServicesHost>;\n systemPort: RpcPort;\n appPort: RpcPort;\n readySignal: Trigger<Error | undefined>;\n options?: {\n heartbeatInterval: number;\n };\n};\n\n/**\n * Represents a tab connection within the worker.\n */\nexport class WorkerSession {\n private readonly _clientRpc: ProtoRpcPeer<ClientServices>;\n private readonly _iframeRpc: ProtoRpcPeer<IframeServiceBundle>;\n private readonly _startTrigger = new Trigger();\n private readonly _getServices: () => Promise<ClientServicesHost>;\n private readonly _options: NonNullable<WorkerSessionParams['options']>;\n private _heartbeatTimer?: NodeJS.Timeout;\n\n public readonly onClose = new Callback<() => Promise<void>>();\n\n @logInfo\n public origin?: string;\n\n public bridgeService?: BridgeService;\n\n constructor({\n getServices,\n systemPort,\n appPort,\n options = {\n heartbeatInterval: 1_000\n }\n }: WorkerSessionParams) {\n assert(options);\n assert(getServices);\n this._options = options;\n this._getServices = getServices;\n\n this._clientRpc = createProtoRpcPeer({\n exposed: clientServiceBundle,\n handlers: {\n HaloInvitationsService: async () => (await this._getServices()).services.HaloInvitationsService,\n DevicesService: async () => (await this._getServices()).services.DevicesService,\n SpaceInvitationsService: async () => (await this._getServices()).services.SpaceInvitationsService,\n SpacesService: async () => (await this._getServices()).services.SpacesService,\n NetworkService: async () => (await this._getServices()).services.NetworkService,\n SpaceService: async () => (await this._getServices()).services.SpaceService,\n DataService: async () => (await this._getServices()).services.DataService,\n ProfileService: async () => (await this._getServices()).services.ProfileService,\n SystemService: async () => (await this._getServices()).services.SystemService,\n DevtoolsHost: async () => (await this._getServices()).services.DevtoolsHost,\n TracingService: async () => (await this._getServices()).services.TracingService\n },\n port: appPort\n });\n\n this._iframeRpc = createProtoRpcPeer({\n requested: iframeServiceBundle,\n exposed: workerServiceBundle,\n handlers: {\n WorkerService: {\n start: async (request) => {\n this.origin = request.origin;\n this._startTrigger.wake();\n },\n\n stop: async () => {\n setTimeout(async () => {\n try {\n await this.close();\n } catch (err: any) {\n log.catch(err);\n }\n });\n }\n }\n },\n port: systemPort,\n timeout: 1000 // With low timeout heartbeat may fail if the tab's thread is saturated.\n });\n\n this.bridgeService = this._iframeRpc.rpc.BridgeService;\n }\n\n async open() {\n log.info('opening..');\n await Promise.all([this._clientRpc.open(), this._iframeRpc.open()]);\n\n await this._startTrigger.wait({ timeout: 3_000 });\n\n // Detect if bridge is present.\n // TODO(burdon): Add heartbeat to client's System service.\n // How do we detect if the client's tab closed?\n this._heartbeatTimer = setInterval(async () => {\n try {\n await this._iframeRpc.rpc.IframeService.heartbeat();\n } catch (err) {\n log.warn('Heartbeat failed', { err });\n try {\n await this.close();\n } catch (err: any) {\n log.catch(err);\n }\n }\n }, this._options.heartbeatInterval);\n }\n\n async close() {\n log.info('closing..');\n try {\n await this.onClose.callIfSet();\n } catch (err: any) {\n log.catch(err);\n }\n\n if (this._heartbeatTimer !== undefined) {\n clearInterval(this._heartbeatTimer);\n }\n\n await Promise.all([this._clientRpc.close(), this._iframeRpc.close()]);\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;AAIA,OAAOA,YAAY;AAEnB,SAASC,0BAA0B;AACnC,SAASC,cAAc;AACvB,SAASC,YAAY;AACrB,SAASC,WAAW;AACpB,SAKEC,mBASK;AAEP,SAASC,gBAAgB;AASlB,IAAMC,mBAAN,MAAMA;EAGXC,YAA6BC,gBAAgC;0BAAhCA;SAFrBC,qBAAyC,oBAAIC,IAAAA;EAES;EAE9DC,iBAAiBC,SAAgE;AAC/E,WAAO,IAAIX,OAAO,CAAC,EAAEY,KAAI,MAAO;AAC9BA,WAAK;QACHC,OAAO;UACLC,WAAWH,QAAQI;UACnBC,QAAQ;UACRC,UAAU;UACVC,SAAS,CAAA;QACX;MACF,CAAA;IACF,CAAA;EA2CF;EAEAC,kBAAkB;AAChB,WAAO,IAAInB,OAAgC,CAAC,EAAEY,KAAI,MAAO;AACvD,YAAMQ,gBAAgB,IAAIrB,mBAAAA;AAE1B,YAAMsB,WAAW,MAAM;AACrB,cAAMC,SAASC,MAAMC,KAAK,KAAKjB,eAAekB,iBAAkBH,OAAOI,OAAM,CAAA,EAAIC,IAC/E,CAACd,WAAkB;UACjBC,WAAWD,MAAMe;UACjBZ,QAAQ;UACRC,UAAU;UACVC,SAASK,MAAMC,KAAKX,MAAMgB,MAAMC,WAAWZ,QAAQQ,OAAM,CAAA,EAAIC,IAAI,CAACI,WAAAA;AAzG9E;AAyG0F;cAC5EC,aAAaD,OAAOH;cACpBK,SAAS;gBACPD,aAAaD,OAAOH;gBACpBM,cAAaH,kBA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AACvB,cAAMC,QAAQ,MAAM,KAAK/B,OAAOgC,KAAI;AACpC,YAAID,UAAUV,QAAW;AACvB,gBAAMU;QACR;AACA,eAAO,KAAKvB;MACd;MACAkB;MACAC;MACAM,aAAa,KAAKjC;IACpB,CAAA;AAGA4B,YAAQM,QAAQC,IAAI,YAAY;AAC9B,WAAKjC,SAASkC,OAAOR,OAAAA;AACrB,WAAKS,iBAAgB;IACvB,CAAA;AAEA,UAAMT,QAAQT,KAAI;AAClB,SAAKjB,SAASoC,IAAIV,OAAAA;AAElB,SAAKS,iBAAgB;EACvB;;;;EAKQA,mBAAmB;AAEzB,QAAI,KAAKE,uBAAuB;AAC9B,UAAI,CAAC,KAAKrC,SAASsC,IAAI,KAAKD,qBAAqB,GAAG;AAClD,aAAKA,wBAAwBlB;MAC/B;IACF;AAGA,QAAI,CAAC,KAAKkB,uBAAuB;AAC/B,YAAME,WAAWC,MAAMC,KAAK,KAAKzC,QAAQ,EAAE0C,KAAK,CAAChB,YAAYA,QAAQiB,aAAa;AAClF,UAAIJ,UAAU;AACZ,aAAKF,wBAAwBE;AAC7B,aAAK3C,kBAAkBgD,iBAAiBL,SAASI,aAAa;MAChE,OAAO;AACL,aAAK/C,kBAAkBgD,iBAAiBzB,MAAAA;MAC1C;IACF;EACF;AACF;",
|
|
6
|
+
"names": ["assert", "EventSubscriptions", "Stream", "todo", "log", "SpaceMember", "humanize", "SpaceServiceImpl", "constructor", "serviceContext", "inviteeInvitations", "Map", "subscribeToSpace", "request", "next", "space", "publicKey", "spaceKey", "isOpen", "isActive", "members", "subscribeSpaces", "subscriptions", "onUpdate", "spaces", "Array", "from", "dataSpaceManager", "values", "map", "key", "inner", "spaceState", "member", "identityKey", "profile", "displayName", "assertion", "presence", "identityManager", "identity", "equals", "getPeersOnline", "filter", "length", "PresenceState", "ONLINE", "OFFLINE", "setTimeout", "initialized", "wait", "add", "updated", "on", "forEach", "stateUpdate", "clear", "getSpaceDetails", "createSpace", "cloneSpace", "snapshot", "setSpaceState", "authenticateInvitation", "processId", "invitation", "get", "secret", "secretTrigger", "subscribeMembers", "createSnapshot", "Stream", "todo", "ProfileServiceImpl", "constructor", "context", "inviteeInvitations", "Map", "subscribeProfile", "next", "emitNext", "profile", "identityManager", "identity", "identityKey", "deviceKey", "displayName", "profileDocument", "undefined", "stateUpdate", "on", "createProfile", "request", "createIdentity", "recoverProfile", "seedPhrase", "Error", "SystemServiceImpl", "constructor", "_config", "_serviceContext", "initSession", "getConfig", "request", "values", "getStatus", "message", "Date", "now", "reset", "TracingServiceImpl", "constructor", "_config", "setTracingOptions", "Error", "subscribeToRpcTrace", "Event", "AsyncEvent", "Stream", "EventSubscriptions", "Stream", "FeedIterator", "PublicKey", "ComplexMap", "subscribeToFeeds", "feedStore", "feedKeys", "next", "length", "feedMap", "hash", "subscriptions", "update", "feeds", "filter", "feed", "some", "feedKey", "equals", "key", "forEach", "has", "set", "on", "add", "off", "Array", "from", "values", "map", "properties", "feedOpened", "clear", "subscribeToFeedBlocks", "maxBlocks", "timeout", "setTimeout", "getFeed", "iterator", "open", "blocks", "block", "push", "slice", "close", "clearTimeout", "Stream", "subscribeToKeyringKeys", "keyring", "next", "update", "keys", "list", "unsubscribe", "keysUpdate", "on", "Stream", "PublicKey", "subscribeToNetworkStatus", "networkManager", "next", "close", "update", "status", "signalManager", "getStatus", "servers", "err", "statusChanged", "on", "subscribeToSignalTrace", "events", "trace", "commandTrace", "msg", "push", "map", "JSON", "stringify", "subscribeToNetworkTopics", "topics", "labeledTopics", "topic", "label", "getSwarm", "toHex", "topicsUpdated", "subscribeToSwarmInfo", "_a", "info", "connectionLog", "swarms", "data", "getNetworkPeers", "request", "Error", "getSwarmMap", "from", "peers", "peer", "connections", "connection", "asUint8Array", "Stream", "subscribeToSpaces", "context", "spaceKeys", "next", "unsubscribe", "update", "spaces", "spaceManager", "values", "filteredSpaces", "filter", "space", "length", "some", "spaceKey", "equals", "key", "map", "spaceMetadata", "metadataStore", "find", "isOpen", "timeframe", "latestTimeframe", "genesisFeed", "genesisFeedKey", "controlFeed", "controlFeedKey", "dataFeed", "dataFeedKey", "timeout", "setTimeout", "initialized", "wait", "dataSpaceManager", "updated", "on", "clearTimeout", "DevtoolsHostEvents", "ready", "AsyncEvent", "DevtoolsServiceImpl", "constructor", "params", "events", "request", "Stream", "next", "on", "getConfig", "Error", "resetStorage", "enableDebugLogging", "disableDebugLogging", "subscribeToKeyringKeys", "keyring", "context", "subscribeToCredentialMessages", "subscribeToSpaces", "subscribeToItems", "subscribeToFeeds", "feedStore", "subscribeToFeedBlocks", "getSpaceSnapshot", "saveSpaceSnapshot", "clearSnapshots", "getNetworkPeers", "subscribeToNetworkTopics", "subscribeToSignalStatus", "subscribeToNetworkStatus", "networkManager", "subscribeToSignalTrace", "subscribeToSwarmInfo", "Trigger", "Context", "verifyCredential", "log", "schema", "createAuthProvider", "signer", "nonce", "credential", "createCredential", "assertion", "subject", "getIssuer", "getCodecForType", "encode", "TrustedKeySetAuthVerifier", "constructor", "_params", "_ctx", "close", "dispose", "_isTrustedKey", "deviceKey", "deviceSet", "trustedKeysProvider", "has", "verifier", "auth", "decode", "result", "kind", "proof", "Buffer", "from", "equals", "issuer", "key", "trigger", "onDispose", "wake", "clear", "update", "on", "wait", "timeout", "authTimeout", "assert", "Event", "DeviceStateMachine", "createCredentialSignerWithKey", "createCredentialSignerWithChain", "ProfileStateMachine", "writeMessages", "log", "AdmittedFeed", "AUTH_TIMEOUT", "Identity", "constructor", "space", "signer", "identityKey", "deviceKey", "stateUpdate", "Event", "_signer", "_deviceStateMachine", "spaceState", "registerProcessor", "DeviceStateMachine", "onUpdate", "emit", "_profileStateMachine", "ProfileStateMachine", "authVerifier", "TrustedKeySetAuthVerifier", "trustedKeysProvider", "authorizedDeviceKeys", "update", "authTimeout", "processor", "open", "close", "ready", "deviceChainReady", "wait", "profileDocument", "profile", "controlPipeline", "haloSpaceKey", "key", "haloGenesisFeedKey", "genesisFeedKey", "getAdmissionCredentials", "controlFeedKey", "dataFeedKey", "getIdentityCredentialSigner", "assert", "deviceCredentialChain", "createCredentialSignerWithChain", "getDeviceCredentialSigner", "createCredentialSignerWithKey", "admitDevice", "log", "hostDevice", "writeMessages", "writer", "createCredential", "subject", "assertion", "spaceKey", "designation", "AdmittedFeed", "Designation", "CONTROL", "DATA", "map", "credential", "assert", "Event", "createCredentialSignerWithKey", "CredentialGenerator", "log", "AdmittedFeed", "deferFunction", "IdentityManager", "constructor", "_metadataStore", "_keyring", "_spaceManager", "stateUpdate", "Event", "identity", "_identity", "open", "load", "identityRecord", "getIdentityRecord", "log", "_constructIdentity", "ready", "emit", "close", "createIdentity", "displayName", "assert", "controlFeedKey", "createKey", "identityKey", "deviceKey", "haloSpace", "spaceKey", "genesisFeedKey", "writeControlFeedKey", "writeDataFeedKey", "generator", "CredentialGenerator", "credentials", "createSpaceGenesis", "createFeedAdmission", "AdmittedFeed", "Designation", "DATA", "push", "createProfileCredential", "createDeviceAuthorization", "credential", "controlPipeline", "writer", "write", "setIdentityRecord", "acceptIdentity", "params", "haloSpaceKey", "haloGenesisFeedKey", "space", "_constructSpace", "spaceRecord", "swarmIdentity", "peerKey", "credentialProvider", "createAuthProvider", "createCredentialSignerWithKey", "credentialAuthenticator", "deferFunction", "authVerifier", "verifier", "Identity", "signer", "constructSpace", "metadata", "key", "dataFeedKey", "onNetworkConnection", "base", "schema", "base62", "codec", "getCodecForType", "InvitationEncoder", "decode", "text", "encode", "invitation", "assert", "scheduleTask", "sleep", "Trigger", "Context", "generatePasscode", "failUndefined", "PublicKey", "log", "createTeleportProtocolFactory", "StarTopology", "schema", "Invitation", "AuthenticationResponse", "RpcExtension", "assert", "CancellableObservableProvider", "Invitation", "AUTHENTICATION_CODE_LENGTH", "INVITATION_TIMEOUT", "ON_CLOSE_DELAY", "InvitationObservableProvider", "invitation", "_invitation", "setInvitation", "AuthenticatingInvitationProvider", "constructor", "_actions", "onCancel", "authenticate", "authenticationCode", "onAuthenticate", "wrapObservable", "observable", "Promise", "resolve", "reject", "unsubscribe", "subscribe", "onSuccess", "state", "State", "SUCCESS", "onError", "err", "AbstractInvitationsHandler", "_networkManager", "HaloInvitationsHandler", "AbstractInvitationsHandler", "constructor", "networkManager", "_identityManager", "createInvitation", "context", "options", "type", "timeout", "INVITATION_TIMEOUT", "swarmKey", "assert", "Invitation", "Type", "OFFLINE", "identity", "failUndefined", "invitation", "invitationId", "PublicKey", "random", "toHex", "authenticationCode", "generatePasscode", "AUTHENTICATION_CODE_LENGTH", "ctx", "Context", "onError", "err", "dispose", "observable", "callback", "InvitationObservableProvider", "complete", "Trigger", "createExtension", "hostInvitationExtension", "HostHaloInvitationExtension", "requestAdmission", "_a", "log", "host", "deviceKey", "onAuthenticating", "identityKey", "haloSpaceKey", "genesisFeedKey", "haloGenesisFeedKey", "authenticate", "code", "status", "AuthenticationResponse", "Status", "OK", "presentAdmissionCredentials", "credentials", "INTERACTIVE_TESTING", "undefined", "Error", "guest", "admitDevice", "wake", "onOpen", "scheduleTask", "onConnected", "wait", "onSuccess", "cancelled", "error", "sleep", "ON_CLOSE_DELAY", "topic", "swarmConnection", "_networkManager", "joinSwarm", "peerId", "protocolProvider", "createTeleportProtocolFactory", "teleport", "addExtension", "topology", "StarTopology", "onDispose", "close", "onConnecting", "acceptInvitation", "authenticated", "AuthenticatingInvitationProvider", "onCancel", "onAuthenticate", "connectionCount", "extension", "GuestHaloInvitationExtension", "rpc", "HaloHostService", "INTERACTIVE", "acceptIdentity", "getAdmissionCredentials", "warn", "RpcExtension", "_callbacks", "exposed", "schema", "getService", "getHandlers", "requested", "assert", "observableError", "log", "Invitation", "AbstractInvitationsProxy", "constructor", "_invitationsService", "createInvitation", "context", "options", "invitationId", "observable", "InvitationObservableProvider", "cancelInvitation", "invitation", "getInvitationOptions", "stream", "subscribe", "setInvitation", "state", "Invitation", "State", "CONNECTING", "assert", "callback", "onConnecting", "CONNECTED", "onConnected", "AUTHENTICATING", "onAuthenticating", "SUCCESS", "onSuccess", "CANCELLED", "onCancelled", "log", "error", "err", "observableError", "acceptInvitation", "swarmKey", "AuthenticatingInvitationProvider", "onCancel", "onAuthenticate", "authenticationCode", "authenticate", "HaloInvitationsProxy", "AbstractInvitationsProxy", "getInvitationOptions", "assert", "Stream", "log", "Invitation", "AbstractInvitationsService", "_identityManager", "_getInvitationsHandler", "_createInvitations", "Map", "_acceptInvitations", "getLoggingContext", "deviceKey", "identity", "createInvitation", "invitation", "next", "close", "invitationsHandler", "context", "getContext", "invitationId", "type", "swarmKey", "observable", "subscribe", "onConnecting", "set", "state", "State", "CONNECTING", "onConnected", "CONNECTED", "onAuthenticating", "AUTHENTICATING", "onSuccess", "SUCCESS", "onCancelled", "CANCELLED", "onTimeout", "err", "TIMEOUT", "onError", "ERROR", "warn", "delete", "acceptInvitation", "options", "authenticate", "authenticationCode", "get", "cancelInvitation", "cancel", "HaloInvitationsServiceImpl", "AbstractInvitationsService", "constructor", "identityManager", "invitationsHandler", "getContext", "invitation", "assert", "scheduleTask", "sleep", "Trigger", "Context", "createAdmissionCredentials", "generatePasscode", "getCredentialAssertion", "writeMessages", "PublicKey", "log", "createTeleportProtocolFactory", "StarTopology", "schema", "Invitation", "AuthenticationResponse", "RpcExtension", "MAX_OTP_ATTEMPTS", "SpaceInvitationsHandler", "AbstractInvitationsHandler", "constructor", "networkManager", "_spaceManager", "_signingContext", "_keyring", "createInvitation", "space", "options", "swarmConnection", "type", "timeout", "INVITATION_TIMEOUT", "swarmKey", "assert", "Invitation", "Type", "OFFLINE", "invitation", "invitationId", "PublicKey", "random", "toHex", "spaceKey", "key", "authenticationCode", "generatePasscode", "AUTHENTICATION_CODE_LENGTH", "ctx", "Context", "onError", "err", "dispose", "observable", "callback", "InvitationObservableProvider", "close", "authenticationRetry", "createExtension", "complete", "Trigger", "guestProfile", "hostInvitationExtension", "HostSpaceInvitationExtension", "introduce", "profile", "log", "host", "deviceKey", "onAuthenticating", "authenticate", "code", "status", "AuthenticationResponse", "Status", "OK", "INVALID_OPT_ATTEMPTS", "INVALID_OTP", "requestAdmission", "identityKey", "controlFeedKey", "dataFeedKey", "INTERACTIVE_TESTING", "MULTIUSE_TESTING", "undefined", "Error", "guest", "credentials", "createAdmissionCredentials", "credentialSigner", "inner", "genesisFeedKey", "spaceMemberCredential", "credential", "getCredentialAssertion", "writeMessages", "controlPipeline", "writer", "wake", "onOpen", "scheduleTask", "onConnected", "wait", "onSuccess", "cancelled", "error", "sleep", "ON_CLOSE_DELAY", "topic", "_networkManager", "joinSwarm", "peerId", "protocolProvider", "createTeleportProtocolFactory", "teleport", "addExtension", "topology", "StarTopology", "onDispose", "onConnecting", "acceptInvitation", "authenticated", "AuthenticatingInvitationProvider", "onCancel", "onAuthenticate", "connectionCount", "extension", "GuestSpaceInvitationExtension", "rpc", "SpaceHostService", "INTERACTIVE", "attempt", "response", "reset", "createKey", "assertion", "subject", "id", "equals", "acceptSpace", "warn", "RpcExtension", "_callbacks", "exposed", "schema", "getService", "getHandlers", "params", "context", "requested", "SpaceInvitationsProxy", "AbstractInvitationsProxy", "getInvitationOptions", "context", "spaceKey", "assert", "SpaceInvitationsServiceImpl", "AbstractInvitationsService", "constructor", "identityManager", "invitationsHandler", "_getSpaceManager", "getContext", "invitation", "assert", "spaceKey", "spaceManager", "space", "spaces", "get", "Trigger", "failUndefined", "valueEncoding", "DataServiceSubscriptions", "MetadataStore", "SpaceManager", "SnapshotStore", "FeedFactory", "FeedStore", "Keyring", "log", "assert", "Event", "synchronized", "trackLeaks", "Context", "spaceGenesis", "SnapshotManager", "PublicKey", "log", "Presence", "ComplexMap", "deferFunction", "assert", "trackLeaks", "Context", "DataPipelineControllerImpl", "PublicKey", "ComplexSet", "AUTH_TIMEOUT", "DataSpace", "constructor", "params", "_ctx", "Context", "_inner", "inner", "_presence", "presence", "_dataPipelineController", "DataPipelineControllerImpl", "modelFactory", "metadataStore", "snapshotManager", "memberKey", "spaceKey", "key", "feedInfoProvider", "feedKey", "spaceState", "feeds", "get", "snapshotId", "authVerifier", "TrustedKeySetAuthVerifier", "trustedKeysProvider", "ComplexSet", "PublicKey", "hash", "Array", "from", "members", "keys", "update", "stateUpdate", "authTimeout", "isOpen", "dataPipelineController", "database", "assert", "open", "initDataPipeline", "close", "dispose", "destroy", "trackLeaks", "__decorate", "DataSpaceManager", "constructor", "_spaceManager", "_metadataStore", "_dataServiceSubscriptions", "_keyring", "_signingContext", "_modelFactory", "_snapshotStore", "_ctx", "Context", "updated", "Event", "_spaces", "ComplexMap", "PublicKey", "hash", "spaces", "open", "load", "log", "length", "spaceMetadata", "space", "_constructSpace", "latestTimeframe", "dataPipelineController", "waitUntilTimeframe", "close", "dispose", "values", "createSpace", "spaceKey", "createKey", "controlFeedKey", "dataFeedKey", "metadata", "key", "genesisFeedKey", "spaceGenesis", "inner", "addSpace", "emit", "acceptSpace", "opts", "assert", "has", "presence", "Presence", "localPeerId", "deviceKey", "announceInterval", "offlineTimeout", "identityKey", "snapshotManager", "SnapshotManager", "constructSpace", "swarmIdentity", "peerKey", "credentialProvider", "createAuthProvider", "credentialSigner", "credentialAuthenticator", "deferFunction", "dataSpace", "authVerifier", "verifier", "onNetworkConnection", "session", "addExtension", "createExtension", "remotePeerId", "objectSync", "DataSpace", "modelFactory", "metadataStore", "memberKey", "snapshotId", "snapshot", "registerSpace", "database", "createDataServiceHost", "set", "synchronized", "trackLeaks", "ServiceContext", "constructor", "storage", "networkManager", "modelFactory", "initialized", "Trigger", "dataServiceSubscriptions", "DataServiceSubscriptions", "metadataStore", "MetadataStore", "createDirectory", "snapshotStore", "SnapshotStore", "keyring", "Keyring", "feedStore", "FeedStore", "factory", "FeedFactory", "root", "signer", "hypercore", "valueEncoding", "spaceManager", "SpaceManager", "identityManager", "IdentityManager", "haloInvitations", "HaloInvitationsHandler", "open", "log", "identity", "_initialize", "close", "dataSpaceManager", "clear", "reset", "createIdentity", "params", "failUndefined", "signingContext", "credentialSigner", "getIdentityCredentialSigner", "identityKey", "deviceKey", "profile", "profileDocument", "DataSpaceManager", "spaceInvitations", "SpaceInvitationsHandler", "wake", "schema", "createServiceBundle", "clientServiceBundle", "HaloInvitationsService", "getService", "DevicesService", "SpaceInvitationsService", "SpacesService", "NetworkService", "SpaceService", "DataService", "ProfileService", "SystemService", "DevtoolsHost", "TracingService", "raise", "DataServiceImpl", "log", "ModelFactory", "ObjectModel", "TextModel", "EventSubscriptions", "Stream", "DevicesServiceImpl", "constructor", "_identityManager", "updateDevice", "Error", "queryDevices", "next", "update", "deviceKeys", "identity", "authorizedDeviceKeys", "devices", "Array", "from", "values", "map", "key", "deviceKey", "dispose", "add", "stateUpdate", "on", "clear", "Stream", "NetworkServiceImpl", "constructor", "networkManager", "subscribeToNetworkStatus", "next", "unsubscribe", "connectionStateChanged", "on", "state", "connectionState", "setNetworkOptions", "request", "setConnectionState", "scheduleTask", "Stream", "raise", "SpaceNotFoundError", "SpacesServiceImpl", "constructor", "_spaceManager", "createSpace", "Error", "querySpaces", "queryMembers", "query", "queryCredentials", "spaceKey", "ctx", "next", "space", "spaces", "get", "processor", "spaceState", "registerProcessor", "process", "credential", "onDispose", "close", "open", "InvalidConfigError", "Runtime", "createStorage", "StorageType", "StorageDriver", "createStorageObjects", "config", "path", "storageType", "keyStorage", "persistent", "RAM", "undefined", "storage", "type", "toStorageType", "root", "CHROME", "FIREFOX", "IDB", "NODE", "Error", "ServiceRegistry", "constructor", "_serviceBundle", "_handlers", "descriptors", "services", "createDefaultModelFactory", "ModelFactory", "registerModel", "ObjectModel", "TextModel", "ClientServicesHost", "constructor", "config", "modelFactory", "networkManager", "storage", "createStorageObjects", "get", "_config", "_modelFactory", "_networkManager", "_storage", "descriptors", "_serviceRegistry", "services", "open", "log", "_initialize", "_serviceContext", "deviceKey", "identityManager", "identity", "close", "ServiceContext", "ServiceRegistry", "clientServiceBundle", "HaloInvitationsService", "HaloInvitationsServiceImpl", "haloInvitations", "DevicesService", "DevicesServiceImpl", "SpaceInvitationsService", "SpaceInvitationsServiceImpl", "spaceInvitations", "raise", "Error", "dataSpaceManager", "SpacesService", "SpacesServiceImpl", "spaceManager", "DataService", "DataServiceImpl", "dataServiceSubscriptions", "NetworkService", "NetworkServiceImpl", "ProfileService", "ProfileServiceImpl", "SpaceService", "SpaceServiceImpl", "SystemService", "SystemServiceImpl", "TracingService", "TracingServiceImpl", "DevtoolsHost", "DevtoolsServiceImpl", "events", "DevtoolsHostEvents", "context", "asyncTimeout", "RemoteServiceConnectionTimeout", "createProtoRpcPeer", "ClientServicesProxy", "constructor", "port", "_timeout", "_proxy", "createProtoRpcPeer", "requested", "clientServiceBundle", "exposed", "handlers", "proxy", "descriptors", "services", "rpc", "open", "asyncTimeout", "RemoteServiceConnectionTimeout", "close", "WebRTCTransportService", "createProtoRpcPeer", "schema", "iframeServiceBundle", "IframeService", "getService", "BridgeService", "workerServiceBundle", "WorkerService", "IFrameRuntime", "constructor", "systemPort", "workerAppPort", "windowAppPort", "_transportService", "WebRTCTransportService", "_systemPort", "_windowAppPort", "_workerAppPort", "_systemRpc", "createProtoRpcPeer", "requested", "workerServiceBundle", "exposed", "iframeServiceBundle", "handlers", "BridgeService", "IframeService", "heartbeat", "port", "timeout", "subscribe", "msg", "send", "open", "origin", "rpc", "WorkerService", "start", "close", "stop", "Trigger", "MemorySignalManager", "MemorySignalManagerContext", "WebsocketSignalManager", "NetworkManager", "WebRTCTransportProxyFactory", "assert", "Trigger", "log", "logInfo", "createProtoRpcPeer", "Callback", "__decorate", "WorkerSession", "constructor", "getServices", "systemPort", "appPort", "options", "heartbeatInterval", "_startTrigger", "Trigger", "onClose", "Callback", "assert", "_options", "_getServices", "_clientRpc", "createProtoRpcPeer", "exposed", "clientServiceBundle", "handlers", "HaloInvitationsService", "services", "DevicesService", "SpaceInvitationsService", "SpacesService", "NetworkService", "SpaceService", "DataService", "ProfileService", "SystemService", "DevtoolsHost", "TracingService", "port", "_iframeRpc", "requested", "iframeServiceBundle", "workerServiceBundle", "WorkerService", "start", "request", "origin", "wake", "stop", "setTimeout", "close", "err", "log", "catch", "timeout", "bridgeService", "rpc", "BridgeService", "open", "info", "Promise", "all", "wait", "_heartbeatTimer", "setInterval", "IframeService", "heartbeat", "warn", "callIfSet", "undefined", "clearInterval", "logInfo", "WorkerRuntime", "constructor", "_configProvider", "_transportFactory", "WebRTCTransportProxyFactory", "_ready", "Trigger", "sessions", "Set", "start", "_config", "signalServer", "get", "_clientServices", "ClientServicesHost", "config", "networkManager", "NetworkManager", "log", "signalManager", "WebsocketSignalManager", "MemorySignalManager", "MemorySignalManagerContext", "transportFactory", "open", "wake", "undefined", "err", "stop", "close", "createSession", "appPort", "systemPort", "session", "WorkerSession", "getServices", "error", "wait", "readySignal", "onClose", "set", "delete", "_reconnectWebrtc", "add", "_sessionForNetworking", "has", "selected", "Array", "from", "find", "bridgeService", "setBridgeService"]
|
|
7
7
|
}
|