matrix-js-sdk 41.6.0 → 41.7.0-rc.2
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/lib/ReEmitter.js +1 -1
- package/lib/ReEmitter.js.map +1 -1
- package/lib/ToDeviceMessageQueue.js +2 -2
- package/lib/ToDeviceMessageQueue.js.map +1 -1
- package/lib/autodiscovery.js +1 -0
- package/lib/autodiscovery.js.map +1 -1
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +77 -3
- package/lib/client.js.map +1 -1
- package/lib/common-crypto/CryptoBackend.js +2 -0
- package/lib/common-crypto/CryptoBackend.js.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store-backend.js +1 -1
- package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store.js +2 -0
- package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
- package/lib/crypto-api/index.js +58 -58
- package/lib/crypto-api/index.js.map +1 -1
- package/lib/embedded.js +13 -9
- package/lib/embedded.js.map +1 -1
- package/lib/extensible_events_v1/MessageEvent.js +15 -15
- package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollEndEvent.js +8 -8
- package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollResponseEvent.js +1 -0
- package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollStartEvent.js +28 -28
- package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
- package/lib/filter.js +3 -1
- package/lib/filter.js.map +1 -1
- package/lib/http-api/errors.js +16 -16
- package/lib/http-api/errors.js.map +1 -1
- package/lib/http-api/fetch.js +2 -1
- package/lib/http-api/fetch.js.map +1 -1
- package/lib/http-api/refresh.js +7 -6
- package/lib/http-api/refresh.js.map +1 -1
- package/lib/http-api/utils.d.ts.map +1 -1
- package/lib/http-api/utils.js +1 -5
- package/lib/http-api/utils.js.map +1 -1
- package/lib/interactive-auth.js +11 -1
- package/lib/interactive-auth.js.map +1 -1
- package/lib/logger.js +2 -0
- package/lib/logger.js.map +1 -1
- package/lib/matrixrtc/CallMembership.js +6 -5
- package/lib/matrixrtc/CallMembership.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.js +15 -5
- package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSessionManager.js +3 -2
- package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
- package/lib/matrixrtc/MembershipManager.js +24 -17
- package/lib/matrixrtc/MembershipManager.js.map +1 -1
- package/lib/matrixrtc/MembershipManagerActionScheduler.js +2 -1
- package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
- package/lib/matrixrtc/RTCEncryptionManager.js +6 -4
- package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
- package/lib/matrixrtc/ToDeviceKeyTransport.js +4 -4
- package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
- package/lib/models/MSC3089TreeSpace.js +2 -1
- package/lib/models/MSC3089TreeSpace.js.map +1 -1
- package/lib/models/beacon.js +8 -4
- package/lib/models/beacon.js.map +1 -1
- package/lib/models/device.js +7 -0
- package/lib/models/device.js.map +1 -1
- package/lib/models/event-context.js +2 -1
- package/lib/models/event-context.js.map +1 -1
- package/lib/models/event-timeline-set.js +7 -1
- package/lib/models/event-timeline-set.js.map +1 -1
- package/lib/models/event-timeline.js +5 -1
- package/lib/models/event-timeline.js.map +1 -1
- package/lib/models/event.js +35 -11
- package/lib/models/event.js.map +1 -1
- package/lib/models/poll.js +7 -3
- package/lib/models/poll.js.map +1 -1
- package/lib/models/related-relations.js +2 -0
- package/lib/models/related-relations.js.map +1 -1
- package/lib/models/relations-container.js +2 -2
- package/lib/models/relations-container.js.map +1 -1
- package/lib/models/relations.js +4 -3
- package/lib/models/relations.js.map +1 -1
- package/lib/models/room-member.js +24 -2
- package/lib/models/room-member.js.map +1 -1
- package/lib/models/room-receipts.js +19 -12
- package/lib/models/room-receipts.js.map +1 -1
- package/lib/models/room-state.js +2 -2
- package/lib/models/room-state.js.map +1 -1
- package/lib/models/room-sticky-events.js +1 -0
- package/lib/models/room-sticky-events.js.map +1 -1
- package/lib/models/room.js +35 -4
- package/lib/models/room.js.map +1 -1
- package/lib/models/thread.js +46 -2
- package/lib/models/thread.js.map +1 -1
- package/lib/models/user.js +20 -1
- package/lib/models/user.js.map +1 -1
- package/lib/oidc/tokenRefresher.js +11 -8
- package/lib/oidc/tokenRefresher.js.map +1 -1
- package/lib/pushprocessor.js +1 -1
- package/lib/pushprocessor.js.map +1 -1
- package/lib/rendezvous/MSC4108SignInWithQR.js +6 -1
- package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
- package/lib/rendezvous/channels/MSC4108SecureChannel.js +3 -1
- package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
- package/lib/rendezvous/transports/MSC4108RendezvousSession.js +8 -0
- package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
- package/lib/room-hierarchy.js +8 -4
- package/lib/room-hierarchy.js.map +1 -1
- package/lib/rust-crypto/DehydratedDeviceManager.js +3 -2
- package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
- package/lib/rust-crypto/KeyClaimManager.js +2 -1
- package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
- package/lib/rust-crypto/OutgoingRequestsManager.js +12 -12
- package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +5 -3
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
- package/lib/rust-crypto/RoomEncryptor.js +6 -6
- package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
- package/lib/rust-crypto/backup.js +6 -4
- package/lib/rust-crypto/backup.js.map +1 -1
- package/lib/rust-crypto/rust-crypto.js +18 -10
- package/lib/rust-crypto/rust-crypto.js.map +1 -1
- package/lib/rust-crypto/verification.js +9 -7
- package/lib/rust-crypto/verification.js.map +1 -1
- package/lib/scheduler.js +2 -2
- package/lib/scheduler.js.map +1 -1
- package/lib/serverCapabilities.js +5 -2
- package/lib/serverCapabilities.js.map +1 -1
- package/lib/sliding-sync-sdk.js +6 -3
- package/lib/sliding-sync-sdk.js.map +1 -1
- package/lib/sliding-sync.js +9 -4
- package/lib/sliding-sync.js.map +1 -1
- package/lib/store/indexeddb-local-backend.js +5 -1
- package/lib/store/indexeddb-local-backend.js.map +1 -1
- package/lib/store/indexeddb-remote-backend.js +7 -6
- package/lib/store/indexeddb-remote-backend.js.map +1 -1
- package/lib/store/indexeddb-store-worker.js +2 -1
- package/lib/store/indexeddb-store-worker.js.map +1 -1
- package/lib/store/indexeddb.js +1 -0
- package/lib/store/indexeddb.js.map +1 -1
- package/lib/store/memory.js +4 -0
- package/lib/store/memory.js.map +1 -1
- package/lib/sync-accumulator.js +1 -1
- package/lib/sync-accumulator.js.map +1 -1
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +32 -16
- package/lib/sync.js.map +1 -1
- package/lib/timeline-window.js +6 -2
- package/lib/timeline-window.js.map +1 -1
- package/lib/webrtc/call.js +42 -6
- package/lib/webrtc/call.js.map +1 -1
- package/lib/webrtc/callEventHandler.js +5 -0
- package/lib/webrtc/callEventHandler.js.map +1 -1
- package/lib/webrtc/callFeed.js +15 -0
- package/lib/webrtc/callFeed.js.map +1 -1
- package/lib/webrtc/groupCall.js +24 -8
- package/lib/webrtc/groupCall.js.map +1 -1
- package/lib/webrtc/groupCallEventHandler.js +1 -1
- package/lib/webrtc/groupCallEventHandler.js.map +1 -1
- package/lib/webrtc/mediaHandler.js +7 -3
- package/lib/webrtc/mediaHandler.js.map +1 -1
- package/lib/webrtc/stats/callStatsReportGatherer.js +5 -2
- package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
- package/lib/webrtc/stats/groupCallStats.js +4 -3
- package/lib/webrtc/stats/groupCallStats.js.map +1 -1
- package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
- package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
- package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +1 -1
- package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
- package/package.json +125 -138
- package/src/client.ts +4 -1
- package/src/http-api/utils.ts +4 -9
- package/src/matrixrtc/MatrixRTCSession.ts +4 -3
- package/src/sync.ts +5 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MSC4108SecureChannel.js","names":["Ecies","QrCodeData","QrCodeIntent","ClientRendezvousFailureReason","MSC4108FailureReason","RendezvousError","logger","MSC4108SecureChannel","constructor","rendezvousSession","theirPublicKey","onFailure","_defineProperty","secureChannel","generateCode","mode","serverName","_this","_asyncToGenerator","url","Error","public_key","Reciprocate","undefined","toBytes","getCheckCode","_this$establishedChan","x","establishedChannel","check_code","Array","from","as_bytes","map","b","concat","join","connect","_this2","connected","result","establish_outbound_channel","channel","info","send","initial_message","ciphertext","receive","UnexpectedMessageReceived","candidateLoginOkMessage","decrypt","InsecureChannelDetected","loginInitiateMessage","_this2$secureChannel$","establish_inbound_channel","candidateLoginInitiateMessage","message","loginOkMessage","encrypt","_this3","plaintext","_this4","secureSend","payload","_this5","stringifiedPayload","JSON","stringify","debug","type","secureReceive","_this6","json","parse","close","_this7","cancel","reason","_this8","_this8$onFailure","call","UserDeclined","UserCancelled","cancelled"],"sources":["../../../src/rendezvous/channels/MSC4108SecureChannel.ts"],"sourcesContent":["/*\nCopyright 2024 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 Curve25519PublicKey,\n Ecies,\n type EstablishedEcies,\n QrCodeData,\n QrCodeIntent,\n} from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport {\n ClientRendezvousFailureReason,\n MSC4108FailureReason,\n type MSC4108Payload,\n RendezvousError,\n type RendezvousFailureListener,\n} from \"../index.ts\";\nimport { type MSC4108RendezvousSession } from \"../transports/MSC4108RendezvousSession.ts\";\nimport { logger } from \"../../logger.ts\";\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * secure rendezvous session protocol.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n * Imports @matrix-org/matrix-sdk-crypto-wasm so should be async-imported to avoid bundling the WASM into the main bundle.\n */\nexport class MSC4108SecureChannel {\n private readonly secureChannel: Ecies;\n private establishedChannel?: EstablishedEcies;\n private connected = false;\n\n public constructor(\n private rendezvousSession: MSC4108RendezvousSession,\n private theirPublicKey?: Curve25519PublicKey,\n public onFailure?: RendezvousFailureListener,\n ) {\n this.secureChannel = new Ecies();\n }\n\n /**\n * Generate a QR code for the current session.\n * @param mode the mode to generate the QR code in, either `Login` or `Reciprocate`.\n * @param serverName the name of the homeserver to connect to, as defined by server discovery in the spec, required for `Reciprocate` mode.\n */\n public async generateCode(mode: QrCodeIntent.Login): Promise<Uint8Array>;\n public async generateCode(mode: QrCodeIntent.Reciprocate, serverName: string): Promise<Uint8Array>;\n public async generateCode(mode: QrCodeIntent, serverName?: string): Promise<Uint8Array> {\n const { url } = this.rendezvousSession;\n\n if (!url) {\n throw new Error(\"No rendezvous session URL\");\n }\n\n return new QrCodeData(\n this.secureChannel.public_key(),\n url,\n mode === QrCodeIntent.Reciprocate ? serverName : undefined,\n ).toBytes();\n }\n\n /**\n * Returns the check code for the secure channel or undefined if not generated yet.\n */\n public getCheckCode(): string | undefined {\n const x = this.establishedChannel?.check_code();\n\n if (!x) {\n return undefined;\n }\n return Array.from(x.as_bytes())\n .map((b) => `${b % 10}`)\n .join(\"\");\n }\n\n /**\n * Connects and establishes a secure channel with the other device.\n */\n public async connect(): Promise<void> {\n if (this.connected) {\n throw new Error(\"Channel already connected\");\n }\n\n if (this.theirPublicKey) {\n // We are the scanning device\n const result = this.secureChannel.establish_outbound_channel(\n this.theirPublicKey,\n \"MATRIX_QR_CODE_LOGIN_INITIATE\",\n );\n this.establishedChannel = result.channel;\n\n /*\n Secure Channel step 4. Device S sends the initial message\n\n Nonce := 0\n SH := ECDH(Ss, Gp)\n EncKey := HKDF_SHA256(SH, \"MATRIX_QR_CODE_LOGIN|\" || Gp || \"|\" || Sp, 0, 32)\n TaggedCiphertext := ChaCha20Poly1305_Encrypt(EncKey, Nonce, \"MATRIX_QR_CODE_LOGIN_INITIATE\")\n Nonce := Nonce + 2\n LoginInitiateMessage := UnpaddedBase64(TaggedCiphertext) || \"|\" || UnpaddedBase64(Sp)\n */\n {\n logger.info(\"Sending LoginInitiateMessage\");\n await this.rendezvousSession.send(result.initial_message);\n }\n\n /*\n Secure Channel step 6. Verification by Device S\n\n Nonce_G := 1\n (TaggedCiphertext, Sp) := Unpack(Message)\n Plaintext := ChaCha20Poly1305_Decrypt(EncKey, Nonce_G, TaggedCiphertext)\n Nonce_G := Nonce_G + 2\n\n unless Plaintext == \"MATRIX_QR_CODE_LOGIN_OK\":\n FAIL\n */\n {\n logger.info(\"Waiting for LoginOkMessage\");\n const ciphertext = await this.rendezvousSession.receive();\n\n if (!ciphertext) {\n throw new RendezvousError(\n \"No response from other device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n const candidateLoginOkMessage = await this.decrypt(ciphertext);\n\n if (candidateLoginOkMessage !== \"MATRIX_QR_CODE_LOGIN_OK\") {\n throw new RendezvousError(\n \"Invalid response from other device\",\n ClientRendezvousFailureReason.InsecureChannelDetected,\n );\n }\n\n // Step 6 is now complete. We trust the channel\n }\n } else {\n /*\n Secure Channel step 5. Device G confirms\n\n Nonce_S := 0\n (TaggedCiphertext, Sp) := Unpack(LoginInitiateMessage)\n SH := ECDH(Gs, Sp)\n EncKey := HKDF_SHA256(SH, \"MATRIX_QR_CODE_LOGIN|\" || Gp || \"|\" || Sp, 0, 32)\n Plaintext := ChaCha20Poly1305_Decrypt(EncKey, Nonce_S, TaggedCiphertext)\n Nonce_S := Nonce_S + 2\n */\n // wait for the other side to send us their public key\n logger.info(\"Waiting for LoginInitiateMessage\");\n const loginInitiateMessage = await this.rendezvousSession.receive();\n if (!loginInitiateMessage) {\n throw new RendezvousError(\n \"No response from other device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n const { channel, message: candidateLoginInitiateMessage } =\n this.secureChannel.establish_inbound_channel(loginInitiateMessage);\n this.establishedChannel = channel;\n\n if (candidateLoginInitiateMessage !== \"MATRIX_QR_CODE_LOGIN_INITIATE\") {\n throw new RendezvousError(\n \"Invalid response from other device\",\n ClientRendezvousFailureReason.InsecureChannelDetected,\n );\n }\n logger.info(\"LoginInitiateMessage received\");\n\n logger.info(\"Sending LoginOkMessage\");\n const loginOkMessage = await this.encrypt(\"MATRIX_QR_CODE_LOGIN_OK\");\n await this.rendezvousSession.send(loginOkMessage);\n\n // Step 5 is complete. We don't yet trust the channel\n\n // next step will be for the user to confirm the check code on the other device\n }\n\n this.connected = true;\n }\n\n private async decrypt(ciphertext: string): Promise<string> {\n if (!this.establishedChannel) {\n throw new Error(\"Channel closed\");\n }\n\n return this.establishedChannel.decrypt(ciphertext);\n }\n\n private async encrypt(plaintext: string): Promise<string> {\n if (!this.establishedChannel) {\n throw new Error(\"Channel closed\");\n }\n\n return this.establishedChannel.encrypt(plaintext);\n }\n\n /**\n * Sends a payload securely to the other device.\n * @param payload the payload to encrypt and send\n */\n public async secureSend<T extends MSC4108Payload>(payload: T): Promise<void> {\n if (!this.connected) {\n throw new Error(\"Channel closed\");\n }\n\n const stringifiedPayload = JSON.stringify(payload);\n logger.debug(`=> {\"type\": ${JSON.stringify(payload.type)}, ...}`);\n\n await this.rendezvousSession.send(await this.encrypt(stringifiedPayload));\n }\n\n /**\n * Receives an encrypted payload from the other device and decrypts it.\n */\n public async secureReceive<T extends MSC4108Payload>(): Promise<Partial<T> | undefined> {\n if (!this.establishedChannel) {\n throw new Error(\"Channel closed\");\n }\n\n const ciphertext = await this.rendezvousSession.receive();\n if (!ciphertext) {\n return undefined;\n }\n const plaintext = await this.decrypt(ciphertext);\n const json = JSON.parse(plaintext);\n\n logger.debug(`<= {\"type\": ${JSON.stringify(json.type)}, ...}`);\n return json as Partial<T> | undefined;\n }\n\n /**\n * Closes the secure channel.\n */\n public async close(): Promise<void> {\n await this.rendezvousSession.close();\n }\n\n /**\n * Cancels the secure channel.\n * @param reason the reason for the cancellation\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n try {\n await this.rendezvousSession.cancel(reason);\n this.onFailure?.(reason);\n } finally {\n if (\n reason !== ClientRendezvousFailureReason.UserDeclined &&\n reason !== MSC4108FailureReason.UserCancelled\n ) {\n await this.close();\n }\n }\n }\n\n /**\n * Returns whether the rendezvous session has been cancelled.\n */\n public get cancelled(): boolean {\n return this.rendezvousSession.cancelled;\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAEIA,KAAK,EAELC,UAAU,EACVC,YAAY,QACT,oCAAoC;AAE3C,SACIC,6BAA6B,EAC7BC,oBAAoB,EAEpBC,eAAe,QAEZ,aAAa;AAEpB,SAASC,MAAM,QAAQ,iBAAiB;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,oBAAoB,CAAC;EAKvBC,WAAWA,CACNC,iBAA2C,EAC3CC,cAAoC,EACrCC,SAAqC,EAC9C;IAAAC,eAAA,oBANkB,KAAK;IAAA,KAGbH,iBAA2C,GAA3CA,iBAA2C;IAAA,KAC3CC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ACA,MAAMD,MAAI,CAACrE,iBAAiB,CAACmE,MAAM,CAACC,MAAM,CAAC;QAC3C,CAAAE,gBAAA,GAAAD,MAAI,CAACnE,SAAS,cAAAoE,gBAAA,eAAdA,gBAAA,CAAAC,IAAA,CAAAF,MAAI,EAAaD,MAAM,CAAC;MAC5B,CAAC,SAAS;QACN,IACIA,MAAM,KAAK1E,6BAA6B,CAAC8E,YAAY,IACrDJ,MAAM,KAAKzE,oBAAoB,CAAC8E,aAAa,EAC/C;UACE,MAAMJ,MAAI,CAACJ,KAAK,CAAC,CAAC;QACtB;MACJ;IAAC;EACL;;EAEA;AACJ;AACA;EACI,IAAWS,SAASA,CAAA,EAAY;IAC5B,OAAO,IAAI,CAAC1E,iBAAiB,CAAC0E,SAAS;EAC3C;AACJ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"MSC4108SecureChannel.js","names":["Ecies","QrCodeData","QrCodeIntent","ClientRendezvousFailureReason","MSC4108FailureReason","RendezvousError","logger","MSC4108SecureChannel","constructor","rendezvousSession","theirPublicKey","onFailure","_defineProperty","secureChannel","generateCode","mode","serverName","_this","_asyncToGenerator","url","Error","public_key","Reciprocate","undefined","toBytes","getCheckCode","_this$establishedChan","x","establishedChannel","check_code","Array","from","as_bytes","map","b","concat","join","connect","_this2","connected","result","establish_outbound_channel","channel","info","send","initial_message","ciphertext","receive","UnexpectedMessageReceived","candidateLoginOkMessage","decrypt","InsecureChannelDetected","loginInitiateMessage","_this2$secureChannel$","establish_inbound_channel","candidateLoginInitiateMessage","message","loginOkMessage","encrypt","_this3","plaintext","_this4","secureSend","payload","_this5","stringifiedPayload","JSON","stringify","debug","type","secureReceive","_this6","json","parse","close","_this7","cancel","reason","_this8","_this8$onFailure","call","UserDeclined","UserCancelled","cancelled"],"sources":["../../../src/rendezvous/channels/MSC4108SecureChannel.ts"],"sourcesContent":["/*\nCopyright 2024 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 Curve25519PublicKey,\n Ecies,\n type EstablishedEcies,\n QrCodeData,\n QrCodeIntent,\n} from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport {\n ClientRendezvousFailureReason,\n MSC4108FailureReason,\n type MSC4108Payload,\n RendezvousError,\n type RendezvousFailureListener,\n} from \"../index.ts\";\nimport { type MSC4108RendezvousSession } from \"../transports/MSC4108RendezvousSession.ts\";\nimport { logger } from \"../../logger.ts\";\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * secure rendezvous session protocol.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n * Imports @matrix-org/matrix-sdk-crypto-wasm so should be async-imported to avoid bundling the WASM into the main bundle.\n */\nexport class MSC4108SecureChannel {\n private readonly secureChannel: Ecies;\n private establishedChannel?: EstablishedEcies;\n private connected = false;\n\n public constructor(\n private rendezvousSession: MSC4108RendezvousSession,\n private theirPublicKey?: Curve25519PublicKey,\n public onFailure?: RendezvousFailureListener,\n ) {\n this.secureChannel = new Ecies();\n }\n\n /**\n * Generate a QR code for the current session.\n * @param mode the mode to generate the QR code in, either `Login` or `Reciprocate`.\n * @param serverName the name of the homeserver to connect to, as defined by server discovery in the spec, required for `Reciprocate` mode.\n */\n public async generateCode(mode: QrCodeIntent.Login): Promise<Uint8Array>;\n public async generateCode(mode: QrCodeIntent.Reciprocate, serverName: string): Promise<Uint8Array>;\n public async generateCode(mode: QrCodeIntent, serverName?: string): Promise<Uint8Array> {\n const { url } = this.rendezvousSession;\n\n if (!url) {\n throw new Error(\"No rendezvous session URL\");\n }\n\n return new QrCodeData(\n this.secureChannel.public_key(),\n url,\n mode === QrCodeIntent.Reciprocate ? serverName : undefined,\n ).toBytes();\n }\n\n /**\n * Returns the check code for the secure channel or undefined if not generated yet.\n */\n public getCheckCode(): string | undefined {\n const x = this.establishedChannel?.check_code();\n\n if (!x) {\n return undefined;\n }\n return Array.from(x.as_bytes())\n .map((b) => `${b % 10}`)\n .join(\"\");\n }\n\n /**\n * Connects and establishes a secure channel with the other device.\n */\n public async connect(): Promise<void> {\n if (this.connected) {\n throw new Error(\"Channel already connected\");\n }\n\n if (this.theirPublicKey) {\n // We are the scanning device\n const result = this.secureChannel.establish_outbound_channel(\n this.theirPublicKey,\n \"MATRIX_QR_CODE_LOGIN_INITIATE\",\n );\n this.establishedChannel = result.channel;\n\n /*\n Secure Channel step 4. Device S sends the initial message\n\n Nonce := 0\n SH := ECDH(Ss, Gp)\n EncKey := HKDF_SHA256(SH, \"MATRIX_QR_CODE_LOGIN|\" || Gp || \"|\" || Sp, 0, 32)\n TaggedCiphertext := ChaCha20Poly1305_Encrypt(EncKey, Nonce, \"MATRIX_QR_CODE_LOGIN_INITIATE\")\n Nonce := Nonce + 2\n LoginInitiateMessage := UnpaddedBase64(TaggedCiphertext) || \"|\" || UnpaddedBase64(Sp)\n */\n {\n logger.info(\"Sending LoginInitiateMessage\");\n await this.rendezvousSession.send(result.initial_message);\n }\n\n /*\n Secure Channel step 6. Verification by Device S\n\n Nonce_G := 1\n (TaggedCiphertext, Sp) := Unpack(Message)\n Plaintext := ChaCha20Poly1305_Decrypt(EncKey, Nonce_G, TaggedCiphertext)\n Nonce_G := Nonce_G + 2\n\n unless Plaintext == \"MATRIX_QR_CODE_LOGIN_OK\":\n FAIL\n */\n {\n logger.info(\"Waiting for LoginOkMessage\");\n const ciphertext = await this.rendezvousSession.receive();\n\n if (!ciphertext) {\n throw new RendezvousError(\n \"No response from other device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n const candidateLoginOkMessage = await this.decrypt(ciphertext);\n\n if (candidateLoginOkMessage !== \"MATRIX_QR_CODE_LOGIN_OK\") {\n throw new RendezvousError(\n \"Invalid response from other device\",\n ClientRendezvousFailureReason.InsecureChannelDetected,\n );\n }\n\n // Step 6 is now complete. We trust the channel\n }\n } else {\n /*\n Secure Channel step 5. Device G confirms\n\n Nonce_S := 0\n (TaggedCiphertext, Sp) := Unpack(LoginInitiateMessage)\n SH := ECDH(Gs, Sp)\n EncKey := HKDF_SHA256(SH, \"MATRIX_QR_CODE_LOGIN|\" || Gp || \"|\" || Sp, 0, 32)\n Plaintext := ChaCha20Poly1305_Decrypt(EncKey, Nonce_S, TaggedCiphertext)\n Nonce_S := Nonce_S + 2\n */\n // wait for the other side to send us their public key\n logger.info(\"Waiting for LoginInitiateMessage\");\n const loginInitiateMessage = await this.rendezvousSession.receive();\n if (!loginInitiateMessage) {\n throw new RendezvousError(\n \"No response from other device\",\n MSC4108FailureReason.UnexpectedMessageReceived,\n );\n }\n\n const { channel, message: candidateLoginInitiateMessage } =\n this.secureChannel.establish_inbound_channel(loginInitiateMessage);\n this.establishedChannel = channel;\n\n if (candidateLoginInitiateMessage !== \"MATRIX_QR_CODE_LOGIN_INITIATE\") {\n throw new RendezvousError(\n \"Invalid response from other device\",\n ClientRendezvousFailureReason.InsecureChannelDetected,\n );\n }\n logger.info(\"LoginInitiateMessage received\");\n\n logger.info(\"Sending LoginOkMessage\");\n const loginOkMessage = await this.encrypt(\"MATRIX_QR_CODE_LOGIN_OK\");\n await this.rendezvousSession.send(loginOkMessage);\n\n // Step 5 is complete. We don't yet trust the channel\n\n // next step will be for the user to confirm the check code on the other device\n }\n\n this.connected = true;\n }\n\n private async decrypt(ciphertext: string): Promise<string> {\n if (!this.establishedChannel) {\n throw new Error(\"Channel closed\");\n }\n\n return this.establishedChannel.decrypt(ciphertext);\n }\n\n private async encrypt(plaintext: string): Promise<string> {\n if (!this.establishedChannel) {\n throw new Error(\"Channel closed\");\n }\n\n return this.establishedChannel.encrypt(plaintext);\n }\n\n /**\n * Sends a payload securely to the other device.\n * @param payload the payload to encrypt and send\n */\n public async secureSend<T extends MSC4108Payload>(payload: T): Promise<void> {\n if (!this.connected) {\n throw new Error(\"Channel closed\");\n }\n\n const stringifiedPayload = JSON.stringify(payload);\n logger.debug(`=> {\"type\": ${JSON.stringify(payload.type)}, ...}`);\n\n await this.rendezvousSession.send(await this.encrypt(stringifiedPayload));\n }\n\n /**\n * Receives an encrypted payload from the other device and decrypts it.\n */\n public async secureReceive<T extends MSC4108Payload>(): Promise<Partial<T> | undefined> {\n if (!this.establishedChannel) {\n throw new Error(\"Channel closed\");\n }\n\n const ciphertext = await this.rendezvousSession.receive();\n if (!ciphertext) {\n return undefined;\n }\n const plaintext = await this.decrypt(ciphertext);\n const json = JSON.parse(plaintext);\n\n logger.debug(`<= {\"type\": ${JSON.stringify(json.type)}, ...}`);\n return json as Partial<T> | undefined;\n }\n\n /**\n * Closes the secure channel.\n */\n public async close(): Promise<void> {\n await this.rendezvousSession.close();\n }\n\n /**\n * Cancels the secure channel.\n * @param reason the reason for the cancellation\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n try {\n await this.rendezvousSession.cancel(reason);\n this.onFailure?.(reason);\n } finally {\n if (\n reason !== ClientRendezvousFailureReason.UserDeclined &&\n reason !== MSC4108FailureReason.UserCancelled\n ) {\n await this.close();\n }\n }\n }\n\n /**\n * Returns whether the rendezvous session has been cancelled.\n */\n public get cancelled(): boolean {\n return this.rendezvousSession.cancelled;\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAEIA,KAAK,EAELC,UAAU,EACVC,YAAY,QACT,oCAAoC;AAE3C,SACIC,6BAA6B,EAC7BC,oBAAoB,EAEpBC,eAAe,QAEZ,aAAa;AAEpB,SAASC,MAAM,QAAQ,iBAAiB;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,oBAAoB,CAA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iB,CAACiE,KAAK,CAAC,CAAC;IAAC;EACzC;;EAEA;AACJ;AACA;AACA;EACiBE,MAAMA,CAACC,MAA4D,EAAiB;IAAA,IAAAC,MAAA;IAAA,OAAA5D,iBAAA;MAC7F,IAAI;QAAA,IAAA6D,gBAAA;QACA,MAAMD,MAAI,CAACrE,iBAAiB,CAACmE,MAAM,CAACC,MAAM,CAAC;QAC3C,CAAAE,gBAAA,GAAAD,MAAI,CAACnE,SAAS,cAAAoE,gBAAA,eAAdA,gBAAA,CAAAC,IAAA,CAAAF,MAAI,EAAaD,MAAM,CAAC;MAC5B,CAAC,SAAS;QACN,IACIA,MAAM,KAAK1E,6BAA6B,CAAC8E,YAAY,IACrDJ,MAAM,KAAKzE,oBAAoB,CAAC8E,aAAa,EAC/C;UACE,MAAMJ,MAAI,CAACJ,KAAK,CAAC,CAAC;QACtB;MACJ;IAAC;EACL;;EAEA;AACJ;AACA;EACI,IAAWS,SAASA,CAAA,EAAY;IAC5B,OAAO,IAAI,CAAC1E,iBAAiB,CAAC0E,SAAS;EAC3C;AACJ","ignoreList":[]}
|
|
@@ -34,6 +34,14 @@ export class MSC4108RendezvousSession {
|
|
|
34
34
|
url = _ref.url,
|
|
35
35
|
client = _ref.client,
|
|
36
36
|
fallbackRzServer = _ref.fallbackRzServer;
|
|
37
|
+
_defineProperty(this, "url", void 0);
|
|
38
|
+
_defineProperty(this, "client", void 0);
|
|
39
|
+
_defineProperty(this, "fallbackRzServer", void 0);
|
|
40
|
+
_defineProperty(this, "fetchFn", void 0);
|
|
41
|
+
_defineProperty(this, "onFailure", void 0);
|
|
42
|
+
_defineProperty(this, "etag", void 0);
|
|
43
|
+
_defineProperty(this, "expiresAt", void 0);
|
|
44
|
+
_defineProperty(this, "expiresTimer", void 0);
|
|
37
45
|
_defineProperty(this, "_cancelled", false);
|
|
38
46
|
_defineProperty(this, "_ready", false);
|
|
39
47
|
this.fetchFn = fetchFn;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MSC4108RendezvousSession.js","names":["logger","sleep","ClientRendezvousFailureReason","MSC4108FailureReason","Method","ClientPrefix","MSC4108RendezvousSession","constructor","_ref","fetchFn","onFailure","url","client","fallbackRzServer","_defineProperty","ready","_ready","cancelled","_cancelled","fetch","resource","options","globalThis","getPostEndpoint","_this","_asyncToGenerator","doesServerSupportUnstableFeature","http","getUrl","undefined","Unstable","toString","err","warn","send","data","_this2","_this2$url","_res$headers$get","method","Put","Post","uri","Error","headers","etag","receive","info","concat","res","body","redirect","status","cancel","Unknown","get","expires","expiresTimer","clearTimeout","expiresAt","Date","setTimeout","Expired","getTime","now","json","_this3","_poll$headers$get","poll","Get","ETagMissing","text","reason","_this4","_this4$onFailure","call","UserDeclined","UserCancelled","close","_this5","Delete","e"],"sources":["../../../src/rendezvous/transports/MSC4108RendezvousSession.ts"],"sourcesContent":["/*\nCopyright 2024 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 { logger } from \"../../logger.ts\";\nimport { sleep } from \"../../utils.ts\";\nimport { ClientRendezvousFailureReason, MSC4108FailureReason, type RendezvousFailureListener } from \"../index.ts\";\nimport { type MatrixClient, Method } from \"../../matrix.ts\";\nimport { ClientPrefix } from \"../../http-api/index.ts\";\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * insecure rendezvous session protocol.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport class MSC4108RendezvousSession {\n public url?: string;\n private readonly client?: MatrixClient;\n private readonly fallbackRzServer?: string;\n private readonly fetchFn?: typeof globalThis.fetch;\n public onFailure?: RendezvousFailureListener;\n private etag?: string;\n private expiresAt?: Date;\n private expiresTimer?: ReturnType<typeof setTimeout>;\n private _cancelled = false;\n private _ready = false;\n\n public constructor({\n onFailure,\n url,\n fetchFn,\n }: {\n fetchFn?: typeof globalThis.fetch;\n onFailure?: RendezvousFailureListener;\n url: string;\n });\n public constructor({\n onFailure,\n client,\n fallbackRzServer,\n fetchFn,\n }: {\n fetchFn?: typeof globalThis.fetch;\n onFailure?: RendezvousFailureListener;\n client?: MatrixClient;\n fallbackRzServer?: string;\n });\n public constructor({\n fetchFn,\n onFailure,\n url,\n client,\n fallbackRzServer,\n }: {\n fetchFn?: typeof globalThis.fetch;\n onFailure?: RendezvousFailureListener;\n url?: string;\n client?: MatrixClient;\n fallbackRzServer?: string;\n }) {\n this.fetchFn = fetchFn;\n this.onFailure = onFailure;\n this.client = client;\n this.fallbackRzServer = fallbackRzServer;\n this.url = url;\n }\n\n /**\n * Returns whether the channel is ready to be used.\n */\n public get ready(): boolean {\n return this._ready;\n }\n\n /**\n * Returns whether the channel has been cancelled.\n */\n public get cancelled(): boolean {\n return this._cancelled;\n }\n\n private fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.fetchFn) {\n return this.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n private async getPostEndpoint(): Promise<string | undefined> {\n if (this.client) {\n try {\n if (await this.client.doesServerSupportUnstableFeature(\"org.matrix.msc4108\")) {\n return this.client.http\n .getUrl(\"/org.matrix.msc4108/rendezvous\", undefined, ClientPrefix.Unstable)\n .toString();\n }\n } catch (err) {\n logger.warn(\"Failed to get unstable features\", err);\n }\n }\n\n return this.fallbackRzServer;\n }\n\n /**\n * Sends data via the rendezvous channel.\n * @param data the payload to send\n */\n public async send(data: string): Promise<void> {\n if (this._cancelled) {\n return;\n }\n const method = this.url ? Method.Put : Method.Post;\n const uri = this.url ?? (await this.getPostEndpoint());\n\n if (!uri) {\n throw new Error(\"Invalid rendezvous URI\");\n }\n\n const headers: Record<string, string> = { \"content-type\": \"text/plain\" };\n\n // if we didn't create the rendezvous channel, we need to fetch the first etag if needed\n if (!this.etag && this.url) {\n await this.receive();\n }\n\n if (this.etag) {\n headers[\"if-match\"] = this.etag;\n }\n\n logger.info(`=> ${method} ${uri} with ${data} if-match: ${this.etag}`);\n\n const res = await this.fetch(uri, { method, headers, body: data, redirect: \"follow\" });\n if (res.status === 404) {\n return this.cancel(ClientRendezvousFailureReason.Unknown);\n }\n this.etag = res.headers.get(\"etag\") ?? undefined;\n\n logger.info(`Received etag: ${this.etag}`);\n\n if (method === Method.Post) {\n const expires = res.headers.get(\"expires\");\n if (expires) {\n if (this.expiresTimer) {\n clearTimeout(this.expiresTimer);\n this.expiresTimer = undefined;\n }\n this.expiresAt = new Date(expires);\n this.expiresTimer = setTimeout(() => {\n this.expiresTimer = undefined;\n this.cancel(ClientRendezvousFailureReason.Expired);\n }, this.expiresAt.getTime() - Date.now());\n }\n // MSC4108: we expect a JSON response with a rendezvous URL\n const json = await res.json();\n if (typeof json.url !== \"string\") {\n throw new Error(\"No rendezvous URL given\");\n }\n this.url = json.url;\n this._ready = true;\n }\n }\n\n /**\n * Receives data from the rendezvous channel.\n * @return the returned promise won't resolve until new data is acquired or the channel is closed either by the server or the other party.\n */\n public async receive(): Promise<string | undefined> {\n if (!this.url) {\n throw new Error(\"Rendezvous not set up\");\n }\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (this._cancelled) {\n return undefined;\n }\n\n const headers: Record<string, string> = {};\n if (this.etag) {\n headers[\"if-none-match\"] = this.etag;\n }\n\n logger.info(`=> GET ${this.url} if-none-match: ${this.etag}`);\n const poll = await this.fetch(this.url, { method: Method.Get, headers });\n\n if (poll.status === 404) {\n await this.cancel(ClientRendezvousFailureReason.Unknown);\n return undefined;\n }\n\n // rely on server expiring the channel rather than checking ourselves\n\n const etag = poll.headers.get(\"etag\") ?? undefined;\n if (poll.headers.get(\"content-type\") !== \"text/plain\") {\n this.etag = etag;\n } else if (poll.status === 200) {\n if (!etag) {\n // Some browsers & extensions block the ETag header for anti-tracking purposes\n // We try and detect this so the client can give the user a somewhat helpful message\n await this.cancel(ClientRendezvousFailureReason.ETagMissing);\n return undefined;\n }\n\n this.etag = etag;\n const text = await poll.text();\n logger.info(`Received: ${text} with etag ${this.etag}`);\n return text;\n }\n await sleep(1000);\n }\n }\n\n /**\n * Cancels the rendezvous channel.\n * If the reason is user_declined or user_cancelled then the channel will also be closed.\n * @param reason the reason to cancel with\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n if (this._cancelled) return;\n if (this.expiresTimer) {\n clearTimeout(this.expiresTimer);\n this.expiresTimer = undefined;\n }\n\n if (\n reason === ClientRendezvousFailureReason.Unknown &&\n this.expiresAt &&\n this.expiresAt.getTime() < Date.now()\n ) {\n reason = ClientRendezvousFailureReason.Expired;\n }\n\n this._cancelled = true;\n this._ready = false;\n this.onFailure?.(reason);\n\n if (reason === ClientRendezvousFailureReason.UserDeclined || reason === MSC4108FailureReason.UserCancelled) {\n await this.close();\n }\n }\n\n /**\n * Closes the rendezvous channel.\n */\n public async close(): Promise<void> {\n if (this.expiresTimer) {\n clearTimeout(this.expiresTimer);\n this.expiresTimer = undefined;\n }\n\n if (!this.url) return;\n try {\n const method = Method.Delete;\n logger.info(`=> ${method} ${this.url}`);\n await this.fetch(this.url, { method });\n } catch (e) {\n logger.warn(e);\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,iBAAiB;AACxC,SAASC,KAAK,QAAQ,gBAAgB;AACtC,SAASC,6BAA6B,EAAEC,oBAAoB,QAAwC,aAAa;AACjH,SAA4BC,MAAM,QAAQ,iBAAiB;AAC3D,SAASC,YAAY,QAAQ,yBAAyB;;AAEtD;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,wBAAw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oB,CAAC0E,aAAa,EAAE;QACxG,MAAMJ,MAAI,CAACK,KAAK,CAAC,CAAC;MACtB;IAAC;EACL;;EAEA;AACJ;AACA;EACiBA,KAAKA,CAAA,EAAkB;IAAA,IAAAC,MAAA;IAAA,OAAAtD,iBAAA;MAChC,IAAIsD,MAAI,CAACtB,YAAY,EAAE;QACnBC,YAAY,CAACqB,MAAI,CAACtB,YAAY,CAAC;QAC/BsB,MAAI,CAACtB,YAAY,GAAG5B,SAAS;MACjC;MAEA,IAAI,CAACkD,MAAI,CAACpE,GAAG,EAAE;MACf,IAAI;QACA,IAAM4B,MAAM,GAAGnC,MAAM,CAAC4E,MAAM;QAC5BhF,MAAM,CAAC+C,IAAI,OAAAC,MAAA,CAAOT,MAAM,OAAAS,MAAA,CAAI+B,MAAI,CAACpE,GAAG,CAAE,CAAC;QACvC,MAAMoE,MAAI,CAAC5D,KAAK,CAAC4D,MAAI,CAACpE,GAAG,EAAE;UAAE4B;QAAO,CAAC,CAAC;MAC1C,CAAC,CAAC,OAAO0C,CAAC,EAAE;QACRjF,MAAM,CAACiC,IAAI,CAACgD,CAAC,CAAC;MAClB;IAAC;EACL;AACJ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"MSC4108RendezvousSession.js","names":["logger","sleep","ClientRendezvousFailureReason","MSC4108FailureReason","Method","ClientPrefix","MSC4108RendezvousSession","constructor","_ref","fetchFn","onFailure","url","client","fallbackRzServer","_defineProperty","ready","_ready","cancelled","_cancelled","fetch","resource","options","globalThis","getPostEndpoint","_this","_asyncToGenerator","doesServerSupportUnstableFeature","http","getUrl","undefined","Unstable","toString","err","warn","send","data","_this2","_this2$url","_res$headers$get","method","Put","Post","uri","Error","headers","etag","receive","info","concat","res","body","redirect","status","cancel","Unknown","get","expires","expiresTimer","clearTimeout","expiresAt","Date","setTimeout","Expired","getTime","now","json","_this3","_poll$headers$get","poll","Get","ETagMissing","text","reason","_this4","_this4$onFailure","call","UserDeclined","UserCancelled","close","_this5","Delete","e"],"sources":["../../../src/rendezvous/transports/MSC4108RendezvousSession.ts"],"sourcesContent":["/*\nCopyright 2024 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 { logger } from \"../../logger.ts\";\nimport { sleep } from \"../../utils.ts\";\nimport { ClientRendezvousFailureReason, MSC4108FailureReason, type RendezvousFailureListener } from \"../index.ts\";\nimport { type MatrixClient, Method } from \"../../matrix.ts\";\nimport { ClientPrefix } from \"../../http-api/index.ts\";\n\n/**\n * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)\n * insecure rendezvous session protocol.\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\nexport class MSC4108RendezvousSession {\n public url?: string;\n private readonly client?: MatrixClient;\n private readonly fallbackRzServer?: string;\n private readonly fetchFn?: typeof globalThis.fetch;\n public onFailure?: RendezvousFailureListener;\n private etag?: string;\n private expiresAt?: Date;\n private expiresTimer?: ReturnType<typeof setTimeout>;\n private _cancelled = false;\n private _ready = false;\n\n public constructor({\n onFailure,\n url,\n fetchFn,\n }: {\n fetchFn?: typeof globalThis.fetch;\n onFailure?: RendezvousFailureListener;\n url: string;\n });\n public constructor({\n onFailure,\n client,\n fallbackRzServer,\n fetchFn,\n }: {\n fetchFn?: typeof globalThis.fetch;\n onFailure?: RendezvousFailureListener;\n client?: MatrixClient;\n fallbackRzServer?: string;\n });\n public constructor({\n fetchFn,\n onFailure,\n url,\n client,\n fallbackRzServer,\n }: {\n fetchFn?: typeof globalThis.fetch;\n onFailure?: RendezvousFailureListener;\n url?: string;\n client?: MatrixClient;\n fallbackRzServer?: string;\n }) {\n this.fetchFn = fetchFn;\n this.onFailure = onFailure;\n this.client = client;\n this.fallbackRzServer = fallbackRzServer;\n this.url = url;\n }\n\n /**\n * Returns whether the channel is ready to be used.\n */\n public get ready(): boolean {\n return this._ready;\n }\n\n /**\n * Returns whether the channel has been cancelled.\n */\n public get cancelled(): boolean {\n return this._cancelled;\n }\n\n private fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.fetchFn) {\n return this.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n private async getPostEndpoint(): Promise<string | undefined> {\n if (this.client) {\n try {\n if (await this.client.doesServerSupportUnstableFeature(\"org.matrix.msc4108\")) {\n return this.client.http\n .getUrl(\"/org.matrix.msc4108/rendezvous\", undefined, ClientPrefix.Unstable)\n .toString();\n }\n } catch (err) {\n logger.warn(\"Failed to get unstable features\", err);\n }\n }\n\n return this.fallbackRzServer;\n }\n\n /**\n * Sends data via the rendezvous channel.\n * @param data the payload to send\n */\n public async send(data: string): Promise<void> {\n if (this._cancelled) {\n return;\n }\n const method = this.url ? Method.Put : Method.Post;\n const uri = this.url ?? (await this.getPostEndpoint());\n\n if (!uri) {\n throw new Error(\"Invalid rendezvous URI\");\n }\n\n const headers: Record<string, string> = { \"content-type\": \"text/plain\" };\n\n // if we didn't create the rendezvous channel, we need to fetch the first etag if needed\n if (!this.etag && this.url) {\n await this.receive();\n }\n\n if (this.etag) {\n headers[\"if-match\"] = this.etag;\n }\n\n logger.info(`=> ${method} ${uri} with ${data} if-match: ${this.etag}`);\n\n const res = await this.fetch(uri, { method, headers, body: data, redirect: \"follow\" });\n if (res.status === 404) {\n return this.cancel(ClientRendezvousFailureReason.Unknown);\n }\n this.etag = res.headers.get(\"etag\") ?? undefined;\n\n logger.info(`Received etag: ${this.etag}`);\n\n if (method === Method.Post) {\n const expires = res.headers.get(\"expires\");\n if (expires) {\n if (this.expiresTimer) {\n clearTimeout(this.expiresTimer);\n this.expiresTimer = undefined;\n }\n this.expiresAt = new Date(expires);\n this.expiresTimer = setTimeout(() => {\n this.expiresTimer = undefined;\n this.cancel(ClientRendezvousFailureReason.Expired);\n }, this.expiresAt.getTime() - Date.now());\n }\n // MSC4108: we expect a JSON response with a rendezvous URL\n const json = await res.json();\n if (typeof json.url !== \"string\") {\n throw new Error(\"No rendezvous URL given\");\n }\n this.url = json.url;\n this._ready = true;\n }\n }\n\n /**\n * Receives data from the rendezvous channel.\n * @return the returned promise won't resolve until new data is acquired or the channel is closed either by the server or the other party.\n */\n public async receive(): Promise<string | undefined> {\n if (!this.url) {\n throw new Error(\"Rendezvous not set up\");\n }\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (this._cancelled) {\n return undefined;\n }\n\n const headers: Record<string, string> = {};\n if (this.etag) {\n headers[\"if-none-match\"] = this.etag;\n }\n\n logger.info(`=> GET ${this.url} if-none-match: ${this.etag}`);\n const poll = await this.fetch(this.url, { method: Method.Get, headers });\n\n if (poll.status === 404) {\n await this.cancel(ClientRendezvousFailureReason.Unknown);\n return undefined;\n }\n\n // rely on server expiring the channel rather than checking ourselves\n\n const etag = poll.headers.get(\"etag\") ?? undefined;\n if (poll.headers.get(\"content-type\") !== \"text/plain\") {\n this.etag = etag;\n } else if (poll.status === 200) {\n if (!etag) {\n // Some browsers & extensions block the ETag header for anti-tracking purposes\n // We try and detect this so the client can give the user a somewhat helpful message\n await this.cancel(ClientRendezvousFailureReason.ETagMissing);\n return undefined;\n }\n\n this.etag = etag;\n const text = await poll.text();\n logger.info(`Received: ${text} with etag ${this.etag}`);\n return text;\n }\n await sleep(1000);\n }\n }\n\n /**\n * Cancels the rendezvous channel.\n * If the reason is user_declined or user_cancelled then the channel will also be closed.\n * @param reason the reason to cancel with\n */\n public async cancel(reason: MSC4108FailureReason | ClientRendezvousFailureReason): Promise<void> {\n if (this._cancelled) return;\n if (this.expiresTimer) {\n clearTimeout(this.expiresTimer);\n this.expiresTimer = undefined;\n }\n\n if (\n reason === ClientRendezvousFailureReason.Unknown &&\n this.expiresAt &&\n this.expiresAt.getTime() < Date.now()\n ) {\n reason = ClientRendezvousFailureReason.Expired;\n }\n\n this._cancelled = true;\n this._ready = false;\n this.onFailure?.(reason);\n\n if (reason === ClientRendezvousFailureReason.UserDeclined || reason === MSC4108FailureReason.UserCancelled) {\n await this.close();\n }\n }\n\n /**\n * Closes the rendezvous channel.\n */\n public async close(): Promise<void> {\n if (this.expiresTimer) {\n clearTimeout(this.expiresTimer);\n this.expiresTimer = undefined;\n }\n\n if (!this.url) return;\n try {\n const method = Method.Delete;\n logger.info(`=> ${method} ${this.url}`);\n await this.fetch(this.url, { method });\n } catch (e) {\n logger.warn(e);\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,iBAAiB;AACxC,SAASC,KAAK,QAAQ,gBAAgB;AACtC,SAASC,6BAA6B,EAAEC,oBAAoB,QAAwC,aAAa;AACjH,SAA4BC,MAAM,QAAQ,iBAAiB;AAC3D,SAASC,YAAY,QAAQ,yBAAyB;;AAEtD;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,wBAAwB,CAAC;EAgC3BC,WAAWA,CAAAC,IAAA,EAYf;IAAA,IAXCC,OAAO,GAAAD,IAAA,CAAPC,OAAO;MACPC,SAAS,GAAAF,IAAA,CAATE,SAAS;MACTC,GAAG,GAAAH,IAAA,CAAHG,GAAG;MACHC,MAAM,GAAAJ,IAAA,CAANI,MAAM;MACNC,gBAAgB,GAAAL,IAAA,CAAhBK,gBAAgB;IAAAC,eAAA;IAAAA,eAAA;IAAAA,eAAA;IAAAA,eAAA;IAAAA,eAAA;IAAAA,eAAA;IAAAA,eAAA;IAAAA,eAAA;IAAAA,eAAA,qBA5BC,KAAK;IAAAA,eAAA,iBACT,KAAK;IAmClB,IAAI,CAACL,OAAO,GAAGA,OAAO;IACtB,IAAI,CAACC,SAAS,GAAGA,S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B,MAAM,GAAGnC,MAAM,CAAC4E,MAAM;QAC5BhF,MAAM,CAAC+C,IAAI,OAAAC,MAAA,CAAOT,MAAM,OAAAS,MAAA,CAAI+B,MAAI,CAACpE,GAAG,CAAE,CAAC;QACvC,MAAMoE,MAAI,CAAC5D,KAAK,CAAC4D,MAAI,CAACpE,GAAG,EAAE;UAAE4B;QAAO,CAAC,CAAC;MAC1C,CAAC,CAAC,OAAO0C,CAAC,EAAE;QACRjF,MAAM,CAACiC,IAAI,CAACgD,CAAC,CAAC;MAClB;IAAC;EACL;AACJ","ignoreList":[]}
|
package/lib/room-hierarchy.js
CHANGED
|
@@ -30,16 +30,20 @@ export class RoomHierarchy {
|
|
|
30
30
|
*/
|
|
31
31
|
constructor(root, pageSize, maxDepth) {
|
|
32
32
|
var suggestedOnly = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
|
|
33
|
+
this.root = root;
|
|
34
|
+
this.pageSize = pageSize;
|
|
35
|
+
this.maxDepth = maxDepth;
|
|
36
|
+
this.suggestedOnly = suggestedOnly;
|
|
33
37
|
// Map from room id to list of servers which are listed as a via somewhere in the loaded hierarchy
|
|
34
38
|
_defineProperty(this, "viaMap", new Map());
|
|
35
39
|
// Map from room id to list of rooms which claim this room as their child
|
|
36
40
|
_defineProperty(this, "backRefs", new Map());
|
|
37
41
|
// Map from room id to object
|
|
38
42
|
_defineProperty(this, "roomMap", new Map());
|
|
39
|
-
this
|
|
40
|
-
this
|
|
41
|
-
this
|
|
42
|
-
this
|
|
43
|
+
_defineProperty(this, "loadRequest", void 0);
|
|
44
|
+
_defineProperty(this, "nextBatch", void 0);
|
|
45
|
+
_defineProperty(this, "_rooms", void 0);
|
|
46
|
+
_defineProperty(this, "serverSupportError", void 0);
|
|
43
47
|
}
|
|
44
48
|
get noSupport() {
|
|
45
49
|
return !!this.serverSupportError;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"room-hierarchy.js","names":["EventType","RoomHierarchy","constructor","root","pageSize","maxDepth","suggestedOnly","arguments","length","undefined","_defineProperty","Map","noSupport","serverSupportError","canLoadMore","nextBatch","_rooms","loading","loadRequest","rooms","load","_arguments","_this","_asyncToGenerator","then","r","client","getRoomHierarchy","roomId","_yield$_this$loadRequ","next_batch","e","errcode","concat","forEach","room","roomMap","set","room_id","children_state","ev","type","SpaceChild","childRoomId","state_key","backRefs","has","get","push","Array","isArray","content","via","viaMap","Set","vias","add","getRelation","parentId","childId","_this$roomMap$get","find","isSuggested","_this$getRelation","suggested","removeRelation","delete","filter","ref"],"sources":["../src/room-hierarchy.ts"],"sourcesContent":["/*\nCopyright 2021 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 { type Room } from \"./models/room.ts\";\nimport { type IHierarchyRoom, type IHierarchyRelation } from \"./@types/spaces.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { EventType } from \"./@types/event.ts\";\nimport { type MatrixError } from \"./http-api/index.ts\";\n\nexport class RoomHierarchy {\n // Map from room id to list of servers which are listed as a via somewhere in the loaded hierarchy\n public readonly viaMap = new Map<string, Set<string>>();\n // Map from room id to list of rooms which claim this room as their child\n public readonly backRefs = new Map<string, string[]>();\n // Map from room id to object\n public readonly roomMap = new Map<string, IHierarchyRoom>();\n private loadRequest?: ReturnType<MatrixClient[\"getRoomHierarchy\"]>;\n private nextBatch?: string;\n private _rooms?: IHierarchyRoom[];\n private serverSupportError?: Error;\n\n /**\n * Construct a new RoomHierarchy\n *\n * A RoomHierarchy instance allows you to easily make use of the /hierarchy API and paginate it.\n *\n * @param root - the root of this hierarchy\n * @param pageSize - the maximum number of rooms to return per page, can be overridden per load request.\n * @param maxDepth - the maximum depth to traverse the hierarchy to\n * @param suggestedOnly - whether to only return rooms with suggested=true.\n */\n public constructor(\n public readonly root: Room,\n private readonly pageSize?: number,\n private readonly maxDepth?: number,\n private readonly suggestedOnly = false,\n ) {}\n\n public get noSupport(): boolean {\n return !!this.serverSupportError;\n }\n\n public get canLoadMore(): boolean {\n return !!this.serverSupportError || !!this.nextBatch || !this._rooms;\n }\n\n public get loading(): boolean {\n return !!this.loadRequest;\n }\n\n public get rooms(): IHierarchyRoom[] | undefined {\n return this._rooms;\n }\n\n public async load(pageSize = this.pageSize): Promise<IHierarchyRoom[]> {\n if (this.loadRequest) return this.loadRequest.then((r) => r.rooms);\n\n this.loadRequest = this.root.client.getRoomHierarchy(\n this.root.roomId,\n pageSize,\n this.maxDepth,\n this.suggestedOnly,\n this.nextBatch,\n );\n\n let rooms: IHierarchyRoom[];\n try {\n ({ rooms, next_batch: this.nextBatch } = await this.loadRequest);\n } catch (e) {\n if ((<MatrixError>e).errcode === \"M_UNRECOGNIZED\") {\n this.serverSupportError = <MatrixError>e;\n } else {\n throw e;\n }\n\n return [];\n } finally {\n this.loadRequest = undefined;\n }\n\n if (this._rooms) {\n this._rooms = this._rooms.concat(rooms);\n } else {\n this._rooms = rooms;\n }\n\n rooms.forEach((room) => {\n this.roomMap.set(room.room_id, room);\n\n room.children_state.forEach((ev) => {\n if (ev.type !== EventType.SpaceChild) return;\n const childRoomId = ev.state_key;\n\n // track backrefs for quicker hierarchy navigation\n if (!this.backRefs.has(childRoomId)) {\n this.backRefs.set(childRoomId, []);\n }\n this.backRefs.get(childRoomId)!.push(room.room_id);\n\n // fill viaMap\n if (Array.isArray(ev.content.via)) {\n if (!this.viaMap.has(childRoomId)) {\n this.viaMap.set(childRoomId, new Set());\n }\n const vias = this.viaMap.get(childRoomId)!;\n ev.content.via.forEach((via) => vias.add(via));\n }\n });\n });\n\n return rooms;\n }\n\n public getRelation(parentId: string, childId: string): IHierarchyRelation | undefined {\n return this.roomMap.get(parentId)?.children_state.find((e) => e.state_key === childId);\n }\n\n public isSuggested(parentId: string, childId: string): boolean | undefined {\n return this.getRelation(parentId, childId)?.content.suggested;\n }\n\n // locally remove a relation as a form of local echo\n public removeRelation(parentId: string, childId: string): void {\n const backRefs = this.backRefs.get(childId);\n if (backRefs?.length === 1) {\n this.backRefs.delete(childId);\n } else if (backRefs?.length) {\n this.backRefs.set(\n childId,\n backRefs.filter((ref) => ref !== parentId),\n );\n }\n\n const room = this.roomMap.get(parentId);\n if (room) {\n room.children_state = room.children_state.filter((ev) => ev.state_key !== childId);\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,SAASA,SAAS,QAAQ,mBAAmB;AAG7C,OAAO,MAAMC,aAAa,CAAC;EAYvB;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACWC,WAAWA,CACEC,IAAU,EACTC,QAAiB,EACjBC,QAAiB,EAEpC;IAAA,IADmBC,aAAa,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,KAAK;IAzB1C;IAAAG,eAAA,iBACyB,IAAIC,GAAG,CAAsB,CAAC;IACvD;IAAAD,eAAA,mBAC2B,IAAIC,GAAG,CAAmB,CAAC;IACtD;IAAAD,eAAA,kBAC0B,IAAIC,GAAG,CAAyB,CAAC;IAAA,KAiBvCR,IAAU,GAAVA,IAAU;IAAA,KACTC,QAAiB,GAAjBA,QAAiB;IAAA,KACjBC,QAAiB,GAAjBA,QAAiB;IAAA,KACjBC,aAAa,GAAbA,aAAa;EAC/B;EAEH,IAAWM,SAASA,CAAA,EAAY;IAC5B,OAAO,CAAC,CAAC,IAAI,CAACC,kBAAkB;EACpC;EAEA,IAAWC,WAAWA,CAAA,EAAY;IAC9B,OAAO,CAAC,CAAC,IAAI,CAACD,kBAAkB,IAAI,CAA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[]}
|
|
1
|
+
{"version":3,"file":"room-hierarchy.js","names":["EventType","RoomHierarchy","constructor","root","pageSize","maxDepth","suggestedOnly","arguments","length","undefined","_defineProperty","Map","noSupport","serverSupportError","canLoadMore","nextBatch","_rooms","loading","loadRequest","rooms","load","_arguments","_this","_asyncToGenerator","then","r","client","getRoomHierarchy","roomId","_yield$_this$loadRequ","next_batch","e","errcode","concat","forEach","room","roomMap","set","room_id","children_state","ev","type","SpaceChild","childRoomId","state_key","backRefs","has","get","push","Array","isArray","content","via","viaMap","Set","vias","add","getRelation","parentId","childId","_this$roomMap$get","find","isSuggested","_this$getRelation","suggested","removeRelation","delete","filter","ref"],"sources":["../src/room-hierarchy.ts"],"sourcesContent":["/*\nCopyright 2021 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 { type Room } from \"./models/room.ts\";\nimport { type IHierarchyRoom, type IHierarchyRelation } from \"./@types/spaces.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { EventType } from \"./@types/event.ts\";\nimport { type MatrixError } from \"./http-api/index.ts\";\n\nexport class RoomHierarchy {\n // Map from room id to list of servers which are listed as a via somewhere in the loaded hierarchy\n public readonly viaMap = new Map<string, Set<string>>();\n // Map from room id to list of rooms which claim this room as their child\n public readonly backRefs = new Map<string, string[]>();\n // Map from room id to object\n public readonly roomMap = new Map<string, IHierarchyRoom>();\n private loadRequest?: ReturnType<MatrixClient[\"getRoomHierarchy\"]>;\n private nextBatch?: string;\n private _rooms?: IHierarchyRoom[];\n private serverSupportError?: Error;\n\n /**\n * Construct a new RoomHierarchy\n *\n * A RoomHierarchy instance allows you to easily make use of the /hierarchy API and paginate it.\n *\n * @param root - the root of this hierarchy\n * @param pageSize - the maximum number of rooms to return per page, can be overridden per load request.\n * @param maxDepth - the maximum depth to traverse the hierarchy to\n * @param suggestedOnly - whether to only return rooms with suggested=true.\n */\n public constructor(\n public readonly root: Room,\n private readonly pageSize?: number,\n private readonly maxDepth?: number,\n private readonly suggestedOnly = false,\n ) {}\n\n public get noSupport(): boolean {\n return !!this.serverSupportError;\n }\n\n public get canLoadMore(): boolean {\n return !!this.serverSupportError || !!this.nextBatch || !this._rooms;\n }\n\n public get loading(): boolean {\n return !!this.loadRequest;\n }\n\n public get rooms(): IHierarchyRoom[] | undefined {\n return this._rooms;\n }\n\n public async load(pageSize = this.pageSize): Promise<IHierarchyRoom[]> {\n if (this.loadRequest) return this.loadRequest.then((r) => r.rooms);\n\n this.loadRequest = this.root.client.getRoomHierarchy(\n this.root.roomId,\n pageSize,\n this.maxDepth,\n this.suggestedOnly,\n this.nextBatch,\n );\n\n let rooms: IHierarchyRoom[];\n try {\n ({ rooms, next_batch: this.nextBatch } = await this.loadRequest);\n } catch (e) {\n if ((<MatrixError>e).errcode === \"M_UNRECOGNIZED\") {\n this.serverSupportError = <MatrixError>e;\n } else {\n throw e;\n }\n\n return [];\n } finally {\n this.loadRequest = undefined;\n }\n\n if (this._rooms) {\n this._rooms = this._rooms.concat(rooms);\n } else {\n this._rooms = rooms;\n }\n\n rooms.forEach((room) => {\n this.roomMap.set(room.room_id, room);\n\n room.children_state.forEach((ev) => {\n if (ev.type !== EventType.SpaceChild) return;\n const childRoomId = ev.state_key;\n\n // track backrefs for quicker hierarchy navigation\n if (!this.backRefs.has(childRoomId)) {\n this.backRefs.set(childRoomId, []);\n }\n this.backRefs.get(childRoomId)!.push(room.room_id);\n\n // fill viaMap\n if (Array.isArray(ev.content.via)) {\n if (!this.viaMap.has(childRoomId)) {\n this.viaMap.set(childRoomId, new Set());\n }\n const vias = this.viaMap.get(childRoomId)!;\n ev.content.via.forEach((via) => vias.add(via));\n }\n });\n });\n\n return rooms;\n }\n\n public getRelation(parentId: string, childId: string): IHierarchyRelation | undefined {\n return this.roomMap.get(parentId)?.children_state.find((e) => e.state_key === childId);\n }\n\n public isSuggested(parentId: string, childId: string): boolean | undefined {\n return this.getRelation(parentId, childId)?.content.suggested;\n }\n\n // locally remove a relation as a form of local echo\n public removeRelation(parentId: string, childId: string): void {\n const backRefs = this.backRefs.get(childId);\n if (backRefs?.length === 1) {\n this.backRefs.delete(childId);\n } else if (backRefs?.length) {\n this.backRefs.set(\n childId,\n backRefs.filter((ref) => ref !== parentId),\n );\n }\n\n const room = this.roomMap.get(parentId);\n if (room) {\n room.children_state = room.children_state.filter((ev) => ev.state_key !== childId);\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,SAASA,SAAS,QAAQ,mBAAmB;AAG7C,OAAO,MAAMC,aAAa,CAAC;EAYvB;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACWC,WAAWA,CACEC,IAAU,EACTC,QAAiB,EACjBC,QAAiB,EAEpC;IAAA,IADmBC,aAAa,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,KAAK;IAAA,KAHtBJ,IAAU,GAAVA,IAAU;IAAA,KACTC,QAAiB,GAAjBA,QAAiB;IAAA,KACjBC,QAAiB,GAAjBA,QAAiB;IAAA,KACjBC,aAAa,GAAbA,aAAa;IAzBlC;IAAAI,eAAA,iBACyB,IAAIC,GAAG,CAAsB,CAAC;IACvD;IAAAD,eAAA,mBAC2B,IAAIC,GAAG,CAAmB,CAAC;IACtD;IAAAD,eAAA,kBAC0B,IAAIC,GAAG,CAAyB,CAAC;IAAAD,eAAA;IAAAA,eAAA;IAAAA,eAAA;IAAAA,eAAA;EAqBxD;EAEH,IAAWE,SAASA,CAAA,EAAY;IAC5B,OAAO,CA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AAGJ,IAAI,CAACI,cAAc,CAAC4B,MAAM,CAAE3B,EAAE,IAAKA,EAAE,CAACI,SAAS,KAAKe,OAAO,CAAC;IACtF;EACJ;AACJ","ignoreList":[]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
|
|
2
|
+
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
|
2
3
|
/*
|
|
3
4
|
Copyright 2024 The Matrix.org Foundation C.I.C.
|
|
4
5
|
|
|
@@ -57,8 +58,6 @@ var DEHYDRATION_INTERVAL = 7 * 24 * 60 * 60 * 1000;
|
|
|
57
58
|
* @internal
|
|
58
59
|
*/
|
|
59
60
|
export class DehydratedDeviceManager extends TypedEventEmitter {
|
|
60
|
-
/** the ID of the interval for periodically replacing the dehydrated device */
|
|
61
|
-
|
|
62
61
|
constructor(logger, olmMachine, http, outgoingRequestProcessor, secretStorage) {
|
|
63
62
|
super();
|
|
64
63
|
this.logger = logger;
|
|
@@ -66,6 +65,8 @@ export class DehydratedDeviceManager extends TypedEventEmitter {
|
|
|
66
65
|
this.http = http;
|
|
67
66
|
this.outgoingRequestProcessor = outgoingRequestProcessor;
|
|
68
67
|
this.secretStorage = secretStorage;
|
|
68
|
+
/** the ID of the interval for periodically replacing the dehydrated device */
|
|
69
|
+
_defineProperty(this, "intervalId", void 0);
|
|
69
70
|
}
|
|
70
71
|
cacheKey(key) {
|
|
71
72
|
var _this = this;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DehydratedDeviceManager.js","names":["RustSdkCryptoJs","encodeUri","Method","decodeBase64","CryptoEvent","TypedEventEmitter","UnstablePrefix","SECRET_STORAGE_NAME","DEHYDRATION_INTERVAL","DehydratedDeviceManager","constructor","logger","olmMachine","http","outgoingRequestProcessor","secretStorage","cacheKey","key","_this","_asyncToGenerator","dehydratedDevices","saveDehydratedDeviceKey","emit","DehydrationKeyCached","isSupported","_this2","authedRequest","Get","undefined","prefix","error","err","errcode","start","_arguments","arguments","_this3","opts","length","createNewKey","onlyIfKeyCached","getDehydratedDeviceKey","stop","rehydrate","rehydrateDeviceIfAvailable","e","info","RehydrationError","message","resetKey","scheduleDeviceDehydration","isKeyStored","_this4","Boolean","isStored","_this5","DehydratedDeviceKey","createRandomKey","store","toBase64","getKey","create","_this6","cachedKey","keyB64","get","bytes","createKeyFromArray","fill","_this7","dehydratedDeviceResp","RehydrationStarted","rehydratedDevice","DeviceId","device_id","JSON","stringify","device_data","nextBatch","toDeviceCount","roomKeyCount","path","$device_id","eventResp","Post","next_batch","events","roomKeyInfos","receiveEvents","RehydrationProgress","concat","RehydrationCompleted","createAndUploadDehydratedDevice","_this8","dehydratedDevice","DehydratedDeviceCreated","request","keysForUpload","makeOutgoingRequest","DehydratedDeviceUploaded","_this9","intervalId","setInterval","catch","DehydratedDeviceRotationError","clearInterval","delete","_this0","Delete"],"sources":["../../src/rust-crypto/DehydratedDeviceManager.ts"],"sourcesContent":["/*\nCopyright 2024 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 * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport { type OutgoingRequestProcessor } from \"./OutgoingRequestProcessor.ts\";\nimport { encodeUri } from \"../utils.ts\";\nimport { type IHttpOpts, type MatrixError, type MatrixHttpApi, Method } from \"../http-api/index.ts\";\nimport { type IToDeviceEvent } from \"../sync-accumulator.ts\";\nimport { type ServerSideSecretStorage } from \"../secret-storage.ts\";\nimport { decodeBase64 } from \"../base64.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { CryptoEvent, type CryptoEventHandlerMap, type StartDehydrationOpts } from \"../crypto-api/index.ts\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\n\n/**\n * The response body of `GET /_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device`.\n */\ninterface DehydratedDeviceResp {\n device_id: string;\n device_data: {\n algorithm: string;\n };\n}\n/**\n * The response body of `POST /_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device/events`.\n */\ninterface DehydratedDeviceEventsResp {\n events: IToDeviceEvent[];\n next_batch: string;\n}\n\n/**\n * The unstable URL prefix for dehydrated device endpoints\n */\nexport const UnstablePrefix = \"/_matrix/client/unstable/org.matrix.msc3814.v1\";\n/**\n * The name used for the dehydration key in Secret Storage\n */\nconst SECRET_STORAGE_NAME = \"org.matrix.msc3814\";\n\n/**\n * The interval between creating dehydrated devices. (one week)\n */\nconst DEHYDRATION_INTERVAL = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Manages dehydrated devices\n *\n * We have one of these per `RustCrypto`. It's responsible for\n *\n * * determining server support for dehydrated devices\n * * creating new dehydrated devices when requested, including periodically\n * replacing the dehydrated device with a new one\n * * rehydrating a device when requested, and when present\n *\n * @internal\n */\nexport class DehydratedDeviceManager extends TypedEventEmitter<DehydratedDevicesEvents, DehydratedDevicesEventMap> {\n /** the ID of the interval for periodically replacing the dehydrated device */\n private intervalId?: ReturnType<typeof setInterval>;\n\n public constructor(\n private readonly logger: Logger,\n private readonly olmMachine: RustSdkCryptoJs.OlmMachine,\n private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,\n private readonly outgoingRequestProcessor: OutgoingRequestProcessor,\n private readonly secretStorage: ServerSideSecretStorage,\n ) {\n super();\n }\n\n private async cacheKey(key: RustSdkCryptoJs.DehydratedDeviceKey): Promise<void> {\n await this.olmMachine.dehydratedDevices().saveDehydratedDeviceKey(key);\n this.emit(CryptoEvent.DehydrationKeyCached);\n }\n\n /**\n * Return whether the server supports dehydrated devices.\n */\n public async isSupported(): Promise<boolean> {\n // call the endpoint to get a dehydrated device. If it returns an\n // M_UNRECOGNIZED error, then dehydration is unsupported. If it returns\n // a successful response, or an M_NOT_FOUND, then dehydration is supported.\n // Any other exceptions are passed through.\n try {\n await this.http.authedRequest<DehydratedDeviceResp>(\n Method.Get,\n \"/dehydrated_device\",\n undefined,\n undefined,\n {\n prefix: UnstablePrefix,\n },\n );\n } catch (error) {\n const err = error as MatrixError;\n if (err.errcode === \"M_UNRECOGNIZED\") {\n return false;\n } else if (err.errcode === \"M_NOT_FOUND\") {\n return true;\n }\n throw error;\n }\n return true;\n }\n\n /**\n * Start using device dehydration.\n *\n * - Rehydrates a dehydrated device, if one is available and `opts.rehydrate`\n * is `true`.\n * - Creates a new dehydration key, if necessary, and stores it in Secret\n * Storage.\n * - If `opts.createNewKey` is set to true, always creates a new key.\n * - If a dehydration key is not available, creates a new one.\n * - Creates a new dehydrated device, and schedules periodically creating\n * new dehydrated devices.\n *\n * @param opts - options for device dehydration. For backwards compatibility\n * with old code, a boolean can be given here, which will be treated as\n * the `createNewKey` option. However, this is deprecated.\n */\n public async start(opts: StartDehydrationOpts | boolean = {}): Promise<void> {\n if (typeof opts === \"boolean\") {\n opts = { createNewKey: opts };\n }\n\n if (opts.onlyIfKeyCached && !(await this.olmMachine.dehydratedDevices().getDehydratedDeviceKey())) {\n return;\n }\n this.stop();\n if (opts.rehydrate !== false) {\n try {\n await this.rehydrateDeviceIfAvailable();\n } catch (e) {\n // If rehydration fails, there isn't much we can do about it. Log\n // the error, and create a new device.\n this.logger.info(\"dehydration: Error rehydrating device:\", e);\n this.emit(CryptoEvent.RehydrationError, (e as Error).message);\n }\n }\n if (opts.createNewKey) {\n await this.resetKey();\n }\n await this.scheduleDeviceDehydration();\n }\n\n /**\n * Return whether the dehydration key is stored in Secret Storage.\n */\n public async isKeyStored(): Promise<boolean> {\n return Boolean(await this.secretStorage.isStored(SECRET_STORAGE_NAME));\n }\n\n /**\n * Reset the dehydration key.\n *\n * Creates a new key and stores it in secret storage.\n *\n * @returns The newly-generated key.\n */\n public async resetKey(): Promise<RustSdkCryptoJs.DehydratedDeviceKey> {\n const key = RustSdkCryptoJs.DehydratedDeviceKey.createRandomKey();\n await this.secretStorage.store(SECRET_STORAGE_NAME, key.toBase64());\n // Also cache it in the rust SDK's crypto store.\n await this.cacheKey(key);\n return key;\n }\n\n /**\n * Get and cache the encryption key from secret storage.\n *\n * If `create` is `true`, creates a new key if no existing key is present.\n *\n * @returns the key, if available, or `null` if no key is available\n */\n private async getKey(create: boolean): Promise<RustSdkCryptoJs.DehydratedDeviceKey | null> {\n const cachedKey = await this.olmMachine.dehydratedDevices().getDehydratedDeviceKey();\n if (cachedKey) return cachedKey;\n const keyB64 = await this.secretStorage.get(SECRET_STORAGE_NAME);\n if (keyB64 === undefined) {\n if (!create) {\n return null;\n }\n return await this.resetKey();\n }\n\n // We successfully found the key in secret storage: decode it, and cache it in\n // the rust SDK's crypto store.\n const bytes = decodeBase64(keyB64);\n try {\n const key = RustSdkCryptoJs.DehydratedDeviceKey.createKeyFromArray(bytes);\n await this.cacheKey(key);\n return key;\n } finally {\n bytes.fill(0);\n }\n }\n\n /**\n * Rehydrate the dehydrated device stored on the server.\n *\n * Checks if there is a dehydrated device on the server. If so, rehydrates\n * the device and processes the to-device events.\n *\n * Returns whether or not a dehydrated device was found.\n */\n public async rehydrateDeviceIfAvailable(): Promise<boolean> {\n const key = await this.getKey(false);\n if (!key) {\n return false;\n }\n\n let dehydratedDeviceResp;\n try {\n dehydratedDeviceResp = await this.http.authedRequest<DehydratedDeviceResp>(\n Method.Get,\n \"/dehydrated_device\",\n undefined,\n undefined,\n {\n prefix: UnstablePrefix,\n },\n );\n } catch (error) {\n const err = error as MatrixError;\n // We ignore M_NOT_FOUND (there is no dehydrated device, so nothing\n // us to do) and M_UNRECOGNIZED (the server does not understand the\n // endpoint). We pass through any other errors.\n if (err.errcode === \"M_NOT_FOUND\" || err.errcode === \"M_UNRECOGNIZED\") {\n this.logger.info(\"dehydration: No dehydrated device\");\n return false;\n }\n throw err;\n }\n\n this.logger.info(\"dehydration: dehydrated device found\");\n this.emit(CryptoEvent.RehydrationStarted);\n\n const rehydratedDevice = await this.olmMachine\n .dehydratedDevices()\n .rehydrate(\n key,\n new RustSdkCryptoJs.DeviceId(dehydratedDeviceResp.device_id),\n JSON.stringify(dehydratedDeviceResp.device_data),\n );\n\n this.logger.info(\"dehydration: device rehydrated\");\n\n let nextBatch: string | undefined = undefined;\n let toDeviceCount = 0;\n let roomKeyCount = 0;\n const path = encodeUri(\"/dehydrated_device/$device_id/events\", {\n $device_id: dehydratedDeviceResp.device_id,\n });\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const eventResp: DehydratedDeviceEventsResp = await this.http.authedRequest<DehydratedDeviceEventsResp>(\n Method.Post,\n path,\n undefined,\n nextBatch ? { next_batch: nextBatch } : {},\n {\n prefix: UnstablePrefix,\n },\n );\n\n if (eventResp.events.length === 0) {\n break;\n }\n toDeviceCount += eventResp.events.length;\n nextBatch = eventResp.next_batch;\n const roomKeyInfos = await rehydratedDevice.receiveEvents(JSON.stringify(eventResp.events));\n roomKeyCount += roomKeyInfos.length;\n\n this.emit(CryptoEvent.RehydrationProgress, roomKeyCount, toDeviceCount);\n }\n this.logger.info(`dehydration: received ${roomKeyCount} room keys from ${toDeviceCount} to-device events`);\n this.emit(CryptoEvent.RehydrationCompleted);\n\n return true;\n }\n\n /**\n * Creates and uploads a new dehydrated device.\n *\n * Creates and stores a new key in secret storage if none is available.\n */\n public async createAndUploadDehydratedDevice(): Promise<void> {\n const key = (await this.getKey(true))!;\n\n const dehydratedDevice = await this.olmMachine.dehydratedDevices().create();\n this.emit(CryptoEvent.DehydratedDeviceCreated);\n const request = await dehydratedDevice.keysForUpload(\"Dehydrated device\", key);\n\n await this.outgoingRequestProcessor.makeOutgoingRequest(request);\n this.emit(CryptoEvent.DehydratedDeviceUploaded);\n\n this.logger.info(\"dehydration: uploaded device\");\n }\n\n /**\n * Schedule periodic creation of dehydrated devices.\n */\n public async scheduleDeviceDehydration(): Promise<void> {\n // cancel any previously-scheduled tasks\n this.stop();\n\n await this.createAndUploadDehydratedDevice();\n this.intervalId = setInterval(() => {\n this.createAndUploadDehydratedDevice().catch((error) => {\n this.emit(CryptoEvent.DehydratedDeviceRotationError, error.message);\n this.logger.error(\"Error creating dehydrated device:\", error);\n });\n }, DEHYDRATION_INTERVAL);\n }\n\n /**\n * Stop the dehydrated device manager.\n *\n * Cancels any scheduled dehydration tasks.\n */\n public stop(): void {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = undefined;\n }\n }\n\n /**\n * Delete the current dehydrated device and stop the dehydrated device manager.\n */\n public async delete(): Promise<void> {\n this.stop();\n try {\n await this.http.authedRequest(\n Method.Delete,\n \"/dehydrated_device\",\n undefined,\n {},\n {\n prefix: UnstablePrefix,\n },\n );\n } catch (error) {\n const err = error as MatrixError;\n // If dehydrated devices aren't supported, or no dehydrated device\n // is found, we don't consider it an error, because we we'll end up\n // with no dehydrated device.\n if (err.errcode === \"M_UNRECOGNIZED\") {\n return;\n } else if (err.errcode === \"M_NOT_FOUND\") {\n return;\n }\n throw error;\n }\n }\n}\n\n/**\n * The events fired by the DehydratedDeviceManager\n * @internal\n */\ntype DehydratedDevicesEvents =\n | CryptoEvent.DehydratedDeviceCreated\n | CryptoEvent.DehydratedDeviceUploaded\n | CryptoEvent.RehydrationStarted\n | CryptoEvent.RehydrationProgress\n | CryptoEvent.RehydrationCompleted\n | CryptoEvent.RehydrationError\n | CryptoEvent.DehydrationKeyCached\n | CryptoEvent.DehydratedDeviceRotationError;\n\n/**\n * A map of the {@link DehydratedDeviceEvents} fired by the {@link DehydratedDeviceManager} and their payloads.\n * @internal\n */\ntype DehydratedDevicesEventMap = Pick<CryptoEventHandlerMap, DehydratedDevicesEvents>;\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA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EtB,oBAAoB,CAAC;IAAC;EAC7B;;EAEA;AACJ;AACA;AACA;AACA;EACWkC,IAAIA,CAAA,EAAS;IAChB,IAAI,IAAI,CAAC2D,UAAU,EAAE;MACjBI,aAAa,CAAC,IAAI,CAACJ,UAAU,CAAC;MAC9B,IAAI,CAACA,UAAU,GAAGzE,SAAS;IAC/B;EACJ;;EAEA;AACJ;AACA;EACiB8E,MAAMA,CAAA,EAAkB;IAAA,IAAAC,MAAA;IAAA,OAAAxF,iBAAA;MACjCwF,MAAI,CAACjE,IAAI,CAAC,CAAC;MACX,IAAI;QACA,MAAMiE,MAAI,CAAC9F,IAAI,CAACa,aAAa,CACzBxB,MAAM,CAAC0G,MAAM,EACb,oBAAoB,EACpBhF,SAAS,EACT,CAAC,CAAC,EACF;UACIC,MAAM,EAAEvB;QACZ,CACJ,CAAC;MACL,CAAC,CAAC,OAAOwB,KAAK,EAAE;QACZ,IAAMC,GAAG,GAAGD,KAAoB;QAChC;QACA;QACA;QACA,IAAIC,GAAG,CAACC,OAAO,KAAK,gBAAgB,EAAE;UAClC;QACJ,CAAC,MAAM,IAAID,GAAG,CAACC,OAAO,KAAK,aAAa,EAAE;UACtC;QACJ;QACA,MAAMF,KAAK;MACf;IAAC;EACL;AACJ;;AAEA;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"DehydratedDeviceManager.js","names":["RustSdkCryptoJs","encodeUri","Method","decodeBase64","CryptoEvent","TypedEventEmitter","UnstablePrefix","SECRET_STORAGE_NAME","DEHYDRATION_INTERVAL","DehydratedDeviceManager","constructor","logger","olmMachine","http","outgoingRequestProcessor","secretStorage","_defineProperty","cacheKey","key","_this","_asyncToGenerator","dehydratedDevices","saveDehydratedDeviceKey","emit","DehydrationKeyCached","isSupported","_this2","authedRequest","Get","undefined","prefix","error","err","errcode","start","_arguments","arguments","_this3","opts","length","createNewKey","onlyIfKeyCached","getDehydratedDeviceKey","stop","rehydrate","rehydrateDeviceIfAvailable","e","info","RehydrationError","message","resetKey","scheduleDeviceDehydration","isKeyStored","_this4","Boolean","isStored","_this5","DehydratedDeviceKey","createRandomKey","store","toBase64","getKey","create","_this6","cachedKey","keyB64","get","bytes","createKeyFromArray","fill","_this7","dehydratedDeviceResp","RehydrationStarted","rehydratedDevice","DeviceId","device_id","JSON","stringify","device_data","nextBatch","toDeviceCount","roomKeyCount","path","$device_id","eventResp","Post","next_batch","events","roomKeyInfos","receiveEvents","RehydrationProgress","concat","RehydrationCompleted","createAndUploadDehydratedDevice","_this8","dehydratedDevice","DehydratedDeviceCreated","request","keysForUpload","makeOutgoingRequest","DehydratedDeviceUploaded","_this9","intervalId","setInterval","catch","DehydratedDeviceRotationError","clearInterval","delete","_this0","Delete"],"sources":["../../src/rust-crypto/DehydratedDeviceManager.ts"],"sourcesContent":["/*\nCopyright 2024 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 * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport { type OutgoingRequestProcessor } from \"./OutgoingRequestProcessor.ts\";\nimport { encodeUri } from \"../utils.ts\";\nimport { type IHttpOpts, type MatrixError, type MatrixHttpApi, Method } from \"../http-api/index.ts\";\nimport { type IToDeviceEvent } from \"../sync-accumulator.ts\";\nimport { type ServerSideSecretStorage } from \"../secret-storage.ts\";\nimport { decodeBase64 } from \"../base64.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { CryptoEvent, type CryptoEventHandlerMap, type StartDehydrationOpts } from \"../crypto-api/index.ts\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\n\n/**\n * The response body of `GET /_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device`.\n */\ninterface DehydratedDeviceResp {\n device_id: string;\n device_data: {\n algorithm: string;\n };\n}\n/**\n * The response body of `POST /_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device/events`.\n */\ninterface DehydratedDeviceEventsResp {\n events: IToDeviceEvent[];\n next_batch: string;\n}\n\n/**\n * The unstable URL prefix for dehydrated device endpoints\n */\nexport const UnstablePrefix = \"/_matrix/client/unstable/org.matrix.msc3814.v1\";\n/**\n * The name used for the dehydration key in Secret Storage\n */\nconst SECRET_STORAGE_NAME = \"org.matrix.msc3814\";\n\n/**\n * The interval between creating dehydrated devices. (one week)\n */\nconst DEHYDRATION_INTERVAL = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Manages dehydrated devices\n *\n * We have one of these per `RustCrypto`. It's responsible for\n *\n * * determining server support for dehydrated devices\n * * creating new dehydrated devices when requested, including periodically\n * replacing the dehydrated device with a new one\n * * rehydrating a device when requested, and when present\n *\n * @internal\n */\nexport class DehydratedDeviceManager extends TypedEventEmitter<DehydratedDevicesEvents, DehydratedDevicesEventMap> {\n /** the ID of the interval for periodically replacing the dehydrated device */\n private intervalId?: ReturnType<typeof setInterval>;\n\n public constructor(\n private readonly logger: Logger,\n private readonly olmMachine: RustSdkCryptoJs.OlmMachine,\n private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,\n private readonly outgoingRequestProcessor: OutgoingRequestProcessor,\n private readonly secretStorage: ServerSideSecretStorage,\n ) {\n super();\n }\n\n private async cacheKey(key: RustSdkCryptoJs.DehydratedDeviceKey): Promise<void> {\n await this.olmMachine.dehydratedDevices().saveDehydratedDeviceKey(key);\n this.emit(CryptoEvent.DehydrationKeyCached);\n }\n\n /**\n * Return whether the server supports dehydrated devices.\n */\n public async isSupported(): Promise<boolean> {\n // call the endpoint to get a dehydrated device. If it returns an\n // M_UNRECOGNIZED error, then dehydration is unsupported. If it returns\n // a successful response, or an M_NOT_FOUND, then dehydration is supported.\n // Any other exceptions are passed through.\n try {\n await this.http.authedRequest<DehydratedDeviceResp>(\n Method.Get,\n \"/dehydrated_device\",\n undefined,\n undefined,\n {\n prefix: UnstablePrefix,\n },\n );\n } catch (error) {\n const err = error as MatrixError;\n if (err.errcode === \"M_UNRECOGNIZED\") {\n return false;\n } else if (err.errcode === \"M_NOT_FOUND\") {\n return true;\n }\n throw error;\n }\n return true;\n }\n\n /**\n * Start using device dehydration.\n *\n * - Rehydrates a dehydrated device, if one is available and `opts.rehydrate`\n * is `true`.\n * - Creates a new dehydration key, if necessary, and stores it in Secret\n * Storage.\n * - If `opts.createNewKey` is set to true, always creates a new key.\n * - If a dehydration key is not available, creates a new one.\n * - Creates a new dehydrated device, and schedules periodically creating\n * new dehydrated devices.\n *\n * @param opts - options for device dehydration. For backwards compatibility\n * with old code, a boolean can be given here, which will be treated as\n * the `createNewKey` option. However, this is deprecated.\n */\n public async start(opts: StartDehydrationOpts | boolean = {}): Promise<void> {\n if (typeof opts === \"boolean\") {\n opts = { createNewKey: opts };\n }\n\n if (opts.onlyIfKeyCached && !(await this.olmMachine.dehydratedDevices().getDehydratedDeviceKey())) {\n return;\n }\n this.stop();\n if (opts.rehydrate !== false) {\n try {\n await this.rehydrateDeviceIfAvailable();\n } catch (e) {\n // If rehydration fails, there isn't much we can do about it. Log\n // the error, and create a new device.\n this.logger.info(\"dehydration: Error rehydrating device:\", e);\n this.emit(CryptoEvent.RehydrationError, (e as Error).message);\n }\n }\n if (opts.createNewKey) {\n await this.resetKey();\n }\n await this.scheduleDeviceDehydration();\n }\n\n /**\n * Return whether the dehydration key is stored in Secret Storage.\n */\n public async isKeyStored(): Promise<boolean> {\n return Boolean(await this.secretStorage.isStored(SECRET_STORAGE_NAME));\n }\n\n /**\n * Reset the dehydration key.\n *\n * Creates a new key and stores it in secret storage.\n *\n * @returns The newly-generated key.\n */\n public async resetKey(): Promise<RustSdkCryptoJs.DehydratedDeviceKey> {\n const key = RustSdkCryptoJs.DehydratedDeviceKey.createRandomKey();\n await this.secretStorage.store(SECRET_STORAGE_NAME, key.toBase64());\n // Also cache it in the rust SDK's crypto store.\n await this.cacheKey(key);\n return key;\n }\n\n /**\n * Get and cache the encryption key from secret storage.\n *\n * If `create` is `true`, creates a new key if no existing key is present.\n *\n * @returns the key, if available, or `null` if no key is available\n */\n private async getKey(create: boolean): Promise<RustSdkCryptoJs.DehydratedDeviceKey | null> {\n const cachedKey = await this.olmMachine.dehydratedDevices().getDehydratedDeviceKey();\n if (cachedKey) return cachedKey;\n const keyB64 = await this.secretStorage.get(SECRET_STORAGE_NAME);\n if (keyB64 === undefined) {\n if (!create) {\n return null;\n }\n return await this.resetKey();\n }\n\n // We successfully found the key in secret storage: decode it, and cache it in\n // the rust SDK's crypto store.\n const bytes = decodeBase64(keyB64);\n try {\n const key = RustSdkCryptoJs.DehydratedDeviceKey.createKeyFromArray(bytes);\n await this.cacheKey(key);\n return key;\n } finally {\n bytes.fill(0);\n }\n }\n\n /**\n * Rehydrate the dehydrated device stored on the server.\n *\n * Checks if there is a dehydrated device on the server. If so, rehydrates\n * the device and processes the to-device events.\n *\n * Returns whether or not a dehydrated device was found.\n */\n public async rehydrateDeviceIfAvailable(): Promise<boolean> {\n const key = await this.getKey(false);\n if (!key) {\n return false;\n }\n\n let dehydratedDeviceResp;\n try {\n dehydratedDeviceResp = await this.http.authedRequest<DehydratedDeviceResp>(\n Method.Get,\n \"/dehydrated_device\",\n undefined,\n undefined,\n {\n prefix: UnstablePrefix,\n },\n );\n } catch (error) {\n const err = error as MatrixError;\n // We ignore M_NOT_FOUND (there is no dehydrated device, so nothing\n // us to do) and M_UNRECOGNIZED (the server does not understand the\n // endpoint). We pass through any other errors.\n if (err.errcode === \"M_NOT_FOUND\" || err.errcode === \"M_UNRECOGNIZED\") {\n this.logger.info(\"dehydration: No dehydrated device\");\n return false;\n }\n throw err;\n }\n\n this.logger.info(\"dehydration: dehydrated device found\");\n this.emit(CryptoEvent.RehydrationStarted);\n\n const rehydratedDevice = await this.olmMachine\n .dehydratedDevices()\n .rehydrate(\n key,\n new RustSdkCryptoJs.DeviceId(dehydratedDeviceResp.device_id),\n JSON.stringify(dehydratedDeviceResp.device_data),\n );\n\n this.logger.info(\"dehydration: device rehydrated\");\n\n let nextBatch: string | undefined = undefined;\n let toDeviceCount = 0;\n let roomKeyCount = 0;\n const path = encodeUri(\"/dehydrated_device/$device_id/events\", {\n $device_id: dehydratedDeviceResp.device_id,\n });\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const eventResp: DehydratedDeviceEventsResp = await this.http.authedRequest<DehydratedDeviceEventsResp>(\n Method.Post,\n path,\n undefined,\n nextBatch ? { next_batch: nextBatch } : {},\n {\n prefix: UnstablePrefix,\n },\n );\n\n if (eventResp.events.length === 0) {\n break;\n }\n toDeviceCount += eventResp.events.length;\n nextBatch = eventResp.next_batch;\n const roomKeyInfos = await rehydratedDevice.receiveEvents(JSON.stringify(eventResp.events));\n roomKeyCount += roomKeyInfos.length;\n\n this.emit(CryptoEvent.RehydrationProgress, roomKeyCount, toDeviceCount);\n }\n this.logger.info(`dehydration: received ${roomKeyCount} room keys from ${toDeviceCount} to-device events`);\n this.emit(CryptoEvent.RehydrationCompleted);\n\n return true;\n }\n\n /**\n * Creates and uploads a new dehydrated device.\n *\n * Creates and stores a new key in secret storage if none is available.\n */\n public async createAndUploadDehydratedDevice(): Promise<void> {\n const key = (await this.getKey(true))!;\n\n const dehydratedDevice = await this.olmMachine.dehydratedDevices().create();\n this.emit(CryptoEvent.DehydratedDeviceCreated);\n const request = await dehydratedDevice.keysForUpload(\"Dehydrated device\", key);\n\n await this.outgoingRequestProcessor.makeOutgoingRequest(request);\n this.emit(CryptoEvent.DehydratedDeviceUploaded);\n\n this.logger.info(\"dehydration: uploaded device\");\n }\n\n /**\n * Schedule periodic creation of dehydrated devices.\n */\n public async scheduleDeviceDehydration(): Promise<void> {\n // cancel any previously-scheduled tasks\n this.stop();\n\n await this.createAndUploadDehydratedDevice();\n this.intervalId = setInterval(() => {\n this.createAndUploadDehydratedDevice().catch((error) => {\n this.emit(CryptoEvent.DehydratedDeviceRotationError, error.message);\n this.logger.error(\"Error creating dehydrated device:\", error);\n });\n }, DEHYDRATION_INTERVAL);\n }\n\n /**\n * Stop the dehydrated device manager.\n *\n * Cancels any scheduled dehydration tasks.\n */\n public stop(): void {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = undefined;\n }\n }\n\n /**\n * Delete the current dehydrated device and stop the dehydrated device manager.\n */\n public async delete(): Promise<void> {\n this.stop();\n try {\n await this.http.authedRequest(\n Method.Delete,\n \"/dehydrated_device\",\n undefined,\n {},\n {\n prefix: UnstablePrefix,\n },\n );\n } catch (error) {\n const err = error as MatrixError;\n // If dehydrated devices aren't supported, or no dehydrated device\n // is found, we don't consider it an error, because we we'll end up\n // with no dehydrated device.\n if (err.errcode === \"M_UNRECOGNIZED\") {\n return;\n } else if (err.errcode === \"M_NOT_FOUND\") {\n return;\n }\n throw error;\n }\n }\n}\n\n/**\n * The events fired by the DehydratedDeviceManager\n * @internal\n */\ntype DehydratedDevicesEvents =\n | CryptoEvent.DehydratedDeviceCreated\n | CryptoEvent.DehydratedDeviceUploaded\n | CryptoEvent.RehydrationStarted\n | CryptoEvent.RehydrationProgress\n | CryptoEvent.RehydrationCompleted\n | CryptoEvent.RehydrationError\n | CryptoEvent.DehydrationKeyCached\n | CryptoEvent.DehydratedDeviceRotationError;\n\n/**\n * A map of the {@link DehydratedDeviceEvents} fired by the {@link DehydratedDeviceManager} and their payloads.\n * @internal\n */\ntype DehydratedDevicesEventMap = Pick<CryptoEventHandlerMap, DehydratedDevicesEvents>;\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAO,KAAKA,eAAe,MAAM,oCAAoC;AAGrE,SAASC,SAAS,QAAQ,aAAa;AACvC,SAA+DC,MAAM,Q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S;IAChB,IAAI,IAAI,CAAC2D,UAAU,EAAE;MACjBI,aAAa,CAAC,IAAI,CAACJ,UAAU,CAAC;MAC9B,IAAI,CAACA,UAAU,GAAGzE,SAAS;IAC/B;EACJ;;EAEA;AACJ;AACA;EACiB8E,MAAMA,CAAA,EAAkB;IAAA,IAAAC,MAAA;IAAA,OAAAxF,iBAAA;MACjCwF,MAAI,CAACjE,IAAI,CAAC,CAAC;MACX,IAAI;QACA,MAAMiE,MAAI,CAAC/F,IAAI,CAACc,aAAa,CACzBzB,MAAM,CAAC2G,MAAM,EACb,oBAAoB,EACpBhF,SAAS,EACT,CAAC,CAAC,EACF;UACIC,MAAM,EAAExB;QACZ,CACJ,CAAC;MACL,CAAC,CAAC,OAAOyB,KAAK,EAAE;QACZ,IAAMC,GAAG,GAAGD,KAAoB;QAChC;QACA;QACA;QACA,IAAIC,GAAG,CAACC,OAAO,KAAK,gBAAgB,EAAE;UAClC;QACJ,CAAC,MAAM,IAAID,GAAG,CAACC,OAAO,KAAK,aAAa,EAAE;UACtC;QACJ;QACA,MAAMF,KAAK;MACf;IAAC;EACL;AACJ;;AAEA;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA","ignoreList":[]}
|
|
@@ -25,9 +25,10 @@ limitations under the License.
|
|
|
25
25
|
*/
|
|
26
26
|
export class KeyClaimManager {
|
|
27
27
|
constructor(olmMachine, outgoingRequestProcessor) {
|
|
28
|
-
_defineProperty(this, "stopped", false);
|
|
29
28
|
this.olmMachine = olmMachine;
|
|
30
29
|
this.outgoingRequestProcessor = outgoingRequestProcessor;
|
|
30
|
+
_defineProperty(this, "currentClaimPromise", void 0);
|
|
31
|
+
_defineProperty(this, "stopped", false);
|
|
31
32
|
this.currentClaimPromise = Promise.resolve();
|
|
32
33
|
}
|
|
33
34
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"KeyClaimManager.js","names":["KeyClaimManager","constructor","olmMachine","outgoingRequestProcessor","_defineProperty","currentClaimPromise","Promise","resolve","stop","stopped","ensureSessionsForUsers","logger","userList","prom","catch","then","ensureSessionsForUsersInner","_this","_asyncToGenerator","Error","info","claimRequest","getMissingSessions","map","u","clone","makeOutgoingRequest"],"sources":["../../src/rust-crypto/KeyClaimManager.ts"],"sourcesContent":["/*\nCopyright 2023 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 { type OlmMachine, type UserId } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport { type OutgoingRequestProcessor } from \"./OutgoingRequestProcessor.ts\";\nimport { type LogSpan } from \"../logger.ts\";\n\n/**\n * KeyClaimManager: linearises calls to OlmMachine.getMissingSessions to avoid races\n *\n * We have one of these per `RustCrypto` (and hence per `MatrixClient`).\n *\n * @internal\n */\nexport class KeyClaimManager {\n private currentClaimPromise: Promise<void>;\n private stopped = false;\n\n public constructor(\n private readonly olmMachine: OlmMachine,\n private readonly outgoingRequestProcessor: OutgoingRequestProcessor,\n ) {\n this.currentClaimPromise = Promise.resolve();\n }\n\n /**\n * Tell the KeyClaimManager to immediately stop processing requests.\n *\n * Any further calls, and any still in the queue, will fail with an error.\n */\n public stop(): void {\n this.stopped = true;\n }\n\n /**\n * Given a list of users, attempt to ensure that we have Olm Sessions active with each of their devices\n *\n * If we don't have an active olm session, we will claim a one-time key and start one.\n * @param logger - logger to use\n * @param userList - list of userIDs to claim\n */\n public ensureSessionsForUsers(logger: LogSpan, userList: Array<UserId>): Promise<void> {\n // The Rust-SDK requires that we only have one getMissingSessions process in flight at once. This little dance\n // ensures that, by only having one call to ensureSessionsForUsersInner active at once (and making them\n // queue up in order).\n const prom = this.currentClaimPromise\n .catch(() => {\n // any errors in the previous claim will have been reported already, so there is nothing to do here.\n // we just throw away the error and start anew.\n })\n .then(() => this.ensureSessionsForUsersInner(logger, userList));\n this.currentClaimPromise = prom;\n return prom;\n }\n\n private async ensureSessionsForUsersInner(logger: LogSpan, userList: Array<UserId>): Promise<void> {\n // bail out quickly if we've been stopped.\n if (this.stopped) {\n throw new Error(`Cannot ensure Olm sessions: shutting down`);\n }\n logger.info(\"Checking for missing Olm sessions\");\n // By passing the userId array to rust we transfer ownership of the items to rust, causing\n // them to be invalidated on the JS side as soon as the method is called.\n // As we haven't created the `userList` let's clone the users, to not break the caller from re-using it.\n const claimRequest = await this.olmMachine.getMissingSessions(userList.map((u) => u.clone()));\n if (claimRequest) {\n logger.info(\"Making /keys/claim request\");\n await this.outgoingRequestProcessor.makeOutgoingRequest(claimRequest);\n }\n logger.info(\"Olm sessions prepared\");\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMA,eAAe,CAAC;EAIlBC,WAAWA,CACGC,UAAsB,EACtBC,wBAAkD,EACrE;
|
|
1
|
+
{"version":3,"file":"KeyClaimManager.js","names":["KeyClaimManager","constructor","olmMachine","outgoingRequestProcessor","_defineProperty","currentClaimPromise","Promise","resolve","stop","stopped","ensureSessionsForUsers","logger","userList","prom","catch","then","ensureSessionsForUsersInner","_this","_asyncToGenerator","Error","info","claimRequest","getMissingSessions","map","u","clone","makeOutgoingRequest"],"sources":["../../src/rust-crypto/KeyClaimManager.ts"],"sourcesContent":["/*\nCopyright 2023 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 { type OlmMachine, type UserId } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport { type OutgoingRequestProcessor } from \"./OutgoingRequestProcessor.ts\";\nimport { type LogSpan } from \"../logger.ts\";\n\n/**\n * KeyClaimManager: linearises calls to OlmMachine.getMissingSessions to avoid races\n *\n * We have one of these per `RustCrypto` (and hence per `MatrixClient`).\n *\n * @internal\n */\nexport class KeyClaimManager {\n private currentClaimPromise: Promise<void>;\n private stopped = false;\n\n public constructor(\n private readonly olmMachine: OlmMachine,\n private readonly outgoingRequestProcessor: OutgoingRequestProcessor,\n ) {\n this.currentClaimPromise = Promise.resolve();\n }\n\n /**\n * Tell the KeyClaimManager to immediately stop processing requests.\n *\n * Any further calls, and any still in the queue, will fail with an error.\n */\n public stop(): void {\n this.stopped = true;\n }\n\n /**\n * Given a list of users, attempt to ensure that we have Olm Sessions active with each of their devices\n *\n * If we don't have an active olm session, we will claim a one-time key and start one.\n * @param logger - logger to use\n * @param userList - list of userIDs to claim\n */\n public ensureSessionsForUsers(logger: LogSpan, userList: Array<UserId>): Promise<void> {\n // The Rust-SDK requires that we only have one getMissingSessions process in flight at once. This little dance\n // ensures that, by only having one call to ensureSessionsForUsersInner active at once (and making them\n // queue up in order).\n const prom = this.currentClaimPromise\n .catch(() => {\n // any errors in the previous claim will have been reported already, so there is nothing to do here.\n // we just throw away the error and start anew.\n })\n .then(() => this.ensureSessionsForUsersInner(logger, userList));\n this.currentClaimPromise = prom;\n return prom;\n }\n\n private async ensureSessionsForUsersInner(logger: LogSpan, userList: Array<UserId>): Promise<void> {\n // bail out quickly if we've been stopped.\n if (this.stopped) {\n throw new Error(`Cannot ensure Olm sessions: shutting down`);\n }\n logger.info(\"Checking for missing Olm sessions\");\n // By passing the userId array to rust we transfer ownership of the items to rust, causing\n // them to be invalidated on the JS side as soon as the method is called.\n // As we haven't created the `userList` let's clone the users, to not break the caller from re-using it.\n const claimRequest = await this.olmMachine.getMissingSessions(userList.map((u) => u.clone()));\n if (claimRequest) {\n logger.info(\"Making /keys/claim request\");\n await this.outgoingRequestProcessor.makeOutgoingRequest(claimRequest);\n }\n logger.info(\"Olm sessions prepared\");\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMA,eAAe,CAAC;EAIlBC,WAAWA,CACGC,UAAsB,EACtBC,wBAAkD,EACrE;IAAA,KAFmBD,UAAsB,GAAtBA,UAAsB;IAAA,KACtBC,wBAAkD,GAAlDA,wBAAkD;IAAAC,eAAA;IAAAA,eAAA,kBAJrD,KAAK;IAMnB,IAAI,CAACC,mBAAmB,GAAGC,OAAO,CAACC,OAAO,CAAC,CAAC;EAChD;;EAEA;AACJ;AACA;AACA;AACA;EACWC,IAAIA,CAAA,EAAS;IAChB,IAAI,CAACC,OAAO,GAAG,IAAI;EACvB;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;EACWC,sBAAsBA,CAACC,MAAe,EAAEC,QAAuB,EAAiB;IACnF;IACA;IACA;IACA,IAAMC,IAAI,GAAG,IAAI,CAACR,mBAAmB,CAChCS,KAAK,CAAC,MAAM;MACT;MACA;IAAA,CACH,CAAC,CACDC,IAAI,CAAC,MAAM,IAAI,CAACC,2BAA2B,CAACL,MAAM,EAAEC,QAAQ,CAAC,CAAC;IACnE,IAAI,CAACP,mBAAmB,GAAGQ,IAAI;IAC/B,OAAOA,IAAI;EACf;EAEcG,2BAA2BA,CAACL,MAAe,EAAEC,QAAuB,EAAiB;IAAA,IAAAK,KAAA;IAAA,OAAAC,iBAAA;MAC/F;MACA,IAAID,KAAI,CAACR,OAAO,EAAE;QACd,MAAM,IAAIU,KAAK,4CAA4C,CAAC;MAChE;MACAR,MAAM,CAACS,IAAI,CAAC,mCAAmC,CAAC;MAChD;MACA;MACA;MACA,IAAMC,YAAY,SAASJ,KAAI,CAACf,UAAU,CAACoB,kBAAkB,CAACV,QAAQ,CAACW,GAAG,CAAEC,CAAC,IAAKA,CAAC,CAACC,KAAK,CAAC,CAAC,CAAC,CAAC;MAC7F,IAAIJ,YAAY,EAAE;QACdV,MAAM,CAACS,IAAI,CAAC,4BAA4B,CAAC;QACzC,MAAMH,KAAI,CAACd,wBAAwB,CAACuB,mBAAmB,CAACL,YAAY,CAAC;MACzE;MACAV,MAAM,CAACS,IAAI,CAAC,uBAAuB,CAAC;IAAC;EACzC;AACJ","ignoreList":[]}
|
|
@@ -23,23 +23,23 @@ import { logDuration } from "../utils.js";
|
|
|
23
23
|
* Ensure that only one loop is going on at once, and that the requests are processed in order.
|
|
24
24
|
*/
|
|
25
25
|
export class OutgoingRequestsManager {
|
|
26
|
-
/**
|
|
27
|
-
* If there are additional calls to doProcessOutgoingRequests() while there is a current call running
|
|
28
|
-
* we need to remember in order to call `doProcessOutgoingRequests` again (as there could be new requests).
|
|
29
|
-
*
|
|
30
|
-
* If this is defined, it is an indication that we need to do another iteration; in this case the deferred
|
|
31
|
-
* will resolve once that next iteration completes. If it is undefined, there have been no new calls
|
|
32
|
-
* to `doProcessOutgoingRequests` since the current iteration started.
|
|
33
|
-
*/
|
|
34
|
-
|
|
35
26
|
constructor(logger, olmMachine, outgoingRequestProcessor) {
|
|
27
|
+
this.logger = logger;
|
|
28
|
+
this.olmMachine = olmMachine;
|
|
29
|
+
this.outgoingRequestProcessor = outgoingRequestProcessor;
|
|
36
30
|
/** whether {@link stop} has been called */
|
|
37
31
|
_defineProperty(this, "stopped", false);
|
|
38
32
|
/** whether {@link outgoingRequestLoop} is currently running */
|
|
39
33
|
_defineProperty(this, "outgoingRequestLoopRunning", false);
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
34
|
+
/**
|
|
35
|
+
* If there are additional calls to doProcessOutgoingRequests() while there is a current call running
|
|
36
|
+
* we need to remember in order to call `doProcessOutgoingRequests` again (as there could be new requests).
|
|
37
|
+
*
|
|
38
|
+
* If this is defined, it is an indication that we need to do another iteration; in this case the deferred
|
|
39
|
+
* will resolve once that next iteration completes. If it is undefined, there have been no new calls
|
|
40
|
+
* to `doProcessOutgoingRequests` since the current iteration started.
|
|
41
|
+
*/
|
|
42
|
+
_defineProperty(this, "nextLoopDeferred", void 0);
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OutgoingRequestsManager.js","names":["logDuration","OutgoingRequestsManager","constructor","logger","olmMachine","outgoingRequestProcessor","_defineProperty","stop","stopped","doProcessOutgoingRequests","nextLoopDeferred","Promise","withResolvers","result","promise","outgoingRequestLoopRunning","outgoingRequestLoop","catch","e","error","_this","_asyncToGenerator","Error","loopTickResolvers","undefined","processOutgoingRequests","then","resolve","reject","_this2","outgoingRequests","successes","_loop","request","v","concat","type","makeOutgoingRequest","_ret","warn"],"sources":["../../src/rust-crypto/OutgoingRequestsManager.ts"],"sourcesContent":["/*\nCopyright 2023 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 { type OlmMachine, type OutgoingRequest } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport { type OutgoingRequestProcessor } from \"./OutgoingRequestProcessor.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { logDuration } from \"../utils.ts\";\n\n/**\n * OutgoingRequestsManager: responsible for processing outgoing requests from the OlmMachine.\n * Ensure that only one loop is going on at once, and that the requests are processed in order.\n */\nexport class OutgoingRequestsManager {\n /** whether {@link stop} has been called */\n private stopped = false;\n\n /** whether {@link outgoingRequestLoop} is currently running */\n private outgoingRequestLoopRunning = false;\n\n /**\n * If there are additional calls to doProcessOutgoingRequests() while there is a current call running\n * we need to remember in order to call `doProcessOutgoingRequests` again (as there could be new requests).\n *\n * If this is defined, it is an indication that we need to do another iteration; in this case the deferred\n * will resolve once that next iteration completes. If it is undefined, there have been no new calls\n * to `doProcessOutgoingRequests` since the current iteration started.\n */\n private nextLoopDeferred?: PromiseWithResolvers<void>;\n\n public constructor(\n private readonly logger: Logger,\n private readonly olmMachine: OlmMachine,\n public readonly outgoingRequestProcessor: OutgoingRequestProcessor,\n ) {}\n\n /**\n * Shut down as soon as possible the current loop of outgoing requests processing.\n */\n public stop(): void {\n this.stopped = true;\n }\n\n /**\n * Process the OutgoingRequests from the OlmMachine.\n *\n * This should be called at the end of each sync, to process any OlmMachine OutgoingRequests created by the rust sdk.\n * In some cases if OutgoingRequests need to be sent immediately, this can be called directly.\n *\n * Calls to doProcessOutgoingRequests() are processed synchronously, one after the other, in order.\n * If doProcessOutgoingRequests() is called while another call is still being processed, it will be queued.\n * Multiple calls to doProcessOutgoingRequests() when a call is already processing will be batched together.\n */\n public doProcessOutgoingRequests(): Promise<void> {\n // Flag that we need at least one more iteration of the loop.\n //\n // It is important that we do this even if the loop is currently running. There is potential for a race whereby\n // a request is added to the queue *after* `OlmMachine.outgoingRequests` checks the queue, but *before* it\n // returns. In such a case, the item could sit there unnoticed for some time.\n //\n // In order to circumvent the race, we set a flag which tells the loop to go round once again even if the\n // queue appears to be empty.\n if (!this.nextLoopDeferred) {\n this.nextLoopDeferred = Promise.withResolvers();\n }\n\n // ... and wait for it to complete.\n const result = this.nextLoopDeferred.promise;\n\n // set the loop going if it is not already.\n if (!this.outgoingRequestLoopRunning) {\n this.outgoingRequestLoop().catch((e) => {\n // this should not happen; outgoingRequestLoop should return any errors via `nextLoopDeferred`.\n /* istanbul ignore next */\n this.logger.error(\"Uncaught error in outgoing request loop\", e);\n });\n }\n return result;\n }\n\n private async outgoingRequestLoop(): Promise<void> {\n /* istanbul ignore if */\n if (this.outgoingRequestLoopRunning) {\n throw new Error(\"Cannot run two outgoing request loops\");\n }\n this.outgoingRequestLoopRunning = true;\n try {\n while (!this.stopped && this.nextLoopDeferred) {\n const loopTickResolvers = this.nextLoopDeferred;\n\n // reset `nextLoopDeferred` so that any future calls to `doProcessOutgoingRequests` are queued\n // for another additional iteration.\n this.nextLoopDeferred = undefined;\n\n // make the requests and feed the results back to the `nextLoopDeferred`\n await this.processOutgoingRequests().then(loopTickResolvers.resolve, loopTickResolvers.reject);\n }\n } finally {\n this.outgoingRequestLoopRunning = false;\n }\n\n if (this.nextLoopDeferred) {\n // the loop was stopped, but there was a call to `doProcessOutgoingRequests`. Make sure that\n // we reject the promise in case anything is waiting for it.\n this.nextLoopDeferred.reject(new Error(\"OutgoingRequestsManager was stopped\"));\n }\n }\n\n /**\n * Make a single request to `olmMachine.outgoingRequests` and do the corresponding requests.\n */\n private async processOutgoingRequests(): Promise<void> {\n if (this.stopped) return;\n\n const outgoingRequests: OutgoingRequest[] = await this.olmMachine.outgoingRequests();\n\n let successes = 0;\n for (const request of outgoingRequests) {\n if (this.stopped) return;\n try {\n await logDuration(this.logger, `Make outgoing request ${request.type}`, async () => {\n await this.outgoingRequestProcessor.makeOutgoingRequest(request);\n successes++;\n });\n } catch (e) {\n // as part of the loop we silently ignore errors, but log them.\n // The rust sdk will retry the request later as it won't have been marked as sent.\n this.logger.error(`Failed to process outgoing request ${request.type}: ${e}`);\n }\n }\n\n // If we successfully handled any requests this time, more may have been queued as\n // part of that handling.\n //\n // For example, we may have processed a `/keys/claim` request, which\n // meant the rust side could establish an Olm session and is now ready to\n // send out an `m.secret.send` message.\n // (See https://github.com/element-hq/element-web/issues/30988.)\n //\n // So, if we have successfully processed any requests, flag that we need to make another\n // pass around the outgoing-requests loop, to make sure we handle any\n // pending requests immediately.\n //\n // If all requests failed (or there weren't any) we don't want to retry them in a tight\n // loop. They will be retried after the next sync.\n // (See https://github.com/element-hq/element-web/issues/31790.)\n if (successes > 0) {\n // We call doProcessOutgoingRequests but since we expect that we are\n // already processing outgoing requests, this call will not kick off\n // the processing loop, but just set `nextLoopDeferred` and return,\n // which will mean we loop one more time.\n this.doProcessOutgoingRequests().catch((e) => {\n this.logger.warn(\"processOutgoingRequests: Error re-checking outgoing requests\", e);\n });\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,WAAW,QAAQ,aAAa;;AAEzC;AACA;AACA;AACA;AACA,OAAO,MAAMC,uBAAuB,CAAC;EAOjC;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;;EAGWC,WAAWA,CACGC,MAAc,EACdC,UAAsB,EACvBC,wBAAkD,EACpE;IApBF;IAAAC,eAAA,kBACkB,KAAK;IAEvB;IAAAA,eAAA,qCACqC,KAAK;IAAA,KAarBH,MAAc,GAAdA,MAAc;IAAA,KACdC,UAAsB,GAAtBA,UAAsB;IAAA,KACvBC,wBAAkD,GAAlDA,wBAAkD;EACnE;;EAEH;AACJ;AACA;EACWE,IAAIA,CAAA,EAAS;IAChB,IAAI,CAACC,OAAO,GAAG,IAAI;EACvB;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACWC,yBAAyBA,CAAA,EAAkB;IAC9C;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,IAAI,CAAC,IAAI,CAACC,gBAAgB,EAAE;MACxB,IAAI,CAACA,gBAAgB,GAAGC,OAAO,CAACC,aAAa,CAAC,CAAC;IACnD;;IAEA;IACA,IAAMC,MAAM,GAAG,IAAI,CAACH,gBAAgB,CAACI,OAAO;;IAE5C;IACA,IAAI,CAAC,IAAI,CAACC,0BAA0B,EAAE;MAClC,IAAI,CAACC,mBAAmB,CAAC,CAAC,CAACC,KAAK,CAAEC,CAAC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MlC,WAAW,CAAC6B,MAAI,CAAC1B,MAAM,2BAAAgC,MAAA,CAA2BF,OAAO,CAACG,IAAI,gBAAAf,iBAAA,CAAI,aAAY;cAChF,MAAMQ,MAAI,CAACxB,wBAAwB,CAACgC,mBAAmB,CAACJ,OAAO,CAAC;cAChEF,SAAS,EAAE;YACf,CAAC,EAAC;UACN,CAAC,CAAC,OAAOb,CAAC,EAAE;YACR;YACA;YACAW,MAAI,CAAC1B,MAAM,CAACgB,KAAK,uCAAAgB,MAAA,CAAuCF,OAAO,CAACG,IAAI,QAAAD,MAAA,CAAKjB,CAAC,CAAE,CAAC;UACjF;QACJ,CAAC;QAAAoB,IAAA;MAZD,KAAK,IAAML,OAAO,IAAIH,gBAAgB;QAAAQ,IAAA,UAAAN,KAAA,CAAAC,OAAA;QAAA,IAAAK,IAAA,SAAAA,IAAA,CAAAJ,CAAA;MAAA;;MActC;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA,IAAIH,SAAS,GAAG,CAAC,EAAE;QACf;QACA;QACA;QACA;QACAF,MAAI,CAACpB,yBAAyB,CAAC,CAAC,CAACQ,KAAK,CAAEC,CAAC,IAAK;UAC1CW,MAAI,CAAC1B,MAAM,CAACoC,IAAI,CAAC,8DAA8D,EAAErB,CAAC,CAAC;QACvF,CAAC,CAAC;MACN;IAAC;EACL;AACJ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"OutgoingRequestsManager.js","names":["logDuration","OutgoingRequestsManager","constructor","logger","olmMachine","outgoingRequestProcessor","_defineProperty","stop","stopped","doProcessOutgoingRequests","nextLoopDeferred","Promise","withResolvers","result","promise","outgoingRequestLoopRunning","outgoingRequestLoop","catch","e","error","_this","_asyncToGenerator","Error","loopTickResolvers","undefined","processOutgoingRequests","then","resolve","reject","_this2","outgoingRequests","successes","_loop","request","v","concat","type","makeOutgoingRequest","_ret","warn"],"sources":["../../src/rust-crypto/OutgoingRequestsManager.ts"],"sourcesContent":["/*\nCopyright 2023 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 { type OlmMachine, type OutgoingRequest } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport { type OutgoingRequestProcessor } from \"./OutgoingRequestProcessor.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { logDuration } from \"../utils.ts\";\n\n/**\n * OutgoingRequestsManager: responsible for processing outgoing requests from the OlmMachine.\n * Ensure that only one loop is going on at once, and that the requests are processed in order.\n */\nexport class OutgoingRequestsManager {\n /** whether {@link stop} has been called */\n private stopped = false;\n\n /** whether {@link outgoingRequestLoop} is currently running */\n private outgoingRequestLoopRunning = false;\n\n /**\n * If there are additional calls to doProcessOutgoingRequests() while there is a current call running\n * we need to remember in order to call `doProcessOutgoingRequests` again (as there could be new requests).\n *\n * If this is defined, it is an indication that we need to do another iteration; in this case the deferred\n * will resolve once that next iteration completes. If it is undefined, there have been no new calls\n * to `doProcessOutgoingRequests` since the current iteration started.\n */\n private nextLoopDeferred?: PromiseWithResolvers<void>;\n\n public constructor(\n private readonly logger: Logger,\n private readonly olmMachine: OlmMachine,\n public readonly outgoingRequestProcessor: OutgoingRequestProcessor,\n ) {}\n\n /**\n * Shut down as soon as possible the current loop of outgoing requests processing.\n */\n public stop(): void {\n this.stopped = true;\n }\n\n /**\n * Process the OutgoingRequests from the OlmMachine.\n *\n * This should be called at the end of each sync, to process any OlmMachine OutgoingRequests created by the rust sdk.\n * In some cases if OutgoingRequests need to be sent immediately, this can be called directly.\n *\n * Calls to doProcessOutgoingRequests() are processed synchronously, one after the other, in order.\n * If doProcessOutgoingRequests() is called while another call is still being processed, it will be queued.\n * Multiple calls to doProcessOutgoingRequests() when a call is already processing will be batched together.\n */\n public doProcessOutgoingRequests(): Promise<void> {\n // Flag that we need at least one more iteration of the loop.\n //\n // It is important that we do this even if the loop is currently running. There is potential for a race whereby\n // a request is added to the queue *after* `OlmMachine.outgoingRequests` checks the queue, but *before* it\n // returns. In such a case, the item could sit there unnoticed for some time.\n //\n // In order to circumvent the race, we set a flag which tells the loop to go round once again even if the\n // queue appears to be empty.\n if (!this.nextLoopDeferred) {\n this.nextLoopDeferred = Promise.withResolvers();\n }\n\n // ... and wait for it to complete.\n const result = this.nextLoopDeferred.promise;\n\n // set the loop going if it is not already.\n if (!this.outgoingRequestLoopRunning) {\n this.outgoingRequestLoop().catch((e) => {\n // this should not happen; outgoingRequestLoop should return any errors via `nextLoopDeferred`.\n /* istanbul ignore next */\n this.logger.error(\"Uncaught error in outgoing request loop\", e);\n });\n }\n return result;\n }\n\n private async outgoingRequestLoop(): Promise<void> {\n /* istanbul ignore if */\n if (this.outgoingRequestLoopRunning) {\n throw new Error(\"Cannot run two outgoing request loops\");\n }\n this.outgoingRequestLoopRunning = true;\n try {\n while (!this.stopped && this.nextLoopDeferred) {\n const loopTickResolvers = this.nextLoopDeferred;\n\n // reset `nextLoopDeferred` so that any future calls to `doProcessOutgoingRequests` are queued\n // for another additional iteration.\n this.nextLoopDeferred = undefined;\n\n // make the requests and feed the results back to the `nextLoopDeferred`\n await this.processOutgoingRequests().then(loopTickResolvers.resolve, loopTickResolvers.reject);\n }\n } finally {\n this.outgoingRequestLoopRunning = false;\n }\n\n if (this.nextLoopDeferred) {\n // the loop was stopped, but there was a call to `doProcessOutgoingRequests`. Make sure that\n // we reject the promise in case anything is waiting for it.\n this.nextLoopDeferred.reject(new Error(\"OutgoingRequestsManager was stopped\"));\n }\n }\n\n /**\n * Make a single request to `olmMachine.outgoingRequests` and do the corresponding requests.\n */\n private async processOutgoingRequests(): Promise<void> {\n if (this.stopped) return;\n\n const outgoingRequests: OutgoingRequest[] = await this.olmMachine.outgoingRequests();\n\n let successes = 0;\n for (const request of outgoingRequests) {\n if (this.stopped) return;\n try {\n await logDuration(this.logger, `Make outgoing request ${request.type}`, async () => {\n await this.outgoingRequestProcessor.makeOutgoingRequest(request);\n successes++;\n });\n } catch (e) {\n // as part of the loop we silently ignore errors, but log them.\n // The rust sdk will retry the request later as it won't have been marked as sent.\n this.logger.error(`Failed to process outgoing request ${request.type}: ${e}`);\n }\n }\n\n // If we successfully handled any requests this time, more may have been queued as\n // part of that handling.\n //\n // For example, we may have processed a `/keys/claim` request, which\n // meant the rust side could establish an Olm session and is now ready to\n // send out an `m.secret.send` message.\n // (See https://github.com/element-hq/element-web/issues/30988.)\n //\n // So, if we have successfully processed any requests, flag that we need to make another\n // pass around the outgoing-requests loop, to make sure we handle any\n // pending requests immediately.\n //\n // If all requests failed (or there weren't any) we don't want to retry them in a tight\n // loop. They will be retried after the next sync.\n // (See https://github.com/element-hq/element-web/issues/31790.)\n if (successes > 0) {\n // We call doProcessOutgoingRequests but since we expect that we are\n // already processing outgoing requests, this call will not kick off\n // the processing loop, but just set `nextLoopDeferred` and return,\n // which will mean we loop one more time.\n this.doProcessOutgoingRequests().catch((e) => {\n this.logger.warn(\"processOutgoingRequests: Error re-checking outgoing requests\", e);\n });\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,WAAW,QAAQ,aAAa;;AAEzC;AACA;AACA;AACA;AACA,OAAO,MAAMC,uBAAuB,CAAC;EAiB1BC,WAAWA,CACGC,MAAc,EACdC,UAAsB,EACvBC,wBAAkD,EACpE;IAAA,KAHmBF,MAAc,GAAdA,MAAc;IAAA,KACdC,UAAsB,GAAtBA,UAAsB;IAAA,KACvBC,wBAAkD,GAAlDA,wBAAkD;IAnBtE;IAAAC,eAAA,kBACkB,KAAK;IAEvB;IAAAA,eAAA,qCACq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QACA;QACA;QACA;QACAF,MAAI,CAACpB,yBAAyB,CAAC,CAAC,CAACQ,KAAK,CAAEC,CAAC,IAAK;UAC1CW,MAAI,CAAC1B,MAAM,CAACoC,IAAI,CAAC,8DAA8D,EAAErB,CAAC,CAAC;QACvF,CAAC,CAAC;MACN;IAAC;EACL;AACJ","ignoreList":[]}
|
|
@@ -77,6 +77,9 @@ export class PerSessionKeyBackupDownloader {
|
|
|
77
77
|
* @param logger - The logger to use.
|
|
78
78
|
*/
|
|
79
79
|
constructor(logger, olmMachine, http, backupManager) {
|
|
80
|
+
this.olmMachine = olmMachine;
|
|
81
|
+
this.http = http;
|
|
82
|
+
this.backupManager = backupManager;
|
|
80
83
|
_defineProperty(this, "stopped", false);
|
|
81
84
|
/**
|
|
82
85
|
* The version and decryption key to use with current backup if all set up correctly.
|
|
@@ -87,6 +90,8 @@ export class PerSessionKeyBackupDownloader {
|
|
|
87
90
|
/** We remember when a session was requested and not found in backup to avoid query again too soon.
|
|
88
91
|
* Map of session_id to timestamp */
|
|
89
92
|
_defineProperty(this, "sessionLastCheckAttemptedTime", new Map());
|
|
93
|
+
/** The logger to use */
|
|
94
|
+
_defineProperty(this, "logger", void 0);
|
|
90
95
|
/** Whether the download loop is running. */
|
|
91
96
|
_defineProperty(this, "downloadLoopRunning", false);
|
|
92
97
|
/** The list of requests that are queued. */
|
|
@@ -110,9 +115,6 @@ export class PerSessionKeyBackupDownloader {
|
|
|
110
115
|
}
|
|
111
116
|
});
|
|
112
117
|
});
|
|
113
|
-
this.olmMachine = olmMachine;
|
|
114
|
-
this.http = http;
|
|
115
|
-
this.backupManager = backupManager;
|
|
116
118
|
this.logger = logger.getChild("[PerSessionKeyBackupDownloader]");
|
|
117
119
|
backupManager.on(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);
|
|
118
120
|
backupManager.on(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);
|