matrix-js-sdk 42.3.0 → 42.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/lib/@types/json.d.ts.map +1 -1
- package/lib/@types/json.js.map +1 -1
- package/lib/client.d.ts +74 -5
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +83 -7
- package/lib/client.js.map +1 -1
- package/lib/common-crypto/CryptoBackend.d.ts +42 -23
- package/lib/common-crypto/CryptoBackend.d.ts.map +1 -1
- package/lib/common-crypto/CryptoBackend.js +7 -0
- package/lib/common-crypto/CryptoBackend.js.map +1 -1
- package/lib/embedded.d.ts +35 -1
- package/lib/embedded.d.ts.map +1 -1
- package/lib/embedded.js +49 -1
- package/lib/embedded.js.map +1 -1
- package/lib/http-api/fetch.d.ts +0 -1
- package/lib/http-api/fetch.d.ts.map +1 -1
- package/lib/http-api/fetch.js +3 -22
- package/lib/http-api/fetch.js.map +1 -1
- package/lib/http-api/logging.d.ts +10 -0
- package/lib/http-api/logging.d.ts.map +1 -0
- package/lib/http-api/logging.js +46 -0
- package/lib/http-api/logging.js.map +1 -0
- package/lib/matrixrtc/EncryptionManager.d.ts +5 -0
- package/lib/matrixrtc/EncryptionManager.d.ts.map +1 -1
- package/lib/matrixrtc/EncryptionManager.js.map +1 -1
- package/lib/matrixrtc/LivekitTransport.d.ts +82 -0
- package/lib/matrixrtc/LivekitTransport.d.ts.map +1 -1
- package/lib/matrixrtc/LivekitTransport.js +25 -0
- package/lib/matrixrtc/LivekitTransport.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.d.ts +41 -2
- package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.js +59 -1
- package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
- package/lib/matrixrtc/MembershipManager.js +7 -4
- package/lib/matrixrtc/MembershipManager.js.map +1 -1
- package/lib/matrixrtc/RTCEncryptionManager.d.ts +17 -0
- package/lib/matrixrtc/RTCEncryptionManager.d.ts.map +1 -1
- package/lib/matrixrtc/RTCEncryptionManager.js +68 -29
- package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
- package/lib/models/room-receipts.d.ts +9 -3
- package/lib/models/room-receipts.d.ts.map +1 -1
- package/lib/models/room-receipts.js +51 -11
- package/lib/models/room-receipts.js.map +1 -1
- package/lib/oauth/authorize.d.ts +7 -2
- package/lib/oauth/authorize.d.ts.map +1 -1
- package/lib/oauth/authorize.js +10 -4
- package/lib/oauth/authorize.js.map +1 -1
- package/lib/oauth/fetch.d.ts +17 -0
- package/lib/oauth/fetch.d.ts.map +1 -0
- package/lib/oauth/fetch.js +47 -0
- package/lib/oauth/fetch.js.map +1 -0
- package/lib/oauth/index.d.ts +15 -2
- package/lib/oauth/index.d.ts.map +1 -1
- package/lib/oauth/index.js +33 -12
- package/lib/oauth/index.js.map +1 -1
- package/lib/rust-crypto/index.d.ts +17 -0
- package/lib/rust-crypto/index.d.ts.map +1 -1
- package/lib/rust-crypto/index.js +4 -2
- package/lib/rust-crypto/index.js.map +1 -1
- package/lib/rust-crypto/rust-crypto.d.ts +6 -26
- package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
- package/lib/rust-crypto/rust-crypto.js +19 -54
- package/lib/rust-crypto/rust-crypto.js.map +1 -1
- package/lib/sliding-sync-sdk.d.ts.map +1 -1
- package/lib/sliding-sync-sdk.js +65 -27
- package/lib/sliding-sync-sdk.js.map +1 -1
- package/lib/sliding-sync.d.ts +17 -0
- package/lib/sliding-sync.d.ts.map +1 -1
- package/lib/sliding-sync.js +21 -9
- package/lib/sliding-sync.js.map +1 -1
- package/lib/sync.d.ts +9 -1
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +54 -29
- package/lib/sync.js.map +1 -1
- package/package.json +5 -5
- package/src/@types/json.ts +11 -2
- package/src/client.ts +126 -11
- package/src/common-crypto/CryptoBackend.ts +45 -23
- package/src/embedded.ts +67 -4
- package/src/http-api/fetch.ts +2 -23
- package/src/http-api/logging.ts +46 -0
- package/src/matrixrtc/EncryptionManager.ts +6 -0
- package/src/matrixrtc/LivekitTransport.ts +86 -0
- package/src/matrixrtc/MatrixRTCSession.ts +81 -1
- package/src/matrixrtc/MembershipManager.ts +7 -7
- package/src/matrixrtc/RTCEncryptionManager.ts +80 -31
- package/src/models/room-receipts.ts +54 -10
- package/src/oauth/authorize.ts +10 -2
- package/src/oauth/fetch.ts +54 -0
- package/src/oauth/index.ts +29 -10
- package/src/rust-crypto/index.ts +23 -0
- package/src/rust-crypto/rust-crypto.ts +25 -67
- package/src/sliding-sync-sdk.ts +73 -33
- package/src/sliding-sync.ts +31 -14
- package/src/sync.ts +58 -35
package/lib/embedded.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"embedded.js","names":["roomId"],"sources":["../src/embedded.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type WidgetApi,\n WidgetApiToWidgetAction,\n WidgetApiResponseError,\n MatrixCapabilities,\n type IWidgetApiRequest,\n type IWidgetApiAcknowledgeResponseData,\n type ISendEventToWidgetActionRequest,\n type ISendToDeviceToWidgetActionRequest,\n type ISendEventFromWidgetResponseData,\n type IWidgetApiRequestData,\n type WidgetApiAction,\n type IWidgetApiResponse,\n type IWidgetApiResponseData,\n type IUpdateStateToWidgetActionRequest,\n UnstableApiVersion,\n} from \"matrix-widget-api\";\n\nimport { type Transport } from \"./matrixrtc/index.ts\";\nimport { MatrixEvent, type IEvent, EventStatus } from \"./models/event.ts\";\nimport {\n type ISendEventResponse,\n type SendDelayedEventRequestOpts,\n type SendDelayedEventResponse,\n UpdateDelayedEventAction,\n isSendDelayedEventRequestOpts,\n} from \"./@types/requests.ts\";\nimport { EventType, type StateEvents } from \"./@types/event.ts\";\nimport { logger } from \"./logger.ts\";\nimport {\n MatrixClient,\n ClientEvent,\n type IMatrixClientCreateOpts,\n type IStartClientOpts,\n type SendToDeviceContentMap,\n type IOpenIDToken,\n UNSTABLE_MSC4140_DELAYED_EVENTS,\n} from \"./client.ts\";\nimport { SyncApi, SyncState } from \"./sync.ts\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk.ts\";\nimport { ConnectionError, MatrixError } from \"./http-api/errors.ts\";\nimport { User } from \"./models/user.ts\";\nimport { type Room } from \"./models/room.ts\";\nimport { type ToDeviceBatch, type ToDevicePayload } from \"./models/ToDeviceMessage.ts\";\nimport { MapWithDefault, type QueryDict, recursiveMapToObject } from \"./utils.ts\";\nimport { type EmptyObject, TypedEventEmitter, UnsupportedDelayedEventsEndpointError } from \"./matrix.ts\";\n\ninterface IStateEventRequest {\n eventType: string;\n stateKey?: string;\n}\n\nexport interface ICapabilities {\n /**\n * Event types that this client expects to send.\n */\n sendEvent?: string[];\n /**\n * Event types that this client expects to receive.\n */\n receiveEvent?: string[];\n\n /**\n * Message types that this client expects to send, or true for all message\n * types.\n */\n sendMessage?: string[] | true;\n /**\n * Message types that this client expects to receive, or true for all\n * message types.\n */\n receiveMessage?: string[] | true;\n\n /**\n * Types of state events that this client expects to send.\n */\n sendState?: IStateEventRequest[];\n /**\n * Types of state events that this client expects to receive.\n */\n receiveState?: IStateEventRequest[];\n\n /**\n * To-device event types that this client expects to send.\n */\n sendToDevice?: string[];\n /**\n * To-device event types that this client expects to receive.\n */\n receiveToDevice?: string[];\n\n /**\n * Whether this client needs access to TURN servers.\n * @defaultValue false\n */\n turnServers?: boolean;\n\n /**\n * Whether this client needs to be able to send delayed events.\n * @experimental Part of MSC4140 & MSC4157\n * @defaultValue false\n */\n sendDelayedEvents?: boolean;\n\n /**\n * Whether this client needs to be able to update delayed events.\n * @experimental Part of MSC4140 & MSC4157\n * @defaultValue false\n */\n updateDelayedEvents?: boolean;\n\n /**\n * Whether this client needs to be able to send sticky events.\n * @experimental Part of MSC4354 & MSC4407\n * @defaultValue false\n */\n sendSticky?: boolean;\n\n /**\n * Whether this client needs to be able to receive sticky events.\n * @experimental Part of MSC4354 & MSC4407\n * @defaultValue false\n */\n receiveSticky?: boolean;\n\n /**\n * Whether this client needs to be able to discover the RTC transports the host can reach.\n * @experimental Part of MSC4515\n * @defaultValue false\n */\n rtcTransports?: boolean;\n}\n\nexport enum RoomWidgetClientEvent {\n PendingEventsChanged = \"PendingEvent.pendingEventsChanged\",\n}\nexport type EventHandlerMap = { [RoomWidgetClientEvent.PendingEventsChanged]: () => void };\n\n/**\n * A MatrixClient that routes its requests through the widget API instead of the\n * real CS API.\n * @experimental This class is considered unstable!\n */\nexport class RoomWidgetClient extends MatrixClient {\n private room?: Room;\n private readonly widgetApiReady: Promise<void>;\n private readonly roomStateSynced: Promise<void>;\n private lifecycle?: AbortController;\n private syncState: SyncState | null = null;\n\n private pendingSendingEventsTxId: { type: string; id: string | undefined; txId: string }[] = [];\n private eventEmitter = new TypedEventEmitter<keyof EventHandlerMap, EventHandlerMap>();\n\n /**\n *\n * @param widgetApi - The widget api to use for communication.\n * @param capabilities - The capabilities the widget client will request.\n * @param roomId - The room id the widget is associated with.\n * @param opts - The configuration options for this client.\n * @param sendContentLoaded - Whether to send a content loaded widget action immediately after initial setup.\n * Set to `false` if the widget uses `waitForIFrameLoad=true` (in this case the client does not expect a content loaded action at all),\n * or if the the widget wants to send the `ContentLoaded` action at a later point in time after the initial setup.\n */\n public constructor(\n private readonly widgetApi: WidgetApi,\n private readonly capabilities: ICapabilities,\n private readonly roomId: string,\n opts: IMatrixClientCreateOpts,\n sendContentLoaded: boolean,\n ) {\n super(opts);\n\n const transportSend = this.widgetApi.transport.send.bind(this.widgetApi.transport);\n this.widgetApi.transport.send = async <\n T extends IWidgetApiRequestData,\n R extends IWidgetApiResponseData = IWidgetApiAcknowledgeResponseData,\n >(\n action: WidgetApiAction,\n data: T,\n ): Promise<R> => {\n try {\n return await transportSend(action, data);\n } catch (error) {\n processAndThrow(error);\n }\n };\n\n const transportSendComplete = this.widgetApi.transport.sendComplete.bind(this.widgetApi.transport);\n this.widgetApi.transport.sendComplete = async <T extends IWidgetApiRequestData, R extends IWidgetApiResponse>(\n action: WidgetApiAction,\n data: T,\n ): Promise<R> => {\n try {\n return await transportSendComplete(action, data);\n } catch (error) {\n processAndThrow(error);\n }\n };\n\n this.widgetApiReady = new Promise<void>((resolve) => this.widgetApi.once(\"ready\", resolve));\n this.roomStateSynced = capabilities.receiveState?.length\n ? new Promise<void>((resolve) =>\n this.widgetApi.once(`action:${WidgetApiToWidgetAction.UpdateState}`, resolve),\n )\n : Promise.resolve();\n\n this.requestInitialCapabilities(capabilities, roomId);\n\n widgetApi.on(`action:${WidgetApiToWidgetAction.SendEvent}`, this.onEvent);\n widgetApi.on(`action:${WidgetApiToWidgetAction.SendToDevice}`, this.onToDevice);\n widgetApi.on(`action:${WidgetApiToWidgetAction.UpdateState}`, this.onStateUpdate);\n\n // Open communication with the host\n widgetApi.start();\n // Send a content loaded event now we've started the widget API\n // Note that element-web currently does not use waitForIFrameLoad=false and so\n // does *not* (yes, that is the right way around) wait for this event. Let's\n // start sending this, then once this has rolled out, we can change element-web to\n // use waitForIFrameLoad=false and have a widget API that's less racy.\n if (sendContentLoaded) widgetApi.sendContentLoaded();\n }\n\n private requestInitialCapabilities(capabilities: ICapabilities, roomId: string): void {\n // Request capabilities for the functionality this client needs to support\n if (\n capabilities.sendEvent?.length ||\n capabilities.receiveEvent?.length ||\n capabilities.sendMessage === true ||\n (Array.isArray(capabilities.sendMessage) && capabilities.sendMessage.length) ||\n capabilities.receiveMessage === true ||\n (Array.isArray(capabilities.receiveMessage) && capabilities.receiveMessage.length) ||\n capabilities.sendState?.length ||\n capabilities.receiveState?.length\n ) {\n this.widgetApi.requestCapabilityForRoomTimeline(roomId);\n }\n capabilities.sendEvent?.forEach((eventType) => this.widgetApi.requestCapabilityToSendEvent(eventType));\n capabilities.receiveEvent?.forEach((eventType) => this.widgetApi.requestCapabilityToReceiveEvent(eventType));\n if (capabilities.sendMessage === true) {\n this.widgetApi.requestCapabilityToSendMessage();\n } else if (Array.isArray(capabilities.sendMessage)) {\n capabilities.sendMessage.forEach((msgType) => this.widgetApi.requestCapabilityToSendMessage(msgType));\n }\n if (capabilities.receiveMessage === true) {\n this.widgetApi.requestCapabilityToReceiveMessage();\n } else if (Array.isArray(capabilities.receiveMessage)) {\n capabilities.receiveMessage.forEach((msgType) => this.widgetApi.requestCapabilityToReceiveMessage(msgType));\n }\n capabilities.sendState?.forEach(({ eventType, stateKey }) =>\n this.widgetApi.requestCapabilityToSendState(eventType, stateKey),\n );\n capabilities.receiveState?.forEach(({ eventType, stateKey }) =>\n this.widgetApi.requestCapabilityToReceiveState(eventType, stateKey),\n );\n capabilities.sendToDevice?.forEach((eventType) => this.widgetApi.requestCapabilityToSendToDevice(eventType));\n capabilities.receiveToDevice?.forEach((eventType) =>\n this.widgetApi.requestCapabilityToReceiveToDevice(eventType),\n );\n if (\n capabilities.sendDelayedEvents &&\n (capabilities.sendEvent?.length ||\n capabilities.sendMessage === true ||\n (Array.isArray(capabilities.sendMessage) && capabilities.sendMessage.length) ||\n capabilities.sendState?.length)\n ) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4157SendDelayedEvent);\n }\n if (capabilities.updateDelayedEvents) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4157UpdateDelayedEvent);\n }\n if (capabilities.sendSticky) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4407SendStickyEvent);\n }\n if (capabilities.receiveSticky) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4407ReceiveStickyEvent);\n }\n if (capabilities.turnServers) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC3846TurnServers);\n }\n if (capabilities.rtcTransports) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4515RtcTransports);\n }\n }\n\n public async supportUpdateState(): Promise<boolean> {\n return (await this.widgetApi.getClientVersions()).includes(UnstableApiVersion.MSC2762_UPDATE_STATE);\n }\n\n private readonly syncApiResolver = Promise.withResolvers<void>();\n public async startClient(opts: IStartClientOpts = {}): Promise<void> {\n this.lifecycle = new AbortController();\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n // Even though we have no access token and cannot sync, the sync class\n // still has some valuable helper methods that we make use of, so we\n // instantiate it anyways\n if (opts.slidingSync) {\n this.syncApi = new SlidingSyncSdk(opts.slidingSync, this, opts, this.buildSyncApiOptions());\n } else {\n this.syncApi = new SyncApi(this, opts, this.buildSyncApiOptions());\n }\n this.syncApiResolver.resolve();\n\n this.room = this.syncApi.createRoom(this.roomId);\n this.store.storeRoom(this.room);\n\n await this.widgetApiReady;\n\n // sync room state:\n if (await this.supportUpdateState()) {\n // This will resolve once the client driver has sent us all the allowed room state.\n await this.roomStateSynced;\n } else {\n // Backfill the requested events\n // We only get the most recent event for every type + state key combo,\n // so it doesn't really matter what order we inject them in\n await Promise.all(\n this.capabilities.receiveState?.map(async ({ eventType, stateKey }) => {\n const rawEvents = await this.widgetApi.readStateEvents(eventType, undefined, stateKey, [\n this.roomId,\n ]);\n const events = rawEvents.map((rawEvent) => new MatrixEvent(rawEvent as Partial<IEvent>));\n\n if (this.syncApi instanceof SyncApi) {\n // Passing events as `stateAfterEventList` will update the state.\n await this.syncApi.injectRoomEvents(this.room!, undefined, events);\n } else {\n await this.syncApi!.injectRoomEvents(this.room!, events); // Sliding Sync\n }\n events.forEach((event) => {\n this.emit(ClientEvent.Event, event);\n logger.info(`Backfilled event ${event.getId()} ${event.getType()} ${event.getStateKey()}`);\n });\n }) ?? [],\n );\n }\n\n this.cachedWellKnown.start(\n opts.clientWellKnownPollPeriod !== undefined ? 1000 * opts.clientWellKnownPollPeriod : undefined,\n );\n this.setSyncState(SyncState.Syncing);\n logger.info(\"Finished initial sync\");\n\n this.matrixRTC.start();\n\n // Watch for TURN servers, if requested\n if (this.capabilities.turnServers) this.watchTurnServers();\n }\n\n public stopClient(): void {\n this.widgetApi.off(`action:${WidgetApiToWidgetAction.SendEvent}`, this.onEvent);\n this.widgetApi.off(`action:${WidgetApiToWidgetAction.SendToDevice}`, this.onToDevice);\n this.widgetApi.off(`action:${WidgetApiToWidgetAction.UpdateState}`, this.onStateUpdate);\n\n super.stopClient();\n this.lifecycle!.abort(); // Signal to other async tasks that the client has stopped\n }\n\n public async joinRoom(roomIdOrAlias: string): Promise<Room> {\n if (roomIdOrAlias === this.roomId) return this.room!;\n throw new Error(`Unknown room: ${roomIdOrAlias}`);\n }\n\n protected async encryptAndSendEvent(\n room: Room,\n event: MatrixEvent,\n queryDict?: QueryDict,\n ): Promise<ISendEventResponse>;\n protected async encryptAndSendEvent(\n room: Room,\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n queryDict?: QueryDict,\n ): Promise<ISendEventResponse>;\n protected async encryptAndSendEvent(\n room: Room,\n event: MatrixEvent,\n delayOptsOrQuery?: SendDelayedEventRequestOpts | QueryDict,\n queryDict?: QueryDict,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let queryOpts = queryDict;\n let delayOpts: SendDelayedEventRequestOpts | undefined;\n if (delayOptsOrQuery && isSendDelayedEventRequestOpts(delayOptsOrQuery)) {\n delayOpts = delayOptsOrQuery;\n } else if (!queryOpts) {\n queryOpts = delayOptsOrQuery;\n }\n\n const stickyDurationMs = queryOpts?.[\"org.matrix.msc4354.sticky_duration_ms\"];\n if (stickyDurationMs !== undefined && typeof stickyDurationMs !== \"number\") {\n throw new Error(\"Sticky duration must be a number when defined\");\n }\n // This is save since we just checked that above\n // We need the additional as assertion for the EW linter to be happy.\n // It is not capable of implying the type based on the throw if `stickyDurationMs !== undefined && typeof stickyDurationMs !== \"number\"`\n // above\n const stickyDurationMsAsNumber: number | undefined = stickyDurationMs;\n\n // We need to extend the content with the redacts parameter\n // The js sdk uses event.redacts but the widget api uses event.content.redacts\n // This will be converted back to event.redacts in the widget driver.\n const content = event.event.redacts\n ? { ...event.getContent(), redacts: event.event.redacts }\n : event.getContent();\n\n // Delayed event special case.\n if (delayOpts) {\n // TODO: updatePendingEvent for delayed events?\n const response = await this.widgetApi\n .sendRoomEvent(\n event.getType(),\n content,\n room.roomId,\n \"delay\" in delayOpts ? delayOpts.delay : undefined,\n \"parent_delay_id\" in delayOpts ? delayOpts.parent_delay_id : undefined,\n stickyDurationMsAsNumber,\n )\n .catch(timeoutToConnectionError);\n return this.validateSendDelayedEventResponse(response);\n }\n\n const txId = event.getTxnId();\n // Add the txnId to the pending list (still with unknown evID)\n if (txId) this.pendingSendingEventsTxId.push({ type: event.getType(), id: undefined, txId });\n\n let response: ISendEventFromWidgetResponseData;\n try {\n response = await this.widgetApi\n .sendRoomEvent(event.getType(), content, room.roomId, undefined, undefined, stickyDurationMsAsNumber)\n .catch(timeoutToConnectionError);\n } catch (e) {\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n throw e;\n }\n // This also checks for an event id on the response\n room.updatePendingEvent(event, EventStatus.SENT, response.event_id);\n\n // Update the pending events list with the eventId\n this.pendingSendingEventsTxId.forEach((p) => {\n if (p.txId === txId) p.id = response.event_id;\n });\n this.eventEmitter.emit(RoomWidgetClientEvent.PendingEventsChanged);\n\n return { event_id: response.event_id! };\n }\n\n public async sendStateEvent(\n roomId: string,\n eventType: string,\n content: any,\n stateKey = \"\",\n ): Promise<ISendEventResponse> {\n const response = await this.widgetApi\n .sendStateEvent(eventType, stateKey, content, roomId)\n .catch(timeoutToConnectionError);\n if (response.event_id === undefined) {\n throw new Error(\"'event_id' absent from response to an event request\");\n }\n return { event_id: response.event_id };\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n */\n public async _unstable_sendDelayedStateEvent<K extends keyof StateEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"sendDelayedStateEvent\",\n );\n }\n\n const response = await this.widgetApi\n .sendStateEvent(\n eventType,\n stateKey,\n content,\n roomId,\n \"delay\" in delayOpts ? delayOpts.delay : undefined,\n \"parent_delay_id\" in delayOpts ? delayOpts.parent_delay_id : undefined,\n )\n .catch(timeoutToConnectionError);\n return this.validateSendDelayedEventResponse(response);\n }\n\n private validateSendDelayedEventResponse(response: ISendEventFromWidgetResponseData): SendDelayedEventResponse {\n if (response.delay_id === undefined) {\n throw new Error(\"'delay_id' absent from response to a delayed event request\");\n }\n return { delay_id: response.delay_id };\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n * @deprecated Instead use one of:\n * - {@link _unstable_cancelScheduledDelayedEvent}\n * - {@link _unstable_restartScheduledDelayedEvent}\n * - {@link _unstable_sendScheduledDelayedEvent}\n */\n public async _unstable_updateDelayedEvent(delayId: string, action: UpdateDelayedEventAction): Promise<EmptyObject> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"updateDelayedEvent\",\n );\n }\n\n switch (action) {\n case UpdateDelayedEventAction.Cancel:\n await this.widgetApi.cancelScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n break;\n case UpdateDelayedEventAction.Restart:\n await this.widgetApi.restartScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n break;\n case UpdateDelayedEventAction.Send:\n await this.widgetApi.sendScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n break;\n }\n return {};\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n */\n public async _unstable_cancelScheduledDelayedEvent(delayId: string): Promise<EmptyObject> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"cancelScheduledDelayedEvent\",\n );\n }\n\n await this.widgetApi.cancelScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n return {};\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n */\n public async _unstable_restartScheduledDelayedEvent(delayId: string): Promise<EmptyObject> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"restartScheduledDelayedEvent\",\n );\n }\n\n await this.widgetApi.restartScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n return {};\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n */\n public async _unstable_sendScheduledDelayedEvent(delayId: string): Promise<EmptyObject> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"sendScheduledDelayedEvent\",\n );\n }\n\n await this.widgetApi.sendScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n return {};\n }\n\n /**\n * by {@link MatrixClient.encryptAndSendToDevice}.\n */\n public async encryptAndSendToDevice(\n eventType: string,\n devices: { userId: string; deviceId: string }[],\n payload: ToDevicePayload,\n ): Promise<void> {\n // map: user Id → device Id → payload\n const contentMap: MapWithDefault<string, Map<string, ToDevicePayload>> = new MapWithDefault(() => new Map());\n for (const { userId, deviceId } of devices) {\n contentMap.getOrCreate(userId).set(deviceId, payload);\n }\n\n await this.widgetApi\n .sendToDevice(eventType, true, recursiveMapToObject(contentMap))\n .catch(timeoutToConnectionError);\n }\n\n public async sendToDevice(eventType: string, contentMap: SendToDeviceContentMap): Promise<EmptyObject> {\n await this.widgetApi\n .sendToDevice(eventType, false, recursiveMapToObject(contentMap))\n .catch(timeoutToConnectionError);\n return {};\n }\n\n public async getOpenIdToken(): Promise<IOpenIDToken> {\n const token = await this.widgetApi.requestOpenIDConnectToken().catch(timeoutToConnectionError);\n // the IOpenIDCredentials from the widget-api and IOpenIDToken form the matrix-js-sdk are compatible.\n // we still recreate the token to make this transparent and catch'able by the linter in case the types change in the future.\n return <IOpenIDToken>{\n access_token: token.access_token,\n expires_in: token.expires_in,\n matrix_server_name: token.matrix_server_name,\n token_type: token.token_type,\n };\n }\n\n /**\n * Returns a set of configured RTC transports supported by the homeserver.\n *\n * Overrides the homeserver-side {@link MatrixClient._unstable_getRTCTransports} (MSC4143):\n * a widget cannot make authenticated homeserver calls itself, so we ask the host over the\n * widget API instead (MSC4515). Requires the `rtcTransports` capability and a host that\n * advertises the `org.matrix.msc4515` API version (otherwise the request throws).\n */\n public override async _unstable_getRTCTransports(): Promise<Transport[]> {\n const { rtc_transports: rtcTransports } = await this.widgetApi\n .getRtcTransports()\n .catch(timeoutToConnectionError);\n return rtcTransports;\n }\n\n public async queueToDevice({ eventType, batch }: ToDeviceBatch): Promise<void> {\n // map: user Id → device Id → payload\n const contentMap: MapWithDefault<string, Map<string, ToDevicePayload>> = new MapWithDefault(() => new Map());\n for (const { userId, deviceId, payload } of batch) {\n contentMap.getOrCreate(userId).set(deviceId, payload);\n }\n\n await this.widgetApi\n .sendToDevice(eventType, false, recursiveMapToObject(contentMap))\n .catch(timeoutToConnectionError);\n }\n\n /**\n * Send an event to a specific list of devices via the widget API. Optionally encrypts the event.\n *\n * If you are using a full MatrixClient you would be calling {@link MatrixClient.getCrypto().encryptToDeviceMessages()} followed\n * by {@link MatrixClient.queueToDevice}.\n *\n * However, this is combined into a single step when running as an embedded widget client. So, we expose this method for those\n * that need it.\n *\n * @param eventType - Type of the event to send.\n * @param encrypted - Whether the event should be encrypted.\n * @param contentMap - The content to send. Map from user_id to device_id to content object.\n */\n public async sendToDeviceViaWidgetApi(\n eventType: string,\n encrypted: boolean,\n contentMap: SendToDeviceContentMap,\n ): Promise<void> {\n await this.widgetApi\n .sendToDevice(eventType, encrypted, recursiveMapToObject(contentMap))\n .catch(timeoutToConnectionError);\n }\n\n // Overridden since we get TURN servers automatically over the widget API,\n // and this method would otherwise complain about missing an access token\n public async checkTurnServers(): Promise<boolean> {\n return this.turnServers.length > 0;\n }\n\n // Overridden since we 'sync' manually without the sync API\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n private setSyncState(state: SyncState): void {\n const oldState = this.syncState;\n this.syncState = state;\n this.emit(ClientEvent.Sync, state, oldState);\n }\n\n private async ack(ev: CustomEvent<IWidgetApiRequest>): Promise<void> {\n this.widgetApi.transport.reply<IWidgetApiAcknowledgeResponseData>(ev.detail, {});\n }\n\n private updateTxId = async (event: MatrixEvent): Promise<void> => {\n // We update the txId for remote echos that originate from this client.\n // This happens with the help of `pendingSendingEventsTxId` where we store all events that are currently sending\n // with their widget txId and once ready the final evId.\n if (\n // This could theoretically be an event send by this device\n // In that case we need to update the txId of the event because the embedded client/widget\n // knows this event with a different transaction Id than what was used by the host client.\n event.getSender() === this.getUserId() &&\n // We optimize by not blocking events from types that we have not send\n // with this client.\n this.pendingSendingEventsTxId.some((p) => event.getType() === p.type)\n ) {\n // Compare by event Id if we have a matching pending event where we know the txId.\n let matchingTxId = this.pendingSendingEventsTxId.find((p) => p.id === event.getId())?.txId;\n // Block any further processing of this event until we have received the sending response.\n // -> until we know the event id.\n // -> until we have not pending events anymore.\n while (!matchingTxId && this.pendingSendingEventsTxId.length > 0) {\n // Recheck whenever the PendingEventsChanged\n await new Promise<void>((resolve) =>\n this.eventEmitter.once(RoomWidgetClientEvent.PendingEventsChanged, () => resolve()),\n );\n matchingTxId = this.pendingSendingEventsTxId.find((p) => p.id === event.getId())?.txId;\n }\n\n // We found the correct txId: we update the event and delete the entry of the pending events.\n if (matchingTxId) {\n event.setTxnId(matchingTxId);\n event.setUnsigned({ ...event.getUnsigned(), transaction_id: matchingTxId });\n }\n this.pendingSendingEventsTxId = this.pendingSendingEventsTxId.filter((p) => p.id !== event.getId());\n\n // Emit once there are no pending events anymore to release all other events that got\n // awaited in the `while (!matchingTxId && this.pendingSendingEventsTxId.length > 0)` loop\n // but are not send by this client.\n if (this.pendingSendingEventsTxId.length === 0) {\n this.eventEmitter.emit(RoomWidgetClientEvent.PendingEventsChanged);\n }\n }\n };\n\n private onEvent = async (ev: CustomEvent<ISendEventToWidgetActionRequest>): Promise<void> => {\n ev.preventDefault();\n\n // Verify the room ID matches, since it's possible for the client to\n // send us events from other rooms if this widget is always on screen\n if (ev.detail.data.room_id === this.roomId) {\n const event = new MatrixEvent(ev.detail.data);\n\n // Only inject once we have update the txId\n await this.updateTxId(event);\n await this.syncApiResolver.promise;\n if (this.syncApi instanceof SyncApi) {\n if (await this.supportUpdateState()) {\n await this.syncApi.injectRoomEvents(this.room!, undefined, [], [event]);\n } else {\n // Passing undefined for `stateAfterEventList` will make `injectRoomEvents` run in legacy mode\n // -> state events in `timelineEventList` will update the state.\n await this.syncApi.injectRoomEvents(this.room!, [], undefined, [event]);\n }\n } else {\n // Sliding Sync\n if (await this.supportUpdateState()) {\n await this.syncApi!.injectRoomEvents(this.room!, [], [event]);\n } else {\n logger.error(\n \"slididng sync cannot be used in widget mode if the client widget driver does not support the version: 'org.matrix.msc2762_update_state'\",\n );\n }\n }\n\n this.emit(ClientEvent.Event, event);\n if (event.unstableStickyInfo !== undefined) this.room!._unstable_addStickyEvents([event]);\n this.setSyncState(SyncState.Syncing);\n logger.info(`Received event ${event.getId()} ${event.getType()}`);\n } else {\n const { event_id: eventId, room_id: roomId } = ev.detail.data;\n logger.info(`Received event ${eventId} for a different room ${roomId}; discarding`);\n }\n\n await this.ack(ev);\n };\n\n private onToDevice = async (ev: CustomEvent<ISendToDeviceToWidgetActionRequest>): Promise<void> => {\n ev.preventDefault();\n\n const event = new MatrixEvent({\n type: ev.detail.data.type,\n sender: ev.detail.data.sender,\n content: ev.detail.data.content,\n });\n // Mark the event as encrypted if it was, using fake contents and keys since those are unknown to us\n if (ev.detail.data.encrypted) event.makeEncrypted(EventType.RoomMessageEncrypted, {}, \"\", \"\");\n\n this.emit(ClientEvent.ToDeviceEvent, event);\n this.setSyncState(SyncState.Syncing);\n await this.ack(ev);\n };\n\n private onStateUpdate = async (ev: CustomEvent<IUpdateStateToWidgetActionRequest>): Promise<void> => {\n ev.preventDefault();\n if (!(await this.supportUpdateState())) {\n logger.warn(\n \"received update_state widget action but the widget driver did not claim to support 'org.matrix.msc2762_update_state'\",\n );\n }\n await this.syncApiResolver.promise;\n for (const rawEvent of ev.detail.data.state) {\n // Verify the room ID matches, since it's possible for the client to\n // send us state updates from other rooms if this widget is always\n // on screen\n if (rawEvent.room_id === this.roomId) {\n const event = new MatrixEvent(rawEvent);\n\n if (this.syncApi instanceof SyncApi) {\n await this.syncApi.injectRoomEvents(this.room!, undefined, [event]);\n } else {\n // Sliding Sync\n await this.syncApi!.injectRoomEvents(this.room!, [event]);\n }\n logger.debug(`Updated state entry ${event.getType()} ${event.getStateKey()} to ${event.getId()}`);\n } else {\n const { event_id: eventId, room_id: roomId } = ev.detail.data;\n logger.info(`Received state entry ${eventId} for a different room ${roomId}; discarding`);\n }\n }\n\n await this.ack(ev);\n };\n\n private async watchTurnServers(): Promise<void> {\n const servers = this.widgetApi.getTurnServers();\n const onClientStopped = (): void => {\n servers.return(undefined);\n };\n this.lifecycle!.signal.addEventListener(\"abort\", onClientStopped);\n\n try {\n for await (const server of servers) {\n this.turnServers = [\n {\n urls: server.uris,\n username: server.username,\n credential: server.password,\n },\n ];\n this.emit(ClientEvent.TurnServers, this.turnServers);\n logger.log(`Received TURN server: ${server.uris}`);\n }\n } catch (e) {\n logger.warn(\"Error watching TURN servers\", e);\n } finally {\n this.lifecycle!.signal.removeEventListener(\"abort\", onClientStopped);\n }\n }\n}\n\nfunction processAndThrow(error: unknown): never {\n if (error instanceof WidgetApiResponseError && error.data.matrix_api_error) {\n throw MatrixError.fromWidgetApiErrorData(error.data.matrix_api_error);\n } else {\n throw error;\n }\n}\n\n/**\n * This converts an \"Request timed out\" error from the PostmessageTransport into a ConnectionError.\n * It either throws the original error or a new ConnectionError.\n **/\nfunction timeoutToConnectionError(error: unknown): never {\n // TODO: this should not check on error.message but instead it should be a specific type\n // error instanceof WidgetTimeoutError\n if (error instanceof Error && error.message === \"Request timed out\") {\n throw new ConnectionError(\"widget api timeout\");\n }\n throw error;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAEI,uBAAuB,EACvB,sBAAsB,EACtB,kBAAkB,EAWlB,kBAAkB,QACf,mBAAmB;AAG1B,SAAS,WAAW,EAAe,WAAW,QAAQ,mBAAmB;AACzE,SAII,wBAAwB,EACxB,6BAA6B,QAC1B,sBAAsB;AAC7B,SAAS,SAAS,QAA0B,mBAAmB;AAC/D,SAAS,MAAM,QAAQ,aAAa;AACpC,SACI,YAAY,EACZ,WAAW,EAKX,+BAA+B,QAC5B,aAAa;AACpB,SAAS,OAAO,EAAE,SAAS,QAAQ,WAAW;AAC9C,SAAS,cAAc,QAAQ,uBAAuB;AACtD,SAAS,eAAe,EAAE,WAAW,QAAQ,sBAAsB;AACnE,SAAS,IAAI,QAAQ,kBAAkB;AAGvC,SAAS,cAAc,EAAkB,oBAAoB,QAAQ,YAAY;AACjF,SAA2B,iBAAiB,EAAE,qCAAqC,QAAQ,aAAa;AAwFxG,WAAY,qBAAqB,0BAArB,qBAAqB;EAArB,qBAAqB;EAAA,OAArB,qBAAqB;AAAA;AAKjC;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,gBAAgB,SAAS,YAAY,CAAC;EAU/C;AACJ;AACA;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CAAC,MAAM;IACH,MAAM,KAAK;EACf;AACJ;;AAEA;AACA;AACA;AACA;AACA,SAAS,wBAAwB,CAAC,KAAc,EAAS;EACrD;EACA;EACA,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,KAAK,mBAAmB,EAAE;IACjE,MAAM,IAAI,eAAe,CAAC,oBAAoB,CAAC;EACnD;EACA,MAAM,KAAK;AACf","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"embedded.js","names":["roomId"],"sources":["../src/embedded.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type WidgetApi,\n WidgetApiToWidgetAction,\n WidgetApiResponseError,\n MatrixCapabilities,\n type IWidgetApiRequest,\n type IWidgetApiAcknowledgeResponseData,\n type ISendEventToWidgetActionRequest,\n type ISendToDeviceToWidgetActionRequest,\n type ISendEventFromWidgetResponseData,\n type IWidgetApiRequestData,\n type WidgetApiAction,\n type IWidgetApiResponse,\n type IWidgetApiResponseData,\n type IUpdateStateToWidgetActionRequest,\n UnstableApiVersion,\n} from \"matrix-widget-api\";\n\nimport {\n type LivekitDelegateDelayedLeaveRequest,\n type LivekitGetTokenRequest,\n type LivekitGetTokenResponse,\n type Transport,\n} from \"./matrixrtc/index.ts\";\nimport { MatrixEvent, type IEvent, EventStatus } from \"./models/event.ts\";\nimport {\n type ISendEventResponse,\n type SendDelayedEventRequestOpts,\n type SendDelayedEventResponse,\n UpdateDelayedEventAction,\n isSendDelayedEventRequestOpts,\n} from \"./@types/requests.ts\";\nimport { EventType, type StateEvents } from \"./@types/event.ts\";\nimport { logger } from \"./logger.ts\";\nimport {\n MatrixClient,\n ClientEvent,\n type IMatrixClientCreateOpts,\n type IStartClientOpts,\n type SendToDeviceContentMap,\n type IOpenIDToken,\n UNSTABLE_MSC4140_DELAYED_EVENTS,\n} from \"./client.ts\";\nimport { SyncApi, SyncState } from \"./sync.ts\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk.ts\";\nimport { ConnectionError, MatrixError } from \"./http-api/errors.ts\";\nimport { User } from \"./models/user.ts\";\nimport { type Room } from \"./models/room.ts\";\nimport { type ToDeviceBatch, type ToDevicePayload } from \"./models/ToDeviceMessage.ts\";\nimport { MapWithDefault, type QueryDict, recursiveMapToObject } from \"./utils.ts\";\nimport { type EmptyObject, TypedEventEmitter, UnsupportedDelayedEventsEndpointError } from \"./matrix.ts\";\n\ninterface IStateEventRequest {\n eventType: string;\n stateKey?: string;\n}\n\nexport interface ICapabilities {\n /**\n * Event types that this client expects to send.\n */\n sendEvent?: string[];\n /**\n * Event types that this client expects to receive.\n */\n receiveEvent?: string[];\n\n /**\n * Message types that this client expects to send, or true for all message\n * types.\n */\n sendMessage?: string[] | true;\n /**\n * Message types that this client expects to receive, or true for all\n * message types.\n */\n receiveMessage?: string[] | true;\n\n /**\n * Types of state events that this client expects to send.\n */\n sendState?: IStateEventRequest[];\n /**\n * Types of state events that this client expects to receive.\n */\n receiveState?: IStateEventRequest[];\n\n /**\n * To-device event types that this client expects to send.\n */\n sendToDevice?: string[];\n /**\n * To-device event types that this client expects to receive.\n */\n receiveToDevice?: string[];\n\n /**\n * Whether this client needs access to TURN servers.\n * @defaultValue false\n */\n turnServers?: boolean;\n\n /**\n * Whether this client needs to be able to send delayed events.\n * @experimental Part of MSC4140 & MSC4157\n * @defaultValue false\n */\n sendDelayedEvents?: boolean;\n\n /**\n * Whether this client needs to be able to update delayed events.\n * @experimental Part of MSC4140 & MSC4157\n * @defaultValue false\n */\n updateDelayedEvents?: boolean;\n\n /**\n * Whether this client needs to be able to send sticky events.\n * @experimental Part of MSC4354 & MSC4407\n * @defaultValue false\n */\n sendSticky?: boolean;\n\n /**\n * Whether this client needs to be able to receive sticky events.\n * @experimental Part of MSC4354 & MSC4407\n * @defaultValue false\n */\n receiveSticky?: boolean;\n\n /**\n * Whether this client needs to be able to discover the RTC transports the host can reach.\n * @experimental Part of MSC4515\n * @defaultValue false\n */\n rtcTransports?: boolean;\n\n /**\n * Whether this client needs to be able to obtain LiveKit SFU tokens through the host.\n * @experimental Part of MSC4195 & MSC4533\n * @defaultValue false\n */\n rtcLivekitGetToken?: boolean;\n\n /**\n * Whether this client needs to be able to hand delayed MatrixRTC leave events over to the\n * homeserver through the host.\n * @experimental Part of MSC4195 & MSC4533\n * @defaultValue false\n */\n rtcLivekitDelegateDelayedLeave?: boolean;\n}\n\nexport enum RoomWidgetClientEvent {\n PendingEventsChanged = \"PendingEvent.pendingEventsChanged\",\n}\nexport type EventHandlerMap = { [RoomWidgetClientEvent.PendingEventsChanged]: () => void };\n\n/**\n * A MatrixClient that routes its requests through the widget API instead of the\n * real CS API.\n * @experimental This class is considered unstable!\n */\nexport class RoomWidgetClient extends MatrixClient {\n private room?: Room;\n private readonly widgetApiReady: Promise<void>;\n private readonly roomStateSynced: Promise<void>;\n private lifecycle?: AbortController;\n private syncState: SyncState | null = null;\n\n private pendingSendingEventsTxId: { type: string; id: string | undefined; txId: string }[] = [];\n private eventEmitter = new TypedEventEmitter<keyof EventHandlerMap, EventHandlerMap>();\n\n /**\n *\n * @param widgetApi - The widget api to use for communication.\n * @param capabilities - The capabilities the widget client will request.\n * @param roomId - The room id the widget is associated with.\n * @param opts - The configuration options for this client.\n * @param sendContentLoaded - Whether to send a content loaded widget action immediately after initial setup.\n * Set to `false` if the widget uses `waitForIFrameLoad=true` (in this case the client does not expect a content loaded action at all),\n * or if the the widget wants to send the `ContentLoaded` action at a later point in time after the initial setup.\n */\n public constructor(\n private readonly widgetApi: WidgetApi,\n private readonly capabilities: ICapabilities,\n private readonly roomId: string,\n opts: IMatrixClientCreateOpts,\n sendContentLoaded: boolean,\n ) {\n super(opts);\n\n const transportSend = this.widgetApi.transport.send.bind(this.widgetApi.transport);\n this.widgetApi.transport.send = async <\n T extends IWidgetApiRequestData,\n R extends IWidgetApiResponseData = IWidgetApiAcknowledgeResponseData,\n >(\n action: WidgetApiAction,\n data: T,\n ): Promise<R> => {\n try {\n return await transportSend(action, data);\n } catch (error) {\n processAndThrow(error);\n }\n };\n\n const transportSendComplete = this.widgetApi.transport.sendComplete.bind(this.widgetApi.transport);\n this.widgetApi.transport.sendComplete = async <T extends IWidgetApiRequestData, R extends IWidgetApiResponse>(\n action: WidgetApiAction,\n data: T,\n ): Promise<R> => {\n try {\n return await transportSendComplete(action, data);\n } catch (error) {\n processAndThrow(error);\n }\n };\n\n this.widgetApiReady = new Promise<void>((resolve) => this.widgetApi.once(\"ready\", resolve));\n this.roomStateSynced = capabilities.receiveState?.length\n ? new Promise<void>((resolve) =>\n this.widgetApi.once(`action:${WidgetApiToWidgetAction.UpdateState}`, resolve),\n )\n : Promise.resolve();\n\n this.requestInitialCapabilities(capabilities, roomId);\n\n widgetApi.on(`action:${WidgetApiToWidgetAction.SendEvent}`, this.onEvent);\n widgetApi.on(`action:${WidgetApiToWidgetAction.SendToDevice}`, this.onToDevice);\n widgetApi.on(`action:${WidgetApiToWidgetAction.UpdateState}`, this.onStateUpdate);\n\n // Open communication with the host\n widgetApi.start();\n // Send a content loaded event now we've started the widget API\n // Note that element-web currently does not use waitForIFrameLoad=false and so\n // does *not* (yes, that is the right way around) wait for this event. Let's\n // start sending this, then once this has rolled out, we can change element-web to\n // use waitForIFrameLoad=false and have a widget API that's less racy.\n if (sendContentLoaded) widgetApi.sendContentLoaded();\n }\n\n private requestInitialCapabilities(capabilities: ICapabilities, roomId: string): void {\n // Request capabilities for the functionality this client needs to support\n if (\n capabilities.sendEvent?.length ||\n capabilities.receiveEvent?.length ||\n capabilities.sendMessage === true ||\n (Array.isArray(capabilities.sendMessage) && capabilities.sendMessage.length) ||\n capabilities.receiveMessage === true ||\n (Array.isArray(capabilities.receiveMessage) && capabilities.receiveMessage.length) ||\n capabilities.sendState?.length ||\n capabilities.receiveState?.length\n ) {\n this.widgetApi.requestCapabilityForRoomTimeline(roomId);\n }\n capabilities.sendEvent?.forEach((eventType) => this.widgetApi.requestCapabilityToSendEvent(eventType));\n capabilities.receiveEvent?.forEach((eventType) => this.widgetApi.requestCapabilityToReceiveEvent(eventType));\n if (capabilities.sendMessage === true) {\n this.widgetApi.requestCapabilityToSendMessage();\n } else if (Array.isArray(capabilities.sendMessage)) {\n capabilities.sendMessage.forEach((msgType) => this.widgetApi.requestCapabilityToSendMessage(msgType));\n }\n if (capabilities.receiveMessage === true) {\n this.widgetApi.requestCapabilityToReceiveMessage();\n } else if (Array.isArray(capabilities.receiveMessage)) {\n capabilities.receiveMessage.forEach((msgType) => this.widgetApi.requestCapabilityToReceiveMessage(msgType));\n }\n capabilities.sendState?.forEach(({ eventType, stateKey }) =>\n this.widgetApi.requestCapabilityToSendState(eventType, stateKey),\n );\n capabilities.receiveState?.forEach(({ eventType, stateKey }) =>\n this.widgetApi.requestCapabilityToReceiveState(eventType, stateKey),\n );\n capabilities.sendToDevice?.forEach((eventType) => this.widgetApi.requestCapabilityToSendToDevice(eventType));\n capabilities.receiveToDevice?.forEach((eventType) =>\n this.widgetApi.requestCapabilityToReceiveToDevice(eventType),\n );\n if (\n capabilities.sendDelayedEvents &&\n (capabilities.sendEvent?.length ||\n capabilities.sendMessage === true ||\n (Array.isArray(capabilities.sendMessage) && capabilities.sendMessage.length) ||\n capabilities.sendState?.length)\n ) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4157SendDelayedEvent);\n }\n if (capabilities.updateDelayedEvents) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4157UpdateDelayedEvent);\n }\n if (capabilities.sendSticky) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4407SendStickyEvent);\n }\n if (capabilities.receiveSticky) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4407ReceiveStickyEvent);\n }\n if (capabilities.turnServers) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC3846TurnServers);\n }\n if (capabilities.rtcTransports) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4515RtcTransports);\n }\n if (capabilities.rtcLivekitGetToken) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4533RtcLivekitGetToken);\n }\n if (capabilities.rtcLivekitDelegateDelayedLeave) {\n this.widgetApi.requestCapability(MatrixCapabilities.MSC4533RtcLivekitDelegateDelayedLeave);\n }\n }\n\n public async supportUpdateState(): Promise<boolean> {\n return (await this.widgetApi.getClientVersions()).includes(UnstableApiVersion.MSC2762_UPDATE_STATE);\n }\n\n private readonly syncApiResolver = Promise.withResolvers<void>();\n public async startClient(opts: IStartClientOpts = {}): Promise<void> {\n this.lifecycle = new AbortController();\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n // Even though we have no access token and cannot sync, the sync class\n // still has some valuable helper methods that we make use of, so we\n // instantiate it anyways\n if (opts.slidingSync) {\n this.syncApi = new SlidingSyncSdk(opts.slidingSync, this, opts, this.buildSyncApiOptions());\n } else {\n this.syncApi = new SyncApi(this, opts, this.buildSyncApiOptions());\n }\n this.syncApiResolver.resolve();\n\n this.room = this.syncApi.createRoom(this.roomId);\n this.store.storeRoom(this.room);\n\n await this.widgetApiReady;\n\n // sync room state:\n if (await this.supportUpdateState()) {\n // This will resolve once the client driver has sent us all the allowed room state.\n await this.roomStateSynced;\n } else {\n // Backfill the requested events\n // We only get the most recent event for every type + state key combo,\n // so it doesn't really matter what order we inject them in\n await Promise.all(\n this.capabilities.receiveState?.map(async ({ eventType, stateKey }) => {\n const rawEvents = await this.widgetApi.readStateEvents(eventType, undefined, stateKey, [\n this.roomId,\n ]);\n const events = rawEvents.map((rawEvent) => new MatrixEvent(rawEvent as Partial<IEvent>));\n\n if (this.syncApi instanceof SyncApi) {\n // Passing events as `stateAfterEventList` will update the state.\n await this.syncApi.injectRoomEvents(this.room!, undefined, events);\n } else {\n await this.syncApi!.injectRoomEvents(this.room!, events); // Sliding Sync\n }\n events.forEach((event) => {\n this.emit(ClientEvent.Event, event);\n logger.info(`Backfilled event ${event.getId()} ${event.getType()} ${event.getStateKey()}`);\n });\n }) ?? [],\n );\n }\n\n // Only poll the client well-known when a poll period was configured: leaving\n // `clientWellKnownPollPeriod` undefined disables the lookups entirely.\n if (opts.clientWellKnownPollPeriod !== undefined) {\n this.cachedWellKnown.start(1000 * opts.clientWellKnownPollPeriod);\n }\n this.setSyncState(SyncState.Syncing);\n logger.info(\"Finished initial sync\");\n\n this.matrixRTC.start();\n\n // Watch for TURN servers, if requested\n if (this.capabilities.turnServers) this.watchTurnServers();\n }\n\n public stopClient(): void {\n this.widgetApi.off(`action:${WidgetApiToWidgetAction.SendEvent}`, this.onEvent);\n this.widgetApi.off(`action:${WidgetApiToWidgetAction.SendToDevice}`, this.onToDevice);\n this.widgetApi.off(`action:${WidgetApiToWidgetAction.UpdateState}`, this.onStateUpdate);\n\n super.stopClient();\n this.lifecycle!.abort(); // Signal to other async tasks that the client has stopped\n }\n\n public async joinRoom(roomIdOrAlias: string): Promise<Room> {\n if (roomIdOrAlias === this.roomId) return this.room!;\n throw new Error(`Unknown room: ${roomIdOrAlias}`);\n }\n\n protected async encryptAndSendEvent(\n room: Room,\n event: MatrixEvent,\n queryDict?: QueryDict,\n ): Promise<ISendEventResponse>;\n protected async encryptAndSendEvent(\n room: Room,\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n queryDict?: QueryDict,\n ): Promise<ISendEventResponse>;\n protected async encryptAndSendEvent(\n room: Room,\n event: MatrixEvent,\n delayOptsOrQuery?: SendDelayedEventRequestOpts | QueryDict,\n queryDict?: QueryDict,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let queryOpts = queryDict;\n let delayOpts: SendDelayedEventRequestOpts | undefined;\n if (delayOptsOrQuery && isSendDelayedEventRequestOpts(delayOptsOrQuery)) {\n delayOpts = delayOptsOrQuery;\n } else if (!queryOpts) {\n queryOpts = delayOptsOrQuery;\n }\n\n const stickyDurationMs = queryOpts?.[\"org.matrix.msc4354.sticky_duration_ms\"];\n if (stickyDurationMs !== undefined && typeof stickyDurationMs !== \"number\") {\n throw new Error(\"Sticky duration must be a number when defined\");\n }\n // This is save since we just checked that above\n // We need the additional as assertion for the EW linter to be happy.\n // It is not capable of implying the type based on the throw if `stickyDurationMs !== undefined && typeof stickyDurationMs !== \"number\"`\n // above\n const stickyDurationMsAsNumber: number | undefined = stickyDurationMs;\n\n // We need to extend the content with the redacts parameter\n // The js sdk uses event.redacts but the widget api uses event.content.redacts\n // This will be converted back to event.redacts in the widget driver.\n const content = event.event.redacts\n ? { ...event.getContent(), redacts: event.event.redacts }\n : event.getContent();\n\n // Delayed event special case.\n if (delayOpts) {\n // TODO: updatePendingEvent for delayed events?\n const response = await this.widgetApi\n .sendRoomEvent(\n event.getType(),\n content,\n room.roomId,\n \"delay\" in delayOpts ? delayOpts.delay : undefined,\n \"parent_delay_id\" in delayOpts ? delayOpts.parent_delay_id : undefined,\n stickyDurationMsAsNumber,\n )\n .catch(timeoutToConnectionError);\n return this.validateSendDelayedEventResponse(response);\n }\n\n const txId = event.getTxnId();\n // Add the txnId to the pending list (still with unknown evID)\n if (txId) this.pendingSendingEventsTxId.push({ type: event.getType(), id: undefined, txId });\n\n let response: ISendEventFromWidgetResponseData;\n try {\n response = await this.widgetApi\n .sendRoomEvent(event.getType(), content, room.roomId, undefined, undefined, stickyDurationMsAsNumber)\n .catch(timeoutToConnectionError);\n } catch (e) {\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n throw e;\n }\n // This also checks for an event id on the response\n room.updatePendingEvent(event, EventStatus.SENT, response.event_id);\n\n // Update the pending events list with the eventId\n this.pendingSendingEventsTxId.forEach((p) => {\n if (p.txId === txId) p.id = response.event_id;\n });\n this.eventEmitter.emit(RoomWidgetClientEvent.PendingEventsChanged);\n\n return { event_id: response.event_id! };\n }\n\n public async sendStateEvent(\n roomId: string,\n eventType: string,\n content: any,\n stateKey = \"\",\n ): Promise<ISendEventResponse> {\n const response = await this.widgetApi\n .sendStateEvent(eventType, stateKey, content, roomId)\n .catch(timeoutToConnectionError);\n if (response.event_id === undefined) {\n throw new Error(\"'event_id' absent from response to an event request\");\n }\n return { event_id: response.event_id };\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n */\n public async _unstable_sendDelayedStateEvent<K extends keyof StateEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"sendDelayedStateEvent\",\n );\n }\n\n const response = await this.widgetApi\n .sendStateEvent(\n eventType,\n stateKey,\n content,\n roomId,\n \"delay\" in delayOpts ? delayOpts.delay : undefined,\n \"parent_delay_id\" in delayOpts ? delayOpts.parent_delay_id : undefined,\n )\n .catch(timeoutToConnectionError);\n return this.validateSendDelayedEventResponse(response);\n }\n\n private validateSendDelayedEventResponse(response: ISendEventFromWidgetResponseData): SendDelayedEventResponse {\n if (response.delay_id === undefined) {\n throw new Error(\"'delay_id' absent from response to a delayed event request\");\n }\n return { delay_id: response.delay_id };\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n * @deprecated Instead use one of:\n * - {@link _unstable_cancelScheduledDelayedEvent}\n * - {@link _unstable_restartScheduledDelayedEvent}\n * - {@link _unstable_sendScheduledDelayedEvent}\n */\n public async _unstable_updateDelayedEvent(delayId: string, action: UpdateDelayedEventAction): Promise<EmptyObject> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"updateDelayedEvent\",\n );\n }\n\n switch (action) {\n case UpdateDelayedEventAction.Cancel:\n await this.widgetApi.cancelScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n break;\n case UpdateDelayedEventAction.Restart:\n await this.widgetApi.restartScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n break;\n case UpdateDelayedEventAction.Send:\n await this.widgetApi.sendScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n break;\n }\n return {};\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n */\n public async _unstable_cancelScheduledDelayedEvent(delayId: string): Promise<EmptyObject> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"cancelScheduledDelayedEvent\",\n );\n }\n\n await this.widgetApi.cancelScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n return {};\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n */\n public async _unstable_restartScheduledDelayedEvent(delayId: string): Promise<EmptyObject> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"restartScheduledDelayedEvent\",\n );\n }\n\n await this.widgetApi.restartScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n return {};\n }\n\n /**\n * @experimental This currently relies on an unstable MSC (MSC4140).\n */\n public async _unstable_sendScheduledDelayedEvent(delayId: string): Promise<EmptyObject> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw new UnsupportedDelayedEventsEndpointError(\n \"Server does not support the delayed events API\",\n \"sendScheduledDelayedEvent\",\n );\n }\n\n await this.widgetApi.sendScheduledDelayedEvent(delayId).catch(timeoutToConnectionError);\n return {};\n }\n\n /**\n * by {@link MatrixClient.encryptAndSendToDevice}.\n */\n public async encryptAndSendToDevice(\n eventType: string,\n devices: { userId: string; deviceId: string }[],\n payload: ToDevicePayload,\n ): Promise<void> {\n // map: user Id → device Id → payload\n const contentMap: MapWithDefault<string, Map<string, ToDevicePayload>> = new MapWithDefault(() => new Map());\n for (const { userId, deviceId } of devices) {\n contentMap.getOrCreate(userId).set(deviceId, payload);\n }\n\n await this.widgetApi\n .sendToDevice(eventType, true, recursiveMapToObject(contentMap))\n .catch(timeoutToConnectionError);\n }\n\n public async sendToDevice(eventType: string, contentMap: SendToDeviceContentMap): Promise<EmptyObject> {\n await this.widgetApi\n .sendToDevice(eventType, false, recursiveMapToObject(contentMap))\n .catch(timeoutToConnectionError);\n return {};\n }\n\n public async getOpenIdToken(): Promise<IOpenIDToken> {\n const token = await this.widgetApi.requestOpenIDConnectToken().catch(timeoutToConnectionError);\n // the IOpenIDCredentials from the widget-api and IOpenIDToken form the matrix-js-sdk are compatible.\n // we still recreate the token to make this transparent and catch'able by the linter in case the types change in the future.\n return <IOpenIDToken>{\n access_token: token.access_token,\n expires_in: token.expires_in,\n matrix_server_name: token.matrix_server_name,\n token_type: token.token_type,\n };\n }\n\n /**\n * Returns a set of configured RTC transports supported by the homeserver.\n *\n * Overrides the homeserver-side {@link MatrixClient._unstable_getRTCTransports} (MSC4143):\n * a widget cannot make authenticated homeserver calls itself, so we ask the host over the\n * widget API instead (MSC4515). Requires the `rtcTransports` capability and a host that\n * advertises the `org.matrix.msc4515` API version (otherwise the request throws).\n */\n public override async _unstable_getRTCTransports(): Promise<Transport[]> {\n const { rtc_transports: rtcTransports } = await this.widgetApi\n .getRtcTransports()\n .catch(timeoutToConnectionError);\n return rtcTransports;\n }\n\n /**\n * Requests a token to authenticate against a LiveKit SFU with.\n *\n * Overrides the homeserver-side {@link MatrixClient._unstable_getLivekitToken} (MSC4195): a widget\n * cannot make authenticated homeserver calls itself, so we ask the host to make the call on our\n * behalf over the widget API instead (MSC4533). Requires the `rtcLivekitGetToken` capability and a\n * host that advertises the `org.matrix.msc4533` API version (otherwise the request throws).\n *\n * `server_name` defaults to our own homeserver, matching what the endpoint would do server-side.\n */\n public override async _unstable_getLivekitToken(body: LivekitGetTokenRequest): Promise<LivekitGetTokenResponse> {\n const serverName = body.server_name ?? this.getDomain();\n if (serverName === null) throw new Error(\"Cannot determine the server name to request a token from\");\n const { jwt } = await this.widgetApi\n .getRtcLivekitToken({ ...body, server_name: serverName })\n .catch(timeoutToConnectionError);\n return { jwt };\n }\n\n /**\n * Hands over the management of a delayed MatrixRTC leave event to the homeserver.\n *\n * Overrides the homeserver-side {@link MatrixClient._unstable_delegateDelayedLeave} (MSC4195): a\n * widget cannot make authenticated homeserver calls itself, so we ask the host to make the call on\n * our behalf over the widget API instead (MSC4533). Requires the `rtcLivekitDelegateDelayedLeave`\n * capability and a host that advertises the `org.matrix.msc4533` API version (otherwise the request\n * throws).\n */\n public override async _unstable_delegateDelayedLeave(\n body: LivekitDelegateDelayedLeaveRequest,\n ): Promise<EmptyObject> {\n await this.widgetApi.delegateRtcLivekitDelayedLeave(body).catch(timeoutToConnectionError);\n return {};\n }\n\n public async queueToDevice({ eventType, batch }: ToDeviceBatch): Promise<void> {\n // map: user Id → device Id → payload\n const contentMap: MapWithDefault<string, Map<string, ToDevicePayload>> = new MapWithDefault(() => new Map());\n for (const { userId, deviceId, payload } of batch) {\n contentMap.getOrCreate(userId).set(deviceId, payload);\n }\n\n await this.widgetApi\n .sendToDevice(eventType, false, recursiveMapToObject(contentMap))\n .catch(timeoutToConnectionError);\n }\n\n /**\n * Send an event to a specific list of devices via the widget API. Optionally encrypts the event.\n *\n * If you are using a full MatrixClient you would be calling {@link MatrixClient.getCrypto().encryptToDeviceMessages()} followed\n * by {@link MatrixClient.queueToDevice}.\n *\n * However, this is combined into a single step when running as an embedded widget client. So, we expose this method for those\n * that need it.\n *\n * @param eventType - Type of the event to send.\n * @param encrypted - Whether the event should be encrypted.\n * @param contentMap - The content to send. Map from user_id to device_id to content object.\n */\n public async sendToDeviceViaWidgetApi(\n eventType: string,\n encrypted: boolean,\n contentMap: SendToDeviceContentMap,\n ): Promise<void> {\n await this.widgetApi\n .sendToDevice(eventType, encrypted, recursiveMapToObject(contentMap))\n .catch(timeoutToConnectionError);\n }\n\n // Overridden since we get TURN servers automatically over the widget API,\n // and this method would otherwise complain about missing an access token\n public async checkTurnServers(): Promise<boolean> {\n return this.turnServers.length > 0;\n }\n\n // Overridden since we 'sync' manually without the sync API\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n private setSyncState(state: SyncState): void {\n const oldState = this.syncState;\n this.syncState = state;\n this.emit(ClientEvent.Sync, state, oldState);\n }\n\n private async ack(ev: CustomEvent<IWidgetApiRequest>): Promise<void> {\n this.widgetApi.transport.reply<IWidgetApiAcknowledgeResponseData>(ev.detail, {});\n }\n\n private updateTxId = async (event: MatrixEvent): Promise<void> => {\n // We update the txId for remote echos that originate from this client.\n // This happens with the help of `pendingSendingEventsTxId` where we store all events that are currently sending\n // with their widget txId and once ready the final evId.\n if (\n // This could theoretically be an event send by this device\n // In that case we need to update the txId of the event because the embedded client/widget\n // knows this event with a different transaction Id than what was used by the host client.\n event.getSender() === this.getUserId() &&\n // We optimize by not blocking events from types that we have not send\n // with this client.\n this.pendingSendingEventsTxId.some((p) => event.getType() === p.type)\n ) {\n // Compare by event Id if we have a matching pending event where we know the txId.\n let matchingTxId = this.pendingSendingEventsTxId.find((p) => p.id === event.getId())?.txId;\n // Block any further processing of this event until we have received the sending response.\n // -> until we know the event id.\n // -> until we have not pending events anymore.\n while (!matchingTxId && this.pendingSendingEventsTxId.length > 0) {\n // Recheck whenever the PendingEventsChanged\n await new Promise<void>((resolve) =>\n this.eventEmitter.once(RoomWidgetClientEvent.PendingEventsChanged, () => resolve()),\n );\n matchingTxId = this.pendingSendingEventsTxId.find((p) => p.id === event.getId())?.txId;\n }\n\n // We found the correct txId: we update the event and delete the entry of the pending events.\n if (matchingTxId) {\n event.setTxnId(matchingTxId);\n event.setUnsigned({ ...event.getUnsigned(), transaction_id: matchingTxId });\n }\n this.pendingSendingEventsTxId = this.pendingSendingEventsTxId.filter((p) => p.id !== event.getId());\n\n // Emit once there are no pending events anymore to release all other events that got\n // awaited in the `while (!matchingTxId && this.pendingSendingEventsTxId.length > 0)` loop\n // but are not send by this client.\n if (this.pendingSendingEventsTxId.length === 0) {\n this.eventEmitter.emit(RoomWidgetClientEvent.PendingEventsChanged);\n }\n }\n };\n\n private onEvent = async (ev: CustomEvent<ISendEventToWidgetActionRequest>): Promise<void> => {\n ev.preventDefault();\n\n // Verify the room ID matches, since it's possible for the client to\n // send us events from other rooms if this widget is always on screen\n if (ev.detail.data.room_id === this.roomId) {\n const event = new MatrixEvent(ev.detail.data);\n\n // Only inject once we have update the txId\n await this.updateTxId(event);\n await this.syncApiResolver.promise;\n if (this.syncApi instanceof SyncApi) {\n if (await this.supportUpdateState()) {\n await this.syncApi.injectRoomEvents(this.room!, undefined, [], [event]);\n } else {\n // Passing undefined for `stateAfterEventList` will make `injectRoomEvents` run in legacy mode\n // -> state events in `timelineEventList` will update the state.\n await this.syncApi.injectRoomEvents(this.room!, [], undefined, [event]);\n }\n } else {\n // Sliding Sync\n if (await this.supportUpdateState()) {\n await this.syncApi!.injectRoomEvents(this.room!, [], [event]);\n } else {\n logger.error(\n \"slididng sync cannot be used in widget mode if the client widget driver does not support the version: 'org.matrix.msc2762_update_state'\",\n );\n }\n }\n\n this.emit(ClientEvent.Event, event);\n if (event.unstableStickyInfo !== undefined) this.room!._unstable_addStickyEvents([event]);\n this.setSyncState(SyncState.Syncing);\n logger.info(`Received event ${event.getId()} ${event.getType()}`);\n } else {\n const { event_id: eventId, room_id: roomId } = ev.detail.data;\n logger.info(`Received event ${eventId} for a different room ${roomId}; discarding`);\n }\n\n await this.ack(ev);\n };\n\n private onToDevice = async (ev: CustomEvent<ISendToDeviceToWidgetActionRequest>): Promise<void> => {\n ev.preventDefault();\n\n const event = new MatrixEvent({\n type: ev.detail.data.type,\n sender: ev.detail.data.sender,\n content: ev.detail.data.content,\n });\n // Mark the event as encrypted if it was, using fake contents and keys since those are unknown to us\n if (ev.detail.data.encrypted) event.makeEncrypted(EventType.RoomMessageEncrypted, {}, \"\", \"\");\n\n this.emit(ClientEvent.ToDeviceEvent, event);\n this.setSyncState(SyncState.Syncing);\n await this.ack(ev);\n };\n\n private onStateUpdate = async (ev: CustomEvent<IUpdateStateToWidgetActionRequest>): Promise<void> => {\n ev.preventDefault();\n if (!(await this.supportUpdateState())) {\n logger.warn(\n \"received update_state widget action but the widget driver did not claim to support 'org.matrix.msc2762_update_state'\",\n );\n }\n await this.syncApiResolver.promise;\n for (const rawEvent of ev.detail.data.state) {\n // Verify the room ID matches, since it's possible for the client to\n // send us state updates from other rooms if this widget is always\n // on screen\n if (rawEvent.room_id === this.roomId) {\n const event = new MatrixEvent(rawEvent);\n\n if (this.syncApi instanceof SyncApi) {\n await this.syncApi.injectRoomEvents(this.room!, undefined, [event]);\n } else {\n // Sliding Sync\n await this.syncApi!.injectRoomEvents(this.room!, [event]);\n }\n logger.debug(`Updated state entry ${event.getType()} ${event.getStateKey()} to ${event.getId()}`);\n } else {\n const { event_id: eventId, room_id: roomId } = ev.detail.data;\n logger.info(`Received state entry ${eventId} for a different room ${roomId}; discarding`);\n }\n }\n\n await this.ack(ev);\n };\n\n private async watchTurnServers(): Promise<void> {\n const servers = this.widgetApi.getTurnServers();\n const onClientStopped = (): void => {\n servers.return(undefined);\n };\n this.lifecycle!.signal.addEventListener(\"abort\", onClientStopped);\n\n try {\n for await (const server of servers) {\n this.turnServers = [\n {\n urls: server.uris,\n username: server.username,\n credential: server.password,\n },\n ];\n this.emit(ClientEvent.TurnServers, this.turnServers);\n logger.log(`Received TURN server: ${server.uris}`);\n }\n } catch (e) {\n logger.warn(\"Error watching TURN servers\", e);\n } finally {\n this.lifecycle!.signal.removeEventListener(\"abort\", onClientStopped);\n }\n }\n}\n\nfunction processAndThrow(error: unknown): never {\n if (error instanceof WidgetApiResponseError && error.data.matrix_api_error) {\n throw MatrixError.fromWidgetApiErrorData(error.data.matrix_api_error);\n } else {\n throw error;\n }\n}\n\n/**\n * This converts an \"Request timed out\" error from the PostmessageTransport into a ConnectionError.\n * It either throws the original error or a new ConnectionError.\n **/\nfunction timeoutToConnectionError(error: unknown): never {\n // TODO: this should not check on error.message but instead it should be a specific type\n // error instanceof WidgetTimeoutError\n if (error instanceof Error && error.message === \"Request timed out\") {\n throw new ConnectionError(\"widget api timeout\");\n }\n throw error;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAEI,uBAAuB,EACvB,sBAAsB,EACtB,kBAAkB,EAWlB,kBAAkB,QACf,mBAAmB;AAQ1B,SAAS,WAAW,EAAe,WAAW,QAAQ,mBAAmB;AACzE,SAII,wBAAwB,EACxB,6BAA6B,QAC1B,sBAAsB;AAC7B,SAAS,SAAS,QAA0B,mBAAmB;AAC/D,SAAS,MAAM,QAAQ,aAAa;AACpC,SACI,YAAY,EACZ,WAAW,EAKX,+BAA+B,QAC5B,aAAa;AACpB,SAAS,OAAO,EAAE,SAAS,QAAQ,WAAW;AAC9C,SAAS,cAAc,QAAQ,uBAAuB;AACtD,SAAS,eAAe,EAAE,WAAW,QAAQ,sBAAsB;AACnE,SAAS,IAAI,QAAQ,kBAAkB;AAGvC,SAAS,cAAc,EAAkB,oBAAoB,QAAQ,YAAY;AACjF,SAA2B,iBAAiB,EAAE,qCAAqC,QAAQ,aAAa;AAuGxG,WAAY,qBAAqB,0BAArB,qBAAqB;EAArB,qBAAqB;EAAA,OAArB,qBAAqB;AAAA;AAKjC;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,gBAAgB,SAAS,YAAY,CAAC;EAU/C;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EAC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@throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.
|
|
67
67
|
*/
|
|
68
68
|
requestOtherUrl<T>(method: Method, url: URL | string, body?: Body, opts?: BaseRequestOpts): Promise<T>;
|
|
69
|
-
private sanitizeUrlForLogs;
|
|
70
69
|
/**
|
|
71
70
|
* Form and return a homeserver request URL based on the given path params and prefix.
|
|
72
71
|
* @param path - The HTTP path <b>after</b> the supplied prefix e.g. "/createRoom".
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/http-api/fetch.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,KAAK,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EACH,KAAK,eAAe,EACpB,YAAY,EACZ,KAAK,sBAAsB,EAC3B,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,IAAI,EACZ,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/http-api/fetch.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,KAAK,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EACH,KAAK,eAAe,EACpB,YAAY,EACZ,KAAK,sBAAsB,EAC3B,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,IAAI,EACZ,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AAG7C,qBAAa,YAAY,CAAC,CAAC,SAAS,SAAS;IAKrC,OAAO,CAAC,YAAY;aACJ,IAAI,EAAE,CAAC;IAL3B,OAAO,CAAC,eAAe,CAAyB;IAChD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAiB;IAEhD,YACY,YAAY,EAAE,iBAAiB,CAAC,Y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C3B,OAAO,CAAC,CAAC,CAAC,CA4FZ;IAED;;;;;;;OAOG;IACI,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAa3F;CACJ"}
|
package/lib/http-api/fetch.js
CHANGED
|
@@ -25,6 +25,7 @@ import { Method } from "./method.js";
|
|
|
25
25
|
import { ConnectionError, MatrixError, TokenRefreshError } from "./errors.js";
|
|
26
26
|
import { HttpApiEvent } from "./interface.js";
|
|
27
27
|
import { anySignal, parseErrorResponse, timeoutSignal } from "./utils.js";
|
|
28
|
+
import { sanitizeUrlForLogs } from "./logging.js";
|
|
28
29
|
import { TokenRefresher, TokenRefreshOutcome } from "./refresh.js";
|
|
29
30
|
export class FetchHttpApi {
|
|
30
31
|
constructor(eventEmitter, opts) {
|
|
@@ -188,7 +189,7 @@ export class FetchHttpApi {
|
|
|
188
189
|
if (opts.json !== undefined && opts.rawResponseBody !== undefined) {
|
|
189
190
|
throw new Error("Invalid call to `FetchHttpApi` sets both `opts.json` and `opts.rawResponseBody`");
|
|
190
191
|
}
|
|
191
|
-
const urlForLogs =
|
|
192
|
+
const urlForLogs = sanitizeUrlForLogs(url);
|
|
192
193
|
this.opts.logger?.debug(`FetchHttpApi: --> ${method} ${urlForLogs}`);
|
|
193
194
|
const headers = Object.assign({}, opts.headers || {});
|
|
194
195
|
const jsonResponse = !opts.rawResponseBody && opts.json !== false;
|
|
@@ -269,27 +270,7 @@ export class FetchHttpApi {
|
|
|
269
270
|
return await res.text();
|
|
270
271
|
}
|
|
271
272
|
}
|
|
272
|
-
|
|
273
|
-
try {
|
|
274
|
-
let asUrl;
|
|
275
|
-
if (typeof url === "string") {
|
|
276
|
-
asUrl = new URL(url);
|
|
277
|
-
} else {
|
|
278
|
-
asUrl = url;
|
|
279
|
-
}
|
|
280
|
-
// Remove the values of any URL params that could contain potential secrets
|
|
281
|
-
const sanitizedQs = new URLSearchParams();
|
|
282
|
-
for (const key of asUrl.searchParams.keys()) {
|
|
283
|
-
sanitizedQs.append(key, "xxx");
|
|
284
|
-
}
|
|
285
|
-
const sanitizedQsString = sanitizedQs.toString();
|
|
286
|
-
const sanitizedQsUrlPiece = sanitizedQsString ? `?${sanitizedQsString}` : "";
|
|
287
|
-
return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;
|
|
288
|
-
} catch {
|
|
289
|
-
// defensive coding for malformed url
|
|
290
|
-
return "??";
|
|
291
|
-
}
|
|
292
|
-
}
|
|
273
|
+
|
|
293
274
|
/**
|
|
294
275
|
* Form and return a homeserver request URL based on the given path params and prefix.
|
|
295
276
|
* @param path - The HTTP path <b>after</b> the supplied prefix e.g. "/createRoom".
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.js","names":[],"sources":["../../src/http-api/fetch.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nimport { checkObjectHasKeys, deepCopy, encodeParams } from \"../utils.ts\";\nimport { type TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { Method } from \"./method.ts\";\nimport { ConnectionError, MatrixError, TokenRefreshError } from \"./errors.ts\";\nimport {\n type BaseRequestOpts,\n HttpApiEvent,\n type HttpApiEventHandlerMap,\n type IHttpOpts,\n type IRequestOpts,\n type Body,\n} from \"./interface.ts\";\nimport { anySignal, parseErrorResponse, timeoutSignal } from \"./utils.ts\";\nimport { type QueryDict } from \"../utils.ts\";\nimport { TokenRefresher, TokenRefreshOutcome } from \"./refresh.ts\";\n\nexport class FetchHttpApi<O extends IHttpOpts> {\n private abortController = new AbortController();\n private readonly tokenRefresher: TokenRefresher;\n\n public constructor(\n private eventEmitter: TypedEventEmitter<HttpApiEvent, HttpApiEventHandlerMap>,\n public readonly opts: O,\n ) {\n checkObjectHasKeys(opts, [\"baseUrl\", \"prefix\"]);\n if (!opts.onlyData) {\n throw new Error(\"Constructing FetchHttpApi without `onlyData=true` is no longer supported.\");\n }\n opts.useAuthorizationHeader = opts.useAuthorizationHeader ?? true;\n\n this.tokenRefresher = new TokenRefresher(opts);\n }\n\n public abort(): void {\n this.abortController.abort();\n this.abortController = new AbortController();\n }\n\n public fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.opts.fetchFn) {\n return this.opts.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n /**\n * Sets the base URL for the identity server\n * @param url - The new base url\n */\n public setIdBaseUrl(url?: string): void {\n this.opts.idBaseUrl = url;\n }\n\n public idServerRequest<T extends object = Record<string, unknown>>(\n method: Method,\n path: string,\n params: Record<string, string | string[]> | undefined,\n prefix: string,\n accessToken?: string,\n ): Promise<T> {\n if (!this.opts.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n let queryParams: QueryDict | undefined = undefined;\n let body: Record<string, string | string[]> | undefined = undefined;\n if (method === Method.Get) {\n queryParams = params;\n } else {\n body = params;\n }\n\n const fullUri = this.getUrl(path, queryParams, prefix, this.opts.idBaseUrl);\n\n const opts: IRequestOpts = {\n json: true,\n headers: {},\n };\n if (accessToken) {\n opts.headers!.Authorization = `Bearer ${accessToken}`;\n }\n\n return this.requestOtherUrl(method, fullUri, body, opts);\n }\n\n /**\n * Perform an authorised request to the homeserver.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param paramOpts - additional options.\n * When `paramOpts.doNotAttemptTokenRefresh` is true, token refresh will not be attempted\n * when an expired token is encountered. Used to only attempt token refresh once.\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public authedRequest<T>(\n method: Method,\n path: string,\n queryParams: QueryDict = {},\n body?: Body,\n paramOpts: IRequestOpts = {},\n ): Promise<T> {\n return this.doAuthedRequest<T>(1, method, path, queryParams, body, paramOpts);\n }\n\n // Wrapper around public method authedRequest to allow for tracking retry attempt counts\n private async doAuthedRequest<T>(\n attempt: number,\n method: Method,\n path: string,\n queryParams: QueryDict,\n body?: Body,\n paramOpts: IRequestOpts = {},\n ): Promise<T> {\n // avoid mutating paramOpts so they can be used on retry\n const opts = deepCopy(paramOpts);\n // we have to manually copy the abortSignal over as it is not a plain object\n opts.abortSignal = paramOpts.abortSignal;\n\n // Take a snapshot of the current token state before we start the request so we can reference it if we error\n const requestSnapshot = await this.tokenRefresher.prepareForRequest();\n if (requestSnapshot.accessToken) {\n if (this.opts.useAuthorizationHeader) {\n if (!opts.headers) {\n opts.headers = {};\n }\n if (!opts.headers.Authorization) {\n opts.headers.Authorization = `Bearer ${requestSnapshot.accessToken}`;\n }\n if (queryParams.access_token) {\n delete queryParams.access_token;\n }\n } else if (!queryParams.access_token) {\n queryParams.access_token = requestSnapshot.accessToken;\n }\n }\n\n try {\n const response = await this.request<T>(method, path, queryParams, body, opts);\n return response;\n } catch (error) {\n if (!(error instanceof MatrixError)) {\n throw error;\n }\n\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n const outcome = await this.tokenRefresher.handleUnknownToken(requestSnapshot, attempt);\n if (outcome === TokenRefreshOutcome.Success) {\n // if we got a new token retry the request\n return this.doAuthedRequest(attempt + 1, method, path, queryParams, body, paramOpts);\n }\n if (outcome === TokenRefreshOutcome.Failure) {\n throw new TokenRefreshError(error);\n }\n\n if (!opts?.inhibitLogoutEmit) {\n this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, error);\n }\n } else if (error.errcode == \"M_CONSENT_NOT_GIVEN\") {\n this.eventEmitter.emit(HttpApiEvent.NoConsent, error.message, error.data.consent_uri);\n }\n\n throw error;\n }\n }\n\n /**\n * Perform a request to the homeserver without any credentials.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public request<T = unknown>(\n method: Method,\n path: string,\n queryParams?: QueryDict,\n body?: Body,\n opts?: IRequestOpts,\n ): Promise<T> {\n const fullUri = this.getUrl(path, queryParams, opts?.prefix, opts?.baseUrl);\n return this.requestOtherUrl<T>(method, fullUri, body, opts);\n }\n\n /**\n * Perform a request to an arbitrary URL.\n * @param method - The HTTP method e.g. \"GET\".\n * @param url - The HTTP URL object.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public async requestOtherUrl<T>(\n method: Method,\n url: URL | string,\n body?: Body,\n opts: BaseRequestOpts = {},\n ): Promise<T> {\n if (opts.json !== undefined && opts.rawResponseBody !== undefined) {\n throw new Error(\"Invalid call to `FetchHttpApi` sets both `opts.json` and `opts.rawResponseBody`\");\n }\n\n const urlForLogs = this.sanitizeUrlForLogs(url);\n\n this.opts.logger?.debug(`FetchHttpApi: --> ${method} ${urlForLogs}`);\n\n const headers = Object.assign({}, opts.headers || {});\n\n const jsonResponse = !opts.rawResponseBody && opts.json !== false;\n if (jsonResponse) {\n if (!headers[\"Accept\"]) {\n headers[\"Accept\"] = \"application/json\";\n }\n }\n\n const timeout = opts.localTimeoutMs ?? this.opts.localTimeoutMs;\n const keepAlive = opts.keepAlive ?? false;\n const signals = [this.abortController.signal];\n if (timeout !== undefined) {\n signals.push(timeoutSignal(timeout));\n }\n if (opts.abortSignal) {\n signals.push(opts.abortSignal);\n }\n\n // If the body is an object, encode it as JSON and set the `Content-Type` header,\n // unless that has been explicitly inhibited by setting `opts.json: false`.\n // We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref\n let data: BodyInit;\n if (opts.json !== false && body?.constructor?.name === Object.name) {\n data = JSON.stringify(body);\n if (!headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n } else {\n data = body as BodyInit;\n }\n\n const { signal, cleanup } = anySignal(signals);\n\n // Set cache mode based on presence of Authorization header.\n // Browsers/proxies do not cache responses to requests with Authorization headers.\n // So specifying \"no-cache\" is redundant, and actually prevents caching\n // of preflight requests in CORS scenarios. As such, we only set \"no-cache\"\n // when there is no Authorization header.\n const cacheMode = \"Authorization\" in headers ? undefined : \"no-cache\";\n\n let res: Response;\n const start = Date.now();\n try {\n res = await this.fetch(url, {\n signal,\n method,\n body: data,\n headers,\n mode: \"cors\",\n redirect: \"follow\",\n referrer: \"\",\n referrerPolicy: \"no-referrer\",\n cache: cacheMode,\n credentials: \"omit\", // we send credentials via headers\n keepalive: keepAlive,\n priority: opts.priority,\n });\n\n this.opts.logger?.debug(\n `FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${res.status}]`,\n );\n } catch (e) {\n this.opts.logger?.debug(`FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${e}]`);\n if ((<Error>e).name === \"AbortError\") {\n throw e;\n }\n throw new ConnectionError(\"fetch failed\", <Error>e);\n } finally {\n cleanup();\n }\n\n if (!res.ok) {\n throw parseErrorResponse(res, await res.text());\n }\n\n if (opts.rawResponseBody) {\n return (await res.blob()) as T;\n } else if (jsonResponse) {\n return await res.json();\n } else {\n return (await res.text()) as T;\n }\n }\n\n private sanitizeUrlForLogs(url: URL | string): string {\n try {\n let asUrl: URL;\n if (typeof url === \"string\") {\n asUrl = new URL(url);\n } else {\n asUrl = url;\n }\n // Remove the values of any URL params that could contain potential secrets\n const sanitizedQs = new URLSearchParams();\n for (const key of asUrl.searchParams.keys()) {\n sanitizedQs.append(key, \"xxx\");\n }\n const sanitizedQsString = sanitizedQs.toString();\n const sanitizedQsUrlPiece = sanitizedQsString ? `?${sanitizedQsString}` : \"\";\n\n return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;\n } catch {\n // defensive coding for malformed url\n return \"??\";\n }\n }\n /**\n * Form and return a homeserver request URL based on the given path params and prefix.\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g. \"/createRoom\".\n * @param queryParams - A dict of query params (these will NOT be urlencoded).\n * @param prefix - The full prefix to use e.g. \"/_matrix/client/v2_alpha\", defaulting to this.opts.prefix.\n * @param baseUrl - The baseUrl to use e.g. \"https://matrix.org\", defaulting to this.opts.baseUrl.\n * @returns URL\n */\n public getUrl(path: string, queryParams?: QueryDict, prefix?: string, baseUrl?: string): URL {\n const baseUrlWithFallback = baseUrl ?? this.opts.baseUrl;\n const baseUrlWithoutTrailingSlash = baseUrlWithFallback.endsWith(\"/\")\n ? baseUrlWithFallback.slice(0, -1)\n : baseUrlWithFallback;\n const url = new URL(baseUrlWithoutTrailingSlash + (prefix ?? this.opts.prefix) + path);\n // If there are any params, encode and append them to the URL.\n if (this.opts.extraParams || queryParams) {\n const mergedParams = { ...this.opts.extraParams, ...queryParams };\n encodeParams(mergedParams, url.searchParams);\n }\n\n return url;\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,SAAS,kBAAkB,EAAE,QAAQ,EAAE,YAAY,QAAQ,aAAa;AAExE,SAAS,MAAM,QAAQ,aAAa;AACpC,SAAS,eAAe,EAAE,WA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AW,CAAE;MACjE,YAAY,CAAC,YAAY,EAAE,GAAG,CAAC,YAAY,CAAC;IAChD;IAEA,OAAO,GAAG;EACd;AACJ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"fetch.js","names":[],"sources":["../../src/http-api/fetch.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nimport { checkObjectHasKeys, deepCopy, encodeParams } from \"../utils.ts\";\nimport { type TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { Method } from \"./method.ts\";\nimport { ConnectionError, MatrixError, TokenRefreshError } from \"./errors.ts\";\nimport {\n type BaseRequestOpts,\n HttpApiEvent,\n type HttpApiEventHandlerMap,\n type IHttpOpts,\n type IRequestOpts,\n type Body,\n} from \"./interface.ts\";\nimport { anySignal, parseErrorResponse, timeoutSignal } from \"./utils.ts\";\nimport { sanitizeUrlForLogs } from \"./logging.ts\";\nimport { type QueryDict } from \"../utils.ts\";\nimport { TokenRefresher, TokenRefreshOutcome } from \"./refresh.ts\";\n\nexport class FetchHttpApi<O extends IHttpOpts> {\n private abortController = new AbortController();\n private readonly tokenRefresher: TokenRefresher;\n\n public constructor(\n private eventEmitter: TypedEventEmitter<HttpApiEvent, HttpApiEventHandlerMap>,\n public readonly opts: O,\n ) {\n checkObjectHasKeys(opts, [\"baseUrl\", \"prefix\"]);\n if (!opts.onlyData) {\n throw new Error(\"Constructing FetchHttpApi without `onlyData=true` is no longer supported.\");\n }\n opts.useAuthorizationHeader = opts.useAuthorizationHeader ?? true;\n\n this.tokenRefresher = new TokenRefresher(opts);\n }\n\n public abort(): void {\n this.abortController.abort();\n this.abortController = new AbortController();\n }\n\n public fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.opts.fetchFn) {\n return this.opts.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n /**\n * Sets the base URL for the identity server\n * @param url - The new base url\n */\n public setIdBaseUrl(url?: string): void {\n this.opts.idBaseUrl = url;\n }\n\n public idServerRequest<T extends object = Record<string, unknown>>(\n method: Method,\n path: string,\n params: Record<string, string | string[]> | undefined,\n prefix: string,\n accessToken?: string,\n ): Promise<T> {\n if (!this.opts.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n let queryParams: QueryDict | undefined = undefined;\n let body: Record<string, string | string[]> | undefined = undefined;\n if (method === Method.Get) {\n queryParams = params;\n } else {\n body = params;\n }\n\n const fullUri = this.getUrl(path, queryParams, prefix, this.opts.idBaseUrl);\n\n const opts: IRequestOpts = {\n json: true,\n headers: {},\n };\n if (accessToken) {\n opts.headers!.Authorization = `Bearer ${accessToken}`;\n }\n\n return this.requestOtherUrl(method, fullUri, body, opts);\n }\n\n /**\n * Perform an authorised request to the homeserver.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param paramOpts - additional options.\n * When `paramOpts.doNotAttemptTokenRefresh` is true, token refresh will not be attempted\n * when an expired token is encountered. Used to only attempt token refresh once.\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public authedRequest<T>(\n method: Method,\n path: string,\n queryParams: QueryDict = {},\n body?: Body,\n paramOpts: IRequestOpts = {},\n ): Promise<T> {\n return this.doAuthedRequest<T>(1, method, path, queryParams, body, paramOpts);\n }\n\n // Wrapper around public method authedRequest to allow for tracking retry attempt counts\n private async doAuthedRequest<T>(\n attempt: number,\n method: Method,\n path: string,\n queryParams: QueryDict,\n body?: Body,\n paramOpts: IRequestOpts = {},\n ): Promise<T> {\n // avoid mutating paramOpts so they can be used on retry\n const opts = deepCopy(paramOpts);\n // we have to manually copy the abortSignal over as it is not a plain object\n opts.abortSignal = paramOpts.abortSignal;\n\n // Take a snapshot of the current token state before we start the request so we can reference it if we error\n const requestSnapshot = await this.tokenRefresher.prepareForRequest();\n if (requestSnapshot.accessToken) {\n if (this.opts.useAuthorizationHeader) {\n if (!opts.headers) {\n opts.headers = {};\n }\n if (!opts.headers.Authorization) {\n opts.headers.Authorization = `Bearer ${requestSnapshot.accessToken}`;\n }\n if (queryParams.access_token) {\n delete queryParams.access_token;\n }\n } else if (!queryParams.access_token) {\n queryParams.access_token = requestSnapshot.accessToken;\n }\n }\n\n try {\n const response = await this.request<T>(method, path, queryParams, body, opts);\n return response;\n } catch (error) {\n if (!(error instanceof MatrixError)) {\n throw error;\n }\n\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n const outcome = await this.tokenRefresher.handleUnknownToken(requestSnapshot, attempt);\n if (outcome === TokenRefreshOutcome.Success) {\n // if we got a new token retry the request\n return this.doAuthedRequest(attempt + 1, method, path, queryParams, body, paramOpts);\n }\n if (outcome === TokenRefreshOutcome.Failure) {\n throw new TokenRefreshError(error);\n }\n\n if (!opts?.inhibitLogoutEmit) {\n this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, error);\n }\n } else if (error.errcode == \"M_CONSENT_NOT_GIVEN\") {\n this.eventEmitter.emit(HttpApiEvent.NoConsent, error.message, error.data.consent_uri);\n }\n\n throw error;\n }\n }\n\n /**\n * Perform a request to the homeserver without any credentials.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public request<T = unknown>(\n method: Method,\n path: string,\n queryParams?: QueryDict,\n body?: Body,\n opts?: IRequestOpts,\n ): Promise<T> {\n const fullUri = this.getUrl(path, queryParams, opts?.prefix, opts?.baseUrl);\n return this.requestOtherUrl<T>(method, fullUri, body, opts);\n }\n\n /**\n * Perform a request to an arbitrary URL.\n * @param method - The HTTP method e.g. \"GET\".\n * @param url - The HTTP URL object.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public async requestOtherUrl<T>(\n method: Method,\n url: URL | string,\n body?: Body,\n opts: BaseRequestOpts = {},\n ): Promise<T> {\n if (opts.json !== undefined && opts.rawResponseBody !== undefined) {\n throw new Error(\"Invalid call to `FetchHttpApi` sets both `opts.json` and `opts.rawResponseBody`\");\n }\n\n const urlForLogs = sanitizeUrlForLogs(url);\n\n this.opts.logger?.debug(`FetchHttpApi: --> ${method} ${urlForLogs}`);\n\n const headers = Object.assign({}, opts.headers || {});\n\n const jsonResponse = !opts.rawResponseBody && opts.json !== false;\n if (jsonResponse) {\n if (!headers[\"Accept\"]) {\n headers[\"Accept\"] = \"application/json\";\n }\n }\n\n const timeout = opts.localTimeoutMs ?? this.opts.localTimeoutMs;\n const keepAlive = opts.keepAlive ?? false;\n const signals = [this.abortController.signal];\n if (timeout !== undefined) {\n signals.push(timeoutSignal(timeout));\n }\n if (opts.abortSignal) {\n signals.push(opts.abortSignal);\n }\n\n // If the body is an object, encode it as JSON and set the `Content-Type` header,\n // unless that has been explicitly inhibited by setting `opts.json: false`.\n // We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref\n let data: BodyInit;\n if (opts.json !== false && body?.constructor?.name === Object.name) {\n data = JSON.stringify(body);\n if (!headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n } else {\n data = body as BodyInit;\n }\n\n const { signal, cleanup } = anySignal(signals);\n\n // Set cache mode based on presence of Authorization header.\n // Browsers/proxies do not cache responses to requests with Authorization headers.\n // So specifying \"no-cache\" is redundant, and actually prevents caching\n // of preflight requests in CORS scenarios. As such, we only set \"no-cache\"\n // when there is no Authorization header.\n const cacheMode = \"Authorization\" in headers ? undefined : \"no-cache\";\n\n let res: Response;\n const start = Date.now();\n try {\n res = await this.fetch(url, {\n signal,\n method,\n body: data,\n headers,\n mode: \"cors\",\n redirect: \"follow\",\n referrer: \"\",\n referrerPolicy: \"no-referrer\",\n cache: cacheMode,\n credentials: \"omit\", // we send credentials via headers\n keepalive: keepAlive,\n priority: opts.priority,\n });\n\n this.opts.logger?.debug(\n `FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${res.status}]`,\n );\n } catch (e) {\n this.opts.logger?.debug(`FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${e}]`);\n if ((<Error>e).name === \"AbortError\") {\n throw e;\n }\n throw new ConnectionError(\"fetch failed\", <Error>e);\n } finally {\n cleanup();\n }\n\n if (!res.ok) {\n throw parseErrorResponse(res, await res.text());\n }\n\n if (opts.rawResponseBody) {\n return (await res.blob()) as T;\n } else if (jsonResponse) {\n return await res.json();\n } else {\n return (await res.text()) as T;\n }\n }\n\n /**\n * Form and return a homeserver request URL based on the given path params and prefix.\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g. \"/createRoom\".\n * @param queryParams - A dict of query params (these will NOT be urlencoded).\n * @param prefix - The full prefix to use e.g. \"/_matrix/client/v2_alpha\", defaulting to this.opts.prefix.\n * @param baseUrl - The baseUrl to use e.g. \"https://matrix.org\", defaulting to this.opts.baseUrl.\n * @returns URL\n */\n public getUrl(path: string, queryParams?: QueryDict, prefix?: string, baseUrl?: string): URL {\n const baseUrlWithFallback = baseUrl ?? this.opts.baseUrl;\n const baseUrlWithoutTrailingSlash = baseUrlWithFallback.endsWith(\"/\")\n ? baseUrlWithFallback.slice(0, -1)\n : baseUrlWithFallback;\n const url = new URL(baseUrlWithoutTrailingSlash + (prefix ?? this.opts.prefix) + path);\n // If there are any params, encode and append them to the URL.\n if (this.opts.extraParams || queryParams) {\n const mergedParams = { ...this.opts.extraParams, ...queryParams };\n encodeParams(mergedParams, url.searchParams);\n }\n\n return url;\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,SAAS,kBAAkB,EAAE,QAAQ,EAAE,YAAY,QAAQ,aAAa;AAExE,SAAS,MAAM,QAAQ,aAAa;AACpC,SAAS,eAAe,EAAE,WAAW,EAAE,iBAAiB,QAAQ,aAAa;AAC7E,SAEI,YAAY,QAKT,gBAAgB;AACvB,SAAS,SAAS,EAAE,kBAAkB,EAAE,aAAa,QAAQ,YAAY;AACzE,SAAS,kBAAkB,QAAQ,cAAc;AAEjD,SAAS,cAAc,EAAE,mBAAmB,QAAQ,cAAc;AAElE,OAAO,MAAM,YAAY,CAAsB;EAIpC,WAAW,CACN,YAAqE,EAC7D,IAAO,EACzB;IAAA,yCANwB,IAAI,eAAe,CAAC,CAAC;IAAA;IAAA,KAInC,YAAqE,GAArE,YAAqE;IAAA,KAC7D,IAAO,GAAP,IAAO;IAEvB,kBAAkB,CAAC,IAAI,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAC/C,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE;MAChB,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC;IAChG;IACA,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAC,sBAAsB,IAAI,IAAI;IAEjE,IAAI,CAAC,cAAc,GAAG,IAAI,cAAc,CAAC,IAAI,CAAC;EAClD;EAEO,KAAK,GAAS;IACjB,IAAI,CAAC,eAAe,CAAC,KAA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10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Produce a version of the given URL which is safe to write to logs, by redacting the values of any query parameters,
|
|
3
|
+
* as they may contain secrets.
|
|
4
|
+
*
|
|
5
|
+
* @internal
|
|
6
|
+
* @param url - the URL to sanitize.
|
|
7
|
+
* @returns the sanitized URL, or `"??"` if the URL could not be parsed.
|
|
8
|
+
*/
|
|
9
|
+
export declare function sanitizeUrlForLogs(url: URL | string): string;
|
|
10
|
+
//# sourceMappingURL=logging.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logging.d.ts","sourceRoot":"","sources":["../../src/http-api/logging.ts"],"names":[],"mappings":"AAgBA;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,MAAM,CAqB5D"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2026 The Matrix.org Foundation C.I.C.
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Produce a version of the given URL which is safe to write to logs, by redacting the values of any query parameters,
|
|
19
|
+
* as they may contain secrets.
|
|
20
|
+
*
|
|
21
|
+
* @internal
|
|
22
|
+
* @param url - the URL to sanitize.
|
|
23
|
+
* @returns the sanitized URL, or `"??"` if the URL could not be parsed.
|
|
24
|
+
*/
|
|
25
|
+
export function sanitizeUrlForLogs(url) {
|
|
26
|
+
try {
|
|
27
|
+
let asUrl;
|
|
28
|
+
if (typeof url === "string") {
|
|
29
|
+
asUrl = new URL(url);
|
|
30
|
+
} else {
|
|
31
|
+
asUrl = url;
|
|
32
|
+
}
|
|
33
|
+
// Remove the values of any URL params that could contain potential secrets
|
|
34
|
+
const sanitizedQs = new URLSearchParams();
|
|
35
|
+
for (const key of asUrl.searchParams.keys()) {
|
|
36
|
+
sanitizedQs.append(key, "xxx");
|
|
37
|
+
}
|
|
38
|
+
const sanitizedQsString = sanitizedQs.toString();
|
|
39
|
+
const sanitizedQsUrlPiece = sanitizedQsString ? `?${sanitizedQsString}` : "";
|
|
40
|
+
return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;
|
|
41
|
+
} catch {
|
|
42
|
+
// defensive coding for malformed url
|
|
43
|
+
return "??";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=logging.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logging.js","names":[],"sources":["../../src/http-api/logging.ts"],"sourcesContent":["/*\nCopyright 2026 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Produce a version of the given URL which is safe to write to logs, by redacting the values of any query parameters,\n * as they may contain secrets.\n *\n * @internal\n * @param url - the URL to sanitize.\n * @returns the sanitized URL, or `\"??\"` if the URL could not be parsed.\n */\nexport function sanitizeUrlForLogs(url: URL | string): string {\n try {\n let asUrl: URL;\n if (typeof url === \"string\") {\n asUrl = new URL(url);\n } else {\n asUrl = url;\n }\n // Remove the values of any URL params that could contain potential secrets\n const sanitizedQs = new URLSearchParams();\n for (const key of asUrl.searchParams.keys()) {\n sanitizedQs.append(key, \"xxx\");\n }\n const sanitizedQsString = sanitizedQs.toString();\n const sanitizedQsUrlPiece = sanitizedQsString ? `?${sanitizedQsString}` : \"\";\n\n return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;\n } catch {\n // defensive coding for malformed url\n return \"??\";\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,kBAAkB,CAAC,GAAiB,EAAU;EAC1D,IAAI;IACA,IAAI,KAAU;IACd,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;MACzB,KAAK,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC;IACxB,CAAC,MAAM;MACH,KAAK,GAAG,GAAG;IACf;IACA;IACA,MAAM,WAAW,GAAG,IAAI,eAAe,CAAC,CAAC;IACzC,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,EAAE;MACzC,WAAW,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC;IAClC;IACA,MAAM,iBAAiB,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,mBAAmB,GAAG,iBAAiB,GAAG,IAAI,iBAAiB,EAAE,GAAG,EAAE;IAE5E,OAAO,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,QAAQ,GAAG,mBAAmB;EAC9D,CAAC,CAAC,MAAM;IACJ;IACA,OAAO,IAAI;EACf;AACJ","ignoreList":[]}
|
|
@@ -11,6 +11,11 @@ export declare function getEncryptionKeyMapKey(membership: CallMembershipIdentit
|
|
|
11
11
|
* @internal
|
|
12
12
|
*/
|
|
13
13
|
export interface IEncryptionManager {
|
|
14
|
+
/**
|
|
15
|
+
* Whether the key rotation is currently halted.
|
|
16
|
+
* @see EncryptionConfig.keyRotationParticipantLimit
|
|
17
|
+
*/
|
|
18
|
+
readonly isKeyRotationSuppressed: boolean;
|
|
14
19
|
/**
|
|
15
20
|
* Joins the encryption manager with the provided configuration.
|
|
16
21
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EncryptionManager.d.ts","sourceRoot":"","sources":["../../src/matrixrtc/EncryptionManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,KAAK,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,2BAA2B,GAAG,mBAAmB,CAEnG;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IAC/B;;;;;OAKG;IACH,IAAI,CAAC,UAAU,EAAE,gBAAgB,GAAG,SAAS,GAAG,IAAI,CAAC;IAErD;;OAEG;IACH,KAAK,IAAI,IAAI,CAAC;IAEd;;;;OAIG;IACH,mBAAmB,CAAC,cAAc,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;IAE5D;;;;OAIG;IACH,iBAAiB,IAAI,WAAW,CAC5B,mBAAmB,EACnB,aAAa,CAAC;QACV,GAAG,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;QAC7B,QAAQ,EAAE,MAAM,CAAC;QACjB,UAAU,EAAE,2BAA2B,CAAC;QACxC,kBAAkB,EAAE,MAAM,CAAC;KAC9B,CAAC,CACL,CAAC;CACL;AAED,MAAM,MAAM,2BAA2B,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,GAAG,UAAU,GAAG,UAAU,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"EncryptionManager.d.ts","sourceRoot":"","sources":["../../src/matrixrtc/EncryptionManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,KAAK,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,2BAA2B,GAAG,mBAAmB,CAEnG;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IAC/B;;;OAGG;IACH,QAAQ,CAAC,uBAAuB,EAAE,OAAO,CAAC;IAE1C;;;;;OAKG;IACH,IAAI,CAAC,UAAU,EAAE,gBAAgB,GAAG,SAAS,GAAG,IAAI,CAAC;IAErD;;OAEG;IACH,KAAK,IAAI,IAAI,CAAC;IAEd;;;;OAIG;IACH,mBAAmB,CAAC,cAAc,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;IAE5D;;;;OAIG;IACH,iBAAiB,IAAI,WAAW,CAC5B,mBAAmB,EACnB,aAAa,CAAC;QACV,GAAG,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;QAC7B,QAAQ,EAAE,MAAM,CAAC;QACjB,UAAU,EAAE,2BAA2B,CAAC;QACxC,kBAAkB,EAAE,MAAM,CAAC;KAC9B,CAAC,CACL,CAAC;CACL;AAED,MAAM,MAAM,2BAA2B,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,GAAG,UAAU,GAAG,UAAU,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EncryptionManager.js","names":[],"sources":["../../src/matrixrtc/EncryptionManager.ts"],"sourcesContent":["import { type EncryptionConfig } from \"./MatrixRTCSession.ts\";\nimport { type CallMembership } from \"./CallMembership.ts\";\nimport { type EncryptionKeyMapKey } from \"./types.ts\";\n\n/**\n * The string used for the keys in the the encryption key map.\n * `@bob:examle.org:DEVICEID(UUIDRANDOM_MEMBERID_RANDOMUUID)`\n */\nexport function getEncryptionKeyMapKey(membership: CallMembershipIdentityParts): EncryptionKeyMapKey {\n return `${membership.userId}:${membership.deviceId}(${membership.memberId})`;\n}\n\n/**\n * This interface is for testing and for making it possible to interchange the encryption manager.\n * @internal\n */\nexport interface IEncryptionManager {\n /**\n * Joins the encryption manager with the provided configuration.\n *\n * @param joinConfig - The configuration for joining encryption, or undefined\n * if no specific configuration is provided.\n */\n join(joinConfig: EncryptionConfig | undefined): void;\n\n /**\n * Leaves the encryption manager, cleaning up any associated resources.\n */\n leave(): void;\n\n /**\n * Called from the MatrixRTCSession when the memberships in this session updated.\n *\n * @param oldMemberships - The previous state of call memberships before the update.\n */\n onMembershipsUpdate(oldMemberships: CallMembership[]): void;\n\n /**\n * Retrieves the encryption keys currently managed by the encryption manager.\n *\n * @returns A map of participant IDs to their encryption keys.\n */\n getEncryptionKeys(): ReadonlyMap<\n EncryptionKeyMapKey,\n ReadonlyArray<{\n key: Uint8Array<ArrayBuffer>;\n keyIndex: number;\n membership: CallMembershipIdentityParts;\n rtcBackendIdentity: string;\n }>\n >;\n}\n\nexport type CallMembershipIdentityParts = Pick<CallMembership, \"userId\" | \"deviceId\" | \"memberId\">;\n"],"mappings":"AAIA;AACA;AACA;AACA;AACA,OAAO,SAAS,sBAAsB,CAAC,UAAuC,EAAuB;EACjG,OAAO,GAAG,UAAU,CAAC,MAAM,IAAI,UAAU,CAAC,QAAQ,IAAI,UAAU,CAAC,QAAQ,GAAG;AAChF;;AAEA;AACA;AACA;AACA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"EncryptionManager.js","names":[],"sources":["../../src/matrixrtc/EncryptionManager.ts"],"sourcesContent":["import { type EncryptionConfig } from \"./MatrixRTCSession.ts\";\nimport { type CallMembership } from \"./CallMembership.ts\";\nimport { type EncryptionKeyMapKey } from \"./types.ts\";\n\n/**\n * The string used for the keys in the the encryption key map.\n * `@bob:examle.org:DEVICEID(UUIDRANDOM_MEMBERID_RANDOMUUID)`\n */\nexport function getEncryptionKeyMapKey(membership: CallMembershipIdentityParts): EncryptionKeyMapKey {\n return `${membership.userId}:${membership.deviceId}(${membership.memberId})`;\n}\n\n/**\n * This interface is for testing and for making it possible to interchange the encryption manager.\n * @internal\n */\nexport interface IEncryptionManager {\n /**\n * Whether the key rotation is currently halted.\n * @see EncryptionConfig.keyRotationParticipantLimit\n */\n readonly isKeyRotationSuppressed: boolean;\n\n /**\n * Joins the encryption manager with the provided configuration.\n *\n * @param joinConfig - The configuration for joining encryption, or undefined\n * if no specific configuration is provided.\n */\n join(joinConfig: EncryptionConfig | undefined): void;\n\n /**\n * Leaves the encryption manager, cleaning up any associated resources.\n */\n leave(): void;\n\n /**\n * Called from the MatrixRTCSession when the memberships in this session updated.\n *\n * @param oldMemberships - The previous state of call memberships before the update.\n */\n onMembershipsUpdate(oldMemberships: CallMembership[]): void;\n\n /**\n * Retrieves the encryption keys currently managed by the encryption manager.\n *\n * @returns A map of participant IDs to their encryption keys.\n */\n getEncryptionKeys(): ReadonlyMap<\n EncryptionKeyMapKey,\n ReadonlyArray<{\n key: Uint8Array<ArrayBuffer>;\n keyIndex: number;\n membership: CallMembershipIdentityParts;\n rtcBackendIdentity: string;\n }>\n >;\n}\n\nexport type CallMembershipIdentityParts = Pick<CallMembership, \"userId\" | \"deviceId\" | \"memberId\">;\n"],"mappings":"AAIA;AACA;AACA;AACA;AACA,OAAO,SAAS,sBAAsB,CAAC,UAAuC,EAAuB;EACjG,OAAO,GAAG,UAAU,CAAC,MAAM,IAAI,UAAU,CAAC,QAAQ,IAAI,UAAU,CAAC,QAAQ,GAAG;AAChF;;AAEA;AACA;AACA;AACA","ignoreList":[]}
|