@dxos/client-services 0.7.2 → 0.7.3-main.2dd075e
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/{chunk-K5O5LV2R.mjs → chunk-5GKWY67F.mjs} +340 -422
- package/dist/lib/browser/chunk-5GKWY67F.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +1 -1
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +1 -1
- package/dist/lib/node/{chunk-SPLKKUM4.cjs → chunk-RVO5327U.cjs} +329 -411
- package/dist/lib/node/chunk-RVO5327U.cjs.map +7 -0
- package/dist/lib/node/index.cjs +47 -47
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +8 -8
- package/dist/lib/node-esm/{chunk-NSCBFSXO.mjs → chunk-LMUKPYXE.mjs} +334 -416
- package/dist/lib/node-esm/chunk-LMUKPYXE.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +1 -1
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +1 -1
- package/dist/types/src/packlets/agents/edge-agent-service.d.ts +5 -2
- package/dist/types/src/packlets/agents/edge-agent-service.d.ts.map +1 -1
- package/dist/types/src/packlets/identity/identity-service.d.ts +1 -0
- package/dist/types/src/packlets/identity/identity-service.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/epoch-migrations.d.ts.map +1 -1
- package/dist/types/src/version.d.ts +1 -1
- package/dist/types/src/version.d.ts.map +1 -1
- package/package.json +38 -38
- package/src/packlets/agents/edge-agent-service.ts +28 -3
- package/src/packlets/identity/identity-service.ts +16 -1
- package/src/packlets/services/service-context.ts +4 -1
- package/src/packlets/services/service-host.ts +1 -1
- package/src/packlets/spaces/data-space-manager.ts +4 -13
- package/src/packlets/spaces/epoch-migrations.ts +3 -84
- package/src/version.ts +1 -5
- package/dist/lib/browser/chunk-K5O5LV2R.mjs.map +0 -7
- package/dist/lib/node/chunk-SPLKKUM4.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-NSCBFSXO.mjs.map +0 -7
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/packlets/devtools/feeds.ts", "../../../src/packlets/devtools/network.ts", "../../../src/packlets/devtools/spaces.ts", "../../../src/packlets/devtools/devtools.ts", "../../../src/packlets/devtools/keys.ts", "../../../src/packlets/devtools/metadata.ts", "../../../src/packlets/diagnostics/diagnostics.ts", "../../../src/version.ts", "../../../src/packlets/services/platform.ts", "../../../src/packlets/diagnostics/browser-diagnostics-broadcast.ts", "../../../src/packlets/diagnostics/diagnostics-collector.ts", "../../../src/packlets/identity/authenticator.ts", "../../../src/packlets/spaces/edge-feed-replicator.ts", "../../../src/packlets/spaces/data-space.ts", "../../../src/packlets/spaces/automerge-space-state.ts", "../../../src/packlets/spaces/epoch-migrations.ts", "../../../src/packlets/spaces/notarization-plugin.ts", "../../../src/packlets/identity/identity.ts", "../../../src/packlets/identity/default-space-state-machine.ts", "../../../src/packlets/spaces/data-space-manager.ts", "../../../src/packlets/spaces/genesis.ts", "../../../src/packlets/spaces/spaces-service.ts", "../../../src/packlets/identity/identity-manager.ts", "../../../src/packlets/identity/identity-service.ts", "../../../src/packlets/invitations/device-invitation-protocol.ts", "../../../src/packlets/invitations/invitations-handler.ts", "../../../src/packlets/invitations/edge-invitation-handler.ts", "../../../src/packlets/invitations/utils.ts", "../../../src/packlets/invitations/invitation-guest-extenstion.ts", "../../../src/packlets/invitations/invitation-host-extension.ts", "../../../src/packlets/invitations/invitation-state.ts", "../../../src/packlets/invitations/invitation-topology.ts", "../../../src/packlets/invitations/invitations-service.ts", "../../../src/packlets/invitations/space-invitation-protocol.ts", "../../../src/packlets/invitations/invitations-manager.ts", "../../../src/packlets/locks/browser.ts", "../../../src/packlets/services/client-rpc-server.ts", "../../../src/packlets/agents/edge-agent-manager.ts", "../../../src/packlets/agents/edge-agent-service.ts", "../../../src/packlets/services/service-context.ts", "../../../src/packlets/identity/identity-recovery-manager.ts", "../../../src/packlets/services/service-registry.ts", "../../../src/packlets/storage/storage.ts", "../../../src/packlets/storage/util.ts", "../../../src/packlets/storage/level.ts", "../../../src/packlets/storage/profile-archive.ts", "../../../src/packlets/services/service-host.ts", "../../../src/packlets/devices/devices-service.ts", "../../../src/packlets/identity/contacts-service.ts", "../../../src/packlets/logging/logging-service.ts", "../../../src/packlets/network/network-service.ts", "../../../src/packlets/system/system-service.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2021 DXOS.org\n//\n\nimport { EventSubscriptions } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type SpaceManager } from '@dxos/echo-pipeline';\nimport { FeedIterator, type FeedStore, type FeedWrapper } from '@dxos/feed-store';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n type SubscribeToFeedsRequest,\n type SubscribeToFeedsResponse,\n type SubscribeToFeedBlocksRequest,\n type SubscribeToFeedBlocksResponse,\n} from '@dxos/protocols/proto/dxos/devtools/host';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { ComplexMap } from '@dxos/util';\n\ntype FeedInfo = {\n feed: FeedWrapper<FeedMessage>;\n owner?: SubscribeToFeedsResponse.FeedOwner;\n};\n\nexport const subscribeToFeeds = (\n { feedStore, spaceManager }: { feedStore: FeedStore<FeedMessage>; spaceManager: SpaceManager },\n { feedKeys }: SubscribeToFeedsRequest,\n) => {\n return new Stream<SubscribeToFeedsResponse>(({ next }) => {\n const subscriptions = new EventSubscriptions();\n const feedMap = new ComplexMap<PublicKey, FeedInfo>(PublicKey.hash);\n\n const update = () => {\n const { feeds } = feedStore;\n feeds\n .filter((feed) => !feedKeys?.length || feedKeys.some((feedKey) => feedKey.equals(feed.key)))\n .forEach((feed) => {\n if (!feedMap.has(feed.key)) {\n feedMap.set(feed.key, { feed });\n feed.on('close', update);\n subscriptions.add(() => feed.off('close', update));\n }\n if (!feedMap.get(feed.key)?.owner) {\n feedMap.get(feed.key)!.owner = findFeedOwner(spaceManager, feed.key);\n }\n });\n\n next({\n feeds: Array.from(feedMap.values()).map(({ feed, owner }) => ({\n feedKey: feed.key,\n length: feed.properties.length,\n bytes: feed.core.byteLength,\n downloaded: feed.core.bitfield?.data.toBuffer() ?? new Uint8Array(),\n owner,\n })),\n });\n };\n\n subscriptions.add(feedStore.feedOpened.on(update));\n update();\n\n return () => {\n subscriptions.clear();\n };\n });\n};\n\nconst findFeedOwner = (\n spaceManager: SpaceManager,\n feedKey: PublicKey,\n): SubscribeToFeedsResponse.FeedOwner | undefined => {\n const feedInfo = [...spaceManager.spaces.values()]\n .flatMap((space) => [...space.spaceState.feeds.values()])\n .find((feed) => feed.key.equals(feedKey));\n log('feeds', { feedInfo, key: feedKey.truncate(), allSpaces: spaceManager.spaces.size });\n if (!feedInfo) {\n return undefined;\n }\n return {\n identity: feedInfo.assertion.identityKey,\n device: feedInfo.assertion.deviceKey,\n };\n};\n\nexport const subscribeToFeedBlocks = (\n { feedStore }: { feedStore: FeedStore<FeedMessage> },\n { feedKey, maxBlocks = 10 }: SubscribeToFeedBlocksRequest,\n) => {\n return new Stream<SubscribeToFeedBlocksResponse>(({ next }) => {\n if (!feedKey) {\n return;\n }\n 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 if (!feed.properties.length) {\n next({ blocks: [] });\n return;\n }\n\n const iterator = new FeedIterator(feed);\n await iterator.open();\n const blocks = [];\n for await (const block of iterator) {\n blocks.push(block);\n if (blocks.length >= feed.properties.length) {\n break;\n }\n }\n\n next({\n blocks: blocks.slice(-maxBlocks),\n });\n\n await iterator.close();\n };\n\n feed.on('append', update);\n subscriptions.add(() => feed.off('append', update));\n\n feed.on('truncate', update);\n subscriptions.add(() => feed.off('truncate', update));\n await update();\n });\n\n return () => {\n subscriptions.clear();\n clearTimeout(timeout);\n };\n });\n};\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { Context } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { type SignalManager } from '@dxos/messaging';\nimport { type SwarmNetworkManager } from '@dxos/network-manager';\nimport {\n type GetNetworkPeersRequest,\n type GetNetworkPeersResponse,\n type SubscribeToNetworkTopicsResponse,\n type SubscribeToSignalStatusResponse,\n type SignalResponse,\n type SubscribeToSwarmInfoResponse,\n} from '@dxos/protocols/proto/dxos/devtools/host';\n\nexport const subscribeToNetworkStatus = ({ signalManager }: { signalManager: SignalManager }) =>\n new Stream<SubscribeToSignalStatusResponse>(({ next, close }) => {\n const update = () => {\n try {\n const status = signalManager.getStatus?.();\n next({ servers: status });\n } catch (err: any) {\n close(err);\n }\n };\n\n signalManager.statusChanged?.on(() => update());\n update();\n });\n\nexport const subscribeToSignal = ({ signalManager }: { signalManager: SignalManager }) =>\n new Stream<SignalResponse>(({ next }) => {\n const ctx = new Context();\n signalManager.onMessage.on(ctx, (message) => {\n next({\n message: {\n author: PublicKey.from(message.author.peerKey).asUint8Array(),\n recipient: PublicKey.from(message.recipient.peerKey).asUint8Array(),\n payload: message.payload,\n },\n receivedAt: new Date(),\n });\n });\n signalManager.swarmEvent.on(ctx, (swarmEvent) => {\n next({\n swarmEvent: swarmEvent.peerAvailable\n ? {\n peerAvailable: {\n peer: PublicKey.from(swarmEvent.peerAvailable.peer.peerKey).asUint8Array(),\n since: swarmEvent.peerAvailable.since,\n },\n }\n : { peerLeft: { peer: PublicKey.from(swarmEvent.peerLeft!.peer.peerKey).asUint8Array() } },\n topic: swarmEvent.topic.asUint8Array(),\n receivedAt: new Date(),\n });\n });\n return () => {\n return ctx.dispose();\n };\n });\n\nexport const subscribeToNetworkTopics = ({ networkManager }: { networkManager: SwarmNetworkManager }) =>\n new Stream<SubscribeToNetworkTopicsResponse>(({ next, close }) => {\n const update = () => {\n try {\n const topics = networkManager.topics;\n const labeledTopics = topics.map((topic) => ({\n topic,\n label: networkManager.getSwarm(topic)?.label ?? topic.toHex(),\n }));\n next({ topics: labeledTopics });\n } catch (err: any) {\n close(err);\n }\n };\n networkManager.topicsUpdated.on(update);\n\n update();\n });\n\nexport const subscribeToSwarmInfo = ({ networkManager }: { networkManager: SwarmNetworkManager }) =>\n new Stream<SubscribeToSwarmInfoResponse>(({ next }) => {\n const update = () => {\n const info = networkManager.connectionLog?.swarms;\n if (info) {\n next({ data: info });\n }\n };\n networkManager.connectionLog?.update.on(update);\n update();\n });\n\nexport const getNetworkPeers = (\n { networkManager }: { networkManager: SwarmNetworkManager },\n request: GetNetworkPeersRequest,\n): GetNetworkPeersResponse => {\n if (!request.topic) {\n throw new Error('Expected a network topic');\n }\n\n const map = networkManager.getSwarmMap(PublicKey.from(request.topic));\n return {\n peers: map?.peers.map((peer) => ({\n ...peer,\n connections: peer.connections.map((connection) => connection.asUint8Array()),\n })),\n };\n};\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type Space } from '@dxos/echo-pipeline';\nimport {\n type SubscribeToSpacesRequest,\n type SubscribeToSpacesResponse,\n} from '@dxos/protocols/proto/dxos/devtools/host';\nimport { type SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\n\nimport { type ServiceContext } from '../services';\n\nexport const subscribeToSpaces = (context: ServiceContext, { spaceKeys = [] }: SubscribeToSpacesRequest) => {\n return new Stream<SubscribeToSpacesResponse>(({ next }) => {\n let unsubscribe: () => void;\n\n const update = async () => {\n const spaces: Space[] = [...context.spaceManager!.spaces.values()];\n const filteredSpaces = spaces.filter(\n (space) => !spaceKeys?.length || spaceKeys.some((spaceKey) => spaceKey.equals(space.key)),\n );\n\n next({\n spaces: filteredSpaces.map((space): SubscribeToSpacesResponse.SpaceInfo => {\n const spaceMetadata = context.metadataStore.spaces.find((spaceMetadata: SpaceMetadata) =>\n spaceMetadata.key.equals(space.key),\n );\n\n return {\n key: space.key,\n isOpen: space.isOpen,\n timeframe: spaceMetadata?.dataTimeframe,\n genesisFeed: space.genesisFeedKey,\n controlFeed: space.controlFeedKey!, // TODO(dmaretskyi): Those keys may be missing.\n dataFeed: space.dataFeedKey!,\n };\n }),\n });\n };\n\n const timeout = setTimeout(async () => {\n await context.initialized.wait();\n unsubscribe = context.dataSpaceManager!.updated.on(() => update());\n\n // Send initial spaces.\n await update();\n });\n\n return () => {\n unsubscribe?.();\n clearTimeout(timeout);\n };\n });\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event as AsyncEvent } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type Config } from '@dxos/config';\nimport {\n type ClearSnapshotsRequest,\n type DevtoolsHost, // TODO(burdon): Rename DevtoolsService\n type EnableDebugLoggingRequest,\n type EnableDebugLoggingResponse,\n type Event,\n type GetConfigResponse,\n type GetNetworkPeersRequest,\n type GetNetworkPeersResponse,\n type GetSpaceSnapshotRequest,\n type GetSpaceSnapshotResponse,\n type ResetStorageRequest,\n type SaveSpaceSnapshotRequest,\n type SaveSpaceSnapshotResponse,\n type SubscribeToCredentialMessagesRequest,\n type SubscribeToCredentialMessagesResponse,\n type SubscribeToFeedBlocksRequest,\n type SubscribeToFeedBlocksResponse,\n type SubscribeToFeedsRequest,\n type SubscribeToFeedsResponse,\n type SubscribeToItemsRequest,\n type SubscribeToItemsResponse,\n type SubscribeToKeyringKeysRequest,\n type SubscribeToKeyringKeysResponse,\n type SubscribeToNetworkTopicsResponse,\n type SubscribeToSpacesRequest,\n type SubscribeToSpacesResponse,\n type SubscribeToSignalStatusResponse,\n type SignalResponse,\n type SubscribeToSwarmInfoResponse,\n type StorageInfo,\n type GetSnapshotsResponse,\n type SubscribeToMetadataResponse,\n type GetBlobsResponse,\n} from '@dxos/protocols/proto/dxos/devtools/host';\n\nimport { subscribeToFeedBlocks, subscribeToFeeds } from './feeds';\nimport { subscribeToKeyringKeys } from './keys';\nimport { subscribeToMetadata } from './metadata';\nimport { subscribeToNetworkStatus, subscribeToSignal, subscribeToSwarmInfo } from './network';\nimport { subscribeToSpaces } from './spaces';\nimport { type ServiceContext } from '../services';\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 async getConfig(request: void): Promise<GetConfigResponse> {\n return { config: JSON.stringify(this.params.config.values) }; // 😨\n }\n\n async getStorageInfo(): Promise<StorageInfo> {\n const storageUsage = (await this.params.context.storage.getDiskInfo?.()) ?? { used: 0 };\n\n const navigatorInfo = typeof navigator === 'object' ? await navigator.storage.estimate() : undefined;\n\n return {\n type: this.params.context.storage.type,\n storageUsage: storageUsage.used,\n originUsage: navigatorInfo?.usage ?? 0,\n usageQuota: navigatorInfo?.quota ?? 0,\n };\n }\n\n async getBlobs(): Promise<GetBlobsResponse> {\n return {\n blobs: await this.params.context.blobStore.list(),\n };\n }\n\n async getSnapshots(): Promise<GetSnapshotsResponse> {\n return {\n snapshots: [],\n };\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(this.params.context, 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({ signalManager: this.params.context.signalManager });\n }\n\n subscribeToSignal(): Stream<SignalResponse> {\n return subscribeToSignal({ signalManager: this.params.context.signalManager });\n }\n\n subscribeToSwarmInfo(): Stream<SubscribeToSwarmInfoResponse> {\n return subscribeToSwarmInfo({ networkManager: this.params.context.networkManager });\n }\n\n subscribeToMetadata(): Stream<SubscribeToMetadataResponse> {\n return subscribeToMetadata({ context: this.params.context });\n }\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { scheduleTask } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type Keyring } from '@dxos/keyring';\nimport { type SubscribeToKeyringKeysResponse } from '@dxos/protocols/proto/dxos/devtools/host';\n\nexport const subscribeToKeyringKeys = ({ keyring }: { keyring: Keyring }) =>\n new Stream<SubscribeToKeyringKeysResponse>(({ next, ctx }) => {\n const update = async () => {\n next({\n keys: await keyring.list(),\n });\n };\n keyring.keysUpdate.on(ctx, update);\n scheduleTask(ctx, update);\n });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type SubscribeToMetadataResponse } from '@dxos/protocols/proto/dxos/devtools/host';\n\nimport { type ServiceContext } from '../services';\n\nexport const subscribeToMetadata = ({ context }: { context: ServiceContext }) =>\n new Stream<SubscribeToMetadataResponse>(({ next, ctx }) => {\n context.metadataStore.update.on(ctx, (data) => next({ metadata: data }));\n next({ metadata: context.metadataStore.metadata });\n });\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { asyncTimeout } from '@dxos/async';\nimport { type ClientServices } from '@dxos/client-protocol';\nimport { getFirstStreamValue } from '@dxos/codec-protobuf';\nimport { type Config, type ConfigProto } from '@dxos/config';\nimport { credentialTypeFilter } from '@dxos/credentials';\nimport { invariant } from '@dxos/invariant';\nimport { type PublicKey } from '@dxos/keys';\nimport { STORAGE_VERSION } from '@dxos/protocols';\nimport {\n SpaceMember,\n type Device,\n type Identity,\n type LogEntry,\n type Metrics,\n type NetworkStatus,\n type Platform,\n type Space as SpaceProto,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type SubscribeToFeedsResponse } from '@dxos/protocols/proto/dxos/devtools/host';\nimport { type SwarmInfo } from '@dxos/protocols/proto/dxos/devtools/swarm';\nimport { type Epoch } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type Resource, type Span } from '@dxos/protocols/proto/dxos/tracing';\nimport { TRACE_PROCESSOR } from '@dxos/tracing';\n\nimport { DXOS_VERSION } from '../../version';\nimport { type ServiceContext } from '../services';\nimport { getPlatform } from '../services/platform';\nimport { type DataSpace } from '../spaces';\n\nconst DEFAULT_TIMEOUT = 1_000;\n\nexport type Diagnostics = {\n client: {\n config: ConfigProto;\n trace: TraceDiagnostic;\n };\n services: {\n trace: TraceDiagnostic;\n created: string;\n platform: Platform;\n config?: ConfigProto;\n client: {\n version: string;\n storage: {\n version: number;\n };\n };\n identity?: Identity;\n devices?: Device[];\n spaces?: SpaceStats[];\n networkStatus?: NetworkStatus;\n swarms?: SwarmInfo[];\n feeds?: Partial<SubscribeToFeedsResponse.Feed>[];\n metrics?: Metrics;\n storage?: { file: string; count: number }[];\n };\n};\n\nexport type TraceDiagnostic = {\n resources: Record<string, Resource>;\n spans: Span[];\n logs: LogEntry[];\n};\n\n// TODO(burdon): Normalize for ECHO/HALO.\nexport type SpaceStats = {\n key: PublicKey;\n properties?: {\n name: string;\n };\n db?: {\n objects: number;\n };\n metrics?: SpaceProto.Metrics & {\n startupTime?: number;\n };\n epochs?: (Epoch & { id?: PublicKey })[];\n members?: SpaceMember[];\n pipeline?: SpaceProto.PipelineState;\n};\n\n/**\n * Create diagnostics to provide snapshot of current system state.\n */\nexport const createDiagnostics = async (\n clientServices: Partial<ClientServices>,\n serviceContext: ServiceContext,\n config: Config,\n): Promise<Diagnostics['services']> => {\n const diagnostics: Diagnostics['services'] = {\n created: new Date().toISOString(),\n platform: getPlatform(),\n client: {\n version: DXOS_VERSION,\n storage: {\n version: STORAGE_VERSION,\n },\n },\n trace: TRACE_PROCESSOR.getDiagnostics(),\n };\n\n await Promise.all([\n (async () => {\n // Trace metrics.\n // TODO(burdon): Move here from logging service?\n invariant(clientServices.LoggingService, 'SystemService is not available.');\n diagnostics.metrics = await getFirstStreamValue(clientServices.LoggingService.queryMetrics({}), {\n timeout: DEFAULT_TIMEOUT,\n }).catch(() => undefined);\n })(),\n (async () => {\n diagnostics.storage = await asyncTimeout(getStorageDiagnostics(), DEFAULT_TIMEOUT).catch(() => undefined);\n })(),\n async () => {\n const identity = serviceContext.identityManager.identity;\n if (identity) {\n // Identity.\n diagnostics.identity = {\n identityKey: identity.identityKey,\n spaceKey: identity.space.key,\n profile: identity.profileDocument,\n };\n\n // Devices.\n const { devices } =\n (await getFirstStreamValue(clientServices.DevicesService!.queryDevices(), {\n timeout: DEFAULT_TIMEOUT,\n }).catch(() => undefined)) ?? {};\n diagnostics.devices = devices;\n\n // TODO(dmaretskyi): Add metrics for halo space.\n\n // Spaces.\n if (serviceContext.dataSpaceManager) {\n diagnostics.spaces = await Promise.all(\n Array.from(serviceContext.dataSpaceManager.spaces.values()).map((space) => getSpaceStats(space)) ?? [],\n );\n }\n\n // Feeds.\n const { feeds = [] } =\n (await getFirstStreamValue(clientServices.DevtoolsHost!.subscribeToFeeds({}), {\n timeout: DEFAULT_TIMEOUT,\n }).catch(() => undefined)) ?? {};\n diagnostics.feeds = feeds.map(({ feedKey, bytes, length }) => ({ feedKey, bytes, length }));\n\n // Signal servers.\n\n const status = await getFirstStreamValue(clientServices.NetworkService!.queryStatus(), {\n timeout: DEFAULT_TIMEOUT,\n }).catch(() => undefined);\n diagnostics.networkStatus = status;\n\n // Networking.\n\n diagnostics.swarms = serviceContext.networkManager.connectionLog?.swarms;\n }\n },\n ]);\n\n diagnostics.config = config.values;\n\n return diagnostics;\n};\n\nconst getSpaceStats = async (space: DataSpace): Promise<SpaceStats> => {\n const stats: SpaceStats = {\n key: space.key,\n metrics: space.metrics,\n\n epochs: space.inner.spaceState.credentials\n .filter(credentialTypeFilter('dxos.halo.credentials.Epoch'))\n .map((credential) => ({\n ...credential.subject.assertion,\n id: credential.id,\n })),\n\n members: Array.from(space.inner.spaceState.members.values()).map((member) => ({\n role: member.role,\n identity: {\n identityKey: member.key,\n profile: {\n displayName: member.assertion.profile?.displayName,\n },\n },\n presence:\n space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key)).length > 0\n ? SpaceMember.PresenceState.ONLINE\n : SpaceMember.PresenceState.OFFLINE,\n })),\n\n pipeline: {\n // TODO(burdon): Pick properties from credentials if needed.\n currentEpoch: space.automergeSpaceState.lastEpoch,\n appliedEpoch: space.automergeSpaceState.lastEpoch,\n\n controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),\n currentControlTimeframe: space.inner.controlPipeline.state.timeframe,\n targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,\n totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe,\n },\n };\n\n // TODO(burdon): Factor out.\n if (stats.metrics) {\n const { open, ready } = stats.metrics;\n stats.metrics.startupTime = open && ready && ready.getTime() - open.getTime();\n }\n\n return stats;\n};\n\nconst getStorageDiagnostics = async () => {\n if (typeof navigator === 'undefined' || !navigator.storage) {\n return undefined;\n }\n const map = new Map();\n const dir = await navigator.storage.getDirectory();\n for await (const filename of (dir as any)?.keys()) {\n const idx = filename.indexOf('-', filename.indexOf('-') + 1);\n if (idx === -1) {\n continue;\n }\n\n map.set(filename.slice(0, idx), (map.get(filename.slice(0, idx)) ?? 0) + 1);\n }\n\n return Array.from(map.entries())\n .sort((a, b) => b[1] - a[1])\n .map(([file, count]) => ({ file, count }));\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nexport const DXOS_VERSION = '0.7.2'; // {x-release-please-version}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Platform } from '@dxos/protocols/proto/dxos/client/services';\n\nexport const getPlatform = (): Platform => {\n if ((process as any).browser) {\n if (typeof window !== 'undefined') {\n // Browser.\n const { userAgent } = window.navigator;\n return {\n type: Platform.PLATFORM_TYPE.BROWSER,\n userAgent,\n uptime: Math.floor((Date.now() - window.performance.timeOrigin) / 1_000),\n };\n } else {\n // Shared worker.\n return {\n type: Platform.PLATFORM_TYPE.SHARED_WORKER,\n uptime: Math.floor((Date.now() - performance.timeOrigin) / 1_000),\n };\n }\n } else {\n // Node.\n const { platform, version, arch } = process;\n return {\n type: Platform.PLATFORM_TYPE.NODE,\n platform,\n arch,\n runtime: version,\n uptime: Math.floor(process.uptime()),\n memory: process.memoryUsage(),\n };\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Trigger } from '@dxos/async';\nimport { log } from '@dxos/log';\nimport { type SystemService } from '@dxos/protocols/proto/dxos/client/services';\n\nimport {\n type CollectDiagnosticsBroadcastSender,\n type CollectDiagnosticsBroadcastHandler,\n} from './diagnostics-collector';\n\nconst CHANNEL_NAME = 'dxos.diagnostics.broadcast';\n\nenum MessageType {\n PROBE = 'probe',\n PROBE_ACK = 'probe-ack',\n REQUEST_DIAGNOSTICS = 'request-diagnostics',\n RECEIVE_DIAGNOSTICS = 'receive-diagnostics',\n}\n\ninterface Message {\n type: MessageType;\n payload?: any;\n}\n\nexport const createCollectDiagnosticsBroadcastSender = (): CollectDiagnosticsBroadcastSender => {\n return {\n broadcastDiagnosticsRequest: async () => {\n let expectedResponse = MessageType.PROBE_ACK;\n let channel: BroadcastChannel | undefined;\n try {\n const trigger = new Trigger<Message>();\n channel = new BroadcastChannel(CHANNEL_NAME);\n channel.onmessage = (msg) => {\n if (expectedResponse === msg.data.type) {\n trigger.wake(msg.data);\n }\n };\n channel.postMessage({ type: MessageType.PROBE });\n await trigger.wait({ timeout: 200 });\n expectedResponse = MessageType.RECEIVE_DIAGNOSTICS;\n trigger.reset();\n channel.postMessage({ type: MessageType.REQUEST_DIAGNOSTICS });\n const diagnostics = await trigger.wait({ timeout: 5000 });\n return diagnostics.payload;\n } catch (e) {\n const errorDescription = e instanceof Error ? e.message : JSON.stringify(e);\n return { expectedResponse, errorDescription };\n } finally {\n safeClose(channel);\n }\n },\n };\n};\n\nexport const createCollectDiagnosticsBroadcastHandler = (\n systemService: SystemService,\n): CollectDiagnosticsBroadcastHandler => {\n let channel: BroadcastChannel | undefined;\n return {\n start: () => {\n channel = new BroadcastChannel(CHANNEL_NAME);\n channel.onmessage = async (message) => {\n try {\n if (message.data.type === MessageType.PROBE) {\n channel?.postMessage({ type: MessageType.PROBE_ACK });\n } else if (message.data.type === MessageType.REQUEST_DIAGNOSTICS) {\n const diagnostics = await systemService.getDiagnostics({});\n channel?.postMessage({\n type: MessageType.RECEIVE_DIAGNOSTICS,\n payload: diagnostics,\n });\n }\n } catch (error) {\n log.catch(error);\n }\n };\n },\n stop: () => {\n safeClose(channel);\n channel = undefined;\n },\n };\n};\n\nconst safeClose = (channel?: BroadcastChannel) => {\n try {\n channel?.close();\n } catch (e) {\n // ignored\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type ClientServicesProvider, ClientServicesProviderResource } from '@dxos/client-protocol';\nimport { type Config, ConfigResource } from '@dxos/config';\nimport { GetDiagnosticsRequest } from '@dxos/protocols/proto/dxos/client/services';\nimport { TRACE_PROCESSOR } from '@dxos/tracing';\nimport { type JsonKeyOptions, jsonKeyReplacer, nonNullable } from '@dxos/util';\n\nimport { createCollectDiagnosticsBroadcastSender } from './diagnostics-broadcast';\n\nconst GET_DIAGNOSTICS_RPC_TIMEOUT = 10_000;\n\nexport interface CollectDiagnosticsBroadcastSender {\n broadcastDiagnosticsRequest(): any;\n}\n\nexport interface CollectDiagnosticsBroadcastHandler {\n start(): void;\n stop(): void;\n}\n\nexport class DiagnosticsCollector {\n private static broadcastSender = createCollectDiagnosticsBroadcastSender();\n\n public static async collect(\n config: Config | Config[] = findConfigs(),\n services: ClientServicesProvider | null = findSystemServiceProvider(),\n options: JsonKeyOptions = {},\n ): Promise<any> {\n const serviceDiagnostics = await services?.services?.SystemService?.getDiagnostics(\n {\n keys: options.humanize\n ? GetDiagnosticsRequest.KEY_OPTION.HUMANIZE\n : options.truncate\n ? GetDiagnosticsRequest.KEY_OPTION.TRUNCATE\n : undefined,\n },\n { timeout: GET_DIAGNOSTICS_RPC_TIMEOUT },\n );\n\n const clientDiagnostics = {\n config,\n trace: TRACE_PROCESSOR.getDiagnostics(),\n };\n\n const diagnostics =\n serviceDiagnostics != null\n ? { client: clientDiagnostics, services: serviceDiagnostics }\n : {\n client: clientDiagnostics,\n broadcast: await this.broadcastSender.broadcastDiagnosticsRequest(),\n };\n\n return JSON.parse(JSON.stringify(diagnostics, jsonKeyReplacer(options)));\n }\n}\n\nconst findSystemServiceProvider = (): ClientServicesProvider | null => {\n const serviceProviders = TRACE_PROCESSOR.findResourcesByAnnotation(ClientServicesProviderResource);\n const providerResource = serviceProviders.find((r) => r.instance.deref()?.services?.SystemService != null);\n return providerResource?.instance?.deref() ?? null;\n};\n\nconst findConfigs = (): Config[] => {\n const configs = TRACE_PROCESSOR.findResourcesByAnnotation(ConfigResource);\n return configs.map((r) => r.instance.deref()).filter(nonNullable);\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Event, Trigger } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { verifyCredential, type CredentialSigner } from '@dxos/credentials';\nimport { type AuthProvider, type AuthVerifier } from '@dxos/echo-pipeline';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols/proto';\nimport { type ComplexSet } from '@dxos/util';\n\nconst Credential = schema.getCodecForType('dxos.halo.credentials.Credential');\n\nexport const createAuthProvider =\n (signer: CredentialSigner): AuthProvider =>\n async (nonce) => {\n const credential = await signer.createCredential({\n assertion: {\n '@type': 'dxos.halo.credentials.Auth',\n },\n subject: signer.getIssuer(),\n nonce,\n });\n\n return Credential.encode(credential);\n };\n\nexport type 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 get verifier(): AuthVerifier {\n return async (nonce, auth) => {\n const credential = Credential.decode(auth);\n log('authenticating...', { credential });\n\n const result = await verifyCredential(credential);\n if (result.kind === 'fail') {\n log('Invalid credential', { result });\n return false;\n }\n\n if (!credential.proof!.nonce || !Buffer.from(nonce).equals(credential.proof!.nonce)) {\n log('Invalid nonce', { nonce, credential });\n return false;\n }\n\n if (this._isTrustedKey(credential.issuer)) {\n log('key is trusted -- auth success', { key: credential.issuer });\n return true;\n }\n\n const trigger = new Trigger<boolean>();\n this._ctx.onDispose(() => {\n trigger.wake(false);\n });\n\n const clear = this._params.update.on(this._ctx, () => {\n if (this._isTrustedKey(credential.issuer)) {\n log('auth success', { key: credential.issuer });\n trigger.wake(true);\n } else {\n log('key is not currently in trusted set, waiting...', {\n key: credential.issuer,\n trusted: [...this._params.trustedKeysProvider()],\n });\n }\n });\n\n try {\n return await trigger.wait({ timeout: this._params.authTimeout });\n } catch {\n return false;\n } finally {\n clear();\n }\n };\n }\n\n private _isTrustedKey(deviceKey: PublicKey) {\n const deviceSet = this._params.trustedKeysProvider();\n return deviceSet.has(deviceKey);\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { decode as decodeCbor, encode as encodeCbor } from 'cbor-x';\n\nimport { Event, Mutex, scheduleMicroTask } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { EdgeConnectionClosedError, EdgeIdentityChangedError } from '@dxos/edge-client';\nimport { type FeedWrapper } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey, type SpaceId } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport { EdgeService } from '@dxos/protocols';\nimport { buf } from '@dxos/protocols/buf';\nimport {\n MessageSchema as RouterMessageSchema,\n type Message as RouterMessage,\n} from '@dxos/protocols/buf/dxos/edge/messenger_pb';\nimport type { FeedBlock, ProtocolMessage } from '@dxos/protocols/feed-replication';\nimport { ComplexMap, arrayToBuffer, bufferToArray, defaultMap, rangeFromTo } from '@dxos/util';\n\nexport type EdgeFeedReplicatorParams = {\n messenger: EdgeConnection;\n spaceId: SpaceId;\n};\n\nexport class EdgeFeedReplicator extends Resource {\n private readonly _messenger: EdgeConnection;\n\n @logInfo\n private readonly _spaceId: SpaceId;\n\n private readonly _feeds = new ComplexMap<PublicKey, FeedWrapper<any>>(PublicKey.hash);\n\n private _connectionCtx?: Context = undefined;\n private _connected = false;\n /**\n * Feed length at service.\n */\n private _remoteLength = new ComplexMap<PublicKey, number>(PublicKey.hash);\n\n /**\n * Protects against concurrent pushes so that remote length is updated consistently.\n */\n private _pushMutex = new ComplexMap<PublicKey, Mutex>(PublicKey.hash);\n\n constructor({ messenger, spaceId }: EdgeFeedReplicatorParams) {\n super();\n this._messenger = messenger;\n this._spaceId = spaceId;\n }\n\n protected override async _open(): Promise<void> {\n log('open');\n // TODO: handle reconnects\n this._ctx.onDispose(\n this._messenger.onMessage((message: RouterMessage) => {\n if (!message.serviceId) {\n return;\n }\n const [service, ...rest] = message.serviceId.split(':');\n if (service !== EdgeService.FEED_REPLICATOR) {\n return;\n }\n\n const [spaceId] = rest;\n if (spaceId !== this._spaceId) {\n log('spaceID mismatch', { spaceId, _spaceId: this._spaceId });\n return;\n }\n\n const payload = decodeCbor(message.payload!.value) as ProtocolMessage;\n log('receive', { from: message.source, feedKey: payload.feedKey, type: payload.type });\n this._onMessage(payload);\n }),\n );\n\n this._ctx.onDispose(\n this._messenger.onReconnected(() => {\n scheduleMicroTask(this._ctx, () => this._handleReconnect());\n }),\n );\n }\n\n private async _handleReconnect() {\n await this._resetConnection();\n if (this._messenger.isConnected) {\n this._startReplication();\n }\n }\n\n protected override async _close(): Promise<void> {\n log('close');\n await this._resetConnection();\n }\n\n private _startReplication() {\n this._connected = true;\n const connectionCtx = this._createConnectionContext();\n this._connectionCtx = connectionCtx;\n log('connection context created');\n scheduleMicroTask(connectionCtx, async () => {\n for (const feed of this._feeds.values()) {\n await this._replicateFeed(connectionCtx, feed);\n }\n });\n }\n\n private async _resetConnection() {\n log('resetConnection');\n this._connected = false;\n await this._connectionCtx?.dispose();\n this._connectionCtx = undefined;\n this._remoteLength.clear();\n }\n\n async addFeed(feed: FeedWrapper<any>) {\n log.info('addFeed', { key: feed.key, connected: this._connected, hasConnectionCtx: !!this._connectionCtx });\n this._feeds.set(feed.key, feed);\n\n if (this._connected && this._connectionCtx) {\n await this._replicateFeed(this._connectionCtx, feed);\n }\n }\n\n private _getPushMutex(key: PublicKey) {\n return defaultMap(this._pushMutex, key, () => new Mutex());\n }\n\n private async _replicateFeed(ctx: Context, feed: FeedWrapper<any>) {\n log('replicateFeed', { key: feed.key });\n await this._sendMessage({\n type: 'get-metadata',\n feedKey: feed.key.toHex(),\n });\n\n Event.wrap(feed.core as any, 'append').on(ctx, async () => {\n await this._pushBlocksIfNeeded(feed);\n });\n }\n\n private async _sendMessage(message: ProtocolMessage) {\n if (!this._connectionCtx) {\n log.info('message dropped because connection was disposed');\n return;\n }\n\n const logPayload =\n message.type === 'data' ? { feedKey: message.feedKey, blocks: message.blocks.map((b) => b.index) } : { message };\n log.info('sending message', logPayload);\n\n invariant(message.feedKey);\n const payloadValue = bufferToArray(encodeCbor(message));\n\n log('send', { type: message.type });\n await this._messenger.send(\n buf.create(RouterMessageSchema, {\n source: {\n identityKey: this._messenger.identityKey,\n peerKey: this._messenger.peerKey,\n },\n serviceId: `${EdgeService.FEED_REPLICATOR}:${this._spaceId}`,\n payload: { value: payloadValue },\n }),\n );\n }\n\n private _onMessage(message: ProtocolMessage) {\n if (!this._connectionCtx) {\n log.warn('received message after connection context was disposed');\n return;\n }\n scheduleMicroTask(this._connectionCtx, async () => {\n switch (message.type) {\n case 'metadata': {\n log.info('received metadata', { message });\n\n const feedKey = PublicKey.fromHex(message.feedKey);\n const feed = this._feeds.get(feedKey);\n if (!feed) {\n log.warn('Feed not found', { feedKey });\n return;\n }\n\n using _guard = await this._getPushMutex(feed.key).acquire();\n\n this._remoteLength.set(feedKey, message.length);\n\n if (message.length > feed.length) {\n await this._sendMessage({\n type: 'request',\n feedKey: feedKey.toHex(),\n range: { from: feed.length, to: message.length },\n });\n } else if (message.length < feed.length) {\n await this._pushBlocks(feed, message.length, feed.length);\n }\n\n break;\n }\n\n case 'data': {\n log.info('received data', { feed: message.feedKey, blocks: message.blocks.map((b) => b.index) });\n\n const feedKey = PublicKey.fromHex(message.feedKey);\n const feed = this._feeds.get(feedKey);\n if (!feed) {\n log.warn('Feed not found', { feedKey });\n return;\n }\n\n await this._integrateBlocks(feed, message.blocks);\n break;\n }\n\n default: {\n log.warn('Unknown message', { ...message });\n }\n }\n });\n }\n\n private async _pushBlocks(feed: FeedWrapper<any>, from: number, to: number) {\n log.info('pushing blocks', { feed: feed.key.toHex(), from, to });\n\n const blocks: FeedBlock[] = await Promise.all(\n rangeFromTo(from, to).map(async (index) => {\n const data = await feed.get(index, { valueEncoding: 'binary' });\n invariant(data instanceof Uint8Array);\n const proof = await feed.proof(index);\n\n return {\n index,\n data,\n nodes: proof.nodes,\n signature: proof.signature,\n } satisfies FeedBlock;\n }),\n );\n\n await this._sendMessage({\n type: 'data',\n feedKey: feed.key.toHex(),\n blocks,\n });\n this._remoteLength.set(feed.key, to);\n }\n\n private async _integrateBlocks(feed: FeedWrapper<any>, blocks: FeedBlock[]) {\n log.info('integrating blocks', { feed: feed.key.toHex(), blocks: blocks.length });\n\n for (const block of blocks) {\n if (feed.has(block.index)) {\n continue;\n }\n const blockBuffer = bufferizeBlock(block);\n\n await feed.putBuffer(\n block.index,\n blockBuffer.data,\n { nodes: blockBuffer.nodes, signature: blockBuffer.signature },\n null,\n );\n }\n }\n\n private async _pushBlocksIfNeeded(feed: FeedWrapper<any>) {\n using _ = await this._getPushMutex(feed.key).acquire();\n\n if (!this._remoteLength.has(feed.key)) {\n log('blocks not pushed because remote length is unknown');\n return;\n }\n\n const remoteLength = this._remoteLength.get(feed.key)!;\n if (remoteLength < feed.length) {\n await this._pushBlocks(feed, remoteLength, feed.length);\n }\n }\n\n private _createConnectionContext() {\n const connectionCtx = new Context({\n onError: async (err: any) => {\n if (connectionCtx !== this._connectionCtx) {\n return;\n }\n if (err instanceof EdgeIdentityChangedError || err instanceof EdgeConnectionClosedError) {\n log('resetting on reconnect');\n await this._resetConnection();\n } else {\n this._ctx.raise(err);\n }\n },\n });\n return connectionCtx;\n }\n}\n\n// hypercore requires buffers\nconst bufferizeBlock = (block: FeedBlock) => ({\n index: block.index,\n data: arrayToBuffer(block.data),\n nodes: block.nodes.map((node) => ({\n index: node.index,\n hash: arrayToBuffer(node.hash),\n size: node.size,\n })),\n signature: arrayToBuffer(block.signature),\n});\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, Mutex, scheduleTask, sleep, synchronized, trackLeaks } from '@dxos/async';\nimport { AUTH_TIMEOUT } from '@dxos/client-protocol';\nimport { Context, ContextDisposedError, cancelWithContext } from '@dxos/context';\nimport type { SpecificCredential } from '@dxos/credentials';\nimport { timed, warnAfterTimeout } from '@dxos/debug';\nimport {\n type EchoHost,\n type DatabaseRoot,\n createMappedFeedWriter,\n type MetadataStore,\n type Space,\n} from '@dxos/echo-pipeline';\nimport { SpaceDocVersion } from '@dxos/echo-protocol';\nimport type { EdgeConnection, EdgeHttpClient } from '@dxos/edge-client';\nimport { type FeedStore, type FeedWrapper } from '@dxos/feed-store';\nimport { failedInvariant } from '@dxos/invariant';\nimport { type Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { CancelledError, SystemError } from '@dxos/protocols';\nimport {\n type CreateEpochRequest,\n SpaceState,\n type Space as SpaceProto,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type SpaceCache } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport {\n AdmittedFeed,\n SpaceMember,\n type Credential,\n type Epoch,\n type ProfileDocument,\n} from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type GossipMessage } from '@dxos/protocols/proto/dxos/mesh/teleport/gossip';\nimport { type Gossip, type Presence } from '@dxos/teleport-extension-gossip';\nimport { Timeframe } from '@dxos/timeframe';\nimport { trace } from '@dxos/tracing';\nimport { CallbackCollection, ComplexSet, type AsyncCallback } from '@dxos/util';\n\nimport { AutomergeSpaceState } from './automerge-space-state';\nimport { type SigningContext } from './data-space-manager';\nimport { EdgeFeedReplicator } from './edge-feed-replicator';\nimport { runEpochMigration } from './epoch-migrations';\nimport { NotarizationPlugin } from './notarization-plugin';\nimport { TrustedKeySetAuthVerifier } from '../identity';\n\nexport type DataSpaceCallbacks = {\n /**\n * Called before transitioning to the ready state.\n */\n beforeReady?: () => Promise<void>;\n\n /**\n * Called after transitioning to the ready state.\n */\n afterReady?: () => Promise<void>;\n\n /**\n * Called before space gets closed.\n */\n beforeClose?: () => Promise<void>;\n};\n\nexport type DataSpaceParams = {\n initialState: SpaceState;\n inner: Space;\n metadataStore: MetadataStore;\n gossip: Gossip;\n presence: Presence;\n keyring: Keyring;\n feedStore: FeedStore<FeedMessage>;\n echoHost: EchoHost;\n signingContext: SigningContext;\n callbacks?: DataSpaceCallbacks;\n cache?: SpaceCache;\n edgeConnection?: EdgeConnection;\n edgeHttpClient?: EdgeHttpClient;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n activeEdgeNotarizationPollingInterval?: number;\n};\n\nexport type CreateEpochOptions = {\n migration?: CreateEpochRequest.Migration;\n newAutomergeRoot?: string;\n};\n\n@trackLeaks('open', 'close')\n@trace.resource()\nexport class DataSpace {\n private _ctx = new Context();\n @trace.info()\n private readonly _inner: Space;\n\n private readonly _gossip: Gossip;\n private readonly _presence: Presence;\n private readonly _keyring: Keyring;\n private readonly _feedStore: FeedStore<FeedMessage>;\n private readonly _metadataStore: MetadataStore;\n private readonly _signingContext: SigningContext;\n private readonly _notarizationPlugin: NotarizationPlugin;\n private readonly _callbacks: DataSpaceCallbacks;\n private readonly _cache?: SpaceCache = undefined;\n private readonly _echoHost: EchoHost;\n private readonly _edgeFeedReplicator?: EdgeFeedReplicator = undefined;\n\n // TODO(dmaretskyi): Move into Space?\n private readonly _automergeSpaceState = new AutomergeSpaceState((rootUrl) => this._onNewAutomergeRoot(rootUrl));\n\n private readonly _epochProcessingMutex = new Mutex();\n\n private _state = SpaceState.SPACE_CLOSED;\n\n private _databaseRoot: DatabaseRoot | null = null;\n\n /**\n * Error for _state === SpaceState.SPACE_ERROR.\n */\n public error: Error | undefined = undefined;\n\n public readonly authVerifier: TrustedKeySetAuthVerifier;\n public readonly stateUpdate = new Event();\n\n public readonly postOpen = new CallbackCollection<AsyncCallback<void>>();\n public readonly preClose = new CallbackCollection<AsyncCallback<void>>();\n\n public metrics: SpaceProto.Metrics = {};\n\n constructor(params: DataSpaceParams) {\n this._inner = params.inner;\n this._inner.stateUpdate.on(this._ctx, () => this.stateUpdate.emit());\n\n this._gossip = params.gossip;\n this._presence = params.presence;\n this._keyring = params.keyring;\n this._feedStore = params.feedStore;\n this._metadataStore = params.metadataStore;\n this._signingContext = params.signingContext;\n this._callbacks = params.callbacks ?? {};\n this._echoHost = params.echoHost;\n this._notarizationPlugin = new NotarizationPlugin({\n spaceId: this._inner.id,\n edgeClient: params.edgeHttpClient,\n edgeFeatures: params.edgeFeatures,\n activeEdgePollingInterval: params.activeEdgeNotarizationPollingInterval,\n });\n\n this.authVerifier = new TrustedKeySetAuthVerifier({\n trustedKeysProvider: () =>\n new ComplexSet(\n PublicKey.hash,\n Array.from(this._inner.spaceState.members.values())\n .filter((member) => member.role !== SpaceMember.Role.REMOVED)\n .map((member) => member.key),\n ),\n update: this._inner.stateUpdate,\n authTimeout: AUTH_TIMEOUT,\n });\n\n this._cache = params.cache;\n\n if (params.edgeConnection && params.edgeFeatures?.feedReplicator) {\n this._edgeFeedReplicator = new EdgeFeedReplicator({ messenger: params.edgeConnection, spaceId: this.id });\n }\n\n this._state = params.initialState;\n log('new state', { state: SpaceState[this._state] });\n }\n\n @trace.info()\n get id() {\n return this._inner.id;\n }\n\n @trace.info()\n get key() {\n return this._inner.key;\n }\n\n get isOpen() {\n return this._inner.isOpen;\n }\n\n @trace.info({ enum: SpaceState })\n get state(): SpaceState {\n return this._state;\n }\n\n // TODO(burdon): Can we mark this for debugging only?\n get inner() {\n return this._inner;\n }\n\n get presence() {\n return this._presence;\n }\n\n get notarizationPlugin() {\n return this._notarizationPlugin;\n }\n\n get cache() {\n return this._cache;\n }\n\n get automergeSpaceState() {\n return this._automergeSpaceState;\n }\n\n get databaseRoot(): DatabaseRoot | null {\n return this._databaseRoot;\n }\n\n @trace.info({ depth: null })\n private get _automergeInfo() {\n return {\n rootUrl: this._automergeSpaceState.rootUrl,\n lastEpoch: this._automergeSpaceState.lastEpoch,\n };\n }\n\n @synchronized\n async open() {\n if (this._state === SpaceState.SPACE_CLOSED) {\n await this._open();\n }\n }\n\n private async _open() {\n await this._presence.open();\n await this._gossip.open();\n await this._notarizationPlugin.open();\n await this._inner.spaceState.addCredentialProcessor(this._notarizationPlugin);\n await this._automergeSpaceState.open();\n await this._inner.spaceState.addCredentialProcessor(this._automergeSpaceState);\n\n if (this._edgeFeedReplicator) {\n this.inner.protocol.feedAdded.append(this._onFeedAdded);\n }\n\n await this._inner.open(new Context());\n await this._inner.startProtocol();\n\n await this._edgeFeedReplicator?.open();\n\n this._state = SpaceState.SPACE_CONTROL_ONLY;\n log('new state', { state: SpaceState[this._state] });\n this.stateUpdate.emit();\n this.metrics = {};\n this.metrics.open = new Date();\n\n await this.postOpen.callSerial();\n }\n\n @synchronized\n async close() {\n await this._close();\n }\n\n private async _close() {\n await this._callbacks.beforeClose?.();\n\n await this.preClose.callSerial();\n\n this._state = SpaceState.SPACE_CLOSED;\n log('new state', { state: SpaceState[this._state] });\n await this._ctx.dispose();\n this._ctx = new Context();\n\n if (this._edgeFeedReplicator) {\n this.inner.protocol.feedAdded.remove(this._onFeedAdded);\n }\n\n await this._edgeFeedReplicator?.close();\n\n await this.authVerifier.close();\n\n await this._inner.close();\n await this._inner.spaceState.removeCredentialProcessor(this._automergeSpaceState);\n await this._automergeSpaceState.close();\n await this._inner.spaceState.removeCredentialProcessor(this._notarizationPlugin);\n await this._notarizationPlugin.close();\n\n await this._presence.close();\n await this._gossip.close();\n }\n\n async postMessage(channel: string, message: any) {\n return this._gossip.postMessage(channel, message);\n }\n\n listen(channel: string, callback: (message: GossipMessage) => void) {\n return this._gossip.listen(channel, callback);\n }\n\n /**\n * Initialize the data pipeline in a separate task.\n */\n initializeDataPipelineAsync() {\n scheduleTask(this._ctx, async () => {\n try {\n this.metrics.pipelineInitBegin = new Date();\n await this.initializeDataPipeline();\n } catch (err) {\n if (err instanceof CancelledError || err instanceof ContextDisposedError) {\n log('data pipeline initialization cancelled', err);\n return;\n }\n\n log.error('Error initializing data pipeline', err);\n this._state = SpaceState.SPACE_ERROR;\n log('new state', { state: SpaceState[this._state] });\n this.error = err as Error;\n this.stateUpdate.emit();\n } finally {\n this.metrics.ready = new Date();\n }\n });\n }\n\n @trace.span({ showInBrowserTimeline: true })\n async initializeDataPipeline() {\n if (this._state !== SpaceState.SPACE_CONTROL_ONLY) {\n throw new SystemError('Invalid operation');\n }\n\n this._state = SpaceState.SPACE_INITIALIZING;\n log('new state', { state: SpaceState[this._state] });\n\n log('initializing control pipeline');\n await this._initializeAndReadControlPipeline();\n\n // Allow other tasks to run before loading the data pipeline.\n await sleep(1);\n\n const ready = this.stateUpdate.waitForCondition(() => this._state === SpaceState.SPACE_READY);\n\n log('initializing automerge root');\n this._automergeSpaceState.startProcessingRootDocs();\n\n // TODO(dmaretskyi): Change so `initializeDataPipeline` doesn't wait for the space to be READY, but rather any state with a valid root.\n log('waiting for space to be ready');\n await ready;\n log('space is ready');\n }\n\n private async _enterReadyState() {\n await this._callbacks.beforeReady?.();\n\n this._state = SpaceState.SPACE_READY;\n log('new state', { state: SpaceState[this._state] });\n this.stateUpdate.emit();\n\n await this._callbacks.afterReady?.();\n }\n\n @trace.span({ showInBrowserTimeline: true })\n private async _initializeAndReadControlPipeline() {\n await this._inner.controlPipeline.state.waitUntilReachedTargetTimeframe({\n ctx: this._ctx,\n timeout: 10_000,\n breakOnStall: false,\n });\n\n this.metrics.controlPipelineReady = new Date();\n\n await this._createWritableFeeds();\n log('writable feeds created');\n this.stateUpdate.emit();\n\n if (!this.notarizationPlugin.hasWriter) {\n this.notarizationPlugin.setWriter(\n createMappedFeedWriter<Credential, FeedMessage.Payload>(\n (credential) => ({\n credential: { credential },\n }),\n this._inner.controlPipeline.writer,\n ),\n );\n }\n }\n\n @timed(10_000)\n private async _createWritableFeeds() {\n const credentials: Credential[] = [];\n if (!this.inner.controlFeedKey) {\n const controlFeed = await this._feedStore.openFeed(await this._keyring.createKey(), { writable: true });\n await this.inner.setControlFeed(controlFeed);\n\n credentials.push(\n await this._signingContext.credentialSigner.createCredential({\n subject: controlFeed.key,\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n spaceKey: this.key,\n deviceKey: this._signingContext.deviceKey,\n identityKey: this._signingContext.identityKey,\n designation: AdmittedFeed.Designation.CONTROL,\n },\n }),\n );\n }\n if (!this.inner.dataFeedKey) {\n const dataFeed = await this._feedStore.openFeed(await this._keyring.createKey(), {\n writable: true,\n sparse: true,\n });\n await this.inner.setDataFeed(dataFeed);\n\n credentials.push(\n await this._signingContext.credentialSigner.createCredential({\n subject: dataFeed.key,\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n spaceKey: this.key,\n deviceKey: this._signingContext.deviceKey,\n identityKey: this._signingContext.identityKey,\n designation: AdmittedFeed.Designation.DATA,\n },\n }),\n );\n }\n\n if (credentials.length > 0) {\n try {\n log('will notarize credentials for feed admission', { count: credentials.length });\n // Never times out\n await this.notarizationPlugin.notarize({ ctx: this._ctx, credentials, timeout: 0 });\n\n log('credentials notarized');\n } catch (err) {\n log.error('error notarizing credentials for feed admission', err);\n throw err;\n }\n\n // Set this after credentials are notarized so that on failure we will retry.\n await this._metadataStore.setWritableFeedKeys(this.key, this.inner.controlFeedKey!, this.inner.dataFeedKey!);\n }\n }\n\n private _onNewAutomergeRoot(rootUrl: string) {\n log('loading automerge root doc for space', { space: this.key, rootUrl });\n\n const handle = this._echoHost.automergeRepo.find(rootUrl as any);\n\n // TODO(dmaretskyi): Make this single-threaded (but doc loading should still be parallel to not block epoch processing).\n queueMicrotask(async () => {\n try {\n await warnAfterTimeout(5_000, 'Automerge root doc load timeout (DataSpace)', async () => {\n await cancelWithContext(this._ctx, handle.whenReady());\n });\n if (this._ctx.disposed) {\n return;\n }\n\n // Ensure only one root is processed at a time.\n using _guard = await this._epochProcessingMutex.acquire();\n\n // Attaching space keys to legacy documents.\n const doc = handle.docSync() ?? failedInvariant();\n if (!doc.access?.spaceKey) {\n handle.change((doc: any) => {\n doc.access = { spaceKey: this.key.toHex() };\n });\n }\n\n // TODO(dmaretskyi): Close roots.\n // TODO(dmaretskyi): How do we handle changing to the next EPOCH?\n const root = await this._echoHost.openSpaceRoot(this.id, handle.url);\n\n // NOTE: Make sure this assignment happens synchronously together with the state change.\n this._databaseRoot = root;\n if (root.getVersion() !== SpaceDocVersion.CURRENT) {\n this._state = SpaceState.SPACE_REQUIRES_MIGRATION;\n this.stateUpdate.emit();\n } else if (this._state !== SpaceState.SPACE_READY) {\n await this._enterReadyState();\n } else {\n this.stateUpdate.emit();\n }\n } catch (err) {\n if (err instanceof ContextDisposedError) {\n return;\n }\n log.warn('error loading automerge root doc', { space: this.key, rootUrl, err });\n }\n });\n }\n\n // TODO(dmaretskyi): Use profile from signing context.\n async updateOwnProfile(profile: ProfileDocument) {\n const credential = await this._signingContext.credentialSigner.createCredential({\n subject: this._signingContext.identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.MemberProfile',\n profile,\n },\n });\n await this.inner.controlPipeline.writer.write({ credential: { credential } });\n }\n\n async createEpoch(options?: CreateEpochOptions): Promise<CreateEpochResult | null> {\n const ctx = this._ctx.derive();\n\n // Preserving existing behavior.\n if (!options?.migration) {\n return null;\n }\n\n const { newRoot } = await runEpochMigration(ctx, {\n echoHost: this._echoHost,\n spaceId: this.id,\n spaceKey: this.key,\n migration: options.migration,\n currentRoot: this._automergeSpaceState.rootUrl ?? null,\n newAutomergeRoot: options.newAutomergeRoot,\n });\n\n const epoch: Epoch = {\n previousId: this._automergeSpaceState.lastEpoch?.id,\n number: (this._automergeSpaceState.lastEpoch?.subject.assertion.number ?? -1) + 1,\n timeframe: this._automergeSpaceState.lastEpoch?.subject.assertion.timeframe ?? new Timeframe(),\n automergeRoot: newRoot ?? this._automergeSpaceState.rootUrl,\n };\n\n const credential = (await this._signingContext.credentialSigner.createCredential({\n subject: this.key,\n assertion: {\n '@type': 'dxos.halo.credentials.Epoch',\n ...epoch,\n },\n })) as SpecificCredential<Epoch>;\n\n const receipt = await this.inner.controlPipeline.writer.write({\n credential: { credential },\n });\n\n const timeframe = new Timeframe([[receipt.feedKey, receipt.seq]]);\n await this.inner.controlPipeline.state.waitUntilTimeframe(timeframe);\n await this._echoHost.updateIndexes();\n\n return { credential, timeframe };\n }\n\n @synchronized\n async activate() {\n if (![SpaceState.SPACE_CLOSED, SpaceState.SPACE_INACTIVE].includes(this._state)) {\n return;\n }\n\n await this._metadataStore.setSpaceState(this.key, SpaceState.SPACE_ACTIVE);\n await this._open();\n this.initializeDataPipelineAsync();\n }\n\n @synchronized\n async deactivate() {\n if (this._state === SpaceState.SPACE_INACTIVE) {\n return;\n }\n // Unregister from data service.\n await this._metadataStore.setSpaceState(this.key, SpaceState.SPACE_INACTIVE);\n if (this._state !== SpaceState.SPACE_CLOSED) {\n await this._close();\n }\n this._state = SpaceState.SPACE_INACTIVE;\n log('new state', { state: SpaceState[this._state] });\n this.stateUpdate.emit();\n }\n\n getEdgeReplicationSetting() {\n return this._metadataStore.getSpaceEdgeReplicationSetting(this.key);\n }\n\n private _onFeedAdded = async (feed: FeedWrapper<any>) => {\n await this._edgeFeedReplicator!.addFeed(feed);\n };\n}\n\ntype CreateEpochResult = {\n credential: SpecificCredential<Epoch>;\n timeframe: Timeframe;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { Resource, type Context } from '@dxos/context';\nimport { type CredentialProcessor, type SpecificCredential, checkCredentialType } from '@dxos/credentials';\nimport { type Credential, type Epoch } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nexport class AutomergeSpaceState extends Resource implements CredentialProcessor {\n public rootUrl: string | undefined = undefined;\n public lastEpoch: SpecificCredential<Epoch> | undefined = undefined;\n\n public readonly onNewEpoch = new Event<SpecificCredential<Epoch>>();\n\n private _isProcessingRootDocs = false;\n\n constructor(private readonly _onNewRoot: (rootUrl: string) => void) {\n super();\n }\n\n protected override async _open(ctx: Context): Promise<void> {}\n\n protected override async _close(ctx: Context): Promise<void> {\n this._isProcessingRootDocs = false;\n }\n\n async processCredential(credential: Credential) {\n if (!checkCredentialType(credential, 'dxos.halo.credentials.Epoch')) {\n return;\n }\n\n this.lastEpoch = credential;\n if (credential.subject.assertion.automergeRoot) {\n this.rootUrl = credential.subject.assertion.automergeRoot;\n\n if (this._isProcessingRootDocs) {\n this._onNewRoot(this.rootUrl);\n }\n }\n\n this.onNewEpoch.emit(credential);\n }\n\n startProcessingRootDocs() {\n if (this._isProcessingRootDocs) {\n return;\n }\n\n if (this.rootUrl) {\n this._onNewRoot(this.rootUrl);\n }\n this._isProcessingRootDocs = true;\n }\n\n async ensureEpochInitialized() {\n await this.onNewEpoch.waitForCondition(() => !!this.lastEpoch);\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport type { AutomergeUrl } from '@dxos/automerge/automerge-repo';\nimport { type Context } from '@dxos/context';\nimport { migrateDocument } from '@dxos/echo-db';\nimport {\n convertLegacyReferences,\n convertLegacySpaceRootDoc,\n findInlineObjectOfType,\n type EchoHost,\n} from '@dxos/echo-pipeline';\nimport { SpaceDocVersion, type SpaceDoc } from '@dxos/echo-protocol';\nimport { TYPE_PROPERTIES } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport type { PublicKey, SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { CreateEpochRequest } from '@dxos/protocols/proto/dxos/client/services';\n\nexport type MigrationContext = {\n echoHost: EchoHost;\n\n spaceId: SpaceId;\n /**\n * @deprecated Remove.\n */\n spaceKey: PublicKey;\n migration: CreateEpochRequest.Migration;\n currentRoot: string | null;\n\n /**\n * For set automerge root migration type.\n */\n newAutomergeRoot?: string;\n};\n\nexport type MigrationResult = {\n newRoot?: string;\n};\n\nconst LOAD_DOC_TIMEOUT = 10_000;\n\nexport const runEpochMigration = async (ctx: Context, context: MigrationContext): Promise<MigrationResult> => {\n switch (context.migration) {\n case CreateEpochRequest.Migration.INIT_AUTOMERGE: {\n const document = context.echoHost.createDoc();\n await context.echoHost.flush();\n return { newRoot: document.url };\n }\n case CreateEpochRequest.Migration.PRUNE_AUTOMERGE_ROOT_HISTORY: {\n if (!context.currentRoot) {\n throw new Error('Space does not have an automerge root');\n }\n const rootHandle = await context.echoHost.loadDoc(ctx, context.currentRoot as AutomergeUrl, {\n timeout: LOAD_DOC_TIMEOUT,\n });\n\n const newRoot = context.echoHost.createDoc(rootHandle.docSync());\n await context.echoHost.flush();\n return { newRoot: newRoot.url };\n }\n case CreateEpochRequest.Migration.FRAGMENT_AUTOMERGE_ROOT: {\n log.info('Fragmenting');\n\n const currentRootUrl = context.currentRoot;\n const rootHandle = await context.echoHost.loadDoc<SpaceDoc>(ctx, currentRootUrl as any, {\n timeout: LOAD_DOC_TIMEOUT,\n });\n\n // Find properties object.\n const objects = Object.entries((rootHandle.docSync() as SpaceDoc).objects!);\n const properties = findInlineObjectOfType(rootHandle.docSync() as SpaceDoc, TYPE_PROPERTIES);\n const otherObjects = objects.filter(([key]) => key !== properties?.[0]);\n invariant(properties, 'Properties not found');\n\n // Create a new space doc with the properties object.\n const newRoot = context.echoHost.createDoc({\n ...rootHandle.docSync(),\n objects: Object.fromEntries([properties]),\n });\n invariant(typeof newRoot.url === 'string' && newRoot.url.length > 0);\n\n // Create new automerge documents for all objects.\n const newLinks: [string, AutomergeUrl][] = [];\n for (const [id, objData] of otherObjects) {\n const handle = context.echoHost.createDoc<SpaceDoc>({\n version: SpaceDocVersion.CURRENT,\n access: {\n spaceKey: context.spaceKey.toHex(),\n },\n objects: {\n [id]: objData,\n },\n });\n newLinks.push([id, handle.url]);\n }\n newRoot.change((doc: SpaceDoc) => {\n doc.links ??= {};\n for (const [id, url] of newLinks) {\n doc.links[id] = url;\n }\n });\n\n await context.echoHost.flush();\n return {\n newRoot: newRoot.url,\n };\n }\n case CreateEpochRequest.Migration.MIGRATE_REFERENCES_TO_DXN: {\n const currentRootUrl = context.currentRoot;\n const rootHandle = await context.echoHost.loadDoc<SpaceDoc>(ctx, currentRootUrl as any, {\n timeout: LOAD_DOC_TIMEOUT,\n });\n invariant(rootHandle.docSync(), 'Root doc not found');\n\n const newRootContent = await convertLegacySpaceRootDoc(structuredClone(rootHandle.docSync()!));\n\n for (const [id, url] of Object.entries(newRootContent.links ?? {})) {\n try {\n const handle = await context.echoHost.loadDoc(ctx, url as any, { timeout: LOAD_DOC_TIMEOUT });\n invariant(handle.docSync());\n const newDoc = await convertLegacyReferences(structuredClone(handle.docSync()!));\n const migratedDoc = migrateDocument(handle.docSync(), newDoc);\n const newHandle = context.echoHost.createDoc(migratedDoc, { preserveHistory: true });\n newRootContent.links![id] = newHandle.url;\n } catch (err) {\n log.warn('Failed to migrate reference', { id, url, error: err });\n delete newRootContent.links![id];\n }\n }\n\n const migratedRoot = migrateDocument(rootHandle.docSync(), newRootContent);\n const newRoot = context.echoHost.createDoc(migratedRoot, { preserveHistory: true });\n\n await context.echoHost.flush();\n return {\n newRoot: newRoot.url,\n };\n }\n // TODO(dmaretskyi): This path doesn't seem to fit here. This is not a migration.\n case CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT: {\n invariant(context.newAutomergeRoot);\n\n // Defensive programming - it should be the responsibility of the caller to flush the new root.\n await context.echoHost.flush();\n return {\n newRoot: context.newAutomergeRoot,\n };\n }\n }\n\n return {};\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { DeferredTask, Event, scheduleTask, sleep, TimeoutError, Trigger, scheduleMicroTask } from '@dxos/async';\nimport { type Context, rejectOnDispose, Resource } from '@dxos/context';\nimport { type CredentialProcessor, verifyCredential } from '@dxos/credentials';\nimport { type EdgeHttpClient } from '@dxos/edge-client';\nimport { type FeedWriter } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { type SpaceId } from '@dxos/keys';\nimport { logInfo, log } from '@dxos/log';\nimport { EdgeCallFailedError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type NotarizationService, type NotarizeRequest } from '@dxos/protocols/proto/dxos/mesh/teleport/notarization';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\nimport { ComplexMap, ComplexSet, entry } from '@dxos/util';\n\nconst DEFAULT_RETRY_TIMEOUT = 1_000;\n\nconst DEFAULT_SUCCESS_DELAY = 1_000;\n\nconst DEFAULT_NOTARIZE_TIMEOUT = 10_000;\n\nconst DEFAULT_ACTIVE_EDGE_POLLING_INTERVAL = 3_000;\n\nconst MAX_EDGE_RETRIES = 2;\n\nconst WRITER_NOT_SET_ERROR_CODE = 'WRITER_NOT_SET';\n\nconst credentialCodec = schema.getCodecForType('dxos.halo.credentials.Credential');\n\nexport type NotarizationPluginParams = {\n spaceId: SpaceId;\n edgeClient?: EdgeHttpClient;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n activeEdgePollingInterval?: number;\n};\n\nexport type NotarizeParams = {\n /**\n * For cancellation.\n */\n ctx?: Context;\n\n /**\n * Credentials to notarize.\n */\n credentials: Credential[];\n\n /**\n * Timeout for the whole notarization process.\n * Set to 0 to disable.\n * @default {@link DEFAULT_NOTARIZE_TIMEOUT}\n */\n timeout?: number;\n\n /**\n * Retry timeout.\n * @default {@link DEFAULT_RETRY_TIMEOUT}\n */\n retryTimeout?: number;\n\n /**\n * Minimum wait time after a peer confirms successful notarization before attempting with a new peer.\n * This is to avoid spamming peers with notarization requests.\n * @default {@link DEFAULT_SUCCESS_DELAY}\n */\n successDelay?: number;\n\n /**\n * A random amount of time before making or retrying an edge request to help prevent large bursts of requests.\n */\n edgeRetryJitter?: number;\n};\n\n/**\n * See NotarizationService proto.\n */\nexport class NotarizationPlugin extends Resource implements CredentialProcessor {\n private readonly _extensionOpened = new Event();\n\n private _writer: FeedWriter<Credential> | undefined;\n private readonly _extensions = new Set<NotarizationTeleportExtension>();\n private readonly _processedCredentials = new ComplexSet<PublicKey>(PublicKey.hash);\n private readonly _processCredentialsTriggers = new ComplexMap<PublicKey, Trigger>(PublicKey.hash);\n\n private _activeEdgePollingIntervalHandle: any | undefined = undefined;\n private readonly _activeEdgePollingInterval: number;\n\n @logInfo\n private readonly _spaceId: SpaceId;\n\n private readonly _edgeClient: EdgeHttpClient | undefined;\n\n constructor(params: NotarizationPluginParams) {\n super();\n this._spaceId = params.spaceId;\n this._activeEdgePollingInterval = params.activeEdgePollingInterval ?? DEFAULT_ACTIVE_EDGE_POLLING_INTERVAL;\n if (params.edgeClient && params.edgeFeatures?.feedReplicator) {\n this._edgeClient = params.edgeClient;\n }\n }\n\n setActiveEdgePollingEnabled(enabled: boolean) {\n invariant(this.isOpen);\n const client = this._edgeClient;\n invariant(client);\n if (enabled && !this._activeEdgePollingIntervalHandle) {\n this._activeEdgePollingIntervalHandle = setInterval(() => {\n if (this._writer) {\n this._notarizePendingEdgeCredentials(client, this._writer);\n }\n }, this._activeEdgePollingInterval);\n } else if (!enabled && this._activeEdgePollingIntervalHandle) {\n clearInterval(this._activeEdgePollingIntervalHandle);\n this._activeEdgePollingIntervalHandle = undefined;\n }\n }\n\n get hasWriter() {\n return !!this._writer;\n }\n\n protected override async _open() {\n if (this._edgeClient && this._writer) {\n this._notarizePendingEdgeCredentials(this._edgeClient, this._writer);\n }\n }\n\n protected override async _close() {\n if (this._activeEdgePollingIntervalHandle) {\n clearInterval(this._activeEdgePollingIntervalHandle);\n this._activeEdgePollingIntervalHandle = undefined;\n }\n await this._ctx.dispose();\n }\n\n /**\n * Request credentials to be notarized.\n */\n async notarize({\n ctx: opCtx,\n credentials,\n timeout = DEFAULT_NOTARIZE_TIMEOUT,\n retryTimeout = DEFAULT_RETRY_TIMEOUT,\n successDelay = DEFAULT_SUCCESS_DELAY,\n edgeRetryJitter,\n }: NotarizeParams) {\n log('notarize', { credentials });\n invariant(\n credentials.every((credential) => credential.id),\n 'Credentials must have an id',\n );\n\n const errors = new Trigger();\n const ctx = this._ctx.derive({\n onError: (err) => {\n log.warn('Notarization error', { err });\n void ctx.dispose();\n errors.throw(err);\n },\n });\n opCtx?.onDispose(() => ctx.dispose());\n\n if (timeout !== 0) {\n this._scheduleTimeout(ctx, errors, timeout);\n }\n\n const allNotarized = Promise.all(credentials.map((credential) => this._waitUntilProcessed(credential.id!)));\n\n this._tryNotarizeCredentialsWithPeers(ctx, credentials, { retryTimeout, successDelay });\n\n if (this._edgeClient) {\n this._tryNotarizeCredentialsWithEdge(ctx, this._edgeClient, credentials, {\n retryTimeout,\n successDelay,\n jitter: edgeRetryJitter,\n });\n }\n\n try {\n await Promise.race([rejectOnDispose(ctx), allNotarized, errors.wait()]);\n log('done');\n } finally {\n await ctx.dispose();\n }\n }\n\n private _tryNotarizeCredentialsWithPeers(\n ctx: Context,\n credentials: Credential[],\n { retryTimeout, successDelay }: NotarizationTimeouts,\n ) {\n const peersTried = new Set<NotarizationTeleportExtension>();\n\n // Repeatable task that tries to notarize credentials with one of the available peers.\n const notarizeTask = new DeferredTask(ctx, async () => {\n try {\n if (this._extensions.size === 0) {\n return; // No peers to try.\n }\n\n // Pick a peer that we haven't tried yet.\n const peer = [...this._extensions].find((peer) => !peersTried.has(peer));\n if (!peer) {\n log.info('Exhausted all peers to notarize with', { retryIn: retryTimeout });\n peersTried.clear();\n scheduleTask(ctx, () => notarizeTask.schedule(), retryTimeout); // retry with all peers again\n return;\n }\n\n peersTried.add(peer);\n log('try notarizing', { peer: peer.localPeerId, credentialId: credentials.map((credential) => credential.id) });\n await peer.rpc.NotarizationService.notarize({\n credentials: credentials.filter((credential) => !this._processedCredentials.has(credential.id!)),\n });\n log('success');\n\n await sleep(successDelay); // wait before trying with a new peer\n } catch (err: any) {\n if (!ctx.disposed && !err.message.includes(WRITER_NOT_SET_ERROR_CODE)) {\n log.info('error notarizing (recoverable)', err);\n }\n notarizeTask.schedule(); // retry immediately with next peer\n }\n });\n\n notarizeTask.schedule();\n this._extensionOpened.on(ctx, () => notarizeTask.schedule());\n }\n\n private _tryNotarizeCredentialsWithEdge(\n ctx: Context,\n client: EdgeHttpClient,\n credentials: Credential[],\n timeouts: NotarizationTimeouts & { jitter?: number },\n ) {\n const encodedCredentials = credentials.map((credential) => {\n const binary = credentialCodec.encode(credential);\n return Buffer.from(binary).toString('base64');\n });\n scheduleTask(ctx, async () => {\n try {\n await client.notarizeCredentials(\n this._spaceId,\n { credentials: encodedCredentials },\n { retry: { count: MAX_EDGE_RETRIES, timeout: timeouts.retryTimeout, jitter: timeouts.jitter } },\n );\n\n log('edge notarization success');\n } catch (error: any) {\n handleEdgeError(error);\n }\n });\n }\n\n /**\n * Called with credentials arriving from the control pipeline.\n */\n async processCredential(credential: Credential) {\n if (!credential.id) {\n return;\n }\n this._processCredentialsTriggers.get(credential.id)?.wake();\n this._processedCredentials.add(credential.id);\n this._processCredentialsTriggers.delete(credential.id);\n }\n\n setWriter(writer: FeedWriter<Credential>) {\n invariant(!this._writer, 'Writer already set.');\n this._writer = writer;\n if (this._edgeClient) {\n this._notarizePendingEdgeCredentials(this._edgeClient, writer);\n }\n }\n\n /**\n * The method is used only for adding agent feeds to spaces.\n * When an agent is created we can admit them into all the existing spaces. In case the operation fails\n * this method will fix it on the next space open.\n * Given how rarely this happens there's no need to poll the endpoint.\n */\n private _notarizePendingEdgeCredentials(client: EdgeHttpClient, writer: FeedWriter<Credential>) {\n scheduleMicroTask(this._ctx, async () => {\n try {\n const response = await client.getCredentialsForNotarization(this._spaceId, {\n retry: { count: MAX_EDGE_RETRIES },\n });\n\n const credentials = response.awaitingNotarization.credentials;\n if (!credentials.length) {\n log('edge did not return credentials for notarization');\n return;\n }\n\n log('got edge credentials for notarization', { count: credentials.length });\n\n const decodedCredentials = credentials.map((credential) => {\n const binary = Buffer.from(credential, 'base64');\n return credentialCodec.decode(binary);\n });\n\n await this._notarizeCredentials(writer, decodedCredentials);\n\n log.info('notarized edge credentials', { count: decodedCredentials.length });\n } catch (error: any) {\n handleEdgeError(error);\n }\n });\n }\n\n private async _waitUntilProcessed(id: PublicKey) {\n if (this._processedCredentials.has(id)) {\n return;\n }\n await entry(this._processCredentialsTriggers, id).orInsert(new Trigger()).value.wait();\n }\n\n /**\n * Requests from other peers to notarize credentials.\n */\n private async _onNotarize(request: NotarizeRequest) {\n if (!this._writer) {\n throw new Error(WRITER_NOT_SET_ERROR_CODE);\n }\n await this._notarizeCredentials(this._writer, request.credentials ?? []);\n }\n\n private async _notarizeCredentials(writer: FeedWriter<Credential>, credentials: Credential[]) {\n for (const credential of credentials) {\n invariant(credential.id, 'Credential must have an id');\n if (this._processedCredentials.has(credential.id)) {\n continue;\n }\n const verificationResult = await verifyCredential(credential);\n if (verificationResult.kind === 'fail') {\n throw new Error(`Credential verification failed: ${verificationResult.errors.join('\\n')}.`);\n }\n await writer.write(credential);\n }\n }\n\n createExtension() {\n const extension = new NotarizationTeleportExtension({\n onOpen: async () => {\n log('extension opened', { peer: extension.localPeerId });\n this._extensions.add(extension);\n this._extensionOpened.emit();\n },\n onClose: async () => {\n log('extension closed', { peer: extension.localPeerId });\n this._extensions.delete(extension);\n },\n onNotarize: this._onNotarize.bind(this),\n });\n return extension;\n }\n\n private _scheduleTimeout(ctx: Context, errors: Trigger, timeout: number) {\n scheduleTask(\n ctx,\n () => {\n log.warn('Notarization timeout', {\n timeout,\n peers: Array.from(this._extensions).map((extension) => extension.remotePeerId),\n });\n void ctx.dispose();\n errors.throw(new TimeoutError(timeout, 'Notarization timed out'));\n },\n timeout,\n );\n }\n}\n\nconst handleEdgeError = (error: any) => {\n if (!(error instanceof EdgeCallFailedError) || error.errorData) {\n log.catch(error);\n } else {\n log.info('Edge notarization failure', { reason: error.reason });\n }\n};\n\nexport type NotarizationTeleportExtensionParams = {\n onOpen: () => Promise<void>;\n onClose: () => Promise<void>;\n onNotarize: (request: NotarizeRequest) => Promise<void>;\n};\n\nexport class NotarizationTeleportExtension extends RpcExtension<Services, Services> {\n constructor(private readonly _params: NotarizationTeleportExtensionParams) {\n super({\n requested: {\n NotarizationService: schema.getService('dxos.mesh.teleport.notarization.NotarizationService'),\n },\n exposed: {\n NotarizationService: schema.getService('dxos.mesh.teleport.notarization.NotarizationService'),\n },\n });\n }\n\n protected async getHandlers(): Promise<Services> {\n return {\n NotarizationService: {\n notarize: async (request) => {\n await this._params.onNotarize(request);\n },\n },\n };\n }\n\n override async onOpen(ctx: ExtensionContext) {\n await super.onOpen(ctx);\n await this._params.onOpen();\n }\n\n override async onClose(err?: Error | undefined) {\n await this._params.onClose();\n await super.onClose(err);\n }\n}\n\ntype NotarizationTimeouts = {\n retryTimeout: number;\n successDelay: number;\n};\n\ntype Services = {\n NotarizationService: NotarizationService;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { AUTH_TIMEOUT, LOAD_CONTROL_FEEDS_TIMEOUT } from '@dxos/client-protocol';\nimport { type Context } from '@dxos/context';\nimport {\n DeviceStateMachine,\n type CredentialSigner,\n createCredentialSignerWithKey,\n createCredentialSignerWithChain,\n ProfileStateMachine,\n} from '@dxos/credentials';\nimport { type Signer } from '@dxos/crypto';\nimport { type Space } from '@dxos/echo-pipeline';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { writeMessages, type FeedWrapper } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport {\n AdmittedFeed,\n type DeviceProfileDocument,\n type ProfileDocument,\n type Credential,\n} from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type DeviceAdmissionRequest } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type Presence } from '@dxos/teleport-extension-gossip';\nimport { Timeframe } from '@dxos/timeframe';\nimport { trace } from '@dxos/tracing';\nimport { type ComplexMap, ComplexSet } from '@dxos/util';\n\nimport { TrustedKeySetAuthVerifier } from './authenticator';\nimport { DefaultSpaceStateMachine } from './default-space-state-machine';\nimport { EdgeFeedReplicator } from '../spaces';\n\nexport type IdentityParams = {\n identityKey: PublicKey;\n deviceKey: PublicKey;\n signer: Signer;\n space: Space;\n presence?: Presence;\n\n edgeConnection?: EdgeConnection;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n};\n\n/**\n * Agent identity manager, which includes the agent's Halo space.\n */\n@trace.resource()\nexport class Identity {\n public readonly space: Space;\n private readonly _signer: Signer;\n private readonly _presence?: Presence;\n private readonly _deviceStateMachine: DeviceStateMachine;\n private readonly _profileStateMachine: ProfileStateMachine;\n private readonly _defaultSpaceStateMachine: DefaultSpaceStateMachine;\n private readonly _edgeFeedReplicator?: EdgeFeedReplicator = undefined;\n\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(params: IdentityParams) {\n this.space = params.space;\n this._signer = params.signer;\n this._presence = params.presence;\n\n this.identityKey = params.identityKey;\n this.deviceKey = params.deviceKey;\n\n log.trace('dxos.halo.device', { deviceKey: params.deviceKey });\n\n this._deviceStateMachine = new DeviceStateMachine({\n identityKey: this.identityKey,\n deviceKey: this.deviceKey,\n onUpdate: () => this.stateUpdate.emit(),\n });\n this._profileStateMachine = new ProfileStateMachine({\n identityKey: this.identityKey,\n onUpdate: () => this.stateUpdate.emit(),\n });\n this._defaultSpaceStateMachine = new DefaultSpaceStateMachine({\n identityKey: this.identityKey,\n onUpdate: () => this.stateUpdate.emit(),\n });\n\n this.authVerifier = new TrustedKeySetAuthVerifier({\n trustedKeysProvider: () => new ComplexSet(PublicKey.hash, this.authorizedDeviceKeys.keys()),\n update: this.stateUpdate,\n authTimeout: AUTH_TIMEOUT,\n });\n\n if (params.edgeConnection && params.edgeFeatures?.feedReplicator) {\n this._edgeFeedReplicator = new EdgeFeedReplicator({ messenger: params.edgeConnection, spaceId: this.space.id });\n }\n }\n\n // TODO(burdon): Expose state object?\n get authorizedDeviceKeys(): ComplexMap<PublicKey, DeviceProfileDocument> {\n return this._deviceStateMachine.authorizedDeviceKeys;\n }\n\n get defaultSpaceId(): SpaceId | undefined {\n return this._defaultSpaceStateMachine.spaceId;\n }\n\n @trace.span()\n async open(ctx: Context) {\n await this._presence?.open();\n await this.space.spaceState.addCredentialProcessor(this._deviceStateMachine);\n await this.space.spaceState.addCredentialProcessor(this._profileStateMachine);\n await this.space.spaceState.addCredentialProcessor(this._defaultSpaceStateMachine);\n if (this._edgeFeedReplicator) {\n this.space.protocol.feedAdded.append(this._onFeedAdded);\n }\n await this.space.open(ctx);\n }\n\n public async joinNetwork() {\n await this.space.startProtocol();\n await this._edgeFeedReplicator?.open();\n }\n\n @trace.span()\n async close(ctx: Context) {\n await this._presence?.close();\n await this.authVerifier.close();\n await this.space.spaceState.removeCredentialProcessor(this._defaultSpaceStateMachine);\n await this.space.spaceState.removeCredentialProcessor(this._profileStateMachine);\n await this.space.spaceState.removeCredentialProcessor(this._deviceStateMachine);\n\n if (this._edgeFeedReplicator) {\n this.space.protocol.feedAdded.remove(this._onFeedAdded);\n }\n\n await this._edgeFeedReplicator?.close();\n\n await this.space.close();\n }\n\n async ready() {\n await this._deviceStateMachine.deviceChainReady.wait();\n\n await this.controlPipeline.state.waitUntilReachedTargetTimeframe({ timeout: LOAD_CONTROL_FEEDS_TIMEOUT });\n }\n\n get profileDocument(): ProfileDocument | undefined {\n return this._profileStateMachine.profile;\n }\n\n /**\n * @test-only\n */\n get controlPipeline() {\n return this.space.controlPipeline;\n }\n\n get haloSpaceId() {\n return this.space.id;\n }\n\n get haloSpaceKey() {\n return this.space.key;\n }\n\n get haloGenesisFeedKey() {\n return this.space.genesisFeedKey;\n }\n\n get deviceCredentialChain() {\n return this._deviceStateMachine.deviceCredentialChain;\n }\n\n get presence() {\n return this._presence;\n }\n\n get signer() {\n return this._signer;\n }\n\n /**\n * Issues credentials as identity.\n * Requires identity to be ready.\n */\n getIdentityCredentialSigner(): CredentialSigner {\n invariant(this._deviceStateMachine.deviceCredentialChain, 'Device credential chain is not ready.');\n return createCredentialSignerWithChain(\n this._signer,\n this._deviceStateMachine.deviceCredentialChain,\n this.deviceKey,\n );\n }\n\n /**\n * Issues credentials as device.\n */\n getDeviceCredentialSigner(): CredentialSigner {\n return createCredentialSignerWithKey(this._signer, this.deviceKey);\n }\n\n async updateDefaultSpace(spaceId: SpaceId) {\n const credential = await this.getDeviceCredentialSigner().createCredential({\n subject: this.identityKey,\n assertion: { '@type': 'dxos.halo.credentials.DefaultSpace', spaceId },\n });\n const receipt = await this.controlPipeline.writer.write({ credential: { credential } });\n await this.controlPipeline.state.waitUntilTimeframe(new Timeframe([[receipt.feedKey, receipt.seq]]));\n }\n\n async admitDevice({ deviceKey, controlFeedKey, dataFeedKey }: DeviceAdmissionRequest): Promise<Credential> {\n log('Admitting device:', {\n identityKey: this.identityKey,\n hostDevice: this.deviceKey,\n deviceKey,\n controlFeedKey,\n dataFeedKey,\n });\n const signer = this.getIdentityCredentialSigner();\n const deviceCredential = await signer.createCredential({\n subject: deviceKey,\n assertion: {\n '@type': 'dxos.halo.credentials.AuthorizedDevice',\n identityKey: this.identityKey,\n deviceKey,\n },\n });\n await writeMessages(\n this.controlPipeline.writer,\n [\n deviceCredential,\n await signer.createCredential({\n subject: controlFeedKey,\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n spaceKey: this.haloSpaceKey,\n deviceKey,\n identityKey: this.identityKey,\n designation: AdmittedFeed.Designation.CONTROL,\n },\n }),\n await signer.createCredential({\n subject: dataFeedKey,\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n spaceKey: this.haloSpaceKey,\n deviceKey,\n identityKey: this.identityKey,\n designation: AdmittedFeed.Designation.DATA,\n },\n }),\n ].map((credential): FeedMessage.Payload => ({ credential: { credential } })),\n );\n\n return deviceCredential;\n }\n\n private _onFeedAdded = async (feed: FeedWrapper<any>) => {\n await this._edgeFeedReplicator!.addFeed(feed);\n };\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type CredentialProcessor, getCredentialAssertion } from '@dxos/credentials';\nimport { SpaceId, type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\ntype DefaultSpaceStateMachineParams = {\n identityKey: PublicKey;\n onUpdate?: () => void;\n};\n\n/**\n * Processes device invitation credentials.\n */\nexport class DefaultSpaceStateMachine implements CredentialProcessor {\n private _spaceId: SpaceId | undefined;\n\n constructor(private readonly _params: DefaultSpaceStateMachineParams) {}\n\n public get spaceId(): SpaceId | undefined {\n return this._spaceId;\n }\n\n async processCredential(credential: Credential) {\n const assertion = getCredentialAssertion(credential);\n switch (assertion['@type']) {\n case 'dxos.halo.credentials.DefaultSpace': {\n if (!credential.subject.id.equals(this._params.identityKey)) {\n log.warn('Invalid default space credential', { expectedIdentity: this._params.identityKey, credential });\n return;\n }\n if (!SpaceId.isValid(assertion.spaceId)) {\n log.warn('Invalid default space id', { id: assertion.spaceId });\n return;\n }\n this._spaceId = assertion.spaceId;\n break;\n }\n }\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, synchronized, trackLeaks } from '@dxos/async';\nimport { type Doc } from '@dxos/automerge/automerge';\nimport { type AutomergeUrl, type DocHandle } from '@dxos/automerge/automerge-repo';\nimport { PropertiesType } from '@dxos/client-protocol';\nimport { LifecycleState, Resource, cancelWithContext } from '@dxos/context';\nimport {\n createAdmissionCredentials,\n getCredentialAssertion,\n type CredentialSigner,\n type DelegateInvitationCredential,\n type MemberInfo,\n} from '@dxos/credentials';\nimport {\n convertLegacyReferences,\n findInlineObjectOfType,\n type EchoEdgeReplicator,\n type EchoHost,\n AuthStatus,\n CredentialServerExtension,\n type MeshEchoReplicator,\n type MetadataStore,\n type Space,\n type SpaceManager,\n type SpaceProtocol,\n type SpaceProtocolSession,\n} from '@dxos/echo-pipeline';\nimport {\n LEGACY_TYPE_PROPERTIES,\n SpaceDocVersion,\n encodeReference,\n type ObjectStructure,\n type SpaceDoc,\n} from '@dxos/echo-protocol';\nimport { TYPE_PROPERTIES, createObjectId, getTypeReference } from '@dxos/echo-schema';\nimport type { EdgeConnection, EdgeHttpClient } from '@dxos/edge-client';\nimport { writeMessages, type FeedStore } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { AlreadyJoinedError, trace as Trace } from '@dxos/protocols';\nimport { Invitation, SpaceState } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type SpaceMetadata, EdgeReplicationSetting } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport { SpaceMember, type Credential, type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type DelegateSpaceInvitation } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type PeerState } from '@dxos/protocols/proto/dxos/mesh/presence';\nimport { type Teleport } from '@dxos/teleport';\nimport { Gossip, Presence } from '@dxos/teleport-extension-gossip';\nimport { type Timeframe } from '@dxos/timeframe';\nimport { trace } from '@dxos/tracing';\nimport { ComplexMap, setDeep, deferFunction, forEachAsync } from '@dxos/util';\n\nimport { DataSpace } from './data-space';\nimport { spaceGenesis } from './genesis';\nimport { createAuthProvider } from '../identity';\nimport { type InvitationsManager } from '../invitations';\n\nconst PRESENCE_ANNOUNCE_INTERVAL = 10_000;\nconst PRESENCE_OFFLINE_TIMEOUT = 20_000;\n\n// Space properties key for default metadata.\nconst DEFAULT_SPACE_KEY = '__DEFAULT__';\n\nexport interface SigningContext {\n identityKey: PublicKey;\n deviceKey: PublicKey;\n credentialSigner: CredentialSigner; // TODO(burdon): Already has keyring.\n recordCredential: (credential: Credential) => Promise<void>;\n // TODO(dmaretskyi): Should be a getter.\n getProfile: () => ProfileDocument | undefined;\n}\n\nexport type AcceptSpaceOptions = {\n spaceKey: PublicKey;\n genesisFeedKey: PublicKey;\n\n /**\n * Latest known timeframe for the control pipeline.\n * We will try to catch up to this timeframe before starting the data pipeline.\n */\n controlTimeframe?: Timeframe;\n\n /**\n * Latest known timeframe for the data pipeline.\n * We will try to catch up to this timeframe before initializing the database.\n */\n dataTimeframe?: Timeframe;\n};\n\nexport type AdmitMemberOptions = {\n spaceKey: PublicKey;\n identityKey: PublicKey;\n role: SpaceMember.Role;\n profile?: ProfileDocument;\n delegationCredentialId?: PublicKey;\n};\n\nexport type DataSpaceManagerParams = {\n spaceManager: SpaceManager;\n metadataStore: MetadataStore;\n keyring: Keyring;\n signingContext: SigningContext;\n feedStore: FeedStore<FeedMessage>;\n echoHost: EchoHost;\n invitationsManager: InvitationsManager;\n edgeConnection?: EdgeConnection;\n edgeHttpClient?: EdgeHttpClient;\n meshReplicator?: MeshEchoReplicator;\n echoEdgeReplicator?: EchoEdgeReplicator;\n runtimeParams?: DataSpaceManagerRuntimeParams;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n};\n\nexport type DataSpaceManagerRuntimeParams = {\n spaceMemberPresenceAnnounceInterval?: number;\n spaceMemberPresenceOfflineTimeout?: number;\n activeEdgeNotarizationPollingInterval?: number;\n disableP2pReplication?: boolean;\n};\n\n@trackLeaks('open', 'close')\nexport class DataSpaceManager extends Resource {\n public readonly updated = new Event();\n\n private readonly _spaces = new ComplexMap<PublicKey, DataSpace>(PublicKey.hash);\n\n private readonly _instanceId = PublicKey.random().toHex();\n\n private readonly _spaceManager: SpaceManager;\n private readonly _metadataStore: MetadataStore;\n private readonly _keyring: Keyring;\n private readonly _signingContext: SigningContext;\n private readonly _feedStore: FeedStore<FeedMessage>;\n private readonly _echoHost: EchoHost;\n private readonly _invitationsManager: InvitationsManager;\n private readonly _edgeConnection?: EdgeConnection = undefined;\n private readonly _edgeHttpClient?: EdgeHttpClient = undefined;\n private readonly _edgeFeatures?: Runtime.Client.EdgeFeatures = undefined;\n private readonly _meshReplicator?: MeshEchoReplicator = undefined;\n private readonly _echoEdgeReplicator?: EchoEdgeReplicator = undefined;\n private readonly _runtimeParams?: DataSpaceManagerRuntimeParams = undefined;\n\n constructor(params: DataSpaceManagerParams) {\n super();\n\n this._spaceManager = params.spaceManager;\n this._metadataStore = params.metadataStore;\n this._keyring = params.keyring;\n this._signingContext = params.signingContext;\n this._feedStore = params.feedStore;\n this._echoHost = params.echoHost;\n this._meshReplicator = params.meshReplicator;\n this._invitationsManager = params.invitationsManager;\n this._edgeConnection = params.edgeConnection;\n this._edgeFeatures = params.edgeFeatures;\n this._echoEdgeReplicator = params.echoEdgeReplicator;\n this._edgeHttpClient = params.edgeHttpClient;\n this._runtimeParams = params.runtimeParams;\n\n trace.diagnostic({\n id: 'spaces',\n name: 'Spaces',\n fetch: async () => {\n return Array.from(this._spaces.values()).map((space) => {\n const rootUrl = space.automergeSpaceState.rootUrl;\n const rootHandle = rootUrl ? this._echoHost.automergeRepo.find(rootUrl as AutomergeUrl) : undefined;\n const rootDoc = rootHandle?.docSync() as Doc<SpaceDoc> | undefined;\n\n const properties = rootDoc && findInlineObjectOfType(rootDoc, TYPE_PROPERTIES);\n\n return {\n key: space.key.toHex(),\n state: SpaceState[space.state],\n name: properties?.[1].data.name ?? null,\n inlineObjects: rootDoc ? Object.keys(rootDoc.objects ?? {}).length : null,\n linkedObjects: rootDoc ? Object.keys(rootDoc.links ?? {}).length : null,\n credentials: space.inner.spaceState.credentials.length,\n members: space.inner.spaceState.members.size,\n rootUrl,\n };\n });\n },\n });\n }\n\n // TODO(burdon): Remove.\n get spaces() {\n return this._spaces;\n }\n\n @synchronized\n protected override async _open() {\n log('open');\n log.trace('dxos.echo.data-space-manager.open', Trace.begin({ id: this._instanceId }));\n log('metadata loaded', { spaces: this._metadataStore.spaces.length });\n\n await forEachAsync(this._metadataStore.spaces, async (spaceMetadata) => {\n try {\n log('load space', { spaceMetadata });\n await this._constructSpace(spaceMetadata);\n } catch (err) {\n log.error('Error loading space', { spaceMetadata, err });\n }\n });\n\n this.updated.emit();\n\n log.trace('dxos.echo.data-space-manager.open', Trace.end({ id: this._instanceId }));\n }\n\n @synchronized\n protected override async _close() {\n log('close');\n for (const space of this._spaces.values()) {\n await space.close();\n }\n this._spaces.clear();\n }\n\n /**\n * Creates a new space writing the genesis credentials to the control feed.\n */\n @synchronized\n async createSpace() {\n invariant(this._lifecycleState === LifecycleState.OPEN, 'Not open.');\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 state: SpaceState.SPACE_ACTIVE,\n };\n\n log('creating space...', { spaceKey });\n\n const root = await this._echoHost.createSpaceRoot(spaceKey);\n const space = await this._constructSpace(metadata);\n await space.open();\n\n const credentials = await spaceGenesis(this._keyring, this._signingContext, space.inner, root.url);\n await this._metadataStore.addSpace(metadata);\n\n const memberCredential = credentials[1];\n invariant(getCredentialAssertion(memberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember');\n await this._signingContext.recordCredential(memberCredential);\n\n await space.initializeDataPipeline();\n\n this.updated.emit();\n return space;\n }\n\n async isDefaultSpace(space: DataSpace): Promise<boolean> {\n if (!space.databaseRoot) {\n return false;\n }\n switch (space.databaseRoot.getVersion()) {\n case SpaceDocVersion.CURRENT: {\n const [_, properties] = findInlineObjectOfType(space.databaseRoot.docSync()!, TYPE_PROPERTIES) ?? [];\n return properties?.data?.[DEFAULT_SPACE_KEY] === this._signingContext.identityKey.toHex();\n }\n case SpaceDocVersion.LEGACY: {\n const convertedDoc = await convertLegacyReferences(space.databaseRoot.docSync()!);\n const [_, properties] = findInlineObjectOfType(convertedDoc, LEGACY_TYPE_PROPERTIES) ?? [];\n return properties?.data?.[DEFAULT_SPACE_KEY] === this._signingContext.identityKey.toHex();\n }\n\n default:\n log.warn('unknown space version', { version: space.databaseRoot.getVersion(), spaceId: space.id });\n return false;\n }\n }\n\n async createDefaultSpace() {\n const space = await this.createSpace();\n const document = await this._getSpaceRootDocument(space);\n\n // TODO(dmaretskyi): Better API for low-level data access.\n const properties: ObjectStructure = {\n system: {\n type: encodeReference(getTypeReference(PropertiesType)!),\n },\n data: {\n [DEFAULT_SPACE_KEY]: this._signingContext.identityKey.toHex(),\n },\n meta: {\n keys: [],\n },\n };\n\n const propertiesId = createObjectId();\n document.change((doc: SpaceDoc) => {\n setDeep(doc, ['objects', propertiesId], properties);\n });\n\n await this._echoHost.flush();\n return space;\n }\n\n private async _getSpaceRootDocument(space: DataSpace): Promise<DocHandle<SpaceDoc>> {\n const automergeIndex = space.automergeSpaceState.rootUrl;\n invariant(automergeIndex);\n const document = this._echoHost.automergeRepo.find<SpaceDoc>(automergeIndex as any);\n await document.whenReady();\n return document;\n }\n\n // TODO(burdon): Rename join space.\n @synchronized\n async acceptSpace(opts: AcceptSpaceOptions): Promise<DataSpace> {\n log('accept space', { opts });\n invariant(this._lifecycleState === LifecycleState.OPEN, 'Not open.');\n invariant(!this._spaces.has(opts.spaceKey), 'Space already exists.');\n\n const metadata: SpaceMetadata = {\n key: opts.spaceKey,\n genesisFeedKey: opts.genesisFeedKey,\n controlTimeframe: opts.controlTimeframe,\n dataTimeframe: opts.dataTimeframe,\n };\n\n const space = await this._constructSpace(metadata);\n await space.open();\n await this._metadataStore.addSpace(metadata);\n space.initializeDataPipelineAsync();\n\n this.updated.emit();\n return space;\n }\n\n async admitMember(options: AdmitMemberOptions): Promise<Credential> {\n const space = this._spaceManager.spaces.get(options.spaceKey);\n invariant(space);\n\n if (space.spaceState.getMemberRole(options.identityKey) !== SpaceMember.Role.REMOVED) {\n throw new AlreadyJoinedError();\n }\n\n // TODO(burdon): Check if already admitted.\n const credentials: FeedMessage.Payload[] = await createAdmissionCredentials(\n this._signingContext.credentialSigner,\n options.identityKey,\n space.key,\n space.genesisFeedKey,\n options.role,\n space.spaceState.membershipChainHeads,\n options.profile,\n options.delegationCredentialId,\n );\n\n // TODO(dmaretskyi): Refactor.\n invariant(credentials[0].credential);\n const spaceMemberCredential = credentials[0].credential.credential;\n invariant(getCredentialAssertion(spaceMemberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember');\n await writeMessages(space.controlPipeline.writer, credentials);\n\n return spaceMemberCredential;\n }\n\n /**\n * Wait until the space data pipeline is fully initialized.\n * Used by invitation handler.\n * TODO(dmaretskyi): Consider removing.\n */\n async waitUntilSpaceReady(spaceKey: PublicKey) {\n await cancelWithContext(\n this._ctx,\n this.updated.waitForCondition(() => {\n const space = this._spaces.get(spaceKey);\n return !!space && space.state === SpaceState.SPACE_READY;\n }),\n );\n }\n\n public async requestSpaceAdmissionCredential(spaceKey: PublicKey): Promise<Credential> {\n return this._spaceManager.requestSpaceAdmissionCredential({\n spaceKey,\n identityKey: this._signingContext.identityKey,\n timeout: 15_000,\n swarmIdentity: {\n identityKey: this._signingContext.identityKey,\n peerKey: this._signingContext.deviceKey,\n credentialProvider: createAuthProvider(this._signingContext.credentialSigner),\n credentialAuthenticator: async () => true,\n },\n });\n }\n\n async setSpaceEdgeReplicationSetting(spaceKey: PublicKey, setting: EdgeReplicationSetting) {\n const space = this._spaces.get(spaceKey);\n invariant(space, 'Space not found.');\n\n await this._metadataStore.setSpaceEdgeReplicationSetting(spaceKey, setting);\n\n if (space.isOpen) {\n switch (setting) {\n case EdgeReplicationSetting.DISABLED:\n await this._echoEdgeReplicator?.disconnectFromSpace(space.id);\n break;\n case EdgeReplicationSetting.ENABLED:\n await this._echoEdgeReplicator?.connectToSpace(space.id);\n break;\n }\n }\n\n space.stateUpdate.emit();\n }\n\n private async _constructSpace(metadata: SpaceMetadata) {\n log('construct space', { metadata });\n const gossip = new Gossip({\n localPeerId: this._signingContext.deviceKey,\n });\n const presence = new Presence({\n announceInterval: this._runtimeParams?.spaceMemberPresenceAnnounceInterval ?? PRESENCE_ANNOUNCE_INTERVAL,\n offlineTimeout: this._runtimeParams?.spaceMemberPresenceOfflineTimeout ?? PRESENCE_OFFLINE_TIMEOUT,\n identityKey: this._signingContext.identityKey,\n gossip,\n });\n\n const controlFeed =\n metadata.controlFeedKey && (await this._feedStore.openFeed(metadata.controlFeedKey, { writable: true }));\n const dataFeed =\n metadata.dataFeedKey &&\n (await this._feedStore.openFeed(metadata.dataFeedKey, {\n writable: true,\n sparse: true,\n }));\n\n const space: Space = await this._spaceManager.constructSpace({\n metadata,\n swarmIdentity: {\n identityKey: this._signingContext.identityKey,\n peerKey: this._signingContext.deviceKey,\n credentialProvider: createAuthProvider(this._signingContext.credentialSigner),\n credentialAuthenticator: deferFunction(() => dataSpace.authVerifier.verifier),\n },\n onAuthorizedConnection: (session) =>\n queueMicrotask(async () => {\n try {\n if (!session.isOpen) {\n return;\n }\n session.addExtension('dxos.mesh.teleport.admission-discovery', new CredentialServerExtension(space));\n session.addExtension(\n 'dxos.mesh.teleport.gossip',\n gossip.createExtension({ remotePeerId: session.remotePeerId }),\n );\n session.addExtension('dxos.mesh.teleport.notarization', dataSpace.notarizationPlugin.createExtension());\n await this._connectEchoMeshReplicator(space, session);\n } catch (err: any) {\n log.warn('error on authorized connection', { err });\n await session.close(err);\n }\n }),\n onAuthFailure: () => {\n log.warn('auth failure');\n },\n onMemberRolesChanged: async (members: MemberInfo[]) => {\n if (dataSpace?.state === SpaceState.SPACE_READY) {\n this._handleMemberRoleChanges(presence, space.protocol, members);\n }\n },\n memberKey: this._signingContext.identityKey,\n onDelegatedInvitationStatusChange: (invitation, isActive) => {\n return this._handleInvitationStatusChange(dataSpace, invitation, isActive);\n },\n });\n controlFeed && (await space.setControlFeed(controlFeed));\n dataFeed && (await space.setDataFeed(dataFeed));\n\n const dataSpace = new DataSpace({\n inner: space,\n initialState: metadata.state === SpaceState.SPACE_INACTIVE ? SpaceState.SPACE_INACTIVE : SpaceState.SPACE_CLOSED,\n metadataStore: this._metadataStore,\n gossip,\n presence,\n keyring: this._keyring,\n feedStore: this._feedStore,\n echoHost: this._echoHost,\n signingContext: this._signingContext,\n callbacks: {\n beforeReady: async () => {\n log('before space ready', { space: space.key });\n },\n afterReady: async () => {\n log('after space ready', { space: space.key, open: this._lifecycleState === LifecycleState.OPEN });\n if (this._lifecycleState === LifecycleState.OPEN) {\n await this._createDelegatedInvitations(dataSpace, [...space.spaceState.invitations.entries()]);\n this._handleMemberRoleChanges(presence, space.protocol, [...space.spaceState.members.values()]);\n this.updated.emit();\n }\n },\n beforeClose: async () => {\n log('before space close', { space: space.key });\n },\n },\n cache: metadata.cache,\n edgeConnection: this._edgeConnection,\n edgeHttpClient: this._edgeHttpClient,\n edgeFeatures: this._edgeFeatures,\n activeEdgeNotarizationPollingInterval: this._runtimeParams?.activeEdgeNotarizationPollingInterval,\n });\n dataSpace.postOpen.append(async () => {\n const setting = dataSpace.getEdgeReplicationSetting();\n if (setting === EdgeReplicationSetting.ENABLED) {\n await this._echoEdgeReplicator?.connectToSpace(dataSpace.id);\n } else if (this._echoEdgeReplicator) {\n log('not connecting EchoEdgeReplicator because of EdgeReplicationSetting', { spaceId: dataSpace.id });\n }\n });\n dataSpace.preClose.append(async () => {\n const setting = dataSpace.getEdgeReplicationSetting();\n if (setting === EdgeReplicationSetting.ENABLED) {\n await this._echoEdgeReplicator?.disconnectFromSpace(dataSpace.id);\n }\n });\n\n presence.newPeer.on((peerState) => {\n if (dataSpace.state === SpaceState.SPACE_READY) {\n this._handleNewPeerConnected(space, peerState);\n }\n });\n\n if (metadata.controlTimeframe) {\n dataSpace.inner.controlPipeline.state.setTargetTimeframe(metadata.controlTimeframe);\n }\n\n this._spaces.set(metadata.key, dataSpace);\n return dataSpace;\n }\n\n private async _connectEchoMeshReplicator(space: Space, session: Teleport) {\n const replicator = this._meshReplicator;\n if (!replicator) {\n log.warn('p2p automerge replication disabled', { space: space.key });\n return;\n }\n await replicator.authorizeDevice(space.key, session.remotePeerId);\n // session ended during device authorization\n if (session.isOpen) {\n session.addExtension('dxos.mesh.teleport.automerge', replicator.createExtension());\n }\n }\n\n private _handleMemberRoleChanges(presence: Presence, spaceProtocol: SpaceProtocol, memberInfo: MemberInfo[]): void {\n let closedSessions = 0;\n for (const member of memberInfo) {\n if (member.key.equals(presence.getLocalState().identityKey)) {\n continue;\n }\n const peers = presence.getPeersByIdentityKey(member.key);\n const sessions = peers.map((p) => p.peerId && spaceProtocol.sessions.get(p.peerId));\n const sessionsToClose = sessions.filter((s): s is SpaceProtocolSession => {\n return (s && (member.role === SpaceMember.Role.REMOVED) !== (s.authStatus === AuthStatus.FAILURE)) ?? false;\n });\n sessionsToClose.forEach((session) => {\n void session.close().catch(log.error);\n });\n closedSessions += sessionsToClose.length;\n }\n log('processed member role changes', {\n roleChangeCount: memberInfo.length,\n peersOnline: presence.getPeersOnline().length,\n closedSessions,\n });\n // Handle the case when there was a removed peer online, we can now establish a connection with them\n spaceProtocol.updateTopology();\n }\n\n private _handleNewPeerConnected(space: Space, peerState: PeerState): void {\n const role = space.spaceState.getMemberRole(peerState.identityKey);\n if (role === SpaceMember.Role.REMOVED) {\n const session = peerState.peerId && space.protocol.sessions.get(peerState.peerId);\n if (session != null) {\n log('closing a session with a removed peer', { peerId: peerState.peerId });\n void session.close().catch(log.error);\n }\n }\n }\n\n private async _handleInvitationStatusChange(\n dataSpace: DataSpace | undefined,\n delegatedInvitation: DelegateInvitationCredential,\n isActive: boolean,\n ): Promise<void> {\n if (dataSpace?.state !== SpaceState.SPACE_READY) {\n return;\n }\n if (isActive) {\n await this._createDelegatedInvitations(dataSpace, [\n [delegatedInvitation.credentialId, delegatedInvitation.invitation],\n ]);\n } else {\n await this._invitationsManager.cancelInvitation(delegatedInvitation.invitation);\n }\n }\n\n private async _createDelegatedInvitations(\n space: DataSpace,\n invitations: Array<[PublicKey, DelegateSpaceInvitation]>,\n ): Promise<void> {\n const tasks = invitations.map(([credentialId, invitation]) => {\n return this._invitationsManager.createInvitation({\n type: Invitation.Type.DELEGATED,\n kind: Invitation.Kind.SPACE,\n spaceKey: space.key,\n authMethod: invitation.authMethod,\n invitationId: invitation.invitationId,\n swarmKey: invitation.swarmKey,\n guestKeypair: invitation.guestKey ? { publicKey: invitation.guestKey } : undefined,\n lifetime: invitation.expiresOn ? invitation.expiresOn.getTime() - Date.now() : undefined,\n multiUse: invitation.multiUse,\n delegationCredentialId: credentialId,\n persistent: false,\n });\n });\n await Promise.all(tasks);\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { createCredential } from '@dxos/credentials';\nimport { failUndefined } from '@dxos/debug';\nimport { type Space } from '@dxos/echo-pipeline';\nimport { type Keyring } from '@dxos/keyring';\nimport { AdmittedFeed, SpaceMember } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { Timeframe } from '@dxos/timeframe';\n\nimport { type SigningContext } from './data-space-manager';\n\nexport const spaceGenesis = async (\n keyring: Keyring,\n signingContext: SigningContext,\n space: Space,\n automergeRoot?: string,\n) => {\n // TODO(dmaretskyi): Find a way to reconcile with credential generator.\n const credentials = [\n await createCredential({\n signer: keyring,\n issuer: space.key,\n subject: space.key,\n assertion: {\n '@type': 'dxos.halo.credentials.SpaceGenesis',\n spaceKey: space.key,\n },\n }),\n\n await createCredential({\n signer: keyring,\n issuer: space.key,\n subject: signingContext.identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.SpaceMember',\n spaceKey: space.key,\n role: SpaceMember.Role.OWNER,\n profile: signingContext.getProfile(),\n genesisFeedKey: space.controlFeedKey ?? failUndefined(),\n },\n }),\n\n await signingContext.credentialSigner.createCredential({\n subject: space.controlFeedKey ?? failUndefined(),\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n spaceKey: space.key,\n identityKey: signingContext.identityKey,\n deviceKey: signingContext.deviceKey,\n designation: AdmittedFeed.Designation.CONTROL,\n },\n }),\n\n await signingContext.credentialSigner.createCredential({\n subject: space.dataFeedKey ?? failUndefined(),\n assertion: {\n '@type': 'dxos.halo.credentials.AdmittedFeed',\n spaceKey: space.key,\n identityKey: signingContext.identityKey,\n deviceKey: signingContext.deviceKey,\n designation: AdmittedFeed.Designation.DATA,\n },\n }),\n\n await signingContext.credentialSigner.createCredential({\n subject: space.key ?? failUndefined(),\n assertion: {\n '@type': 'dxos.halo.credentials.Epoch',\n number: 0,\n previousId: undefined,\n timeframe: new Timeframe(),\n snapshotCid: undefined,\n automergeRoot,\n },\n }),\n ];\n\n for (const credential of credentials) {\n await space.controlPipeline.writer.write({\n credential: { credential },\n });\n }\n\n return credentials;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { EventSubscriptions, UpdateScheduler, scheduleTask } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { createAdmissionCredentials, type CredentialProcessor, getCredentialAssertion } from '@dxos/credentials';\nimport { raise } from '@dxos/debug';\nimport { type SpaceManager } from '@dxos/echo-pipeline';\nimport { writeMessages } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport {\n ApiError,\n SpaceNotFoundError,\n encodeError,\n IdentityNotInitializedError,\n AuthorizationError,\n} from '@dxos/protocols';\nimport {\n SpaceMember,\n SpaceState,\n type CreateEpochRequest,\n type PostMessageRequest,\n type QueryCredentialsRequest,\n type QuerySpacesResponse,\n type Space,\n type SpacesService,\n type SubscribeMessagesRequest,\n type UpdateSpaceRequest,\n type WriteCredentialsRequest,\n type UpdateMemberRoleRequest,\n type AdmitContactRequest,\n type ContactAdmission,\n type JoinSpaceResponse,\n type JoinBySpaceKeyRequest,\n type CreateEpochResponse,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type GossipMessage } from '@dxos/protocols/proto/dxos/mesh/teleport/gossip';\nimport { trace } from '@dxos/tracing';\nimport { type Provider } from '@dxos/util';\n\nimport { type DataSpace } from './data-space';\nimport { type DataSpaceManager } from './data-space-manager';\nimport { type IdentityManager } from '../identity';\n\nexport class SpacesServiceImpl implements SpacesService {\n constructor(\n private readonly _identityManager: IdentityManager,\n private readonly _spaceManager: SpaceManager,\n private readonly _getDataSpaceManager: Provider<Promise<DataSpaceManager>>,\n ) {}\n\n async createSpace(): Promise<Space> {\n this._requireIdentity();\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = await dataSpaceManager.createSpace();\n await this._updateMetrics();\n return this._serializeSpace(space);\n }\n\n async updateSpace({ spaceKey, state, edgeReplication }: UpdateSpaceRequest) {\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n\n if (state) {\n switch (state) {\n case SpaceState.SPACE_ACTIVE:\n await space.activate();\n break;\n\n case SpaceState.SPACE_INACTIVE:\n await space.deactivate();\n break;\n default:\n throw new ApiError('Invalid space state');\n }\n }\n\n if (edgeReplication !== undefined) {\n await dataSpaceManager.setSpaceEdgeReplicationSetting(spaceKey, edgeReplication);\n }\n }\n\n async updateMemberRole(request: UpdateMemberRoleRequest): Promise<void> {\n const identity = this._requireIdentity();\n const space = this._spaceManager.spaces.get(request.spaceKey);\n if (space == null) {\n throw new SpaceNotFoundError(request.spaceKey);\n }\n if (!space.spaceState.hasMembershipManagementPermission(identity.identityKey)) {\n throw new AuthorizationError('No member management permission.', {\n spaceKey: space.key,\n role: space.spaceState.getMemberRole(identity.identityKey),\n });\n }\n const credentials = await createAdmissionCredentials(\n identity.getIdentityCredentialSigner(),\n request.memberKey,\n space.key,\n space.genesisFeedKey,\n request.newRole,\n space.spaceState.membershipChainHeads,\n );\n invariant(credentials[0].credential);\n const spaceMemberCredential = credentials[0].credential.credential;\n invariant(getCredentialAssertion(spaceMemberCredential)['@type'] === 'dxos.halo.credentials.SpaceMember');\n await writeMessages(space.controlPipeline.writer, credentials);\n }\n\n querySpaces(): Stream<QuerySpacesResponse> {\n return new Stream<QuerySpacesResponse>(({ next, ctx }) => {\n const scheduler = new UpdateScheduler(\n ctx,\n async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n const spaces = Array.from(dataSpaceManager.spaces.values()).map((space) => this._serializeSpace(space));\n log('update', () => ({ ids: spaces.map((space) => space.id) }));\n await this._updateMetrics();\n next({ spaces });\n },\n { maxFrequency: process.env.NODE_ENV === 'test' ? undefined : 2 },\n );\n\n scheduleTask(ctx, async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n\n const subscriptions = new EventSubscriptions();\n ctx.onDispose(() => subscriptions.clear());\n\n // TODO(dmaretskyi): Create a pattern for subscribing to a set of objects.\n const subscribeSpaces = () => {\n subscriptions.clear();\n\n for (const space of dataSpaceManager.spaces.values()) {\n let lastState: SpaceState | undefined;\n subscriptions.add(\n space.stateUpdate.on(ctx, () => {\n // Always send a separate update if the space state has changed.\n if (space.state !== lastState) {\n scheduler.forceTrigger();\n } else {\n scheduler.trigger();\n }\n lastState = space.state;\n }),\n );\n\n subscriptions.add(space.presence.updated.on(ctx, () => scheduler.trigger()));\n subscriptions.add(space.automergeSpaceState.onNewEpoch.on(ctx, () => scheduler.trigger()));\n\n // Pipeline progress.\n subscriptions.add(space.inner.controlPipeline.state.timeframeUpdate.on(ctx, () => scheduler.trigger()));\n }\n };\n\n dataSpaceManager.updated.on(ctx, () => {\n subscribeSpaces();\n scheduler.trigger();\n });\n subscribeSpaces();\n\n scheduler.trigger();\n });\n\n if (!this._identityManager.identity) {\n next({ spaces: [] });\n }\n });\n }\n\n async postMessage({ spaceKey, channel, message }: PostMessageRequest) {\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n await space.postMessage(getChannelId(channel), message);\n }\n\n subscribeMessages({ spaceKey, channel }: SubscribeMessagesRequest) {\n return new Stream<GossipMessage>(({ ctx, next }) => {\n scheduleTask(ctx, async () => {\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n const handle = space.listen(getChannelId(channel), (message) => {\n next(message);\n });\n ctx.onDispose(() => handle.unsubscribe());\n });\n });\n }\n\n queryCredentials({ spaceKey, noTail }: QueryCredentialsRequest): Stream<Credential> {\n return new Stream(({ ctx, next, close }) => {\n const space = this._spaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n\n const processor: CredentialProcessor = {\n processCredential: async (credential) => {\n next(credential);\n },\n };\n ctx.onDispose(() => space.spaceState.removeCredentialProcessor(processor));\n scheduleTask(ctx, async () => {\n await space.spaceState.addCredentialProcessor(processor);\n if (noTail) {\n close();\n }\n });\n });\n }\n\n async writeCredentials({ spaceKey, credentials }: WriteCredentialsRequest) {\n const space = this._spaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n for (const credential of credentials ?? []) {\n if (credential.proof) {\n await space.controlPipeline.writer.write({ credential: { credential } });\n } else {\n invariant(!credential.id, 'Id on unsigned credentials is not allowed');\n invariant(this._identityManager.identity, 'Identity is not available');\n const signer = this._identityManager.identity.getIdentityCredentialSigner();\n invariant(credential.issuer.equals(signer.getIssuer()));\n const signedCredential = await signer.createCredential({\n subject: credential.subject.id,\n assertion: credential.subject.assertion,\n });\n await space.controlPipeline.writer.write({ credential: { credential: signedCredential } });\n }\n }\n }\n\n async createEpoch({ spaceKey, migration, automergeRootUrl }: CreateEpochRequest): Promise<CreateEpochResponse> {\n const dataSpaceManager = await this._getDataSpaceManager();\n const space = dataSpaceManager.spaces.get(spaceKey) ?? raise(new SpaceNotFoundError(spaceKey));\n const result = await space.createEpoch({ migration, newAutomergeRoot: automergeRootUrl });\n return { epochCredential: result?.credential, controlTimeframe: result?.timeframe };\n }\n\n async admitContact(request: AdmitContactRequest): Promise<void> {\n const dataSpaceManager = await this._getDataSpaceManager();\n await dataSpaceManager.admitMember({\n spaceKey: request.spaceKey,\n identityKey: request.contact.identityKey,\n role: request.role,\n });\n }\n\n async joinBySpaceKey({ spaceKey }: JoinBySpaceKeyRequest): Promise<JoinSpaceResponse> {\n const dataSpaceManager = await this._getDataSpaceManager();\n const credential = await dataSpaceManager.requestSpaceAdmissionCredential(spaceKey);\n return this._joinByAdmission({ credential });\n }\n\n private async _joinByAdmission({ credential }: ContactAdmission): Promise<JoinSpaceResponse> {\n const assertion = getCredentialAssertion(credential);\n invariant(assertion['@type'] === 'dxos.halo.credentials.SpaceMember', 'Invalid credential');\n const myIdentity = this._identityManager.identity;\n invariant(myIdentity && credential.subject.id.equals(myIdentity.identityKey));\n\n const dataSpaceManager = await this._getDataSpaceManager();\n let dataSpace = dataSpaceManager.spaces.get(assertion.spaceKey);\n if (!dataSpace) {\n dataSpace = await dataSpaceManager.acceptSpace({\n spaceKey: assertion.spaceKey,\n genesisFeedKey: assertion.genesisFeedKey,\n });\n await myIdentity.controlPipeline.writer.write({ credential: { credential } });\n }\n\n return { space: this._serializeSpace(dataSpace) };\n }\n\n private _serializeSpace(space: DataSpace): Space {\n return {\n id: space.id,\n spaceKey: space.key,\n state: space.state,\n error: space.error ? encodeError(space.error) : undefined,\n pipeline: {\n currentEpoch: space.automergeSpaceState.lastEpoch,\n appliedEpoch: space.automergeSpaceState.lastEpoch,\n\n controlFeeds: space.inner.controlPipeline.state.feeds.map((feed) => feed.key),\n currentControlTimeframe: space.inner.controlPipeline.state.timeframe,\n targetControlTimeframe: space.inner.controlPipeline.state.targetTimeframe,\n totalControlTimeframe: space.inner.controlPipeline.state.endTimeframe,\n\n dataFeeds: undefined,\n startDataTimeframe: undefined,\n currentDataTimeframe: undefined,\n targetDataTimeframe: undefined,\n totalDataTimeframe: undefined,\n\n spaceRootUrl: space.databaseRoot?.url,\n },\n members: Array.from(space.inner.spaceState.members.values()).map((member) => {\n const peers = space.presence.getPeersOnline().filter(({ identityKey }) => identityKey.equals(member.key));\n const isMe = this._identityManager.identity?.identityKey.equals(member.key);\n\n if (isMe) {\n peers.push(space.presence.getLocalState());\n }\n\n return {\n identity: {\n identityKey: member.key,\n profile: member.profile ?? {},\n },\n role: member.role,\n presence: peers.length > 0 ? SpaceMember.PresenceState.ONLINE : SpaceMember.PresenceState.OFFLINE,\n peerStates: peers,\n };\n }),\n creator: space.inner.spaceState.creator?.key,\n cache: space.cache,\n metrics: space.metrics,\n edgeReplication: space.getEdgeReplicationSetting(),\n };\n }\n\n private _requireIdentity() {\n if (!this._identityManager.identity) {\n throw new IdentityNotInitializedError(\n 'This device has no HALO identity available. See https://docs.dxos.org/guide/platform/halo',\n );\n }\n return this._identityManager.identity;\n }\n\n private async _updateMetrics() {\n const dataSpaceManager = await this._getDataSpaceManager();\n const identity = this._identityManager.identity?.identityKey.truncate();\n if (identity) {\n trace.metrics.gauge('dxos.echo.space.count', dataSpaceManager.spaces.size, {\n tags: { identity },\n });\n }\n }\n}\n\n// Add `user-channel` prefix to the channel name, so that it doesn't collide with the internal channels.\nconst getChannelId = (channel: string): string => `user-channel/${channel}`;\n", "//\n// Copyright 2022 DXOS.org\n//\nimport platform from 'platform';\n\nimport { Event } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport {\n createCredentialSignerWithKey,\n CredentialGenerator,\n generateSeedPhrase,\n keyPairFromSeedPhrase,\n} from '@dxos/credentials';\nimport { type MetadataStore, type SpaceManager, type SwarmIdentity } from '@dxos/echo-pipeline';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { type FeedStore } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { trace } from '@dxos/protocols';\nimport { Device, DeviceKind } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { type FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type IdentityRecord, type SpaceMetadata } from '@dxos/protocols/proto/dxos/echo/metadata';\nimport {\n AdmittedFeed,\n type DeviceProfileDocument,\n DeviceType,\n type ProfileDocument,\n type Credential,\n} from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { Gossip, Presence } from '@dxos/teleport-extension-gossip';\nimport { Timeframe } from '@dxos/timeframe';\nimport { trace as Trace } from '@dxos/tracing';\nimport { isNode, deferFunction } from '@dxos/util';\n\nimport { createAuthProvider } from './authenticator';\nimport { Identity } from './identity';\n\nconst DEVICE_PRESENCE_ANNOUNCE_INTERVAL = 10_000;\nconst DEVICE_PRESENCE_OFFLINE_TIMEOUT = 20_000;\n\ninterface ConstructSpaceParams {\n spaceRecord: SpaceMetadata;\n swarmIdentity: SwarmIdentity;\n identityKey: PublicKey;\n gossip: Gossip;\n}\n\nexport type JoinIdentityParams = {\n identityKey: PublicKey;\n deviceKey: PublicKey;\n haloSpaceKey: PublicKey;\n haloGenesisFeedKey: PublicKey;\n controlFeedKey: PublicKey;\n dataFeedKey: PublicKey;\n authorizedDeviceCredential: Credential;\n\n /**\n * Latest known timeframe for the control pipeline.\n * We will try to catch up to this timeframe before starting the data pipeline.\n */\n controlTimeframe?: Timeframe;\n // Custom device profile, merged with defaults, to be applied once the identity is accepted.\n deviceProfile?: DeviceProfileDocument;\n};\n\nexport type CreateIdentityOptions = {\n displayName?: string;\n // device profile for device creating the identity.\n deviceProfile?: DeviceProfileDocument;\n};\n\nexport type IdentityManagerParams = {\n metadataStore: MetadataStore;\n keyring: Keyring;\n feedStore: FeedStore<FeedMessage>;\n spaceManager: SpaceManager;\n edgeConnection?: EdgeConnection;\n edgeFeatures?: Runtime.Client.EdgeFeatures;\n devicePresenceAnnounceInterval?: number;\n devicePresenceOfflineTimeout?: number;\n};\n\n// TODO(dmaretskyi): Rename: represents the peer's state machine.\n@Trace.resource()\nexport class IdentityManager {\n readonly stateUpdate = new Event();\n\n private readonly _metadataStore: MetadataStore;\n private readonly _keyring: Keyring;\n private readonly _feedStore: FeedStore<FeedMessage>;\n private readonly _spaceManager: SpaceManager;\n private readonly _devicePresenceAnnounceInterval: number;\n private readonly _devicePresenceOfflineTimeout: number;\n private readonly _edgeConnection: EdgeConnection | undefined;\n private readonly _edgeFeatures: Runtime.Client.EdgeFeatures | undefined;\n\n private _identity?: Identity;\n\n // TODO(dmaretskyi): Perhaps this should take/generate the peerKey outside of an initialized identity.\n constructor(params: IdentityManagerParams) {\n this._metadataStore = params.metadataStore;\n this._keyring = params.keyring;\n this._feedStore = params.feedStore;\n this._spaceManager = params.spaceManager;\n this._edgeConnection = params.edgeConnection;\n this._edgeFeatures = params.edgeFeatures;\n this._devicePresenceAnnounceInterval = params.devicePresenceAnnounceInterval ?? DEVICE_PRESENCE_ANNOUNCE_INTERVAL;\n this._devicePresenceOfflineTimeout = params.devicePresenceOfflineTimeout ?? DEVICE_PRESENCE_OFFLINE_TIMEOUT;\n }\n\n get identity() {\n return this._identity;\n }\n\n @Trace.span({ showInBrowserTimeline: true })\n async open(ctx: Context) {\n const traceId = PublicKey.random().toHex();\n log.trace('dxos.halo.identity-manager.open', trace.begin({ id: traceId }));\n\n const identityRecord = this._metadataStore.getIdentityRecord();\n log('identity record', { identityRecord });\n if (identityRecord) {\n this._identity = await this._constructIdentity(identityRecord);\n await this._identity.open(ctx);\n await this._identity.ready();\n log.trace('dxos.halo.identity', {\n identityKey: identityRecord.identityKey,\n displayName: this._identity.profileDocument?.displayName,\n });\n\n this.stateUpdate.emit();\n }\n log.trace('dxos.halo.identity-manager.open', trace.end({ id: traceId }));\n }\n\n async close() {\n await this._identity?.close(new Context());\n }\n\n async createIdentity({ displayName, deviceProfile }: CreateIdentityOptions = {}) {\n // TODO(nf): populate using context from ServiceContext?\n invariant(!this._identity, 'Identity already exists.');\n log('creating identity...');\n\n const controlFeedKey = await this._keyring.createKey();\n const identityRecord: IdentityRecord = {\n identityKey: await this._keyring.createKey(),\n deviceKey: await this._keyring.createKey(),\n haloSpace: {\n key: await this._keyring.createKey(),\n genesisFeedKey: controlFeedKey,\n controlFeedKey,\n dataFeedKey: await this._keyring.createKey(),\n },\n };\n\n const identity = await this._constructIdentity(identityRecord);\n await identity.open(new Context());\n\n {\n const generator = new CredentialGenerator(this._keyring, identityRecord.identityKey, identityRecord.deviceKey);\n invariant(identityRecord.haloSpace.genesisFeedKey, 'Genesis feed key is required.');\n invariant(identityRecord.haloSpace.dataFeedKey, 'Data feed key is required.');\n const credentials = [\n // Space genesis.\n ...(await generator.createSpaceGenesis(identityRecord.haloSpace.key, identityRecord.haloSpace.genesisFeedKey)),\n\n // Feed admission.\n await generator.createFeedAdmission(\n identityRecord.haloSpace.key,\n identityRecord.haloSpace.dataFeedKey,\n AdmittedFeed.Designation.DATA,\n ),\n ];\n\n if (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 // Write device metadata to profile.\n credentials.push(\n await generator.createDeviceProfile({\n ...this.createDefaultDeviceProfile(),\n ...deviceProfile,\n }),\n );\n for (const credential of credentials) {\n await identity.controlPipeline.writer.write({\n credential: { credential },\n });\n }\n }\n\n await this._metadataStore.setIdentityRecord(identityRecord);\n this._identity = identity;\n await this._identity.ready();\n log.trace('dxos.halo.identity', {\n identityKey: identityRecord.identityKey,\n displayName: this._identity.profileDocument?.displayName,\n });\n this.stateUpdate.emit();\n\n log('created identity', {\n identityKey: identity.identityKey,\n deviceKey: identity.deviceKey,\n profile: identity.profileDocument,\n });\n\n return identity;\n }\n\n // TODO(nf): receive platform info rather than generating it here.\n createDefaultDeviceProfile(): DeviceProfileDocument {\n let type: DeviceType;\n // TODO(nf): call Platform service instead?\n if (isNode()) {\n type = DeviceType.AGENT;\n } else {\n if (platform.name?.startsWith('iOS') || platform.name?.startsWith('Android')) {\n type = DeviceType.MOBILE;\n } else if ((globalThis as any).__args) {\n type = DeviceType.NATIVE;\n } else {\n type = DeviceType.BROWSER;\n }\n }\n\n return {\n type,\n platform: platform.name,\n platformVersion: platform.version,\n architecture: typeof platform.os?.architecture === 'number' ? String(platform.os.architecture) : undefined,\n os: platform.os?.family,\n osVersion: platform.os?.version,\n };\n }\n\n /**\n * Prepare an identity object as the first step of acceptIdentity flow.\n */\n async prepareIdentity(params: JoinIdentityParams) {\n log('accepting identity', { params });\n invariant(!this._identity, 'Identity already exists.');\n\n const identityRecord: IdentityRecord = {\n identityKey: params.identityKey,\n deviceKey: params.deviceKey,\n haloSpace: {\n key: params.haloSpaceKey,\n genesisFeedKey: params.haloGenesisFeedKey,\n controlFeedKey: params.controlFeedKey,\n dataFeedKey: params.dataFeedKey,\n controlTimeframe: params.controlTimeframe,\n },\n };\n const identity = await this._constructIdentity(identityRecord);\n await identity.open(new Context());\n return { identity, identityRecord };\n }\n\n /**\n * Accept an existing identity. Expects its device key to be authorized (now or later).\n */\n public async acceptIdentity(identity: Identity, identityRecord: IdentityRecord, profile?: DeviceProfileDocument) {\n this._identity = identity;\n\n // Identity becomes ready after device chain is replicated. Wait for it before storing the record.\n await this._identity.ready();\n await this._metadataStore.setIdentityRecord(identityRecord);\n\n log.trace('dxos.halo.identity', {\n identityKey: this._identity!.identityKey,\n displayName: this._identity.profileDocument?.displayName,\n });\n\n await this.updateDeviceProfile({\n ...this.createDefaultDeviceProfile(),\n ...profile,\n });\n this.stateUpdate.emit();\n\n log('accepted identity', { identityKey: identity.identityKey, deviceKey: identity.deviceKey });\n }\n\n /**\n * Update the profile document of an existing identity.\n */\n async updateProfile(profile: ProfileDocument) {\n invariant(this._identity, 'Identity not initialized.');\n // TODO(wittjosiah): Use CredentialGenerator.\n const credential = await this._identity.getIdentityCredentialSigner().createCredential({\n subject: this._identity.identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.IdentityProfile',\n profile,\n },\n });\n\n const receipt = await this._identity.controlPipeline.writer.write({ credential: { credential } });\n await this._identity.controlPipeline.state.waitUntilTimeframe(new Timeframe([[receipt.feedKey, receipt.seq]]));\n this.stateUpdate.emit();\n return profile;\n }\n\n async updateDeviceProfile(profile: DeviceProfileDocument): Promise<Device> {\n invariant(this._identity, 'Identity not initialized.');\n\n // TODO(nf): CredentialGenerator doesn't work when not updating own device.\n // const generator = new CredentialGenerator(this._keyring, this._identity.identityKey, this._identity.deviceKey);\n // const credential = await generator.createDeviceProfile(profile);\n\n const credential = await this._identity.getDeviceCredentialSigner().createCredential({\n subject: this._identity.deviceKey,\n assertion: {\n '@type': 'dxos.halo.credentials.DeviceProfile',\n profile,\n },\n });\n\n const receipt = await this._identity.controlPipeline.writer.write({ credential: { credential } });\n await this._identity.controlPipeline.state.waitUntilTimeframe(new Timeframe([[receipt.feedKey, receipt.seq]]));\n this.stateUpdate.emit();\n return {\n deviceKey: this._identity.deviceKey,\n kind: DeviceKind.CURRENT,\n presence: Device.PresenceState.ONLINE,\n profile,\n };\n }\n\n async createRecoveryPhrase() {\n const identity = this._identity;\n invariant(identity);\n\n const seedphrase = generateSeedPhrase();\n const keypair = keyPairFromSeedPhrase(seedphrase);\n const recoveryKey = PublicKey.from(keypair.publicKey);\n const identityKey = identity.identityKey;\n const credential = await identity.getIdentityCredentialSigner().createCredential({\n subject: identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.IdentityRecovery',\n recoveryKey,\n identityKey,\n },\n });\n\n const receipt = await identity.controlPipeline.writer.write({ credential: { credential } });\n await identity.controlPipeline.state.waitUntilTimeframe(new Timeframe([[receipt.feedKey, receipt.seq]]));\n\n return { seedphrase };\n }\n\n private async _constructIdentity(identityRecord: IdentityRecord) {\n invariant(!this._identity);\n log('constructing identity', { identityRecord });\n\n const gossip = new Gossip({\n localPeerId: identityRecord.deviceKey,\n });\n const presence = new Presence({\n announceInterval: this._devicePresenceAnnounceInterval,\n offlineTimeout: this._devicePresenceOfflineTimeout,\n identityKey: identityRecord.deviceKey,\n gossip,\n });\n\n // Must be created before the space so the feeds are writable.\n invariant(identityRecord.haloSpace.controlFeedKey);\n const controlFeed = await this._feedStore.openFeed(identityRecord.haloSpace.controlFeedKey, {\n writable: true,\n });\n invariant(identityRecord.haloSpace.dataFeedKey);\n const dataFeed = await this._feedStore.openFeed(identityRecord.haloSpace.dataFeedKey, {\n writable: true,\n sparse: true,\n });\n\n const space = await this._constructSpace({\n spaceRecord: identityRecord.haloSpace,\n swarmIdentity: {\n identityKey: identityRecord.identityKey,\n peerKey: identityRecord.deviceKey,\n credentialProvider: createAuthProvider(createCredentialSignerWithKey(this._keyring, identityRecord.deviceKey)),\n credentialAuthenticator: deferFunction(() => identity.authVerifier.verifier),\n },\n gossip,\n identityKey: identityRecord.identityKey,\n });\n await space.setControlFeed(controlFeed);\n await space.setDataFeed(dataFeed);\n\n const identity: Identity = new Identity({\n space,\n presence,\n signer: this._keyring,\n identityKey: identityRecord.identityKey,\n deviceKey: identityRecord.deviceKey,\n edgeConnection: this._edgeConnection,\n edgeFeatures: this._edgeFeatures,\n });\n log('done', { identityKey: identityRecord.identityKey });\n\n // TODO(mykola): Set new timeframe on a write to a feed.\n if (identityRecord.haloSpace.controlTimeframe) {\n identity.controlPipeline.state.setTargetTimeframe(identityRecord.haloSpace.controlTimeframe);\n }\n\n identity.stateUpdate.on(() => this.stateUpdate.emit());\n return identity;\n }\n\n private async _constructSpace({ spaceRecord, swarmIdentity, identityKey, gossip }: ConstructSpaceParams) {\n return this._spaceManager.constructSpace({\n metadata: {\n key: spaceRecord.key,\n genesisFeedKey: spaceRecord.genesisFeedKey,\n },\n swarmIdentity,\n onAuthorizedConnection: (session) => {\n session.addExtension(\n 'dxos.mesh.teleport.gossip',\n gossip.createExtension({ remotePeerId: session.remotePeerId }),\n );\n },\n onAuthFailure: () => {\n log.warn('auth failure');\n },\n memberKey: identityKey,\n onDelegatedInvitationStatusChange: async () => {}, // TODO: will be used for recovery keys\n onMemberRolesChanged: async () => {}, // TODO: will be used for device revocation\n });\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Trigger, sleep } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { Resource } from '@dxos/context';\nimport { signPresentation } from '@dxos/credentials';\nimport { invariant } from '@dxos/invariant';\nimport { type Keyring } from '@dxos/keyring';\nimport { log } from '@dxos/log';\nimport {\n type CreateIdentityRequest,\n type Identity as IdentityProto,\n type IdentityService,\n type QueryIdentityResponse,\n type RecoverIdentityRequest,\n type SignPresentationRequest,\n SpaceState,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type Presentation, type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { safeAwaitAll } from '@dxos/util';\n\nimport { type Identity } from './identity';\nimport { type CreateIdentityOptions, type IdentityManager } from './identity-manager';\nimport { type EdgeIdentityRecoveryManager } from './identity-recovery-manager';\nimport { type DataSpaceManager } from '../spaces';\n\nconst DEFAULT_SPACE_SEARCH_TIMEOUT = 10_000;\n\nexport class IdentityServiceImpl extends Resource implements IdentityService {\n constructor(\n private readonly _identityManager: IdentityManager,\n private readonly _recoveryManager: EdgeIdentityRecoveryManager,\n private readonly _keyring: Keyring,\n private readonly _dataSpaceManagerProvider: () => DataSpaceManager,\n private readonly _createIdentity: (params: CreateIdentityOptions) => Promise<Identity>,\n private readonly _onProfileUpdate?: (profile: ProfileDocument | undefined) => Promise<void>,\n ) {\n super();\n }\n\n protected override async _open() {\n const identity = this._identityManager.identity;\n if (identity && !identity.defaultSpaceId) {\n await this._fixIdentityWithoutDefaultSpace(identity);\n }\n }\n\n async createIdentity(request: CreateIdentityRequest): Promise<IdentityProto> {\n await this._createIdentity({ displayName: request.profile?.displayName, deviceProfile: request.deviceProfile });\n const dataSpaceManager = this._dataSpaceManagerProvider();\n await this._createDefaultSpace(dataSpaceManager);\n return this._getIdentity()!;\n }\n\n private async _createDefaultSpace(dataSpaceManager: DataSpaceManager) {\n const space = await dataSpaceManager!.createDefaultSpace();\n const identity = this._identityManager.identity;\n invariant(identity);\n await identity.updateDefaultSpace(space.id);\n }\n\n queryIdentity(): Stream<QueryIdentityResponse> {\n return new Stream(({ next }) => {\n const emitNext = () => next({ identity: this._getIdentity() });\n\n emitNext();\n return this._identityManager.stateUpdate.on(emitNext);\n });\n }\n\n private _getIdentity(): IdentityProto | undefined {\n if (!this._identityManager.identity) {\n return undefined;\n }\n\n return {\n identityKey: this._identityManager.identity.identityKey,\n spaceKey: this._identityManager.identity.space.key,\n profile: this._identityManager.identity.profileDocument,\n };\n }\n\n async updateProfile(profile: ProfileDocument): Promise<IdentityProto> {\n invariant(this._identityManager.identity, 'Identity not initialized.');\n await this._identityManager.updateProfile(profile);\n await this._onProfileUpdate?.(this._identityManager.identity.profileDocument);\n return this._getIdentity()!;\n }\n\n async createRecoveryPhrase() {\n return this._recoveryManager.createRecoveryPhrase();\n }\n\n async recoverIdentity(request: RecoverIdentityRequest): Promise<IdentityProto> {\n await this._recoveryManager.recoverIdentity(request);\n return this._getIdentity()!;\n }\n\n // TODO(burdon): Rename createPresentation?\n async signPresentation({ presentation, nonce }: SignPresentationRequest): Promise<Presentation> {\n invariant(this._identityManager.identity, 'Identity not initialized.');\n\n return await signPresentation({\n presentation,\n signer: this._keyring,\n signerKey: this._identityManager.identity.deviceKey,\n chain: this._identityManager.identity.deviceCredentialChain,\n nonce,\n });\n }\n\n private async _fixIdentityWithoutDefaultSpace(identity: Identity) {\n let recodedDefaultSpace = false;\n let foundDefaultSpace = false;\n const dataSpaceManager = this._dataSpaceManagerProvider();\n\n const recordedDefaultSpaceTrigger = new Trigger();\n\n const allProcessed = safeAwaitAll(\n dataSpaceManager.spaces.values(),\n async (space) => {\n if (space.state === SpaceState.SPACE_CLOSED) {\n await space.open();\n\n // Wait until the space is either READY or REQUIRES_MIGRATION.\n // NOTE: Space could potentially never initialize if the space data is corrupted.\n const requiresMigration = space.stateUpdate.waitForCondition(\n () => space.state === SpaceState.SPACE_REQUIRES_MIGRATION,\n );\n await Promise.race([space.initializeDataPipeline(), requiresMigration]);\n }\n if (await dataSpaceManager.isDefaultSpace(space)) {\n if (foundDefaultSpace) {\n log.warn('Multiple default spaces found. Using the first one.', { duplicate: space.id });\n return;\n }\n\n foundDefaultSpace = true;\n await identity.updateDefaultSpace(space.id);\n recodedDefaultSpace = true;\n recordedDefaultSpaceTrigger.wake();\n }\n },\n (err) => {\n log.catch(err);\n },\n );\n\n // Wait for all spaces to be processed or until the default space is recorded.\n // If the timeout is reached, create a new default space.\n await Promise.race([allProcessed, recordedDefaultSpaceTrigger.wait(), sleep(DEFAULT_SPACE_SEARCH_TIMEOUT)]);\n\n if (!recodedDefaultSpace) {\n await this._createDefaultSpace(dataSpaceManager);\n }\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { getCredentialAssertion } from '@dxos/credentials';\nimport { invariant } from '@dxos/invariant';\nimport { type Keyring } from '@dxos/keyring';\nimport { type PublicKey } from '@dxos/keys';\nimport { AlreadyJoinedError, type ApiError } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport type { DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionRequest,\n type AdmissionResponse,\n type IntroductionRequest,\n} from '@dxos/protocols/proto/dxos/halo/invitations';\n\nimport { type InvitationProtocol } from './invitation-protocol';\nimport { type Identity, type JoinIdentityParams } from '../identity';\n\nexport class DeviceInvitationProtocol implements InvitationProtocol {\n constructor(\n private readonly _keyring: Keyring,\n private readonly _getIdentity: () => Identity,\n private readonly _acceptIdentity: (identity: JoinIdentityParams) => Promise<Identity>,\n ) {}\n\n toJSON(): object {\n return {\n kind: 'device',\n };\n }\n\n checkCanInviteNewMembers(): ApiError | undefined {\n return undefined;\n }\n\n getInvitationContext(): Partial<Invitation> & Pick<Invitation, 'kind'> {\n return {\n kind: Invitation.Kind.DEVICE,\n };\n }\n\n async delegate(): Promise<PublicKey> {\n throw new Error('delegation not supported');\n }\n\n async cancelDelegation(): Promise<void> {\n throw new Error('delegation not supported');\n }\n\n async admit(_: Invitation, request: AdmissionRequest): Promise<AdmissionResponse> {\n invariant(request.device);\n const identity = this._getIdentity();\n const credential = await identity.admitDevice(request.device);\n invariant(getCredentialAssertion(credential)['@type'] === 'dxos.halo.credentials.AuthorizedDevice');\n\n return {\n device: {\n identityKey: identity.identityKey,\n haloSpaceKey: identity.haloSpaceKey,\n genesisFeedKey: identity.haloGenesisFeedKey,\n controlTimeframe: identity.controlPipeline.state.timeframe,\n credential,\n },\n };\n }\n\n checkInvitation(invitation: Partial<Invitation>) {\n try {\n const identity = this._getIdentity();\n if (identity) {\n return new AlreadyJoinedError('Currently only one identity per client is supported.');\n }\n } catch {\n // No identity.\n }\n }\n\n createIntroduction(): IntroductionRequest {\n return {};\n }\n\n async createAdmissionRequest(deviceProfile?: DeviceProfileDocument): Promise<AdmissionRequest> {\n const deviceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n\n return {\n device: {\n deviceKey,\n controlFeedKey,\n dataFeedKey,\n profile: deviceProfile,\n },\n };\n }\n\n async accept(response: AdmissionResponse, request: AdmissionRequest): Promise<Partial<Invitation>> {\n invariant(response.device);\n const { identityKey, haloSpaceKey, genesisFeedKey, controlTimeframe } = response.device;\n\n invariant(request.device);\n const { deviceKey, controlFeedKey, dataFeedKey, profile } = request.device;\n\n // TODO(wittjosiah): When multiple identities are supported, verify identity doesn't already exist before accepting.\n\n await this._acceptIdentity({\n identityKey,\n deviceKey,\n haloSpaceKey,\n haloGenesisFeedKey: genesisFeedKey,\n controlFeedKey,\n dataFeedKey,\n controlTimeframe,\n deviceProfile: profile,\n authorizedDeviceCredential: response.device.credential,\n });\n\n return { identityKey };\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type PushStream, scheduleTask, TimeoutError, type Trigger } from '@dxos/async';\nimport { INVITATION_TIMEOUT } from '@dxos/client-protocol';\nimport { type Context, ContextDisposedError } from '@dxos/context';\nimport { createKeyPair, sign } from '@dxos/crypto';\nimport { type EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { createTeleportProtocolFactory, type SwarmNetworkManager, type SwarmConnection } from '@dxos/network-manager';\nimport { InvalidInvitationExtensionRoleError, trace } from '@dxos/protocols';\nimport { type AdmissionKeypair, Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { AuthenticationResponse, type IntroductionResponse } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { InvitationOptions } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type ExtensionContext, type TeleportExtension, type TeleportParams } from '@dxos/teleport';\nimport { trace as _trace } from '@dxos/tracing';\nimport { ComplexSet } from '@dxos/util';\n\nimport { type EdgeInvitationConfig, EdgeInvitationHandler } from './edge-invitation-handler';\nimport { InvitationGuestExtension } from './invitation-guest-extenstion';\nimport { InvitationHostExtension, isAuthenticationRequired, MAX_OTP_ATTEMPTS } from './invitation-host-extension';\nimport { type InvitationProtocol } from './invitation-protocol';\nimport { createGuardedInvitationState } from './invitation-state';\nimport { InvitationTopology } from './invitation-topology';\n\nconst metrics = _trace.metrics;\n\nconst MAX_DELEGATED_INVITATION_HOST_TRIES = 3;\n\nexport type InvitationConnectionParams = {\n teleport: Partial<TeleportParams>;\n edgeInvitations?: EdgeInvitationConfig;\n};\n\n/**\n * Generic handler for Halo and Space invitations.\n * Handles the life-cycle of invitations between peers.\n *\n * Host\n * - Creates an invitation containing a swarm topic (which can be shared via a URL, QR code, or direct message).\n * - Joins the swarm with the topic and waits for guest's introduction.\n * - Wait for guest to authenticate with challenge specified in the invitation.\n * - Waits for guest to present credentials (containing local device and feed keys).\n * - Writes credentials to control feed then exits or waits for more guests (multi use invitations).\n *\n * Guest\n * - Joins the swarm with the topic.\n * - Sends an introduction.\n * - Submits the challenge.\n * - If Space handler then creates a local cloned space (with genesis block).\n * - Sends admission credentials.\n * ```\n * [Guest] [Host]\n * |------------------------------------Introduce-->|\n * |-------------------------------[Authenticate]-->|\n * |----------------------------------------Admit-->|\n * ```\n *\n * TODO: consider refactoring using xstate making the logic separation more explicit:\n * TODO: the flow logic should either be contained in invitations-handler or in extensions, not be split across\n * TODO: potentially re-evaluate host-side API to allow multiple concurrent connection, so that mutex can be removed\n */\nexport class InvitationsHandler {\n /**\n * @internal\n */\n constructor(\n private readonly _networkManager: SwarmNetworkManager,\n private readonly _edgeClient?: EdgeHttpClient,\n private readonly _connectionParams?: InvitationConnectionParams,\n ) {}\n\n handleInvitationFlow(\n ctx: Context,\n stream: PushStream<Invitation>,\n protocol: InvitationProtocol,\n invitation: Invitation,\n ): void {\n log.verbose('dxos.sdk.invitations-handler.handleInvitationFlow', {\n state: invitation.state,\n invitationId: invitation.invitationId,\n kind: invitation.kind,\n type: invitation.type,\n });\n metrics.increment('dxos.invitation.host');\n const guardedState = createGuardedInvitationState(ctx, invitation, stream);\n // Called for every connecting peer.\n const createExtension = (): InvitationHostExtension => {\n const extension = new InvitationHostExtension(guardedState.mutex, {\n get activeInvitation() {\n return ctx.disposed ? null : guardedState.current;\n },\n\n onStateUpdate: (newState: Invitation.State): Invitation => {\n if (newState !== Invitation.State.ERROR && newState !== Invitation.State.TIMEOUT) {\n guardedState.set(extension, newState);\n }\n return guardedState.current;\n },\n\n admit: async (admissionRequest) => {\n try {\n log.verbose('dxos.sdk.invitations-handler.host.admit', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n });\n const deviceKey = admissionRequest.device?.deviceKey ?? admissionRequest.space?.deviceKey;\n invariant(deviceKey);\n const admissionResponse = await protocol.admit(invitation, admissionRequest, extension.guestProfile);\n\n // Updating credentials complete.\n extension.completedTrigger.wake(deviceKey);\n\n return admissionResponse;\n } catch (err: any) {\n // TODO(burdon): Generic RPC callback to report error to client.\n guardedState.error(extension, err);\n throw err; // Propagate error to guest.\n }\n },\n\n onOpen: (connectionCtx: Context, extensionsCtx: ExtensionContext) => {\n let admitted = false;\n connectionCtx.onDispose(() => {\n if (!admitted) {\n guardedState.set(extension, Invitation.State.CONNECTING);\n }\n });\n\n scheduleTask(connectionCtx, async () => {\n const traceId = PublicKey.random().toHex();\n try {\n log.trace('dxos.sdk.invitations-handler.host.onOpen', trace.begin({ id: traceId }));\n log.verbose('connected', { ...protocol.toJSON() });\n const deviceKey = await extension.completedTrigger.wait({ timeout: invitation.timeout });\n log.verbose('admitted guest', { guest: deviceKey, ...protocol.toJSON() });\n guardedState.set(extension, Invitation.State.SUCCESS);\n metrics.increment('dxos.invitation.success');\n log.trace('dxos.sdk.invitations-handler.host.onOpen', trace.end({ id: traceId }));\n admitted = true;\n\n if (!invitation.multiUse) {\n await ctx.dispose();\n }\n } catch (err: any) {\n const stateChanged = guardedState.set(extension, Invitation.State.CONNECTING);\n if (err instanceof TimeoutError) {\n if (stateChanged) {\n metrics.increment('dxos.invitation.timeout');\n log.verbose('timeout', { ...protocol.toJSON() });\n }\n } else {\n if (stateChanged) {\n metrics.increment('dxos.invitation.failed');\n log.error('failed', err);\n }\n }\n log.trace('dxos.sdk.invitations-handler.host.onOpen', trace.error({ id: traceId, error: err }));\n // Close connection\n extensionsCtx.close(err);\n }\n });\n },\n onError: (err) => {\n const stateChanged = guardedState.set(extension, Invitation.State.CONNECTING);\n if (err instanceof InvalidInvitationExtensionRoleError) {\n log('invalid role', { ...err.context });\n return;\n }\n if (err instanceof TimeoutError) {\n if (stateChanged) {\n metrics.increment('dxos.invitation.timeout');\n log.verbose('timeout', { err });\n }\n } else {\n if (stateChanged) {\n metrics.increment('dxos.invitation.failed');\n log.error('failed', err);\n }\n }\n },\n });\n\n return extension;\n };\n\n if (invitation.lifetime && invitation.created) {\n if (invitation.created.getTime() + invitation.lifetime * 1000 < Date.now()) {\n log.warn('invitation has already expired');\n guardedState.set(null, Invitation.State.EXPIRED);\n void ctx.dispose().catch((err) => log.catch(err));\n return;\n }\n scheduleTask(\n ctx,\n async () => {\n // ensure the swarm is closed before changing state and closing the stream.\n await swarmConnection.close();\n guardedState.set(null, Invitation.State.EXPIRED);\n metrics.increment('dxos.invitation.expired');\n await ctx.dispose();\n },\n invitation.created.getTime() + invitation.lifetime * 1000 - Date.now(),\n );\n }\n\n let swarmConnection: SwarmConnection;\n scheduleTask(ctx, async () => {\n swarmConnection = await this._joinSwarm(ctx, invitation, InvitationOptions.Role.HOST, createExtension);\n guardedState.set(null, Invitation.State.CONNECTING);\n });\n }\n\n acceptInvitation(\n ctx: Context,\n stream: PushStream<Invitation>,\n protocol: InvitationProtocol,\n invitation: Invitation,\n otpEnteredTrigger: Trigger<string>,\n deviceProfile?: DeviceProfileDocument,\n ): void {\n log.verbose('dxos.sdk.invitations-handler.acceptInvitation', {\n state: invitation.state,\n invitationId: invitation.invitationId,\n kind: invitation.kind,\n type: invitation.type,\n });\n const { timeout = INVITATION_TIMEOUT } = invitation;\n\n if (deviceProfile) {\n invariant(invitation.kind === Invitation.Kind.DEVICE, 'deviceProfile provided for non-device invitation');\n }\n\n const triedPeersIds = new ComplexSet(PublicKey.hash);\n const guardedState = createGuardedInvitationState(ctx, invitation, stream);\n\n const shouldCancelInvitationFlow = (extension: InvitationGuestExtension) => {\n const isLockedByAnotherConnection = guardedState.mutex.isLocked() && !extension.hasFlowLock();\n log('should cancel invitation flow', {\n isLockedByAnotherConnection,\n invitationType: Invitation.Type.DELEGATED,\n triedPeers: triedPeersIds.size,\n });\n if (isLockedByAnotherConnection) {\n return false;\n }\n // for delegated invitations we might try with other hosts and will dispose either after\n // a timeout or when the number of tries was exceeded\n return invitation.type !== Invitation.Type.DELEGATED || triedPeersIds.size >= MAX_DELEGATED_INVITATION_HOST_TRIES;\n };\n\n let admitted = false;\n const createExtension = (): InvitationGuestExtension => {\n const extension = new InvitationGuestExtension(guardedState.mutex, {\n onStateUpdate: (newState: Invitation.State) => {\n guardedState.set(extension, newState);\n },\n onOpen: (connectionCtx: Context, extensionCtx: ExtensionContext) => {\n triedPeersIds.add(extensionCtx.remotePeerId);\n\n if (admitted) {\n extensionCtx.close();\n return;\n }\n\n connectionCtx.onDispose(async () => {\n log.verbose('extension disposed', { admitted, currentState: guardedState.current.state });\n if (!admitted) {\n guardedState.error(extension, new ContextDisposedError());\n if (shouldCancelInvitationFlow(extension)) {\n await ctx.dispose();\n }\n }\n });\n\n scheduleTask(connectionCtx, async () => {\n const traceId = PublicKey.random().toHex();\n try {\n log.trace('dxos.sdk.invitations-handler.guest.onOpen', trace.begin({ id: traceId }));\n\n scheduleTask(\n connectionCtx,\n () => {\n guardedState.set(extension, Invitation.State.TIMEOUT);\n extensionCtx.close();\n },\n timeout,\n );\n\n log.verbose('dxos.sdk.invitations-handler.guest.connected', { ...protocol.toJSON() });\n guardedState.set(extension, Invitation.State.CONNECTED);\n\n // 1. Introduce guest to host.\n log.verbose('dxos.sdk.invitations-handler.guest.introduce', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n });\n const introductionResponse = await extension.rpc.InvitationHostService.introduce({\n invitationId: invitation.invitationId,\n ...protocol.createIntroduction(),\n });\n log.verbose('dxos.sdk.invitations-handler.guest.introduce-response', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n authMethod: introductionResponse.authMethod,\n });\n invitation.authMethod = introductionResponse.authMethod;\n\n // 2. Get authentication code.\n if (isAuthenticationRequired(invitation)) {\n switch (invitation.authMethod) {\n case Invitation.AuthMethod.SHARED_SECRET:\n await this._handleGuestOtpAuth(\n extension,\n (state) => guardedState.set(extension, state),\n otpEnteredTrigger,\n { timeout },\n );\n break;\n case Invitation.AuthMethod.KNOWN_PUBLIC_KEY:\n await this._handleGuestKpkAuth(\n extension,\n (state) => guardedState.set(extension, state),\n invitation,\n introductionResponse,\n );\n break;\n }\n }\n\n // 3. Send admission credentials to host (with local space keys).\n log.verbose('dxos.sdk.invitations-handler.guest.request-admission', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n });\n const admissionRequest = await protocol.createAdmissionRequest(deviceProfile);\n const admissionResponse = await extension.rpc.InvitationHostService.admit(admissionRequest);\n\n // Remote connection no longer needed.\n admitted = true;\n\n // 4. Record credential in our HALO.\n const result = await protocol.accept(admissionResponse, admissionRequest);\n\n // 5. Success.\n log.verbose('dxos.sdk.invitations-handler.guest.admitted-by-host', {\n invitationId: invitation.invitationId,\n ...protocol.toJSON(),\n });\n guardedState.complete({\n ...guardedState.current,\n ...result,\n state: Invitation.State.SUCCESS,\n });\n log.trace('dxos.sdk.invitations-handler.guest.onOpen', trace.end({ id: traceId }));\n } catch (err: any) {\n if (err instanceof TimeoutError) {\n log.verbose('timeout', { ...protocol.toJSON() });\n guardedState.set(extension, Invitation.State.TIMEOUT);\n } else {\n log.verbose('auth failed', err);\n guardedState.error(extension, err);\n }\n extensionCtx.close(err);\n log.trace('dxos.sdk.invitations-handler.guest.onOpen', trace.error({ id: traceId, error: err }));\n }\n });\n },\n onError: (err) => {\n if (err instanceof InvalidInvitationExtensionRoleError) {\n return;\n }\n if (err instanceof TimeoutError) {\n log.verbose('timeout', { ...protocol.toJSON() });\n guardedState.set(extension, Invitation.State.TIMEOUT);\n } else {\n log.verbose('auth failed', err);\n guardedState.error(extension, err);\n }\n },\n });\n\n return extension;\n };\n\n const edgeInvitationHandler = new EdgeInvitationHandler(this._connectionParams?.edgeInvitations, this._edgeClient, {\n onInvitationSuccess: async (admissionResponse, admissionRequest) => {\n const result = await protocol.accept(admissionResponse, admissionRequest);\n log.info('admitted by edge', { ...protocol.toJSON() });\n guardedState.complete({ ...guardedState.current, ...result, state: Invitation.State.SUCCESS });\n },\n });\n edgeInvitationHandler.handle(ctx, guardedState, protocol, deviceProfile);\n\n scheduleTask(ctx, async () => {\n const error = protocol.checkInvitation(invitation);\n if (error) {\n stream.error(error);\n await ctx.dispose();\n } else {\n invariant(invitation.swarmKey);\n\n const timeoutInactive = () => {\n if (guardedState.mutex.isLocked()) {\n scheduleTask(ctx, timeoutInactive, timeout);\n } else {\n guardedState.set(null, Invitation.State.TIMEOUT);\n }\n };\n\n // Timeout if no connection is established.\n scheduleTask(ctx, timeoutInactive, timeout);\n\n await this._joinSwarm(ctx, invitation, InvitationOptions.Role.GUEST, createExtension);\n guardedState.set(null, Invitation.State.CONNECTING);\n }\n });\n }\n\n private async _joinSwarm(\n ctx: Context,\n invitation: Invitation,\n role: InvitationOptions.Role,\n extensionFactory: () => TeleportExtension,\n ): Promise<SwarmConnection> {\n let label: string;\n if (role === InvitationOptions.Role.GUEST) {\n label = 'invitation guest';\n } else if (invitation.kind === Invitation.Kind.DEVICE) {\n label = 'invitation host for device';\n } else {\n label = `invitation host for space ${invitation.spaceKey?.truncate()}`;\n }\n const swarmConnection = await this._networkManager.joinSwarm({\n topic: invitation.swarmKey,\n protocolProvider: createTeleportProtocolFactory(async (teleport) => {\n teleport.addExtension('dxos.halo.invitations', extensionFactory());\n }, this._connectionParams?.teleport),\n topology: new InvitationTopology(role),\n label,\n });\n ctx.onDispose(() => swarmConnection.close());\n return swarmConnection;\n }\n\n private async _handleGuestOtpAuth(\n extension: InvitationGuestExtension,\n setState: (newState: Invitation.State) => void,\n authenticated: Trigger<string>,\n options: { timeout: number },\n ) {\n for (let attempt = 1; attempt <= MAX_OTP_ATTEMPTS; attempt++) {\n log('guest waiting for authentication code...');\n setState(Invitation.State.READY_FOR_AUTHENTICATION);\n const authCode = await authenticated.wait(options);\n\n log('sending authentication request');\n setState(Invitation.State.AUTHENTICATING);\n const response = await extension.rpc.InvitationHostService.authenticate({ authCode });\n if (response.status === undefined || response.status === AuthenticationResponse.Status.OK) {\n break;\n }\n\n if (response.status === AuthenticationResponse.Status.INVALID_OTP) {\n if (attempt === MAX_OTP_ATTEMPTS) {\n throw new Error(`Maximum retry attempts: ${MAX_OTP_ATTEMPTS}`);\n } else {\n log('retrying invalid code', { attempt });\n authenticated.reset();\n }\n }\n }\n }\n\n private async _handleGuestKpkAuth(\n extension: InvitationGuestExtension,\n setState: (newState: Invitation.State) => void,\n invitation: Invitation,\n introductionResponse: IntroductionResponse,\n ) {\n if (invitation.guestKeypair?.privateKey == null) {\n throw new Error('keypair missing in the invitation');\n }\n if (introductionResponse.challenge == null) {\n throw new Error('challenge missing in the introduction');\n }\n log('sending authentication request');\n const signature = sign(Buffer.from(introductionResponse.challenge), invitation.guestKeypair.privateKey);\n const response = await extension.rpc.InvitationHostService.authenticate({\n signedChallenge: signature,\n });\n if (response.status !== AuthenticationResponse.Status.OK) {\n throw new Error(`Authentication failed with code: ${response.status}`);\n }\n }\n}\n\nexport const createAdmissionKeypair = (): AdmissionKeypair => {\n const keypair = createKeyPair();\n return { publicKey: PublicKey.from(keypair.publicKey), privateKey: keypair.secretKey };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type MutexGuard, scheduleMicroTask, scheduleTask } from '@dxos/async';\nimport { type Context } from '@dxos/context';\nimport { sign } from '@dxos/crypto';\nimport { type EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n EdgeAuthChallengeError,\n EdgeCallFailedError,\n type JoinSpaceRequest,\n type JoinSpaceResponseBody,\n} from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionResponse,\n type AdmissionRequest,\n type SpaceAdmissionRequest,\n} from '@dxos/protocols/proto/dxos/halo/invitations';\n\nimport { type InvitationProtocol } from './invitation-protocol';\nimport { type FlowLockHolder, type GuardedInvitationState } from './invitation-state';\nimport { tryAcquireBeforeContextDisposed } from './utils';\n\nexport interface EdgeInvitationHandlerCallbacks {\n onInvitationSuccess(response: AdmissionResponse, request: AdmissionRequest): Promise<void>;\n}\n\nexport const MAX_RETRIES_PER_INVITATION = 5;\nexport const DEFAULT_REQUEST_RETRY_INTERVAL_MS = 3000;\nexport const DEFAULT_REQUEST_RETRY_JITTER_MS = 500;\n\nexport type EdgeInvitationConfig = {\n retryInterval?: number;\n retryJitter?: number;\n};\n\nexport class EdgeInvitationHandler implements FlowLockHolder {\n private _flowLock: MutexGuard | undefined;\n\n private readonly _retryInterval: number;\n private readonly _retryJitter: number;\n\n constructor(\n config: EdgeInvitationConfig | undefined,\n private readonly _client: EdgeHttpClient | undefined,\n private readonly _callbacks: EdgeInvitationHandlerCallbacks,\n ) {\n this._retryInterval = config?.retryInterval ?? DEFAULT_REQUEST_RETRY_INTERVAL_MS;\n this._retryJitter = config?.retryJitter ?? DEFAULT_REQUEST_RETRY_JITTER_MS;\n }\n\n public handle(\n ctx: Context,\n guardedState: GuardedInvitationState,\n protocol: InvitationProtocol,\n deviceProfile?: DeviceProfileDocument,\n ) {\n if (!this._client) {\n log('edge disabled');\n return;\n }\n\n const invitation = guardedState.current;\n const spaceId = invitation.spaceId;\n const canBeHandledByEdge =\n invitation.authMethod !== Invitation.AuthMethod.SHARED_SECRET &&\n invitation.type === Invitation.Type.DELEGATED &&\n invitation.kind === Invitation.Kind.SPACE &&\n spaceId != null &&\n SpaceId.isValid(spaceId);\n\n if (!canBeHandledByEdge) {\n log('invitation could not be handled by edge', { invitation });\n return;\n }\n\n ctx.onDispose(() => {\n this._flowLock?.release();\n this._flowLock = undefined;\n });\n\n let requestCount = 0;\n const tryHandleInvitation = async () => {\n requestCount++;\n const admissionRequest = await protocol.createAdmissionRequest(deviceProfile);\n if (admissionRequest.space) {\n try {\n await this._handleSpaceInvitationFlow(ctx, guardedState, admissionRequest.space, spaceId);\n } catch (error) {\n if (error instanceof EdgeCallFailedError) {\n log.info('join space with edge unsuccessful', {\n reason: error.message,\n retryable: error.isRetryable,\n after: error.retryAfterMs ?? this._calculateNextRetryMs(),\n });\n if (error.isRetryable && requestCount < MAX_RETRIES_PER_INVITATION) {\n scheduleTask(ctx, tryHandleInvitation, error.retryAfterMs ?? this._calculateNextRetryMs());\n }\n } else if (requestCount < MAX_RETRIES_PER_INVITATION) {\n log.info('failed to handle invitation with edge', { error });\n scheduleTask(ctx, tryHandleInvitation, this._calculateNextRetryMs());\n }\n }\n }\n };\n scheduleMicroTask(ctx, tryHandleInvitation);\n }\n\n private async _handleSpaceInvitationFlow(\n ctx: Context,\n guardedState: GuardedInvitationState,\n admissionRequest: SpaceAdmissionRequest,\n spaceId: SpaceId,\n ) {\n try {\n log('edge invitation flow');\n this._flowLock = await tryAcquireBeforeContextDisposed(ctx, guardedState.mutex);\n log.verbose('edge invitation flow acquired the lock');\n\n guardedState.set(this, Invitation.State.CONNECTING);\n\n const response = await this._joinSpaceByInvitation(guardedState, spaceId, {\n identityKey: admissionRequest.identityKey.toHex(),\n invitationId: guardedState.current.invitationId,\n });\n\n const admissionResponse = await this._mapToAdmissionResponse(response);\n await this._callbacks.onInvitationSuccess(admissionResponse, { space: admissionRequest });\n } catch (error) {\n guardedState.set(this, Invitation.State.ERROR);\n throw error;\n } finally {\n this._flowLock?.release();\n this._flowLock = undefined;\n }\n }\n\n private async _mapToAdmissionResponse(edgeResponse: JoinSpaceResponseBody): Promise<AdmissionResponse> {\n const credentialBytes = Buffer.from(edgeResponse.spaceMemberCredential, 'base64');\n const codec = schema.getCodecForType('dxos.halo.credentials.Credential');\n return {\n space: {\n credential: codec.decode(credentialBytes),\n },\n };\n }\n\n private async _joinSpaceByInvitation(\n guardedState: GuardedInvitationState,\n spaceId: SpaceId,\n request: JoinSpaceRequest,\n ): Promise<JoinSpaceResponseBody> {\n invariant(this._client);\n try {\n return await this._client.joinSpaceByInvitation(spaceId, request);\n } catch (error: any) {\n if (error instanceof EdgeAuthChallengeError) {\n const publicKey = guardedState.current.guestKeypair?.publicKey;\n const privateKey = guardedState.current.guestKeypair?.privateKey;\n if (!privateKey || !publicKey) {\n throw error;\n }\n const signature = sign(Buffer.from(error.challenge, 'base64'), privateKey);\n return this._client.joinSpaceByInvitation(spaceId, {\n ...request,\n signature: Buffer.from(signature).toString('base64'),\n });\n } else {\n throw error;\n }\n }\n }\n\n public hasFlowLock(): boolean {\n return this._flowLock != null;\n }\n\n private _calculateNextRetryMs() {\n return this._retryInterval + Math.random() * this._retryJitter;\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Mutex, type MutexGuard } from '@dxos/async';\nimport { cancelWithContext, type Context, ContextDisposedError } from '@dxos/context';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nexport const stateToString = (state: Invitation.State): string => {\n return Object.entries(Invitation.State).find(([key, val]) => val === state)?.[0] ?? 'unknown';\n};\n\nexport const tryAcquireBeforeContextDisposed = async (ctx: Context, mutex: Mutex): Promise<MutexGuard> => {\n let guard: MutexGuard | undefined;\n return cancelWithContext(\n ctx,\n (async () => {\n guard = await mutex.acquire();\n if (ctx.disposed) {\n guard.release();\n guard = undefined;\n throw new ContextDisposedError();\n }\n return guard;\n })(),\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Mutex, type MutexGuard, Trigger } from '@dxos/async';\nimport { cancelWithContext, Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { InvalidInvitationExtensionRoleError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type InvitationHostService, InvitationOptions } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport { type FlowLockHolder } from './invitation-state';\nimport { tryAcquireBeforeContextDisposed } from './utils';\n\nconst OPTIONS_TIMEOUT = 10_000;\n\ntype InvitationGuestExtensionCallbacks = {\n // Deliberately not async to not block the extensions opening.\n onOpen: (ctx: Context, extensionCtx: ExtensionContext) => void;\n onError: (error: Error) => void;\n\n onStateUpdate: (newState: Invitation.State) => void;\n};\n\n/**\n * Guest's side for a connection to a concrete peer in p2p network during invitation.\n */\nexport class InvitationGuestExtension\n extends RpcExtension<\n { InvitationHostService: InvitationHostService },\n { InvitationHostService: InvitationHostService }\n >\n implements FlowLockHolder\n{\n private _ctx = new Context();\n private _remoteOptions?: InvitationOptions;\n private _remoteOptionsTrigger = new Trigger();\n /**\n * Held to allow only one invitation flow at a time to be active.\n */\n private _invitationFlowLock: MutexGuard | null = null;\n\n constructor(\n private readonly _invitationFlowMutex: Mutex,\n private readonly _callbacks: InvitationGuestExtensionCallbacks,\n ) {\n super({\n requested: {\n InvitationHostService: schema.getService('dxos.halo.invitations.InvitationHostService'),\n },\n exposed: {\n InvitationHostService: schema.getService('dxos.halo.invitations.InvitationHostService'),\n },\n });\n }\n\n public hasFlowLock(): boolean {\n return this._invitationFlowLock != null;\n }\n\n protected override async getHandlers(): Promise<{ InvitationHostService: InvitationHostService }> {\n return {\n InvitationHostService: {\n options: async (options) => {\n invariant(!this._remoteOptions, 'Remote options already set.');\n this._remoteOptions = options;\n this._remoteOptionsTrigger.wake();\n },\n introduce: () => {\n throw new Error('Method not allowed.');\n },\n authenticate: () => {\n throw new Error('Method not allowed.');\n },\n admit: () => {\n throw new Error('Method not allowed.');\n },\n },\n };\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n\n try {\n log.verbose('guest acquire lock');\n this._invitationFlowLock = await tryAcquireBeforeContextDisposed(this._ctx, this._invitationFlowMutex);\n log.verbose('guest lock acquired');\n await cancelWithContext(\n this._ctx,\n this.rpc.InvitationHostService.options({ role: InvitationOptions.Role.GUEST }),\n );\n log.verbose('options sent');\n await cancelWithContext(this._ctx, this._remoteOptionsTrigger.wait({ timeout: OPTIONS_TIMEOUT }));\n log.verbose('options received');\n if (this._remoteOptions?.role !== InvitationOptions.Role.HOST) {\n throw new InvalidInvitationExtensionRoleError(undefined, {\n expected: InvitationOptions.Role.HOST,\n remoteOptions: this._remoteOptions,\n remotePeerId: context.remotePeerId,\n });\n }\n\n this._callbacks.onOpen(this._ctx, context);\n } catch (err: any) {\n if (this._invitationFlowLock != null) {\n this._callbacks.onError(err);\n }\n if (!this._ctx.disposed) {\n context.close(err);\n }\n }\n }\n\n override async onClose() {\n await this._destroy();\n }\n\n override async onAbort(): Promise<void> {\n await this._destroy();\n }\n\n private async _destroy() {\n await this._ctx.dispose();\n if (this._invitationFlowLock != null) {\n this._invitationFlowLock.release();\n this._invitationFlowLock = null;\n log.verbose('invitation flow lock released');\n }\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Mutex, type MutexGuard, Trigger, scheduleTask } from '@dxos/async';\nimport { cancelWithContext, Context } from '@dxos/context';\nimport { randomBytes, verify } from '@dxos/crypto';\nimport { invariant, InvariantViolation } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { InvalidInvitationExtensionRoleError, trace } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionRequest,\n type AdmissionResponse,\n AuthenticationResponse,\n type InvitationHostService,\n InvitationOptions,\n} from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { type ExtensionContext, RpcExtension } from '@dxos/teleport';\n\nimport type { FlowLockHolder } from './invitation-state';\nimport { stateToString, tryAcquireBeforeContextDisposed } from './utils';\n\n/// Timeout for the options exchange.\nconst OPTIONS_TIMEOUT = 10_000;\n\nexport const MAX_OTP_ATTEMPTS = 3;\n\ntype InvitationHostExtensionCallbacks = {\n activeInvitation: Invitation | null;\n\n // Deliberately not async to not block the extensions opening.\n onOpen: (ctx: Context, extensionCtx: ExtensionContext) => void;\n onError: (error: Error) => void;\n\n onStateUpdate: (newState: Invitation.State) => void;\n\n admit: (request: AdmissionRequest) => Promise<AdmissionResponse>;\n};\n\n/**\n * Host's side for a connection to a concrete peer in p2p network during invitation.\n */\nexport class InvitationHostExtension\n extends RpcExtension<\n { InvitationHostService: InvitationHostService },\n { InvitationHostService: InvitationHostService }\n >\n implements FlowLockHolder\n{\n /**\n * @internal\n */\n private _ctx = new Context();\n private _remoteOptions?: InvitationOptions;\n private _remoteOptionsTrigger = new Trigger();\n\n private _challenge?: Buffer = undefined;\n\n public guestProfile?: ProfileDocument = undefined;\n\n public authenticationPassed = false;\n\n /**\n * Retry counter for SHARED_SECRET authentication method.\n */\n public authenticationRetry = 0;\n\n /**\n * Resolved when admission is completed.\n */\n public completedTrigger = new Trigger<PublicKey>();\n\n /**\n * Held to allow only one invitation flow at a time to be active.\n */\n private _invitationFlowLock: MutexGuard | null = null;\n\n constructor(\n private readonly _invitationFlowMutex: Mutex,\n private readonly _callbacks: InvitationHostExtensionCallbacks,\n ) {\n super({\n requested: {\n InvitationHostService: schema.getService('dxos.halo.invitations.InvitationHostService'),\n },\n exposed: {\n InvitationHostService: schema.getService('dxos.halo.invitations.InvitationHostService'),\n },\n });\n }\n\n public hasFlowLock(): boolean {\n return this._invitationFlowLock != null;\n }\n\n protected override async getHandlers(): Promise<{ InvitationHostService: InvitationHostService }> {\n return {\n // TODO(dmaretskyi): For now this is just forwarding the data to callbacks since we don't have session-specific logic.\n // Perhaps in the future we will have more complex logic here.\n InvitationHostService: {\n options: async (options) => {\n invariant(!this._remoteOptions, 'Remote options already set.');\n this._remoteOptions = options;\n this._remoteOptionsTrigger.wake();\n },\n\n introduce: async (request) => {\n const { profile, invitationId } = request;\n const traceId = PublicKey.random().toHex();\n log.trace('dxos.sdk.invitation-handler.host.introduce', trace.begin({ id: traceId }));\n\n const invitation = this._requireActiveInvitation();\n this._assertInvitationState(Invitation.State.CONNECTED);\n if (invitationId !== invitation?.invitationId) {\n log.warn('incorrect invitationId', { expected: invitation.invitationId, actual: invitationId });\n this._callbacks.onError(new Error('Incorrect invitationId.'));\n scheduleTask(this._ctx, () => this.close());\n // TODO(dmaretskyi): Better error handling.\n return {\n authMethod: Invitation.AuthMethod.NONE,\n };\n }\n\n log.verbose('guest introduced themselves', { guestProfile: profile });\n this.guestProfile = profile;\n this._callbacks.onStateUpdate(Invitation.State.READY_FOR_AUTHENTICATION);\n this._challenge =\n invitation.authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY ? randomBytes(32) : undefined;\n\n log.trace('dxos.sdk.invitation-handler.host.introduce', trace.end({ id: traceId }));\n return {\n authMethod: invitation.authMethod,\n challenge: this._challenge,\n };\n },\n\n authenticate: async ({ authCode: code, signedChallenge }) => {\n const traceId = PublicKey.random().toHex();\n log.trace('dxos.sdk.invitation-handler.host.authenticate', trace.begin({ id: traceId }));\n\n const invitation = this._requireActiveInvitation();\n log.verbose('received authentication request', { authCode: code });\n let status = AuthenticationResponse.Status.OK;\n\n this._assertInvitationState([Invitation.State.AUTHENTICATING, Invitation.State.READY_FOR_AUTHENTICATION]);\n this._callbacks.onStateUpdate(Invitation.State.AUTHENTICATING);\n\n switch (invitation.authMethod) {\n case Invitation.AuthMethod.NONE: {\n log('authentication not required');\n return { status: AuthenticationResponse.Status.OK };\n }\n\n case Invitation.AuthMethod.SHARED_SECRET: {\n if (invitation.authCode) {\n if (this.authenticationRetry++ > MAX_OTP_ATTEMPTS) {\n status = AuthenticationResponse.Status.INVALID_OPT_ATTEMPTS;\n } else if (code !== invitation.authCode) {\n status = AuthenticationResponse.Status.INVALID_OTP;\n } else {\n this.authenticationPassed = true;\n }\n }\n break;\n }\n\n case Invitation.AuthMethod.KNOWN_PUBLIC_KEY: {\n if (!invitation.guestKeypair) {\n status = AuthenticationResponse.Status.INTERNAL_ERROR;\n break;\n }\n const isSignatureValid =\n this._challenge &&\n verify(\n this._challenge,\n Buffer.from(signedChallenge ?? []),\n invitation.guestKeypair.publicKey.asBuffer(),\n );\n if (isSignatureValid) {\n this.authenticationPassed = true;\n } else {\n status = AuthenticationResponse.Status.INVALID_SIGNATURE;\n }\n break;\n }\n\n default: {\n log.error('invalid authentication method', { authMethod: invitation.authMethod });\n status = AuthenticationResponse.Status.INTERNAL_ERROR;\n break;\n }\n }\n\n if (![AuthenticationResponse.Status.OK, AuthenticationResponse.Status.INVALID_OTP].includes(status)) {\n this._callbacks.onError(new Error(`Authentication failed, with status=${status}`));\n scheduleTask(this._ctx, () => this.close());\n return { status };\n }\n\n log.trace('dxos.sdk.invitation-handler.host.authenticate', trace.end({ id: traceId, data: { status } }));\n return { status };\n },\n\n admit: async (request) => {\n const traceId = PublicKey.random().toHex();\n log.trace('dxos.sdk.invitation-handler.host.admit', trace.begin({ id: traceId }));\n const invitation = this._requireActiveInvitation();\n\n try {\n // Check authenticated.\n if (isAuthenticationRequired(invitation)) {\n this._assertInvitationState(Invitation.State.AUTHENTICATING);\n if (!this.authenticationPassed) {\n throw new Error('Not authenticated');\n }\n }\n\n const response = await this._callbacks.admit(request);\n\n log.trace('dxos.sdk.invitation-handler.host.admit', trace.end({ id: traceId }));\n return response;\n } catch (err: any) {\n this._callbacks.onError(err);\n throw err;\n }\n },\n },\n };\n }\n\n override async onOpen(context: ExtensionContext) {\n await super.onOpen(context);\n\n try {\n log.verbose('host acquire lock');\n this._invitationFlowLock = await tryAcquireBeforeContextDisposed(this._ctx, this._invitationFlowMutex);\n log.verbose('host lock acquired');\n this._callbacks.onStateUpdate(Invitation.State.CONNECTING);\n await this.rpc.InvitationHostService.options({ role: InvitationOptions.Role.HOST });\n log.verbose('options sent');\n await cancelWithContext(this._ctx, this._remoteOptionsTrigger.wait({ timeout: OPTIONS_TIMEOUT }));\n log.verbose('options received');\n if (this._remoteOptions?.role !== InvitationOptions.Role.GUEST) {\n throw new InvalidInvitationExtensionRoleError(undefined, {\n expected: InvitationOptions.Role.GUEST,\n remoteOptions: this._remoteOptions,\n remotePeerId: context.remotePeerId,\n });\n }\n this._callbacks.onStateUpdate(Invitation.State.CONNECTED);\n this._callbacks.onOpen(this._ctx, context);\n } catch (err: any) {\n if (this._invitationFlowLock != null) {\n this._callbacks.onError(err);\n }\n if (!this._ctx.disposed) {\n context.close(err);\n }\n }\n }\n\n private _requireActiveInvitation(): Invitation {\n const invitation = this._callbacks.activeInvitation;\n if (invitation == null) {\n scheduleTask(this._ctx, () => this.close());\n throw new Error('Active invitation not found');\n }\n return invitation;\n }\n\n private _assertInvitationState(stateOrMany: Invitation.State | Invitation.State[]) {\n const invitation = this._requireActiveInvitation();\n const validStates = Array.isArray(stateOrMany) ? stateOrMany : [stateOrMany];\n if (!validStates.includes(invitation.state)) {\n scheduleTask(this._ctx, () => this.close());\n throw new InvariantViolation(\n `Expected ${stateToString(invitation.state)} to be one of [${validStates.map(stateToString).join(', ')}]`,\n );\n }\n }\n\n override async onClose() {\n await this._destroy();\n }\n\n override async onAbort() {\n await this._destroy();\n }\n\n private async _destroy() {\n await this._ctx.dispose();\n if (this._invitationFlowLock != null) {\n this._invitationFlowLock?.release();\n this._invitationFlowLock = null;\n log.verbose('invitation flow lock released');\n }\n }\n}\n\nexport const isAuthenticationRequired = (invitation: Invitation) =>\n invitation.authMethod !== Invitation.AuthMethod.NONE;\n", "/**\n * A utility object for serializing invitation state changes by multiple concurrent\n * invitation flow connections.\n */\n//\n// Copyright 2024 DXOS.org\n//\n\nimport { Mutex, type PushStream } from '@dxos/async';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { stateToString } from './utils';\n\nexport interface FlowLockHolder {\n hasFlowLock(): boolean;\n}\n\nexport interface GuardedInvitationState {\n mutex: Mutex;\n current: Invitation;\n\n complete(newState: Partial<Invitation>): void;\n set(lockHolder: FlowLockHolder | null, newState: Invitation.State): boolean;\n error(lockHolder: FlowLockHolder | null, error: any): boolean;\n}\n\nexport const createGuardedInvitationState = (\n ctx: Context,\n invitation: Invitation,\n stream: PushStream<Invitation>,\n): GuardedInvitationState => {\n // the mutex guards invitation flow on host and guest side, making sure only one flow is currently active\n // deadlocks seem very unlikely because hosts don't initiate multiple connections\n // even if this somehow happens that there are 2 guests (A, B) and 2 hosts (1, 2) and:\n // A has lock for flow with 1, B has lock for flow with 2\n // 1 has lock for flow with B, 2 has lock for flow with A\n // there'll be a 10-second introduction timeout after which connection will be closed and deadlock broken\n const mutex = new Mutex();\n let lastActiveLockHolder: FlowLockHolder | null = null;\n let currentInvitation = { ...invitation };\n const isStateChangeAllowed = (lockHolder: FlowLockHolder | null) => {\n if (ctx.disposed || (lockHolder !== null && mutex.isLocked() && !lockHolder.hasFlowLock())) {\n return false;\n }\n // don't allow transitions from a terminal state unless a new extension acquired mutex\n // handles a case when error occurs (e.g. connection is closed) after we completed the flow\n // successfully or already reported another error\n return lockHolder == null || lastActiveLockHolder !== lockHolder || isNonTerminalState(currentInvitation.state);\n };\n return {\n mutex,\n get current() {\n return currentInvitation;\n },\n // disposing context prevents any further state updates\n complete: (newState: Partial<Invitation>) => {\n logStateUpdate(currentInvitation, undefined, invitation.state);\n currentInvitation = { ...currentInvitation, ...newState };\n stream.next(currentInvitation);\n return ctx.dispose();\n },\n set: (lockHolder: FlowLockHolder | null, newState: Invitation.State): boolean => {\n if (isStateChangeAllowed(lockHolder)) {\n logStateUpdate(currentInvitation, lockHolder, newState);\n currentInvitation = { ...currentInvitation, state: newState };\n stream.next(currentInvitation);\n lastActiveLockHolder = lockHolder;\n return true;\n }\n return false;\n },\n error: (lockHolder: FlowLockHolder | null, error: any): boolean => {\n if (isStateChangeAllowed(lockHolder)) {\n logStateUpdate(currentInvitation, lockHolder, Invitation.State.ERROR, error);\n currentInvitation = { ...currentInvitation, state: Invitation.State.ERROR };\n stream.next(currentInvitation);\n stream.error(error);\n lastActiveLockHolder = lockHolder;\n return true;\n }\n return false;\n },\n };\n};\n\nconst logStateUpdate = (invitation: Invitation, actor: any, newState: Invitation.State, error?: Error) => {\n const logContext = {\n invitationId: invitation.invitationId,\n actor: actor?.constructor.name,\n newState: stateToString(newState),\n oldState: stateToString(invitation.state),\n error: error?.message,\n errorStack: error?.stack,\n };\n if (isNonTerminalState(newState)) {\n log.verbose('dxos.sdk.invitations-handler.state.update', logContext);\n } else {\n log.info('dxos.sdk.invitations-handler.state.update', logContext);\n }\n};\n\nconst isNonTerminalState = (currentState: Invitation.State): boolean => {\n return ![\n Invitation.State.SUCCESS,\n Invitation.State.ERROR,\n Invitation.State.CANCELLED,\n Invitation.State.TIMEOUT,\n Invitation.State.EXPIRED,\n ].includes(currentState);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport type { SwarmController, Topology } from '@dxos/network-manager';\nimport { InvitationOptions } from '@dxos/protocols/proto/dxos/halo/invitations';\nimport { ComplexSet } from '@dxos/util';\n\n/**\n * Hosts are listening on an invitation topic.\n * They initiate a connection with any new peer if they are not currently in the invitation flow\n * with another peer (connected.length > 0).\n * When the invitation flow ends guest leaves the swarm and topology is updated once again,\n * so we can connect to the next peer we haven't tried yet.\n * If the peer turns out to be a host or a malicious guest their ID is remembered so that we don't try\n * to establish a connection with them again.\n *\n * Guests don't initiate connections. They accept all connections because if we reject,\n * the host won't retry their offer.\n * Even if we started an invitation flow with one host we might want to try other hosts in case\n * the first one failed due to a network error, so multiple connections are accepted.\n */\nexport class InvitationTopology implements Topology {\n private _controller?: SwarmController;\n\n /**\n * Peers we tried to establish a connection with.\n * In invitation flow peers are assigned random ids when they join the swarm, so we'll retry\n * a peer if they reload an invitation.\n *\n * Consider keeping a separate set for peers we know are hosts and have some retry timeout\n * for guests we failed an invitation flow with (potentially due to a network error).\n */\n private _seenPeers = new ComplexSet<PublicKey>(PublicKey.hash);\n\n constructor(private readonly _role: InvitationOptions.Role) {}\n\n init(controller: SwarmController): void {\n invariant(!this._controller, 'Already initialized.');\n this._controller = controller;\n }\n\n update(): void {\n invariant(this._controller, 'Not initialized.');\n const { ownPeerId, candidates, connected, allPeers } = this._controller.getState();\n\n // guests don't initiate connections\n if (this._role === InvitationOptions.Role.GUEST) {\n return;\n }\n\n // don't start a connection while we have an active invitation flow\n if (connected.length > 0) {\n // update seenPeers here as well in case another host initiated a connection with us\n connected.forEach((c) => this._seenPeers.add(c));\n return;\n }\n\n const firstUnknownPeer = candidates.find((peerId) => !this._seenPeers.has(peerId));\n // cleanup\n this._seenPeers = new ComplexSet<PublicKey>(\n PublicKey.hash,\n allPeers.filter((peerId) => this._seenPeers.has(peerId)),\n );\n if (firstUnknownPeer != null) {\n log('invitation connect', { ownPeerId, remotePeerId: firstUnknownPeer });\n this._controller.connect(firstUnknownPeer);\n this._seenPeers.add(firstUnknownPeer);\n }\n }\n\n async onOffer(peer: PublicKey): Promise<boolean> {\n invariant(this._controller, 'Not initialized.');\n return !this._seenPeers.has(peer);\n }\n\n async destroy(): Promise<void> {\n this._seenPeers.clear();\n }\n\n toString() {\n return `InvitationTopology(${this._role === InvitationOptions.Role.GUEST ? 'guest' : 'host'})`;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport {\n type AuthenticationRequest,\n type AcceptInvitationRequest,\n type Invitation,\n type InvitationsService,\n QueryInvitationsResponse,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { trace } from '@dxos/tracing';\n\nimport { type InvitationsManager } from './invitations-manager';\n\n/**\n * Adapts invitation service observable to client/service stream.\n */\nexport class InvitationsServiceImpl implements InvitationsService {\n constructor(private readonly _invitationsManager: InvitationsManager) {}\n\n // TODO(burdon): Guest/host label.\n getLoggingContext() {\n return {\n // deviceKey: this._identityManager.identity?.deviceKey\n };\n }\n\n createInvitation(options: Invitation): Stream<Invitation> {\n return new Stream<Invitation>(({ next, close }) => {\n void this._invitationsManager\n .createInvitation(options)\n .then((invitation) => {\n trace.metrics.increment('dxos.invitation.created');\n invitation.subscribe(next, close, close);\n })\n .catch(close);\n });\n }\n\n acceptInvitation(request: AcceptInvitationRequest): Stream<Invitation> {\n const invitation = this._invitationsManager.acceptInvitation(request);\n return new Stream<Invitation>(({ next, close }) => {\n invitation.subscribe(next, close, close);\n });\n }\n\n async authenticate(request: AuthenticationRequest): Promise<void> {\n return this._invitationsManager.authenticate(request);\n }\n\n async cancelInvitation(request: { invitationId: string }): Promise<void> {\n return this._invitationsManager.cancelInvitation(request);\n }\n\n queryInvitations(): Stream<QueryInvitationsResponse> {\n return new Stream<QueryInvitationsResponse>(({ next, ctx }) => {\n // Push added invitations to the stream.\n this._invitationsManager.invitationCreated.on(ctx, (invitation) => {\n next({\n action: QueryInvitationsResponse.Action.ADDED,\n type: QueryInvitationsResponse.Type.CREATED,\n invitations: [invitation],\n });\n });\n\n this._invitationsManager.invitationAccepted.on(ctx, (invitation) => {\n next({\n action: QueryInvitationsResponse.Action.ADDED,\n type: QueryInvitationsResponse.Type.ACCEPTED,\n invitations: [invitation],\n });\n });\n\n // Push removed invitations to the stream.\n this._invitationsManager.removedCreated.on(ctx, (invitation) => {\n next({\n action: QueryInvitationsResponse.Action.REMOVED,\n type: QueryInvitationsResponse.Type.CREATED,\n invitations: [invitation],\n });\n });\n\n this._invitationsManager.removedAccepted.on(ctx, (invitation) => {\n next({\n action: QueryInvitationsResponse.Action.REMOVED,\n type: QueryInvitationsResponse.Type.ACCEPTED,\n invitations: [invitation],\n });\n });\n\n // used only for testing\n this._invitationsManager.saved.on(ctx, (invitation) => {\n next({\n action: QueryInvitationsResponse.Action.SAVED,\n type: QueryInvitationsResponse.Type.CREATED,\n invitations: [invitation],\n });\n });\n\n // Push existing invitations to the stream.\n next({\n action: QueryInvitationsResponse.Action.ADDED,\n type: QueryInvitationsResponse.Type.CREATED,\n invitations: this._invitationsManager.getCreatedInvitations(),\n existing: true,\n });\n\n next({\n action: QueryInvitationsResponse.Action.ADDED,\n type: QueryInvitationsResponse.Type.ACCEPTED,\n invitations: this._invitationsManager.getAcceptedInvitations(),\n existing: true,\n });\n\n this._invitationsManager.onPersistentInvitationsLoaded(ctx, () => {\n next({\n action: QueryInvitationsResponse.Action.LOAD_COMPLETE,\n type: QueryInvitationsResponse.Type.CREATED,\n // TODO(nf): populate with invitations\n });\n });\n // TODO(nf): expired invitations?\n });\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport {\n createCancelDelegatedSpaceInvitationCredential,\n createDelegatedSpaceInvitationCredential,\n getCredentialAssertion,\n} from '@dxos/credentials';\nimport { writeMessages } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { type Keyring } from '@dxos/keyring';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n AlreadyJoinedError,\n type ApiError,\n AuthorizationError,\n InvalidInvitationError,\n SpaceNotFoundError,\n} from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { SpaceMember, type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport {\n type AdmissionRequest,\n type AdmissionResponse,\n type IntroductionRequest,\n} from '@dxos/protocols/proto/dxos/halo/invitations';\n\nimport { type InvitationProtocol } from './invitation-protocol';\nimport { type DataSpaceManager, type SigningContext } from '../spaces';\n\nexport class SpaceInvitationProtocol implements InvitationProtocol {\n constructor(\n private readonly _spaceManager: DataSpaceManager,\n private readonly _signingContext: SigningContext,\n private readonly _keyring: Keyring,\n private readonly _spaceKey?: PublicKey,\n ) {}\n\n toJSON(): object {\n return {\n kind: 'space',\n deviceKey: this._signingContext.deviceKey,\n spaceKey: this._spaceKey,\n };\n }\n\n checkCanInviteNewMembers(): ApiError | undefined {\n if (this._spaceKey == null) {\n return new InvalidInvitationError('No spaceKey was provided for a space invitation.');\n }\n const space = this._spaceManager.spaces.get(this._spaceKey);\n if (space == null) {\n return new SpaceNotFoundError(this._spaceKey);\n }\n if (!space?.inner.spaceState.hasMembershipManagementPermission(this._signingContext.identityKey)) {\n return new AuthorizationError('No member management permission.');\n }\n return undefined;\n }\n\n getInvitationContext(): Partial<Invitation> & Pick<Invitation, 'kind'> {\n invariant(this._spaceKey);\n const space = this._spaceManager.spaces.get(this._spaceKey);\n invariant(space);\n return {\n kind: Invitation.Kind.SPACE,\n spaceKey: this._spaceKey,\n spaceId: space.id,\n };\n }\n\n async admit(\n invitation: Invitation,\n request: AdmissionRequest,\n guestProfile?: ProfileDocument | undefined,\n ): Promise<AdmissionResponse> {\n invariant(this._spaceKey && request.space);\n log('writing guest credentials', { host: this._signingContext.deviceKey, guest: request.space.deviceKey });\n\n const spaceMemberCredential = await this._spaceManager.admitMember({\n spaceKey: this._spaceKey,\n identityKey: request.space.identityKey,\n role: invitation.role ?? SpaceMember.Role.ADMIN,\n profile: guestProfile,\n delegationCredentialId: invitation.delegationCredentialId,\n });\n\n const space = this._spaceManager.spaces.get(this._spaceKey);\n return {\n space: {\n credential: spaceMemberCredential,\n controlTimeframe: space?.inner.controlPipeline.state.timeframe,\n },\n };\n }\n\n async delegate(invitation: Invitation): Promise<PublicKey> {\n invariant(this._spaceKey);\n const space = this._spaceManager.spaces.get(this._spaceKey);\n invariant(space);\n if (invitation.authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY) {\n invariant(invitation.guestKeypair?.publicKey);\n }\n\n log('writing delegate space invitation', { host: this._signingContext.deviceKey, id: invitation.invitationId });\n const credential = await createDelegatedSpaceInvitationCredential(\n this._signingContext.credentialSigner,\n space.key,\n {\n invitationId: invitation.invitationId,\n authMethod: invitation.authMethod,\n swarmKey: invitation.swarmKey,\n role: invitation.role ?? SpaceMember.Role.ADMIN,\n expiresOn: invitation.lifetime\n ? new Date((invitation.created?.getTime() ?? Date.now()) + invitation.lifetime)\n : undefined,\n multiUse: invitation.multiUse ?? false,\n guestKey:\n invitation.authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY\n ? invitation.guestKeypair!.publicKey\n : undefined,\n },\n );\n\n invariant(credential.credential);\n await writeMessages(space.inner.controlPipeline.writer, [credential]);\n return credential.credential.credential.id!;\n }\n\n async cancelDelegation(invitation: Invitation): Promise<void> {\n invariant(this._spaceKey);\n invariant(invitation.type === Invitation.Type.DELEGATED && invitation.delegationCredentialId);\n const space = this._spaceManager.spaces.get(this._spaceKey);\n invariant(space);\n\n log('cancelling delegated space invitation', { host: this._signingContext.deviceKey, id: invitation.invitationId });\n const credential = await createCancelDelegatedSpaceInvitationCredential(\n this._signingContext.credentialSigner,\n space.key,\n invitation.delegationCredentialId,\n );\n\n invariant(credential.credential);\n await writeMessages(space.inner.controlPipeline.writer, [credential]);\n }\n\n checkInvitation(invitation: Partial<Invitation>) {\n if (invitation.spaceKey == null) {\n return new InvalidInvitationError('No spaceKey was provided for a space invitation.');\n }\n if (this._spaceManager.spaces.has(invitation.spaceKey)) {\n return new AlreadyJoinedError('Already joined space.');\n }\n }\n\n createIntroduction(): IntroductionRequest {\n return {\n profile: this._signingContext.getProfile(),\n };\n }\n\n async createAdmissionRequest(): Promise<AdmissionRequest> {\n // Generate a pair of keys for our feeds.\n const controlFeedKey = await this._keyring.createKey();\n const dataFeedKey = await this._keyring.createKey();\n\n return {\n space: {\n identityKey: this._signingContext.identityKey,\n deviceKey: this._signingContext.deviceKey,\n controlFeedKey,\n dataFeedKey,\n },\n };\n }\n\n async accept(response: AdmissionResponse): Promise<Partial<Invitation>> {\n invariant(response.space);\n const { credential, controlTimeframe, dataTimeframe } = response.space;\n const assertion = getCredentialAssertion(credential);\n invariant(assertion['@type'] === 'dxos.halo.credentials.SpaceMember', 'Invalid credential');\n invariant(credential.subject.id.equals(this._signingContext.identityKey));\n\n if (this._spaceManager.spaces.has(assertion.spaceKey)) {\n throw new AlreadyJoinedError('Already joined space.');\n }\n\n // Create local space.\n await this._spaceManager.acceptSpace({\n spaceKey: assertion.spaceKey,\n genesisFeedKey: assertion.genesisFeedKey,\n controlTimeframe,\n dataTimeframe,\n });\n\n await this._signingContext.recordCredential(credential);\n\n return { spaceKey: assertion.spaceKey };\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event, PushStream, TimeoutError, Trigger } from '@dxos/async';\nimport {\n AuthenticatingInvitation,\n AUTHENTICATION_CODE_LENGTH,\n CancellableInvitation,\n INVITATION_TIMEOUT,\n} from '@dxos/client-protocol';\nimport { Context } from '@dxos/context';\nimport { generatePasscode } from '@dxos/credentials';\nimport { hasInvitationExpired, type MetadataStore } from '@dxos/echo-pipeline';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n type AcceptInvitationRequest,\n type AuthenticationRequest,\n Invitation,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { SpaceMember } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport type { InvitationProtocol } from './invitation-protocol';\nimport { createAdmissionKeypair, type InvitationsHandler } from './invitations-handler';\n\n/**\n * Entry point for creating and accepting invitations, keeps track of existing invitation set and\n * emits events when the set changes.\n */\nexport class InvitationsManager {\n private readonly _createInvitations = new Map<string, CancellableInvitation>();\n private readonly _acceptInvitations = new Map<string, AuthenticatingInvitation>();\n\n public readonly invitationCreated = new Event<Invitation>();\n public readonly invitationAccepted = new Event<Invitation>();\n public readonly removedCreated = new Event<Invitation>();\n public readonly removedAccepted = new Event<Invitation>();\n public readonly saved = new Event<Invitation>();\n\n private readonly _persistentInvitationsLoadedEvent = new Event();\n private _persistentInvitationsLoaded = false;\n\n constructor(\n private readonly _invitationsHandler: InvitationsHandler,\n private readonly _getHandler: (invitation: Partial<Invitation> & Pick<Invitation, 'kind'>) => InvitationProtocol,\n private readonly _metadataStore: MetadataStore,\n ) {}\n\n async createInvitation(options: Partial<Invitation> & Pick<Invitation, 'kind'>): Promise<CancellableInvitation> {\n if (options.invitationId) {\n const existingInvitation = this._createInvitations.get(options.invitationId);\n if (existingInvitation) {\n return existingInvitation;\n }\n }\n\n const handler = this._getHandler(options);\n const invitationError = handler.checkCanInviteNewMembers();\n if (invitationError != null) {\n throw invitationError;\n }\n const invitation = this._createInvitation(handler, options);\n\n const { ctx, stream, observableInvitation } = this._createObservableInvitation(handler, invitation);\n\n this._createInvitations.set(invitation.invitationId, observableInvitation);\n this.invitationCreated.emit(invitation);\n // onComplete is called on cancel, expiration, or redemption of a single-use invitation\n this._onInvitationComplete(observableInvitation, async () => {\n this._createInvitations.delete(observableInvitation.get().invitationId);\n this.removedCreated.emit(observableInvitation.get());\n if (observableInvitation.get().persistent) {\n await this._safeDeleteInvitation(observableInvitation.get());\n }\n });\n\n try {\n await this._persistIfRequired(handler, stream, invitation);\n } catch (err) {\n log.catch(err);\n await observableInvitation.cancel();\n return observableInvitation;\n }\n\n this._invitationsHandler.handleInvitationFlow(ctx, stream, handler, observableInvitation.get());\n\n return observableInvitation;\n }\n\n async loadPersistentInvitations(): Promise<{ invitations: Invitation[] }> {\n if (this._persistentInvitationsLoaded) {\n const invitations = this.getCreatedInvitations().filter((i) => i.persistent);\n return { invitations };\n }\n try {\n const persistentInvitations = this._metadataStore.getInvitations();\n // get saved persistent invitations, filter and remove from storage those that have expired.\n const freshInvitations = persistentInvitations.filter((invitation) => !hasInvitationExpired(invitation));\n\n const loadTasks = freshInvitations.map((persistentInvitation) => {\n invariant(!this._createInvitations.get(persistentInvitation.invitationId), 'invitation already exists');\n return this.createInvitation({ ...persistentInvitation, persistent: false });\n });\n const cInvitations = await Promise.all(loadTasks);\n\n return { invitations: cInvitations.map((invitation) => invitation.get()) };\n } catch (err) {\n log.catch(err);\n return { invitations: [] };\n } finally {\n this._persistentInvitationsLoadedEvent.emit();\n this._persistentInvitationsLoaded = true;\n }\n }\n\n acceptInvitation(request: AcceptInvitationRequest): AuthenticatingInvitation {\n const options = request.invitation;\n const existingInvitation = this._acceptInvitations.get(options.invitationId);\n if (existingInvitation) {\n return existingInvitation;\n }\n\n const handler = this._getHandler(options);\n const { ctx, invitation, stream, otpEnteredTrigger } = this._createObservableAcceptingInvitation(handler, options);\n this._invitationsHandler.acceptInvitation(ctx, stream, handler, options, otpEnteredTrigger, request.deviceProfile);\n this._acceptInvitations.set(invitation.get().invitationId, invitation);\n this.invitationAccepted.emit(invitation.get());\n\n this._onInvitationComplete(invitation, () => {\n this._acceptInvitations.delete(invitation.get().invitationId);\n this.removedAccepted.emit(invitation.get());\n });\n\n return invitation;\n }\n\n async authenticate({ invitationId, authCode }: AuthenticationRequest): Promise<void> {\n log('authenticating...');\n invariant(invitationId);\n const observable = this._acceptInvitations.get(invitationId);\n if (!observable) {\n log.warn('invalid invitation', { invitationId });\n } else {\n await observable.authenticate(authCode);\n }\n }\n\n async cancelInvitation({ invitationId }: { invitationId: string }): Promise<void> {\n log('cancelInvitation...', { invitationId });\n invariant(invitationId);\n const created = this._createInvitations.get(invitationId);\n if (created) {\n // remove from storage before modifying in-memory state, higher chance of failing\n if (created.get().persistent) {\n await this._metadataStore.removeInvitation(invitationId);\n }\n if (created.get().type === Invitation.Type.DELEGATED) {\n const handler = this._getHandler(created.get());\n await handler.cancelDelegation(created.get());\n }\n await created.cancel();\n this._createInvitations.delete(invitationId);\n this.removedCreated.emit(created.get());\n return;\n }\n\n const accepted = this._acceptInvitations.get(invitationId);\n if (accepted) {\n await accepted.cancel();\n this._acceptInvitations.delete(invitationId);\n this.removedAccepted.emit(accepted.get());\n }\n }\n\n getCreatedInvitations(): Invitation[] {\n return [...this._createInvitations.values()].map((i) => i.get());\n }\n\n getAcceptedInvitations(): Invitation[] {\n return [...this._acceptInvitations.values()].map((i) => i.get());\n }\n\n onPersistentInvitationsLoaded(ctx: Context, callback: () => void) {\n if (this._persistentInvitationsLoaded) {\n callback();\n } else {\n this._persistentInvitationsLoadedEvent.once(ctx, () => callback());\n }\n }\n\n private _createInvitation(protocol: InvitationProtocol, _options?: Partial<Invitation>): Invitation {\n const {\n invitationId = PublicKey.random().toHex(),\n type = Invitation.Type.INTERACTIVE,\n authMethod = Invitation.AuthMethod.SHARED_SECRET,\n state = Invitation.State.INIT,\n timeout = INVITATION_TIMEOUT,\n swarmKey = PublicKey.random(),\n persistent = _options?.authMethod !== Invitation.AuthMethod.KNOWN_PUBLIC_KEY, // default no not storing keypairs\n created = new Date(),\n guestKeypair = undefined,\n role = SpaceMember.Role.ADMIN,\n lifetime = 86400, // 1 day,\n multiUse = false,\n ...options\n } = _options ?? {};\n const authCode =\n options?.authCode ??\n (authMethod === Invitation.AuthMethod.SHARED_SECRET ? generatePasscode(AUTHENTICATION_CODE_LENGTH) : undefined);\n\n return {\n invitationId,\n type,\n authMethod,\n state,\n swarmKey,\n authCode,\n timeout,\n persistent: persistent && type !== Invitation.Type.DELEGATED, // delegated invitations are persisted in control feed\n guestKeypair:\n guestKeypair ?? (authMethod === Invitation.AuthMethod.KNOWN_PUBLIC_KEY ? createAdmissionKeypair() : undefined),\n created,\n lifetime,\n role,\n multiUse,\n delegationCredentialId: options?.delegationCredentialId,\n ...options,\n ...protocol.getInvitationContext(),\n } satisfies Invitation;\n }\n\n private _createObservableInvitation(handler: InvitationProtocol, invitation: Invitation) {\n const stream = new PushStream<Invitation>();\n const ctx = new Context({\n onError: (err) => {\n stream.error(err);\n void ctx.dispose();\n },\n });\n ctx.onDispose(() => {\n log('complete', { ...handler.toJSON() });\n stream.complete();\n });\n const observableInvitation = new CancellableInvitation({\n initialInvitation: invitation,\n subscriber: stream.observable,\n onCancel: async () => {\n stream.next({ ...invitation, state: Invitation.State.CANCELLED });\n await ctx.dispose();\n },\n });\n return { ctx, stream, observableInvitation };\n }\n\n private _createObservableAcceptingInvitation(handler: InvitationProtocol, initialState: Invitation) {\n const otpEnteredTrigger = new Trigger<string>();\n const stream = new PushStream<Invitation>();\n const ctx = new Context({\n onError: (err) => {\n if (err instanceof TimeoutError) {\n log('timeout', { ...handler.toJSON() });\n stream.next({ ...initialState, state: Invitation.State.TIMEOUT });\n } else {\n log.warn('auth failed', err);\n stream.next({ ...initialState, state: Invitation.State.ERROR });\n }\n void ctx.dispose();\n },\n });\n ctx.onDispose(() => {\n log('complete', { ...handler.toJSON() });\n stream.complete();\n });\n const invitation = new AuthenticatingInvitation({\n initialInvitation: initialState,\n subscriber: stream.observable,\n onCancel: async () => {\n stream.next({ ...initialState, state: Invitation.State.CANCELLED });\n await ctx.dispose();\n },\n onAuthenticate: async (code: string) => {\n // TODO(burdon): Reset creates a race condition? Event?\n otpEnteredTrigger.wake(code);\n },\n });\n return { ctx, invitation, stream, otpEnteredTrigger };\n }\n\n private async _persistIfRequired(\n handler: InvitationProtocol,\n changeStream: PushStream<Invitation>,\n invitation: Invitation,\n ): Promise<void> {\n if (invitation.type === Invitation.Type.DELEGATED && invitation.delegationCredentialId == null) {\n const delegationCredentialId = await handler.delegate(invitation);\n changeStream.next({ ...invitation, delegationCredentialId });\n } else if (invitation.persistent) {\n await this._metadataStore.addInvitation(invitation);\n this.saved.emit(invitation);\n }\n }\n\n private async _safeDeleteInvitation(invitation: Invitation): Promise<void> {\n try {\n await this._metadataStore.removeInvitation(invitation.invitationId);\n } catch (err) {\n log.catch(err);\n }\n }\n\n private _onInvitationComplete(invitation: CancellableInvitation, callback: () => void) {\n invitation.subscribe(\n () => {},\n () => {},\n callback,\n );\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { asyncTimeout, Trigger } from '@dxos/async';\nimport { RESOURCE_LOCK_TIMEOUT } from '@dxos/client-protocol';\nimport { log, logInfo } from '@dxos/log';\n\nimport { type ResourceLock, type ResourceLockOptions } from './resource-lock';\n\nenum Message {\n ACQUIRING = 'acquiring',\n}\n\n// TODO(mykola): Factor out.\n// TODO(burdon): Extend to support locking for web and NodeJS (use npm lockfile). Use to lock agents.\nexport class Lock implements ResourceLock {\n private readonly _broadcastChannel = new BroadcastChannel('vault-resource-lock');\n private readonly _lockKey: string;\n private readonly _onAcquire: ResourceLockOptions['onAcquire'];\n private readonly _onRelease: ResourceLockOptions['onRelease'];\n private _releaseTrigger = new Trigger();\n\n constructor({ lockKey, onAcquire, onRelease }: ResourceLockOptions) {\n this._lockKey = lockKey;\n this._onAcquire = onAcquire;\n this._onRelease = onRelease;\n this._broadcastChannel.onmessage = this._onMessage.bind(this);\n }\n\n @logInfo\n get lockKey() {\n return this._lockKey;\n }\n\n async acquire() {\n this._broadcastChannel.postMessage({\n message: Message.ACQUIRING,\n });\n\n try {\n log('aquiring lock...');\n await asyncTimeout(this._requestLock(), RESOURCE_LOCK_TIMEOUT);\n log('acquired lock');\n } catch {\n log('stealing lock...');\n await this._requestLock(true);\n log('stolen lock');\n }\n }\n\n async release() {\n this._releaseTrigger.wake();\n }\n\n private _onMessage(event: MessageEvent<any>) {\n if (event.data.message === Message.ACQUIRING) {\n this._releaseTrigger.wake();\n }\n }\n\n private async _requestLock(steal = false) {\n log('requesting lock...', { steal });\n const acquired = new Trigger();\n\n void navigator.locks\n .request(this._lockKey, { steal }, async () => {\n await this._onAcquire?.();\n acquired.wake();\n this._releaseTrigger = new Trigger();\n await this._releaseTrigger.wait();\n log('releasing lock...');\n await this._onRelease?.();\n log('released lock');\n })\n .catch(async () => {\n await this._onRelease?.();\n });\n\n await acquired.wait();\n log('recieved lock', { steal });\n }\n}\n\n// TODO(mykola): Implement.\nexport const isLocked = (lockPath: string) => {\n throw new Error('Not implemented');\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type ClientServices } from '@dxos/client-protocol';\nimport { type Any, type ServiceHandler, Stream } from '@dxos/codec-protobuf';\nimport { raise } from '@dxos/debug';\nimport { parseMethodName, RpcPeer, type RpcPeerOptions, type ServiceBundle } from '@dxos/rpc';\nimport { MapCounter, trace } from '@dxos/tracing';\nimport { type MaybePromise } from '@dxos/util';\n\nimport { type ServiceRegistry } from './service-registry';\n\nexport type ClientRpcServerParams = {\n serviceRegistry: ServiceRegistry<ClientServices>;\n handleCall?: (\n method: string,\n params: Any,\n handler: (method: string, params: Any) => MaybePromise<Any>,\n ) => Promise<Any>;\n handleStream?: (\n method: string,\n params: Any,\n handler: (method: string, params: Any) => Stream<Any>,\n ) => MaybePromise<Stream<Any>>;\n} & Omit<RpcPeerOptions, 'callHandler' | 'streamHandler'>;\n\n@trace.resource()\nexport class ClientRpcServer {\n private readonly _serviceRegistry: ServiceRegistry<ClientServices>;\n private readonly _rpcPeer: RpcPeer;\n private readonly _handlerCache = new Map<string, ServiceHandler<any>>();\n private readonly _handleCall: ClientRpcServerParams['handleCall'];\n private readonly _handleStream: ClientRpcServerParams['handleStream'];\n\n @trace.metricsCounter()\n private readonly _callMetrics = new MapCounter();\n\n @trace.info()\n private get _services() {\n return Object.keys(this._serviceRegistry.services);\n }\n\n constructor(params: ClientRpcServerParams) {\n const { serviceRegistry, handleCall, handleStream, ...rpcOptions } = params;\n this._handleCall = handleCall;\n this._handleStream = handleStream;\n\n this._serviceRegistry = serviceRegistry;\n this._rpcPeer = new RpcPeer({\n ...rpcOptions,\n callHandler: (method, params) => {\n const [serviceName, methodName] = parseMethodName(method);\n const handler = (method: string, params: Any) => this._getServiceHandler(serviceName).call(method, params);\n\n this._callMetrics.inc(`${serviceName}.${methodName} request`);\n\n if (this._handleCall) {\n return this._handleCall(methodName, params, handler);\n } else {\n return handler(methodName, params);\n }\n },\n streamHandler: (method, params) => {\n const [serviceName, methodName] = parseMethodName(method);\n const handler = (method: string, params: Any) =>\n this._getServiceHandler(serviceName).callStream(method, params);\n\n this._callMetrics.inc(`${serviceName}.${methodName} request stream`);\n\n if (this._handleStream) {\n return Stream.map(Stream.unwrapPromise(this._handleStream(methodName, params, handler)), (data) => {\n this._callMetrics.inc(`${serviceName}.${methodName} response stream`);\n return data;\n });\n } else {\n return handler(methodName, params);\n }\n },\n });\n }\n\n async open() {\n await this._rpcPeer.open();\n }\n\n async close() {\n await this._rpcPeer.close();\n }\n\n private _getServiceHandler(serviceName: string) {\n if (!this._handlerCache.has(serviceName)) {\n const [key, descriptor] =\n Object.entries(this._serviceRegistry.descriptors as ServiceBundle<Record<string, any>>).find(\n ([key, descriptor]) => descriptor.name === serviceName,\n ) ?? raise(new Error(`Service not available: ${serviceName}`));\n\n const service = this._serviceRegistry.services[key as keyof ClientServices] as any;\n if (!service) {\n throw new Error(`Service not available: ${serviceName}`);\n }\n\n this._handlerCache.set(serviceName, descriptor.createServer(service));\n }\n\n return this._handlerCache.get(serviceName)!;\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { DeferredTask, Event, scheduleTask, synchronized } from '@dxos/async';\nimport { Resource } from '@dxos/context';\nimport { type EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { EdgeAgentStatus, EdgeCallFailedError } from '@dxos/protocols';\nimport { SpaceState } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\n\nimport { type Identity } from '../identity';\nimport { type DataSpaceManager } from '../spaces';\n\nconst AGENT_STATUS_QUERY_RETRY_INTERVAL = 5000;\nconst AGENT_STATUS_QUERY_RETRY_JITTER = 1000;\n\nexport type EdgeAgentManagerConfig = {};\n\nexport class EdgeAgentManager extends Resource {\n public agentStatusChanged = new Event<EdgeAgentStatus>();\n\n private _agentDeviceKey: PublicKey | undefined;\n private _agentStatus: EdgeAgentStatus | undefined;\n\n private _lastKnownDeviceCount = 0;\n\n private _fetchAgentStatusTask: DeferredTask | undefined;\n\n constructor(\n private readonly _edgeFeatures: Runtime.Client.EdgeFeatures | undefined,\n private readonly _edgeHttpClient: EdgeHttpClient | undefined,\n private readonly _dataSpaceManager: DataSpaceManager,\n private readonly _identity: Identity,\n ) {\n super();\n }\n\n public get agentStatus(): EdgeAgentStatus | undefined {\n return this._agentStatus;\n }\n\n public get agentExists() {\n return this._agentStatus && this._agentStatus !== EdgeAgentStatus.NOT_FOUND;\n }\n\n @synchronized\n public async createAgent() {\n invariant(this.isOpen);\n invariant(this._edgeHttpClient);\n invariant(this._edgeFeatures?.agents);\n\n const response = await this._edgeHttpClient.createAgent({\n identityKey: this._identity.identityKey.toHex(),\n haloSpaceId: this._identity.haloSpaceId,\n haloSpaceKey: this._identity.haloSpaceKey.toHex(),\n });\n\n const deviceKey = PublicKey.fromHex(response.deviceKey);\n\n await this._identity.admitDevice({\n deviceKey,\n controlFeedKey: PublicKey.fromHex(response.feedKey),\n // TODO: agents don't have data feed, should be removed\n dataFeedKey: PublicKey.random(),\n });\n\n log('agent created', response);\n\n this._updateStatus(EdgeAgentStatus.ACTIVE, deviceKey);\n }\n\n protected override async _open() {\n const isEnabled = this._edgeHttpClient && this._edgeFeatures?.agents;\n\n log('edge agent manager open', { isEnabled });\n\n if (!isEnabled) {\n return;\n }\n\n this._lastKnownDeviceCount = this._identity.authorizedDeviceKeys.size;\n this._fetchAgentStatusTask = new DeferredTask(this._ctx, async () => {\n await this._fetchAgentStatus();\n });\n this._fetchAgentStatusTask.schedule();\n\n this._dataSpaceManager.updated.on(this._ctx, () => {\n if (this._agentDeviceKey) {\n this._ensureAgentIsInSpaces(this._agentDeviceKey);\n }\n });\n\n this._identity.stateUpdate.on(this._ctx, () => {\n const maybeAgentWasCreated = this._identity.authorizedDeviceKeys.size > this._lastKnownDeviceCount;\n if (this.agentExists || !maybeAgentWasCreated) {\n return;\n }\n this._lastKnownDeviceCount = this._identity.authorizedDeviceKeys.size;\n this._fetchAgentStatusTask?.schedule();\n });\n }\n\n protected override async _close() {\n this._fetchAgentStatusTask = undefined;\n this._lastKnownDeviceCount = 0;\n }\n\n protected async _fetchAgentStatus() {\n invariant(this._edgeHttpClient);\n try {\n log('fetching agent status');\n const { agent } = await this._edgeHttpClient.getAgentStatus({ ownerIdentityKey: this._identity.identityKey });\n const wasAgentCreatedDuringQuery = this._agentStatus === EdgeAgentStatus.ACTIVE;\n if (!wasAgentCreatedDuringQuery) {\n const deviceKey = agent.deviceKey ? PublicKey.fromHex(agent.deviceKey) : undefined;\n this._updateStatus(agent.status, deviceKey);\n }\n } catch (err) {\n if (err instanceof EdgeCallFailedError) {\n if (!err.isRetryable) {\n log.warn('non retryable error on agent status fetch attempt', { err });\n return;\n }\n }\n const retryAfterMs = AGENT_STATUS_QUERY_RETRY_INTERVAL + Math.random() * AGENT_STATUS_QUERY_RETRY_JITTER;\n log.info('agent status fetching failed', { err, retryAfterMs });\n scheduleTask(this._ctx, () => this._fetchAgentStatusTask?.schedule(), retryAfterMs);\n }\n }\n\n /**\n * We don't want notarization plugin to always actively poll edge looking for credentials to notarize,\n * because most of the time we'll be getting an empty response.\n * Instead, we stay in active polling mode while there are spaces where we don't see our agent's feed.\n */\n protected _ensureAgentIsInSpaces(agentDeviceKey: PublicKey) {\n for (const space of this._dataSpaceManager.spaces.values()) {\n if ([SpaceState.SPACE_INACTIVE, SpaceState.SPACE_CLOSED].includes(space.state)) {\n continue;\n }\n const agentFeedNeedsNotarization = ![...space.inner.spaceState.feeds.values()].some((feed) =>\n feed.assertion.deviceKey.equals(agentDeviceKey),\n );\n space.notarizationPlugin.setActiveEdgePollingEnabled(agentFeedNeedsNotarization);\n\n log.info('set active edge polling', { enabled: agentFeedNeedsNotarization, spaceId: space.id });\n }\n }\n\n private _updateStatus(status: EdgeAgentStatus, deviceKey: PublicKey | undefined) {\n this._agentStatus = status;\n this._agentDeviceKey = deviceKey;\n this.agentStatusChanged.emit(status);\n if (deviceKey) {\n this._ensureAgentIsInSpaces(deviceKey);\n }\n log.info('agent status update', { status });\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { EdgeAgentStatus } from '@dxos/protocols';\nimport { QueryAgentStatusResponse, type EdgeAgentService } from '@dxos/protocols/proto/dxos/client/services';\n\nimport { type EdgeAgentManager } from './edge-agent-manager';\n\nexport class EdgeAgentServiceImpl implements EdgeAgentService {\n constructor(private readonly _agentManagerProvider: () => Promise<EdgeAgentManager>) {}\n\n public async createAgent(): Promise<void> {\n return (await this._agentManagerProvider()).createAgent();\n }\n\n queryAgentStatus(): Stream<QueryAgentStatusResponse> {\n return new Stream(({ ctx, next }) => {\n next({ status: QueryAgentStatusResponse.AgentStatus.UNKNOWN });\n void this._agentManagerProvider().then((agentManager) => {\n next({ status: mapStatus(agentManager.agentStatus) });\n agentManager.agentStatusChanged.on(ctx, (newStatus) => {\n next({ status: mapStatus(newStatus) });\n });\n });\n });\n }\n}\n\nconst mapStatus = (agentStatus: EdgeAgentStatus | undefined): QueryAgentStatusResponse.AgentStatus => {\n switch (agentStatus) {\n case EdgeAgentStatus.ACTIVE:\n return QueryAgentStatusResponse.AgentStatus.ACTIVE;\n case EdgeAgentStatus.INACTIVE:\n return QueryAgentStatusResponse.AgentStatus.INACTIVE;\n case EdgeAgentStatus.NOT_FOUND:\n return QueryAgentStatusResponse.AgentStatus.NOT_FOUND;\n case undefined:\n return QueryAgentStatusResponse.AgentStatus.UNKNOWN;\n }\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Mutex, Trigger } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { getCredentialAssertion, type CredentialProcessor } from '@dxos/credentials';\nimport { failUndefined, warnAfterTimeout } from '@dxos/debug';\nimport {\n EchoEdgeReplicator,\n EchoHost,\n MeshEchoReplicator,\n MetadataStore,\n SpaceManager,\n valueEncoding,\n} from '@dxos/echo-pipeline';\nimport { createChainEdgeIdentity, createEphemeralEdgeIdentity } from '@dxos/edge-client';\nimport type { EdgeHttpClient, EdgeConnection, EdgeIdentity } from '@dxos/edge-client';\nimport { FeedFactory, FeedStore } from '@dxos/feed-store';\nimport { invariant } from '@dxos/invariant';\nimport { Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { type LevelDB } from '@dxos/kv-store';\nimport { log } from '@dxos/log';\nimport { type SignalManager } from '@dxos/messaging';\nimport { type SwarmNetworkManager } from '@dxos/network-manager';\nimport { InvalidStorageVersionError, STORAGE_VERSION, trace } from '@dxos/protocols';\nimport { Invitation } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\nimport type { FeedMessage } from '@dxos/protocols/proto/dxos/echo/feed';\nimport { type Credential, type ProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { type Storage } from '@dxos/random-access-storage';\nimport { BlobStore } from '@dxos/teleport-extension-object-sync';\nimport { trace as Trace } from '@dxos/tracing';\nimport { safeInstanceof } from '@dxos/util';\n\nimport { EdgeAgentManager } from '../agents';\nimport {\n IdentityManager,\n type CreateIdentityOptions,\n type IdentityManagerParams,\n type JoinIdentityParams,\n} from '../identity';\nimport { EdgeIdentityRecoveryManager } from '../identity/identity-recovery-manager';\nimport {\n DeviceInvitationProtocol,\n type InvitationConnectionParams,\n InvitationsHandler,\n InvitationsManager,\n SpaceInvitationProtocol,\n type InvitationProtocol,\n} from '../invitations';\nimport { DataSpaceManager, type DataSpaceManagerRuntimeParams, type SigningContext } from '../spaces';\n\nexport type ServiceContextRuntimeParams = Pick<\n IdentityManagerParams,\n 'devicePresenceOfflineTimeout' | 'devicePresenceAnnounceInterval'\n> &\n DataSpaceManagerRuntimeParams & {\n invitationConnectionDefaultParams?: InvitationConnectionParams;\n disableP2pReplication?: boolean;\n };\n/**\n * Shared backend for all client services.\n */\n// TODO(burdon): Rename/break-up into smaller components. And/or make members private.\n// TODO(dmaretskyi): Gets duplicated in CJS build between normal and testing bundles.\n@safeInstanceof('dxos.client-services.ServiceContext')\n@Trace.resource()\nexport class ServiceContext extends Resource {\n private readonly _edgeIdentityUpdateMutex = new Mutex();\n\n public readonly initialized = new Trigger();\n public readonly metadataStore: MetadataStore;\n public readonly blobStore: BlobStore;\n public readonly feedStore: FeedStore<FeedMessage>;\n public readonly keyring: Keyring;\n public readonly spaceManager: SpaceManager;\n public readonly identityManager: IdentityManager;\n public readonly recoveryManager: EdgeIdentityRecoveryManager;\n public readonly invitations: InvitationsHandler;\n public readonly invitationsManager: InvitationsManager;\n public readonly echoHost: EchoHost;\n private readonly _meshReplicator?: MeshEchoReplicator = undefined;\n private readonly _echoEdgeReplicator?: EchoEdgeReplicator = undefined;\n\n // Initialized after identity is initialized.\n public dataSpaceManager?: DataSpaceManager;\n public edgeAgentManager?: EdgeAgentManager;\n\n private readonly _handlerFactories = new Map<\n Invitation.Kind,\n (invitation: Partial<Invitation>) => InvitationProtocol\n >();\n\n private _deviceSpaceSync?: CredentialProcessor;\n\n private readonly _instanceId = PublicKey.random().toHex();\n\n constructor(\n public readonly storage: Storage,\n public readonly level: LevelDB,\n public readonly networkManager: SwarmNetworkManager,\n public readonly signalManager: SignalManager,\n private readonly _edgeConnection: EdgeConnection | undefined,\n private readonly _edgeHttpClient: EdgeHttpClient | undefined,\n public readonly _runtimeParams?: ServiceContextRuntimeParams,\n private readonly _edgeFeatures?: Runtime.Client.EdgeFeatures,\n ) {\n super();\n\n // TODO(burdon): Move strings to constants.\n this.metadataStore = new MetadataStore(storage.createDirectory('metadata'));\n this.blobStore = new BlobStore(storage.createDirectory('blobs'));\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 stats: true,\n },\n }),\n });\n\n this.spaceManager = new SpaceManager({\n feedStore: this.feedStore,\n networkManager: this.networkManager,\n blobStore: this.blobStore,\n metadataStore: this.metadataStore,\n disableP2pReplication: this._runtimeParams?.disableP2pReplication,\n });\n\n this.identityManager = new IdentityManager({\n metadataStore: this.metadataStore,\n keyring: this.keyring,\n feedStore: this.feedStore,\n spaceManager: this.spaceManager,\n devicePresenceOfflineTimeout: this._runtimeParams?.devicePresenceOfflineTimeout,\n devicePresenceAnnounceInterval: this._runtimeParams?.devicePresenceAnnounceInterval,\n edgeConnection: this._edgeConnection,\n edgeFeatures: this._edgeFeatures,\n });\n\n this.recoveryManager = new EdgeIdentityRecoveryManager(\n this.keyring,\n this._edgeHttpClient,\n () => this.identityManager.identity,\n this._acceptIdentity.bind(this),\n );\n\n this.echoHost = new EchoHost({ kv: this.level });\n\n this._meshReplicator = new MeshEchoReplicator();\n\n this.invitations = new InvitationsHandler(\n this.networkManager, //\n this._edgeHttpClient,\n _runtimeParams?.invitationConnectionDefaultParams,\n );\n this.invitationsManager = new InvitationsManager(\n this.invitations,\n (invitation) => this.getInvitationHandler(invitation),\n this.metadataStore,\n );\n\n // TODO(burdon): _initialize called in multiple places.\n // TODO(burdon): Call _initialize on success.\n this._handlerFactories.set(\n Invitation.Kind.DEVICE,\n () =>\n new DeviceInvitationProtocol(\n this.keyring,\n () => this.identityManager.identity ?? failUndefined(),\n this._acceptIdentity.bind(this),\n ),\n );\n\n if (!this._runtimeParams?.disableP2pReplication) {\n this._meshReplicator = new MeshEchoReplicator();\n }\n if (this._edgeConnection && this._edgeFeatures?.echoReplicator) {\n this._echoEdgeReplicator = new EchoEdgeReplicator({\n edgeConnection: this._edgeConnection,\n });\n }\n }\n\n @Trace.span()\n protected override async _open(ctx: Context) {\n await this._checkStorageVersion();\n\n log('opening...');\n log.trace('dxos.sdk.service-context.open', trace.begin({ id: this._instanceId }));\n\n await this.identityManager.open(ctx);\n\n await this._setNetworkIdentity();\n\n await this._edgeConnection?.open();\n await this.signalManager.open();\n await this.networkManager.open();\n\n await this.echoHost.open(ctx);\n\n if (this._meshReplicator) {\n await this.echoHost.addReplicator(this._meshReplicator);\n }\n if (this._echoEdgeReplicator) {\n await this.echoHost.addReplicator(this._echoEdgeReplicator);\n }\n\n await this.metadataStore.load();\n await this.spaceManager.open();\n\n if (this.identityManager.identity) {\n await this.identityManager.identity.joinNetwork();\n await this._initialize(ctx);\n }\n\n const loadedInvitations = await this.invitationsManager.loadPersistentInvitations();\n log('loaded persistent invitations', { count: loadedInvitations.invitations?.length });\n\n log.trace('dxos.sdk.service-context.open', trace.end({ id: this._instanceId }));\n log('opened');\n }\n\n protected override async _close(ctx: Context) {\n log('closing...');\n if (this._deviceSpaceSync && this.identityManager.identity) {\n await this.identityManager.identity.space.spaceState.removeCredentialProcessor(this._deviceSpaceSync);\n }\n await this.dataSpaceManager?.close();\n await this.edgeAgentManager?.close();\n await this.identityManager.close();\n await this.spaceManager.close();\n await this.feedStore.close();\n await this.metadataStore.close();\n\n await this.echoHost.close(ctx);\n await this.networkManager.close();\n await this.signalManager.close();\n await this._edgeConnection?.close();\n\n log('closed');\n }\n\n async createIdentity(params: CreateIdentityOptions = {}) {\n const identity = await this.identityManager.createIdentity(params);\n await this._setNetworkIdentity();\n await identity.joinNetwork();\n await this._initialize(new Context());\n return identity;\n }\n\n getInvitationHandler(invitation: Partial<Invitation> & Pick<Invitation, 'kind'>): InvitationProtocol {\n if (this.identityManager.identity == null && invitation.kind === Invitation.Kind.SPACE) {\n throw new Error('Identity must be created before joining a space.');\n }\n const factory = this._handlerFactories.get(invitation.kind);\n invariant(factory, `Unknown invitation kind: ${invitation.kind}`);\n return factory(invitation);\n }\n\n async broadcastProfileUpdate(profile: ProfileDocument | undefined) {\n if (!profile || !this.dataSpaceManager) {\n return;\n }\n\n for (const space of this.dataSpaceManager.spaces.values()) {\n await space.updateOwnProfile(profile);\n }\n }\n\n private async _acceptIdentity(params: JoinIdentityParams) {\n const { identity, identityRecord } = await this.identityManager.prepareIdentity(params);\n await this._setNetworkIdentity({ deviceCredential: params.authorizedDeviceCredential! });\n await identity.joinNetwork();\n await this.identityManager.acceptIdentity(identity, identityRecord, params.deviceProfile);\n await this._initialize(new Context());\n return identity;\n }\n\n private async _checkStorageVersion() {\n await this.metadataStore.load();\n if (this.metadataStore.version !== STORAGE_VERSION) {\n throw new InvalidStorageVersionError(STORAGE_VERSION, this.metadataStore.version);\n // TODO(mykola): Migrate storage to a new version if incompatibility is detected.\n }\n }\n\n // Called when identity is created.\n @Trace.span()\n private async _initialize(ctx: Context) {\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 getProfile: () => identity.profileDocument,\n recordCredential: async (credential) => {\n await identity.controlPipeline.writer.write({ credential: { credential } });\n },\n };\n\n this.dataSpaceManager = new DataSpaceManager({\n spaceManager: this.spaceManager,\n metadataStore: this.metadataStore,\n keyring: this.keyring,\n signingContext,\n feedStore: this.feedStore,\n echoHost: this.echoHost,\n invitationsManager: this.invitationsManager,\n edgeConnection: this._edgeConnection,\n edgeHttpClient: this._edgeHttpClient,\n echoEdgeReplicator: this._echoEdgeReplicator,\n meshReplicator: this._meshReplicator,\n runtimeParams: this._runtimeParams as DataSpaceManagerRuntimeParams,\n edgeFeatures: this._edgeFeatures,\n });\n await this.dataSpaceManager.open();\n\n this.edgeAgentManager = new EdgeAgentManager(\n this._edgeFeatures,\n this._edgeHttpClient,\n this.dataSpaceManager,\n identity,\n );\n await this.edgeAgentManager.open();\n\n this._handlerFactories.set(Invitation.Kind.SPACE, (invitation) => {\n invariant(this.dataSpaceManager, 'dataSpaceManager not initialized yet');\n return new SpaceInvitationProtocol(this.dataSpaceManager, signingContext, this.keyring, invitation.spaceKey);\n });\n this.initialized.wake();\n\n this._deviceSpaceSync = {\n processCredential: async (credential: Credential) => {\n const assertion = getCredentialAssertion(credential);\n if (assertion['@type'] !== 'dxos.halo.credentials.SpaceMember') {\n return;\n }\n if (assertion.spaceKey.equals(identity.space.key)) {\n // ignore halo space\n return;\n }\n if (!this.dataSpaceManager) {\n log('dataSpaceManager not initialized yet, ignoring space admission', { details: assertion });\n return;\n }\n if (this.dataSpaceManager.spaces.has(assertion.spaceKey)) {\n log('space already exists, ignoring space admission', { details: assertion });\n return;\n }\n\n try {\n log('accepting space recorded in halo', { details: assertion });\n await this.dataSpaceManager.acceptSpace({\n spaceKey: assertion.spaceKey,\n genesisFeedKey: assertion.genesisFeedKey,\n });\n } catch (err) {\n log.catch(err);\n }\n },\n };\n\n await identity.space.spaceState.addCredentialProcessor(this._deviceSpaceSync);\n }\n\n private async _setNetworkIdentity(params?: { deviceCredential: Credential }) {\n using _ = await this._edgeIdentityUpdateMutex.acquire();\n\n let edgeIdentity: EdgeIdentity;\n const identity = this.identityManager.identity;\n if (identity) {\n log.info('Setting identity on edge connection', {\n identity: identity.identityKey.toHex(),\n swarms: this.networkManager.topics,\n });\n if (params?.deviceCredential) {\n edgeIdentity = await createChainEdgeIdentity(\n identity.signer,\n identity.identityKey,\n identity.deviceKey,\n params?.deviceCredential && { credential: params.deviceCredential },\n [], // TODO(dmaretskyi): Service access credentials.\n );\n } else {\n // TODO: throw here or from identity if device chain can't be loaded, to avoid indefinite hangup\n await warnAfterTimeout(10_000, 'Waiting for identity to be ready for edge connection', async () => {\n await identity.ready();\n });\n\n invariant(identity.deviceCredentialChain);\n\n edgeIdentity = await createChainEdgeIdentity(\n identity.signer,\n identity.identityKey,\n identity.deviceKey,\n identity.deviceCredentialChain,\n [], // TODO(dmaretskyi): Service access credentials.\n );\n }\n } else {\n edgeIdentity = await createEphemeralEdgeIdentity();\n }\n\n this._edgeConnection?.setIdentity(edgeIdentity);\n this._edgeHttpClient?.setIdentity(edgeIdentity);\n this.networkManager.setPeerInfo({\n identityKey: edgeIdentity.identityKey,\n peerKey: edgeIdentity.peerKey,\n });\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { generateSeedPhrase, keyPairFromSeedPhrase } from '@dxos/credentials';\nimport { sign } from '@dxos/crypto';\nimport { type EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { type Keyring } from '@dxos/keyring';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { EdgeAuthChallengeError, type RecoverIdentityRequest, type RecoverIdentityResponseBody } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { Timeframe } from '@dxos/timeframe';\n\nimport { type Identity } from './identity';\nimport { type JoinIdentityParams } from './identity-manager';\n\nexport class EdgeIdentityRecoveryManager {\n constructor(\n private readonly _keyring: Keyring,\n private readonly _edgeClient: EdgeHttpClient | undefined,\n private readonly _identityProvider: () => Identity | undefined,\n private readonly _acceptRecoveredIdentity: (params: JoinIdentityParams) => Promise<Identity>,\n ) {}\n\n public async createRecoveryPhrase() {\n const identity = this._identityProvider();\n invariant(identity);\n\n const seedphrase = generateSeedPhrase();\n const keypair = keyPairFromSeedPhrase(seedphrase);\n const recoveryKey = PublicKey.from(keypair.publicKey);\n const identityKey = identity.identityKey;\n const credential = await identity.getIdentityCredentialSigner().createCredential({\n subject: identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.IdentityRecovery',\n recoveryKey,\n identityKey,\n },\n });\n\n const receipt = await identity.controlPipeline.writer.write({ credential: { credential } });\n await identity.controlPipeline.state.waitUntilTimeframe(new Timeframe([[receipt.feedKey, receipt.seq]]));\n\n return { seedphrase };\n }\n\n public async recoverIdentity(args: { seedphrase: string }) {\n invariant(this._edgeClient, 'Not connected to EDGE.');\n\n const recoveryKeypair = keyPairFromSeedPhrase(args.seedphrase);\n const recoveryKey = PublicKey.from(recoveryKeypair.publicKey);\n const deviceKey = await this._keyring.createKey();\n const controlFeedKey = await this._keyring.createKey();\n const request: RecoverIdentityRequest = {\n recoveryKey: recoveryKey.toHex(),\n deviceKey: deviceKey.toHex(),\n controlFeedKey: controlFeedKey.toHex(),\n };\n\n let response: RecoverIdentityResponseBody;\n try {\n response = await this._edgeClient.recoverIdentity(request);\n } catch (error: any) {\n if (!(error instanceof EdgeAuthChallengeError)) {\n throw error;\n }\n const signature = sign(Buffer.from(error.challenge, 'base64'), recoveryKeypair.secretKey);\n response = await this._edgeClient.recoverIdentity({\n ...request,\n signature: Buffer.from(signature).toString('base64'),\n });\n }\n\n log.info('recovering identity', response);\n\n await this._acceptRecoveredIdentity({\n authorizedDeviceCredential: decodeCredential(response.deviceAuthCredential),\n haloGenesisFeedKey: PublicKey.fromHex(response.genesisFeedKey),\n haloSpaceKey: PublicKey.fromHex(response.haloSpaceKey),\n identityKey: PublicKey.fromHex(response.identityKey),\n deviceKey,\n controlFeedKey,\n dataFeedKey: await this._keyring.createKey(),\n });\n }\n}\n\nconst decodeCredential = (credentialBase64: string) => {\n const credentialBytes = Buffer.from(credentialBase64, 'base64');\n const codec = schema.getCodecForType('dxos.halo.credentials.Credential');\n return codec.decode(credentialBytes);\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type 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 _handlers: Partial<Services> = {}\n ) {}\n\n get descriptors() {\n return this._serviceBundle;\n }\n\n get services() {\n return this._handlers;\n }\n\n setServices(services: Partial<Services>) {\n this._handlers = services;\n }\n\n addService(name: keyof Services, service: Services[keyof Services]) {\n this._handlers[name] = service;\n }\n\n removeService(name: keyof Services) {\n delete this._handlers[name];\n }\n}\n", "//\n\n//\n// Copyright 2023 DXOS.org\n//\n\nimport { InvalidConfigError } from '@dxos/protocols';\nimport { Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { createStorage, StorageType } from '@dxos/random-access-storage';\n\nimport StorageDriver = Runtime.Client.Storage.StorageDriver;\nimport { getRootPath } from './util';\n\n// TODO(burdon): Factor out.\nexport const createStorageObjects = (config: Runtime.Client.Storage) => {\n const { persistent = false, keyStore, dataStore } = config ?? {};\n if (persistent && dataStore === StorageDriver.RAM) {\n throw new InvalidConfigError('RAM storage cannot be used in persistent mode.');\n }\n if (!persistent && dataStore !== undefined && dataStore !== StorageDriver.RAM) {\n throw new InvalidConfigError('Cannot use a persistent storage in not persistent mode.');\n }\n if (persistent && keyStore === StorageDriver.RAM) {\n throw new InvalidConfigError('RAM key storage cannot be used in persistent mode.');\n }\n if (!persistent && keyStore !== StorageDriver.RAM && keyStore !== 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(dataStore) : StorageType.RAM,\n root: getRootPath(config),\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 case StorageDriver.WEBFS:\n return StorageType.WEBFS;\n default:\n throw new Error(`Invalid storage type: ${StorageDriver[type]}`);\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { DX_DATA } from '@dxos/client-protocol';\nimport { Runtime } from '@dxos/protocols/proto/dxos/config';\nimport { isNode } from '@dxos/util';\n\nexport const getRootPath = (config: Runtime.Client.Storage) => {\n const { dataRoot = isNode() ? DX_DATA : 'dxos/storage' } = config ?? {};\n return `${dataRoot}/`;\n};\n\nexport const isPersistent = (config: Runtime.Client.Storage) => {\n const { persistent = false } = config ?? {};\n return (\n (config.dataStore !== undefined && config.dataStore !== Runtime.Client.Storage.StorageDriver.RAM) || persistent\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport path from 'node:path';\n\nimport { PublicKey } from '@dxos/keys';\nimport { createLevel as createKV } from '@dxos/kv-store';\nimport { type Runtime } from '@dxos/protocols/proto/dxos/config';\n\nimport { getRootPath, isPersistent } from './util';\n\nexport const createLevel = async (config: Runtime.Client.Storage) => {\n const persistent = isPersistent(config);\n const storagePath = persistent ? path.join(getRootPath(config), 'level') : `/tmp/dxos-${PublicKey.random().toHex()}`;\n const level = createKV(storagePath);\n // TODO(dmaretskyi): This function shouldn't call open - .\n await level.open();\n return level;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { cbor } from '@dxos/automerge/automerge-repo';\nimport { invariant } from '@dxos/invariant';\nimport type { LevelDB } from '@dxos/kv-store';\nimport { log } from '@dxos/log';\nimport { ProfileArchiveEntryType, type ProfileArchive } from '@dxos/protocols';\nimport type { Storage } from '@dxos/random-access-storage';\nimport { arrayToBuffer } from '@dxos/util';\n\nexport const encodeProfileArchive = (profile: ProfileArchive): Uint8Array => cbor.encode(profile);\n\nexport const decodeProfileArchive = (data: Uint8Array): ProfileArchive => cbor.decode(data);\n\nexport const exportProfileData = async ({\n storage,\n level,\n}: {\n storage: Storage;\n level: LevelDB;\n}): Promise<ProfileArchive> => {\n const archive: ProfileArchive = { storage: [], meta: { timestamp: new Date().toISOString() } };\n\n {\n const directory = await storage.createDirectory();\n const files = await directory.list();\n\n log.info('begin exporting files', { count: files.length });\n for (const filename of files) {\n const file = await directory.getOrCreateFile(filename);\n const { size } = await file.stat();\n const data = await file.read(0, size);\n archive.storage.push({\n type: ProfileArchiveEntryType.FILE,\n key: filename,\n value: data,\n });\n }\n log.info('done exporting files', { count: files.length });\n }\n\n {\n log.info('begin exporting kv pairs');\n const iter = await level.iterator<Uint8Array, Uint8Array>({ keyEncoding: 'binary', valueEncoding: 'binary' });\n let count = 0;\n for await (const [key, value] of iter) {\n archive.storage.push({\n type: ProfileArchiveEntryType.KEY_VALUE,\n key,\n value,\n });\n count++;\n }\n log.info('done exporting kv pairs', { count });\n }\n\n return archive;\n};\n\nexport const importProfileData = async (\n {\n storage,\n level,\n }: {\n storage: Storage;\n level: LevelDB;\n },\n archive: ProfileArchive,\n): Promise<void> => {\n let batch = level.batch();\n\n let count = 0;\n for (const entry of archive.storage) {\n switch (entry.type) {\n case ProfileArchiveEntryType.FILE: {\n const directory = await storage.createDirectory();\n invariant(typeof entry.key === 'string', 'Invalid key type');\n const file = await directory.getOrCreateFile(entry.key);\n invariant(entry.value instanceof Uint8Array, 'Invalid value type');\n await file.write(0, arrayToBuffer(entry.value));\n await file.close();\n break;\n }\n case ProfileArchiveEntryType.KEY_VALUE: {\n invariant(entry.key instanceof Uint8Array, 'Invalid key type');\n invariant(entry.value instanceof Uint8Array, 'Invalid value type');\n batch.put(entry.key, entry.value, { keyEncoding: 'binary', valueEncoding: 'binary' });\n break;\n }\n default:\n throw new Error(`Invalid entry type: ${entry.type}`);\n }\n\n if (++count % 1000 === 0) {\n // Apparently indexedDB can't handle big batches.\n await batch.write();\n batch = level.batch();\n\n log.info('importing', {\n count,\n total: archive.storage.length,\n progress: `${((count / archive.storage.length) * 100).toFixed()}%`,\n });\n }\n }\n\n log.info('committing changes..');\n await batch.write();\n};\n", "//\n// Copyright 2021 DXOS.org\n//\n\nimport { Event, synchronized } from '@dxos/async';\nimport { clientServiceBundle, type ClientServices } from '@dxos/client-protocol';\nimport { type Config } from '@dxos/config';\nimport { Context } from '@dxos/context';\nimport { EdgeClient, EdgeHttpClient, createStubEdgeIdentity, type EdgeConnection } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { type LevelDB } from '@dxos/kv-store';\nimport { log } from '@dxos/log';\nimport { EdgeSignalManager, WebsocketSignalManager, type SignalManager } from '@dxos/messaging';\nimport {\n SwarmNetworkManager,\n createIceProvider,\n createRtcTransportFactory,\n type TransportFactory,\n} from '@dxos/network-manager';\nimport { trace } from '@dxos/protocols';\nimport { SystemStatus } from '@dxos/protocols/proto/dxos/client/services';\nimport { type Storage } from '@dxos/random-access-storage';\nimport { TRACE_PROCESSOR, trace as Trace } from '@dxos/tracing';\nimport { WebsocketRpcClient } from '@dxos/websocket-rpc';\n\nimport { ServiceContext, type ServiceContextRuntimeParams } from './service-context';\nimport { ServiceRegistry } from './service-registry';\nimport { EdgeAgentServiceImpl } from '../agents';\nimport { DevicesServiceImpl } from '../devices';\nimport { DevtoolsHostEvents, DevtoolsServiceImpl } from '../devtools';\nimport {\n createCollectDiagnosticsBroadcastHandler,\n createDiagnostics,\n type CollectDiagnosticsBroadcastHandler,\n} from '../diagnostics';\nimport { IdentityServiceImpl, type CreateIdentityOptions } from '../identity';\nimport { ContactsServiceImpl } from '../identity/contacts-service';\nimport { InvitationsServiceImpl } from '../invitations';\nimport { Lock, type ResourceLock } from '../locks';\nimport { LoggingServiceImpl } from '../logging';\nimport { NetworkServiceImpl } from '../network';\nimport { SpacesServiceImpl } from '../spaces';\nimport { createLevel, createStorageObjects } from '../storage';\nimport { SystemServiceImpl } from '../system';\n\nexport type ClientServicesHostParams = {\n /**\n * Can be omitted if `initialize` is later called.\n */\n config?: Config;\n transportFactory?: TransportFactory;\n signalManager?: SignalManager;\n connectionLog?: boolean;\n storage?: Storage;\n level?: LevelDB;\n lockKey?: string;\n callbacks?: ClientServicesHostCallbacks;\n runtimeParams?: ServiceContextRuntimeParams;\n};\n\nexport type ClientServicesHostCallbacks = {\n onReset?: () => Promise<void>;\n};\n\nexport type InitializeOptions = {\n config?: Config;\n transportFactory?: TransportFactory;\n signalManager?: SignalManager;\n connectionLog?: boolean;\n};\n\n/**\n * Remote service implementation.\n */\n@Trace.resource()\nexport class ClientServicesHost {\n private readonly _resourceLock?: ResourceLock;\n private readonly _serviceRegistry: ServiceRegistry<ClientServices>;\n private readonly _systemService: SystemServiceImpl;\n private readonly _loggingService: LoggingServiceImpl;\n private readonly _tracingService = TRACE_PROCESSOR.createTraceSender();\n\n private _config?: Config;\n private readonly _statusUpdate = new Event<void>();\n private _signalManager?: SignalManager;\n private _networkManager?: SwarmNetworkManager;\n private _storage?: Storage;\n private _level?: LevelDB;\n private _callbacks?: ClientServicesHostCallbacks;\n private _devtoolsProxy?: WebsocketRpcClient<{}, ClientServices>;\n private _edgeConnection?: EdgeConnection = undefined;\n private _edgeHttpClient?: EdgeHttpClient = undefined;\n\n private _serviceContext!: ServiceContext;\n private readonly _runtimeParams: ServiceContextRuntimeParams;\n private diagnosticsBroadcastHandler: CollectDiagnosticsBroadcastHandler;\n\n @Trace.info()\n private _opening = false;\n\n @Trace.info()\n private _open = false;\n\n @Trace.info()\n private _resetting = false;\n\n constructor({\n config,\n transportFactory,\n signalManager,\n storage,\n level,\n // TODO(wittjosiah): Turn this on by default.\n lockKey,\n callbacks,\n runtimeParams,\n }: ClientServicesHostParams = {}) {\n this._storage = storage;\n this._level = level;\n this._callbacks = callbacks;\n this._runtimeParams = runtimeParams ?? {};\n\n if (this._runtimeParams.disableP2pReplication === undefined) {\n this._runtimeParams.disableP2pReplication = config?.get('runtime.client.disableP2pReplication', false);\n }\n\n if (config) {\n this.initialize({ config, transportFactory, signalManager });\n }\n\n if (lockKey) {\n this._resourceLock = new Lock({\n lockKey,\n onAcquire: () => {\n if (!this._opening) {\n void this.open(new Context());\n }\n },\n onRelease: () => this.close(),\n });\n }\n\n // TODO(wittjosiah): If config is not defined here, system service will always have undefined config.\n this._systemService = new SystemServiceImpl({\n config: () => this._config,\n statusUpdate: this._statusUpdate,\n getCurrentStatus: () => (this.isOpen && !this._resetting ? SystemStatus.ACTIVE : SystemStatus.INACTIVE),\n getDiagnostics: () => {\n return createDiagnostics(this._serviceRegistry.services, this._serviceContext, this._config!);\n },\n onUpdateStatus: async (status: SystemStatus) => {\n if (!this.isOpen && status === SystemStatus.ACTIVE) {\n await this._resourceLock?.acquire();\n } else if (this.isOpen && status === SystemStatus.INACTIVE) {\n await this._resourceLock?.release();\n }\n },\n onReset: async () => {\n await this.reset();\n },\n });\n\n this.diagnosticsBroadcastHandler = createCollectDiagnosticsBroadcastHandler(this._systemService);\n this._loggingService = new LoggingServiceImpl();\n\n this._serviceRegistry = new ServiceRegistry<ClientServices>(clientServiceBundle, {\n SystemService: this._systemService,\n TracingService: this._tracingService,\n });\n }\n\n get isOpen() {\n return this._open;\n }\n\n get config() {\n return this._config;\n }\n\n get context() {\n return this._serviceContext;\n }\n\n get serviceRegistry() {\n return this._serviceRegistry;\n }\n\n get descriptors() {\n return this._serviceRegistry.descriptors;\n }\n\n get services() {\n return this._serviceRegistry.services;\n }\n\n /**\n * Initialize the service host with the config.\n * Config can also be provided in the constructor.\n * Can only be called once.\n */\n initialize({ config, ...options }: InitializeOptions) {\n invariant(!this._open, 'service host is open');\n log('initializing...');\n\n if (config) {\n invariant(!this._config, 'config already set');\n this._config = config;\n if (!this._storage) {\n this._storage = createStorageObjects(config.get('runtime.client.storage', {})!).storage;\n }\n }\n\n if (!options.signalManager) {\n log.warn('running signaling without telemetry metadata.');\n }\n\n const edgeEndpoint = config?.get('runtime.services.edge.url');\n if (edgeEndpoint) {\n this._edgeConnection = new EdgeClient(createStubEdgeIdentity(), { socketEndpoint: edgeEndpoint });\n this._edgeHttpClient = new EdgeHttpClient(edgeEndpoint);\n }\n\n const {\n connectionLog = true,\n transportFactory = createRtcTransportFactory(\n { iceServers: this._config?.get('runtime.services.ice') },\n this._config?.get('runtime.services.iceProviders') &&\n createIceProvider(this._config!.get('runtime.services.iceProviders')!),\n ),\n signalManager = this._edgeConnection && this._config?.get('runtime.client.edgeFeatures')?.signaling\n ? new EdgeSignalManager({ edgeConnection: this._edgeConnection })\n : new WebsocketSignalManager(this._config?.get('runtime.services.signaling') ?? []),\n } = options;\n this._signalManager = signalManager;\n\n invariant(!this._networkManager, 'network manager already set');\n this._networkManager = new SwarmNetworkManager({\n enableDevtoolsLogging: connectionLog,\n transportFactory,\n signalManager,\n peerInfo: this._edgeConnection\n ? {\n identityKey: this._edgeConnection.identityKey,\n peerKey: this._edgeConnection.peerKey,\n }\n : undefined,\n });\n\n log('initialized');\n }\n\n @synchronized\n @Trace.span()\n async open(ctx: Context) {\n if (this._open) {\n return;\n }\n\n const traceId = PublicKey.random().toHex();\n log.trace('dxos.client-services.host.open', trace.begin({ id: traceId }));\n\n invariant(this._config, 'config not set');\n invariant(this._storage, 'storage not set');\n invariant(this._signalManager, 'signal manager not set');\n invariant(this._networkManager, 'network manager not set');\n\n this._opening = true;\n log('opening...', { lockKey: this._resourceLock?.lockKey });\n\n await this._resourceLock?.acquire();\n\n if (!this._level) {\n this._level = await createLevel(this._config.get('runtime.client.storage', {})!);\n }\n await this._level.open();\n\n await this._loggingService.open();\n\n this._serviceContext = new ServiceContext(\n this._storage,\n this._level,\n this._networkManager,\n this._signalManager,\n this._edgeConnection,\n this._edgeHttpClient,\n this._runtimeParams,\n this._config.get('runtime.client.edgeFeatures'),\n );\n\n const dataSpaceManagerProvider = async () => {\n await this._serviceContext.initialized.wait();\n return this._serviceContext.dataSpaceManager!;\n };\n\n const agentManagerProvider = async () => {\n await this._serviceContext.initialized.wait();\n return this._serviceContext.edgeAgentManager!;\n };\n\n const identityService = new IdentityServiceImpl(\n this._serviceContext.identityManager,\n this._serviceContext.recoveryManager,\n this._serviceContext.keyring,\n () => this._serviceContext.dataSpaceManager!,\n (params) => this._createIdentity(params),\n (profile) => this._serviceContext.broadcastProfileUpdate(profile),\n );\n\n this._serviceRegistry.setServices({\n SystemService: this._systemService,\n IdentityService: identityService,\n ContactsService: new ContactsServiceImpl(\n this._serviceContext.identityManager,\n this._serviceContext.spaceManager,\n dataSpaceManagerProvider,\n ),\n\n InvitationsService: new InvitationsServiceImpl(this._serviceContext.invitationsManager),\n\n DevicesService: new DevicesServiceImpl(this._serviceContext.identityManager, this._edgeConnection),\n\n SpacesService: new SpacesServiceImpl(\n this._serviceContext.identityManager,\n this._serviceContext.spaceManager,\n dataSpaceManagerProvider,\n ),\n\n DataService: this._serviceContext.echoHost.dataService,\n QueryService: this._serviceContext.echoHost.queryService,\n\n NetworkService: new NetworkServiceImpl(this._serviceContext.networkManager, this._serviceContext.signalManager),\n\n LoggingService: this._loggingService,\n TracingService: this._tracingService,\n\n // TODO(burdon): Move to new protobuf definitions.\n DevtoolsHost: new DevtoolsServiceImpl({\n events: new DevtoolsHostEvents(),\n config: this._config,\n context: this._serviceContext,\n }),\n\n EdgeAgentService: new EdgeAgentServiceImpl(agentManagerProvider),\n });\n\n await this._serviceContext.open(ctx);\n await identityService.open();\n\n const devtoolsProxy = this._config?.get('runtime.client.devtoolsProxy');\n if (devtoolsProxy) {\n this._devtoolsProxy = new WebsocketRpcClient({\n url: devtoolsProxy,\n requested: {},\n exposed: clientServiceBundle,\n handlers: this.services as ClientServices,\n });\n void this._devtoolsProxy.open();\n }\n this.diagnosticsBroadcastHandler.start();\n\n this._opening = false;\n this._open = true;\n this._statusUpdate.emit();\n const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;\n log('opened', { deviceKey });\n log.trace('dxos.client-services.host.open', trace.end({ id: traceId }));\n }\n\n @synchronized\n @Trace.span()\n async close() {\n if (!this._open) {\n return;\n }\n\n const deviceKey = this._serviceContext.identityManager.identity?.deviceKey;\n log('closing...', { deviceKey });\n this.diagnosticsBroadcastHandler.stop();\n await this._devtoolsProxy?.close();\n this._serviceRegistry.setServices({ SystemService: this._systemService });\n await this._loggingService.close();\n await this._serviceContext.close();\n await this._level?.close();\n this._open = false;\n this._statusUpdate.emit();\n log('closed', { deviceKey });\n }\n\n async reset() {\n const traceId = PublicKey.random().toHex();\n log.trace('dxos.sdk.client-services-host.reset', trace.begin({ id: traceId }));\n\n log.info('resetting...');\n // Emit this status update immediately so app returns to fallback.\n // This state is never cleared because the app reloads.\n this._resetting = true;\n this._statusUpdate.emit();\n await this._serviceContext?.close();\n await this._storage!.reset();\n log.info('reset');\n log.trace('dxos.sdk.client-services-host.reset', trace.end({ id: traceId }));\n await this._callbacks?.onReset?.();\n }\n\n private async _createIdentity(params: CreateIdentityOptions) {\n const identity = await this._serviceContext.createIdentity(params);\n await this._serviceContext.initialized.wait();\n return identity;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { EventSubscriptions } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type EdgeConnection } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport {\n Device,\n DeviceKind,\n type DevicesService,\n type QueryDevicesResponse,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { type DeviceProfileDocument } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport { type IdentityManager } from '../identity';\n\nexport class DevicesServiceImpl implements DevicesService {\n constructor(\n private readonly _identityManager: IdentityManager,\n private readonly _edgeConnection?: EdgeConnection,\n ) {}\n\n async updateDevice(profile: DeviceProfileDocument): Promise<Device> {\n return this._identityManager.updateDeviceProfile(profile);\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 invariant(this._identityManager.identity?.presence, 'presence not present');\n const peers = this._identityManager.identity.presence.getPeersOnline();\n next({\n devices: Array.from(deviceKeys.entries()).map(([key, profile]) => {\n const isMe = this._identityManager.identity?.deviceKey.equals(key);\n let presence;\n if (isMe) {\n presence = Device.PresenceState.ONLINE;\n } else if (profile.os?.toUpperCase() === 'EDGE') {\n presence = this._edgeConnection?.isConnected\n ? Device.PresenceState.ONLINE\n : Device.PresenceState.OFFLINE;\n } else {\n presence = peers.some((peer) => peer.identityKey.equals(key))\n ? Device.PresenceState.ONLINE\n : Device.PresenceState.OFFLINE;\n }\n\n return {\n deviceKey: key,\n kind: this._identityManager.identity?.deviceKey.equals(key) ? DeviceKind.CURRENT : DeviceKind.TRUSTED,\n profile,\n presence,\n };\n }),\n });\n }\n };\n\n let identitySubscribed = false;\n let presenceSubscribed = false;\n const subscribeIdentity = () => {\n if (!identitySubscribed) {\n this._identityManager.identity?.stateUpdate.on(() => {\n update();\n });\n identitySubscribed = true;\n }\n };\n\n const subscribePresence = () => {\n if (!presenceSubscribed) {\n this._identityManager.identity?.presence?.updated.on(() => {\n update();\n });\n presenceSubscribed = true;\n }\n };\n\n const subscriptions = new EventSubscriptions();\n\n if (this._identityManager.identity) {\n subscribeIdentity();\n subscribePresence();\n }\n\n subscriptions.add(\n this._identityManager.stateUpdate.on(() => {\n update();\n\n if (this._identityManager.identity) {\n subscribeIdentity();\n subscribePresence();\n }\n }),\n );\n\n update();\n\n return () => subscriptions.clear();\n });\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { EventSubscriptions, scheduleTask, UpdateScheduler } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type MemberInfo } from '@dxos/credentials';\nimport { type SpaceManager } from '@dxos/echo-pipeline';\nimport { PublicKey } from '@dxos/keys';\nimport { type Contact, type ContactBook, type ContactsService } from '@dxos/protocols/proto/dxos/client/services';\nimport { ComplexMap, ComplexSet } from '@dxos/util';\n\nimport { type IdentityManager } from './identity-manager';\nimport { type DataSpaceManager } from '../spaces';\n\nexport class ContactsServiceImpl implements ContactsService {\n constructor(\n private readonly _identityManager: IdentityManager,\n private readonly _spaceManager: SpaceManager,\n private readonly _dataSpaceManagerProvider: () => Promise<DataSpaceManager>,\n ) {}\n\n async getContacts(): Promise<ContactBook> {\n const identity = this._identityManager.identity;\n if (identity == null) {\n return { contacts: [] };\n }\n const contacts = [...this._spaceManager.spaces.values()]\n .flatMap((s) => [...s.spaceState.members.values()].map((m) => [s.key, m]))\n .reduce((acc, v) => {\n const [spaceKey, memberInfo] = v as [PublicKey, MemberInfo];\n if (memberInfo.key.equals(identity.identityKey)) {\n return acc;\n }\n const existing = acc.get(memberInfo.key);\n if (existing != null) {\n existing.profile ??= memberInfo.profile;\n existing.commonSpaces?.push(spaceKey);\n } else {\n acc.set(memberInfo.key, {\n identityKey: memberInfo.key,\n profile: memberInfo.profile,\n commonSpaces: [spaceKey],\n });\n }\n return acc;\n }, new ComplexMap<PublicKey, Contact>(PublicKey.hash));\n return {\n contacts: [...contacts.values()],\n };\n }\n\n queryContacts(): Stream<ContactBook> {\n const subscribedSpaceKeySet = new ComplexSet(PublicKey.hash);\n return new Stream<ContactBook>(({ next, ctx }) => {\n const pushUpdateTask = new UpdateScheduler(\n ctx,\n async () => {\n const contacts = await this.getContacts();\n next(contacts);\n },\n { maxFrequency: 2 },\n );\n scheduleTask(ctx, async () => {\n const subscriptions = new EventSubscriptions();\n ctx.onDispose(() => subscriptions.clear());\n const subscribeToSpaceAndUpdate = () => {\n const oldSetSize = subscribedSpaceKeySet.size;\n for (const space of this._spaceManager.spaces.values()) {\n if (!subscribedSpaceKeySet.has(space.key)) {\n subscriptions.add(space.stateUpdate.on(ctx, () => pushUpdateTask.trigger()));\n subscribedSpaceKeySet.add(space.key);\n }\n }\n if (oldSetSize !== subscribedSpaceKeySet.size) {\n pushUpdateTask.trigger();\n }\n };\n const unsubscribe = (await this._dataSpaceManagerProvider()).updated.on(ctx, subscribeToSpaceAndUpdate);\n ctx.onDispose(unsubscribe);\n subscribeToSpaceAndUpdate();\n });\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { PublicKey } from '@dxos/keys';\nimport {\n type LogLevel,\n type LogProcessor,\n type LogEntry as NaturalLogEntry,\n getContextFromEntry,\n log,\n} from '@dxos/log';\nimport {\n type LogEntry,\n type LoggingService,\n type Metrics,\n QueryLogsRequest,\n type ControlMetricsRequest,\n type ControlMetricsResponse,\n type QueryMetricsRequest,\n type QueryMetricsResponse,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { getDebugName, jsonify, numericalValues, tracer } from '@dxos/util';\n\n/**\n * Logging service used to spy on logs of the host.\n */\nexport class LoggingServiceImpl implements LoggingService {\n private readonly _logs = new Event<NaturalLogEntry>();\n private readonly _started = Date.now();\n private readonly _sessionId = PublicKey.random().toHex();\n\n async open() {\n log.runtimeConfig.processors.push(this._logProcessor);\n }\n\n async close() {\n const index = log.runtimeConfig.processors.findIndex((processor) => processor === this._logProcessor);\n log.runtimeConfig.processors.splice(index, 1);\n }\n\n async controlMetrics({ reset, record }: ControlMetricsRequest): Promise<ControlMetricsResponse> {\n if (reset) {\n tracer.clear();\n }\n\n if (record === true) {\n tracer.start();\n } else if (record === false) {\n tracer.stop();\n }\n\n return { recording: tracer.recording };\n }\n\n /**\n * @deprecated (Move to diagnostics).\n */\n queryMetrics({ interval = 5_000 }: QueryMetricsRequest): Stream<QueryMetricsResponse> {\n // TODO(burdon): Map all traces; how to bind to reducer/metrics shape (e.g., numericalValues)?\n const getNumericalValues = (key: string) => {\n const events = tracer.get(key) ?? [];\n return { key, stats: numericalValues(events, 'duration') };\n };\n\n return new Stream(({ next }) => {\n const update = () => {\n const metrics: Metrics = {\n timestamp: new Date(),\n values: [\n getNumericalValues('dxos.echo.pipeline.control'),\n getNumericalValues('dxos.echo.pipeline.data'),\n ].filter(Boolean) as Metrics.KeyPair[],\n };\n\n next({\n timestamp: new Date(),\n metrics,\n });\n };\n\n update();\n const i = setInterval(update, Math.max(interval, 1_000));\n return () => {\n clearInterval(i);\n };\n });\n }\n\n queryLogs(request: QueryLogsRequest): Stream<LogEntry> {\n return new Stream<LogEntry>(({ ctx, next }) => {\n const handler = (entry: NaturalLogEntry) => {\n // This call was caused by the logging service itself.\n if (LOG_PROCESSING > 0) {\n return;\n }\n\n // Prevent logging feedback loop from logging service.\n if (\n entry.meta?.F.includes('logging-service') ||\n (entry.context &&\n Object.values(entry.context).some((value) => typeof value === 'string' && value.includes('LoggingService')))\n ) {\n return;\n }\n\n if (!shouldLog(entry, request)) {\n return;\n }\n\n const record: LogEntry = {\n ...entry,\n context: jsonify(getContextFromEntry(entry)),\n timestamp: new Date(),\n meta: {\n // TODO(dmaretskyi): Fix proto.\n file: entry.meta?.F ?? '',\n line: entry.meta?.L ?? 0,\n scope: {\n hostSessionId: this._sessionId,\n uptimeSeconds: (Date.now() - this._started) / 1000,\n name: getDebugName(entry.meta?.S),\n },\n },\n };\n\n try {\n LOG_PROCESSING++;\n next(record);\n } finally {\n LOG_PROCESSING--;\n }\n };\n\n this._logs.on(ctx, handler);\n });\n }\n\n private _logProcessor: LogProcessor = (_config, entry) => {\n this._logs.emit(entry);\n };\n}\n\nconst matchFilter = (\n filter: QueryLogsRequest.Filter,\n level: LogLevel,\n path: string,\n options: QueryLogsRequest.MatchingOptions,\n) => {\n switch (options) {\n case QueryLogsRequest.MatchingOptions.INCLUSIVE:\n return level >= filter.level && (!filter.pattern || path.includes(filter.pattern));\n case QueryLogsRequest.MatchingOptions.EXPLICIT:\n return level === filter.level && (!filter.pattern || path.includes(filter.pattern));\n }\n};\n\n/**\n * Determines if the current line should be logged (called by the processor).\n */\nconst shouldLog = (entry: NaturalLogEntry, request: QueryLogsRequest): boolean => {\n const options = request.options ?? QueryLogsRequest.MatchingOptions.INCLUSIVE;\n if (request.filters === undefined) {\n return options === QueryLogsRequest.MatchingOptions.INCLUSIVE;\n } else {\n return request.filters.some((filter) => matchFilter(filter, entry.level, entry.meta?.F ?? '', options));\n }\n};\n\n/**\n * Counter that is used to track whether we are processing a log entry.\n */\nlet LOG_PROCESSING = 0;\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type SignalManager } from '@dxos/messaging';\nimport { type SwarmNetworkManager } from '@dxos/network-manager';\nimport {\n type NetworkService,\n type NetworkStatus,\n type UpdateConfigRequest,\n} from '@dxos/protocols/proto/dxos/client/services';\n\nexport class NetworkServiceImpl implements NetworkService {\n constructor(\n private readonly networkManager: SwarmNetworkManager,\n private readonly signalManager: SignalManager,\n ) {}\n\n queryStatus() {\n return new Stream<NetworkStatus>(({ next }) => {\n const update = () => {\n next({\n swarm: this.networkManager.connectionState,\n connectionInfo: this.networkManager.connectionLog?.swarms,\n signaling: this.signalManager.getStatus?.().map(({ host, state }) => ({ server: host, state })),\n });\n };\n\n const unsubscribeSwarm = this.networkManager.connectionStateChanged.on(() => update());\n const unsubscribeSignal = this.signalManager.statusChanged?.on(() => update());\n update();\n\n return () => {\n unsubscribeSwarm();\n unsubscribeSignal?.();\n };\n });\n }\n\n async updateConfig(request: UpdateConfigRequest) {\n await this.networkManager.setConnectionState(request.swarm);\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Event } from '@dxos/async';\nimport { Stream } from '@dxos/codec-protobuf';\nimport { type Config } from '@dxos/config';\nimport {\n GetDiagnosticsRequest,\n type SystemService,\n type SystemStatus,\n type UpdateStatusRequest,\n type QueryStatusRequest,\n type QueryStatusResponse,\n type Platform,\n} from '@dxos/protocols/proto/dxos/client/services';\nimport { jsonKeyReplacer, type MaybePromise } from '@dxos/util';\n\nimport { type Diagnostics } from '../diagnostics';\nimport { getPlatform } from '../services/platform';\n\nexport type SystemServiceOptions = {\n config?: () => MaybePromise<Config | undefined>;\n statusUpdate: Event<void>;\n getCurrentStatus: () => SystemStatus;\n getDiagnostics: () => Promise<Partial<Diagnostics['services']>>;\n onUpdateStatus: (status: SystemStatus) => MaybePromise<void>;\n onReset: () => MaybePromise<void>;\n};\n\nexport class SystemServiceImpl implements SystemService {\n private readonly _config?: SystemServiceOptions['config'];\n private readonly _statusUpdate: SystemServiceOptions['statusUpdate'];\n private readonly _getCurrentStatus: SystemServiceOptions['getCurrentStatus'];\n private readonly _onUpdateStatus: SystemServiceOptions['onUpdateStatus'];\n private readonly _onReset: SystemServiceOptions['onReset'];\n private readonly _getDiagnostics: SystemServiceOptions['getDiagnostics'];\n\n constructor({\n config,\n statusUpdate,\n getDiagnostics,\n onUpdateStatus,\n getCurrentStatus,\n onReset,\n }: SystemServiceOptions) {\n this._config = config;\n this._statusUpdate = statusUpdate;\n this._getCurrentStatus = getCurrentStatus;\n this._getDiagnostics = getDiagnostics;\n this._onUpdateStatus = onUpdateStatus;\n this._onReset = onReset;\n }\n\n async getConfig() {\n return (await this._config?.())?.values ?? {};\n }\n\n /**\n * NOTE: Since this is serialized as a JSON object, we allow the option to serialize keys.\n */\n async getDiagnostics({ keys }: GetDiagnosticsRequest = {}) {\n const diagnostics = await this._getDiagnostics();\n return {\n timestamp: new Date(),\n diagnostics: JSON.parse(\n JSON.stringify(\n diagnostics,\n jsonKeyReplacer({\n truncate: keys === GetDiagnosticsRequest.KEY_OPTION.TRUNCATE,\n humanize: keys === GetDiagnosticsRequest.KEY_OPTION.HUMANIZE,\n }),\n ),\n ),\n };\n }\n\n async getPlatform(): Promise<Platform> {\n return getPlatform();\n }\n\n async updateStatus({ status }: UpdateStatusRequest) {\n await this._onUpdateStatus(status);\n }\n\n // TODO(burdon): Standardize interval option in stream request?\n queryStatus({ interval = 3_000 }: QueryStatusRequest = {}): Stream<QueryStatusResponse> {\n return new Stream(({ next }) => {\n const update = () => {\n next({ status: this._getCurrentStatus() });\n };\n\n update();\n const unsubscribe = this._statusUpdate.on(() => update());\n const i = setInterval(update, interval);\n return () => {\n clearInterval(i);\n unsubscribe();\n };\n });\n }\n\n async reset() {\n await this._onReset();\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;AAIA,SAASA,0BAA0B;AACnC,SAASC,cAAc;AAEvB,SAASC,oBAAsD;AAC/D,SAASC,iBAAiB;AAC1B,SAASC,WAAW;AAQpB,SAASC,kBAAkB;;AAOpB,IAAMC,mBAAmB,CAC9B,EAAEC,WAAWC,aAAY,GACzB,EAAEC,SAAQ,MAA2B;AAErC,SAAO,IAAIR,OAAiC,CAAC,EAAES,KAAI,MAAE;AACnD,UAAMC,gBAAgB,IAAIX,mBAAAA;AAC1B,UAAMY,UAAU,IAAIP,WAAgCF,UAAUU,IAAI;AAElE,UAAMC,SAAS,MAAA;AACb,YAAM,EAAEC,MAAK,IAAKR;AAClBQ,YACGC,OAAO,CAACC,SAAS,CAACR,UAAUS,UAAUT,SAASU,KAAK,CAACC,YAAYA,QAAQC,OAAOJ,KAAKK,GAAG,CAAA,CAAA,EACxFC,QAAQ,CAACN,SAAAA;AACR,YAAI,CAACL,QAAQY,IAAIP,KAAKK,GAAG,GAAG;AAC1BV,kBAAQa,IAAIR,KAAKK,KAAK;YAAEL;UAAK,CAAA;AAC7BA,eAAKS,GAAG,SAASZ,MAAAA;AACjBH,wBAAcgB,IAAI,MAAMV,KAAKW,IAAI,SAASd,MAAAA,CAAAA;QAC5C;AACA,YAAI,CAACF,QAAQiB,IAAIZ,KAAKK,GAAG,GAAGQ,OAAO;AACjClB,kBAAQiB,IAAIZ,KAAKK,GAAG,EAAGQ,QAAQC,cAAcvB,cAAcS,KAAKK,GAAG;QACrE;MACF,CAAA;AAEFZ,WAAK;QACHK,OAAOiB,MAAMC,KAAKrB,QAAQsB,OAAM,CAAA,EAAIC,IAAI,CAAC,EAAElB,MAAMa,MAAK,OAAQ;UAC5DV,SAASH,KAAKK;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I;GAtBA5J,mBAAAA,WAAAA,YAAAA,MAAAA;;EAyBV8J,OAAMF,KAAI;GAzBA5J,mBAAAA,WAAAA,SAAAA,MAAAA;;EA4BV8J,OAAMF,KAAI;GA5BA5J,mBAAAA,WAAAA,cAAAA,MAAAA;;EAgLV+J;EACAD,OAAME,KAAI;GAjLAhK,mBAAAA,WAAAA,QAAAA,IAAAA;;EAqSV+J;EACAD,OAAME,KAAI;GAtSAhK,mBAAAA,WAAAA,SAAAA,IAAAA;AAAAA,qBAAAA,eAAAA;EADZ8J,OAAMG,SAAQ;GACFjK,kBAAAA;",
|
|
6
|
-
"names": ["EventSubscriptions", "Stream", "FeedIterator", "PublicKey", "log", "ComplexMap", "subscribeToFeeds", "feedStore", "spaceManager", "feedKeys", "next", "subscriptions", "feedMap", "hash", "update", "feeds", "filter", "feed", "length", "some", "feedKey", "equals", "key", "forEach", "has", "set", "on", "add", "off", "get", "owner", "findFeedOwner", "Array", "from", "values", "map", "properties", "bytes", "core", "byteLength", "downloaded", "bitfield", "data", "toBuffer", "Uint8Array", "feedOpened", "clear", "feedInfo", "spaces", "flatMap", "space", "spaceState", "find", "truncate", "allSpaces", "size", "undefined", "identity", "assertion", "identityKey", "device", "deviceKey", "subscribeToFeedBlocks", "maxBlocks", "timeout", "setTimeout", "getFeed", "blocks", "iterator", "open", "block", "push", "slice", "close", "clearTimeout", "Stream", "Context", "PublicKey", "subscribeToNetworkStatus", "signalManager", "next", "close", "update", "status", "getStatus", "servers", "err", "statusChanged", "on", "subscribeToSignal", "ctx", "onMessage", "message", "author", "from", "peerKey", "asUint8Array", "recipient", "payload", "receivedAt", "Date", "swarmEvent", "peerAvailable", "peer", "since", "peerLeft", "topic", "dispose", "subscribeToNetworkTopics", "networkManager", "topics", "labeledTopics", "map", "label", "getSwarm", "toHex", "topicsUpdated", "subscribeToSwarmInfo", "info", "connectionLog", "swarms", "data", "getNetworkPeers", "request", "Error", "getSwarmMap", "peers", "connections", "connection", "Stream", "subscribeToSpaces", "context", "spaceKeys", "Stream", "next", "unsubscribe", "update", "spaces", "spaceManager", "values", "filteredSpaces", "filter", "space", "length", "some", "spaceKey", "equals", "key", "map", "spaceMetadata", "metadataStore", "find", "isOpen", "timeframe", "dataTimeframe", "genesisFeed", "genesisFeedKey", "controlFeed", "controlFeedKey", "dataFeed", "dataFeedKey", "timeout", "setTimeout", "initialized", "wait", "dataSpaceManager", "updated", "on", "clearTimeout", "Event", "AsyncEvent", "Stream", "scheduleTask", "Stream", "subscribeToKeyringKeys", "keyring", "Stream", "next", "ctx", "update", "keys", "list", "keysUpdate", "on", "scheduleTask", "Stream", "subscribeToMetadata", "context", "Stream", "next", "ctx", "metadataStore", "update", "on", "data", "metadata", "DevtoolsHostEvents", "ready", "AsyncEvent", "DevtoolsServiceImpl", "constructor", "params", "events", "request", "Stream", "next", "on", "getConfig", "config", "JSON", "stringify", "values", "getStorageInfo", "storageUsage", "context", "storage", "getDiskInfo", "used", "navigatorInfo", "navigator", "estimate", "undefined", "type", "originUsage", "usage", "usageQuota", "quota", "getBlobs", "blobs", "blobStore", "list", "getSnapshots", "snapshots", "resetStorage", "Error", "enableDebugLogging", "disableDebugLogging", "subscribeToKeyringKeys", "keyring", "subscribeToCredentialMessages", "subscribeToSpaces", "subscribeToItems", "subscribeToFeeds", "subscribeToFeedBlocks", "feedStore", "getSpaceSnapshot", "saveSpaceSnapshot", "clearSnapshots", "getNetworkPeers", "subscribeToNetworkTopics", "subscribeToSignalStatus", "subscribeToNetworkStatus", "signalManager", "subscribeToSignal", "subscribeToSwarmInfo", "networkManager", "subscribeToMetadata", "asyncTimeout", "getFirstStreamValue", "credentialTypeFilter", "invariant", "STORAGE_VERSION", "SpaceMember", "TRACE_PROCESSOR", "DXOS_VERSION", "Platform", "getPlatform", "process", "browser", "window", "userAgent", "navigator", "type", "Platform", "PLATFORM_TYPE", "BROWSER", "uptime", "Math", "floor", "Date", "now", "performance", "timeOrigin", "SHARED_WORKER", "platform", "version", "arch", "NODE", "runtime", "memory", "memoryUsage", "DEFAULT_TIMEOUT", "createDiagnostics", "clientServices", "serviceContext", "config", "diagnostics", "created", "Date", "toISOString", "platform", "getPlatform", "client", "version", "DXOS_VERSION", "storage", "STORAGE_VERSION", "trace", "TRACE_PROCESSOR", "getDiagnostics", "Promise", "all", "invariant", "LoggingService", "metrics", "getFirstStreamValue", "queryMetrics", "timeout", "catch", "undefined", "asyncTimeout", "getStorageDiagnostics", "identity", "identityManager", "identityKey", "spaceKey", "space", "key", "profile", "profileDocument", "devices", "DevicesService", "queryDevices", "dataSpaceManager", "spaces", "Array", "from", "values", "map", "getSpaceStats", "feeds", "DevtoolsHost", "subscribeToFeeds", "feedKey", "bytes", "length", "status", "NetworkService", "queryStatus", "networkStatus", "swarms", "networkManager", "connectionLog", "stats", "epochs", "inner", "spaceState", "credentials", "filter", "credentialTypeFilter", "credential", "subject", "assertion", "id", "members", "member", "role", "displayName", "presence", "getPeersOnline", "equals", "SpaceMember", "PresenceState", "ONLINE", "OFFLINE", "pipeline", "currentEpoch", "automergeSpaceState", "lastEpoch", "appliedEpoch", "controlFeeds", "controlPipeline", "state", "feed", "currentControlTimeframe", "timeframe", "targetControlTimeframe", "targetTimeframe", "totalControlTimeframe", "endTimeframe", "open", "ready", "startupTime", "getTime", "navigator", "Map", "dir", "getDirectory", "filename", "keys", "idx", "indexOf", "set", "slice", "get", "entries", "sort", "a", "b", "file", "count", "Trigger", "log", "CHANNEL_NAME", "MessageType", "createCollectDiagnosticsBroadcastSender", "broadcastDiagnosticsRequest", "expectedResponse", "channel", "trigger", "BroadcastChannel", "onmessage", "msg", "data", "type", "wake", "postMessage", "wait", "timeout", "reset", "diagnostics", "payload", "e", "errorDescription", "Error", "message", "JSON", "stringify", "safeClose", "createCollectDiagnosticsBroadcastHandler", "systemService", "start", "getDiagnostics", "error", "catch", "stop", "undefined", "close", "ClientServicesProviderResource", "ConfigResource", "GetDiagnosticsRequest", "TRACE_PROCESSOR", "jsonKeyReplacer", "nonNullable", "GET_DIAGNOSTICS_RPC_TIMEOUT", "DiagnosticsCollector", "broadcastSender", "createCollectDiagnosticsBroadcastSender", "collect", "config", "findConfigs", "services", "findSystemServiceProvider", "options", "serviceDiagnostics", "SystemService", "getDiagnostics", "keys", "humanize", "GetDiagnosticsRequest", "KEY_OPTION", "HUMANIZE", "truncate", "TRUNCATE", "undefined", "timeout", "clientDiagnostics", "trace", "TRACE_PROCESSOR", "diagnostics", "client", "broadcast", "broadcastDiagnosticsRequest", "JSON", "parse", "stringify", "jsonKeyReplacer", "serviceProviders", "findResourcesByAnnotation", "ClientServicesProviderResource", "providerResource", "find", "r", "instance", "deref", "configs", "ConfigResource", "map", "filter", "nonNullable", "Trigger", "Context", "verifyCredential", "log", "schema", "Credential", "getCodecForType", "createAuthProvider", "signer", "nonce", "credential", "createCredential", "assertion", "subject", "getIssuer", "encode", "TrustedKeySetAuthVerifier", "constructor", "_params", "_ctx", "close", "dispose", "verifier", "auth", "decode", "result", "kind", "proof", "Buffer", "from", "equals", "_isTrustedKey", "issuer", "key", "trigger", "onDispose", "wake", "clear", "update", "on", "trusted", "trustedKeysProvider", "wait", "timeout", "authTimeout", "deviceKey", "deviceSet", "has", "decode", "decodeCbor", "encode", "encodeCbor", "Event", "Mutex", "scheduleMicroTask", "Context", "Resource", "EdgeConnectionClosedError", "EdgeIdentityChangedError", "invariant", "PublicKey", "log", "logInfo", "EdgeService", "buf", "MessageSchema", "RouterMessageSchema", "ComplexMap", "arrayToBuffer", "bufferToArray", "defaultMap", "rangeFromTo", "EdgeFeedReplicator", "constructor", "messenger", "spaceId", "_feeds", "hash", "_connectionCtx", "undefined", "_connected", "_remoteLength", "_pushMutex", "_messenger", "_spaceId", "_open", "_ctx", "onDispose", "onMessage", "message", "serviceId", "service", "rest", "split", "FEED_REPLICATOR", "payload", "value", "from", "source", "feedKey", "type", "_onMessage", "onReconnected", "_handleReconnect", "_resetConnection", "isConnected", "_startReplication", "_close", "connectionCtx", "_createConnectionContext", "feed", "values", "_replicateFeed", "dispose", "clear", "addFeed", "info", "key", "connected", "hasConnectionCtx", "set", "_getPushMutex", "ctx", "_sendMessage", "toHex", "wrap", "core", "on", "_pushBlocksIfNeeded", "logPayload", "blocks", "map", "b", "index", "payloadValue", "send", "create", "identityKey", "peerKey", "warn", "fromHex", "get", "_guard", "acquire", "length", "range", "to", "_pushBlocks", "_integrateBlocks", "Promise", "all", "data", "valueEncoding", "Uint8Array", "proof", "nodes", "signature", "block", "has", "blockBuffer", "bufferizeBlock", "putBuffer", "_", "remoteLength", "onError", "err", "raise", "node", "size", "Event", "Mutex", "scheduleTask", "sleep", "synchronized", "trackLeaks", "AUTH_TIMEOUT", "Context", "ContextDisposedError", "cancelWithContext", "timed", "warnAfterTimeout", "createMappedFeedWriter", "SpaceDocVersion", "failedInvariant", "PublicKey", "log", "CancelledError", "SystemError", "SpaceState", "AdmittedFeed", "SpaceMember", "Timeframe", "trace", "CallbackCollection", "ComplexSet", "Event", "Resource", "checkCredentialType", "AutomergeSpaceState", "Resource", "constructor", "_onNewRoot", "rootUrl", "undefined", "lastEpoch", "onNewEpoch", "Event", "_isProcessingRootDocs", "_open", "ctx", "_close", "processCredential", "credential", "checkCredentialType", "subject", "assertion", "automergeRoot", "emit", "startProcessingRootDocs", "ensureEpochInitialized", "waitForCondition", "migrateDocument", "convertLegacyReferences", "convertLegacySpaceRootDoc", "findInlineObjectOfType", "SpaceDocVersion", "TYPE_PROPERTIES", "invariant", "log", "CreateEpochRequest", "LOAD_DOC_TIMEOUT", "runEpochMigration", "ctx", "context", "migration", "Migration", "INIT_AUTOMERGE", "document", "echoHost", "createDoc", "flush", "newRoot", "url", "PRUNE_AUTOMERGE_ROOT_HISTORY", "currentRoot", "Error", "rootHandle", "loadDoc", "timeout", "docSync", "FRAGMENT_AUTOMERGE_ROOT", "info", "currentRootUrl", "objects", "Object", "entries", "properties", "otherObjects", "filter", "key", "fromEntries", "length", "newLinks", "id", "objData", "handle", "version", "CURRENT", "access", "spaceKey", "toHex", "push", "change", "doc", "links", "MIGRATE_REFERENCES_TO_DXN", "newRootContent", "structuredClone", "newDoc", "migratedDoc", "newHandle", "preserveHistory", "err", "warn", "error", "migratedRoot", "REPLACE_AUTOMERGE_ROOT", "newAutomergeRoot", "DeferredTask", "Event", "scheduleTask", "sleep", "TimeoutError", "Trigger", "scheduleMicroTask", "rejectOnDispose", "Resource", "verifyCredential", "invariant", "PublicKey", "logInfo", "log", "EdgeCallFailedError", "schema", "RpcExtension", "ComplexMap", "ComplexSet", "entry", "DEFAULT_RETRY_TIMEOUT", "DEFAULT_SUCCESS_DELAY", "DEFAULT_NOTARIZE_TIMEOUT", "DEFAULT_ACTIVE_EDGE_POLLING_INTERVAL", "MAX_EDGE_RETRIES", "WRITER_NOT_SET_ERROR_CODE", "credentialCodec", "getCodecForType", "NotarizationPlugin", "constructor", "params", "_extensionOpened", "_extensions", "Set", "_processedCredentials", "hash", "_processCredentialsTriggers", "_activeEdgePollingIntervalHandle", "undefined", "_spaceId", "spaceId", "_activeEdgePollingInterval", "activeEdgePollingInterval", "edgeClient", "edgeFeatures", "feedReplicator", "_edgeClient", "setActiveEdgePollingEnabled", "enabled", "isOpen", "client", "setInterval", "_writer", "_notarizePendingEdgeCredentials", "clearInterval", "hasWriter", "_open", "_close", "_ctx", "dispose", "notarize", "ctx", "opCtx", "credentials", "timeout", "retryTimeout", "successDelay", "edgeRetryJitter", "every", "credential", "id", "errors", "derive", "onError", "err", "warn", "throw", "onDispose", "_scheduleTimeout", "allNotarized", "Promise", "all", "map", "_waitUntilProcessed", "_tryNotarizeCredentialsWithPeers", "_tryNotarizeCredentialsWithEdge", "jitter", "race", "wait", "peersTried", "notarizeTask", "size", "peer", "find", "has", "info", "retryIn", "clear", "schedule", "add", "localPeerId", "credentialId", "rpc", "NotarizationService", "filter", "disposed", "message", "includes", "on", "timeouts", "encodedCredentials", "binary", "encode", "Buffer", "from", "toString", "notarizeCredentials", "retry", "count", "error", "handleEdgeError", "processCredential", "get", "wake", "delete", "setWriter", "writer", "response", "getCredentialsForNotarization", "awaitingNotarization", "length", "decodedCredentials", "decode", "_notarizeCredentials", "orInsert", "value", "_onNotarize", "request", "Error", "verificationResult", "kind", "join", "write", "createExtension", "extension", "NotarizationTeleportExtension", "onOpen", "emit", "onClose", "onNotarize", "bind", "peers", "Array", "remotePeerId", "errorData", "catch", "reason", "_params", "requested", "getService", "exposed", "getHandlers", "Event", "AUTH_TIMEOUT", "LOAD_CONTROL_FEEDS_TIMEOUT", "DeviceStateMachine", "createCredentialSignerWithKey", "createCredentialSignerWithChain", "ProfileStateMachine", "writeMessages", "invariant", "PublicKey", "log", "AdmittedFeed", "Timeframe", "trace", "ComplexSet", "getCredentialAssertion", "SpaceId", "log", "DefaultSpaceStateMachine", "constructor", "_params", "spaceId", "_spaceId", "processCredential", "credential", "assertion", "subject", "id", "equals", "identityKey", "warn", "expectedIdentity", "isValid", "Event", "synchronized", "trackLeaks", "PropertiesType", "LifecycleState", "Resource", "cancelWithContext", "createAdmissionCredentials", "getCredentialAssertion", "convertLegacyReferences", "findInlineObjectOfType", "AuthStatus", "CredentialServerExtension", "LEGACY_TYPE_PROPERTIES", "SpaceDocVersion", "encodeReference", "TYPE_PROPERTIES", "createObjectId", "getTypeReference", "writeMessages", "invariant", "PublicKey", "log", "AlreadyJoinedError", "trace", "Trace", "Invitation", "SpaceState", "EdgeReplicationSetting", "SpaceMember", "Gossip", "Presence", "ComplexMap", "setDeep", "deferFunction", "forEachAsync", "createCredential", "failUndefined", "AdmittedFeed", "SpaceMember", "Timeframe", "spaceGenesis", "keyring", "signingContext", "space", "automergeRoot", "credentials", "createCredential", "signer", "issuer", "key", "subject", "assertion", "spaceKey", "identityKey", "role", "SpaceMember", "Role", "OWNER", "profile", "getProfile", "genesisFeedKey", "controlFeedKey", "failUndefined", "credentialSigner", "deviceKey", "designation", "AdmittedFeed", "Designation", "CONTROL", "dataFeedKey", "DATA", "number", "previousId", "undefined", "timeframe", "Timeframe", "snapshotCid", "credential", "controlPipeline", "writer", "write", "PRESENCE_ANNOUNCE_INTERVAL", "PRESENCE_OFFLINE_TIMEOUT", "DEFAULT_SPACE_KEY", "DataSpaceManager", "Resource", "constructor", "params", "updated", "Event", "_spaces", "ComplexMap", "PublicKey", "hash", "_instanceId", "random", "toHex", "_edgeConnection", "undefined", "_edgeHttpClient", "_edgeFeatures", "_meshReplicator", "_echoEdgeReplicator", "_runtimeParams", "_spaceManager", "spaceManager", "_metadataStore", "metadataStore", "_keyring", "keyring", "_signingContext", "signingContext", "_feedStore", "feedStore", "_echoHost", "echoHost", "meshReplicator", "_invitationsManager", "invitationsManager", "edgeConnection", "edgeFeatures", "echoEdgeReplicator", "edgeHttpClient", "runtimeParams", "trace", "diagnostic", "id", "name", "fetch", "Array", "from", "values", "map", "space", "rootUrl", "automergeSpaceState", "rootHandle", "automergeRepo", "find", "rootDoc", "docSync", "properties", "findInlineObjectOfType", "TYPE_PROPERTIES", "key", "state", "SpaceState", "data", "inlineObjects", "Object", "keys", "objects", "length", "linkedObjects", "links", "credentials", "inner", "spaceState", "members", "size", "spaces", "_open", "log", "Trace", "begin", "forEachAsync", "spaceMetadata", "_constructSpace", "err", "error", "emit", "end", "_close", "close", "clear", "createSpace", "invariant", "_lifecycleState", "LifecycleState", "OPEN", "spaceKey", "createKey", "controlFeedKey", "dataFeedKey", "metadata", "genesisFeedKey", "SPACE_ACTIVE", "root", "createSpaceRoot", "open", "spaceGenesis", "url", "addSpace", "memberCredential", "getCredentialAssertion", "recordCredential", "initializeDataPipeline", "isDefaultSpace", "databaseRoot", "getVersion", "SpaceDocVersion", "CURRENT", "_", "identityKey", "LEGACY", "convertedDoc", "convertLegacyReferences", "LEGACY_TYPE_PROPERTIES", "warn", "version", "spaceId", "createDefaultSpace", "document", "_getSpaceRootDocument", "system", "type", "encodeReference", "getTypeReference", "PropertiesType", "meta", "propertiesId", "createObjectId", "change", "doc", "setDeep", "flush", "automergeIndex", "whenReady", "acceptSpace", "opts", "has", "controlTimeframe", "dataTimeframe", "initializeDataPipelineAsync", "admitMember", "options", "get", "getMemberRole", "SpaceMember", "Role", "REMOVED", "AlreadyJoinedError", "createAdmissionCredentials", "credentialSigner", "role", "membershipChainHeads", "profile", "delegationCredentialId", "credential", "spaceMemberCredential", "writeMessages", "controlPipeline", "writer", "waitUntilSpaceReady", "cancelWithContext", "_ctx", "waitForCondition", "SPACE_READY", "requestSpaceAdmissionCredential", "timeout", "swarmIdentity", "peerKey", "deviceKey", "credentialProvider", "createAuthProvider", "credentialAuthenticator", "setSpaceEdgeReplicationSetting", "setting", "isOpen", "EdgeReplicationSetting", "DISABLED", "disconnectFromSpace", "ENABLED", "connectToSpace", "stateUpdate", "gossip", "Gossip", "localPeerId", "presence", "Presence", "announceInterval", "spaceMemberPresenceAnnounceInterval", "offlineTimeout", "spaceMemberPresenceOfflineTimeout", "controlFeed", "openFeed", "writable", "dataFeed", "sparse", "constructSpace", "deferFunction", "dataSpace", "authVerifier", "verifier", "onAuthorizedConnection", "session", "queueMicrotask", "addExtension", "CredentialServerExtension", "createExtension", "remotePeerId", "notarizationPlugin", "_connectEchoMeshReplicator", "onAuthFailure", "onMemberRolesChanged", "_handleMemberRoleChanges", "protocol", "memberKey", "onDelegatedInvitationStatusChange", "invitation", "isActive", "_handleInvitationStatusChange", "setControlFeed", "setDataFeed", "DataSpace", "initialState", "SPACE_INACTIVE", "SPACE_CLOSED", "callbacks", "beforeReady", "afterReady", "_createDelegatedInvitations", "invitations", "entries", "beforeClose", "cache", "activeEdgeNotarizationPollingInterval", "postOpen", "append", "getEdgeReplicationSetting", "preClose", "newPeer", "on", "peerState", "_handleNewPeerConnected", "setTargetTimeframe", "set", "replicator", "authorizeDevice", "spaceProtocol", "memberInfo", "closedSessions", "member", "equals", "getLocalState", "peers", "getPeersByIdentityKey", "sessions", "p", "peerId", "sessionsToClose", "filter", "s", "authStatus", "AuthStatus", "FAILURE", "forEach", "catch", "roleChangeCount", "peersOnline", "getPeersOnline", "updateTopology", "delegatedInvitation", "credentialId", "cancelInvitation", "tasks", "createInvitation", "Invitation", "Type", "DELEGATED", "kind", "Kind", "SPACE", "authMethod", "invitationId", "swarmKey", "guestKeypair", "guestKey", "publicKey", "lifetime", "expiresOn", "getTime", "Date", "now", "multiUse", "persistent", "Promise", "all", "synchronized", "trackLeaks", "EventSubscriptions", "UpdateScheduler", "scheduleTask", "Stream", "createAdmissionCredentials", "getCredentialAssertion", "raise", "writeMessages", "invariant", "log", "ApiError", "SpaceNotFoundError", "encodeError", "IdentityNotInitializedError", "AuthorizationError", "SpaceMember", "SpaceState", "trace", "SpacesServiceImpl", "constructor", "_identityManager", "_spaceManager", "_getDataSpaceManager", "createSpace", "_requireIdentity", "dataSpaceManager", "space", "_updateMetrics", "_serializeSpace", "updateSpace", "spaceKey", "state", "edgeReplication", "spaces", "get", "SPACE_ACTIVE", "activate", "SPACE_INACTIVE", "deactivate", "undefined", "setSpaceEdgeReplicationSetting", "updateMemberRole", "request", "identity", "spaceState", "hasMembershipManagementPermission", "identityKey", "key", "role", "getMemberRole", "credentials", "getIdentityCredentialSigner", "memberKey", "genesisFeedKey", "newRole", "membershipChainHeads", "credential", "spaceMemberCredential", "controlPipeline", "writer", "querySpaces", "next", "ctx", "scheduler", "Array", "from", "values", "map", "ids", "id", "maxFrequency", "process", "subscriptions", "onDispose", "clear", "subscribeSpaces", "lastState", "add", "stateUpdate", "on", "forceTrigger", "trigger", "presence", "updated", "automergeSpaceState", "onNewEpoch", "inner", "timeframeUpdate", "postMessage", "channel", "message", "getChannelId", "subscribeMessages", "handle", "listen", "unsubscribe", "queryCredentials", "noTail", "close", "processor", "processCredential", "removeCredentialProcessor", "addCredentialProcessor", "writeCredentials", "proof", "write", "signer", "issuer", "equals", "getIssuer", "signedCredential", "createCredential", "subject", "assertion", "createEpoch", "migration", "automergeRootUrl", "result", "newAutomergeRoot", "epochCredential", "controlTimeframe", "timeframe", "admitContact", "admitMember", "contact", "joinBySpaceKey", "requestSpaceAdmissionCredential", "_joinByAdmission", "myIdentity", "dataSpace", "acceptSpace", "error", "pipeline", "currentEpoch", "lastEpoch", "appliedEpoch", "controlFeeds", "feeds", "feed", "currentControlTimeframe", "targetControlTimeframe", "targetTimeframe", "totalControlTimeframe", "endTimeframe", "dataFeeds", "startDataTimeframe", "currentDataTimeframe", "targetDataTimeframe", "totalDataTimeframe", "spaceRootUrl", "databaseRoot", "url", "members", "member", "peers", "getPeersOnline", "filter", "isMe", "push", "getLocalState", "profile", "length", "PresenceState", "ONLINE", "OFFLINE", "peerStates", "creator", "cache", "metrics", "getEdgeReplicationSetting", "truncate", "gauge", "size", "tags", "Identity", "constructor", "params", "_edgeFeedReplicator", "undefined", "stateUpdate", "Event", "_onFeedAdded", "feed", "addFeed", "space", "_signer", "signer", "_presence", "presence", "identityKey", "deviceKey", "log", "trace", "_deviceStateMachine", "DeviceStateMachine", "onUpdate", "emit", "_profileStateMachine", "ProfileStateMachine", "_defaultSpaceStateMachine", "DefaultSpaceStateMachine", "authVerifier", "TrustedKeySetAuthVerifier", "trustedKeysProvider", "ComplexSet", "PublicKey", "hash", "authorizedDeviceKeys", "keys", "update", "authTimeout", "AUTH_TIMEOUT", "edgeConnection", "edgeFeatures", "feedReplicator", "EdgeFeedReplicator", "messenger", "spaceId", "id", "defaultSpaceId", "open", "ctx", "spaceState", "addCredentialProcessor", "protocol", "feedAdded", "append", "joinNetwork", "startProtocol", "close", "removeCredentialProcessor", "remove", "ready", "deviceChainReady", "wait", "controlPipeline", "state", "waitUntilReachedTargetTimeframe", "timeout", "LOAD_CONTROL_FEEDS_TIMEOUT", "profileDocument", "profile", "haloSpaceId", "haloSpaceKey", "key", "haloGenesisFeedKey", "genesisFeedKey", "deviceCredentialChain", "getIdentityCredentialSigner", "invariant", "createCredentialSignerWithChain", "getDeviceCredentialSigner", "createCredentialSignerWithKey", "updateDefaultSpace", "credential", "createCredential", "subject", "assertion", "receipt", "writer", "write", "waitUntilTimeframe", "Timeframe", "feedKey", "seq", "admitDevice", "controlFeedKey", "dataFeedKey", "hostDevice", "deviceCredential", "writeMessages", "spaceKey", "designation", "AdmittedFeed", "Designation", "CONTROL", "DATA", "map", "span", "resource", "platform", "Event", "Context", "createCredentialSignerWithKey", "CredentialGenerator", "generateSeedPhrase", "keyPairFromSeedPhrase", "invariant", "PublicKey", "log", "trace", "Device", "DeviceKind", "AdmittedFeed", "DeviceType", "Gossip", "Presence", "Timeframe", "Trace", "isNode", "deferFunction", "DEVICE_PRESENCE_ANNOUNCE_INTERVAL", "DEVICE_PRESENCE_OFFLINE_TIMEOUT", "IdentityManager", "constructor", "params", "stateUpdate", "Event", "_metadataStore", "metadataStore", "_keyring", "keyring", "_feedStore", "feedStore", "_spaceManager", "spaceManager", "_edgeConnection", "edgeConnection", "_edgeFeatures", "edgeFeatures", "_devicePresenceAnnounceInterval", "devicePresenceAnnounceInterval", "_devicePresenceOfflineTimeout", "devicePresenceOfflineTimeout", "identity", "_identity", "open", "ctx", "traceId", "PublicKey", "random", "toHex", "log", "trace", "begin", "id", "identityRecord", "getIdentityRecord", "_constructIdentity", "ready", "identityKey", "displayName", "profileDocument", "emit", "end", "close", "Context", "createIdentity", "deviceProfile", "invariant", "controlFeedKey", "createKey", "deviceKey", "haloSpace", "key", "genesisFeedKey", "dataFeedKey", "generator", "CredentialGenerator", "credentials", "createSpaceGenesis", "createFeedAdmission", "AdmittedFeed", "Designation", "DATA", "push", "createProfileCredential", "createDeviceAuthorization", "createDeviceProfile", "createDefaultDeviceProfile", "credential", "controlPipeline", "writer", "write", "setIdentityRecord", "profile", "type", "isNode", "DeviceType", "AGENT", "platform", "name", "startsWith", "MOBILE", "globalThis", "__args", "NATIVE", "BROWSER", "platformVersion", "version", "architecture", "os", "String", "undefined", "family", "osVersion", "prepareIdentity", "haloSpaceKey", "haloGenesisFeedKey", "controlTimeframe", "acceptIdentity", "updateDeviceProfile", "updateProfile", "getIdentityCredentialSigner", "createCredential", "subject", "assertion", "receipt", "state", "waitUntilTimeframe", "Timeframe", "feedKey", "seq", "getDeviceCredentialSigner", "kind", "DeviceKind", "CURRENT", "presence", "Device", "PresenceState", "ONLINE", "createRecoveryPhrase", "seedphrase", "generateSeedPhrase", "keypair", "keyPairFromSeedPhrase", "recoveryKey", "from", "publicKey", "gossip", "Gossip", "localPeerId", "Presence", "announceInterval", "offlineTimeout", "controlFeed", "openFeed", "writable", "dataFeed", "sparse", "space", "_constructSpace", "spaceRecord", "swarmIdentity", "peerKey", "credentialProvider", "createAuthProvider", "createCredentialSignerWithKey", "credentialAuthenticator", "deferFunction", "authVerifier", "verifier", "setControlFeed", "setDataFeed", "Identity", "signer", "setTargetTimeframe", "on", "constructSpace", "metadata", "onAuthorizedConnection", "session", "addExtension", "createExtension", "remotePeerId", "onAuthFailure", "warn", "memberKey", "onDelegatedInvitationStatusChange", "onMemberRolesChanged", "Trace", "span", "showInBrowserTimeline", "resource", "Trigger", "sleep", "Stream", "Resource", "signPresentation", "invariant", "log", "SpaceState", "safeAwaitAll", "DEFAULT_SPACE_SEARCH_TIMEOUT", "IdentityServiceImpl", "constructor", "_identityManager", "_recoveryManager", "_keyring", "_dataSpaceManagerProvider", "_createIdentity", "_onProfileUpdate", "_open", "identity", "defaultSpaceId", "_fixIdentityWithoutDefaultSpace", "createIdentity", "request", "displayName", "profile", "deviceProfile", "dataSpaceManager", "_createDefaultSpace", "_getIdentity", "space", "createDefaultSpace", "updateDefaultSpace", "id", "queryIdentity", "next", "emitNext", "stateUpdate", "on", "undefined", "identityKey", "spaceKey", "key", "profileDocument", "updateProfile", "createRecoveryPhrase", "recoverIdentity", "presentation", "nonce", "signer", "signerKey", "deviceKey", "chain", "deviceCredentialChain", "recodedDefaultSpace", "foundDefaultSpace", "recordedDefaultSpaceTrigger", "allProcessed", "spaces", "values", "state", "SPACE_CLOSED", "open", "requiresMigration", "waitForCondition", "SPACE_REQUIRES_MIGRATION", "Promise", "race", "initializeDataPipeline", "isDefaultSpace", "warn", "duplicate", "wake", "err", "catch", "wait", "DataSpace", "constructor", "params", "_ctx", "Context", "_cache", "undefined", "_edgeFeedReplicator", "_automergeSpaceState", "AutomergeSpaceState", "rootUrl", "_onNewAutomergeRoot", "_epochProcessingMutex", "Mutex", "_state", "SpaceState", "SPACE_CLOSED", "_databaseRoot", "error", "stateUpdate", "Event", "postOpen", "CallbackCollection", "preClose", "metrics", "_onFeedAdded", "feed", "addFeed", "_inner", "inner", "on", "emit", "_gossip", "gossip", "_presence", "presence", "_keyring", "keyring", "_feedStore", "feedStore", "_metadataStore", "metadataStore", "_signingContext", "signingContext", "_callbacks", "callbacks", "_echoHost", "echoHost", "_notarizationPlugin", "NotarizationPlugin", "spaceId", "id", "edgeClient", "edgeHttpClient", "edgeFeatures", "activeEdgePollingInterval", "activeEdgeNotarizationPollingInterval", "authVerifier", "TrustedKeySetAuthVerifier", "trustedKeysProvider", "ComplexSet", "PublicKey", "hash", "Array", "from", "spaceState", "members", "values", "filter", "member", "role", "SpaceMember", "Role", "REMOVED", "map", "key", "update", "authTimeout", "AUTH_TIMEOUT", "cache", "edgeConnection", "feedReplicator", "EdgeFeedReplicator", "messenger", "initialState", "log", "state", "isOpen", "notarizationPlugin", "automergeSpaceState", "databaseRoot", "_automergeInfo", "lastEpoch", "open", "_open", "addCredentialProcessor", "protocol", "feedAdded", "append", "startProtocol", "SPACE_CONTROL_ONLY", "Date", "callSerial", "close", "_close", "beforeClose", "dispose", "remove", "removeCredentialProcessor", "postMessage", "channel", "message", "listen", "callback", "initializeDataPipelineAsync", "scheduleTask", "pipelineInitBegin", "initializeDataPipeline", "err", "CancelledError", "ContextDisposedError", "SPACE_ERROR", "ready", "SystemError", "SPACE_INITIALIZING", "_initializeAndReadControlPipeline", "sleep", "waitForCondition", "SPACE_READY", "startProcessingRootDocs", "_enterReadyState", "beforeReady", "afterReady", "controlPipeline", "waitUntilReachedTargetTimeframe", "ctx", "timeout", "breakOnStall", "controlPipelineReady", "_createWritableFeeds", "hasWriter", "setWriter", "createMappedFeedWriter", "credential", "writer", "credentials", "controlFeedKey", "controlFeed", "openFeed", "createKey", "writable", "setControlFeed", "push", "credentialSigner", "createCredential", "subject", "assertion", "spaceKey", "deviceKey", "identityKey", "designation", "AdmittedFeed", "Designation", "CONTROL", "dataFeedKey", "dataFeed", "sparse", "setDataFeed", "DATA", "length", "count", "notarize", "setWritableFeedKeys", "space", "handle", "automergeRepo", "find", "queueMicrotask", "warnAfterTimeout", "cancelWithContext", "whenReady", "disposed", "_guard", "acquire", "doc", "docSync", "failedInvariant", "access", "change", "toHex", "root", "openSpaceRoot", "url", "getVersion", "SpaceDocVersion", "CURRENT", "SPACE_REQUIRES_MIGRATION", "warn", "updateOwnProfile", "profile", "write", "createEpoch", "options", "derive", "migration", "newRoot", "runEpochMigration", "currentRoot", "newAutomergeRoot", "epoch", "previousId", "number", "timeframe", "Timeframe", "automergeRoot", "receipt", "feedKey", "seq", "waitUntilTimeframe", "updateIndexes", "activate", "SPACE_INACTIVE", "includes", "setSpaceState", "SPACE_ACTIVE", "deactivate", "getEdgeReplicationSetting", "getSpaceEdgeReplicationSetting", "trace", "info", "enum", "depth", "synchronized", "span", "showInBrowserTimeline", "timed", "trackLeaks", "resource", "getCredentialAssertion", "invariant", "AlreadyJoinedError", "Invitation", "DeviceInvitationProtocol", "constructor", "_keyring", "_getIdentity", "_acceptIdentity", "toJSON", "kind", "checkCanInviteNewMembers", "undefined", "getInvitationContext", "Kind", "DEVICE", "delegate", "Error", "cancelDelegation", "admit", "_", "request", "device", "identity", "credential", "admitDevice", "identityKey", "haloSpaceKey", "genesisFeedKey", "haloGenesisFeedKey", "controlTimeframe", "controlPipeline", "state", "timeframe", "checkInvitation", "invitation", "createIntroduction", "createAdmissionRequest", "deviceProfile", "deviceKey", "createKey", "controlFeedKey", "dataFeedKey", "profile", "accept", "response", "authorizedDeviceCredential", "scheduleTask", "TimeoutError", "INVITATION_TIMEOUT", "ContextDisposedError", "createKeyPair", "sign", "invariant", "PublicKey", "log", "createTeleportProtocolFactory", "InvalidInvitationExtensionRoleError", "trace", "Invitation", "AuthenticationResponse", "InvitationOptions", "_trace", "ComplexSet", "scheduleMicroTask", "scheduleTask", "sign", "invariant", "SpaceId", "log", "EdgeAuthChallengeError", "EdgeCallFailedError", "schema", "Invitation", "cancelWithContext", "ContextDisposedError", "Invitation", "stateToString", "state", "Object", "entries", "Invitation", "State", "find", "key", "val", "tryAcquireBeforeContextDisposed", "ctx", "mutex", "guard", "cancelWithContext", "acquire", "disposed", "release", "undefined", "ContextDisposedError", "MAX_RETRIES_PER_INVITATION", "DEFAULT_REQUEST_RETRY_INTERVAL_MS", "DEFAULT_REQUEST_RETRY_JITTER_MS", "EdgeInvitationHandler", "constructor", "config", "_client", "_callbacks", "_retryInterval", "retryInterval", "_retryJitter", "retryJitter", "handle", "ctx", "guardedState", "protocol", "deviceProfile", "log", "invitation", "current", "spaceId", "canBeHandledByEdge", "authMethod", "Invitation", "AuthMethod", "SHARED_SECRET", "type", "Type", "DELEGATED", "kind", "Kind", "SPACE", "SpaceId", "isValid", "onDispose", "_flowLock", "release", "undefined", "requestCount", "tryHandleInvitation", "admissionRequest", "createAdmissionRequest", "space", "_handleSpaceInvitationFlow", "error", "EdgeCallFailedError", "info", "reason", "message", "retryable", "isRetryable", "after", "retryAfterMs", "_calculateNextRetryMs", "scheduleTask", "scheduleMicroTask", "tryAcquireBeforeContextDisposed", "mutex", "verbose", "set", "State", "CONNECTING", "response", "_joinSpaceByInvitation", "identityKey", "toHex", "invitationId", "admissionResponse", "_mapToAdmissionResponse", "onInvitationSuccess", "ERROR", "edgeResponse", "credentialBytes", "Buffer", "from", "spaceMemberCredential", "codec", "schema", "getCodecForType", "credential", "decode", "request", "invariant", "joinSpaceByInvitation", "EdgeAuthChallengeError", "publicKey", "guestKeypair", "privateKey", "signature", "sign", "challenge", "toString", "hasFlowLock", "Math", "random", "Trigger", "cancelWithContext", "Context", "invariant", "log", "InvalidInvitationExtensionRoleError", "schema", "InvitationOptions", "RpcExtension", "OPTIONS_TIMEOUT", "InvitationGuestExtension", "RpcExtension", "constructor", "_invitationFlowMutex", "_callbacks", "requested", "InvitationHostService", "schema", "getService", "exposed", "_ctx", "Context", "_remoteOptionsTrigger", "Trigger", "_invitationFlowLock", "hasFlowLock", "getHandlers", "options", "invariant", "_remoteOptions", "wake", "introduce", "Error", "authenticate", "admit", "onOpen", "context", "log", "verbose", "tryAcquireBeforeContextDisposed", "cancelWithContext", "rpc", "role", "InvitationOptions", "Role", "GUEST", "wait", "timeout", "HOST", "InvalidInvitationExtensionRoleError", "undefined", "expected", "remoteOptions", "remotePeerId", "err", "onError", "disposed", "close", "onClose", "_destroy", "onAbort", "dispose", "release", "Trigger", "scheduleTask", "cancelWithContext", "Context", "randomBytes", "verify", "invariant", "InvariantViolation", "PublicKey", "log", "InvalidInvitationExtensionRoleError", "trace", "schema", "Invitation", "AuthenticationResponse", "InvitationOptions", "RpcExtension", "OPTIONS_TIMEOUT", "MAX_OTP_ATTEMPTS", "InvitationHostExtension", "RpcExtension", "constructor", "_invitationFlowMutex", "_callbacks", "requested", "InvitationHostService", "schema", "getService", "exposed", "_ctx", "Context", "_remoteOptionsTrigger", "Trigger", "_challenge", "undefined", "guestProfile", "authenticationPassed", "authenticationRetry", "completedTrigger", "_invitationFlowLock", "hasFlowLock", "getHandlers", "options", "invariant", "_remoteOptions", "wake", "introduce", "request", "profile", "invitationId", "traceId", "PublicKey", "random", "toHex", "log", "trace", "begin", "id", "invitation", "_requireActiveInvitation", "_assertInvitationState", "Invitation", "State", "CONNECTED", "warn", "expected", "actual", "onError", "Error", "scheduleTask", "close", "authMethod", "AuthMethod", "NONE", "verbose", "onStateUpdate", "READY_FOR_AUTHENTICATION", "KNOWN_PUBLIC_KEY", "randomBytes", "end", "challenge", "authenticate", "authCode", "code", "signedChallenge", "status", "AuthenticationResponse", "Status", "OK", "AUTHENTICATING", "SHARED_SECRET", "INVALID_OPT_ATTEMPTS", "INVALID_OTP", "guestKeypair", "INTERNAL_ERROR", "isSignatureValid", "verify", "Buffer", "from", "publicKey", "asBuffer", "INVALID_SIGNATURE", "error", "includes", "data", "admit", "isAuthenticationRequired", "response", "err", "onOpen", "context", "tryAcquireBeforeContextDisposed", "CONNECTING", "rpc", "role", "InvitationOptions", "Role", "HOST", "cancelWithContext", "wait", "timeout", "GUEST", "InvalidInvitationExtensionRoleError", "remoteOptions", "remotePeerId", "disposed", "activeInvitation", "stateOrMany", "validStates", "Array", "isArray", "state", "InvariantViolation", "stateToString", "map", "join", "onClose", "_destroy", "onAbort", "dispose", "release", "Mutex", "log", "Invitation", "createGuardedInvitationState", "ctx", "invitation", "stream", "mutex", "Mutex", "lastActiveLockHolder", "currentInvitation", "isStateChangeAllowed", "lockHolder", "disposed", "isLocked", "hasFlowLock", "isNonTerminalState", "state", "current", "complete", "newState", "logStateUpdate", "undefined", "next", "dispose", "set", "error", "Invitation", "State", "ERROR", "actor", "logContext", "invitationId", "constructor", "name", "stateToString", "oldState", "message", "errorStack", "stack", "log", "verbose", "info", "currentState", "SUCCESS", "CANCELLED", "TIMEOUT", "EXPIRED", "includes", "invariant", "PublicKey", "log", "InvitationOptions", "ComplexSet", "InvitationTopology", "constructor", "_role", "_seenPeers", "hash", "init", "controller", "_controller", "update", "ownPeerId", "candidates", "connected", "allPeers", "getState", "Role", "GUEST", "length", "forEach", "c", "add", "firstUnknownPeer", "find", "peerId", "has", "filter", "remotePeerId", "connect", "onOffer", "peer", "destroy", "clear", "toString", "metrics", "_trace", "MAX_DELEGATED_INVITATION_HOST_TRIES", "InvitationsHandler", "constructor", "_networkManager", "_edgeClient", "_connectionParams", "handleInvitationFlow", "ctx", "stream", "protocol", "invitation", "log", "verbose", "state", "invitationId", "kind", "type", "increment", "guardedState", "createGuardedInvitationState", "createExtension", "extension", "InvitationHostExtension", "mutex", "activeInvitation", "disposed", "current", "onStateUpdate", "newState", "Invitation", "State", "ERROR", "TIMEOUT", "set", "admit", "admissionRequest", "toJSON", "deviceKey", "device", "space", "invariant", "admissionResponse", "guestProfile", "completedTrigger", "wake", "err", "error", "onOpen", "connectionCtx", "extensionsCtx", "admitted", "onDispose", "CONNECTING", "scheduleTask", "traceId", "PublicKey", "random", "toHex", "trace", "begin", "id", "wait", "timeout", "guest", "SUCCESS", "end", "multiUse", "dispose", "stateChanged", "TimeoutError", "close", "onError", "InvalidInvitationExtensionRoleError", "context", "lifetime", "created", "getTime", "Date", "now", "warn", "EXPIRED", "catch", "swarmConnection", "_joinSwarm", "InvitationOptions", "Role", "HOST", "acceptInvitation", "otpEnteredTrigger", "deviceProfile", "INVITATION_TIMEOUT", "Kind", "DEVICE", "triedPeersIds", "ComplexSet", "hash", "shouldCancelInvitationFlow", "isLockedByAnotherConnection", "isLocked", "hasFlowLock", "invitationType", "Type", "DELEGATED", "triedPeers", "size", "InvitationGuestExtension", "extensionCtx", "add", "remotePeerId", "currentState", "ContextDisposedError", "CONNECTED", "introductionResponse", "rpc", "InvitationHostService", "introduce", "createIntroduction", "authMethod", "isAuthenticationRequired", "AuthMethod", "SHARED_SECRET", "_handleGuestOtpAuth", "KNOWN_PUBLIC_KEY", "_handleGuestKpkAuth", "createAdmissionRequest", "result", "accept", "complete", "edgeInvitationHandler", "EdgeInvitationHandler", "edgeInvitations", "onInvitationSuccess", "info", "handle", "checkInvitation", "swarmKey", "timeoutInactive", "GUEST", "role", "extensionFactory", "label", "spaceKey", "truncate", "joinSwarm", "topic", "protocolProvider", "createTeleportProtocolFactory", "teleport", "addExtension", "topology", "InvitationTopology", "setState", "authenticated", "options", "attempt", "MAX_OTP_ATTEMPTS", "READY_FOR_AUTHENTICATION", "authCode", "AUTHENTICATING", "response", "authenticate", "status", "undefined", "AuthenticationResponse", "Status", "OK", "INVALID_OTP", "Error", "reset", "guestKeypair", "privateKey", "challenge", "signature", "sign", "Buffer", "from", "signedChallenge", "createAdmissionKeypair", "keypair", "createKeyPair", "publicKey", "secretKey", "Stream", "QueryInvitationsResponse", "trace", "InvitationsServiceImpl", "constructor", "_invitationsManager", "getLoggingContext", "createInvitation", "options", "Stream", "next", "close", "then", "invitation", "trace", "metrics", "increment", "subscribe", "catch", "acceptInvitation", "request", "authenticate", "cancelInvitation", "queryInvitations", "ctx", "invitationCreated", "on", "action", "QueryInvitationsResponse", "Action", "ADDED", "type", "Type", "CREATED", "invitations", "invitationAccepted", "ACCEPTED", "removedCreated", "REMOVED", "removedAccepted", "saved", "SAVED", "getCreatedInvitations", "existing", "getAcceptedInvitations", "onPersistentInvitationsLoaded", "LOAD_COMPLETE", "createCancelDelegatedSpaceInvitationCredential", "createDelegatedSpaceInvitationCredential", "getCredentialAssertion", "writeMessages", "invariant", "log", "AlreadyJoinedError", "AuthorizationError", "InvalidInvitationError", "SpaceNotFoundError", "Invitation", "SpaceMember", "SpaceInvitationProtocol", "constructor", "_spaceManager", "_signingContext", "_keyring", "_spaceKey", "toJSON", "kind", "deviceKey", "spaceKey", "checkCanInviteNewMembers", "space", "spaces", "get", "inner", "spaceState", "hasMembershipManagementPermission", "identityKey", "undefined", "getInvitationContext", "Kind", "SPACE", "spaceId", "id", "admit", "invitation", "request", "guestProfile", "host", "guest", "spaceMemberCredential", "admitMember", "role", "Role", "ADMIN", "profile", "delegationCredentialId", "credential", "controlTimeframe", "controlPipeline", "state", "timeframe", "delegate", "authMethod", "AuthMethod", "KNOWN_PUBLIC_KEY", "guestKeypair", "publicKey", "invitationId", "credentialSigner", "key", "swarmKey", "expiresOn", "lifetime", "Date", "created", "getTime", "now", "multiUse", "guestKey", "writer", "cancelDelegation", "type", "Type", "DELEGATED", "checkInvitation", "has", "createIntroduction", "getProfile", "createAdmissionRequest", "controlFeedKey", "createKey", "dataFeedKey", "accept", "response", "dataTimeframe", "assertion", "subject", "equals", "acceptSpace", "genesisFeedKey", "recordCredential", "Event", "PushStream", "TimeoutError", "Trigger", "AuthenticatingInvitation", "AUTHENTICATION_CODE_LENGTH", "CancellableInvitation", "INVITATION_TIMEOUT", "Context", "generatePasscode", "hasInvitationExpired", "invariant", "PublicKey", "log", "Invitation", "SpaceMember", "InvitationsManager", "constructor", "_invitationsHandler", "_getHandler", "_metadataStore", "_createInvitations", "Map", "_acceptInvitations", "invitationCreated", "Event", "invitationAccepted", "removedCreated", "removedAccepted", "saved", "_persistentInvitationsLoadedEvent", "_persistentInvitationsLoaded", "createInvitation", "options", "invitationId", "existingInvitation", "get", "handler", "invitationError", "checkCanInviteNewMembers", "invitation", "_createInvitation", "ctx", "stream", "observableInvitation", "_createObservableInvitation", "set", "emit", "_onInvitationComplete", "delete", "persistent", "_safeDeleteInvitation", "_persistIfRequired", "err", "log", "catch", "cancel", "handleInvitationFlow", "loadPersistentInvitations", "invitations", "getCreatedInvitations", "filter", "i", "persistentInvitations", "getInvitations", "freshInvitations", "hasInvitationExpired", "loadTasks", "map", "persistentInvitation", "invariant", "cInvitations", "Promise", "all", "acceptInvitation", "request", "otpEnteredTrigger", "_createObservableAcceptingInvitation", "deviceProfile", "authenticate", "authCode", "observable", "warn", "cancelInvitation", "created", "removeInvitation", "type", "Invitation", "Type", "DELEGATED", "cancelDelegation", "accepted", "values", "getAcceptedInvitations", "onPersistentInvitationsLoaded", "callback", "once", "protocol", "_options", "PublicKey", "random", "toHex", "INTERACTIVE", "authMethod", "AuthMethod", "SHARED_SECRET", "state", "State", "INIT", "timeout", "INVITATION_TIMEOUT", "swarmKey", "KNOWN_PUBLIC_KEY", "Date", "guestKeypair", "undefined", "role", "SpaceMember", "Role", "ADMIN", "lifetime", "multiUse", "generatePasscode", "AUTHENTICATION_CODE_LENGTH", "createAdmissionKeypair", "delegationCredentialId", "getInvitationContext", "PushStream", "Context", "onError", "error", "dispose", "onDispose", "toJSON", "complete", "CancellableInvitation", "initialInvitation", "subscriber", "onCancel", "next", "CANCELLED", "initialState", "Trigger", "TimeoutError", "TIMEOUT", "ERROR", "AuthenticatingInvitation", "onAuthenticate", "code", "wake", "changeStream", "delegate", "addInvitation", "subscribe", "asyncTimeout", "Trigger", "RESOURCE_LOCK_TIMEOUT", "log", "logInfo", "Message", "Lock", "constructor", "lockKey", "onAcquire", "onRelease", "_broadcastChannel", "BroadcastChannel", "_releaseTrigger", "_lockKey", "_onAcquire", "_onRelease", "onmessage", "_onMessage", "bind", "acquire", "postMessage", "message", "_requestLock", "release", "wake", "event", "data", "steal", "acquired", "navigator", "locks", "request", "wait", "catch", "isLocked", "lockPath", "Error", "Stream", "raise", "parseMethodName", "RpcPeer", "MapCounter", "trace", "ClientRpcServer", "constructor", "params", "_handlerCache", "Map", "_callMetrics", "MapCounter", "serviceRegistry", "handleCall", "handleStream", "rpcOptions", "_handleCall", "_handleStream", "_serviceRegistry", "_rpcPeer", "RpcPeer", "callHandler", "method", "serviceName", "methodName", "parseMethodName", "handler", "_getServiceHandler", "call", "inc", "streamHandler", "callStream", "Stream", "map", "unwrapPromise", "data", "_services", "Object", "keys", "services", "open", "close", "has", "key", "descriptor", "entries", "descriptors", "find", "name", "raise", "Error", "service", "set", "createServer", "get", "trace", "metricsCounter", "info", "resource", "DeferredTask", "Event", "scheduleTask", "synchronized", "Resource", "invariant", "PublicKey", "log", "EdgeAgentStatus", "EdgeCallFailedError", "SpaceState", "AGENT_STATUS_QUERY_RETRY_INTERVAL", "AGENT_STATUS_QUERY_RETRY_JITTER", "EdgeAgentManager", "constructor", "_edgeFeatures", "_edgeHttpClient", "_dataSpaceManager", "_identity", "agentStatusChanged", "_lastKnownDeviceCount", "agentStatus", "_agentStatus", "agentExists", "NOT_FOUND", "createAgent", "isOpen", "agents", "response", "identityKey", "toHex", "haloSpaceId", "haloSpaceKey", "deviceKey", "fromHex", "admitDevice", "controlFeedKey", "feedKey", "dataFeedKey", "random", "_updateStatus", "ACTIVE", "_open", "isEnabled", "authorizedDeviceKeys", "size", "_fetchAgentStatusTask", "_ctx", "_fetchAgentStatus", "schedule", "updated", "on", "_agentDeviceKey", "_ensureAgentIsInSpaces", "stateUpdate", "maybeAgentWasCreated", "_close", "undefined", "agent", "getAgentStatus", "ownerIdentityKey", "wasAgentCreatedDuringQuery", "status", "err", "isRetryable", "warn", "retryAfterMs", "Math", "info", "agentDeviceKey", "space", "spaces", "values", "SPACE_INACTIVE", "SPACE_CLOSED", "includes", "state", "agentFeedNeedsNotarization", "inner", "spaceState", "feeds", "some", "feed", "assertion", "equals", "notarizationPlugin", "setActiveEdgePollingEnabled", "enabled", "spaceId", "id", "emit", "Stream", "EdgeAgentStatus", "QueryAgentStatusResponse", "EdgeAgentServiceImpl", "constructor", "_agentManagerProvider", "createAgent", "queryAgentStatus", "Stream", "ctx", "next", "status", "QueryAgentStatusResponse", "AgentStatus", "UNKNOWN", "then", "agentManager", "mapStatus", "agentStatus", "agentStatusChanged", "on", "newStatus", "EdgeAgentStatus", "ACTIVE", "INACTIVE", "NOT_FOUND", "undefined", "Mutex", "Trigger", "Context", "Resource", "getCredentialAssertion", "failUndefined", "warnAfterTimeout", "EchoEdgeReplicator", "EchoHost", "MeshEchoReplicator", "MetadataStore", "SpaceManager", "valueEncoding", "createChainEdgeIdentity", "createEphemeralEdgeIdentity", "FeedFactory", "FeedStore", "invariant", "Keyring", "PublicKey", "log", "InvalidStorageVersionError", "STORAGE_VERSION", "trace", "Invitation", "BlobStore", "Trace", "safeInstanceof", "generateSeedPhrase", "keyPairFromSeedPhrase", "sign", "invariant", "PublicKey", "log", "EdgeAuthChallengeError", "schema", "Timeframe", "EdgeIdentityRecoveryManager", "constructor", "_keyring", "_edgeClient", "_identityProvider", "_acceptRecoveredIdentity", "createRecoveryPhrase", "identity", "seedphrase", "keypair", "recoveryKey", "from", "publicKey", "identityKey", "credential", "getIdentityCredentialSigner", "createCredential", "subject", "assertion", "receipt", "controlPipeline", "writer", "write", "state", "waitUntilTimeframe", "feedKey", "seq", "recoverIdentity", "args", "recoveryKeypair", "deviceKey", "createKey", "controlFeedKey", "request", "toHex", "response", "error", "signature", "Buffer", "challenge", "secretKey", "toString", "info", "authorizedDeviceCredential", "decodeCredential", "deviceAuthCredential", "haloGenesisFeedKey", "fromHex", "genesisFeedKey", "haloSpaceKey", "dataFeedKey", "credentialBase64", "credentialBytes", "codec", "getCodecForType", "decode", "ServiceContext", "Resource", "constructor", "storage", "level", "networkManager", "signalManager", "_edgeConnection", "_edgeHttpClient", "_runtimeParams", "_edgeFeatures", "_edgeIdentityUpdateMutex", "Mutex", "initialized", "Trigger", "_meshReplicator", "undefined", "_echoEdgeReplicator", "_handlerFactories", "Map", "_instanceId", "PublicKey", "random", "toHex", "metadataStore", "MetadataStore", "createDirectory", "blobStore", "BlobStore", "keyring", "Keyring", "feedStore", "FeedStore", "factory", "FeedFactory", "root", "signer", "hypercore", "valueEncoding", "stats", "spaceManager", "SpaceManager", "disableP2pReplication", "identityManager", "IdentityManager", "devicePresenceOfflineTimeout", "devicePresenceAnnounceInterval", "edgeConnection", "edgeFeatures", "recoveryManager", "EdgeIdentityRecoveryManager", "identity", "_acceptIdentity", "bind", "echoHost", "EchoHost", "kv", "MeshEchoReplicator", "invitations", "InvitationsHandler", "invitationConnectionDefaultParams", "invitationsManager", "InvitationsManager", "invitation", "getInvitationHandler", "set", "Invitation", "Kind", "DEVICE", "DeviceInvitationProtocol", "failUndefined", "echoReplicator", "EchoEdgeReplicator", "_open", "ctx", "_checkStorageVersion", "log", "trace", "begin", "id", "open", "_setNetworkIdentity", "addReplicator", "load", "joinNetwork", "_initialize", "loadedInvitations", "loadPersistentInvitations", "count", "length", "end", "_close", "_deviceSpaceSync", "space", "spaceState", "removeCredentialProcessor", "dataSpaceManager", "close", "edgeAgentManager", "createIdentity", "params", "Context", "kind", "SPACE", "Error", "get", "invariant", "broadcastProfileUpdate", "profile", "spaces", "values", "updateOwnProfile", "identityRecord", "prepareIdentity", "deviceCredential", "authorizedDeviceCredential", "acceptIdentity", "deviceProfile", "version", "STORAGE_VERSION", "InvalidStorageVersionError", "signingContext", "credentialSigner", "getIdentityCredentialSigner", "identityKey", "deviceKey", "getProfile", "profileDocument", "recordCredential", "credential", "controlPipeline", "writer", "write", "DataSpaceManager", "edgeHttpClient", "echoEdgeReplicator", "meshReplicator", "runtimeParams", "EdgeAgentManager", "SpaceInvitationProtocol", "spaceKey", "wake", "processCredential", "assertion", "getCredentialAssertion", "equals", "key", "details", "has", "acceptSpace", "genesisFeedKey", "err", "catch", "addCredentialProcessor", "_", "acquire", "edgeIdentity", "info", "swarms", "topics", "createChainEdgeIdentity", "warnAfterTimeout", "ready", "deviceCredentialChain", "createEphemeralEdgeIdentity", "setIdentity", "setPeerInfo", "peerKey", "Trace", "span", "safeInstanceof", "resource", "ServiceRegistry", "constructor", "_serviceBundle", "_handlers", "descriptors", "services", "setServices", "addService", "name", "service", "removeService", "InvalidConfigError", "Runtime", "createStorage", "StorageType", "DX_DATA", "Runtime", "isNode", "getRootPath", "config", "dataRoot", "isNode", "DX_DATA", "isPersistent", "persistent", "dataStore", "undefined", "Runtime", "Client", "Storage", "StorageDriver", "RAM", "StorageDriver", "Runtime", "createStorageObjects", "config", "persistent", "keyStore", "dataStore", "RAM", "InvalidConfigError", "undefined", "storage", "createStorage", "type", "toStorageType", "StorageType", "root", "getRootPath", "CHROME", "FIREFOX", "IDB", "NODE", "WEBFS", "Error", "path", "PublicKey", "createLevel", "createKV", "createLevel", "config", "persistent", "isPersistent", "storagePath", "path", "join", "getRootPath", "PublicKey", "random", "toHex", "level", "createKV", "open", "cbor", "invariant", "log", "ProfileArchiveEntryType", "arrayToBuffer", "encodeProfileArchive", "profile", "encode", "decodeProfileArchive", "data", "decode", "exportProfileData", "storage", "level", "archive", "meta", "timestamp", "Date", "toISOString", "directory", "createDirectory", "files", "list", "info", "count", "length", "filename", "file", "getOrCreateFile", "size", "stat", "read", "push", "type", "FILE", "key", "value", "iter", "iterator", "keyEncoding", "valueEncoding", "KEY_VALUE", "importProfileData", "batch", "entry", "Uint8Array", "write", "close", "put", "Error", "total", "progress", "toFixed", "Event", "synchronized", "clientServiceBundle", "Context", "EdgeClient", "EdgeHttpClient", "createStubEdgeIdentity", "invariant", "PublicKey", "log", "EdgeSignalManager", "WebsocketSignalManager", "SwarmNetworkManager", "createIceProvider", "createRtcTransportFactory", "trace", "SystemStatus", "TRACE_PROCESSOR", "Trace", "WebsocketRpcClient", "EventSubscriptions", "Stream", "invariant", "Device", "DeviceKind", "DevicesServiceImpl", "constructor", "_identityManager", "_edgeConnection", "updateDevice", "profile", "updateDeviceProfile", "queryDevices", "next", "update", "deviceKeys", "identity", "authorizedDeviceKeys", "devices", "presence", "peers", "getPeersOnline", "Array", "from", "entries", "map", "key", "isMe", "deviceKey", "equals", "PresenceState", "ONLINE", "os", "toUpperCase", "isConnected", "OFFLINE", "some", "peer", "identityKey", "kind", "CURRENT", "TRUSTED", "identitySubscribed", "presenceSubscribed", "subscribeIdentity", "stateUpdate", "on", "subscribePresence", "updated", "subscriptions", "add", "clear", "EventSubscriptions", "scheduleTask", "UpdateScheduler", "Stream", "PublicKey", "ComplexMap", "ComplexSet", "ContactsServiceImpl", "constructor", "_identityManager", "_spaceManager", "_dataSpaceManagerProvider", "getContacts", "identity", "contacts", "spaces", "values", "flatMap", "s", "spaceState", "members", "map", "m", "key", "reduce", "acc", "v", "spaceKey", "memberInfo", "equals", "identityKey", "existing", "get", "profile", "commonSpaces", "push", "set", "ComplexMap", "PublicKey", "hash", "queryContacts", "subscribedSpaceKeySet", "ComplexSet", "Stream", "next", "ctx", "pushUpdateTask", "UpdateScheduler", "maxFrequency", "scheduleTask", "subscriptions", "EventSubscriptions", "onDispose", "clear", "subscribeToSpaceAndUpdate", "oldSetSize", "size", "space", "has", "add", "stateUpdate", "on", "trigger", "unsubscribe", "updated", "Event", "Stream", "PublicKey", "getContextFromEntry", "log", "QueryLogsRequest", "getDebugName", "jsonify", "numericalValues", "tracer", "LoggingServiceImpl", "_logs", "Event", "_started", "Date", "now", "_sessionId", "PublicKey", "random", "toHex", "_logProcessor", "_config", "entry", "emit", "open", "log", "runtimeConfig", "processors", "push", "close", "index", "findIndex", "processor", "splice", "controlMetrics", "reset", "record", "tracer", "clear", "start", "stop", "recording", "queryMetrics", "interval", "getNumericalValues", "key", "events", "get", "stats", "numericalValues", "Stream", "next", "update", "metrics", "timestamp", "values", "filter", "Boolean", "i", "setInterval", "Math", "max", "clearInterval", "queryLogs", "request", "ctx", "handler", "LOG_PROCESSING", "meta", "F", "includes", "context", "Object", "some", "value", "shouldLog", "jsonify", "getContextFromEntry", "file", "line", "L", "scope", "hostSessionId", "uptimeSeconds", "name", "getDebugName", "S", "on", "matchFilter", "level", "path", "options", "QueryLogsRequest", "MatchingOptions", "INCLUSIVE", "pattern", "EXPLICIT", "filters", "undefined", "Stream", "NetworkServiceImpl", "constructor", "networkManager", "signalManager", "queryStatus", "Stream", "next", "update", "swarm", "connectionState", "connectionInfo", "connectionLog", "swarms", "signaling", "getStatus", "map", "host", "state", "server", "unsubscribeSwarm", "connectionStateChanged", "on", "unsubscribeSignal", "statusChanged", "updateConfig", "request", "setConnectionState", "Stream", "GetDiagnosticsRequest", "jsonKeyReplacer", "SystemServiceImpl", "constructor", "config", "statusUpdate", "getDiagnostics", "onUpdateStatus", "getCurrentStatus", "onReset", "_config", "_statusUpdate", "_getCurrentStatus", "_getDiagnostics", "_onUpdateStatus", "_onReset", "getConfig", "values", "keys", "diagnostics", "timestamp", "Date", "JSON", "parse", "stringify", "jsonKeyReplacer", "truncate", "GetDiagnosticsRequest", "KEY_OPTION", "TRUNCATE", "humanize", "HUMANIZE", "getPlatform", "updateStatus", "status", "queryStatus", "interval", "Stream", "next", "update", "unsubscribe", "on", "i", "setInterval", "clearInterval", "reset", "ClientServicesHost", "constructor", "config", "transportFactory", "signalManager", "storage", "level", "lockKey", "callbacks", "runtimeParams", "_tracingService", "TRACE_PROCESSOR", "createTraceSender", "_statusUpdate", "Event", "_edgeConnection", "undefined", "_edgeHttpClient", "_opening", "_open", "_resetting", "_storage", "_level", "_callbacks", "_runtimeParams", "disableP2pReplication", "get", "initialize", "_resourceLock", "Lock", "onAcquire", "open", "Context", "onRelease", "close", "_systemService", "SystemServiceImpl", "_config", "statusUpdate", "getCurrentStatus", "isOpen", "SystemStatus", "ACTIVE", "INACTIVE", "getDiagnostics", "createDiagnostics", "_serviceRegistry", "services", "_serviceContext", "onUpdateStatus", "status", "acquire", "release", "onReset", "reset", "diagnosticsBroadcastHandler", "createCollectDiagnosticsBroadcastHandler", "_loggingService", "LoggingServiceImpl", "ServiceRegistry", "clientServiceBundle", "SystemService", "TracingService", "context", "serviceRegistry", "descriptors", "options", "invariant", "log", "createStorageObjects", "warn", "edgeEndpoint", "EdgeClient", "createStubEdgeIdentity", "socketEndpoint", "EdgeHttpClient", "connectionLog", "createRtcTransportFactory", "iceServers", "createIceProvider", "signaling", "EdgeSignalManager", "edgeConnection", "WebsocketSignalManager", "_signalManager", "_networkManager", "SwarmNetworkManager", "enableDevtoolsLogging", "peerInfo", "identityKey", "peerKey", "ctx", "traceId", "PublicKey", "random", "toHex", "trace", "begin", "id", "createLevel", "ServiceContext", "dataSpaceManagerProvider", "initialized", "wait", "dataSpaceManager", "agentManagerProvider", "edgeAgentManager", "identityService", "IdentityServiceImpl", "identityManager", "recoveryManager", "keyring", "params", "_createIdentity", "profile", "broadcastProfileUpdate", "setServices", "IdentityService", "ContactsService", "ContactsServiceImpl", "spaceManager", "InvitationsService", "InvitationsServiceImpl", "invitationsManager", "DevicesService", "DevicesServiceImpl", "SpacesService", "SpacesServiceImpl", "DataService", "echoHost", "dataService", "QueryService", "queryService", "NetworkService", "NetworkServiceImpl", "networkManager", "LoggingService", "DevtoolsHost", "DevtoolsServiceImpl", "events", "DevtoolsHostEvents", "EdgeAgentService", "EdgeAgentServiceImpl", "devtoolsProxy", "_devtoolsProxy", "WebsocketRpcClient", "url", "requested", "exposed", "handlers", "start", "emit", "deviceKey", "identity", "end", "stop", "info", "createIdentity", "Trace", "synchronized", "span", "resource"]
|
|
7
|
-
}
|