@sableclient/sable-call-embedded 0.16.3-sable.1

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.
Files changed (158) hide show
  1. package/LICENSE-AGPL-3.0 +661 -0
  2. package/LICENSE-COMMERCIAL +6 -0
  3. package/README.md +9 -0
  4. package/dist/assets/IndexedDBWorker-Dgn5IQFp.js +25 -0
  5. package/dist/assets/IndexedDBWorker-Dgn5IQFp.js.map +1 -0
  6. package/dist/assets/baduntss-Ca1ZuBEK.ogg +0 -0
  7. package/dist/assets/baduntss-DOe0oFuS.mp3 +0 -0
  8. package/dist/assets/call_declined-1jWRbd4p.mp3 +0 -0
  9. package/dist/assets/call_declined-C6gHsCGH.ogg +0 -0
  10. package/dist/assets/call_timeout-BCxXxRD8.mp3 +0 -0
  11. package/dist/assets/call_timeout-DPKAj6sz.ogg +0 -0
  12. package/dist/assets/cat-4r_NkDcK.ogg +0 -0
  13. package/dist/assets/cat-Dd8bv_2W.mp3 +0 -0
  14. package/dist/assets/clap-AxCMZLTd.ogg +0 -0
  15. package/dist/assets/clap-Dxm5qGyl.mp3 +0 -0
  16. package/dist/assets/crickets-CcwrRdbq.mp3 +0 -0
  17. package/dist/assets/crickets-DUJdcuUa.ogg +0 -0
  18. package/dist/assets/cs-app-Du_5mVg3.json +236 -0
  19. package/dist/assets/da-app-BBz-lePm.json +236 -0
  20. package/dist/assets/de-app-DjOuqT-j.json +237 -0
  21. package/dist/assets/decimal-CeJ0lJls.js +2 -0
  22. package/dist/assets/decimal-CeJ0lJls.js.map +1 -0
  23. package/dist/assets/deer-91r1Gyrx.mp3 +0 -0
  24. package/dist/assets/deer-DPSlVch4.ogg +0 -0
  25. package/dist/assets/dog-BoQdnF-w.mp3 +0 -0
  26. package/dist/assets/dog-CxIWtkNX.ogg +0 -0
  27. package/dist/assets/el-app-BBr3LLTK.json +122 -0
  28. package/dist/assets/en-app-B0mg0RDM.json +261 -0
  29. package/dist/assets/es-app-Q3c7lmEj.json +88 -0
  30. package/dist/assets/et-app-DLvuR7m2.json +234 -0
  31. package/dist/assets/fi-app-tnO3DMdi.json +224 -0
  32. package/dist/assets/fr-app-BxTYbDfK.json +111 -0
  33. package/dist/assets/generic-BBbS3Wph.ogg +0 -0
  34. package/dist/assets/generic-BFeSb6fL.mp3 +0 -0
  35. package/dist/assets/id-app-BEz8ptLJ.json +223 -0
  36. package/dist/assets/inconsolata-latin-400-normal-DTZQ6lD6.woff2 +0 -0
  37. package/dist/assets/inconsolata-latin-400-normal-HYADljCo.woff +0 -0
  38. package/dist/assets/inconsolata-latin-700-normal-ByjKuJjN.woff2 +0 -0
  39. package/dist/assets/inconsolata-latin-700-normal-DzgUY3Rl.woff +0 -0
  40. package/dist/assets/inconsolata-latin-ext-400-normal-BaHVOdFB.woff2 +0 -0
  41. package/dist/assets/inconsolata-latin-ext-400-normal-yvPjCxxx.woff +0 -0
  42. package/dist/assets/inconsolata-latin-ext-700-normal-D0Kpgs_9.woff2 +0 -0
  43. package/dist/assets/inconsolata-latin-ext-700-normal-Dlt-daqV.woff +0 -0
  44. package/dist/assets/inconsolata-vietnamese-400-normal-ByiM2lek.woff +0 -0
  45. package/dist/assets/inconsolata-vietnamese-400-normal-DfC_iMic.woff2 +0 -0
  46. package/dist/assets/inconsolata-vietnamese-700-normal-DLCFFAUf.woff +0 -0
  47. package/dist/assets/inconsolata-vietnamese-700-normal-DuasYmn8.woff2 +0 -0
  48. package/dist/assets/index-BOka8551.js +4 -0
  49. package/dist/assets/index-BOka8551.js.map +1 -0
  50. package/dist/assets/index-Cn2ez1d4.js +3 -0
  51. package/dist/assets/index-Cn2ez1d4.js.map +1 -0
  52. package/dist/assets/index-s-IzAUGa.css +1 -0
  53. package/dist/assets/index-tbZc77bo.js +296 -0
  54. package/dist/assets/index-tbZc77bo.js.map +1 -0
  55. package/dist/assets/inter-cyrillic-400-normal-HOLc17fK.woff +0 -0
  56. package/dist/assets/inter-cyrillic-400-normal-obahsSVq.woff2 +0 -0
  57. package/dist/assets/inter-cyrillic-500-normal-BasfLYem.woff2 +0 -0
  58. package/dist/assets/inter-cyrillic-500-normal-CxZf_p3X.woff +0 -0
  59. package/dist/assets/inter-cyrillic-600-normal-4D_pXhcN.woff +0 -0
  60. package/dist/assets/inter-cyrillic-600-normal-CWCymEST.woff2 +0 -0
  61. package/dist/assets/inter-cyrillic-700-normal-CjBOestx.woff2 +0 -0
  62. package/dist/assets/inter-cyrillic-700-normal-DrXBdSj3.woff +0 -0
  63. package/dist/assets/inter-cyrillic-ext-400-normal-BQZuk6qB.woff2 +0 -0
  64. package/dist/assets/inter-cyrillic-ext-400-normal-DQukG94-.woff +0 -0
  65. package/dist/assets/inter-cyrillic-ext-500-normal-B0yAr1jD.woff2 +0 -0
  66. package/dist/assets/inter-cyrillic-ext-500-normal-BmqWE9Dz.woff +0 -0
  67. package/dist/assets/inter-cyrillic-ext-600-normal-Bcila6Z-.woff +0 -0
  68. package/dist/assets/inter-cyrillic-ext-600-normal-Dfes3d0z.woff2 +0 -0
  69. package/dist/assets/inter-cyrillic-ext-700-normal-BjwYoWNd.woff2 +0 -0
  70. package/dist/assets/inter-cyrillic-ext-700-normal-LO58E6JB.woff +0 -0
  71. package/dist/assets/inter-greek-400-normal-B4URO6DV.woff2 +0 -0
  72. package/dist/assets/inter-greek-400-normal-q2sYcFCs.woff +0 -0
  73. package/dist/assets/inter-greek-500-normal-BIZE56-Y.woff2 +0 -0
  74. package/dist/assets/inter-greek-500-normal-Xzm54t5V.woff +0 -0
  75. package/dist/assets/inter-greek-600-normal-BZpKdvQh.woff +0 -0
  76. package/dist/assets/inter-greek-600-normal-plRanbMR.woff2 +0 -0
  77. package/dist/assets/inter-greek-700-normal-BUv2fZ6O.woff +0 -0
  78. package/dist/assets/inter-greek-700-normal-C3JjAnD8.woff2 +0 -0
  79. package/dist/assets/inter-greek-ext-400-normal-DGGRlc-M.woff2 +0 -0
  80. package/dist/assets/inter-greek-ext-400-normal-KugGGMne.woff +0 -0
  81. package/dist/assets/inter-greek-ext-500-normal-2j5mBUwD.woff +0 -0
  82. package/dist/assets/inter-greek-ext-500-normal-C4iEst2y.woff2 +0 -0
  83. package/dist/assets/inter-greek-ext-600-normal-B8X0CLgF.woff +0 -0
  84. package/dist/assets/inter-greek-ext-600-normal-DRtmH8MT.woff2 +0 -0
  85. package/dist/assets/inter-greek-ext-700-normal-BoQ6DsYi.woff +0 -0
  86. package/dist/assets/inter-greek-ext-700-normal-qfdV9bQt.woff2 +0 -0
  87. package/dist/assets/inter-latin-400-normal-C38fXH4l.woff2 +0 -0
  88. package/dist/assets/inter-latin-400-normal-CyCys3Eg.woff +0 -0
  89. package/dist/assets/inter-latin-500-normal-BL9OpVg8.woff +0 -0
  90. package/dist/assets/inter-latin-500-normal-Cerq10X2.woff2 +0 -0
  91. package/dist/assets/inter-latin-600-normal-CiBQ2DWP.woff +0 -0
  92. package/dist/assets/inter-latin-600-normal-LgqL8muc.woff2 +0 -0
  93. package/dist/assets/inter-latin-700-normal-BLAVimhd.woff +0 -0
  94. package/dist/assets/inter-latin-700-normal-Yt3aPRUw.woff2 +0 -0
  95. package/dist/assets/inter-latin-ext-400-normal-77YHD8bZ.woff +0 -0
  96. package/dist/assets/inter-latin-ext-400-normal-C1nco2VV.woff2 +0 -0
  97. package/dist/assets/inter-latin-ext-500-normal-BxGbmqWO.woff +0 -0
  98. package/dist/assets/inter-latin-ext-500-normal-CV4jyFjo.woff2 +0 -0
  99. package/dist/assets/inter-latin-ext-600-normal-CIVaiw4L.woff +0 -0
  100. package/dist/assets/inter-latin-ext-600-normal-D2bJ5OIk.woff2 +0 -0
  101. package/dist/assets/inter-latin-ext-700-normal-Ca8adRJv.woff2 +0 -0
  102. package/dist/assets/inter-latin-ext-700-normal-TidjK2hL.woff +0 -0
  103. package/dist/assets/inter-vietnamese-400-normal-Bbgyi5SW.woff +0 -0
  104. package/dist/assets/inter-vietnamese-400-normal-DMkecbls.woff2 +0 -0
  105. package/dist/assets/inter-vietnamese-500-normal-DOriooB6.woff2 +0 -0
  106. package/dist/assets/inter-vietnamese-500-normal-mJboJaSs.woff +0 -0
  107. package/dist/assets/inter-vietnamese-600-normal-BuLX-rYi.woff +0 -0
  108. package/dist/assets/inter-vietnamese-600-normal-Cc8MFFhd.woff2 +0 -0
  109. package/dist/assets/inter-vietnamese-700-normal-BZaoP0fm.woff +0 -0
  110. package/dist/assets/inter-vietnamese-700-normal-DlLaEgI2.woff2 +0 -0
  111. package/dist/assets/it-app-Cik25Qgd.json +215 -0
  112. package/dist/assets/ja-app-Cp_00ujI.json +123 -0
  113. package/dist/assets/join_call-DlMV9nHk.ogg +0 -0
  114. package/dist/assets/join_call-dEJCP2wD.mp3 +0 -0
  115. package/dist/assets/left_call-BbqmRgnC.mp3 +0 -0
  116. package/dist/assets/left_call-C7NMl6WI.ogg +0 -0
  117. package/dist/assets/lightbulb-BIeJtAR_.ogg +0 -0
  118. package/dist/assets/lightbulb-BrnY00qi.mp3 +0 -0
  119. package/dist/assets/livekit-client.e2ee.worker-Bmrtztct.js.map +1 -0
  120. package/dist/assets/lv-app-D-ZV3Ytk.json +222 -0
  121. package/dist/assets/matrix-sdk-crypto-wasm-BsWSMcLv.js +3 -0
  122. package/dist/assets/matrix-sdk-crypto-wasm-BsWSMcLv.js.map +1 -0
  123. package/dist/assets/matrix_sdk_crypto_wasm_bg-DU_51VO6.wasm +0 -0
  124. package/dist/assets/pako.esm-Cf42LiW4.js +2 -0
  125. package/dist/assets/pako.esm-Cf42LiW4.js.map +1 -0
  126. package/dist/assets/party-BZPeTgC3.mp3 +0 -0
  127. package/dist/assets/party-D7rIOhAQ.ogg +0 -0
  128. package/dist/assets/pl-app-CUkXVSZk.json +221 -0
  129. package/dist/assets/polyfill-force-BrOePHdV.js +2 -0
  130. package/dist/assets/polyfill-force-BrOePHdV.js.map +1 -0
  131. package/dist/assets/polyfill-force-Btq0hGFe.js +3 -0
  132. package/dist/assets/polyfill-force-Btq0hGFe.js.map +1 -0
  133. package/dist/assets/raise_hand-Bzqn65WB.mp3 +0 -0
  134. package/dist/assets/raise_hand-CUbxEnt9.ogg +0 -0
  135. package/dist/assets/ringtone-B-nJXbbw.ogg +0 -0
  136. package/dist/assets/ringtone-B2csBdU4.mp3 +0 -0
  137. package/dist/assets/ro-app-CdYgKCOW.json +206 -0
  138. package/dist/assets/rock-BVCJXNC-.ogg +0 -0
  139. package/dist/assets/rock-CHdnB31m.mp3 +0 -0
  140. package/dist/assets/ru-app-CIijOjFj.json +229 -0
  141. package/dist/assets/screen_share_started-DH3qxml5.mp3 +0 -0
  142. package/dist/assets/screen_share_started-IZDL-kAw.ogg +0 -0
  143. package/dist/assets/selfie_segmenter-DF05sdL4.tflite +0 -0
  144. package/dist/assets/sk-app-DaVEeQWZ.json +230 -0
  145. package/dist/assets/spa-f1VkEIgz.js +2 -0
  146. package/dist/assets/spa-f1VkEIgz.js.map +1 -0
  147. package/dist/assets/sv-app-DHLBEOTp.json +236 -0
  148. package/dist/assets/tr-app-Dk--6BpP.json +209 -0
  149. package/dist/assets/uk-app-DZD01h76.json +222 -0
  150. package/dist/assets/vision_wasm_internal-CEyeacG0.js +20 -0
  151. package/dist/assets/vision_wasm_internal-TmjHuG4I.wasm +0 -0
  152. package/dist/assets/wave-Bzf1LSMH.mp3 +0 -0
  153. package/dist/assets/wave-FiiOzicp.ogg +0 -0
  154. package/dist/assets/zh-Hans-app-BY5jJGyr.json +133 -0
  155. package/dist/assets/zh-Hant-app-BV1LKS_j.json +114 -0
  156. package/dist/config.json +1 -0
  157. package/dist/index.html +1 -0
  158. package/package.json +14 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-Cn2ez1d4.js","sources":["../../node_modules/matrix-js-sdk/lib/crypto-api/verification.js","../../node_modules/matrix-js-sdk/lib/crypto-api/recovery-key.js","../../node_modules/matrix-js-sdk/lib/crypto-api/key-passphrase.js","../../node_modules/another-json/another-json.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/RoomEncryptor.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/DehydratedDeviceManager.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/OutgoingRequestProcessor.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/KeyClaimManager.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/device-converter.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/CrossSigningIdentity.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/secret-storage.js","../../node_modules/matrix-js-sdk/lib/types.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/verification.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/backup.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/OutgoingRequestsManager.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/PerSessionKeyBackupDownloader.js","../../node_modules/matrix-js-sdk/lib/common-crypto/key-passphrase.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/rust-crypto.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/libolm_migration.js","../../node_modules/matrix-js-sdk/lib/rust-crypto/index.js"],"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\n/**\n * An incoming, or outgoing, request to verify a user or a device via cross-signing.\n */\n\n/** Events emitted by {@link VerificationRequest}. */\nexport var VerificationRequestEvent = /*#__PURE__*/function (VerificationRequestEvent) {\n /**\n * Fires whenever the state of the request object has changed.\n *\n * There is no payload to the event.\n */\n VerificationRequestEvent[\"Change\"] = \"change\";\n return VerificationRequestEvent;\n}({});\n\n/**\n * Listener type map for {@link VerificationRequestEvent}s.\n *\n * @internal\n */\n\n/** The current phase of a verification request. */\nexport var VerificationPhase = /*#__PURE__*/function (VerificationPhase) {\n /** Initial state: no event yet exchanged */\n VerificationPhase[VerificationPhase[\"Unsent\"] = 1] = \"Unsent\";\n /** An `m.key.verification.request` event has been sent or received */\n VerificationPhase[VerificationPhase[\"Requested\"] = 2] = \"Requested\";\n /** An `m.key.verification.ready` event has been sent or received, indicating the verification request is accepted. */\n VerificationPhase[VerificationPhase[\"Ready\"] = 3] = \"Ready\";\n /**\n * The verification is in flight.\n *\n * This means that an `m.key.verification.start` event has been sent or received, choosing a verification method;\n * however the verification has not yet completed or been cancelled.\n */\n VerificationPhase[VerificationPhase[\"Started\"] = 4] = \"Started\";\n /**\n * An `m.key.verification.cancel` event has been sent or received at any time before the `done` event, cancelling\n * the verification request\n */\n VerificationPhase[VerificationPhase[\"Cancelled\"] = 5] = \"Cancelled\";\n /**\n * The verification request is complete.\n *\n * Normally this means that `m.key.verification.done` events have been sent and received.\n */\n VerificationPhase[VerificationPhase[\"Done\"] = 6] = \"Done\";\n return VerificationPhase;\n}({});\n\n/**\n * A `Verifier` is responsible for performing the verification using a particular method, such as via QR code or SAS\n * (emojis).\n *\n * A verifier object can be created by calling `VerificationRequest.beginVerification`; one is also created\n * automatically when a `m.key.verification.start` event is received for an existing VerificationRequest.\n *\n * Once a verifier object is created, the verification can be started by calling the {@link Verifier#verify} method.\n */\n\n/** Events emitted by {@link Verifier} */\nexport var VerifierEvent = /*#__PURE__*/function (VerifierEvent) {\n /**\n * The verification has been cancelled, by us or the other side.\n *\n * The payload is either an {@link Error}, or an (incoming or outgoing) {@link MatrixEvent}, depending on\n * unspecified reasons.\n */\n VerifierEvent[\"Cancel\"] = \"cancel\";\n /**\n * SAS data has been exchanged and should be displayed to the user.\n *\n * The payload is the {@link ShowSasCallbacks} object.\n */\n VerifierEvent[\"ShowSas\"] = \"show_sas\";\n /**\n * The user should confirm if the other side has scanned our QR code.\n *\n * The payload is the {@link ShowQrCodeCallbacks} object.\n */\n VerifierEvent[\"ShowReciprocateQr\"] = \"show_reciprocate_qr\";\n return VerifierEvent;\n}({});\n\n/** Listener type map for {@link VerifierEvent}s. */\n\n/**\n * Callbacks for user actions to confirm that the other side has scanned our QR code.\n *\n * This is exposed as the payload of a `VerifierEvent.ShowReciprocateQr` event, or can be retrieved directly from the\n * verifier as `reciprocateQREvent`.\n */\n\n/**\n * Callbacks for user actions while a SAS is displayed.\n *\n * This is exposed as the payload of a `VerifierEvent.ShowSas` event, or directly from the verifier as `sasEvent`.\n */\n\n/** A generated SAS to be shown to the user, in alternative formats */\n\n/**\n * An emoji for the generated SAS. A tuple `[emoji, name]` where `emoji` is the emoji itself and `name` is the\n * English name.\n */\n\n/**\n * True if the request is in a state where it can be accepted (ie, that we're in phases {@link VerificationPhase.Unsent}\n * or {@link VerificationPhase.Requested}, and that we're not in the process of sending a `ready` or `cancel`).\n */\nexport function canAcceptVerificationRequest(req) {\n return req.phase < VerificationPhase.Ready && !req.accepting && !req.declining;\n}\n//# sourceMappingURL=verification.js.map","/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport bs58 from \"bs58\";\n\n// picked arbitrarily but to try & avoid clashing with any bitcoin ones\n// (which are also base58 encoded, but bitcoin's involve a lot more hashing)\nvar OLM_RECOVERY_KEY_PREFIX = [0x8b, 0x01];\nvar KEY_SIZE = 32;\n\n/**\n * Encode a recovery key using the Matrix {@link https://spec.matrix.org/v1.11/appendices/#cryptographic-key-representation | Cryptographic key representation}\n * @param key\n */\nexport function encodeRecoveryKey(key) {\n var _base58key$match;\n var buf = new Uint8Array(OLM_RECOVERY_KEY_PREFIX.length + key.length + 1);\n buf.set(OLM_RECOVERY_KEY_PREFIX, 0);\n buf.set(key, OLM_RECOVERY_KEY_PREFIX.length);\n var parity = 0;\n for (var i = 0; i < buf.length - 1; ++i) {\n parity ^= buf[i];\n }\n buf[buf.length - 1] = parity;\n var base58key = bs58.encode(buf);\n return (_base58key$match = base58key.match(/.{1,4}/g)) === null || _base58key$match === void 0 ? void 0 : _base58key$match.join(\" \");\n}\n\n/**\n * Decode a recovery key encoded with the Matrix {@link https://spec.matrix.org/v1.11/appendices/#cryptographic-key-representation | Cryptographic key representation} encoding.\n * @param recoveryKey\n */\nexport function decodeRecoveryKey(recoveryKey) {\n var result = bs58.decode(recoveryKey.replace(/ /g, \"\"));\n var parity = 0;\n for (var b of result) {\n parity ^= b;\n }\n if (parity !== 0) {\n throw new Error(\"Incorrect parity\");\n }\n for (var i = 0; i < OLM_RECOVERY_KEY_PREFIX.length; ++i) {\n if (result[i] !== OLM_RECOVERY_KEY_PREFIX[i]) {\n throw new Error(\"Incorrect prefix\");\n }\n }\n if (result.length !== OLM_RECOVERY_KEY_PREFIX.length + KEY_SIZE + 1) {\n throw new Error(\"Incorrect length\");\n }\n return Uint8Array.from(result.slice(OLM_RECOVERY_KEY_PREFIX.length, OLM_RECOVERY_KEY_PREFIX.length + KEY_SIZE));\n}\n//# sourceMappingURL=recovery-key.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nvar DEFAULT_BIT_SIZE = 256;\n\n/**\n * Derive a recovery key from a passphrase and salt using PBKDF2.\n * @see https://spec.matrix.org/v1.11/client-server-api/#deriving-keys-from-passphrases\n *\n * @param passphrase - The passphrase to derive the key from\n * @param salt - The salt to use in the derivation\n * @param iterations - The number of iterations to use in the derivation\n * @param numBits - The number of bits to derive\n */\nexport function deriveRecoveryKeyFromPassphrase(_x, _x2, _x3) {\n return _deriveRecoveryKeyFromPassphrase.apply(this, arguments);\n}\nfunction _deriveRecoveryKeyFromPassphrase() {\n _deriveRecoveryKeyFromPassphrase = _asyncToGenerator(function* (passphrase, salt, iterations) {\n var numBits = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_BIT_SIZE;\n if (!globalThis.crypto.subtle || !TextEncoder) {\n throw new Error(\"Password-based backup is not available on this platform\");\n }\n var key = yield globalThis.crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), {\n name: \"PBKDF2\"\n }, false, [\"deriveBits\"]);\n var keybits = yield globalThis.crypto.subtle.deriveBits({\n name: \"PBKDF2\",\n salt: new TextEncoder().encode(salt),\n iterations: iterations,\n hash: \"SHA-512\"\n }, key, numBits);\n return new Uint8Array(keybits);\n });\n return _deriveRecoveryKeyFromPassphrase.apply(this, arguments);\n}\n//# sourceMappingURL=key-passphrase.js.map","/* Copyright 2015 Mark Haines\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use strict';\n\nvar escaped = /[\\\\\\\"\\x00-\\x1F]/g;\nvar escapes = {};\nfor (var i = 0; i < 0x20; ++i) {\n escapes[String.fromCharCode(i)] = (\n '\\\\U' + ('0000' + i.toString(16)).slice(-4).toUpperCase()\n );\n}\nescapes['\\b'] = '\\\\b';\nescapes['\\t'] = '\\\\t';\nescapes['\\n'] = '\\\\n';\nescapes['\\f'] = '\\\\f';\nescapes['\\r'] = '\\\\r';\nescapes['\\\"'] = '\\\\\\\"';\nescapes['\\\\'] = '\\\\\\\\';\n\nfunction escapeString(value) {\n escaped.lastIndex = 0;\n return value.replace(escaped, function(c) { return escapes[c]; });\n}\n\nfunction stringify(value) {\n switch (typeof value) {\n case 'string':\n return '\"' + escapeString(value) + '\"';\n case 'number':\n return isFinite(value) ? value : 'null';\n case 'boolean':\n return value;\n case 'object':\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return stringifyArray(value);\n }\n return stringifyObject(value);\n default:\n throw new Error('Cannot stringify: ' + typeof value);\n }\n}\n\nfunction stringifyArray(array) {\n var sep = '[';\n var result = '';\n for (var i = 0; i < array.length; ++i) {\n result += sep;\n sep = ',';\n result += stringify(array[i]);\n }\n if (sep != ',') {\n return '[]';\n } else {\n return result + ']';\n }\n}\n\nfunction stringifyObject(object) {\n var sep = '{';\n var result = '';\n var keys = Object.keys(object);\n keys.sort();\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n result += sep + '\"' + escapeString(key) + '\":';\n sep = ',';\n result += stringify(object[key]);\n }\n if (sep != ',') {\n return '{}';\n } else {\n return result + '}';\n }\n}\n\n/** */\nmodule.exports = {stringify: stringify};\n","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\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 * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { CollectStrategy, EncryptionAlgorithm, EncryptionSettings, HistoryVisibility as RustHistoryVisibility, RoomId, UserId } from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { EventType } from \"../@types/event.js\";\nimport { LogSpan } from \"../logger.js\";\nimport { HistoryVisibility } from \"../@types/partials.js\";\nimport { logDuration } from \"../utils.js\";\nimport { KnownMembership } from \"../@types/membership.js\";\nimport { DeviceIsolationModeKind } from \"../crypto-api/index.js\";\n\n/**\n * RoomEncryptor: responsible for encrypting messages to a given room\n *\n * @internal\n */\nexport class RoomEncryptor {\n /**\n * @param prefixedLogger - A logger to use for log messages.\n * @param olmMachine - The rust-sdk's OlmMachine\n * @param keyClaimManager - Our KeyClaimManager, which manages the queue of one-time-key claim requests\n * @param outgoingRequestManager - The OutgoingRequestManager, which manages the queue of outgoing requests.\n * @param room - The room we want to encrypt for\n * @param encryptionSettings - body of the m.room.encryption event currently in force in this room\n */\n constructor(prefixedLogger, olmMachine, keyClaimManager, outgoingRequestManager, room, encryptionSettings) {\n this.prefixedLogger = prefixedLogger;\n this.olmMachine = olmMachine;\n this.keyClaimManager = keyClaimManager;\n this.outgoingRequestManager = outgoingRequestManager;\n this.room = room;\n this.encryptionSettings = encryptionSettings;\n /** whether the room members have been loaded and tracked for the first time */\n _defineProperty(this, \"lazyLoadedMembersResolved\", false);\n /**\n * Ensures that there is only one encryption operation at a time for that room.\n *\n * An encryption operation is either a {@link prepareForEncryption} or an {@link encryptEvent} call.\n */\n _defineProperty(this, \"currentEncryptionPromise\", Promise.resolve());\n // start tracking devices for any users already known to be in this room.\n // Do not load members here, would defeat lazy loading.\n var members = room.getJoinedMembers();\n\n // At this point just mark the known members as tracked, it might not be the full list of members\n // because of lazy loading. This is fine, because we will get a member list update when sending a message for\n // the first time, see `RoomEncryptor#ensureEncryptionSession`\n this.olmMachine.updateTrackedUsers(members.map(u => new RustSdkCryptoJs.UserId(u.userId))).catch(e => this.prefixedLogger.error(\"Error initializing tracked users\", e));\n }\n\n /**\n * Handle a new `m.room.encryption` event in this room\n *\n * @param config - The content of the encryption event\n */\n onCryptoEvent(config) {\n if (JSON.stringify(this.encryptionSettings) != JSON.stringify(config)) {\n // This should currently be unreachable, since the Rust SDK will reject any attempts to change config.\n throw new Error(\"Cannot reconfigure an active RoomEncryptor\");\n }\n }\n\n /**\n * Handle a new `m.room.member` event in this room\n *\n * @param member - new membership state\n */\n onRoomMembership(member) {\n if (member.membership == KnownMembership.Join || member.membership == KnownMembership.Invite && this.room.shouldEncryptForInvitedMembers()) {\n // make sure we are tracking the deviceList for this user\n this.olmMachine.updateTrackedUsers([new UserId(member.userId)]).catch(e => {\n this.prefixedLogger.error(\"Unable to update tracked users\", e);\n });\n }\n\n // TODO: handle leaves (including our own)\n }\n\n /**\n * Prepare to encrypt events in this room.\n *\n * This ensures that we have a megolm session ready to use and that we have shared its key with all the devices\n * in the room.\n * @param globalBlacklistUnverifiedDevices - When `true`, and `deviceIsolationMode` is `AllDevicesIsolationMode`,\n * will not send encrypted messages to unverified devices.\n * Ignored when `deviceIsolationMode` is `OnlySignedDevicesIsolationMode`.\n * @param deviceIsolationMode - The device isolation mode. See {@link DeviceIsolationMode}.\n */\n prepareForEncryption(globalBlacklistUnverifiedDevices, deviceIsolationMode) {\n var _this = this;\n return _asyncToGenerator(function* () {\n // We consider a prepareForEncryption as an encryption promise as it will potentially share keys\n // even if it doesn't send an event.\n // Usually this is called when the user starts typing, so we want to make sure we have keys ready when the\n // message is finally sent.\n // If `encryptEvent` is invoked before `prepareForEncryption` has completed, the `encryptEvent` call will wait for\n // `prepareForEncryption` to complete before executing.\n // The part where `encryptEvent` shares the room key will then usually be a no-op as it was already performed by `prepareForEncryption`.\n yield _this.encryptEvent(null, globalBlacklistUnverifiedDevices, deviceIsolationMode);\n })();\n }\n\n /**\n * Encrypt an event for this room, or prepare for encryption.\n *\n * This will ensure that we have a megolm session for this room, share it with the devices in the room, and\n * then, if an event is provided, encrypt it using the session.\n *\n * @param event - Event to be encrypted, or null if only preparing for encryption (in which case we will pre-share the room key).\n * @param globalBlacklistUnverifiedDevices - When `true`, and `deviceIsolationMode` is `AllDevicesIsolationMode`,\n * will not send encrypted messages to unverified devices.\n * Ignored when `deviceIsolationMode` is `OnlySignedDevicesIsolationMode`.\n * @param deviceIsolationMode - The device isolation mode. See {@link DeviceIsolationMode}.\n */\n encryptEvent(event, globalBlacklistUnverifiedDevices, deviceIsolationMode) {\n var _event$getTxnId,\n _this2 = this;\n var logger = new LogSpan(this.prefixedLogger, event ? (_event$getTxnId = event.getTxnId()) !== null && _event$getTxnId !== void 0 ? _event$getTxnId : \"\" : \"prepareForEncryption\");\n // Ensure order of encryption to avoid message ordering issues, as the scheduler only ensures\n // events order after they have been encrypted.\n var prom = this.currentEncryptionPromise.catch(() => {\n // Any errors in the previous call will have been reported already, so there is nothing to do here.\n // we just throw away the error and start anew.\n }).then(/*#__PURE__*/_asyncToGenerator(function* () {\n yield logDuration(logger, \"ensureEncryptionSession\", /*#__PURE__*/_asyncToGenerator(function* () {\n yield _this2.ensureEncryptionSession(logger, globalBlacklistUnverifiedDevices, deviceIsolationMode);\n }));\n if (event) {\n yield logDuration(logger, \"encryptEventInner\", /*#__PURE__*/_asyncToGenerator(function* () {\n yield _this2.encryptEventInner(logger, event);\n }));\n }\n }));\n this.currentEncryptionPromise = prom;\n return prom;\n }\n\n /**\n * Prepare to encrypt events in this room.\n *\n * This ensures that we have a megolm session ready to use and that we have shared its key with all the devices\n * in the room.\n *\n * @param logger - a place to write diagnostics to\n * @param globalBlacklistUnverifiedDevices - When `true`, and `deviceIsolationMode` is `AllDevicesIsolationMode`,\n * will not send encrypted messages to unverified devices.\n * Ignored when `deviceIsolationMode` is `OnlySignedDevicesIsolationMode`.\n * @param deviceIsolationMode - The device isolation mode. See {@link DeviceIsolationMode}.\n */\n ensureEncryptionSession(logger, globalBlacklistUnverifiedDevices, deviceIsolationMode) {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n if (_this3.encryptionSettings.algorithm !== \"m.megolm.v1.aes-sha2\") {\n throw new Error(\"Cannot encrypt in \".concat(_this3.room.roomId, \" for unsupported algorithm '\").concat(_this3.encryptionSettings.algorithm, \"'\"));\n }\n logger.debug(\"Starting encryption\");\n var members = yield _this3.room.getEncryptionTargetMembers();\n\n // If this is the first time we are sending a message to the room, we may not yet have seen all the members\n // (so the Crypto SDK might not have a device list for them). So, if this is the first time we are encrypting\n // for this room, give the SDK the full list of members, to be on the safe side.\n //\n // This could end up being racy (if two calls to ensureEncryptionSession happen at the same time), but that's\n // not a particular problem, since `OlmMachine.updateTrackedUsers` just adds any users that weren't already tracked.\n if (!_this3.lazyLoadedMembersResolved) {\n yield logDuration(logger, \"loadMembersIfNeeded: updateTrackedUsers\", /*#__PURE__*/_asyncToGenerator(function* () {\n yield _this3.olmMachine.updateTrackedUsers(members.map(u => new RustSdkCryptoJs.UserId(u.userId)));\n }));\n logger.debug(\"Updated tracked users\");\n _this3.lazyLoadedMembersResolved = true;\n\n // Query keys in case we don't have them for newly tracked members.\n // It's important after loading members for the first time, as likely most of them won't be\n // known yet and will be unable to decrypt messages despite being in the room for long.\n // This must be done before ensuring sessions. If not the devices of these users are not\n // known yet and will not get the room key.\n // We don't have API to only get the keys queries related to this member list, so we just\n // process the pending requests from the olmMachine. (usually these are processed\n // at the end of the sync, but we can't wait for that).\n // XXX future improvement process only KeysQueryRequests for the users that have never been queried.\n logger.debug(\"Processing outgoing requests\");\n yield logDuration(logger, \"doProcessOutgoingRequests\", /*#__PURE__*/_asyncToGenerator(function* () {\n yield _this3.outgoingRequestManager.doProcessOutgoingRequests();\n }));\n } else {\n // If members are already loaded it's less critical to await on key queries.\n // We might still want to trigger a processOutgoingRequests here.\n // The call to `ensureSessionsForUsers` below will wait a bit on in-flight key queries we are\n // interested in. If a sync handling happens in the meantime, and some new members are added to the room\n // or have new devices it would give us a chance to query them before sending.\n // It's less critical due to the racy nature of this process.\n logger.debug(\"Processing outgoing requests in background\");\n _this3.outgoingRequestManager.doProcessOutgoingRequests();\n }\n logger.debug(\"Encrypting for users (shouldEncryptForInvitedMembers: \".concat(_this3.room.shouldEncryptForInvitedMembers(), \"):\"), members.map(u => \"\".concat(u.userId, \" (\").concat(u.membership, \")\")));\n var userList = members.map(u => new UserId(u.userId));\n yield logDuration(logger, \"ensureSessionsForUsers\", /*#__PURE__*/_asyncToGenerator(function* () {\n yield _this3.keyClaimManager.ensureSessionsForUsers(logger, userList);\n }));\n var rustEncryptionSettings = new EncryptionSettings();\n rustEncryptionSettings.historyVisibility = toRustHistoryVisibility(_this3.room.getHistoryVisibility());\n\n // We only support megolm\n rustEncryptionSettings.algorithm = EncryptionAlgorithm.MegolmV1AesSha2;\n\n // We need to convert the rotation period from milliseconds to microseconds\n // See https://spec.matrix.org/v1.8/client-server-api/#mroomencryption and\n // https://matrix-org.github.io/matrix-rust-sdk-crypto-wasm/classes/EncryptionSettings.html#rotationPeriod\n if (typeof _this3.encryptionSettings.rotation_period_ms === \"number\") {\n rustEncryptionSettings.rotationPeriod = BigInt(_this3.encryptionSettings.rotation_period_ms * 1000);\n }\n if (typeof _this3.encryptionSettings.rotation_period_msgs === \"number\") {\n rustEncryptionSettings.rotationPeriodMessages = BigInt(_this3.encryptionSettings.rotation_period_msgs);\n }\n switch (deviceIsolationMode.kind) {\n case DeviceIsolationModeKind.AllDevicesIsolationMode:\n {\n var _this3$room$getBlackl;\n // When this.room.getBlacklistUnverifiedDevices() === null, the global settings should be used\n // See Room#getBlacklistUnverifiedDevices\n var onlyAllowTrustedDevices = (_this3$room$getBlackl = _this3.room.getBlacklistUnverifiedDevices()) !== null && _this3$room$getBlackl !== void 0 ? _this3$room$getBlackl : globalBlacklistUnverifiedDevices;\n rustEncryptionSettings.sharingStrategy = CollectStrategy.deviceBasedStrategy(onlyAllowTrustedDevices, deviceIsolationMode.errorOnVerifiedUserProblems);\n }\n break;\n case DeviceIsolationModeKind.OnlySignedDevicesIsolationMode:\n rustEncryptionSettings.sharingStrategy = CollectStrategy.identityBasedStrategy();\n break;\n }\n yield logDuration(logger, \"shareRoomKey\", /*#__PURE__*/_asyncToGenerator(function* () {\n var shareMessages = yield _this3.olmMachine.shareRoomKey(new RoomId(_this3.room.roomId),\n // safe to pass without cloning, as it's not reused here (before or after)\n userList, rustEncryptionSettings);\n if (shareMessages) {\n for (var m of shareMessages) {\n yield _this3.outgoingRequestManager.outgoingRequestProcessor.makeOutgoingRequest(m);\n }\n }\n }));\n })();\n }\n\n /**\n * Discard any existing group session for this room\n */\n forceDiscardSession() {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n var r = yield _this4.olmMachine.invalidateGroupSession(new RoomId(_this4.room.roomId));\n if (r) {\n _this4.prefixedLogger.info(\"Discarded existing group session\");\n }\n })();\n }\n encryptEventInner(logger, event) {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n logger.debug(\"Encrypting actual message content\");\n var room = new RoomId(_this5.room.roomId);\n var type = event.getType();\n var content = JSON.stringify(event.getContent());\n var encryptedContent;\n if (event.isState()) {\n encryptedContent = yield _this5.olmMachine.encryptStateEvent(room, type,\n // Safety: we've already checked above that this is a state event, so the state key must exist.\n event.getStateKey(), content);\n } else {\n encryptedContent = yield _this5.olmMachine.encryptRoomEvent(room, type, content);\n }\n event.makeEncrypted(EventType.RoomMessageEncrypted, JSON.parse(encryptedContent), _this5.olmMachine.identityKeys.curve25519.toBase64(), _this5.olmMachine.identityKeys.ed25519.toBase64());\n logger.debug(\"Encrypted event successfully\");\n })();\n }\n}\n\n/**\n * Convert a HistoryVisibility to a RustHistoryVisibility\n * @param visibility - HistoryVisibility enum\n * @returns a RustHistoryVisibility enum\n */\nexport function toRustHistoryVisibility(visibility) {\n switch (visibility) {\n case HistoryVisibility.Invited:\n return RustHistoryVisibility.Invited;\n case HistoryVisibility.Joined:\n return RustHistoryVisibility.Joined;\n case HistoryVisibility.Shared:\n return RustHistoryVisibility.Shared;\n case HistoryVisibility.WorldReadable:\n return RustHistoryVisibility.WorldReadable;\n }\n}\n//# sourceMappingURL=RoomEncryptor.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\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\";\nimport { encodeUri } from \"../utils.js\";\nimport { Method } from \"../http-api/index.js\";\nimport { decodeBase64 } from \"../base64.js\";\nimport { CryptoEvent } from \"../crypto-api/index.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\n\n/**\n * The response body of `GET /_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device`.\n */\n\n/**\n * The response body of `POST /_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device/events`.\n */\n\n/**\n * The unstable URL prefix for dehydrated device endpoints\n */\nexport var UnstablePrefix = \"/_matrix/client/unstable/org.matrix.msc3814.v1\";\n/**\n * The name used for the dehydration key in Secret Storage\n */\nvar SECRET_STORAGE_NAME = \"org.matrix.msc3814\";\n\n/**\n * The interval between creating dehydrated devices. (one week)\n */\nvar 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 {\n constructor(logger, olmMachine, http, outgoingRequestProcessor, secretStorage) {\n super();\n this.logger = logger;\n this.olmMachine = olmMachine;\n this.http = http;\n this.outgoingRequestProcessor = outgoingRequestProcessor;\n this.secretStorage = secretStorage;\n /** the ID of the interval for periodically replacing the dehydrated device */\n _defineProperty(this, \"intervalId\", void 0);\n }\n cacheKey(key) {\n var _this = this;\n return _asyncToGenerator(function* () {\n yield _this.olmMachine.dehydratedDevices().saveDehydratedDeviceKey(key);\n _this.emit(CryptoEvent.DehydrationKeyCached);\n })();\n }\n\n /**\n * Return whether the server supports dehydrated devices.\n */\n isSupported() {\n var _this2 = this;\n return _asyncToGenerator(function* () {\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 yield _this2.http.authedRequest(Method.Get, \"/dehydrated_device\", undefined, undefined, {\n prefix: UnstablePrefix\n });\n } catch (error) {\n var err = error;\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 /**\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 start() {\n var _arguments = arguments,\n _this3 = this;\n return _asyncToGenerator(function* () {\n var opts = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : {};\n if (typeof opts === \"boolean\") {\n opts = {\n createNewKey: opts\n };\n }\n if (opts.onlyIfKeyCached && !(yield _this3.olmMachine.dehydratedDevices().getDehydratedDeviceKey())) {\n return;\n }\n _this3.stop();\n if (opts.rehydrate !== false) {\n try {\n yield _this3.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 _this3.logger.info(\"dehydration: Error rehydrating device:\", e);\n _this3.emit(CryptoEvent.RehydrationError, e.message);\n }\n }\n if (opts.createNewKey) {\n yield _this3.resetKey();\n }\n yield _this3.scheduleDeviceDehydration();\n })();\n }\n\n /**\n * Return whether the dehydration key is stored in Secret Storage.\n */\n isKeyStored() {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n return Boolean(yield _this4.secretStorage.isStored(SECRET_STORAGE_NAME));\n })();\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 resetKey() {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n var key = RustSdkCryptoJs.DehydratedDeviceKey.createRandomKey();\n yield _this5.secretStorage.store(SECRET_STORAGE_NAME, key.toBase64());\n // Also cache it in the rust SDK's crypto store.\n yield _this5.cacheKey(key);\n return key;\n })();\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 getKey(create) {\n var _this6 = this;\n return _asyncToGenerator(function* () {\n var cachedKey = yield _this6.olmMachine.dehydratedDevices().getDehydratedDeviceKey();\n if (cachedKey) return cachedKey;\n var keyB64 = yield _this6.secretStorage.get(SECRET_STORAGE_NAME);\n if (keyB64 === undefined) {\n if (!create) {\n return null;\n }\n return yield _this6.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 var bytes = decodeBase64(keyB64);\n try {\n var key = RustSdkCryptoJs.DehydratedDeviceKey.createKeyFromArray(bytes);\n yield _this6.cacheKey(key);\n return key;\n } finally {\n bytes.fill(0);\n }\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 rehydrateDeviceIfAvailable() {\n var _this7 = this;\n return _asyncToGenerator(function* () {\n var key = yield _this7.getKey(false);\n if (!key) {\n return false;\n }\n var dehydratedDeviceResp;\n try {\n dehydratedDeviceResp = yield _this7.http.authedRequest(Method.Get, \"/dehydrated_device\", undefined, undefined, {\n prefix: UnstablePrefix\n });\n } catch (error) {\n var err = error;\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 _this7.logger.info(\"dehydration: No dehydrated device\");\n return false;\n }\n throw err;\n }\n _this7.logger.info(\"dehydration: dehydrated device found\");\n _this7.emit(CryptoEvent.RehydrationStarted);\n var rehydratedDevice = yield _this7.olmMachine.dehydratedDevices().rehydrate(key, new RustSdkCryptoJs.DeviceId(dehydratedDeviceResp.device_id), JSON.stringify(dehydratedDeviceResp.device_data));\n _this7.logger.info(\"dehydration: device rehydrated\");\n var nextBatch = undefined;\n var toDeviceCount = 0;\n var roomKeyCount = 0;\n var 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 var eventResp = yield _this7.http.authedRequest(Method.Post, path, undefined, nextBatch ? {\n next_batch: nextBatch\n } : {}, {\n prefix: UnstablePrefix\n });\n if (eventResp.events.length === 0) {\n break;\n }\n toDeviceCount += eventResp.events.length;\n nextBatch = eventResp.next_batch;\n var roomKeyInfos = yield rehydratedDevice.receiveEvents(JSON.stringify(eventResp.events));\n roomKeyCount += roomKeyInfos.length;\n _this7.emit(CryptoEvent.RehydrationProgress, roomKeyCount, toDeviceCount);\n }\n _this7.logger.info(\"dehydration: received \".concat(roomKeyCount, \" room keys from \").concat(toDeviceCount, \" to-device events\"));\n _this7.emit(CryptoEvent.RehydrationCompleted);\n return true;\n })();\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 createAndUploadDehydratedDevice() {\n var _this8 = this;\n return _asyncToGenerator(function* () {\n var key = yield _this8.getKey(true);\n var dehydratedDevice = yield _this8.olmMachine.dehydratedDevices().create();\n _this8.emit(CryptoEvent.DehydratedDeviceCreated);\n var request = yield dehydratedDevice.keysForUpload(\"Dehydrated device\", key);\n yield _this8.outgoingRequestProcessor.makeOutgoingRequest(request);\n _this8.emit(CryptoEvent.DehydratedDeviceUploaded);\n _this8.logger.info(\"dehydration: uploaded device\");\n })();\n }\n\n /**\n * Schedule periodic creation of dehydrated devices.\n */\n scheduleDeviceDehydration() {\n var _this9 = this;\n return _asyncToGenerator(function* () {\n // cancel any previously-scheduled tasks\n _this9.stop();\n yield _this9.createAndUploadDehydratedDevice();\n _this9.intervalId = setInterval(() => {\n _this9.createAndUploadDehydratedDevice().catch(error => {\n _this9.emit(CryptoEvent.DehydratedDeviceRotationError, error.message);\n _this9.logger.error(\"Error creating dehydrated device:\", error);\n });\n }, DEHYDRATION_INTERVAL);\n })();\n }\n\n /**\n * Stop the dehydrated device manager.\n *\n * Cancels any scheduled dehydration tasks.\n */\n stop() {\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 delete() {\n var _this0 = this;\n return _asyncToGenerator(function* () {\n _this0.stop();\n try {\n yield _this0.http.authedRequest(Method.Delete, \"/dehydrated_device\", undefined, {}, {\n prefix: UnstablePrefix\n });\n } catch (error) {\n var err = error;\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/**\n * The events fired by the DehydratedDeviceManager\n * @internal\n */\n\n/**\n * A map of the {@link DehydratedDeviceEvents} fired by the {@link DehydratedDeviceManager} and their payloads.\n * @internal\n */\n//# sourceMappingURL=DehydratedDeviceManager.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\n/*\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 { KeysBackupRequest, KeysClaimRequest, KeysQueryRequest, KeysUploadRequest, PutDehydratedDeviceRequest, RoomMessageRequest, SignatureUploadRequest, ToDeviceRequest, UploadSigningKeysRequest } from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { calculateRetryBackoff, Method } from \"../http-api/index.js\";\nimport { logDuration, sleep } from \"../utils.js\";\nimport { ToDeviceMessageId } from \"../@types/event.js\";\nimport { UnstablePrefix as DehydrationUnstablePrefix } from \"./DehydratedDeviceManager.js\";\n\n/**\n * OutgoingRequestManager: turns `OutgoingRequest`s from the rust sdk into HTTP requests\n *\n * We have one of these per `RustCrypto` (and hence per `MatrixClient`), not that it does anything terribly complicated.\n * It's responsible for:\n *\n * * holding the reference to the `MatrixHttpApi`\n * * turning `OutgoingRequest`s from the rust backend into HTTP requests, and sending them\n * * sending the results of such requests back to the rust backend.\n *\n * @internal\n */\nexport class OutgoingRequestProcessor {\n constructor(logger, olmMachine, http) {\n this.logger = logger;\n this.olmMachine = olmMachine;\n this.http = http;\n }\n makeOutgoingRequest(msg, uiaCallback) {\n var _this = this;\n return _asyncToGenerator(function* () {\n var resp;\n\n /* refer https://docs.rs/matrix-sdk-crypto/0.6.0/matrix_sdk_crypto/requests/enum.OutgoingRequests.html\n * for the complete list of request types\n */\n if (msg instanceof KeysUploadRequest) {\n resp = yield _this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/upload\", {}, msg.body);\n } else if (msg instanceof KeysQueryRequest) {\n resp = yield _this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/query\", {}, msg.body);\n } else if (msg instanceof KeysClaimRequest) {\n resp = yield _this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/claim\", {}, msg.body);\n } else if (msg instanceof SignatureUploadRequest) {\n resp = yield _this.requestWithRetry(Method.Post, \"/_matrix/client/v3/keys/signatures/upload\", {}, msg.body);\n } else if (msg instanceof KeysBackupRequest) {\n resp = yield _this.requestWithRetry(Method.Put, \"/_matrix/client/v3/room_keys/keys\", {\n version: msg.version\n }, msg.body);\n } else if (msg instanceof ToDeviceRequest) {\n resp = yield _this.sendToDeviceRequest(msg);\n } else if (msg instanceof RoomMessageRequest) {\n var path = \"/_matrix/client/v3/rooms/\".concat(encodeURIComponent(msg.room_id), \"/send/\") + \"\".concat(encodeURIComponent(msg.event_type), \"/\").concat(encodeURIComponent(msg.txn_id));\n resp = yield _this.requestWithRetry(Method.Put, path, {}, msg.body);\n } else if (msg instanceof UploadSigningKeysRequest) {\n yield _this.makeRequestWithUIA(Method.Post, \"/_matrix/client/v3/keys/device_signing/upload\", {}, msg.body, uiaCallback);\n // SigningKeysUploadRequest does not implement OutgoingRequest and does not need to be marked as sent.\n return;\n } else if (msg instanceof PutDehydratedDeviceRequest) {\n var _path = DehydrationUnstablePrefix + \"/dehydrated_device\";\n yield _this.rawJsonRequest(Method.Put, _path, {}, msg.body);\n // PutDehydratedDeviceRequest does not implement OutgoingRequest and does not need to be marked as sent.\n return;\n } else {\n _this.logger.warn(\"Unsupported outgoing message\", Object.getPrototypeOf(msg));\n resp = \"\";\n }\n if (msg.id) {\n try {\n yield logDuration(_this.logger, \"Mark Request as sent \".concat(msg.type), /*#__PURE__*/_asyncToGenerator(function* () {\n yield _this.olmMachine.markRequestAsSent(msg.id, msg.type, resp);\n }));\n } catch (e) {\n // Ignore errors which are caused by the olmMachine having been freed. The exact error message depends\n // on whether we are using a release or develop build of rust-sdk-crypto-wasm.\n if (e instanceof Error && (e.message === \"Attempt to use a moved value\" || e.message === \"null pointer passed to rust\")) {\n _this.logger.debug(\"Ignoring error '\".concat(e.message, \"': client is likely shutting down\"));\n } else {\n throw e;\n }\n }\n } else {\n _this.logger.trace(\"Outgoing request type:\".concat(msg.type, \" does not have an ID\"));\n }\n })();\n }\n\n /**\n * Send the HTTP request for a `ToDeviceRequest`\n *\n * @param request - request to send\n * @returns JSON-serialized body of the response, if successful\n */\n sendToDeviceRequest(request) {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n // a bit of extra logging, to help trace to-device messages through the system\n var parsedBody = JSON.parse(request.body);\n var messageList = [];\n for (var [userId, perUserMessages] of Object.entries(parsedBody.messages)) {\n for (var [deviceId, message] of Object.entries(perUserMessages)) {\n messageList.push(\"\".concat(userId, \"/\").concat(deviceId, \" (msgid \").concat(message[ToDeviceMessageId], \")\"));\n }\n }\n _this2.logger.info(\"Sending batch of to-device messages. type=\".concat(request.event_type, \" txnid=\").concat(request.txn_id), messageList);\n var path = \"/_matrix/client/v3/sendToDevice/\".concat(encodeURIComponent(request.event_type), \"/\") + encodeURIComponent(request.txn_id);\n return yield _this2.requestWithRetry(Method.Put, path, {}, request.body);\n })();\n }\n makeRequestWithUIA(method, path, queryParams, body, uiaCallback) {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n if (!uiaCallback) {\n return yield _this3.requestWithRetry(method, path, queryParams, body);\n }\n var parsedBody = JSON.parse(body);\n var makeRequest = /*#__PURE__*/function () {\n var _ref2 = _asyncToGenerator(function* (auth) {\n var newBody = _objectSpread({}, parsedBody);\n if (auth !== null) {\n newBody.auth = auth;\n }\n var resp = yield _this3.requestWithRetry(method, path, queryParams, JSON.stringify(newBody));\n return JSON.parse(resp);\n });\n return function makeRequest(_x) {\n return _ref2.apply(this, arguments);\n };\n }();\n var resp = yield uiaCallback(makeRequest);\n return JSON.stringify(resp);\n })();\n }\n requestWithRetry(method, path, queryParams, body) {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n var currentRetryCount = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n return yield _this4.rawJsonRequest(method, path, queryParams, body);\n } catch (e) {\n currentRetryCount++;\n var backoff = calculateRetryBackoff(e, currentRetryCount, true);\n if (backoff < 0) {\n // Max number of retries reached, or error is not retryable. rethrow the error\n throw e;\n }\n // wait for the specified time and then retry the request\n yield sleep(backoff);\n }\n }\n })();\n }\n rawJsonRequest(method, path, queryParams, body) {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n var opts = {\n // inhibit the JSON stringification and parsing within HttpApi.\n json: false,\n // nevertheless, we are sending, and accept, JSON.\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n // we use the full prefix\n prefix: \"\",\n // We set a timeout of 60 seconds to guard against requests getting stuck forever and wedging the\n // request loop (cf https://github.com/element-hq/element-web/issues/29534).\n //\n // (XXX: should we do this in the whole of the js-sdk?)\n localTimeoutMs: 60000\n };\n return yield _this5.http.authedRequest(method, path, queryParams, body, opts);\n })();\n }\n}\n//# sourceMappingURL=OutgoingRequestProcessor.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\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\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 constructor(olmMachine, outgoingRequestProcessor) {\n this.olmMachine = olmMachine;\n this.outgoingRequestProcessor = outgoingRequestProcessor;\n _defineProperty(this, \"currentClaimPromise\", void 0);\n _defineProperty(this, \"stopped\", false);\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 stop() {\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 ensureSessionsForUsers(logger, userList) {\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 var prom = this.currentClaimPromise.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 }).then(() => this.ensureSessionsForUsersInner(logger, userList));\n this.currentClaimPromise = prom;\n return prom;\n }\n ensureSessionsForUsersInner(logger, userList) {\n var _this = this;\n return _asyncToGenerator(function* () {\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 var claimRequest = yield _this.olmMachine.getMissingSessions(userList.map(u => u.clone()));\n if (claimRequest) {\n logger.info(\"Making /keys/claim request\");\n yield _this.outgoingRequestProcessor.makeOutgoingRequest(claimRequest);\n }\n logger.info(\"Olm sessions prepared\");\n })();\n }\n}\n//# sourceMappingURL=KeyClaimManager.js.map","/*\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 * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { Device, DeviceVerification } from \"../models/device.js\";\n/**\n * Convert a {@link RustSdkCryptoJs.Device} to a {@link Device}\n * @param device - Rust Sdk device\n * @param userId - owner of the device\n *\n * @internal\n */\nexport function rustDeviceToJsDevice(device, userId) {\n // Copy rust device keys to Device.keys\n var keys = new Map();\n for (var [keyId, key] of device.keys.entries()) {\n keys.set(keyId.toString(), key.toBase64());\n }\n\n // Compute verified from device state\n var verified = DeviceVerification.Unverified;\n if (device.isBlacklisted()) {\n verified = DeviceVerification.Blocked;\n } else if (device.isVerified()) {\n verified = DeviceVerification.Verified;\n }\n\n // Convert rust signatures to Device.signatures\n var signatures = new Map();\n var mayBeSignatureMap = device.signatures.get(userId);\n if (mayBeSignatureMap) {\n var convertedSignatures = new Map();\n // Convert maybeSignatures map to a Map<string, string>\n for (var [_key, value] of mayBeSignatureMap.entries()) {\n if (value.isValid() && value.signature) {\n convertedSignatures.set(_key, value.signature.toBase64());\n }\n }\n signatures.set(userId.toString(), convertedSignatures);\n }\n\n // Convert rust algorithms to algorithms\n var rustAlgorithms = device.algorithms;\n // Use set to ensure that algorithms are not duplicated\n var algorithms = new Set();\n rustAlgorithms.forEach(algorithm => {\n switch (algorithm) {\n case RustSdkCryptoJs.EncryptionAlgorithm.MegolmV1AesSha2:\n algorithms.add(\"m.megolm.v1.aes-sha2\");\n break;\n case RustSdkCryptoJs.EncryptionAlgorithm.OlmV1Curve25519AesSha2:\n default:\n algorithms.add(\"m.olm.v1.curve25519-aes-sha2\");\n break;\n }\n });\n return new Device({\n deviceId: device.deviceId.toString(),\n userId: userId.toString(),\n keys,\n algorithms: Array.from(algorithms),\n verified,\n signatures,\n displayName: device.displayName,\n dehydrated: device.isDehydrated\n });\n}\n\n/**\n * Convert {@link DeviceKeys} from `/keys/query` request to a `Map<string, Device>`\n * @param deviceKeys - Device keys object to convert\n *\n * @internal\n */\nexport function deviceKeysToDeviceMap(deviceKeys) {\n return new Map(Object.entries(deviceKeys).map(_ref => {\n var [deviceId, device] = _ref;\n return [deviceId, downloadDeviceToJsDevice(device)];\n }));\n}\n\n// Device from `/keys/query` request\n\n/**\n * Convert `/keys/query` {@link QueryDevice} device to {@link Device}\n * @param device - Device from `/keys/query` request\n *\n * @internal\n */\nexport function downloadDeviceToJsDevice(device) {\n var _device$unsigned;\n var keys = new Map(Object.entries(device.keys));\n var displayName = (_device$unsigned = device.unsigned) === null || _device$unsigned === void 0 ? void 0 : _device$unsigned.device_display_name;\n var signatures = new Map();\n if (device.signatures) {\n for (var userId in device.signatures) {\n signatures.set(userId, new Map(Object.entries(device.signatures[userId])));\n }\n }\n return new Device({\n deviceId: device.device_id,\n userId: device.user_id,\n keys,\n algorithms: device.algorithms,\n verified: DeviceVerification.Unverified,\n signatures,\n displayName\n });\n}\n//# sourceMappingURL=device-converter.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\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\n/** Manages the cross-signing keys for our own user.\n *\n * @internal\n */\nexport class CrossSigningIdentity {\n constructor(logger, olmMachine, outgoingRequestProcessor, secretStorage) {\n this.logger = logger;\n this.olmMachine = olmMachine;\n this.outgoingRequestProcessor = outgoingRequestProcessor;\n this.secretStorage = secretStorage;\n }\n\n /**\n * Initialise our cross-signing keys by creating new keys if they do not exist, and uploading to the server\n */\n bootstrapCrossSigning(opts) {\n var _this = this;\n return _asyncToGenerator(function* () {\n if (opts.setupNewCrossSigning) {\n yield _this.resetCrossSigning(opts.authUploadDeviceSigningKeys);\n return;\n }\n var olmDeviceStatus = yield _this.olmMachine.crossSigningStatus();\n\n // Try to fetch cross signing keys from the secret storage\n var masterKeyFromSecretStorage = yield _this.secretStorage.get(\"m.cross_signing.master\");\n var selfSigningKeyFromSecretStorage = yield _this.secretStorage.get(\"m.cross_signing.self_signing\");\n var userSigningKeyFromSecretStorage = yield _this.secretStorage.get(\"m.cross_signing.user_signing\");\n var privateKeysInSecretStorage = Boolean(masterKeyFromSecretStorage && selfSigningKeyFromSecretStorage && userSigningKeyFromSecretStorage);\n var olmDeviceHasKeys = olmDeviceStatus.hasMaster && olmDeviceStatus.hasUserSigning && olmDeviceStatus.hasSelfSigning;\n\n // Log all relevant state for easier parsing of debug logs.\n _this.logger.debug(\"bootstrapCrossSigning: starting\", {\n setupNewCrossSigning: opts.setupNewCrossSigning,\n olmDeviceHasMaster: olmDeviceStatus.hasMaster,\n olmDeviceHasUserSigning: olmDeviceStatus.hasUserSigning,\n olmDeviceHasSelfSigning: olmDeviceStatus.hasSelfSigning,\n privateKeysInSecretStorage\n });\n if (olmDeviceHasKeys) {\n if (!(yield _this.secretStorage.hasKey())) {\n _this.logger.warn(\"bootstrapCrossSigning: Olm device has private keys, but secret storage is not yet set up; doing nothing for now.\");\n // the keys should get uploaded to 4S once that is set up.\n } else if (!privateKeysInSecretStorage) {\n // the device has the keys but they are not in 4S, so update it\n _this.logger.debug(\"bootstrapCrossSigning: Olm device has private keys: exporting to secret storage\");\n yield _this.exportCrossSigningKeysToStorage();\n } else {\n _this.logger.debug(\"bootstrapCrossSigning: Olm device has private keys and they are saved in secret storage; doing nothing\");\n }\n } /* (!olmDeviceHasKeys) */else {\n if (privateKeysInSecretStorage) {\n // they are in 4S, so import from there\n _this.logger.debug(\"bootstrapCrossSigning: Cross-signing private keys not found locally, but they are available \" + \"in secret storage, reading storage and caching locally\");\n var status = yield _this.olmMachine.importCrossSigningKeys(masterKeyFromSecretStorage, selfSigningKeyFromSecretStorage, userSigningKeyFromSecretStorage);\n\n // Check that `importCrossSigningKeys` worked correctly (for example, it will fail silently if the\n // public keys are not available).\n if (!status.hasMaster || !status.hasSelfSigning || !status.hasUserSigning) {\n throw new Error(\"importCrossSigningKeys failed to import the keys\");\n }\n\n // Get the current device\n var device = yield _this.olmMachine.getDevice(_this.olmMachine.userId, _this.olmMachine.deviceId);\n try {\n // Sign the device with our cross-signing key and upload the signature\n var request = yield device.verify();\n yield _this.outgoingRequestProcessor.makeOutgoingRequest(request);\n } finally {\n device.free();\n }\n } else {\n _this.logger.debug(\"bootstrapCrossSigning: Cross-signing private keys not found locally or in secret storage, creating new keys\");\n yield _this.resetCrossSigning(opts.authUploadDeviceSigningKeys);\n }\n }\n\n // TODO: we might previously have bootstrapped cross-signing but not completed uploading the keys to the\n // server -- in which case we should call OlmDevice.bootstrap_cross_signing. How do we know?\n _this.logger.debug(\"bootstrapCrossSigning: complete\");\n })();\n }\n\n /** Reset our cross-signing keys\n *\n * This method will:\n * * Tell the OlmMachine to create new keys\n * * Upload the new public keys and the device signature to the server\n * * Upload the private keys to SSSS, if it is set up\n */\n resetCrossSigning(authUploadDeviceSigningKeys) {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n // XXX: We must find a way to make this atomic, currently if the user does not remember his account password\n // or 4S passphrase/key the process will fail in a bad state, with keys rotated but not uploaded or saved in 4S.\n var outgoingRequests = yield _this2.olmMachine.bootstrapCrossSigning(true);\n\n // If 4S is configured we need to update it.\n if (!(yield _this2.secretStorage.hasKey())) {\n _this2.logger.warn(\"resetCrossSigning: Secret storage is not yet set up; not exporting keys to secret storage yet.\");\n // the keys should get uploaded to 4S once that is set up.\n } else {\n // Update 4S before uploading cross-signing keys, to stay consistent with legacy that asks\n // 4S passphrase before asking for account password.\n // Ultimately should be made atomic and resistant to forgotten password/passphrase.\n _this2.logger.debug(\"resetCrossSigning: exporting private keys to secret storage\");\n yield _this2.exportCrossSigningKeysToStorage();\n }\n _this2.logger.debug(\"resetCrossSigning: publishing public keys to server\");\n for (var req of [outgoingRequests.uploadKeysRequest, outgoingRequests.uploadSigningKeysRequest, outgoingRequests.uploadSignaturesRequest]) {\n if (req) {\n yield _this2.outgoingRequestProcessor.makeOutgoingRequest(req, authUploadDeviceSigningKeys);\n }\n }\n })();\n }\n\n /**\n * Extract the cross-signing keys from the olm machine and save them to secret storage, if it is configured\n *\n * (If secret storage is *not* configured, we assume that the export will happen when it is set up)\n */\n exportCrossSigningKeysToStorage() {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n var exported = yield _this3.olmMachine.exportCrossSigningKeys();\n /* istanbul ignore else (this function is only called when we know the olm machine has keys) */\n if (exported !== null && exported !== void 0 && exported.masterKey) {\n yield _this3.secretStorage.store(\"m.cross_signing.master\", exported.masterKey);\n } else {\n _this3.logger.error(\"Cannot export MSK to secret storage, private key unknown\");\n }\n if (exported !== null && exported !== void 0 && exported.self_signing_key) {\n yield _this3.secretStorage.store(\"m.cross_signing.self_signing\", exported.self_signing_key);\n } else {\n _this3.logger.error(\"Cannot export SSK to secret storage, private key unknown\");\n }\n if (exported !== null && exported !== void 0 && exported.userSigningKey) {\n yield _this3.secretStorage.store(\"m.cross_signing.user_signing\", exported.userSigningKey);\n } else {\n _this3.logger.error(\"Cannot export USK to secret storage, private key unknown\");\n }\n })();\n }\n}\n//# sourceMappingURL=CrossSigningIdentity.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\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\n/**\n * Check that the private cross signing keys (master, self signing, user signing) are stored in the secret storage and encrypted with the default secret storage key.\n *\n * @param secretStorage - The secret store using account data\n * @returns True if the cross-signing keys are all stored and encrypted with the same secret storage key.\n *\n * @internal\n */\nexport function secretStorageContainsCrossSigningKeys(_x) {\n return _secretStorageContainsCrossSigningKeys.apply(this, arguments);\n}\n\n/**\n *\n * Check that the secret storage can access the given secrets using the default key.\n *\n * @param secretStorage - The secret store using account data\n * @param secretNames - The secret names to check\n * @returns True if all the given secrets are accessible and encrypted with the given key.\n *\n * @internal\n */\nfunction _secretStorageContainsCrossSigningKeys() {\n _secretStorageContainsCrossSigningKeys = _asyncToGenerator(function* (secretStorage) {\n return secretStorageCanAccessSecrets(secretStorage, [\"m.cross_signing.master\", \"m.cross_signing.user_signing\", \"m.cross_signing.self_signing\"]);\n });\n return _secretStorageContainsCrossSigningKeys.apply(this, arguments);\n}\nexport function secretStorageCanAccessSecrets(_x2, _x3) {\n return _secretStorageCanAccessSecrets.apply(this, arguments);\n}\nfunction _secretStorageCanAccessSecrets() {\n _secretStorageCanAccessSecrets = _asyncToGenerator(function* (secretStorage, secretNames) {\n var defaultKeyId = yield secretStorage.getDefaultKeyId();\n if (!defaultKeyId) return false;\n for (var secretName of secretNames) {\n // check which keys this particular secret is encrypted with\n var record = (yield secretStorage.isStored(secretName)) || {};\n // if it's not encrypted with the right key, there is no point continuing\n if (!(defaultKeyId in record)) return false;\n }\n return true;\n });\n return _secretStorageCanAccessSecrets.apply(this, arguments);\n}\n//# sourceMappingURL=secret-storage.js.map","/*\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\n/*\n * This file is a secondary entrypoint for the js-sdk library, for use by Typescript projects.\n * It exposes low-level types and interfaces reflecting structures defined in the Matrix specification.\n *\n * Remember to only export *public* types from this file.\n */\n\nexport * from \"./@types/membership.js\";\n/** The different methods for device and user verification */\nexport var VerificationMethod = /*#__PURE__*/function (VerificationMethod) {\n /** Short authentication string (emoji or decimals).\n *\n * @see https://spec.matrix.org/v1.9/client-server-api/#short-authentication-string-sas-verification\n */\n VerificationMethod[\"Sas\"] = \"m.sas.v1\";\n /**\n * Verification by showing a QR code which is scanned by the other device.\n *\n * @see https://spec.matrix.org/v1.9/client-server-api/#qr-codes\n */\n VerificationMethod[\"ShowQrCode\"] = \"m.qr_code.show.v1\";\n /**\n * Verification by scanning a QR code that is shown by the other device.\n *\n * @see https://spec.matrix.org/v1.9/client-server-api/#qr-codes\n */\n VerificationMethod[\"ScanQrCode\"] = \"m.qr_code.scan.v1\";\n /**\n * Verification by confirming that we have scanned a QR code.\n *\n * @see https://spec.matrix.org/v1.9/client-server-api/#qr-codes\n */\n VerificationMethod[\"Reciprocate\"] = \"m.reciprocate.v1\";\n return VerificationMethod;\n}({});\n//# sourceMappingURL=types.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\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 * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { QrState } from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { VerificationPhase, VerificationRequestEvent, VerifierEvent } from \"../crypto-api/verification.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { TypedReEmitter } from \"../ReEmitter.js\";\nimport { EventType, MsgType } from \"../@types/event.js\";\nimport { VerificationMethod } from \"../types.js\";\n/**\n * An incoming, or outgoing, request to verify a user or a device via cross-signing.\n *\n * @internal\n */\nexport class RustVerificationRequest extends TypedEventEmitter {\n /**\n * Construct a new RustVerificationRequest to wrap the rust-level `VerificationRequest`.\n *\n * @param logger - A logger instance which will be used to log events.\n * @param olmMachine - The `OlmMachine` from the underlying rust crypto sdk.\n * @param inner - VerificationRequest from the Rust SDK.\n * @param outgoingRequestProcessor - `OutgoingRequestProcessor` to use for making outgoing HTTP requests.\n * @param supportedVerificationMethods - Verification methods to use when `accept()` is called.\n */\n constructor(logger, olmMachine, inner, outgoingRequestProcessor, supportedVerificationMethods) {\n super();\n this.logger = logger;\n this.olmMachine = olmMachine;\n this.inner = inner;\n this.outgoingRequestProcessor = outgoingRequestProcessor;\n this.supportedVerificationMethods = supportedVerificationMethods;\n /** a reëmitter which relays VerificationRequestEvent.Changed events emitted by the verifier */\n _defineProperty(this, \"reEmitter\", void 0);\n /** Are we in the process of sending an `m.key.verification.ready` event? */\n _defineProperty(this, \"_accepting\", false);\n /** Are we in the process of sending an `m.key.verification.cancellation` event? */\n _defineProperty(this, \"_cancelling\", false);\n _defineProperty(this, \"_verifier\", void 0);\n this.reEmitter = new TypedReEmitter(this);\n\n // Obviously, the Rust object maintains a reference to the callback function. If the callback function maintains\n // a reference to the Rust object, then we have a reference cycle which means that `RustVerificationRequest`\n // will never be garbage-collected, and hence the underlying rust object will never be freed.\n //\n // To avoid this reference cycle, use a weak reference in the callback function. If the `RustVerificationRequest`\n // gets garbage-collected, then there is nothing to update!\n var weakThis = new WeakRef(this);\n inner.registerChangesCallback(/*#__PURE__*/_asyncToGenerator(function* () {\n var _weakThis$deref;\n return (_weakThis$deref = weakThis.deref()) === null || _weakThis$deref === void 0 ? void 0 : _weakThis$deref.onChange();\n }));\n }\n\n /**\n * Hook which is called when the underlying rust class notifies us that there has been a change.\n */\n onChange() {\n var verification = this.inner.getVerification();\n\n // Set the _verifier object (wrapping the rust `Verification` as a js-sdk Verifier) if:\n // - we now have a `Verification` where we lacked one before\n // - we have transitioned from QR to SAS\n // - we are verifying with SAS, but we need to replace our verifier with a new one because both parties\n // tried to start verification at the same time, and we lost the tie breaking\n if (verification instanceof RustSdkCryptoJs.Sas) {\n if (this._verifier === undefined || this._verifier instanceof RustQrCodeVerifier) {\n this.setVerifier(new RustSASVerifier(verification, this, this.outgoingRequestProcessor));\n } else if (this._verifier instanceof RustSASVerifier) {\n this._verifier.replaceInner(verification);\n }\n } else if (verification instanceof RustSdkCryptoJs.Qr && this._verifier === undefined) {\n this.setVerifier(new RustQrCodeVerifier(verification, this.outgoingRequestProcessor));\n }\n this.emit(VerificationRequestEvent.Change);\n }\n setVerifier(verifier) {\n // if we already have a verifier, unsubscribe from its events\n if (this._verifier) {\n this.reEmitter.stopReEmitting(this._verifier, [VerificationRequestEvent.Change]);\n }\n this._verifier = verifier;\n this.reEmitter.reEmit(this._verifier, [VerificationRequestEvent.Change]);\n }\n\n /**\n * Unique ID for this verification request.\n *\n * An ID isn't assigned until the first message is sent, so this may be `undefined` in the early phases.\n */\n get transactionId() {\n return this.inner.flowId;\n }\n\n /**\n * For an in-room verification, the ID of the room.\n *\n * For to-device verifications, `undefined`.\n */\n get roomId() {\n var _this$inner$roomId;\n return (_this$inner$roomId = this.inner.roomId) === null || _this$inner$roomId === void 0 ? void 0 : _this$inner$roomId.toString();\n }\n\n /**\n * True if this request was initiated by the local client.\n *\n * For in-room verifications, the initiator is who sent the `m.key.verification.request` event.\n * For to-device verifications, the initiator is who sent the `m.key.verification.start` event.\n */\n get initiatedByMe() {\n return this.inner.weStarted();\n }\n\n /** The user id of the other party in this request */\n get otherUserId() {\n return this.inner.otherUserId.toString();\n }\n\n /** For verifications via to-device messages: the ID of the other device. Otherwise, undefined. */\n get otherDeviceId() {\n var _this$inner$otherDevi;\n return (_this$inner$otherDevi = this.inner.otherDeviceId) === null || _this$inner$otherDevi === void 0 ? void 0 : _this$inner$otherDevi.toString();\n }\n\n /** Get the other device involved in the verification, if it is known */\n getOtherDevice() {\n var _this = this;\n return _asyncToGenerator(function* () {\n var otherDeviceId = _this.inner.otherDeviceId;\n if (!otherDeviceId) {\n return undefined;\n }\n return yield _this.olmMachine.getDevice(_this.inner.otherUserId, otherDeviceId, 5);\n })();\n }\n\n /** True if the other party in this request is one of this user's own devices. */\n get isSelfVerification() {\n return this.inner.isSelfVerification();\n }\n\n /** current phase of the request. */\n get phase() {\n var phase = this.inner.phase();\n switch (phase) {\n case RustSdkCryptoJs.VerificationRequestPhase.Created:\n case RustSdkCryptoJs.VerificationRequestPhase.Requested:\n return VerificationPhase.Requested;\n case RustSdkCryptoJs.VerificationRequestPhase.Ready:\n // if we're still sending the `m.key.verification.ready`, that counts as \"Requested\" in the js-sdk's\n // parlance.\n return this._accepting ? VerificationPhase.Requested : VerificationPhase.Ready;\n case RustSdkCryptoJs.VerificationRequestPhase.Transitioned:\n if (!this._verifier) {\n // this shouldn't happen, because the onChange handler should have created a _verifier.\n throw new Error(\"VerificationRequest: inner phase == Transitioned but no verifier!\");\n }\n return this._verifier.verificationPhase;\n case RustSdkCryptoJs.VerificationRequestPhase.Done:\n return VerificationPhase.Done;\n case RustSdkCryptoJs.VerificationRequestPhase.Cancelled:\n return VerificationPhase.Cancelled;\n }\n throw new Error(\"Unknown verification phase \".concat(phase));\n }\n\n /** True if the request has sent its initial event and needs more events to complete\n * (ie it is in phase `Requested`, `Ready` or `Started`).\n */\n get pending() {\n if (this.inner.isPassive()) return false;\n var phase = this.phase;\n return phase !== VerificationPhase.Done && phase !== VerificationPhase.Cancelled;\n }\n\n /**\n * True if we have started the process of sending an `m.key.verification.ready` (but have not necessarily received\n * the remote echo which causes a transition to {@link VerificationPhase.Ready}.\n */\n get accepting() {\n return this._accepting;\n }\n\n /**\n * True if we have started the process of sending an `m.key.verification.cancel` (but have not necessarily received\n * the remote echo which causes a transition to {@link VerificationPhase.Cancelled}).\n */\n get declining() {\n return this._cancelling;\n }\n\n /**\n * The remaining number of ms before the request will be automatically cancelled.\n *\n * `null` indicates that there is no timeout\n */\n get timeout() {\n return this.inner.timeRemainingMillis();\n }\n\n /** once the phase is Started (and !initiatedByMe) or Ready: common methods supported by both sides */\n get methods() {\n throw new Error(\"not implemented\");\n }\n\n /** the method picked in the .start event */\n get chosenMethod() {\n if (this.phase !== VerificationPhase.Started) return null;\n var verification = this.inner.getVerification();\n if (verification instanceof RustSdkCryptoJs.Sas) {\n return VerificationMethod.Sas;\n } else if (verification instanceof RustSdkCryptoJs.Qr) {\n return VerificationMethod.Reciprocate;\n } else {\n return null;\n }\n }\n\n /**\n * Checks whether the other party supports a given verification method.\n * This is useful when setting up the QR code UI, as it is somewhat asymmetrical:\n * if the other party supports SCAN_QR, we should show a QR code in the UI, and vice versa.\n * For methods that need to be supported by both ends, use the `methods` property.\n *\n * @param method - the method to check\n * @returns true if the other party said they supported the method\n */\n otherPartySupportsMethod(method) {\n var theirMethods = this.inner.theirSupportedMethods;\n if (theirMethods === undefined) {\n // no message from the other side yet\n return false;\n }\n var requiredMethod = verificationMethodsByIdentifier[method];\n return theirMethods.some(m => m === requiredMethod);\n }\n\n /**\n * Accepts the request, sending a .ready event to the other party\n *\n * @returns Promise which resolves when the event has been sent.\n */\n accept() {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n if (_this2.inner.phase() !== RustSdkCryptoJs.VerificationRequestPhase.Requested || _this2._accepting) {\n throw new Error(\"Cannot accept a verification request in phase \".concat(_this2.phase));\n }\n _this2._accepting = true;\n try {\n var req = _this2.inner.acceptWithMethods(_this2.supportedVerificationMethods.map(verificationMethodIdentifierToMethod));\n if (req) {\n yield _this2.outgoingRequestProcessor.makeOutgoingRequest(req);\n }\n } finally {\n _this2._accepting = false;\n }\n\n // phase may have changed, so emit a 'change' event\n _this2.emit(VerificationRequestEvent.Change);\n })();\n }\n\n /**\n * Cancels the request, sending a cancellation to the other party\n *\n * @param params - Details for the cancellation, including `reason` (defaults to \"User declined\"), and `code`\n * (defaults to `m.user`).\n *\n * @returns Promise which resolves when the event has been sent.\n */\n cancel(params) {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n if (_this3._cancelling) {\n // already cancelling; do nothing\n return;\n }\n _this3.logger.info(\"Cancelling verification request with params:\", params);\n _this3._cancelling = true;\n try {\n var req = _this3.inner.cancel();\n if (req) {\n yield _this3.outgoingRequestProcessor.makeOutgoingRequest(req);\n }\n } finally {\n _this3._cancelling = false;\n }\n })();\n }\n\n /**\n * Create a {@link Verifier} to do this verification via a particular method.\n *\n * If a verifier has already been created for this request, returns that verifier.\n *\n * This does *not* send the `m.key.verification.start` event - to do so, call {@link Verifier#verifier} on the\n * returned verifier.\n *\n * If no previous events have been sent, pass in `targetDevice` to set who to direct this request to.\n *\n * @param method - the name of the verification method to use.\n * @param targetDevice - details of where to send the request to.\n *\n * @returns The verifier which will do the actual verification.\n */\n beginKeyVerification(method, targetDevice) {\n throw new Error(\"not implemented\");\n }\n\n /**\n * Send an `m.key.verification.start` event to start verification via a particular method.\n *\n * Implementation of {@link Crypto.VerificationRequest#startVerification}.\n *\n * @param method - the name of the verification method to use.\n */\n startVerification(method) {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n if (method !== VerificationMethod.Sas) {\n throw new Error(\"Unsupported verification method \".concat(method));\n }\n\n // make sure that we have a list of the other user's devices (workaround https://github.com/matrix-org/matrix-rust-sdk/issues/2896)\n if (!(yield _this4.getOtherDevice())) {\n throw new Error(\"startVerification(): other device is unknown\");\n }\n var res = yield _this4.inner.startSas();\n if (res) {\n var [, req] = res;\n yield _this4.outgoingRequestProcessor.makeOutgoingRequest(req);\n }\n\n // this should have triggered the onChange callback, and we should now have a verifier\n if (!_this4._verifier) {\n throw new Error(\"Still no verifier after startSas() call\");\n }\n return _this4._verifier;\n })();\n }\n\n /**\n * Start a QR code verification by providing a scanned QR code for this verification flow.\n *\n * Implementation of {@link Crypto.VerificationRequest#scanQRCode}.\n *\n * @param qrCodeData - the decoded QR code.\n * @returns A verifier; call `.verify()` on it to wait for the other side to complete the verification flow.\n */\n scanQRCode(uint8Array) {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n var scan = RustSdkCryptoJs.QrCodeScan.fromBytes(uint8Array);\n var verifier = yield _this5.inner.scanQrCode(scan);\n\n // this should have triggered the onChange callback, and we should now have a verifier\n if (!_this5._verifier) {\n throw new Error(\"Still no verifier after scanQrCode() call\");\n }\n\n // we can immediately trigger the reciprocate request\n var req = verifier.reciprocate();\n if (req) {\n yield _this5.outgoingRequestProcessor.makeOutgoingRequest(req);\n }\n return _this5._verifier;\n })();\n }\n\n /**\n * The verifier which is doing the actual verification, once the method has been established.\n * Only defined when the `phase` is Started.\n */\n get verifier() {\n // It's possible for us to have a Verifier before a method has been chosen (in particular,\n // if we are showing a QR code which the other device has not yet scanned. At that point, we could\n // still switch to SAS).\n //\n // In that case, we should not return it to the application yet, since the application will not expect the\n // Verifier to be replaced during the lifetime of the VerificationRequest.\n return this.phase === VerificationPhase.Started ? this._verifier : undefined;\n }\n\n /**\n * Stub implementation of {@link Crypto.VerificationRequest#getQRCodeBytes}.\n */\n getQRCodeBytes() {\n throw new Error(\"getQRCodeBytes() unsupported in Rust Crypto; use generateQRCode() instead.\");\n }\n\n /**\n * Generate the data for a QR code allowing the other device to verify this one, if it supports it.\n *\n * Implementation of {@link Crypto.VerificationRequest#generateQRCode}.\n */\n generateQRCode() {\n var _this6 = this;\n return _asyncToGenerator(function* () {\n // make sure that we have a list of the other user's devices (workaround https://github.com/matrix-org/matrix-rust-sdk/issues/2896)\n if (!(yield _this6.getOtherDevice())) {\n throw new Error(\"generateQRCode(): other device is unknown\");\n }\n var innerVerifier = yield _this6.inner.generateQrCode();\n // If we are unable to generate a QRCode, we return undefined\n if (!innerVerifier) return;\n return innerVerifier.toBytes();\n })();\n }\n\n /**\n * If this request has been cancelled, the cancellation code (e.g `m.user`) which is responsible for cancelling\n * this verification.\n */\n get cancellationCode() {\n var _this$inner$cancelInf, _this$inner$cancelInf2;\n return (_this$inner$cancelInf = (_this$inner$cancelInf2 = this.inner.cancelInfo) === null || _this$inner$cancelInf2 === void 0 ? void 0 : _this$inner$cancelInf2.cancelCode()) !== null && _this$inner$cancelInf !== void 0 ? _this$inner$cancelInf : null;\n }\n\n /**\n * The id of the user that cancelled the request.\n *\n * Only defined when phase is Cancelled\n */\n get cancellingUserId() {\n var cancelInfo = this.inner.cancelInfo;\n if (!cancelInfo) {\n return undefined;\n } else if (cancelInfo.cancelledbyUs()) {\n return this.olmMachine.userId.toString();\n } else {\n return this.inner.otherUserId.toString();\n }\n }\n}\n\n/** Common base class for `Verifier` implementations which wrap rust classes.\n *\n * The generic parameter `InnerType` is the type of the rust Verification class which we wrap.\n *\n * @internal\n */\nclass BaseRustVerifer extends TypedEventEmitter {\n constructor(inner, outgoingRequestProcessor) {\n super();\n this.inner = inner;\n this.outgoingRequestProcessor = outgoingRequestProcessor;\n /** A deferred which completes when the verification completes (or rejects when it is cancelled/fails) */\n _defineProperty(this, \"completionDeferred\", void 0);\n this.completionDeferred = Promise.withResolvers();\n\n // As with RustVerificationRequest, we need to avoid a reference cycle.\n // See the comments in RustVerificationRequest.\n var weakThis = new WeakRef(this);\n inner.registerChangesCallback(/*#__PURE__*/_asyncToGenerator(function* () {\n var _weakThis$deref2;\n return (_weakThis$deref2 = weakThis.deref()) === null || _weakThis$deref2 === void 0 ? void 0 : _weakThis$deref2.onChange();\n }));\n\n // stop the runtime complaining if nobody catches a failure\n this.completionDeferred.promise.catch(() => null);\n }\n\n /**\n * Hook which is called when the underlying rust class notifies us that there has been a change.\n *\n * Can be overridden by subclasses to see if we can notify the application about an update. The overriding method\n * must call `super.onChange()`.\n */\n onChange() {\n if (this.inner.isDone()) {\n this.completionDeferred.resolve(undefined);\n } else if (this.inner.isCancelled()) {\n var cancelInfo = this.inner.cancelInfo();\n this.completionDeferred.reject(new Error(\"Verification cancelled by \".concat(cancelInfo.cancelledbyUs() ? \"us\" : \"them\", \" with code \").concat(cancelInfo.cancelCode(), \": \").concat(cancelInfo.reason())));\n }\n this.emit(VerificationRequestEvent.Change);\n }\n\n /**\n * Returns true if the verification has been cancelled, either by us or the other side.\n */\n get hasBeenCancelled() {\n return this.inner.isCancelled();\n }\n\n /**\n * The ID of the other user in the verification process.\n */\n get userId() {\n return this.inner.otherUserId.toString();\n }\n\n /**\n * Cancel a verification.\n *\n * We will send an `m.key.verification.cancel` if the verification is still in flight. The verification promise\n * will reject, and a {@link Crypto.VerifierEvent#Cancel} will be emitted.\n *\n * @param e - the reason for the cancellation.\n */\n cancel(e) {\n // TODO: something with `e`\n var req = this.inner.cancel();\n if (req) {\n this.outgoingRequestProcessor.makeOutgoingRequest(req);\n }\n }\n\n /**\n * Get the details for an SAS verification, if one is in progress\n *\n * Returns `null`, unless this verifier is for a SAS-based verification and we are waiting for the user to confirm\n * the SAS matches.\n */\n getShowSasCallbacks() {\n return null;\n }\n\n /**\n * Get the details for reciprocating QR code verification, if one is in progress\n *\n * Returns `null`, unless this verifier is for reciprocating a QR-code-based verification (ie, the other user has\n * already scanned our QR code), and we are waiting for the user to confirm.\n */\n getReciprocateQrCodeCallbacks() {\n return null;\n }\n}\n\n/** A Verifier instance which is used to show and/or scan a QR code. */\nexport class RustQrCodeVerifier extends BaseRustVerifer {\n constructor(inner, outgoingRequestProcessor) {\n super(inner, outgoingRequestProcessor);\n _defineProperty(this, \"callbacks\", null);\n }\n onChange() {\n // if the other side has scanned our QR code and sent us a \"reciprocate\" message, it is now time for the\n // application to prompt the user to confirm their side.\n if (this.callbacks === null && this.inner.hasBeenScanned()) {\n this.callbacks = {\n confirm: () => {\n this.confirmScanning();\n },\n cancel: () => this.cancel()\n };\n }\n super.onChange();\n }\n\n /**\n * Start the key verification, if it has not already been started.\n *\n * @returns Promise which resolves when the verification has completed, or rejects if the verification is cancelled\n * or times out.\n */\n verify() {\n var _this7 = this;\n return _asyncToGenerator(function* () {\n // Some applications (hello, matrix-react-sdk) may not check if there is a `ShowQrCodeCallbacks` and instead\n // register a `ShowReciprocateQr` listener which they expect to be called once `.verify` is called.\n if (_this7.callbacks !== null) {\n _this7.emit(VerifierEvent.ShowReciprocateQr, _this7.callbacks);\n }\n // Nothing to do here but wait.\n yield _this7.completionDeferred.promise;\n })();\n }\n\n /**\n * Calculate an appropriate VerificationPhase for a VerificationRequest where this is the verifier.\n *\n * This is abnormally complicated because a rust-side QR Code verifier can span several verification phases.\n */\n get verificationPhase() {\n switch (this.inner.state()) {\n case QrState.Created:\n // we have created a QR for display; neither side has yet sent an `m.key.verification.start`.\n return VerificationPhase.Ready;\n case QrState.Scanned:\n // other side has scanned our QR and sent an `m.key.verification.start` with `m.reciprocate.v1`\n return VerificationPhase.Started;\n case QrState.Confirmed:\n // we have confirmed the other side's scan and sent an `m.key.verification.done`.\n //\n // However, the verification is not yet \"Done\", because we have to wait until we have received the\n // `m.key.verification.done` from the other side (in particular, we don't mark the device/identity as\n // verified until that happens). If we return \"Done\" too soon, we risk the user cancelling the flow.\n return VerificationPhase.Started;\n case QrState.Reciprocated:\n // although the rust SDK doesn't immediately send the `m.key.verification.start` on transition into this\n // state, `RustVerificationRequest.scanQrCode` immediately calls `reciprocate()` and does so, so in practice\n // we can treat the two the same.\n return VerificationPhase.Started;\n case QrState.Done:\n return VerificationPhase.Done;\n case QrState.Cancelled:\n return VerificationPhase.Cancelled;\n default:\n throw new Error(\"Unknown qr code state \".concat(this.inner.state()));\n }\n }\n\n /**\n * Get the details for reciprocating QR code verification, if one is in progress\n *\n * Returns `null`, unless this verifier is for reciprocating a QR-code-based verification (ie, the other user has\n * already scanned our QR code), and we are waiting for the user to confirm.\n */\n getReciprocateQrCodeCallbacks() {\n return this.callbacks;\n }\n confirmScanning() {\n var _this8 = this;\n return _asyncToGenerator(function* () {\n var req = _this8.inner.confirmScanning();\n if (req) {\n yield _this8.outgoingRequestProcessor.makeOutgoingRequest(req);\n }\n })();\n }\n}\n\n/** A Verifier instance which is used if we are exchanging emojis */\nexport class RustSASVerifier extends BaseRustVerifer {\n constructor(inner, _verificationRequest, outgoingRequestProcessor) {\n super(inner, outgoingRequestProcessor);\n _defineProperty(this, \"callbacks\", null);\n }\n\n /**\n * Start the key verification, if it has not already been started.\n *\n * This means sending a `m.key.verification.start` if we are the first responder, or a `m.key.verification.accept`\n * if the other side has already sent a start event.\n *\n * @returns Promise which resolves when the verification has completed, or rejects if the verification is cancelled\n * or times out.\n */\n verify() {\n var _this9 = this;\n return _asyncToGenerator(function* () {\n yield _this9.sendAccept();\n yield _this9.completionDeferred.promise;\n })();\n }\n\n /**\n * Send the accept or start event, if it hasn't already been sent\n */\n sendAccept() {\n var _this0 = this;\n return _asyncToGenerator(function* () {\n var req = _this0.inner.accept();\n if (req) {\n yield _this0.outgoingRequestProcessor.makeOutgoingRequest(req);\n }\n })();\n }\n\n /** if we can now show the callbacks, do so */\n onChange() {\n var _this1 = this;\n super.onChange();\n if (this.callbacks === null) {\n var emoji = this.inner.emoji();\n var decimal = this.inner.decimals();\n if (emoji === undefined && decimal === undefined) {\n return;\n }\n var sas = {};\n if (emoji) {\n sas.emoji = emoji.map(e => [e.symbol, e.description]);\n }\n if (decimal) {\n sas.decimal = [decimal[0], decimal[1], decimal[2]];\n }\n this.callbacks = {\n sas,\n confirm: function () {\n var _confirm = _asyncToGenerator(function* () {\n var requests = yield _this1.inner.confirm();\n for (var m of requests) {\n yield _this1.outgoingRequestProcessor.makeOutgoingRequest(m);\n }\n });\n function confirm() {\n return _confirm.apply(this, arguments);\n }\n return confirm;\n }(),\n mismatch: () => {\n var request = this.inner.cancelWithCode(\"m.mismatched_sas\");\n if (request) {\n this.outgoingRequestProcessor.makeOutgoingRequest(request);\n }\n },\n cancel: () => {\n var request = this.inner.cancelWithCode(\"m.user\");\n if (request) {\n this.outgoingRequestProcessor.makeOutgoingRequest(request);\n }\n }\n };\n this.emit(VerifierEvent.ShowSas, this.callbacks);\n }\n }\n\n /**\n * Calculate an appropriate VerificationPhase for a VerificationRequest where this is the verifier.\n */\n get verificationPhase() {\n return VerificationPhase.Started;\n }\n\n /**\n * Get the details for an SAS verification, if one is in progress\n *\n * Returns `null`, unless this verifier is for a SAS-based verification and we are waiting for the user to confirm\n * the SAS matches.\n */\n getShowSasCallbacks() {\n return this.callbacks;\n }\n\n /**\n * Replace the inner Rust verifier with a different one.\n *\n * @param inner - the new Rust verifier\n * @internal\n */\n replaceInner(inner) {\n if (this.inner != inner) {\n this.inner = inner;\n\n // As with RustVerificationRequest, we need to avoid a reference cycle.\n // See the comments in RustVerificationRequest.\n var weakThis = new WeakRef(this);\n inner.registerChangesCallback(/*#__PURE__*/_asyncToGenerator(function* () {\n var _weakThis$deref3;\n return (_weakThis$deref3 = weakThis.deref()) === null || _weakThis$deref3 === void 0 ? void 0 : _weakThis$deref3.onChange();\n }));\n\n // replaceInner will only get called if we started the verification at the same time as the other side, and we lost\n // the tie breaker. So we need to re-accept their verification.\n this.sendAccept();\n this.onChange();\n }\n }\n}\n\n/** For each specced verification method, the rust-side `VerificationMethod` corresponding to it */\nvar verificationMethodsByIdentifier = {\n [VerificationMethod.Sas]: RustSdkCryptoJs.VerificationMethod.SasV1,\n [VerificationMethod.ScanQrCode]: RustSdkCryptoJs.VerificationMethod.QrCodeScanV1,\n [VerificationMethod.ShowQrCode]: RustSdkCryptoJs.VerificationMethod.QrCodeShowV1,\n [VerificationMethod.Reciprocate]: RustSdkCryptoJs.VerificationMethod.ReciprocateV1\n};\n\n/**\n * Convert a specced verification method identifier into a rust-side `VerificationMethod`.\n *\n * @param method - specced method identifier, for example `m.sas.v1`.\n * @returns Rust-side `VerificationMethod` corresponding to `method`.\n * @throws An error if the method is unknown.\n *\n * @internal\n */\nexport function verificationMethodIdentifierToMethod(method) {\n var meth = verificationMethodsByIdentifier[method];\n if (meth === undefined) {\n throw new Error(\"Unknown verification method \".concat(method));\n }\n return meth;\n}\n\n/**\n * Return true if the event's type matches that of an in-room verification event\n *\n * @param event - MatrixEvent\n * @returns\n *\n * @internal\n */\nexport function isVerificationEvent(event) {\n switch (event.getType()) {\n case EventType.KeyVerificationCancel:\n case EventType.KeyVerificationDone:\n case EventType.KeyVerificationMac:\n case EventType.KeyVerificationStart:\n case EventType.KeyVerificationKey:\n case EventType.KeyVerificationReady:\n case EventType.KeyVerificationAccept:\n return true;\n case EventType.RoomMessage:\n return event.getContent().msgtype === MsgType.KeyVerificationRequest;\n default:\n return false;\n }\n}\n//# sourceMappingURL=verification.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 - 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\";\nimport { ClientPrefix, MatrixError, Method } from \"../http-api/index.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { encodeUri, logDuration } from \"../utils.js\";\nimport { sleep } from \"../utils.js\";\nimport { CryptoEvent, ImportRoomKeyStage } from \"../crypto-api/index.js\";\n\n/** Authentification of the backup info, depends on algorithm */\n\n/**\n * Holds information of a created keybackup.\n * Useful to get the generated private key material and save it securely somewhere.\n */\n\n/**\n * @internal\n */\nexport class RustBackupManager extends TypedEventEmitter {\n constructor(logger, olmMachine, http, outgoingRequestProcessor) {\n super();\n this.logger = logger;\n this.olmMachine = olmMachine;\n this.http = http;\n this.outgoingRequestProcessor = outgoingRequestProcessor;\n /** Have we checked if there is a backup on the server which we can use */\n _defineProperty(this, \"checkedForBackup\", false);\n /**\n * The latest backup version on the server, when we last checked.\n *\n * If there was no backup on the server, `null`. If our attempt to check resulted in an error, `undefined`.\n *\n * Note that the backup was not necessarily verified.\n */\n _defineProperty(this, \"serverBackupInfo\", undefined);\n _defineProperty(this, \"activeBackupVersion\", null);\n _defineProperty(this, \"stopped\", false);\n /** whether {@link backupKeysLoop} is currently running */\n _defineProperty(this, \"backupKeysLoopRunning\", false);\n _defineProperty(this, \"keyBackupCheckInProgress\", null);\n }\n\n /**\n * Tells the RustBackupManager to stop.\n * The RustBackupManager is scheduling background uploads of keys to the backup, this\n * call allows to cancel the process when the client is stoppped.\n */\n stop() {\n this.stopped = true;\n }\n\n /**\n * Get the backup version we are currently backing up to, if any\n */\n getActiveBackupVersion() {\n var _this = this;\n return _asyncToGenerator(function* () {\n if (!(yield _this.olmMachine.isBackupEnabled())) return null;\n return _this.activeBackupVersion;\n })();\n }\n\n /**\n * Return the details of the latest backup on the server, when we last checked.\n *\n * This normally returns a cached value, but if we haven't yet made a request to the server, it will fire one off.\n * It will always return the details of the active backup if key backup is enabled.\n *\n * If there was no backup on the server, `null`. If our attempt to check resulted in an error, `undefined`.\n */\n getServerBackupInfo() {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n // Do a validity check if we haven't already done one. The check is likely to fail if we don't yet have the\n // backup keys -- but as a side-effect, it will populate `serverBackupInfo`.\n yield _this2.checkKeyBackupAndEnable(false);\n return _this2.serverBackupInfo;\n })();\n }\n\n /**\n * Determine if a key backup can be trusted.\n *\n * @param info - key backup info dict from {@link CryptoApi.getKeyBackupInfo}.\n */\n isKeyBackupTrusted(info) {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n var signatureVerification = yield _this3.olmMachine.verifyBackup(info);\n var backupKeys = yield _this3.olmMachine.getBackupKeys();\n var decryptionKey = backupKeys === null || backupKeys === void 0 ? void 0 : backupKeys.decryptionKey;\n var backupMatchesSavedPrivateKey = !!decryptionKey && _this3.backupInfoMatchesBackupDecryptionKey(info, decryptionKey);\n return {\n matchesDecryptionKey: backupMatchesSavedPrivateKey,\n trusted: signatureVerification.trusted()\n };\n })();\n }\n\n /**\n * Re-check the key backup and enable/disable it as appropriate.\n *\n * @param force - whether we should force a re-check even if one has already happened.\n */\n checkKeyBackupAndEnable(force) {\n if (!force && this.checkedForBackup) {\n return Promise.resolve(null);\n }\n\n // make sure there is only one check going on at a time\n if (!this.keyBackupCheckInProgress) {\n this.keyBackupCheckInProgress = this.doCheckKeyBackup().finally(() => {\n this.keyBackupCheckInProgress = null;\n });\n }\n return this.keyBackupCheckInProgress;\n }\n\n /**\n * Handles a backup secret received event and store it if it matches the current backup version.\n *\n * @param secret - The secret as received from a `m.secret.send` event for secret `m.megolm_backup.v1`.\n * @returns true if the secret is valid and has been stored, false otherwise.\n */\n handleBackupSecretReceived(secret) {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n var _latestBackupInfo;\n // Currently we only receive the decryption key without any key backup version. It is important to\n // check that the secret is valid for the current version before storing it.\n // We force a check to ensure to have the latest version.\n var latestBackupInfo;\n try {\n latestBackupInfo = yield _this4.requestKeyBackupVersion();\n } catch (e) {\n _this4.logger.warn(\"handleBackupSecretReceived: Error checking for latest key backup\", e);\n return false;\n }\n if (!((_latestBackupInfo = latestBackupInfo) !== null && _latestBackupInfo !== void 0 && _latestBackupInfo.version)) {\n // There is no server-side key backup.\n // This decryption key is useless to us.\n _this4.logger.warn(\"handleBackupSecretReceived: Received a backup decryption key, but there is no trusted server-side key backup\");\n return false;\n }\n try {\n var backupDecryptionKey = RustSdkCryptoJs.BackupDecryptionKey.fromBase64(secret);\n var privateKeyMatches = _this4.backupInfoMatchesBackupDecryptionKey(latestBackupInfo, backupDecryptionKey);\n if (!privateKeyMatches) {\n _this4.logger.warn(\"handleBackupSecretReceived: Private decryption key does not match the public key of the current remote backup.\");\n // just ignore the secret\n return false;\n }\n _this4.logger.info(\"handleBackupSecretReceived: A valid backup decryption key has been received and stored in cache.\");\n yield _this4.saveBackupDecryptionKey(backupDecryptionKey, latestBackupInfo.version);\n return true;\n } catch (e) {\n _this4.logger.warn(\"handleBackupSecretReceived: Invalid backup decryption key\", e);\n }\n return false;\n })();\n }\n saveBackupDecryptionKey(backupDecryptionKey, version) {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n yield _this5.olmMachine.saveBackupDecryptionKey(backupDecryptionKey, version);\n // Emit an event that we have a new backup decryption key, so that the sdk can start\n // importing keys from backup if needed.\n _this5.emit(CryptoEvent.KeyBackupDecryptionKeyCached, version);\n })();\n }\n\n /**\n * Import a list of room keys previously exported by exportRoomKeys\n *\n * @param keys - a list of session export objects\n * @param opts - options object\n * @returns a promise which resolves once the keys have been imported\n */\n importRoomKeys(keys, opts) {\n var _this6 = this;\n return _asyncToGenerator(function* () {\n yield _this6.importRoomKeysAsJson(JSON.stringify(keys), opts);\n })();\n }\n\n /**\n * Import a list of room keys previously exported by exportRoomKeysAsJson\n *\n * @param jsonKeys - a JSON string encoding a list of session export objects,\n * each of which is an IMegolmSessionData\n * @param opts - options object\n * @returns a promise which resolves once the keys have been imported\n */\n importRoomKeysAsJson(jsonKeys, opts) {\n var _this7 = this;\n return _asyncToGenerator(function* () {\n yield _this7.olmMachine.importExportedRoomKeys(jsonKeys, (progress, total) => {\n var _opts$progressCallbac;\n var importOpt = {\n total: Number(total),\n successes: Number(progress),\n stage: ImportRoomKeyStage.LoadKeys,\n failures: 0\n };\n opts === null || opts === void 0 || (_opts$progressCallbac = opts.progressCallback) === null || _opts$progressCallbac === void 0 || _opts$progressCallbac.call(opts, importOpt);\n });\n })();\n }\n\n /**\n * Implementation of {@link CryptoBackend#importBackedUpRoomKeys}.\n */\n importBackedUpRoomKeys(keys, backupVersion, opts) {\n var _this8 = this;\n return _asyncToGenerator(function* () {\n var keysByRoom = new Map();\n for (var key of keys) {\n var roomId = new RustSdkCryptoJs.RoomId(key.room_id);\n if (!keysByRoom.has(roomId)) {\n keysByRoom.set(roomId, new Map());\n }\n keysByRoom.get(roomId).set(key.session_id, key);\n }\n yield _this8.olmMachine.importBackedUpRoomKeys(keysByRoom, (progress, total, failures) => {\n var _opts$progressCallbac2;\n var importOpt = {\n total: Number(total),\n successes: Number(progress),\n stage: ImportRoomKeyStage.LoadKeys,\n failures: Number(failures)\n };\n opts === null || opts === void 0 || (_opts$progressCallbac2 = opts.progressCallback) === null || _opts$progressCallbac2 === void 0 || _opts$progressCallbac2.call(opts, importOpt);\n }, backupVersion);\n })();\n }\n /** Helper for `checkKeyBackup` */\n doCheckKeyBackup() {\n var _this9 = this;\n return _asyncToGenerator(function* () {\n _this9.logger.debug(\"Checking key backup status...\");\n var backupInfo;\n try {\n backupInfo = yield _this9.requestKeyBackupVersion();\n } catch (e) {\n _this9.logger.warn(\"Error checking for active key backup\", e);\n _this9.serverBackupInfo = undefined;\n return null;\n }\n _this9.checkedForBackup = true;\n if (backupInfo && !backupInfo.version) {\n _this9.logger.warn(\"active backup lacks a useful 'version'; ignoring it\");\n backupInfo = undefined;\n }\n _this9.serverBackupInfo = backupInfo;\n var activeVersion = yield _this9.getActiveBackupVersion();\n if (!backupInfo) {\n if (activeVersion !== null) {\n _this9.logger.debug(\"No key backup present on server: disabling key backup\");\n yield _this9.disableKeyBackup();\n } else {\n _this9.logger.debug(\"No key backup present on server: not enabling key backup\");\n }\n return null;\n }\n var trustInfo = yield _this9.isKeyBackupTrusted(backupInfo);\n\n // Per the spec, we should enable key upload if either (a) the backup is signed by a trusted key, or\n // (b) the public key matches the private decryption key that we have received from 4S.\n if (!trustInfo.matchesDecryptionKey && !trustInfo.trusted) {\n if (activeVersion !== null) {\n _this9.logger.debug(\"Key backup present on server but not trusted: disabling key backup\");\n yield _this9.disableKeyBackup();\n } else {\n _this9.logger.debug(\"Key backup present on server but not trusted: not enabling key backup\");\n }\n } else {\n if (activeVersion === null) {\n _this9.logger.debug(\"Found usable key backup v\".concat(backupInfo.version, \": enabling key backups\"));\n yield _this9.enableKeyBackup(backupInfo);\n } else if (activeVersion !== backupInfo.version) {\n _this9.logger.debug(\"On backup version \".concat(activeVersion, \" but found version \").concat(backupInfo.version, \": switching.\"));\n // This will remove any pending backup request, remove the backup key and reset the backup state of each room key we have.\n yield _this9.disableKeyBackup();\n // Enabling will now trigger re-upload of all the keys\n yield _this9.enableKeyBackup(backupInfo);\n } else {\n _this9.logger.debug(\"Backup version \".concat(backupInfo.version, \" still current\"));\n }\n }\n return {\n backupInfo,\n trustInfo\n };\n })();\n }\n enableKeyBackup(backupInfo) {\n var _this0 = this;\n return _asyncToGenerator(function* () {\n // we know for certain it must be a Curve25519 key, because we have verified it and only Curve25519\n // keys can be verified.\n //\n // we also checked it has a valid `version`.\n yield _this0.olmMachine.enableBackupV1(backupInfo.auth_data.public_key, backupInfo.version);\n _this0.activeBackupVersion = backupInfo.version;\n _this0.emit(CryptoEvent.KeyBackupStatus, true);\n _this0.backupKeysLoop();\n })();\n }\n\n /**\n * Restart the backup key loop if there is an active trusted backup.\n * Doesn't try to check the backup server side. To be called when a new\n * megolm key is known locally.\n */\n maybeUploadKey() {\n var _this1 = this;\n return _asyncToGenerator(function* () {\n if (_this1.activeBackupVersion != null) {\n _this1.backupKeysLoop();\n }\n })();\n }\n disableKeyBackup() {\n var _this10 = this;\n return _asyncToGenerator(function* () {\n yield _this10.olmMachine.disableBackup();\n _this10.activeBackupVersion = null;\n _this10.emit(CryptoEvent.KeyBackupStatus, false);\n })();\n }\n backupKeysLoop() {\n var _arguments = arguments,\n _this11 = this;\n return _asyncToGenerator(function* () {\n var maxDelay = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : 10000;\n if (_this11.backupKeysLoopRunning) {\n _this11.logger.debug(\"Backup loop already running\");\n return;\n }\n _this11.backupKeysLoopRunning = true;\n _this11.logger.debug(\"Backup: Starting keys upload loop for backup version:\".concat(_this11.activeBackupVersion, \".\"));\n\n // wait between 0 and `maxDelay` seconds, to avoid backup\n // requests from different clients hitting the server all at\n // the same time when a new key is sent\n var delay = Math.random() * maxDelay;\n yield sleep(delay);\n try {\n // number of consecutive network failures for exponential backoff\n var numFailures = 0;\n // The number of keys left to back up. (Populated lazily: see more comments below.)\n var remainingToUploadCount = null;\n // To avoid computing the key when only a few keys were added (after a sync for example),\n // we compute the count only when at least two iterations are needed.\n var isFirstIteration = true;\n while (!_this11.stopped) {\n // Get a batch of room keys to upload\n var request = undefined;\n try {\n request = yield logDuration(_this11.logger, \"BackupRoomKeys: Get keys to backup from rust crypto-sdk\", /*#__PURE__*/_asyncToGenerator(function* () {\n return yield _this11.olmMachine.backupRoomKeys();\n }));\n } catch (err) {\n _this11.logger.error(\"Backup: Failed to get keys to backup from rust crypto-sdk\", err);\n }\n if (!request || _this11.stopped || !_this11.activeBackupVersion) {\n _this11.logger.debug(\"Backup: Ending loop for version \".concat(_this11.activeBackupVersion, \".\"));\n if (!request) {\n // nothing more to upload\n _this11.emit(CryptoEvent.KeyBackupSessionsRemaining, 0);\n }\n return;\n }\n try {\n yield _this11.outgoingRequestProcessor.makeOutgoingRequest(request);\n numFailures = 0;\n if (_this11.stopped) break;\n\n // Key count performance (`olmMachine.roomKeyCounts()`) can be pretty bad on some configurations.\n // In particular, we detected on some M1 macs that when the object store reaches a threshold, the count\n // performance stops growing in O(n) and suddenly becomes very slow (40s, 60s or more).\n // For reference, the performance drop occurs around 300-400k keys on the platforms where this issue is observed.\n // Even on other configurations, the count can take several seconds.\n // This will block other operations on the database, like sending messages.\n //\n // This is a workaround to avoid calling `olmMachine.roomKeyCounts()` too often, and only when necessary.\n // We don't call it on the first loop because there could be only a few keys to upload, and we don't want to wait for the count.\n if (!isFirstIteration && remainingToUploadCount === null) {\n try {\n var keyCount = yield _this11.olmMachine.roomKeyCounts();\n remainingToUploadCount = keyCount.total - keyCount.backedUp;\n } catch (err) {\n _this11.logger.error(\"Backup: Failed to get key counts from rust crypto-sdk\", err);\n }\n }\n if (remainingToUploadCount !== null) {\n _this11.emit(CryptoEvent.KeyBackupSessionsRemaining, remainingToUploadCount);\n var keysCountInBatch = _this11.keysCountInBatch(request);\n // `OlmMachine.roomKeyCounts` is called only once for the current backupKeysLoop. But new\n // keys could be added during the current loop (after a sync for example).\n // So the count can get out of sync with the real number of remaining keys to upload.\n // Depending on the number of new keys imported and the time to complete the loop,\n // this could result in multiple events being emitted with a remaining key count of 0.\n remainingToUploadCount = Math.max(remainingToUploadCount - keysCountInBatch, 0);\n }\n } catch (err) {\n numFailures++;\n _this11.logger.error(\"Backup: Error processing backup request for rust crypto-sdk\", err);\n if (err instanceof MatrixError) {\n var errCode = err.data.errcode;\n if (errCode == \"M_NOT_FOUND\" || errCode == \"M_WRONG_ROOM_KEYS_VERSION\") {\n _this11.logger.debug(\"Backup: Failed to upload keys to current vesion: \".concat(errCode, \".\"));\n try {\n yield _this11.disableKeyBackup();\n } catch (error) {\n _this11.logger.error(\"Backup: An error occurred while disabling key backup:\", error);\n }\n _this11.emit(CryptoEvent.KeyBackupFailed, err.data.errcode);\n // There was an active backup and we are out of sync with the server\n // force a check server side\n _this11.backupKeysLoopRunning = false;\n _this11.checkKeyBackupAndEnable(true);\n return;\n } else if (err.isRateLimitError()) {\n // wait for that and then continue?\n try {\n var waitTime = err.getRetryAfterMs();\n if (waitTime && waitTime > 0) {\n yield sleep(waitTime);\n continue;\n }\n } catch (error) {\n _this11.logger.warn(\"Backup: An error occurred while retrieving a rate-limit retry delay\", error);\n } // else go to the normal backoff\n }\n }\n\n // Some other errors (mx, network, or CORS or invalid urls?) anyhow backoff\n // exponential backoff if we have failures\n yield sleep(1000 * Math.pow(2, Math.min(numFailures - 1, 4)));\n }\n isFirstIteration = false;\n }\n } finally {\n _this11.backupKeysLoopRunning = false;\n }\n })();\n }\n\n /**\n * Utility method to count the number of keys in a backup request, in order to update the remaining keys count.\n * This should be the chunk size of the backup request for all requests but the last, but we don't have access to it\n * (it's static in the Rust SDK).\n * @param batch - The backup request to count the keys from.\n *\n * @returns The number of keys in the backup request.\n */\n keysCountInBatch(batch) {\n var parsedBody = JSON.parse(batch.body);\n return countKeysInBackup(parsedBody);\n }\n\n /**\n * Get information about a key backup from the server\n * - If version is provided, get information about that backup version.\n * - If no version is provided, get information about the latest backup.\n *\n * @param version - The version of the backup to get information about.\n * @returns Information object from API or null if there is no active backup.\n */\n requestKeyBackupVersion(version) {\n var _this12 = this;\n return _asyncToGenerator(function* () {\n return yield requestKeyBackupVersion(_this12.http, version);\n })();\n }\n\n /**\n * Creates a new key backup by generating a new random private key.\n *\n * If there is an existing backup server side it will be deleted and replaced\n * by the new one.\n *\n * @param signObject - Method that should sign the backup with existing device and\n * existing identity.\n * @returns a KeyBackupCreationInfo - All information related to the backup.\n */\n setupKeyBackup(signObject) {\n var _this13 = this;\n return _asyncToGenerator(function* () {\n // Clean up any existing backup\n yield _this13.deleteAllKeyBackupVersions();\n var randomKey = RustSdkCryptoJs.BackupDecryptionKey.createRandomKey();\n var pubKey = randomKey.megolmV1PublicKey;\n var authData = {\n public_key: pubKey.publicKeyBase64\n };\n yield signObject(authData);\n var res = yield _this13.http.authedRequest(Method.Post, \"/room_keys/version\", undefined, {\n algorithm: pubKey.algorithm,\n auth_data: authData\n }, {\n prefix: ClientPrefix.V3\n });\n yield _this13.saveBackupDecryptionKey(randomKey, res.version);\n return {\n version: res.version,\n algorithm: pubKey.algorithm,\n authData: authData,\n decryptionKey: randomKey\n };\n })();\n }\n\n /**\n * Deletes all key backups.\n *\n * Will call the API to delete active backup until there is no more present.\n */\n deleteAllKeyBackupVersions() {\n var _this14 = this;\n return _asyncToGenerator(function* () {\n var _yield$_this14$reques, _yield$_this14$reques2;\n // there could be several backup versions. Delete all to be safe.\n var current = (_yield$_this14$reques = (_yield$_this14$reques2 = yield _this14.requestKeyBackupVersion()) === null || _yield$_this14$reques2 === void 0 ? void 0 : _yield$_this14$reques2.version) !== null && _yield$_this14$reques !== void 0 ? _yield$_this14$reques : null;\n while (current != null) {\n var _yield$_this14$reques3, _yield$_this14$reques4;\n yield _this14.deleteKeyBackupVersion(current);\n current = (_yield$_this14$reques3 = (_yield$_this14$reques4 = yield _this14.requestKeyBackupVersion()) === null || _yield$_this14$reques4 === void 0 ? void 0 : _yield$_this14$reques4.version) !== null && _yield$_this14$reques3 !== void 0 ? _yield$_this14$reques3 : null;\n }\n\n // XXX: Should this also update Secret Storage and delete any existing keys?\n })();\n }\n\n /**\n * Deletes the given key backup.\n *\n * @param version - The backup version to delete.\n */\n deleteKeyBackupVersion(version) {\n var _this15 = this;\n return _asyncToGenerator(function* () {\n _this15.logger.debug(\"deleteKeyBackupVersion v:\".concat(version));\n var path = encodeUri(\"/room_keys/version/$version\", {\n $version: version\n });\n yield _this15.http.authedRequest(Method.Delete, path, undefined, undefined, {\n prefix: ClientPrefix.V3\n });\n // If the backup we are deleting is the active one, we need to disable the key backup and to have the local properties reset\n if (_this15.activeBackupVersion === version) {\n _this15.serverBackupInfo = null;\n yield _this15.disableKeyBackup();\n }\n })();\n }\n\n /**\n * Creates a new backup decryptor for the given private key.\n * @param decryptionKey - The private key to use for decryption.\n */\n createBackupDecryptor(decryptionKey) {\n return new RustBackupDecryptor(this.logger, decryptionKey);\n }\n\n /**\n * Restore a key backup.\n *\n * @param backupVersion - The version of the backup to restore.\n * @param backupDecryptor - The backup decryptor to use to decrypt the keys.\n * @param opts - Options for the restore.\n * @returns The total number of keys and the total imported.\n */\n restoreKeyBackup(backupVersion, backupDecryptor, opts) {\n var _this16 = this;\n return _asyncToGenerator(function* () {\n var keyBackup = yield _this16.downloadKeyBackup(backupVersion);\n return _this16.importKeyBackup(keyBackup, backupVersion, backupDecryptor, opts);\n })();\n }\n\n /**\n * Call `/room_keys/keys` to download the key backup (room keys) for the given backup version.\n * https://spec.matrix.org/v1.12/client-server-api/#get_matrixclientv3room_keyskeys\n *\n * @param backupVersion\n * @returns The key backup response.\n */\n downloadKeyBackup(backupVersion) {\n return this.http.authedRequest(Method.Get, \"/room_keys/keys\", {\n version: backupVersion\n }, undefined, {\n prefix: ClientPrefix.V3\n });\n }\n\n /**\n * Import the room keys from a `/room_keys/keys` call.\n * Calls `opts.progressCallback` with the progress of the import.\n *\n * @param keyBackup - The response from the server containing the keys to import.\n * @param backupVersion - The version of the backup info.\n * @param backupDecryptor - The backup decryptor to use to decrypt the keys.\n * @param opts - Options for the import.\n *\n * @returns The total number of keys and the total imported.\n *\n * @private\n */\n importKeyBackup(keyBackup, backupVersion, backupDecryptor, opts) {\n var _this17 = this;\n return _asyncToGenerator(function* () {\n var _opts$progressCallbac3;\n // We have a full backup here, it can get quite big, so we need to decrypt and import it in chunks.\n\n var CHUNK_SIZE = 200;\n // Get the total count as a first pass\n var totalKeyCount = countKeysInBackup(keyBackup);\n var totalImported = 0;\n var totalFailures = 0;\n opts === null || opts === void 0 || (_opts$progressCallbac3 = opts.progressCallback) === null || _opts$progressCallbac3 === void 0 || _opts$progressCallbac3.call(opts, {\n total: totalKeyCount,\n successes: totalImported,\n stage: ImportRoomKeyStage.LoadKeys,\n failures: totalFailures\n });\n\n /**\n * This method is called when we have enough chunks to decrypt.\n * It will decrypt the chunks and try to import the room keys.\n * @param roomChunks\n */\n var handleChunkCallback = /*#__PURE__*/function () {\n var _ref2 = _asyncToGenerator(function* (roomChunks) {\n var _opts$progressCallbac4;\n var currentChunk = [];\n var _loop = function* _loop(roomId) {\n // Decrypt the sessions for the given room\n var decryptedSessions = yield backupDecryptor.decryptSessions(roomChunks.get(roomId));\n // Add the decrypted sessions to the current chunk\n decryptedSessions.forEach(session => {\n // We set the room_id for each session\n session.room_id = roomId;\n currentChunk.push(session);\n });\n };\n for (var roomId of roomChunks.keys()) {\n yield* _loop(roomId);\n }\n\n // We have a chunk of decrypted keys: import them\n try {\n yield _this17.importBackedUpRoomKeys(currentChunk, backupVersion);\n totalImported += currentChunk.length;\n } catch (e) {\n totalFailures += currentChunk.length;\n // We failed to import some keys, but we should still try to import the rest?\n // Log the error and continue\n _this17.logger.error(\"Error importing keys from backup\", e);\n }\n opts === null || opts === void 0 || (_opts$progressCallbac4 = opts.progressCallback) === null || _opts$progressCallbac4 === void 0 || _opts$progressCallbac4.call(opts, {\n total: totalKeyCount,\n successes: totalImported,\n stage: ImportRoomKeyStage.LoadKeys,\n failures: totalFailures\n });\n });\n return function handleChunkCallback(_x) {\n return _ref2.apply(this, arguments);\n };\n }();\n var groupChunkCount = 0;\n var chunkGroupByRoom = new Map();\n\n // Iterate over the rooms and sessions to group them in chunks\n // And we call the handleChunkCallback when we have enough chunks to decrypt\n for (var [roomId, roomData] of Object.entries(keyBackup.rooms)) {\n // If there are no sessions for the room, skip it\n if (!roomData.sessions) continue;\n\n // Initialize a new chunk group for the current room\n chunkGroupByRoom.set(roomId, {});\n for (var [sessionId, session] of Object.entries(roomData.sessions)) {\n // We set previously the chunk group for the current room, so we can safely get it\n var sessionsForRoom = chunkGroupByRoom.get(roomId);\n sessionsForRoom[sessionId] = session;\n groupChunkCount += 1;\n // If we have enough chunks to decrypt, call the block callback\n if (groupChunkCount >= CHUNK_SIZE) {\n // We have enough chunks to decrypt\n yield handleChunkCallback(chunkGroupByRoom);\n // Reset the chunk group\n chunkGroupByRoom = new Map();\n // There might be remaining keys for that room, so add back an entry for the current room.\n chunkGroupByRoom.set(roomId, {});\n groupChunkCount = 0;\n }\n }\n }\n\n // Handle remaining chunk if needed\n if (groupChunkCount > 0) {\n yield handleChunkCallback(chunkGroupByRoom);\n }\n return {\n total: totalKeyCount,\n imported: totalImported\n };\n })();\n }\n\n /**\n * Checks if the provided backup info matches the given private key.\n *\n * @param info - The backup info to check.\n * @param backupDecryptionKey - The `BackupDecryptionKey` private key to check against.\n * @returns `true` if the private key can decrypt the backup, `false` otherwise.\n */\n backupInfoMatchesBackupDecryptionKey(info, backupDecryptionKey) {\n var _info$auth_data;\n if (info.algorithm !== \"m.megolm_backup.v1.curve25519-aes-sha2\") {\n this.logger.warn(\"backupMatchesPrivateKey: Unsupported backup algorithm\", info.algorithm);\n return false;\n }\n return ((_info$auth_data = info.auth_data) === null || _info$auth_data === void 0 ? void 0 : _info$auth_data.public_key) === backupDecryptionKey.megolmV1PublicKey.publicKeyBase64;\n }\n}\n/**\n * Implementation of {@link BackupDecryptor} for the rust crypto backend.\n */\nexport class RustBackupDecryptor {\n constructor(logger, decryptionKey) {\n this.logger = logger;\n _defineProperty(this, \"decryptionKey\", void 0);\n _defineProperty(this, \"sourceTrusted\", void 0);\n this.decryptionKey = decryptionKey;\n this.sourceTrusted = false;\n }\n\n /**\n * Implements {@link BackupDecryptor#decryptSessions}\n */\n decryptSessions(ciphertexts) {\n var _this18 = this;\n return _asyncToGenerator(function* () {\n var keys = [];\n for (var [sessionId, sessionData] of Object.entries(ciphertexts)) {\n try {\n var decrypted = JSON.parse(_this18.decryptionKey.decryptV1(sessionData.session_data.ephemeral, sessionData.session_data.mac, sessionData.session_data.ciphertext));\n decrypted.session_id = sessionId;\n keys.push(decrypted);\n } catch (e) {\n _this18.logger.debug(\"Failed to decrypt megolm session from backup\", e, sessionData);\n }\n }\n return keys;\n })();\n }\n\n /**\n * Implements {@link BackupDecryptor#free}\n */\n free() {\n this.decryptionKey.free();\n }\n}\n\n/**\n * Fetch a key backup info from the server.\n *\n * If `version` is provided, calls `GET /room_keys/version/$version` and gets the backup info for that version.\n * See https://spec.matrix.org/v1.12/client-server-api/#get_matrixclientv3room_keysversionversion.\n *\n * If not, calls `GET /room_keys/version` and gets the latest backup info.\n * See https://spec.matrix.org/v1.12/client-server-api/#get_matrixclientv3room_keysversion\n *\n * @param http\n * @param version - the specific version of the backup info to fetch\n * @returns The key backup info or null if there is no backup.\n */\nexport function requestKeyBackupVersion(_x2, _x3) {\n return _requestKeyBackupVersion.apply(this, arguments);\n}\n\n/**\n * Checks if the provided decryption key matches the public key of the key backup info.\n *\n * @param decryptionKey - The decryption key to check.\n * @param keyBackupInfo - The key backup info to check against.\n * @returns `true` if the decryption key matches the key backup info, `false` otherwise.\n */\nfunction _requestKeyBackupVersion() {\n _requestKeyBackupVersion = _asyncToGenerator(function* (http, version) {\n try {\n var path = version ? encodeUri(\"/room_keys/version/$version\", {\n $version: version\n }) : \"/room_keys/version\";\n return yield http.authedRequest(Method.Get, path, undefined, undefined, {\n prefix: ClientPrefix.V3\n });\n } catch (e) {\n if (e.errcode === \"M_NOT_FOUND\") {\n return null;\n } else {\n throw e;\n }\n }\n });\n return _requestKeyBackupVersion.apply(this, arguments);\n}\nexport function decryptionKeyMatchesKeyBackupInfo(decryptionKey, keyBackupInfo) {\n var authData = keyBackupInfo.auth_data;\n return authData.public_key === decryptionKey.megolmV1PublicKey.publicKeyBase64;\n}\n\n/**\n * Counts the total number of keys present in a key backup.\n * @param keyBackup - The key backup to count the keys from.\n * @returns The total number of keys in the backup.\n */\nfunction countKeysInBackup(keyBackup) {\n var count = 0;\n for (var {\n sessions\n } of Object.values(keyBackup.rooms)) {\n count += Object.keys(sessions).length;\n }\n return count;\n}\n\n/**\n * Response from GET `/room_keys/keys` endpoint.\n * See https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3room_keyskeys\n */\n//# sourceMappingURL=backup.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\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 { logDuration } from \"../utils.js\";\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 constructor(logger, olmMachine, outgoingRequestProcessor) {\n this.logger = logger;\n this.olmMachine = olmMachine;\n this.outgoingRequestProcessor = outgoingRequestProcessor;\n /** whether {@link stop} has been called */\n _defineProperty(this, \"stopped\", false);\n /** whether {@link outgoingRequestLoop} is currently running */\n _defineProperty(this, \"outgoingRequestLoopRunning\", false);\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 _defineProperty(this, \"nextLoopDeferred\", void 0);\n }\n\n /**\n * Shut down as soon as possible the current loop of outgoing requests processing.\n */\n stop() {\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 doProcessOutgoingRequests() {\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 var 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 outgoingRequestLoop() {\n var _this = this;\n return _asyncToGenerator(function* () {\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 var 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 yield _this.processOutgoingRequests().then(loopTickResolvers.resolve, loopTickResolvers.reject);\n }\n } finally {\n _this.outgoingRequestLoopRunning = false;\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 /**\n * Make a single request to `olmMachine.outgoingRequests` and do the corresponding requests.\n */\n processOutgoingRequests() {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n if (_this2.stopped) return;\n var outgoingRequests = yield _this2.olmMachine.outgoingRequests();\n var successes = 0;\n var _loop = function* _loop(request) {\n if (_this2.stopped) return {\n v: void 0\n };\n try {\n yield logDuration(_this2.logger, \"Make outgoing request \".concat(request.type), /*#__PURE__*/_asyncToGenerator(function* () {\n yield _this2.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 _this2.logger.error(\"Failed to process outgoing request \".concat(request.type, \": \").concat(e));\n }\n },\n _ret;\n for (var request of outgoingRequests) {\n _ret = yield* _loop(request);\n if (_ret) return _ret.v;\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 _this2.doProcessOutgoingRequests().catch(e => {\n _this2.logger.warn(\"processOutgoingRequests: Error re-checking outgoing requests\", e);\n });\n }\n })();\n }\n}\n//# sourceMappingURL=OutgoingRequestsManager.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/*\nCopyright 2023 - 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 { CryptoEvent } from \"../crypto-api/index.js\";\nimport { ClientPrefix, MatrixError, Method } from \"../http-api/index.js\";\nimport { encodeUri, sleep } from \"../utils.js\";\n// The minimum time to wait between two retries in case of errors. To avoid hammering the server.\nvar KEY_BACKUP_BACKOFF = 5000; // ms\n\n/**\n * Enumerates the different kind of errors that can occurs when downloading and importing a key from backup.\n */\nvar KeyDownloadErrorCode = /*#__PURE__*/function (KeyDownloadErrorCode) {\n /** The requested key is not in the backup. */\n KeyDownloadErrorCode[\"MISSING_DECRYPTION_KEY\"] = \"MISSING_DECRYPTION_KEY\";\n /** A network error occurred while trying to download the key from backup. */\n KeyDownloadErrorCode[\"NETWORK_ERROR\"] = \"NETWORK_ERROR\";\n /** The loop has been stopped. */\n KeyDownloadErrorCode[\"STOPPED\"] = \"STOPPED\";\n return KeyDownloadErrorCode;\n}(KeyDownloadErrorCode || {});\nclass KeyDownloadError extends Error {\n constructor(code) {\n super(\"Failed to get key from backup: \".concat(code));\n this.code = code;\n this.name = \"KeyDownloadError\";\n }\n}\nclass KeyDownloadRateLimitError extends Error {\n constructor(retryMillis) {\n super(\"Failed to get key from backup: rate limited\");\n this.retryMillis = retryMillis;\n this.name = \"KeyDownloadRateLimitError\";\n }\n}\n\n/** Details of a megolm session whose key we are trying to fetch. */\n\n/** Holds the current backup decryptor and version that should be used.\n *\n * This is intended to be used as an immutable object (a new instance should be created if the configuration changes),\n * and some of the logic relies on that, so the properties are marked as `readonly`.\n */\n\n/**\n * Used when an 'unable to decrypt' error occurs. It attempts to download the key from the backup.\n *\n * The current backup API lacks pagination, which can lead to lengthy key retrieval times for large histories (several 10s of minutes).\n * To mitigate this, keys are downloaded on demand as decryption errors occurs.\n * While this approach may result in numerous requests, it improves user experience by reducing wait times for message decryption.\n *\n * The PerSessionKeyBackupDownloader is resistant to backup configuration changes: it will automatically resume querying when\n * the backup is configured correctly.\n */\nexport class PerSessionKeyBackupDownloader {\n /**\n * Creates a new instance of PerSessionKeyBackupDownloader.\n *\n * @param backupManager - The backup manager to use.\n * @param olmMachine - The olm machine to use.\n * @param http - The http instance to use.\n * @param logger - The logger to use.\n */\n constructor(logger, olmMachine, http, backupManager) {\n this.olmMachine = olmMachine;\n this.http = http;\n this.backupManager = backupManager;\n _defineProperty(this, \"stopped\", false);\n /**\n * The version and decryption key to use with current backup if all set up correctly.\n *\n * Will not be set unless `hasConfigurationProblem` is `false`.\n */\n _defineProperty(this, \"configuration\", null);\n /** We remember when a session was requested and not found in backup to avoid query again too soon.\n * Map of session_id to timestamp */\n _defineProperty(this, \"sessionLastCheckAttemptedTime\", new Map());\n /** The logger to use */\n _defineProperty(this, \"logger\", void 0);\n /** Whether the download loop is running. */\n _defineProperty(this, \"downloadLoopRunning\", false);\n /** The list of requests that are queued. */\n _defineProperty(this, \"queuedRequests\", []);\n /** Remembers if we have a configuration problem. */\n _defineProperty(this, \"hasConfigurationProblem\", false);\n /** The current server backup version check promise. To avoid doing a server call if one is in flight. */\n _defineProperty(this, \"currentBackupVersionCheck\", null);\n /**\n * Called when the backup status changes (CryptoEvents)\n * This will trigger a check of the backup configuration.\n */\n _defineProperty(this, \"onBackupStatusChanged\", () => {\n // we want to force check configuration, so we clear the current one.\n this.hasConfigurationProblem = false;\n this.configuration = null;\n this.getOrCreateBackupConfiguration().then(configuration => {\n if (configuration) {\n // restart the download loop if it was stopped\n this.downloadKeysLoop();\n }\n });\n });\n this.logger = logger.getChild(\"[PerSessionKeyBackupDownloader]\");\n backupManager.on(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Check if key download is successfully configured and active.\n *\n * @return `true` if key download is correctly configured and active; otherwise `false`.\n */\n isKeyBackupDownloadConfigured() {\n return this.configuration !== null;\n }\n\n /**\n * Return the details of the latest backup on the server, when we last checked.\n *\n * This is just a convenience method to expose {@link RustBackupManager.getServerBackupInfo}.\n */\n getServerBackupInfo() {\n var _this = this;\n return _asyncToGenerator(function* () {\n return yield _this.backupManager.getServerBackupInfo();\n })();\n }\n\n /**\n * Called when a MissingRoomKey or UnknownMessageIndex decryption error is encountered.\n *\n * This will try to download the key from the backup if there is a trusted active backup.\n * In case of success the key will be imported and the onRoomKeysUpdated callback will be called\n * internally by the rust-sdk and decryption will be retried.\n *\n * @param roomId - The room ID of the room where the error occurred.\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n onDecryptionKeyMissingError(roomId, megolmSessionId) {\n // Several messages encrypted with the same session may be decrypted at the same time,\n // so we need to be resistant and not query several time the same session.\n if (this.isAlreadyInQueue(roomId, megolmSessionId)) {\n // There is already a request queued for this session, no need to queue another one.\n this.logger.trace(\"Not checking key backup for session \".concat(megolmSessionId, \" as it is already queued\"));\n return;\n }\n if (this.wasRequestedRecently(megolmSessionId)) {\n // We already tried to download this session recently and it was not in backup, no need to try again.\n this.logger.trace(\"Not checking key backup for session \".concat(megolmSessionId, \" as it was already requested recently\"));\n return;\n }\n\n // We always add the request to the queue, even if we have a configuration problem (can't access backup).\n // This is to make sure that if the configuration problem is resolved, we will try to download the key.\n // This will happen after an initial sync, at this point the backup will not yet be trusted and the decryption\n // key will not be available, but it will be just after the verification.\n // We don't need to persist it because currently on refresh the sdk will retry to decrypt the messages in error.\n this.queuedRequests.push({\n roomId,\n megolmSessionId\n });\n\n // Start the download loop if it's not already running.\n this.downloadKeysLoop();\n }\n stop() {\n this.stopped = true;\n this.backupManager.off(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n /** Returns true if the megolm session is already queued for download. */\n isAlreadyInQueue(roomId, megolmSessionId) {\n return this.queuedRequests.some(info => {\n return info.roomId == roomId && info.megolmSessionId == megolmSessionId;\n });\n }\n\n /**\n * Marks the session as not found in backup, to avoid retrying to soon for a key not in backup\n *\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n markAsNotFoundInBackup(megolmSessionId) {\n var now = Date.now();\n this.sessionLastCheckAttemptedTime.set(megolmSessionId, now);\n // if too big make some cleaning to keep under control\n if (this.sessionLastCheckAttemptedTime.size > 100) {\n this.sessionLastCheckAttemptedTime = new Map(Array.from(this.sessionLastCheckAttemptedTime).filter((sid, ts) => {\n return Math.max(now - ts, 0) < KEY_BACKUP_BACKOFF;\n }));\n }\n }\n\n /** Returns true if the session was requested recently. */\n wasRequestedRecently(megolmSessionId) {\n var lastCheck = this.sessionLastCheckAttemptedTime.get(megolmSessionId);\n if (!lastCheck) return false;\n return Math.max(Date.now() - lastCheck, 0) < KEY_BACKUP_BACKOFF;\n }\n getBackupDecryptionKey() {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n try {\n return yield _this2.olmMachine.getBackupKeys();\n } catch (_unused) {\n return null;\n }\n })();\n }\n\n /**\n * Requests a key from the server side backup.\n *\n * @param version - The backup version to use.\n * @param roomId - The room ID of the room where the error occurred.\n * @param sessionId - The megolm session ID that is missing.\n */\n requestRoomKeyFromBackup(version, roomId, sessionId) {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n var path = encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId,\n $sessionId: sessionId\n });\n return yield _this3.http.authedRequest(Method.Get, path, {\n version\n }, undefined, {\n prefix: ClientPrefix.V3\n });\n })();\n }\n downloadKeysLoop() {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n if (_this4.downloadLoopRunning) return;\n\n // If we have a configuration problem, we don't want to try to download.\n // If any configuration change is detected, we will retry and restart the loop.\n if (_this4.hasConfigurationProblem) return;\n _this4.downloadLoopRunning = true;\n try {\n while (_this4.queuedRequests.length > 0) {\n // we just peek the first one without removing it, so if a new request for same key comes in while we're\n // processing this one, it won't queue another request.\n var request = _this4.queuedRequests[0];\n try {\n // The backup could have changed between the time we queued the request and now, so we need to check\n var configuration = yield _this4.getOrCreateBackupConfiguration();\n if (!configuration) {\n // Backup is not configured correctly, so stop the loop.\n _this4.downloadLoopRunning = false;\n return;\n }\n var result = yield _this4.queryKeyBackup(request.roomId, request.megolmSessionId, configuration);\n if (_this4.stopped) {\n return;\n }\n // We got the encrypted key from backup, let's try to decrypt and import it.\n try {\n yield _this4.decryptAndImport(request, result, configuration);\n } catch (e) {\n _this4.logger.error(\"Error while decrypting and importing key backup for session \".concat(request.megolmSessionId), e);\n }\n // now remove the request from the queue as we've processed it.\n _this4.queuedRequests.shift();\n } catch (err) {\n if (err instanceof KeyDownloadError) {\n switch (err.code) {\n case KeyDownloadErrorCode.MISSING_DECRYPTION_KEY:\n _this4.markAsNotFoundInBackup(request.megolmSessionId);\n // continue for next one\n _this4.queuedRequests.shift();\n break;\n case KeyDownloadErrorCode.NETWORK_ERROR:\n // We don't want to hammer if there is a problem, so wait a bit.\n yield sleep(KEY_BACKUP_BACKOFF);\n break;\n case KeyDownloadErrorCode.STOPPED:\n // If the downloader was stopped, we don't want to retry.\n _this4.downloadLoopRunning = false;\n return;\n }\n } else if (err instanceof KeyDownloadRateLimitError) {\n // we want to retry after the backoff time\n yield sleep(err.retryMillis);\n }\n }\n }\n } finally {\n // all pending request have been processed, we can stop the loop.\n _this4.downloadLoopRunning = false;\n }\n })();\n }\n\n /**\n * Query the backup for a key.\n *\n * @param targetRoomId - ID of the room that the session is used in.\n * @param targetSessionId - ID of the session for which to check backup.\n * @param configuration - The backup configuration to use.\n */\n queryKeyBackup(targetRoomId, targetSessionId, configuration) {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n _this5.logger.debug(\"Checking key backup for session \".concat(targetSessionId));\n if (_this5.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n try {\n var res = yield _this5.requestRoomKeyFromBackup(configuration.backupVersion, targetRoomId, targetSessionId);\n _this5.logger.debug(\"Got key from backup for sessionId:\".concat(targetSessionId));\n return res;\n } catch (e) {\n if (_this5.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n _this5.logger.info(\"No luck requesting key backup for session \".concat(targetSessionId, \": \").concat(e));\n if (e instanceof MatrixError) {\n var errCode = e.data.errcode;\n if (errCode == \"M_NOT_FOUND\") {\n // Unfortunately the spec doesn't give us a way to differentiate between a missing key and a wrong version.\n // Synapse will return:\n // - \"error\": \"Unknown backup version\" if the version is wrong.\n // - \"error\": \"No room_keys found\" if the key is missing.\n // It's useful to know if the key is missing or if the version is wrong.\n // As it's not spec'ed, we fall back on considering the key is not in backup.\n // Notice that this request will be lost if instead the backup got out of sync (updated from other session).\n throw new KeyDownloadError(KeyDownloadErrorCode.MISSING_DECRYPTION_KEY);\n }\n if (e.isRateLimitError()) {\n var waitTime;\n try {\n var _e$getRetryAfterMs;\n waitTime = (_e$getRetryAfterMs = e.getRetryAfterMs()) !== null && _e$getRetryAfterMs !== void 0 ? _e$getRetryAfterMs : undefined;\n } catch (error) {\n _this5.logger.warn(\"Error while retrieving a rate-limit retry delay\", error);\n }\n if (waitTime && waitTime > 0) {\n _this5.logger.info(\"Rate limited by server, waiting \".concat(waitTime, \"ms\"));\n }\n throw new KeyDownloadRateLimitError(waitTime !== null && waitTime !== void 0 ? waitTime : KEY_BACKUP_BACKOFF);\n }\n }\n throw new KeyDownloadError(KeyDownloadErrorCode.NETWORK_ERROR);\n }\n })();\n }\n decryptAndImport(sessionInfo, data, configuration) {\n var _this6 = this;\n return _asyncToGenerator(function* () {\n var sessionsToImport = {\n [sessionInfo.megolmSessionId]: data\n };\n var keys = yield configuration.decryptor.decryptSessions(sessionsToImport);\n for (var k of keys) {\n k.room_id = sessionInfo.roomId;\n }\n yield _this6.backupManager.importBackedUpRoomKeys(keys, configuration.backupVersion);\n })();\n }\n\n /**\n * Gets the current backup configuration or create one if it doesn't exist.\n *\n * When a valid configuration is found it is cached and returned for subsequent calls.\n * Otherwise, if a check is forced or a check has not yet been done, a new check is done.\n *\n * @returns The backup configuration to use or null if there is a configuration problem.\n */\n getOrCreateBackupConfiguration() {\n var _this7 = this;\n return _asyncToGenerator(function* () {\n if (_this7.configuration) {\n return _this7.configuration;\n }\n\n // We already tried to check the configuration and it failed.\n // We don't want to try again immediately, we will retry if a configuration change is detected.\n if (_this7.hasConfigurationProblem) {\n return null;\n }\n\n // This method can be called rapidly by several emitted CryptoEvent, so we need to make sure that we don't\n // query the server several times.\n if (_this7.currentBackupVersionCheck != null) {\n _this7.logger.debug(\"Already checking server version, use current promise\");\n return yield _this7.currentBackupVersionCheck;\n }\n _this7.currentBackupVersionCheck = _this7.internalCheckFromServer();\n try {\n return yield _this7.currentBackupVersionCheck;\n } finally {\n _this7.currentBackupVersionCheck = null;\n }\n })();\n }\n internalCheckFromServer() {\n var _this8 = this;\n return _asyncToGenerator(function* () {\n var _currentServerVersion, _currentServerVersion2, _currentServerVersion4;\n var currentServerVersion = null;\n try {\n currentServerVersion = yield _this8.backupManager.getServerBackupInfo();\n } catch (e) {\n _this8.logger.debug(\"Backup: error while checking server version: \".concat(e));\n _this8.hasConfigurationProblem = true;\n return null;\n }\n _this8.logger.debug(\"Got current backup version from server: \".concat((_currentServerVersion = currentServerVersion) === null || _currentServerVersion === void 0 ? void 0 : _currentServerVersion.version));\n if (((_currentServerVersion2 = currentServerVersion) === null || _currentServerVersion2 === void 0 ? void 0 : _currentServerVersion2.algorithm) != \"m.megolm_backup.v1.curve25519-aes-sha2\") {\n var _currentServerVersion3;\n _this8.logger.info(\"Unsupported algorithm \".concat((_currentServerVersion3 = currentServerVersion) === null || _currentServerVersion3 === void 0 ? void 0 : _currentServerVersion3.algorithm));\n _this8.hasConfigurationProblem = true;\n return null;\n }\n if (!((_currentServerVersion4 = currentServerVersion) !== null && _currentServerVersion4 !== void 0 && _currentServerVersion4.version)) {\n _this8.logger.info(\"No current key backup\");\n _this8.hasConfigurationProblem = true;\n return null;\n }\n var activeVersion = yield _this8.backupManager.getActiveBackupVersion();\n if (activeVersion == null || currentServerVersion.version != activeVersion) {\n // Either the current backup version on server side is not trusted, or it is out of sync with the active version on the client side.\n _this8.logger.info(\"The current backup version on the server (\".concat(currentServerVersion.version, \") is not trusted. Version we are currently backing up to: \").concat(activeVersion));\n _this8.hasConfigurationProblem = true;\n return null;\n }\n var backupKeys = yield _this8.getBackupDecryptionKey();\n if (!(backupKeys !== null && backupKeys !== void 0 && backupKeys.decryptionKey)) {\n _this8.logger.debug(\"Not checking key backup for session (no decryption key)\");\n _this8.hasConfigurationProblem = true;\n return null;\n }\n if (activeVersion != backupKeys.backupVersion) {\n _this8.logger.debug(\"Version for which we have a decryption key (\".concat(backupKeys.backupVersion, \") doesn't match the version we are backing up to (\").concat(activeVersion, \")\"));\n _this8.hasConfigurationProblem = true;\n return null;\n }\n var authData = currentServerVersion.auth_data;\n if (authData.public_key != backupKeys.decryptionKey.megolmV1PublicKey.publicKeyBase64) {\n _this8.logger.debug(\"Key backup on server does not match our decryption key\");\n _this8.hasConfigurationProblem = true;\n return null;\n }\n var backupDecryptor = _this8.backupManager.createBackupDecryptor(backupKeys.decryptionKey);\n _this8.hasConfigurationProblem = false;\n _this8.configuration = {\n decryptor: backupDecryptor,\n backupVersion: activeVersion\n };\n return _this8.configuration;\n })();\n }\n}\n//# sourceMappingURL=PerSessionKeyBackupDownloader.js.map","/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deriveRecoveryKeyFromPassphrase } from \"../crypto-api/index.js\";\n\n/* eslint-disable camelcase */\n\n/**\n * Derive a backup key from a passphrase using the salt and iterations from the auth data.\n * @param authData - The auth data containing the salt and iterations\n * @param passphrase - The passphrase to derive the key from\n * @deprecated Deriving a backup key from a passphrase is not part of the matrix spec. Instead, a random key is generated and stored/shared via 4S.\n */\nexport function keyFromAuthData(authData, passphrase) {\n if (!authData.private_key_salt || !authData.private_key_iterations) {\n throw new Error(\"Salt and/or iterations not found: \" + \"this backup cannot be restored with a passphrase\");\n }\n return deriveRecoveryKeyFromPassphrase(passphrase, authData.private_key_salt, authData.private_key_iterations, authData.private_key_bits);\n}\n//# sourceMappingURL=key-passphrase.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\n/*\nCopyright 2022-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 anotherjson from \"another-json\";\nimport * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { KnownMembership } from \"../@types/membership.js\";\nimport { MatrixEventEvent } from \"../models/event.js\";\nimport { DecryptionError } from \"../common-crypto/CryptoBackend.js\";\nimport { LogSpan } from \"../logger.js\";\nimport { Method } from \"../http-api/index.js\";\nimport { RoomEncryptor } from \"./RoomEncryptor.js\";\nimport { OutgoingRequestProcessor } from \"./OutgoingRequestProcessor.js\";\nimport { KeyClaimManager } from \"./KeyClaimManager.js\";\nimport { MapWithDefault } from \"../utils.js\";\nimport { AllDevicesIsolationMode, CrossSigningKey, CryptoEvent, DecryptionFailureCode, deriveRecoveryKeyFromPassphrase, DeviceIsolationModeKind, DeviceVerificationStatus, encodeRecoveryKey, EventShieldColour, EventShieldReason, ImportRoomKeyStage, UserVerificationStatus } from \"../crypto-api/index.js\";\nimport { deviceKeysToDeviceMap, rustDeviceToJsDevice } from \"./device-converter.js\";\nimport { SECRET_STORAGE_ALGORITHM_V1_AES } from \"../secret-storage.js\";\nimport { CrossSigningIdentity } from \"./CrossSigningIdentity.js\";\nimport { secretStorageContainsCrossSigningKeys } from \"./secret-storage.js\";\nimport { isVerificationEvent, RustVerificationRequest, verificationMethodIdentifierToMethod } from \"./verification.js\";\nimport { EventType, MsgType } from \"../@types/event.js\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.js\";\nimport { decryptionKeyMatchesKeyBackupInfo, RustBackupManager } from \"./backup.js\";\nimport { TypedReEmitter } from \"../ReEmitter.js\";\nimport { secureRandomString } from \"../randomstring.js\";\nimport { ClientStoppedError } from \"../errors.js\";\nimport { decodeBase64, encodeBase64 } from \"../base64.js\";\nimport { OutgoingRequestsManager } from \"./OutgoingRequestsManager.js\";\nimport { PerSessionKeyBackupDownloader } from \"./PerSessionKeyBackupDownloader.js\";\nimport { DehydratedDeviceManager } from \"./DehydratedDeviceManager.js\";\nimport { VerificationMethod } from \"../types.js\";\nimport { keyFromAuthData } from \"../common-crypto/key-passphrase.js\";\nimport { getHttpUriForMxc } from \"../content-repo.js\";\nvar ALL_VERIFICATION_METHODS = [VerificationMethod.Sas, VerificationMethod.ScanQrCode, VerificationMethod.ShowQrCode, VerificationMethod.Reciprocate];\n/**\n * An implementation of {@link CryptoBackend} using the Rust matrix-sdk-crypto.\n *\n * @internal\n */\nexport class RustCrypto extends TypedEventEmitter {\n constructor(logger, /** The `OlmMachine` from the underlying rust crypto sdk. */\n olmMachine,\n /**\n * Low-level HTTP interface: used to make outgoing requests required by the rust SDK.\n *\n * We expect it to set the access token, etc.\n */\n http, /** The local user's User ID. */\n userId, /** The local user's Device ID. */\n _deviceId, /** Interface to server-side secret storage */\n secretStorage, /** Crypto callbacks provided by the application */\n cryptoCallbacks) {\n var enableEncryptedStateEvents = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false;\n super();\n this.logger = logger;\n this.olmMachine = olmMachine;\n this.http = http;\n this.userId = userId;\n this.secretStorage = secretStorage;\n this.cryptoCallbacks = cryptoCallbacks;\n this.enableEncryptedStateEvents = enableEncryptedStateEvents;\n /**\n * The number of iterations to use when deriving a recovery key from a passphrase.\n */\n _defineProperty(this, \"RECOVERY_KEY_DERIVATION_ITERATIONS\", 500000);\n _defineProperty(this, \"_trustCrossSignedDevices\", true);\n _defineProperty(this, \"deviceIsolationMode\", new AllDevicesIsolationMode(false));\n /** whether {@link stop} has been called */\n _defineProperty(this, \"stopped\", false);\n /** mapping of roomId → encryptor class */\n _defineProperty(this, \"roomEncryptors\", {});\n /** mapping of room ID -> inviter ID for rooms pending MSC4268 key bundles */\n _defineProperty(this, \"roomsPendingKeyBundles\", new Map());\n _defineProperty(this, \"eventDecryptor\", void 0);\n _defineProperty(this, \"keyClaimManager\", void 0);\n _defineProperty(this, \"outgoingRequestProcessor\", void 0);\n _defineProperty(this, \"crossSigningIdentity\", void 0);\n _defineProperty(this, \"backupManager\", void 0);\n _defineProperty(this, \"outgoingRequestsManager\", void 0);\n _defineProperty(this, \"perSessionBackupDownloader\", void 0);\n _defineProperty(this, \"dehydratedDeviceManager\", void 0);\n _defineProperty(this, \"reemitter\", new TypedReEmitter(this));\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n //\n // CryptoApi implementation\n //\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n _defineProperty(this, \"globalBlacklistUnverifiedDevices\", false);\n /**\n * The verification methods we offer to the other side during an interactive verification.\n */\n _defineProperty(this, \"_supportedVerificationMethods\", ALL_VERIFICATION_METHODS);\n this.outgoingRequestProcessor = new OutgoingRequestProcessor(logger, olmMachine, http);\n this.outgoingRequestsManager = new OutgoingRequestsManager(this.logger, olmMachine, this.outgoingRequestProcessor);\n this.keyClaimManager = new KeyClaimManager(olmMachine, this.outgoingRequestProcessor);\n this.backupManager = new RustBackupManager(logger, olmMachine, http, this.outgoingRequestProcessor);\n this.perSessionBackupDownloader = new PerSessionKeyBackupDownloader(this.logger, this.olmMachine, this.http, this.backupManager);\n this.dehydratedDeviceManager = new DehydratedDeviceManager(this.logger, olmMachine, http, this.outgoingRequestProcessor, secretStorage);\n this.eventDecryptor = new EventDecryptor(this.logger, olmMachine, this.perSessionBackupDownloader);\n\n // re-emit the events emitted by managers\n this.reemitter.reEmit(this.backupManager, [CryptoEvent.KeyBackupStatus, CryptoEvent.KeyBackupSessionsRemaining, CryptoEvent.KeyBackupFailed, CryptoEvent.KeyBackupDecryptionKeyCached]);\n this.reemitter.reEmit(this.dehydratedDeviceManager, [CryptoEvent.DehydratedDeviceCreated, CryptoEvent.DehydratedDeviceUploaded, CryptoEvent.RehydrationStarted, CryptoEvent.RehydrationProgress, CryptoEvent.RehydrationCompleted, CryptoEvent.RehydrationError, CryptoEvent.DehydrationKeyCached, CryptoEvent.DehydratedDeviceRotationError]);\n this.crossSigningIdentity = new CrossSigningIdentity(logger, olmMachine, this.outgoingRequestProcessor, secretStorage);\n\n // Check and start in background the key backup connection\n this.checkKeyBackupAndEnable();\n }\n\n /**\n * Return the OlmMachine only if {@link RustCrypto#stop} has not been called.\n *\n * This allows us to better handle race conditions where the client is stopped before or during a crypto API call.\n *\n * @throws ClientStoppedError if {@link RustCrypto#stop} has been called.\n */\n getOlmMachineOrThrow() {\n if (this.stopped) {\n throw new ClientStoppedError();\n }\n return this.olmMachine;\n }\n\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n //\n // CryptoBackend implementation\n //\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n set globalErrorOnUnknownDevices(_v) {\n // Not implemented for rust crypto.\n }\n get globalErrorOnUnknownDevices() {\n // Not implemented for rust crypto.\n return false;\n }\n stop() {\n // stop() may be called multiple times, but attempting to close() the OlmMachine twice\n // will cause an error.\n if (this.stopped) {\n return;\n }\n this.stopped = true;\n this.keyClaimManager.stop();\n this.backupManager.stop();\n this.outgoingRequestsManager.stop();\n this.perSessionBackupDownloader.stop();\n this.dehydratedDeviceManager.stop();\n\n // make sure we close() the OlmMachine; doing so means that all the Rust objects will be\n // cleaned up; in particular, the indexeddb connections will be closed, which means they\n // can then be deleted.\n this.olmMachine.close();\n }\n encryptEvent(event, _room) {\n var _this = this;\n return _asyncToGenerator(function* () {\n var roomId = event.getRoomId();\n var encryptor = _this.roomEncryptors[roomId];\n if (!encryptor) {\n throw new Error(\"Cannot encrypt event in unconfigured room \".concat(roomId));\n }\n yield encryptor.encryptEvent(event, _this.globalBlacklistUnverifiedDevices, _this.deviceIsolationMode);\n })();\n }\n decryptEvent(event) {\n var _this2 = this;\n return _asyncToGenerator(function* () {\n var roomId = event.getRoomId();\n if (!roomId) {\n // presumably, a to-device message. These are normally decrypted in preprocessToDeviceMessages\n // so the fact it has come back here suggests that decryption failed.\n //\n // once we drop support for the libolm crypto implementation, we can stop passing to-device messages\n // through decryptEvent and hence get rid of this case.\n throw new Error(\"to-device event was not decrypted in preprocessToDeviceMessages\");\n }\n return yield _this2.eventDecryptor.attemptEventDecryption(event, _this2.deviceIsolationMode);\n })();\n }\n\n /**\n * Implementation of {@link CryptoBackend#getBackupDecryptor}.\n */\n getBackupDecryptor(backupInfo, privKey) {\n var _this3 = this;\n return _asyncToGenerator(function* () {\n if (!(privKey instanceof Uint8Array)) {\n throw new Error(\"getBackupDecryptor: expects Uint8Array\");\n }\n if (backupInfo.algorithm != \"m.megolm_backup.v1.curve25519-aes-sha2\") {\n throw new Error(\"getBackupDecryptor: Unsupported algorithm \".concat(backupInfo.algorithm));\n }\n var backupDecryptionKey = RustSdkCryptoJs.BackupDecryptionKey.fromBase64(encodeBase64(privKey));\n if (!decryptionKeyMatchesKeyBackupInfo(backupDecryptionKey, backupInfo)) {\n throw new Error(\"getBackupDecryptor: key backup on server does not match the decryption key\");\n }\n return _this3.backupManager.createBackupDecryptor(backupDecryptionKey);\n })();\n }\n\n /**\n * Implementation of {@link CryptoBackend#importBackedUpRoomKeys}.\n */\n importBackedUpRoomKeys(keys, backupVersion, opts) {\n var _this4 = this;\n return _asyncToGenerator(function* () {\n return yield _this4.backupManager.importBackedUpRoomKeys(keys, backupVersion, opts);\n })();\n }\n\n /**\n * Implementation of {@link CryptoBackend.maybeAcceptKeyBundle}.\n */\n maybeAcceptKeyBundle(roomId, inviter) {\n var _this5 = this;\n return _asyncToGenerator(function* () {\n // TODO: retry this if it gets interrupted or it fails. (https://github.com/matrix-org/matrix-rust-sdk/issues/5112)\n // TODO: do this in the background.\n\n var logger = new LogSpan(_this5.logger, \"maybeAcceptKeyBundle(\".concat(roomId, \", \").concat(inviter, \")\"));\n\n // Make sure we have an up-to-date idea of the inviter's cross-signing keys, so that we can check if the\n // device that sent us the bundle data was correctly cross-signed.\n //\n // TODO: it would be nice to skip this step if we have an up-to-date copy of the inviter's cross-signing keys,\n // but we don't have an easy way to check that. Possibly the rust side could trigger a key request and then\n // block until it happens.\n logger.info(\"Checking inviter cross-signing keys\");\n var request = _this5.olmMachine.queryKeysForUsers([new RustSdkCryptoJs.UserId(inviter)]);\n yield _this5.outgoingRequestProcessor.makeOutgoingRequest(request);\n var bundleData = yield _this5.olmMachine.getReceivedRoomKeyBundleData(new RustSdkCryptoJs.RoomId(roomId), new RustSdkCryptoJs.UserId(inviter));\n if (!bundleData) {\n logger.info(\"No key bundle found for user\");\n return false;\n }\n logger.info(\"Fetching key bundle \".concat(bundleData.url));\n var url = getHttpUriForMxc(_this5.http.opts.baseUrl, bundleData.url, undefined, undefined, undefined, /* allowDirectLinks */false, /* allowRedirects */true, /* useAuthentication */true);\n var encryptedBundle;\n try {\n var bundleUrl = new URL(url);\n encryptedBundle = yield _this5.http.authedRequest(Method.Get, bundleUrl.pathname + bundleUrl.search, {}, undefined, {\n rawResponseBody: true,\n prefix: \"\"\n });\n } catch (err) {\n logger.warn(\"Error downloading encrypted bundle from \".concat(url, \":\"), err);\n throw err;\n }\n logger.info(\"Received blob of length \".concat(encryptedBundle.size));\n try {\n yield _this5.olmMachine.receiveRoomKeyBundle(bundleData, new Uint8Array(yield encryptedBundle.arrayBuffer()));\n } catch (err) {\n logger.warn(\"Error receiving encrypted bundle:\", err);\n throw err;\n }\n return true;\n })();\n }\n\n /**\n * Implementation of {@link CryptoBackend.markRoomAsPendingKeyBundle}.\n */\n markRoomAsPendingKeyBundle(roomId, inviter) {\n this.roomsPendingKeyBundles.set(roomId, inviter);\n }\n /**\n * Implementation of {@link CryptoApi#getVersion}.\n */\n getVersion() {\n var versions = RustSdkCryptoJs.getVersions();\n return \"Rust SDK \".concat(versions.matrix_sdk_crypto, \" (\").concat(versions.git_sha, \"), Vodozemac \").concat(versions.vodozemac);\n }\n\n /**\n * Implementation of {@link CryptoApi#setDeviceIsolationMode}.\n */\n setDeviceIsolationMode(isolationMode) {\n this.deviceIsolationMode = isolationMode;\n }\n\n /**\n * Implementation of {@link CryptoApi#isEncryptionEnabledInRoom}.\n */\n isEncryptionEnabledInRoom(roomId) {\n var _this6 = this;\n return _asyncToGenerator(function* () {\n var roomSettings = yield _this6.olmMachine.getRoomSettings(new RustSdkCryptoJs.RoomId(roomId));\n return Boolean(roomSettings === null || roomSettings === void 0 ? void 0 : roomSettings.algorithm);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#isStateEncryptionEnabledInRoom}.\n */\n isStateEncryptionEnabledInRoom(roomId) {\n var _this7 = this;\n return _asyncToGenerator(function* () {\n var roomSettings = yield _this7.olmMachine.getRoomSettings(new RustSdkCryptoJs.RoomId(roomId));\n return Boolean(roomSettings === null || roomSettings === void 0 ? void 0 : roomSettings.encryptStateEvents);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getOwnDeviceKeys}.\n */\n getOwnDeviceKeys() {\n var _this8 = this;\n return _asyncToGenerator(function* () {\n var keys = _this8.olmMachine.identityKeys;\n return {\n ed25519: keys.ed25519.toBase64(),\n curve25519: keys.curve25519.toBase64()\n };\n })();\n }\n prepareToEncrypt(room) {\n var encryptor = this.roomEncryptors[room.roomId];\n if (encryptor) {\n encryptor.prepareForEncryption(this.globalBlacklistUnverifiedDevices, this.deviceIsolationMode);\n }\n }\n forceDiscardSession(roomId) {\n var _this$roomEncryptors$;\n return (_this$roomEncryptors$ = this.roomEncryptors[roomId]) === null || _this$roomEncryptors$ === void 0 ? void 0 : _this$roomEncryptors$.forceDiscardSession();\n }\n exportRoomKeys() {\n var _this9 = this;\n return _asyncToGenerator(function* () {\n var raw = yield _this9.olmMachine.exportRoomKeys(() => true);\n return JSON.parse(raw);\n })();\n }\n exportRoomKeysAsJson() {\n var _this0 = this;\n return _asyncToGenerator(function* () {\n return yield _this0.olmMachine.exportRoomKeys(() => true);\n })();\n }\n importRoomKeys(keys, opts) {\n var _this1 = this;\n return _asyncToGenerator(function* () {\n return yield _this1.backupManager.importRoomKeys(keys, opts);\n })();\n }\n importRoomKeysAsJson(keys, opts) {\n var _this10 = this;\n return _asyncToGenerator(function* () {\n return yield _this10.backupManager.importRoomKeysAsJson(keys, opts);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi.userHasCrossSigningKeys}.\n */\n userHasCrossSigningKeys() {\n var _arguments = arguments,\n _this11 = this;\n return _asyncToGenerator(function* () {\n var userId = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : _this11.userId;\n var downloadUncached = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : false;\n // TODO: could probably do with a more efficient way of doing this than returning the whole set and searching\n var rustTrackedUsers = yield _this11.olmMachine.trackedUsers();\n var rustTrackedUser;\n for (var u of rustTrackedUsers) {\n if (userId === u.toString()) {\n rustTrackedUser = u;\n break;\n }\n }\n if (rustTrackedUser !== undefined) {\n if (userId === _this11.userId) {\n /* make sure we have an *up-to-date* idea of the user's cross-signing keys. This is important, because if we\n * return \"false\" here, we will end up generating new cross-signing keys and replacing the existing ones.\n */\n var request = _this11.olmMachine.queryKeysForUsers(\n // clone as rust layer will take ownership and it's reused later\n [rustTrackedUser.clone()]);\n yield _this11.outgoingRequestProcessor.makeOutgoingRequest(request);\n }\n var userIdentity = yield _this11.olmMachine.getIdentity(rustTrackedUser);\n userIdentity === null || userIdentity === void 0 || userIdentity.free();\n return userIdentity !== undefined;\n } else if (downloadUncached) {\n var _keyResult$master_key;\n // Download the cross signing keys and check if the master key is available\n var keyResult = yield _this11.downloadDeviceList(new Set([userId]));\n var keys = (_keyResult$master_key = keyResult.master_keys) === null || _keyResult$master_key === void 0 ? void 0 : _keyResult$master_key[userId];\n\n // No master key\n if (!keys) return false;\n\n // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }\n // We assume only a single key, and we want the bare form without type\n // prefix, so we select the values.\n return Boolean(Object.values(keys.keys)[0]);\n } else {\n return false;\n }\n })();\n }\n\n /**\n * Get the device information for the given list of users.\n *\n * @param userIds - The users to fetch.\n * @param downloadUncached - If true, download the device list for users whose device list we are not\n * currently tracking. Defaults to false, in which case such users will not appear at all in the result map.\n *\n * @returns A map `{@link DeviceMap}`.\n */\n getUserDeviceInfo(userIds) {\n var _arguments2 = arguments,\n _this12 = this;\n return _asyncToGenerator(function* () {\n var downloadUncached = _arguments2.length > 1 && _arguments2[1] !== undefined ? _arguments2[1] : false;\n var deviceMapByUserId = new Map();\n var rustTrackedUsers = yield _this12.getOlmMachineOrThrow().trackedUsers();\n\n // Convert RustSdkCryptoJs.UserId to a `Set<string>`\n var trackedUsers = new Set();\n rustTrackedUsers.forEach(rustUserId => trackedUsers.add(rustUserId.toString()));\n\n // Keep untracked user to download their keys after\n var untrackedUsers = new Set();\n for (var _userId of userIds) {\n // if this is a tracked user, we can just fetch the device list from the rust-sdk\n // (NB: this is probably ok even if we race with a leave event such that we stop tracking the user's\n // devices: the rust-sdk will return the last-known device list, which will be good enough.)\n if (trackedUsers.has(_userId)) {\n deviceMapByUserId.set(_userId, yield _this12.getUserDevices(_userId));\n } else {\n untrackedUsers.add(_userId);\n }\n }\n\n // for any users whose device lists we are not tracking, fall back to downloading the device list\n // over HTTP.\n if (downloadUncached && untrackedUsers.size >= 1) {\n var queryResult = yield _this12.downloadDeviceList(untrackedUsers);\n Object.entries(queryResult.device_keys).forEach(_ref => {\n var [userId, deviceKeys] = _ref;\n return deviceMapByUserId.set(userId, deviceKeysToDeviceMap(deviceKeys));\n });\n }\n return deviceMapByUserId;\n })();\n }\n\n /**\n * Get the device list for the given user from the olm machine\n * @param userId - Rust SDK UserId\n */\n getUserDevices(userId) {\n var _this13 = this;\n return _asyncToGenerator(function* () {\n var rustUserId = new RustSdkCryptoJs.UserId(userId);\n\n // For reasons I don't really understand, the Javascript FinalizationRegistry doesn't seem to run the\n // registered callbacks when `userDevices` goes out of scope, nor when the individual devices in the array\n // returned by `userDevices.devices` do so.\n //\n // This is particularly problematic, because each of those structures holds a reference to the\n // VerificationMachine, which in turn holds a reference to the IndexeddbCryptoStore. Hence, we end up leaking\n // open connections to the crypto store, which means the store can't be deleted on logout.\n //\n // To fix this, we explicitly call `.free` on each of the objects, which tells the rust code to drop the\n // allocated memory and decrement the refcounts for the crypto store.\n\n // Wait for up to a second for any in-flight device list requests to complete.\n // The reason for this isn't so much to avoid races (some level of raciness is\n // inevitable for this method) but to make testing easier.\n var userDevices = yield _this13.olmMachine.getUserDevices(rustUserId, 1);\n try {\n var deviceArray = userDevices.devices();\n try {\n return new Map(deviceArray.map(device => [device.deviceId.toString(), rustDeviceToJsDevice(device, rustUserId)]));\n } finally {\n deviceArray.forEach(d => d.free());\n }\n } finally {\n userDevices.free();\n }\n })();\n }\n\n /**\n * Download the given user keys by calling `/keys/query` request\n * @param untrackedUsers - download keys of these users\n */\n downloadDeviceList(untrackedUsers) {\n var _this14 = this;\n return _asyncToGenerator(function* () {\n var queryBody = {\n device_keys: {}\n };\n untrackedUsers.forEach(user => queryBody.device_keys[user] = []);\n return yield _this14.http.authedRequest(Method.Post, \"/_matrix/client/v3/keys/query\", undefined, queryBody, {\n prefix: \"\"\n });\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getTrustCrossSignedDevices}.\n */\n getTrustCrossSignedDevices() {\n return this._trustCrossSignedDevices;\n }\n\n /**\n * Implementation of {@link CryptoApi#setTrustCrossSignedDevices}.\n */\n setTrustCrossSignedDevices(val) {\n this._trustCrossSignedDevices = val;\n // TODO: legacy crypto goes through the list of known devices and emits DeviceVerificationChanged\n // events. Maybe we need to do the same?\n }\n\n /**\n * Mark the given device as locally verified.\n *\n * Implementation of {@link CryptoApi#setDeviceVerified}.\n */\n setDeviceVerified(userId, deviceId) {\n var _arguments3 = arguments,\n _this15 = this;\n return _asyncToGenerator(function* () {\n var verified = _arguments3.length > 2 && _arguments3[2] !== undefined ? _arguments3[2] : true;\n var device = yield _this15.olmMachine.getDevice(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.DeviceId(deviceId));\n if (!device) {\n throw new Error(\"Unknown device \".concat(userId, \"|\").concat(deviceId));\n }\n try {\n yield device.setLocalTrust(verified ? RustSdkCryptoJs.LocalTrust.Verified : RustSdkCryptoJs.LocalTrust.Unset);\n } finally {\n device.free();\n }\n })();\n }\n\n /**\n * Blindly cross-sign one of our other devices.\n *\n * Implementation of {@link CryptoApi#crossSignDevice}.\n */\n crossSignDevice(deviceId) {\n var _this16 = this;\n return _asyncToGenerator(function* () {\n var device = yield _this16.olmMachine.getDevice(new RustSdkCryptoJs.UserId(_this16.userId), new RustSdkCryptoJs.DeviceId(deviceId));\n if (!device) {\n throw new Error(\"Unknown device \".concat(deviceId));\n }\n try {\n var outgoingRequest = yield device.verify();\n yield _this16.outgoingRequestProcessor.makeOutgoingRequest(outgoingRequest);\n } finally {\n device.free();\n }\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getDeviceVerificationStatus}.\n */\n getDeviceVerificationStatus(userId, deviceId) {\n var _this17 = this;\n return _asyncToGenerator(function* () {\n var device = yield _this17.olmMachine.getDevice(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.DeviceId(deviceId));\n if (!device) return null;\n try {\n return new DeviceVerificationStatus({\n signedByOwner: device.isCrossSignedByOwner(),\n crossSigningVerified: device.isCrossSigningTrusted(),\n localVerified: device.isLocallyTrusted(),\n trustCrossSignedDevices: _this17._trustCrossSignedDevices\n });\n } finally {\n device.free();\n }\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getUserVerificationStatus}.\n */\n getUserVerificationStatus(userId) {\n var _this18 = this;\n return _asyncToGenerator(function* () {\n var userIdentity = yield _this18.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(userId));\n if (userIdentity === undefined) {\n return new UserVerificationStatus(false, false, false);\n }\n var verified = userIdentity.isVerified();\n var wasVerified = userIdentity.wasPreviouslyVerified();\n var needsUserApproval = userIdentity instanceof RustSdkCryptoJs.OtherUserIdentity ? userIdentity.identityNeedsUserApproval() : false;\n userIdentity.free();\n return new UserVerificationStatus(verified, wasVerified, false, needsUserApproval);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#pinCurrentUserIdentity}.\n */\n pinCurrentUserIdentity(userId) {\n var _this19 = this;\n return _asyncToGenerator(function* () {\n var userIdentity = yield _this19.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(userId));\n if (userIdentity === undefined) {\n throw new Error(\"Cannot pin identity of unknown user\");\n }\n if (userIdentity instanceof RustSdkCryptoJs.OwnUserIdentity) {\n throw new Error(\"Cannot pin identity of own user\");\n }\n yield userIdentity.pinCurrentMasterKey();\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#withdrawVerificationRequirement}.\n */\n withdrawVerificationRequirement(userId) {\n var _this20 = this;\n return _asyncToGenerator(function* () {\n var userIdentity = yield _this20.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(userId));\n if (userIdentity === undefined) {\n throw new Error(\"Cannot withdraw verification of unknown user\");\n }\n yield userIdentity.withdrawVerification();\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#isCrossSigningReady}\n */\n isCrossSigningReady() {\n var _this21 = this;\n return _asyncToGenerator(function* () {\n var {\n privateKeysInSecretStorage,\n privateKeysCachedLocally\n } = yield _this21.getCrossSigningStatus();\n var hasKeysInCache = Boolean(privateKeysCachedLocally.masterKey) && Boolean(privateKeysCachedLocally.selfSigningKey) && Boolean(privateKeysCachedLocally.userSigningKey);\n var identity = yield _this21.getOwnIdentity();\n\n // Cross-signing is ready if the public identity is trusted, and the private keys\n // are either cached, or accessible via secret-storage.\n return !!(identity !== null && identity !== void 0 && identity.isVerified()) && (hasKeysInCache || privateKeysInSecretStorage);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getCrossSigningKeyId}\n */\n getCrossSigningKeyId() {\n var _arguments4 = arguments,\n _this22 = this;\n return _asyncToGenerator(function* () {\n var type = _arguments4.length > 0 && _arguments4[0] !== undefined ? _arguments4[0] : CrossSigningKey.Master;\n var userIdentity = yield _this22.olmMachine.getIdentity(new RustSdkCryptoJs.UserId(_this22.userId));\n if (!userIdentity) {\n // The public keys are not available on this device\n return null;\n }\n try {\n var crossSigningStatus = yield _this22.olmMachine.crossSigningStatus();\n var privateKeysOnDevice = crossSigningStatus.hasMaster && crossSigningStatus.hasUserSigning && crossSigningStatus.hasSelfSigning;\n if (!privateKeysOnDevice) {\n // The private keys are not available on this device\n return null;\n }\n if (!userIdentity.isVerified()) {\n // We have both public and private keys, but they don't match!\n return null;\n }\n var key;\n switch (type) {\n case CrossSigningKey.Master:\n key = userIdentity.masterKey;\n break;\n case CrossSigningKey.SelfSigning:\n key = userIdentity.selfSigningKey;\n break;\n case CrossSigningKey.UserSigning:\n key = userIdentity.userSigningKey;\n break;\n default:\n // Unknown type\n return null;\n }\n var parsedKey = JSON.parse(key);\n // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }\n // We assume only a single key, and we want the bare form without type\n // prefix, so we select the values.\n return Object.values(parsedKey.keys)[0];\n } finally {\n userIdentity.free();\n }\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#bootstrapCrossSigning}\n */\n bootstrapCrossSigning(opts) {\n var _this23 = this;\n return _asyncToGenerator(function* () {\n yield _this23.crossSigningIdentity.bootstrapCrossSigning(opts);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#isSecretStorageReady}\n */\n isSecretStorageReady() {\n var _this24 = this;\n return _asyncToGenerator(function* () {\n return (yield _this24.getSecretStorageStatus()).ready;\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getSecretStorageStatus}\n */\n getSecretStorageStatus() {\n var _this25 = this;\n return _asyncToGenerator(function* () {\n // make sure that the cross-signing keys are stored\n var secretsToCheck = [\"m.cross_signing.master\", \"m.cross_signing.user_signing\", \"m.cross_signing.self_signing\"];\n\n // If key backup is active, we also need to check that the backup decryption key is stored\n var keyBackupEnabled = (yield _this25.backupManager.getActiveBackupVersion()) != null;\n if (keyBackupEnabled) {\n secretsToCheck.push(\"m.megolm_backup.v1\");\n }\n var defaultKeyId = yield _this25.secretStorage.getDefaultKeyId();\n var result = {\n // Assume we have all secrets until proven otherwise\n ready: true,\n defaultKeyId,\n secretStorageKeyValidityMap: {}\n };\n for (var secretName of secretsToCheck) {\n // Check which keys this particular secret is encrypted with\n var record = (yield _this25.secretStorage.isStored(secretName)) || {};\n\n // If it's encrypted with the right key, it is valid\n var secretStored = !!defaultKeyId && defaultKeyId in record;\n result.secretStorageKeyValidityMap[secretName] = secretStored;\n result.ready = result.ready && secretStored;\n }\n return result;\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#bootstrapSecretStorage}\n */\n bootstrapSecretStorage() {\n var _arguments5 = arguments,\n _this26 = this;\n return _asyncToGenerator(function* () {\n var {\n createSecretStorageKey,\n setupNewSecretStorage,\n setupNewKeyBackup\n } = _arguments5.length > 0 && _arguments5[0] !== undefined ? _arguments5[0] : {};\n // If an AES Key is already stored in the secret storage and setupNewSecretStorage is not set\n // we don't want to create a new key\n var isNewSecretStorageKeyNeeded = setupNewSecretStorage || !(yield _this26.secretStorageHasAESKey());\n if (isNewSecretStorageKeyNeeded) {\n if (!createSecretStorageKey) {\n throw new Error(\"unable to create a new secret storage key, createSecretStorageKey is not set\");\n }\n\n // Create a new storage key and add it to secret storage\n _this26.logger.info(\"bootstrapSecretStorage: creating new secret storage key\");\n var recoveryKey = yield createSecretStorageKey();\n if (!recoveryKey) {\n throw new Error(\"createSecretStorageKey() callback did not return a secret storage key\");\n }\n yield _this26.addSecretStorageKeyToSecretStorage(recoveryKey);\n }\n var crossSigningPrivateKeys = yield _this26.olmMachine.exportCrossSigningKeys();\n var hasPrivateKeys = crossSigningPrivateKeys && crossSigningPrivateKeys.masterKey !== undefined && crossSigningPrivateKeys.self_signing_key !== undefined && crossSigningPrivateKeys.userSigningKey !== undefined;\n\n // If we have cross-signing private keys cached, store them in secret\n // storage if they are not there already.\n if (hasPrivateKeys && (isNewSecretStorageKeyNeeded || !(yield secretStorageContainsCrossSigningKeys(_this26.secretStorage)))) {\n _this26.logger.info(\"bootstrapSecretStorage: cross-signing keys not yet exported; doing so now.\");\n yield _this26.secretStorage.store(\"m.cross_signing.master\", crossSigningPrivateKeys.masterKey);\n yield _this26.secretStorage.store(\"m.cross_signing.user_signing\", crossSigningPrivateKeys.userSigningKey);\n yield _this26.secretStorage.store(\"m.cross_signing.self_signing\", crossSigningPrivateKeys.self_signing_key);\n }\n\n // likewise with the key backup key: if we have one, store it in secret storage (if it's not already there)\n // also don't bother storing it if we're about to set up a new backup\n if (!setupNewKeyBackup) {\n yield _this26.saveBackupKeyToStorage();\n } else {\n yield _this26.resetKeyBackup();\n }\n })();\n }\n\n /**\n * If we have a backup key for the current, trusted backup in cache,\n * save it to secret storage.\n */\n saveBackupKeyToStorage() {\n var _this27 = this;\n return _asyncToGenerator(function* () {\n var keyBackupInfo = yield _this27.backupManager.getServerBackupInfo();\n if (!keyBackupInfo || !keyBackupInfo.version) {\n _this27.logger.info(\"Not saving backup key to secret storage: no backup info\");\n return;\n }\n var backupKeys = yield _this27.olmMachine.getBackupKeys();\n if (!backupKeys.decryptionKey) {\n _this27.logger.info(\"Not saving backup key to secret storage: no backup key\");\n return;\n }\n if (!decryptionKeyMatchesKeyBackupInfo(backupKeys.decryptionKey, keyBackupInfo)) {\n _this27.logger.info(\"Not saving backup key to secret storage: decryption key does not match backup info\");\n return;\n }\n var backupKeyBase64 = backupKeys.decryptionKey.toBase64();\n yield _this27.secretStorage.store(\"m.megolm_backup.v1\", backupKeyBase64);\n })();\n }\n\n /**\n * Add the secretStorage key to the secret storage\n * - The secret storage key must have the `keyInfo` field filled\n * - The secret storage key is set as the default key of the secret storage\n * - Call `cryptoCallbacks.cacheSecretStorageKey` when done\n *\n * @param secretStorageKey - The secret storage key to add in the secret storage.\n */\n addSecretStorageKeyToSecretStorage(secretStorageKey) {\n var _this28 = this;\n return _asyncToGenerator(function* () {\n var _secretStorageKey$key, _secretStorageKey$key2, _this28$cryptoCallbac, _this28$cryptoCallbac2;\n var secretStorageKeyObject = yield _this28.secretStorage.addKey(SECRET_STORAGE_ALGORITHM_V1_AES, {\n passphrase: (_secretStorageKey$key = secretStorageKey.keyInfo) === null || _secretStorageKey$key === void 0 ? void 0 : _secretStorageKey$key.passphrase,\n name: (_secretStorageKey$key2 = secretStorageKey.keyInfo) === null || _secretStorageKey$key2 === void 0 ? void 0 : _secretStorageKey$key2.name,\n key: secretStorageKey.privateKey\n });\n yield _this28.secretStorage.setDefaultKeyId(secretStorageKeyObject.keyId);\n (_this28$cryptoCallbac = (_this28$cryptoCallbac2 = _this28.cryptoCallbacks).cacheSecretStorageKey) === null || _this28$cryptoCallbac === void 0 || _this28$cryptoCallbac.call(_this28$cryptoCallbac2, secretStorageKeyObject.keyId, secretStorageKeyObject.keyInfo, secretStorageKey.privateKey);\n })();\n }\n\n /**\n * Check if a secret storage AES Key is already added in secret storage\n *\n * @returns True if an AES key is in the secret storage\n */\n secretStorageHasAESKey() {\n var _this29 = this;\n return _asyncToGenerator(function* () {\n // See if we already have an AES secret-storage key.\n var secretStorageKeyTuple = yield _this29.secretStorage.getKey();\n if (!secretStorageKeyTuple) return false;\n var [, keyInfo] = secretStorageKeyTuple;\n\n // Check if the key is an AES key\n return keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES;\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getCrossSigningStatus}\n */\n getCrossSigningStatus() {\n var _this30 = this;\n return _asyncToGenerator(function* () {\n var userIdentity = yield _this30.getOlmMachineOrThrow().getIdentity(new RustSdkCryptoJs.UserId(_this30.userId));\n var publicKeysOnDevice = Boolean(userIdentity === null || userIdentity === void 0 ? void 0 : userIdentity.masterKey) && Boolean(userIdentity === null || userIdentity === void 0 ? void 0 : userIdentity.selfSigningKey) && Boolean(userIdentity === null || userIdentity === void 0 ? void 0 : userIdentity.userSigningKey);\n userIdentity === null || userIdentity === void 0 || userIdentity.free();\n var privateKeysInSecretStorage = yield secretStorageContainsCrossSigningKeys(_this30.secretStorage);\n var crossSigningStatus = yield _this30.getOlmMachineOrThrow().crossSigningStatus();\n return {\n publicKeysOnDevice,\n privateKeysInSecretStorage,\n privateKeysCachedLocally: {\n masterKey: Boolean(crossSigningStatus === null || crossSigningStatus === void 0 ? void 0 : crossSigningStatus.hasMaster),\n userSigningKey: Boolean(crossSigningStatus === null || crossSigningStatus === void 0 ? void 0 : crossSigningStatus.hasUserSigning),\n selfSigningKey: Boolean(crossSigningStatus === null || crossSigningStatus === void 0 ? void 0 : crossSigningStatus.hasSelfSigning)\n }\n };\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#createRecoveryKeyFromPassphrase}\n */\n createRecoveryKeyFromPassphrase(password) {\n var _this31 = this;\n return _asyncToGenerator(function* () {\n if (password) {\n // Generate the key from the passphrase\n // first we generate a random salt\n var salt = secureRandomString(32);\n // then we derive the key from the passphrase\n var recoveryKey = yield deriveRecoveryKeyFromPassphrase(password, salt, _this31.RECOVERY_KEY_DERIVATION_ITERATIONS);\n return {\n keyInfo: {\n passphrase: {\n algorithm: \"m.pbkdf2\",\n iterations: _this31.RECOVERY_KEY_DERIVATION_ITERATIONS,\n salt\n }\n },\n privateKey: recoveryKey,\n encodedPrivateKey: encodeRecoveryKey(recoveryKey)\n };\n } else {\n // Using the navigator crypto API to generate the private key\n var key = new Uint8Array(32);\n globalThis.crypto.getRandomValues(key);\n return {\n privateKey: key,\n encodedPrivateKey: encodeRecoveryKey(key)\n };\n }\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getEncryptionInfoForEvent}.\n */\n getEncryptionInfoForEvent(event) {\n var _this32 = this;\n return _asyncToGenerator(function* () {\n return _this32.eventDecryptor.getEncryptionInfoForEvent(event);\n })();\n }\n\n /**\n * Returns to-device verification requests that are already in progress for the given user id.\n *\n * Implementation of {@link CryptoApi#getVerificationRequestsToDeviceInProgress}\n *\n * @param userId - the ID of the user to query\n *\n * @returns the VerificationRequests that are in progress\n */\n getVerificationRequestsToDeviceInProgress(userId) {\n var requests = this.olmMachine.getVerificationRequests(new RustSdkCryptoJs.UserId(userId));\n return requests.filter(request => request.roomId === undefined && !request.isCancelled()).map(request => this.makeVerificationRequest(request));\n }\n\n /**\n * Finds a DM verification request that is already in progress for the given room id\n *\n * Implementation of {@link CryptoApi#findVerificationRequestDMInProgress}\n *\n * @param roomId - the room to use for verification\n * @param userId - search the verification request for the given user\n *\n * @returns the VerificationRequest that is in progress, if any\n *\n */\n findVerificationRequestDMInProgress(roomId, userId) {\n if (!userId) throw new Error(\"missing userId\");\n var requests = this.olmMachine.getVerificationRequests(new RustSdkCryptoJs.UserId(userId));\n\n // Search for the verification request for the given room id\n var request = requests.find(request => {\n var _request$roomId;\n return ((_request$roomId = request.roomId) === null || _request$roomId === void 0 ? void 0 : _request$roomId.toString()) === roomId && !request.isCancelled();\n });\n if (request) {\n return this.makeVerificationRequest(request);\n }\n }\n\n /**\n * Implementation of {@link CryptoApi#requestVerificationDM}\n */\n requestVerificationDM(userId, roomId) {\n var _this33 = this;\n return _asyncToGenerator(function* () {\n var userIdentity = yield _this33.olmMachine.getIdentity(new RustSdkCryptoJs.UserId(userId));\n if (!userIdentity) throw new Error(\"unknown userId \".concat(userId));\n try {\n // Transform the verification methods into rust objects\n var methods = _this33._supportedVerificationMethods.map(method => verificationMethodIdentifierToMethod(method));\n // Get the request content to send to the DM room\n var verCont = yield userIdentity.verificationRequestContent(methods);\n\n // TODO: due to https://github.com/matrix-org/matrix-rust-sdk/issues/5643, we need to fix up the verification request content to include `msgtype`.\n var verContObj = JSON.parse(verCont);\n verContObj[\"msgtype\"] = \"m.key.verification.request\";\n var verificationEventContent = JSON.stringify(verContObj);\n\n // Send the request content to send to the DM room\n var eventId = yield _this33.sendVerificationRequestContent(roomId, verificationEventContent);\n\n // Get a verification request\n var request = yield userIdentity.requestVerification(new RustSdkCryptoJs.RoomId(roomId), new RustSdkCryptoJs.EventId(eventId), methods);\n return _this33.makeVerificationRequest(request);\n } finally {\n userIdentity.free();\n }\n })();\n }\n\n /**\n * Send the verification content to a room\n * See https://spec.matrix.org/v1.7/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid\n *\n * Prefer to use {@link OutgoingRequestProcessor.makeOutgoingRequest} when dealing with {@link RustSdkCryptoJs.RoomMessageRequest}\n *\n * @param roomId - the targeted room\n * @param verificationEventContent - the request body.\n *\n * @returns the event id\n */\n sendVerificationRequestContent(roomId, verificationEventContent) {\n var _this34 = this;\n return _asyncToGenerator(function* () {\n var txId = secureRandomString(32);\n // Send the verification request content to the DM room\n var {\n event_id: eventId\n } = yield _this34.http.authedRequest(Method.Put, \"/_matrix/client/v3/rooms/\".concat(encodeURIComponent(roomId), \"/send/m.room.message/\").concat(encodeURIComponent(txId)), undefined, verificationEventContent, {\n prefix: \"\"\n });\n return eventId;\n })();\n }\n /**\n * Set the verification methods we offer to the other side during an interactive verification.\n *\n * If `undefined`, we will offer all the methods supported by the Rust SDK.\n */\n setSupportedVerificationMethods(methods) {\n // by default, the Rust SDK does not offer `m.qr_code.scan.v1`, but we do want to offer that.\n this._supportedVerificationMethods = methods !== null && methods !== void 0 ? methods : ALL_VERIFICATION_METHODS;\n }\n\n /**\n * Send a verification request to our other devices.\n *\n * If a verification is already in flight, returns it. Otherwise, initiates a new one.\n *\n * Implementation of {@link CryptoApi#requestOwnUserVerification}.\n *\n * @returns a VerificationRequest when the request has been sent to the other party.\n */\n requestOwnUserVerification() {\n var _this35 = this;\n return _asyncToGenerator(function* () {\n var userIdentity = yield _this35.olmMachine.getIdentity(new RustSdkCryptoJs.UserId(_this35.userId));\n if (userIdentity === undefined) {\n throw new Error(\"cannot request verification for this device when there is no existing cross-signing key\");\n }\n try {\n var [request, outgoingRequest] = yield userIdentity.requestVerification(_this35._supportedVerificationMethods.map(verificationMethodIdentifierToMethod));\n yield _this35.outgoingRequestProcessor.makeOutgoingRequest(outgoingRequest);\n return _this35.makeVerificationRequest(request);\n } finally {\n userIdentity.free();\n }\n })();\n }\n\n /**\n * Request an interactive verification with the given device.\n *\n * If a verification is already in flight, returns it. Otherwise, initiates a new one.\n *\n * Implementation of {@link CryptoApi#requestDeviceVerification}.\n *\n * @param userId - ID of the owner of the device to verify\n * @param deviceId - ID of the device to verify\n *\n * @returns a VerificationRequest when the request has been sent to the other party.\n */\n requestDeviceVerification(userId, deviceId) {\n var _this36 = this;\n return _asyncToGenerator(function* () {\n var device = yield _this36.olmMachine.getDevice(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.DeviceId(deviceId));\n if (!device) {\n throw new Error(\"Not a known device\");\n }\n try {\n var [request, outgoingRequest] = device.requestVerification(_this36._supportedVerificationMethods.map(verificationMethodIdentifierToMethod));\n yield _this36.outgoingRequestProcessor.makeOutgoingRequest(outgoingRequest);\n return _this36.makeVerificationRequest(request);\n } finally {\n device.free();\n }\n })();\n }\n\n /**\n * Fetch the backup decryption key we have saved in our store.\n *\n * Implementation of {@link CryptoApi#getSessionBackupPrivateKey}.\n *\n * @returns the key, if any, or null\n */\n getSessionBackupPrivateKey() {\n var _this37 = this;\n return _asyncToGenerator(function* () {\n var backupKeys = yield _this37.olmMachine.getBackupKeys();\n if (!backupKeys.decryptionKey) return null;\n return decodeBase64(backupKeys.decryptionKey.toBase64());\n })();\n }\n\n /**\n * Store the backup decryption key.\n *\n * Implementation of {@link CryptoApi#storeSessionBackupPrivateKey}.\n *\n * @param key - the backup decryption key\n * @param version - the backup version for this key.\n */\n storeSessionBackupPrivateKey(key, version) {\n var _this38 = this;\n return _asyncToGenerator(function* () {\n var base64Key = encodeBase64(key);\n if (!version) {\n throw new Error(\"storeSessionBackupPrivateKey: version is required\");\n }\n yield _this38.backupManager.saveBackupDecryptionKey(RustSdkCryptoJs.BackupDecryptionKey.fromBase64(base64Key), version);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#loadSessionBackupPrivateKeyFromSecretStorage}.\n */\n loadSessionBackupPrivateKeyFromSecretStorage() {\n var _this39 = this;\n return _asyncToGenerator(function* () {\n var backupKey = yield _this39.secretStorage.get(\"m.megolm_backup.v1\");\n if (!backupKey) {\n throw new Error(\"loadSessionBackupPrivateKeyFromSecretStorage: missing decryption key in secret storage\");\n }\n var keyBackupInfo = yield _this39.backupManager.getServerBackupInfo();\n if (!keyBackupInfo || !keyBackupInfo.version) {\n throw new Error(\"loadSessionBackupPrivateKeyFromSecretStorage: unable to get backup version\");\n }\n var backupDecryptionKey = RustSdkCryptoJs.BackupDecryptionKey.fromBase64(backupKey);\n if (!decryptionKeyMatchesKeyBackupInfo(backupDecryptionKey, keyBackupInfo)) {\n throw new Error(\"loadSessionBackupPrivateKeyFromSecretStorage: decryption key does not match backup info\");\n }\n yield _this39.backupManager.saveBackupDecryptionKey(backupDecryptionKey, keyBackupInfo.version);\n })();\n }\n\n /**\n * Get the current status of key backup.\n *\n * Implementation of {@link CryptoApi#getActiveSessionBackupVersion}.\n */\n getActiveSessionBackupVersion() {\n var _this40 = this;\n return _asyncToGenerator(function* () {\n return yield _this40.backupManager.getActiveBackupVersion();\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#getKeyBackupInfo}.\n */\n getKeyBackupInfo() {\n var _this41 = this;\n return _asyncToGenerator(function* () {\n return (yield _this41.backupManager.getServerBackupInfo()) || null;\n })();\n }\n\n /**\n * Determine if a key backup can be trusted.\n *\n * Implementation of {@link CryptoApi#isKeyBackupTrusted}.\n */\n isKeyBackupTrusted(info) {\n var _this42 = this;\n return _asyncToGenerator(function* () {\n return yield _this42.backupManager.isKeyBackupTrusted(info);\n })();\n }\n\n /**\n * Force a re-check of the key backup and enable/disable it as appropriate.\n *\n * Implementation of {@link CryptoApi#checkKeyBackupAndEnable}.\n */\n checkKeyBackupAndEnable() {\n var _this43 = this;\n return _asyncToGenerator(function* () {\n return yield _this43.backupManager.checkKeyBackupAndEnable(true);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#deleteKeyBackupVersion}.\n */\n deleteKeyBackupVersion(version) {\n var _this44 = this;\n return _asyncToGenerator(function* () {\n yield _this44.backupManager.deleteKeyBackupVersion(version);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#resetKeyBackup}.\n */\n resetKeyBackup() {\n var _this45 = this;\n return _asyncToGenerator(function* () {\n var backupInfo = yield _this45.backupManager.setupKeyBackup(o => _this45.signObject(o));\n\n // we want to store the private key in 4S\n // need to check if 4S is set up?\n if (yield _this45.secretStorageHasAESKey()) {\n yield _this45.secretStorage.store(\"m.megolm_backup.v1\", backupInfo.decryptionKey.toBase64());\n }\n\n // we can check and start async\n _this45.checkKeyBackupAndEnable();\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#disableKeyStorage}.\n */\n disableKeyStorage() {\n var _this46 = this;\n return _asyncToGenerator(function* () {\n // Get the key backup version we're using\n var info = yield _this46.getKeyBackupInfo();\n if (info !== null && info !== void 0 && info.version) {\n yield _this46.deleteKeyBackupVersion(info.version);\n } else {\n _this46.logger.error(\"Can't delete key backup version: no version available\");\n }\n\n // also turn off 4S, since this is also storing keys on the server.\n yield _this46.deleteSecretStorage();\n yield _this46.dehydratedDeviceManager.delete();\n })();\n }\n\n /**\n * Signs the given object with the current device and current identity (if available).\n * As defined in {@link https://spec.matrix.org/v1.8/appendices/#signing-json | Signing JSON}.\n *\n * Helper for {@link RustCrypto#resetKeyBackup}.\n *\n * @param obj - The object to sign\n */\n signObject(obj) {\n var _this47 = this;\n return _asyncToGenerator(function* () {\n var sigs = new Map(Object.entries(obj.signatures || {}));\n var unsigned = obj.unsigned;\n delete obj.signatures;\n delete obj.unsigned;\n var userSignatures = sigs.get(_this47.userId) || {};\n var canonalizedJson = anotherjson.stringify(obj);\n var signatures = yield _this47.olmMachine.sign(canonalizedJson);\n var map = JSON.parse(signatures.asJSON());\n sigs.set(_this47.userId, _objectSpread(_objectSpread({}, userSignatures), map[_this47.userId]));\n if (unsigned !== undefined) obj.unsigned = unsigned;\n obj.signatures = Object.fromEntries(sigs.entries());\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#restoreKeyBackupWithPassphrase}.\n */\n restoreKeyBackupWithPassphrase(passphrase, opts) {\n var _this48 = this;\n return _asyncToGenerator(function* () {\n var backupInfo = yield _this48.backupManager.getServerBackupInfo();\n if (!(backupInfo !== null && backupInfo !== void 0 && backupInfo.version)) {\n throw new Error(\"No backup info available\");\n }\n var privateKey = yield keyFromAuthData(backupInfo.auth_data, passphrase);\n\n // Cache the key\n yield _this48.storeSessionBackupPrivateKey(privateKey, backupInfo.version);\n return _this48.restoreKeyBackup(opts);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#restoreKeyBackup}.\n */\n restoreKeyBackup(opts) {\n var _this49 = this;\n return _asyncToGenerator(function* () {\n // Get the decryption key from the crypto store\n var backupKeys = yield _this49.olmMachine.getBackupKeys();\n var {\n decryptionKey,\n backupVersion\n } = backupKeys;\n if (!decryptionKey || !backupVersion) throw new Error(\"No decryption key found in crypto store\");\n var decodedDecryptionKey = decodeBase64(decryptionKey.toBase64());\n var backupInfo = yield _this49.backupManager.requestKeyBackupVersion(backupVersion);\n if (!backupInfo) throw new Error(\"Backup version to restore \".concat(backupVersion, \" not found on server\"));\n var backupDecryptor = yield _this49.getBackupDecryptor(backupInfo, decodedDecryptionKey);\n try {\n var _opts$progressCallbac;\n opts === null || opts === void 0 || (_opts$progressCallbac = opts.progressCallback) === null || _opts$progressCallbac === void 0 || _opts$progressCallbac.call(opts, {\n stage: ImportRoomKeyStage.Fetch\n });\n return yield _this49.backupManager.restoreKeyBackup(backupVersion, backupDecryptor, opts);\n } finally {\n // Free to avoid to keep in memory the decryption key stored in it. To avoid to exposing it to an attacker.\n backupDecryptor.free();\n }\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#isDehydrationSupported}.\n */\n isDehydrationSupported() {\n var _this50 = this;\n return _asyncToGenerator(function* () {\n return yield _this50.dehydratedDeviceManager.isSupported();\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#startDehydration}.\n */\n startDehydration() {\n var _arguments6 = arguments,\n _this51 = this;\n return _asyncToGenerator(function* () {\n var opts = _arguments6.length > 0 && _arguments6[0] !== undefined ? _arguments6[0] : {};\n if (!(yield _this51.isCrossSigningReady()) || !(yield _this51.isSecretStorageReady())) {\n throw new Error(\"Device dehydration requires cross-signing and secret storage to be set up\");\n }\n return yield _this51.dehydratedDeviceManager.start(opts || {});\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#importSecretsBundle}.\n */\n importSecretsBundle(secrets) {\n var _this52 = this;\n return _asyncToGenerator(function* () {\n var secretsBundle = RustSdkCryptoJs.SecretsBundle.from_json(secrets);\n yield _this52.getOlmMachineOrThrow().importSecretsBundle(secretsBundle); // this method frees the SecretsBundle\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#exportSecretsBundle}.\n */\n exportSecretsBundle() {\n var _this53 = this;\n return _asyncToGenerator(function* () {\n var secretsBundle = yield _this53.getOlmMachineOrThrow().exportSecretsBundle();\n var secrets = secretsBundle.to_json();\n secretsBundle.free();\n return secrets;\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#encryptToDeviceMessages}.\n */\n encryptToDeviceMessages(eventType, devices, payload) {\n var _this54 = this;\n return _asyncToGenerator(function* () {\n var logger = new LogSpan(_this54.logger, \"encryptToDeviceMessages\");\n var uniqueUsers = new Set(devices.map(_ref2 => {\n var {\n userId\n } = _ref2;\n return userId;\n }));\n\n // This will ensure we have Olm sessions for all of the users' devices.\n // However, we only care about some of the devices.\n // So, perhaps we can optimise this later on.\n yield _this54.keyClaimManager.ensureSessionsForUsers(logger, Array.from(uniqueUsers).map(userId => new RustSdkCryptoJs.UserId(userId)));\n var batch = {\n batch: [],\n eventType: EventType.RoomMessageEncrypted\n };\n yield Promise.all(devices.map(/*#__PURE__*/function () {\n var _ref4 = _asyncToGenerator(function* (_ref3) {\n var {\n userId,\n deviceId\n } = _ref3;\n var device = yield _this54.olmMachine.getDevice(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.DeviceId(deviceId));\n if (device) {\n var encryptedPayload = JSON.parse(yield device.encryptToDeviceEvent(eventType, payload));\n batch.batch.push({\n deviceId,\n userId,\n payload: encryptedPayload\n });\n } else {\n _this54.logger.warn(\"encryptToDeviceMessages: unknown device \".concat(userId, \":\").concat(deviceId));\n }\n });\n return function (_x) {\n return _ref4.apply(this, arguments);\n };\n }()));\n return batch;\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#resetEncryption}.\n */\n resetEncryption(authUploadDeviceSigningKeys) {\n var _this55 = this;\n return _asyncToGenerator(function* () {\n _this55.logger.debug(\"resetEncryption: resetting encryption\");\n\n // Delete the dehydrated device, since any existing one will be signed\n // by the wrong cross-signing key\n _this55.dehydratedDeviceManager.delete();\n\n // Disable backup, and delete all the backups from the server\n yield _this55.backupManager.deleteAllKeyBackupVersions();\n yield _this55.deleteSecretStorage();\n\n // Reset the cross-signing keys\n yield _this55.crossSigningIdentity.bootstrapCrossSigning({\n setupNewCrossSigning: true,\n authUploadDeviceSigningKeys\n });\n\n // Create a new key backup\n yield _this55.resetKeyBackup();\n _this55.logger.debug(\"resetEncryption: ended\");\n })();\n }\n\n /**\n * Removes the secret storage key, default key pointer and all (known) secret storage data\n * from the user's account data\n */\n deleteSecretStorage() {\n var _this56 = this;\n return _asyncToGenerator(function* () {\n // Remove the stored secrets in the secret storage\n yield _this56.secretStorage.store(\"m.cross_signing.master\", null);\n yield _this56.secretStorage.store(\"m.cross_signing.self_signing\", null);\n yield _this56.secretStorage.store(\"m.cross_signing.user_signing\", null);\n yield _this56.secretStorage.store(\"m.megolm_backup.v1\", null);\n\n // Remove the recovery key\n var defaultKeyId = yield _this56.secretStorage.getDefaultKeyId();\n if (defaultKeyId) yield _this56.secretStorage.store(\"m.secret_storage.key.\".concat(defaultKeyId), null);\n // Disable the recovery key and the secret storage\n yield _this56.secretStorage.setDefaultKeyId(null);\n })();\n }\n\n /**\n * Implementation of {@link CryptoApi#shareRoomHistoryWithUser}.\n */\n shareRoomHistoryWithUser(roomId, userId) {\n var _this57 = this;\n return _asyncToGenerator(function* () {\n var logger = new LogSpan(_this57.logger, \"shareRoomHistoryWithUser(\".concat(roomId, \", \").concat(userId, \")\"));\n\n // 0. We can only share room history if our user has set up cross-signing.\n var identity = yield _this57.getOwnIdentity();\n if (!(identity !== null && identity !== void 0 && identity.isVerified())) {\n logger.warn(\"Not sharing message history as the current device is not verified by our cross-signing identity\");\n return;\n }\n logger.info(\"Sharing message history\");\n\n // 1. Construct the key bundle\n var bundle = yield _this57.getOlmMachineOrThrow().buildRoomKeyBundle(new RustSdkCryptoJs.RoomId(roomId));\n if (!bundle) {\n logger.info(\"No keys to share\");\n return;\n }\n\n // 2. Upload the encrypted bundle to the server\n var uploadResponse = yield _this57.http.uploadContent(bundle.encryptedData);\n logger.info(\"Uploaded encrypted key blob: \".concat(JSON.stringify(uploadResponse)));\n\n // 3. We may not share a room with the user, so get a fresh list of devices for the invited user.\n var req = _this57.getOlmMachineOrThrow().queryKeysForUsers([new RustSdkCryptoJs.UserId(userId)]);\n yield _this57.outgoingRequestProcessor.makeOutgoingRequest(req);\n\n // 4. Establish Olm sessions with all of the recipient's devices.\n yield _this57.keyClaimManager.ensureSessionsForUsers(logger, [new RustSdkCryptoJs.UserId(userId)]);\n\n // 5. Send to-device messages to the recipient to share the keys.\n var requests = yield _this57.getOlmMachineOrThrow().shareRoomKeyBundleData(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.RoomId(roomId), uploadResponse.content_uri, bundle.mediaEncryptionInfo, RustSdkCryptoJs.CollectStrategy.identityBasedStrategy());\n for (var _req of requests) {\n yield _this57.outgoingRequestProcessor.makeOutgoingRequest(_req);\n }\n })();\n }\n\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n //\n // SyncCryptoCallbacks implementation\n //\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n /**\n * Apply sync changes to the olm machine\n * @param events - the received to-device messages\n * @param oneTimeKeysCounts - the received one time key counts\n * @param unusedFallbackKeys - the received unused fallback keys\n * @param devices - the received device list updates\n * @returns A list of processed to-device messages.\n */\n receiveSyncChanges(_ref5) {\n var _this58 = this;\n return _asyncToGenerator(function* () {\n var {\n events,\n oneTimeKeysCounts = new Map(),\n unusedFallbackKeys,\n devices = new RustSdkCryptoJs.DeviceLists()\n } = _ref5;\n return yield _this58.olmMachine.receiveSyncChanges(events ? JSON.stringify(events) : \"[]\", devices, oneTimeKeysCounts, unusedFallbackKeys);\n })();\n }\n\n /** called by the sync loop to preprocess incoming to-device messages\n *\n * @param events - the received to-device messages\n * @returns A list of preprocessed to-device messages.\n */\n preprocessToDeviceMessages(events) {\n var _this59 = this;\n return _asyncToGenerator(function* () {\n // send the received to-device messages into receiveSyncChanges. We have no info on device-list changes,\n // one-time-keys, or fallback keys, so just pass empty data.\n var processed = yield _this59.receiveSyncChanges({\n events\n });\n var received = [];\n var _loop = function* _loop() {\n var parsedMessage = JSON.parse(message.rawEvent);\n\n // look for interesting to-device messages\n if (parsedMessage.type === EventType.KeyVerificationRequest) {\n var sender = parsedMessage.sender;\n var transactionId = parsedMessage.content.transaction_id;\n if (transactionId && sender) {\n _this59.onIncomingKeyVerificationRequest(sender, transactionId);\n }\n }\n switch (message.type) {\n case RustSdkCryptoJs.ProcessedToDeviceEventType.Decrypted:\n {\n var _encryptionInfo$sende;\n var encryptionInfo = message.encryptionInfo;\n received.push({\n message: parsedMessage,\n encryptionInfo: {\n sender: encryptionInfo.sender.toString(),\n senderDevice: (_encryptionInfo$sende = encryptionInfo.senderDevice) === null || _encryptionInfo$sende === void 0 ? void 0 : _encryptionInfo$sende.toString(),\n senderCurve25519KeyBase64: encryptionInfo.senderCurve25519Key,\n senderVerified: encryptionInfo.isSenderVerified()\n }\n });\n\n // If we have received a room key bundle message, and have previously marked the room\n // IDs it references as pending key bundles, tell the Rust SDK to try and accept it,\n // just in case it was received after invite.\n //\n // We don't actually need to validate the contents of the bundle message, or do\n // anything with its contents at all. We simply want to inform the Rust SDK we have\n // received a new room key bundle that we might be able to download.\n if (isRoomKeyBundleMessage(parsedMessage) && _this59.roomsPendingKeyBundles.has(parsedMessage.content.room_id)) {\n // No `await`-ing here, as this is called from inside the `/sync` loop.\n _this59.maybeAcceptKeyBundle(parsedMessage.content.room_id, _this59.roomsPendingKeyBundles.get(parsedMessage.content.room_id)).then(success => {\n if (success) {\n _this59.roomsPendingKeyBundles.delete(parsedMessage.content.room_id);\n }\n }, err => {\n _this59.logger.error(\"Error attempting to download key bundle for room \".concat(parsedMessage.content.room_id));\n _this59.logger.error(err);\n });\n }\n break;\n }\n case RustSdkCryptoJs.ProcessedToDeviceEventType.PlainText:\n {\n received.push({\n message: parsedMessage,\n encryptionInfo: null\n });\n break;\n }\n case RustSdkCryptoJs.ProcessedToDeviceEventType.UnableToDecrypt:\n // ignore messages we cannot decrypt\n break;\n case RustSdkCryptoJs.ProcessedToDeviceEventType.Invalid:\n // ignore invalid messages\n break;\n }\n };\n for (var message of processed) {\n yield* _loop();\n }\n return received;\n })();\n }\n\n /** called by the sync loop to process one time key counts and unused fallback keys\n *\n * @param oneTimeKeysCounts - the received one time key counts\n * @param unusedFallbackKeys - the received unused fallback keys\n */\n processKeyCounts(oneTimeKeysCounts, unusedFallbackKeys) {\n var _this60 = this;\n return _asyncToGenerator(function* () {\n var mapOneTimeKeysCount = oneTimeKeysCounts && new Map(Object.entries(oneTimeKeysCounts));\n var setUnusedFallbackKeys = unusedFallbackKeys && new Set(unusedFallbackKeys);\n if (mapOneTimeKeysCount !== undefined || setUnusedFallbackKeys !== undefined) {\n yield _this60.receiveSyncChanges({\n oneTimeKeysCounts: mapOneTimeKeysCount,\n unusedFallbackKeys: setUnusedFallbackKeys\n });\n }\n })();\n }\n\n /** called by the sync loop to process the notification that device lists have\n * been changed.\n *\n * @param deviceLists - device_lists field from /sync\n */\n processDeviceLists(deviceLists) {\n var _this61 = this;\n return _asyncToGenerator(function* () {\n var _deviceLists$changed, _deviceLists$left;\n var devices = new RustSdkCryptoJs.DeviceLists((_deviceLists$changed = deviceLists.changed) === null || _deviceLists$changed === void 0 ? void 0 : _deviceLists$changed.map(userId => new RustSdkCryptoJs.UserId(userId)), (_deviceLists$left = deviceLists.left) === null || _deviceLists$left === void 0 ? void 0 : _deviceLists$left.map(userId => new RustSdkCryptoJs.UserId(userId)));\n yield _this61.receiveSyncChanges({\n devices\n });\n })();\n }\n\n /** called by the sync loop on m.room.encryption events\n *\n * @param room - in which the event was received\n * @param event - encryption event to be processed\n */\n onCryptoEvent(room, event) {\n var _this62 = this;\n return _asyncToGenerator(function* () {\n var config = event.getContent();\n var settings = new RustSdkCryptoJs.RoomSettings();\n if (config.algorithm === \"m.megolm.v1.aes-sha2\") {\n settings.algorithm = RustSdkCryptoJs.EncryptionAlgorithm.MegolmV1AesSha2;\n } else {\n // Among other situations, this happens if the crypto state event is redacted.\n _this62.logger.warn(\"Room \".concat(room.roomId, \": ignoring crypto event with invalid algorithm \").concat(config.algorithm));\n return;\n }\n if (config[\"io.element.msc4362.encrypt_state_events\"] && _this62.enableEncryptedStateEvents) {\n _this62.logger.info(\"crypto Enabling state event encryption...\");\n settings.encryptStateEvents = true;\n }\n try {\n settings.sessionRotationPeriodMs = config.rotation_period_ms;\n settings.sessionRotationPeriodMessages = config.rotation_period_msgs;\n yield _this62.olmMachine.setRoomSettings(new RustSdkCryptoJs.RoomId(room.roomId), settings);\n } catch (e) {\n _this62.logger.warn(\"Room \".concat(room.roomId, \": ignoring crypto event which caused error: \").concat(e));\n return;\n }\n\n // If we got this far, the SDK found the event acceptable.\n // We need to either create or update the active RoomEncryptor.\n var existingEncryptor = _this62.roomEncryptors[room.roomId];\n if (existingEncryptor) {\n existingEncryptor.onCryptoEvent(config);\n } else {\n _this62.roomEncryptors[room.roomId] = new RoomEncryptor(_this62.logger.getChild(\"[\".concat(room.roomId, \" encryption]\")), _this62.olmMachine, _this62.keyClaimManager, _this62.outgoingRequestsManager, room, config);\n }\n })();\n }\n\n /** called by the sync loop after processing each sync.\n *\n *\n * @param syncState - information on the completed sync.\n */\n onSyncCompleted(syncState) {\n // Processing the /sync may have produced new outgoing requests which need sending, so kick off the outgoing\n // request loop, if it's not already running.\n this.outgoingRequestsManager.doProcessOutgoingRequests().catch(e => {\n this.logger.warn(\"onSyncCompleted: Error processing outgoing requests\", e);\n });\n }\n\n /**\n * Implementation of {@link CryptoApi#markAllTrackedUsersAsDirty}.\n */\n markAllTrackedUsersAsDirty() {\n var _this63 = this;\n return _asyncToGenerator(function* () {\n yield _this63.olmMachine.markAllTrackedUsersAsDirty();\n })();\n }\n\n /**\n * Handle an incoming m.key.verification.request event, received either in-room or in a to-device message.\n *\n * @param sender - the sender of the event\n * @param transactionId - the transaction ID for the verification. For to-device messages, this comes from the\n * content of the message; for in-room messages it is the event ID.\n */\n onIncomingKeyVerificationRequest(sender, transactionId) {\n var request = this.olmMachine.getVerificationRequest(new RustSdkCryptoJs.UserId(sender), transactionId);\n if (request) {\n this.emit(CryptoEvent.VerificationRequestReceived, this.makeVerificationRequest(request));\n } else {\n // There are multiple reasons this can happen; probably the most likely is that the event is an\n // in-room event which is too old.\n this.logger.info(\"Ignoring just-received verification request \".concat(transactionId, \" which did not start a rust-side verification\"));\n }\n }\n\n /** Utility function to wrap a rust `VerificationRequest` with our own {@link VerificationRequest}. */\n makeVerificationRequest(request) {\n return new RustVerificationRequest(this.logger, this.olmMachine, request, this.outgoingRequestProcessor, this._supportedVerificationMethods);\n }\n\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n //\n // Other public functions\n //\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n /** called by the MatrixClient on a room membership event\n *\n * @param event - The matrix event which caused this event to fire.\n * @param member - The member whose RoomMember.membership changed.\n * @param oldMembership - The previous membership state. Null if it's a new member.\n */\n onRoomMembership(event, member, oldMembership) {\n var enc = this.roomEncryptors[event.getRoomId()];\n if (!enc) {\n // not encrypting in this room\n return;\n }\n enc.onRoomMembership(member);\n }\n\n /** Callback for OlmMachine.registerRoomKeyUpdatedCallback\n *\n * Called by the rust-sdk whenever there is an update to (megolm) room keys. We\n * check if we have any events waiting for the given keys, and schedule them for\n * a decryption retry if so.\n *\n * @param keys - details of the updated keys\n */\n onRoomKeysUpdated(keys) {\n var _this64 = this;\n return _asyncToGenerator(function* () {\n for (var key of keys) {\n _this64.onRoomKeyUpdated(key);\n }\n _this64.backupManager.maybeUploadKey();\n })();\n }\n onRoomKeyUpdated(key) {\n var _this65 = this;\n if (this.stopped) return;\n this.logger.debug(\"Got update for session \".concat(key.sessionId, \" from sender \").concat(key.senderKey.toBase64(), \" in \").concat(key.roomId.toString()));\n var pendingList = this.eventDecryptor.getEventsPendingRoomKey(key.roomId.toString(), key.sessionId);\n if (pendingList.length === 0) return;\n this.logger.debug(\"Retrying decryption on events:\", pendingList.map(e => \"\".concat(e.getId())));\n\n // Have another go at decrypting events with this key.\n //\n // We don't want to end up blocking the callback from Rust, which could otherwise end up dropping updates,\n // so we don't wait for the decryption to complete. In any case, there is no need to wait:\n // MatrixEvent.attemptDecryption ensures that there is only one decryption attempt happening at once,\n // and deduplicates repeated attempts for the same event.\n var _loop2 = function _loop2(ev) {\n ev.attemptDecryption(_this65, {\n isRetry: true\n }).catch(_e => {\n _this65.logger.info(\"Still unable to decrypt event \".concat(ev.getId(), \" after receiving key\"));\n });\n };\n for (var ev of pendingList) {\n _loop2(ev);\n }\n }\n\n /**\n * Callback for `OlmMachine.registerRoomKeyWithheldCallback`.\n *\n * Called by the rust sdk whenever we are told that a key has been withheld. We see if we had any events that\n * failed to decrypt for the given session, and update their status if so.\n *\n * @param withheld - Details of the withheld sessions.\n */\n onRoomKeysWithheld(withheld) {\n var _this66 = this;\n return _asyncToGenerator(function* () {\n for (var session of withheld) {\n _this66.logger.debug(\"Got withheld message for session \".concat(session.sessionId, \" in \").concat(session.roomId.toString()));\n var pendingList = _this66.eventDecryptor.getEventsPendingRoomKey(session.roomId.toString(), session.sessionId);\n if (pendingList.length === 0) return;\n\n // The easiest way to update the status of the event is to have another go at decrypting it.\n _this66.logger.debug(\"Retrying decryption on events:\", pendingList.map(e => \"\".concat(e.getId())));\n for (var ev of pendingList) {\n ev.attemptDecryption(_this66, {\n isRetry: true\n }).catch(_e => {\n // It's somewhat expected that we still can't decrypt here.\n });\n }\n }\n })();\n }\n\n /**\n * Callback for `OlmMachine.registerUserIdentityUpdatedCallback`\n *\n * Called by the rust-sdk whenever there is an update to any user's cross-signing status. We re-check their trust\n * status and emit a `UserTrustStatusChanged` event, as well as a `KeysChanged` if it is our own identity that changed.\n *\n * @param userId - the user with the updated identity\n */\n onUserIdentityUpdated(userId) {\n var _this67 = this;\n return _asyncToGenerator(function* () {\n var newVerification = yield _this67.getUserVerificationStatus(userId.toString());\n _this67.emit(CryptoEvent.UserTrustStatusChanged, userId.toString(), newVerification);\n\n // If our own user identity has changed, we may now trust the key backup where we did not before.\n // So, re-check the key backup status and enable it if available.\n if (userId.toString() === _this67.userId) {\n _this67.emit(CryptoEvent.KeysChanged, {});\n yield _this67.checkKeyBackupAndEnable();\n }\n })();\n }\n\n /**\n * Callback for `OlmMachine.registerDevicesUpdatedCallback`\n *\n * Called when users' devices have updated. Emits `WillUpdateDevices` and `DevicesUpdated`. In the JavaScript\n * crypto backend, these events are called at separate times, with `WillUpdateDevices` being emitted just before\n * the devices are saved, and `DevicesUpdated` being emitted just after. But the OlmMachine only gives us\n * one event, so we emit both events here.\n *\n * @param userIds - an array of user IDs of users whose devices have updated.\n */\n onDevicesUpdated(userIds) {\n var _this68 = this;\n return _asyncToGenerator(function* () {\n _this68.emit(CryptoEvent.WillUpdateDevices, userIds, false);\n _this68.emit(CryptoEvent.DevicesUpdated, userIds, false);\n })();\n }\n\n /**\n * Handles secret received from the rust secret inbox.\n *\n * The gossipped secrets are received using the `m.secret.send` event type\n * and are guaranteed to have been received over a 1-to-1 Olm\n * Session from a verified device.\n *\n * The only secret currently handled in this way is `m.megolm_backup.v1`.\n *\n * @param name - the secret name\n * @param value - the secret value\n */\n handleSecretReceived(name, value) {\n var _this69 = this;\n return _asyncToGenerator(function* () {\n _this69.logger.debug(\"onReceiveSecret: Received secret \".concat(name));\n if (name === \"m.megolm_backup.v1\") {\n return yield _this69.backupManager.handleBackupSecretReceived(value);\n // XXX at this point we should probably try to download the backup and import the keys,\n // or at least retry for the current decryption failures?\n // Maybe add some signaling when a new secret is received, and let clients handle it?\n // as it's where the restore from backup APIs are exposed.\n }\n return false;\n })();\n }\n\n /**\n * Called when a new secret is received in the rust secret inbox.\n *\n * Will poll the secret inbox and handle the secrets received.\n *\n * @param name - The name of the secret received.\n */\n checkSecrets(name) {\n var _this70 = this;\n return _asyncToGenerator(function* () {\n var pendingValues = yield _this70.olmMachine.getSecretsFromInbox(name);\n for (var value of pendingValues) {\n if (yield _this70.handleSecretReceived(name, value)) {\n // If we have a valid secret for that name there is no point of processing the other secrets values.\n // It's probably the same secret shared by another device.\n break;\n }\n }\n\n // Important to call this after handling the secrets as good hygiene.\n yield _this70.olmMachine.deleteSecretsFromInbox(name);\n })();\n }\n\n /**\n * Handle a live event received via /sync.\n * See {@link ClientEventHandlerMap#event}\n *\n * @param event - live event\n */\n onLiveEventFromSync(event) {\n var _this71 = this;\n return _asyncToGenerator(function* () {\n // Ignore state event or remote echo\n // transaction_id is provided in case of remote echo {@link https://spec.matrix.org/v1.7/client-server-api/#local-echo}\n if (event.isState() || !!event.getUnsigned().transaction_id) return;\n var processEvent = /*#__PURE__*/function () {\n var _ref6 = _asyncToGenerator(function* (evt) {\n // Process only verification event\n if (isVerificationEvent(event)) {\n yield _this71.onKeyVerificationEvent(evt);\n }\n });\n return function processEvent(_x2) {\n return _ref6.apply(this, arguments);\n };\n }();\n\n // If the event is encrypted of in failure, we wait for decryption\n if (event.isDecryptionFailure() || event.isEncrypted()) {\n // 5 mins\n var TIMEOUT_DELAY = 5 * 60 * 1000;\n\n // After 5mins, we are not expecting the event to be decrypted\n var timeoutId = setTimeout(() => event.off(MatrixEventEvent.Decrypted, onDecrypted), TIMEOUT_DELAY);\n var onDecrypted = (decryptedEvent, error) => {\n if (error) return;\n clearTimeout(timeoutId);\n event.off(MatrixEventEvent.Decrypted, onDecrypted);\n processEvent(decryptedEvent);\n };\n event.on(MatrixEventEvent.Decrypted, onDecrypted);\n } else {\n yield processEvent(event);\n }\n })();\n }\n\n /**\n * Handle an in-room key verification event.\n *\n * @param event - a key validation request event.\n */\n onKeyVerificationEvent(event) {\n var _this72 = this;\n return _asyncToGenerator(function* () {\n var roomId = event.getRoomId();\n var senderId = event.getSender();\n if (!roomId) {\n throw new Error(\"missing roomId in the event\");\n }\n if (!senderId) {\n throw new Error(\"missing sender in the event\");\n }\n _this72.logger.debug(\"Incoming verification event \".concat(event.getId(), \" type \").concat(event.getType(), \" from \").concat(event.getSender()));\n var isRoomVerificationRequest = event.getType() === EventType.RoomMessage && event.getContent().msgtype === MsgType.KeyVerificationRequest;\n if (isRoomVerificationRequest) {\n // Before processing an in-room verification request, we need to\n // make sure we have the sender's device information - otherwise we\n // will immediately abort verification. So we explicitly fetch it\n // from /keys/query and wait for that request to complete before we\n // call receiveVerificationEvent.\n var req = _this72.getOlmMachineOrThrow().queryKeysForUsers([new RustSdkCryptoJs.UserId(senderId)]);\n yield _this72.outgoingRequestProcessor.makeOutgoingRequest(req);\n }\n yield _this72.getOlmMachineOrThrow().receiveVerificationEvent(JSON.stringify({\n event_id: event.getId(),\n type: event.getType(),\n sender: senderId,\n state_key: event.getStateKey(),\n content: event.getContent(),\n origin_server_ts: event.getTs()\n }), new RustSdkCryptoJs.RoomId(roomId));\n if (isRoomVerificationRequest) {\n _this72.onIncomingKeyVerificationRequest(senderId, event.getId());\n }\n\n // that may have caused us to queue up outgoing requests, so make sure we send them.\n _this72.outgoingRequestsManager.doProcessOutgoingRequests().catch(e => {\n _this72.logger.warn(\"onKeyVerificationRequest: Error processing outgoing requests\", e);\n });\n })();\n }\n\n /**\n * Returns the cross-signing user identity of the current user.\n *\n * Not part of the public crypto-api interface.\n * Used during migration from legacy js-crypto to update local trust if needed.\n */\n getOwnIdentity() {\n var _this73 = this;\n return _asyncToGenerator(function* () {\n return yield _this73.olmMachine.getIdentity(new RustSdkCryptoJs.UserId(_this73.userId));\n })();\n }\n}\nclass EventDecryptor {\n constructor(logger, olmMachine, perSessionBackupDownloader) {\n this.logger = logger;\n this.olmMachine = olmMachine;\n this.perSessionBackupDownloader = perSessionBackupDownloader;\n /**\n * Events which we couldn't decrypt due to unknown sessions / indexes.\n *\n * Map from roomId to sessionId to Set of MatrixEvents\n */\n _defineProperty(this, \"eventsPendingKey\", new MapWithDefault(() => new MapWithDefault(() => new Set())));\n }\n attemptEventDecryption(event, isolationMode) {\n var _this74 = this;\n return _asyncToGenerator(function* () {\n // add the event to the pending list *before* attempting to decrypt.\n // then, if the key turns up while decryption is in progress (and\n // decryption fails), we will schedule a retry.\n // (fixes https://github.com/vector-im/element-web/issues/5001)\n _this74.addEventToPendingList(event);\n var trustRequirement;\n switch (isolationMode.kind) {\n case DeviceIsolationModeKind.AllDevicesIsolationMode:\n trustRequirement = RustSdkCryptoJs.TrustRequirement.Untrusted;\n break;\n case DeviceIsolationModeKind.OnlySignedDevicesIsolationMode:\n trustRequirement = RustSdkCryptoJs.TrustRequirement.CrossSignedOrLegacy;\n break;\n }\n try {\n var _res$forwarder;\n var res = yield _this74.olmMachine.decryptRoomEvent(stringifyEvent(event), new RustSdkCryptoJs.RoomId(event.getRoomId()), new RustSdkCryptoJs.DecryptionSettings(trustRequirement));\n\n // Success. We can remove the event from the pending list, if\n // that hasn't already happened.\n _this74.removeEventFromPendingList(event);\n return {\n clearEvent: JSON.parse(res.event),\n claimedEd25519Key: res.senderClaimedEd25519Key,\n senderCurve25519Key: res.senderCurve25519Key,\n keyForwardedBy: (_res$forwarder = res.forwarder) === null || _res$forwarder === void 0 ? void 0 : _res$forwarder.toString()\n };\n } catch (err) {\n if (err instanceof RustSdkCryptoJs.MegolmDecryptionError) {\n _this74.onMegolmDecryptionError(event, err, yield _this74.perSessionBackupDownloader.getServerBackupInfo());\n } else {\n throw new DecryptionError(DecryptionFailureCode.UNKNOWN_ERROR, \"Unknown error\");\n }\n }\n })();\n }\n\n /**\n * Handle a `MegolmDecryptionError` returned by the rust SDK.\n *\n * Fires off a request to the `perSessionBackupDownloader`, if appropriate, and then throws a `DecryptionError`.\n *\n * @param event - The event which could not be decrypted.\n * @param err - The error from the Rust SDK.\n * @param serverBackupInfo - Details about the current backup from the server. `null` if there is no backup.\n * `undefined` if our attempt to check failed.\n */\n onMegolmDecryptionError(event, err, serverBackupInfo) {\n var content = event.getWireContent();\n var errorDetails = {\n sender_key: content.sender_key,\n session_id: content.session_id\n };\n\n // If the error looks like it might be recoverable from backup, queue up a request to try that.\n if (err.code === RustSdkCryptoJs.DecryptionErrorCode.MissingRoomKey || err.code === RustSdkCryptoJs.DecryptionErrorCode.UnknownMessageIndex) {\n this.perSessionBackupDownloader.onDecryptionKeyMissingError(event.getRoomId(), content.session_id);\n\n // If the server is telling us our membership at the time the event\n // was sent, and it isn't \"join\", we use a different error code.\n var membership = event.getMembershipAtEvent();\n if (membership && membership !== KnownMembership.Join && membership !== KnownMembership.Invite) {\n throw new DecryptionError(DecryptionFailureCode.HISTORICAL_MESSAGE_USER_NOT_JOINED, \"This message was sent when we were not a member of the room.\", errorDetails);\n }\n\n // If the event was sent before this device was created, we use some different error codes.\n if (event.getTs() <= this.olmMachine.deviceCreationTimeMs) {\n if (serverBackupInfo === null) {\n throw new DecryptionError(DecryptionFailureCode.HISTORICAL_MESSAGE_NO_KEY_BACKUP, \"This message was sent before this device logged in, and there is no key backup on the server.\", errorDetails);\n } else if (!this.perSessionBackupDownloader.isKeyBackupDownloadConfigured()) {\n throw new DecryptionError(DecryptionFailureCode.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED, \"This message was sent before this device logged in, and key backup is not working.\", errorDetails);\n } else {\n throw new DecryptionError(DecryptionFailureCode.HISTORICAL_MESSAGE_WORKING_BACKUP, \"This message was sent before this device logged in. Key backup is working, but we still do not (yet) have the key.\", errorDetails);\n }\n }\n }\n\n // If we got a withheld code, expose that.\n if (err.maybe_withheld) {\n // Unfortunately the Rust SDK API doesn't let us distinguish between different withheld cases, other than\n // by string-matching.\n var failureCode = err.maybe_withheld === \"The sender has disabled encrypting to unverified devices.\" ? DecryptionFailureCode.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE : DecryptionFailureCode.MEGOLM_KEY_WITHHELD;\n throw new DecryptionError(failureCode, err.maybe_withheld, errorDetails);\n }\n switch (err.code) {\n case RustSdkCryptoJs.DecryptionErrorCode.MissingRoomKey:\n throw new DecryptionError(DecryptionFailureCode.MEGOLM_UNKNOWN_INBOUND_SESSION_ID, \"The sender's device has not sent us the keys for this message.\", errorDetails);\n case RustSdkCryptoJs.DecryptionErrorCode.UnknownMessageIndex:\n throw new DecryptionError(DecryptionFailureCode.OLM_UNKNOWN_MESSAGE_INDEX, \"The sender's device has not sent us the keys for this message at this index.\", errorDetails);\n case RustSdkCryptoJs.DecryptionErrorCode.SenderIdentityVerificationViolation:\n // We're refusing to decrypt due to not trusting the sender,\n // rather than failing to decrypt due to lack of keys, so we\n // don't need to keep it on the pending list.\n this.removeEventFromPendingList(event);\n throw new DecryptionError(DecryptionFailureCode.SENDER_IDENTITY_PREVIOUSLY_VERIFIED, \"The sender identity is unverified, but was previously verified.\");\n case RustSdkCryptoJs.DecryptionErrorCode.UnknownSenderDevice:\n // We're refusing to decrypt due to not trusting the sender,\n // rather than failing to decrypt due to lack of keys, so we\n // don't need to keep it on the pending list.\n this.removeEventFromPendingList(event);\n throw new DecryptionError(DecryptionFailureCode.UNKNOWN_SENDER_DEVICE, \"The sender device is not known.\");\n case RustSdkCryptoJs.DecryptionErrorCode.UnsignedSenderDevice:\n // We're refusing to decrypt due to not trusting the sender,\n // rather than failing to decrypt due to lack of keys, so we\n // don't need to keep it on the pending list.\n this.removeEventFromPendingList(event);\n throw new DecryptionError(DecryptionFailureCode.UNSIGNED_SENDER_DEVICE, \"The sender identity is not cross-signed.\");\n\n // We don't map MismatchedIdentityKeys for now, as there is no equivalent in legacy.\n // Just put it on the `UNKNOWN_ERROR` bucket.\n default:\n throw new DecryptionError(DecryptionFailureCode.UNKNOWN_ERROR, err.description, errorDetails);\n }\n }\n getEncryptionInfoForEvent(event) {\n var _this75 = this;\n return _asyncToGenerator(function* () {\n if (!event.getClearContent() || event.isDecryptionFailure()) {\n // not successfully decrypted\n return null;\n }\n\n // special-case outgoing events, which the rust crypto-sdk will barf on\n if (event.status !== null) {\n return {\n shieldColour: EventShieldColour.NONE,\n shieldReason: null\n };\n }\n var encryptionInfo = yield _this75.olmMachine.getRoomEventEncryptionInfo(stringifyEvent(event), new RustSdkCryptoJs.RoomId(event.getRoomId()));\n return rustEncryptionInfoToJsEncryptionInfo(_this75.logger, encryptionInfo);\n })();\n }\n\n /**\n * Look for events which are waiting for a given megolm session\n *\n * Returns a list of events which were encrypted by `session` and could not be decrypted\n */\n getEventsPendingRoomKey(roomId, sessionId) {\n var roomPendingEvents = this.eventsPendingKey.get(roomId);\n if (!roomPendingEvents) return [];\n var sessionPendingEvents = roomPendingEvents.get(sessionId);\n if (!sessionPendingEvents) return [];\n return [...sessionPendingEvents];\n }\n\n /**\n * Add an event to the list of those awaiting their session keys.\n */\n addEventToPendingList(event) {\n var roomId = event.getRoomId();\n // We shouldn't have events without a room id here.\n if (!roomId) return;\n var roomPendingEvents = this.eventsPendingKey.getOrCreate(roomId);\n var sessionPendingEvents = roomPendingEvents.getOrCreate(event.getWireContent().session_id);\n sessionPendingEvents.add(event);\n }\n\n /**\n * Remove an event from the list of those awaiting their session keys.\n */\n removeEventFromPendingList(event) {\n var roomId = event.getRoomId();\n if (!roomId) return;\n var roomPendingEvents = this.eventsPendingKey.getOrCreate(roomId);\n if (!roomPendingEvents) return;\n var sessionPendingEvents = roomPendingEvents.get(event.getWireContent().session_id);\n if (!sessionPendingEvents) return;\n sessionPendingEvents.delete(event);\n\n // also clean up the higher-level maps if they are now empty\n if (sessionPendingEvents.size === 0) {\n roomPendingEvents.delete(event.getWireContent().session_id);\n if (roomPendingEvents.size === 0) {\n this.eventsPendingKey.delete(roomId);\n }\n }\n }\n}\nfunction stringifyEvent(event) {\n return JSON.stringify({\n event_id: event.getId(),\n type: event.getWireType(),\n sender: event.getSender(),\n state_key: event.getStateKey(),\n content: event.getWireContent(),\n origin_server_ts: event.getTs()\n });\n}\nfunction rustEncryptionInfoToJsEncryptionInfo(logger, encryptionInfo) {\n if (encryptionInfo === undefined) {\n // not decrypted here\n return null;\n }\n\n // TODO: use strict shield semantics.\n var shieldState = encryptionInfo.shieldState(false);\n var shieldColour;\n switch (shieldState.color) {\n case RustSdkCryptoJs.ShieldColor.Grey:\n shieldColour = EventShieldColour.GREY;\n break;\n case RustSdkCryptoJs.ShieldColor.None:\n shieldColour = EventShieldColour.NONE;\n break;\n default:\n shieldColour = EventShieldColour.RED;\n }\n var shieldReason;\n switch (shieldState.code) {\n case undefined:\n case null:\n shieldReason = null;\n break;\n case RustSdkCryptoJs.ShieldStateCode.AuthenticityNotGuaranteed:\n shieldReason = EventShieldReason.AUTHENTICITY_NOT_GUARANTEED;\n break;\n case RustSdkCryptoJs.ShieldStateCode.UnknownDevice:\n shieldReason = EventShieldReason.UNKNOWN_DEVICE;\n break;\n case RustSdkCryptoJs.ShieldStateCode.UnsignedDevice:\n shieldReason = EventShieldReason.UNSIGNED_DEVICE;\n break;\n case RustSdkCryptoJs.ShieldStateCode.UnverifiedIdentity:\n shieldReason = EventShieldReason.UNVERIFIED_IDENTITY;\n break;\n case RustSdkCryptoJs.ShieldStateCode.VerificationViolation:\n shieldReason = EventShieldReason.VERIFICATION_VIOLATION;\n break;\n case RustSdkCryptoJs.ShieldStateCode.MismatchedSender:\n shieldReason = EventShieldReason.MISMATCHED_SENDER;\n break;\n default:\n shieldReason = EventShieldReason.UNKNOWN;\n break;\n }\n return {\n shieldColour,\n shieldReason\n };\n}\n/**\n * Determines if the given payload is a RoomKeyBundleMessage.\n *\n * A RoomKeyBundleMessage is identified by having a specific message type\n * (\"io.element.msc4268.room_key_bundle\") and a valid room_id in its content.\n *\n * @param message - The received to-device message to check.\n * @returns True if the payload matches the RoomKeyBundleMessage structure, false otherwise.\n */\nfunction isRoomKeyBundleMessage(message) {\n return message.type === \"io.element.msc4268.room_key_bundle\" && typeof message.content.room_id === \"string\";\n}\n//# sourceMappingURL=rust-crypto.js.map","import _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\n/*\nCopyright 2023-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\";\nimport { MigrationState } from \"../crypto/store/base.js\";\nimport { IndexedDBCryptoStore } from \"../crypto/store/indexeddb-crypto-store.js\";\nimport { requestKeyBackupVersion } from \"./backup.js\";\nimport { sleep } from \"../utils.js\";\nimport { encodeBase64 } from \"../base64.js\";\nimport decryptAESSecretStorageItem from \"../utils/decryptAESSecretStorageItem.js\";\n/**\n * Determine if any data needs migrating from the legacy store, and do so.\n *\n * This migrates the base account data, and olm and megolm sessions. It does *not* migrate the room list, which should\n * happen after an `OlmMachine` is created, via {@link migrateRoomSettingsFromLegacyCrypto}.\n *\n * @param args - Arguments object.\n */\nexport function migrateFromLegacyCrypto(_x) {\n return _migrateFromLegacyCrypto.apply(this, arguments);\n}\nfunction _migrateFromLegacyCrypto() {\n _migrateFromLegacyCrypto = _asyncToGenerator(function* (args) {\n var _args$legacyMigration2;\n var {\n logger,\n legacyStore\n } = args;\n\n // initialise the rust matrix-sdk-crypto-wasm, if it hasn't already been done\n yield RustSdkCryptoJs.initAsync();\n if (!(yield legacyStore.containsData())) {\n // This store was never used. Nothing to migrate.\n return;\n }\n yield legacyStore.startup();\n var accountPickle = null;\n yield legacyStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], txn => {\n legacyStore.getAccount(txn, acctPickle => {\n accountPickle = acctPickle;\n });\n });\n if (!accountPickle) {\n // This store is not properly set up. Nothing to migrate.\n logger.debug(\"Legacy crypto store is not set up (no account found). Not migrating.\");\n return;\n }\n var migrationState = yield legacyStore.getMigrationState();\n if (migrationState >= MigrationState.MEGOLM_SESSIONS_MIGRATED) {\n // All migration is done for now. The room list comes later, once we have an OlmMachine.\n return;\n }\n var nOlmSessions = yield countOlmSessions(logger, legacyStore);\n var nMegolmSessions = yield countMegolmSessions(logger, legacyStore);\n var totalSteps = 1 + nOlmSessions + nMegolmSessions;\n logger.info(\"Migrating data from legacy crypto store. \".concat(nOlmSessions, \" olm sessions and \").concat(nMegolmSessions, \" megolm sessions to migrate.\"));\n var stepsDone = 0;\n function onProgress(steps) {\n var _args$legacyMigration;\n stepsDone += steps;\n (_args$legacyMigration = args.legacyMigrationProgressListener) === null || _args$legacyMigration === void 0 || _args$legacyMigration.call(args, stepsDone, totalSteps);\n }\n onProgress(0);\n var pickleKey = new TextEncoder().encode(args.legacyPickleKey).slice();\n if (migrationState === MigrationState.NOT_STARTED) {\n logger.info(\"Migrating data from legacy crypto store. Step 1: base data\");\n yield migrateBaseData(args.http, args.userId, args.deviceId, legacyStore, pickleKey, args.storeHandle, logger);\n migrationState = MigrationState.INITIAL_DATA_MIGRATED;\n yield legacyStore.setMigrationState(migrationState);\n }\n onProgress(1);\n if (migrationState === MigrationState.INITIAL_DATA_MIGRATED) {\n logger.info(\"Migrating data from legacy crypto store. Step 2: olm sessions (\".concat(nOlmSessions, \" sessions to migrate).\"));\n yield migrateOlmSessions(logger, legacyStore, pickleKey, args.storeHandle, onProgress);\n migrationState = MigrationState.OLM_SESSIONS_MIGRATED;\n yield legacyStore.setMigrationState(migrationState);\n }\n if (migrationState === MigrationState.OLM_SESSIONS_MIGRATED) {\n logger.info(\"Migrating data from legacy crypto store. Step 3: megolm sessions (\".concat(nMegolmSessions, \" sessions to migrate).\"));\n yield migrateMegolmSessions(logger, legacyStore, pickleKey, args.storeHandle, onProgress);\n migrationState = MigrationState.MEGOLM_SESSIONS_MIGRATED;\n yield legacyStore.setMigrationState(migrationState);\n }\n\n // Migration is done.\n (_args$legacyMigration2 = args.legacyMigrationProgressListener) === null || _args$legacyMigration2 === void 0 || _args$legacyMigration2.call(args, -1, -1);\n logger.info(\"Migration from legacy crypto store complete\");\n });\n return _migrateFromLegacyCrypto.apply(this, arguments);\n}\nfunction migrateBaseData(_x2, _x3, _x4, _x5, _x6, _x7, _x8) {\n return _migrateBaseData.apply(this, arguments);\n}\nfunction _migrateBaseData() {\n _migrateBaseData = _asyncToGenerator(function* (http, userId, deviceId, legacyStore, pickleKey, storeHandle, logger) {\n var migrationData = new RustSdkCryptoJs.BaseMigrationData();\n migrationData.userId = new RustSdkCryptoJs.UserId(userId);\n migrationData.deviceId = new RustSdkCryptoJs.DeviceId(deviceId);\n yield legacyStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], txn => legacyStore.getAccount(txn, a => {\n migrationData.pickledAccount = a !== null && a !== void 0 ? a : \"\";\n }));\n var recoveryKey = yield getAndDecryptCachedSecretKey(legacyStore, pickleKey, \"m.megolm_backup.v1\");\n\n // If we have a backup recovery key, we need to try to figure out which backup version it is for.\n // All we can really do is ask the server for the most recent version and check if the cached key we have matches.\n // It is possible that the backup has changed since last time his session was opened.\n if (recoveryKey) {\n var backupCallDone = false;\n var backupInfo = null;\n while (!backupCallDone) {\n try {\n backupInfo = yield requestKeyBackupVersion(http);\n backupCallDone = true;\n } catch (e) {\n logger.info(\"Failed to get backup version during migration, retrying in 2 seconds\", e);\n // Retry until successful, use simple constant delay\n yield sleep(2000);\n }\n }\n if (backupInfo && backupInfo.algorithm == \"m.megolm_backup.v1.curve25519-aes-sha2\") {\n // check if the recovery key matches, as the active backup version may have changed since the key was cached\n // and the migration started.\n try {\n var _backupInfo$auth_data;\n var decryptionKey = RustSdkCryptoJs.BackupDecryptionKey.fromBase64(recoveryKey);\n var publicKey = (_backupInfo$auth_data = backupInfo.auth_data) === null || _backupInfo$auth_data === void 0 ? void 0 : _backupInfo$auth_data.public_key;\n var isValid = decryptionKey.megolmV1PublicKey.publicKeyBase64 == publicKey;\n if (isValid) {\n migrationData.backupVersion = backupInfo.version;\n migrationData.backupRecoveryKey = recoveryKey;\n } else {\n logger.debug(\"The backup key to migrate does not match the active backup version\", \"Cached pub key: \".concat(decryptionKey.megolmV1PublicKey.publicKeyBase64), \"Active pub key: \".concat(publicKey));\n }\n } catch (e) {\n logger.warn(\"Failed to check if the backup key to migrate matches the active backup version\", e);\n }\n }\n }\n migrationData.privateCrossSigningMasterKey = yield getAndDecryptCachedSecretKey(legacyStore, pickleKey, \"master\");\n migrationData.privateCrossSigningSelfSigningKey = yield getAndDecryptCachedSecretKey(legacyStore, pickleKey, \"self_signing\");\n migrationData.privateCrossSigningUserSigningKey = yield getAndDecryptCachedSecretKey(legacyStore, pickleKey, \"user_signing\");\n yield RustSdkCryptoJs.Migration.migrateBaseData(migrationData, pickleKey, storeHandle, logger);\n });\n return _migrateBaseData.apply(this, arguments);\n}\nfunction countOlmSessions(_x9, _x0) {\n return _countOlmSessions.apply(this, arguments);\n}\nfunction _countOlmSessions() {\n _countOlmSessions = _asyncToGenerator(function* (logger, legacyStore) {\n logger.debug(\"Counting olm sessions to be migrated\");\n var nSessions;\n yield legacyStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_SESSIONS], txn => legacyStore.countEndToEndSessions(txn, n => nSessions = n));\n return nSessions;\n });\n return _countOlmSessions.apply(this, arguments);\n}\nfunction countMegolmSessions(_x1, _x10) {\n return _countMegolmSessions.apply(this, arguments);\n}\nfunction _countMegolmSessions() {\n _countMegolmSessions = _asyncToGenerator(function* (logger, legacyStore) {\n logger.debug(\"Counting megolm sessions to be migrated\");\n return yield legacyStore.countEndToEndInboundGroupSessions();\n });\n return _countMegolmSessions.apply(this, arguments);\n}\nfunction migrateOlmSessions(_x11, _x12, _x13, _x14, _x15) {\n return _migrateOlmSessions.apply(this, arguments);\n}\nfunction _migrateOlmSessions() {\n _migrateOlmSessions = _asyncToGenerator(function* (logger, legacyStore, pickleKey, storeHandle, onBatchDone) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n var batch = yield legacyStore.getEndToEndSessionsBatch();\n if (batch === null) return;\n logger.debug(\"Migrating batch of \".concat(batch.length, \" olm sessions\"));\n var migrationData = [];\n for (var session of batch) {\n var pickledSession = new RustSdkCryptoJs.PickledSession();\n pickledSession.senderKey = session.deviceKey;\n pickledSession.pickle = session.session;\n pickledSession.lastUseTime = pickledSession.creationTime = new Date(session.lastReceivedMessageTs);\n migrationData.push(pickledSession);\n }\n yield RustSdkCryptoJs.Migration.migrateOlmSessions(migrationData, pickleKey, storeHandle, logger);\n yield legacyStore.deleteEndToEndSessionsBatch(batch);\n onBatchDone(batch.length);\n }\n });\n return _migrateOlmSessions.apply(this, arguments);\n}\nfunction migrateMegolmSessions(_x16, _x17, _x18, _x19, _x20) {\n return _migrateMegolmSessions.apply(this, arguments);\n}\n/**\n * Determine if any room settings need migrating from the legacy store, and do so.\n *\n * @param args - Arguments object.\n */\nfunction _migrateMegolmSessions() {\n _migrateMegolmSessions = _asyncToGenerator(function* (logger, legacyStore, pickleKey, storeHandle, onBatchDone) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n var batch = yield legacyStore.getEndToEndInboundGroupSessionsBatch();\n if (batch === null) return;\n logger.debug(\"Migrating batch of \".concat(batch.length, \" megolm sessions\"));\n var migrationData = [];\n for (var session of batch) {\n var _sessionData$keysClai;\n var sessionData = session.sessionData;\n var pickledSession = new RustSdkCryptoJs.PickledInboundGroupSession();\n pickledSession.pickle = sessionData.session;\n pickledSession.roomId = new RustSdkCryptoJs.RoomId(sessionData.room_id);\n pickledSession.senderKey = session.senderKey;\n pickledSession.senderSigningKey = (_sessionData$keysClai = sessionData.keysClaimed) === null || _sessionData$keysClai === void 0 ? void 0 : _sessionData$keysClai[\"ed25519\"];\n pickledSession.backedUp = !session.needsBackup;\n\n // The Rust SDK `imported` flag is used to indicate the authenticity status of a Megolm\n // session, which tells us whether we can reliably tell which Olm device is the owner\n // (creator) of the session.\n //\n // If `imported` is true, then we have no cryptographic proof that the session is owned\n // by the device with the identity key `senderKey`.\n //\n // Only Megolm sessions received directly from the owning device via an encrypted\n // `m.room_key` to-device message should have `imported` flag set to false. Megolm\n // sessions received by any other currently available means (i.e. from a\n // `m.forwarded_room_key`, from v1 asymmetric server-side key backup, imported from a\n // file, etc) should have the `imported` flag set to true.\n //\n // Messages encrypted with such Megolm sessions will have a grey shield in the UI\n // (\"Authenticity of this message cannot be guaranteed\").\n //\n // However, we don't want to bluntly mark all sessions as `imported` during migration\n // because users will suddenly start seeing all their historic messages decorated with a\n // grey shield, which would be seen as a non-actionable regression.\n //\n // In the legacy crypto stack, the flag encoding similar information was called\n // `InboundGroupSessionData.untrusted`. The value of this flag was set as follows:\n //\n // - For outbound Megolm sessions created by our own device, `untrusted` is `undefined`.\n // - For Megolm sessions received via a `m.room_key` to-device message, `untrusted` is\n // `undefined`.\n // - For Megolm sessions received via a `m.forwarded_room_key` to-device message,\n // `untrusted` is `true`.\n // - For Megolm sessions imported from a (v1 asymmetric / \"legacy\") server-side key\n // backup, `untrusted` is `true`.\n // - For Megolm sessions imported from a file, untrusted is `undefined`.\n //\n // The main difference between the legacy crypto stack and the Rust crypto stack is that\n // the Rust stack considers sessions imported from a file as `imported` (not\n // authenticated). This is because the Megolm session export file format does not\n // encode this authenticity information.\n //\n // Given this migration is only a one-time thing, we make a concession to accept the\n // loss of information in this case, to avoid degrading UX in a non-actionable way.\n pickledSession.imported = sessionData.untrusted === true;\n migrationData.push(pickledSession);\n }\n yield RustSdkCryptoJs.Migration.migrateMegolmSessions(migrationData, pickleKey, storeHandle, logger);\n yield legacyStore.deleteEndToEndInboundGroupSessionsBatch(batch);\n onBatchDone(batch.length);\n }\n });\n return _migrateMegolmSessions.apply(this, arguments);\n}\nexport function migrateRoomSettingsFromLegacyCrypto(_x21) {\n return _migrateRoomSettingsFromLegacyCrypto.apply(this, arguments);\n}\nfunction _migrateRoomSettingsFromLegacyCrypto() {\n _migrateRoomSettingsFromLegacyCrypto = _asyncToGenerator(function* (_ref) {\n var {\n logger,\n legacyStore,\n olmMachine\n } = _ref;\n if (!(yield legacyStore.containsData())) {\n // This store was never used. Nothing to migrate.\n return;\n }\n var migrationState = yield legacyStore.getMigrationState();\n if (migrationState >= MigrationState.ROOM_SETTINGS_MIGRATED) {\n // We've already migrated the room settings.\n return;\n }\n var rooms = {};\n yield legacyStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ROOMS], txn => {\n legacyStore.getEndToEndRooms(txn, result => {\n rooms = result;\n });\n });\n logger.debug(\"Migrating \".concat(Object.keys(rooms).length, \" sets of room settings\"));\n for (var [roomId, legacySettings] of Object.entries(rooms)) {\n try {\n var rustSettings = new RustSdkCryptoJs.RoomSettings();\n if (legacySettings.algorithm !== \"m.megolm.v1.aes-sha2\") {\n logger.warn(\"Room \".concat(roomId, \": ignoring room with invalid algorithm \").concat(legacySettings.algorithm));\n continue;\n }\n rustSettings.algorithm = RustSdkCryptoJs.EncryptionAlgorithm.MegolmV1AesSha2;\n rustSettings.sessionRotationPeriodMs = legacySettings.rotation_period_ms;\n rustSettings.sessionRotationPeriodMessages = legacySettings.rotation_period_msgs;\n yield olmMachine.setRoomSettings(new RustSdkCryptoJs.RoomId(roomId), rustSettings);\n\n // We don't attempt to clear out the settings from the old store, or record where we've gotten up to,\n // which means that if the app gets restarted while we're in the middle of this migration, we'll start\n // again from scratch. So be it. Given that legacy crypto loads the whole room list into memory on startup\n // anyway, we know it can't be that big.\n } catch (e) {\n logger.warn(\"Room \".concat(roomId, \": ignoring settings \").concat(JSON.stringify(legacySettings), \" which caused error \").concat(e));\n }\n }\n logger.debug(\"Completed room settings migration\");\n yield legacyStore.setMigrationState(MigrationState.ROOM_SETTINGS_MIGRATED);\n });\n return _migrateRoomSettingsFromLegacyCrypto.apply(this, arguments);\n}\nfunction getAndDecryptCachedSecretKey(_x22, _x23, _x24) {\n return _getAndDecryptCachedSecretKey.apply(this, arguments);\n}\n/**\n * Check if the user's published identity (ie, public cross-signing keys) was trusted by the legacy session,\n * and if so mark it as trusted in the Rust session if needed.\n *\n * By default, if the legacy session didn't have the private MSK, the migrated session will revert to unverified,\n * even if the user has verified the session in the past.\n *\n * This only occurs if the private MSK was not cached in the crypto store (USK and SSK private keys won't help\n * to establish trust: the trust is rooted in the MSK).\n *\n * Rust crypto will only consider the current session as trusted if we import the private MSK itself.\n *\n * We could prompt the user to verify the session again, but it's probably better to just mark the user identity\n * as locally verified if it was before.\n *\n * See https://github.com/element-hq/element-web/issues/27079\n *\n * @param args - Argument object.\n */\nfunction _getAndDecryptCachedSecretKey() {\n _getAndDecryptCachedSecretKey = _asyncToGenerator(function* (legacyStore, legacyPickleKey, name) {\n var key = yield new Promise(resolve => {\n legacyStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], txn => {\n legacyStore.getSecretStorePrivateKey(txn, resolve, name);\n });\n });\n if (key && key.ciphertext && key.iv && key.mac) {\n return yield decryptAESSecretStorageItem(key, legacyPickleKey, name);\n } else if (key instanceof Uint8Array) {\n // This is a legacy backward compatibility case where the key was stored in clear.\n return encodeBase64(key);\n } else {\n return undefined;\n }\n });\n return _getAndDecryptCachedSecretKey.apply(this, arguments);\n}\nexport function migrateLegacyLocalTrustIfNeeded(_x25) {\n return _migrateLegacyLocalTrustIfNeeded.apply(this, arguments);\n}\n\n/**\n * Checks if the legacy store has a trusted public master key, and returns it if so.\n *\n * @param legacyStore - The legacy store to check.\n *\n * @returns `null` if there were no cross signing keys or if they were not trusted. The trusted public master key if it was.\n */\nfunction _migrateLegacyLocalTrustIfNeeded() {\n _migrateLegacyLocalTrustIfNeeded = _asyncToGenerator(function* (args) {\n var {\n legacyCryptoStore,\n rustCrypto,\n logger\n } = args;\n // Get the public cross-signing identity from rust.\n var rustOwnIdentity = yield rustCrypto.getOwnIdentity();\n if (!rustOwnIdentity) {\n // There are no cross-signing keys published server side, so nothing to do here.\n return;\n }\n if (rustOwnIdentity.isVerified()) {\n // The rust session already trusts the keys, so again, nothing to do.\n return;\n }\n var legacyLocallyTrustedMSK = yield getLegacyTrustedPublicMasterKeyBase64(legacyCryptoStore);\n if (!legacyLocallyTrustedMSK) {\n // The user never verified their identity in the legacy session, so nothing to do.\n return;\n }\n var mskInfo = JSON.parse(rustOwnIdentity.masterKey);\n if (!mskInfo.keys || Object.keys(mskInfo.keys).length === 0) {\n // This should not happen, but let's be safe\n logger.error(\"Post Migration | Unexpected error: no master key in the rust session.\");\n return;\n }\n var rustSeenMSK = Object.values(mskInfo.keys)[0];\n if (rustSeenMSK && rustSeenMSK == legacyLocallyTrustedMSK) {\n logger.info(\"Post Migration: Migrating legacy trusted MSK: \".concat(legacyLocallyTrustedMSK, \" to locally verified.\"));\n // Let's mark the user identity as locally verified as part of the migration.\n yield rustOwnIdentity.verify();\n // As well as marking the MSK as trusted, `OlmMachine.verify` returns a\n // `SignatureUploadRequest` which will publish a signature of the MSK using\n // this device. In this case, we ignore the request: since the user hasn't\n // actually re-verified the MSK, we don't publish a new signature. (`.verify`\n // doesn't store the signature, and if we drop the request here it won't be\n // retried.)\n //\n // Not publishing the signature is consistent with the behaviour of\n // matrix-crypto-sdk when the private key is imported via\n // `importCrossSigningKeys`, and when the identity is verified via interactive\n // verification.\n //\n // [Aside: device signatures on the MSK are not considered by the rust-sdk to\n // establish the trust of the user identity so in any case, what we actually do\n // here is somewhat moot.]\n }\n });\n return _migrateLegacyLocalTrustIfNeeded.apply(this, arguments);\n}\nfunction getLegacyTrustedPublicMasterKeyBase64(_x26) {\n return _getLegacyTrustedPublicMasterKeyBase.apply(this, arguments);\n}\nfunction _getLegacyTrustedPublicMasterKeyBase() {\n _getLegacyTrustedPublicMasterKeyBase = _asyncToGenerator(function* (legacyStore) {\n var maybeTrustedKeys = null;\n yield legacyStore.doTxn(\"readonly\", \"account\", txn => {\n legacyStore.getCrossSigningKeys(txn, keys => {\n // can be an empty object after resetting cross-signing keys, see storeTrustedSelfKeys\n var msk = keys === null || keys === void 0 ? void 0 : keys.master;\n if (msk && Object.keys(msk.keys).length != 0) {\n // `msk.keys` is an object with { [`ed25519:${pubKey}`]: pubKey }\n maybeTrustedKeys = Object.values(msk.keys)[0];\n }\n });\n });\n return maybeTrustedKeys;\n });\n return _getLegacyTrustedPublicMasterKeyBase.apply(this, arguments);\n}\n//# sourceMappingURL=libolm_migration.js.map","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _asyncToGenerator from \"@babel/runtime/helpers/asyncToGenerator\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { StoreHandle } from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { RustCrypto } from \"./rust-crypto.js\";\nimport { MigrationState } from \"../crypto/store/base.js\";\nimport { migrateFromLegacyCrypto, migrateLegacyLocalTrustIfNeeded, migrateRoomSettingsFromLegacyCrypto } from \"./libolm_migration.js\";\n/**\n * Create a new `RustCrypto` implementation\n *\n * @param args - Parameter object\n * @internal\n */\nexport function initRustCrypto(_x) {\n return _initRustCrypto.apply(this, arguments);\n}\nfunction _initRustCrypto() {\n _initRustCrypto = _asyncToGenerator(function* (args) {\n var {\n logger\n } = args;\n\n // initialise the rust matrix-sdk-crypto-wasm, if it hasn't already been done\n logger.debug(\"Initialising Rust crypto-sdk WASM artifact\");\n yield RustSdkCryptoJs.initAsync();\n logger.debug(\"Opening Rust CryptoStore\");\n var storeHandle;\n if (args.storePrefix) {\n if (args.storeKey) {\n storeHandle = yield StoreHandle.openWithKey(args.storePrefix, args.storeKey, logger);\n } else {\n storeHandle = yield StoreHandle.open(args.storePrefix, args.storePassphrase, logger);\n }\n } else {\n storeHandle = yield StoreHandle.open(null, null, logger);\n }\n if (args.legacyCryptoStore) {\n // We have a legacy crypto store, which we may need to migrate from.\n yield migrateFromLegacyCrypto(_objectSpread({\n legacyStore: args.legacyCryptoStore,\n storeHandle\n }, args));\n }\n var rustCrypto = yield initOlmMachine(logger, args.http, args.userId, args.deviceId, args.secretStorage, args.cryptoCallbacks, storeHandle, args.legacyCryptoStore, args.enableEncryptedStateEvents);\n storeHandle.free();\n logger.debug(\"Completed rust crypto-sdk setup\");\n return rustCrypto;\n });\n return _initRustCrypto.apply(this, arguments);\n}\nfunction initOlmMachine(_x2, _x3, _x4, _x5, _x6, _x7, _x8, _x9, _x0) {\n return _initOlmMachine.apply(this, arguments);\n}\nfunction _initOlmMachine() {\n _initOlmMachine = _asyncToGenerator(function* (logger, http, userId, deviceId, secretStorage, cryptoCallbacks, storeHandle, legacyCryptoStore, enableEncryptedStateEvents) {\n logger.debug(\"Init OlmMachine\");\n var olmMachine = yield RustSdkCryptoJs.OlmMachine.initFromStore(new RustSdkCryptoJs.UserId(userId), new RustSdkCryptoJs.DeviceId(deviceId), storeHandle, logger);\n\n // A final migration step, now that we have an OlmMachine.\n if (legacyCryptoStore) {\n yield migrateRoomSettingsFromLegacyCrypto({\n logger,\n legacyStore: legacyCryptoStore,\n olmMachine\n });\n }\n\n // Disable room key requests, per https://github.com/vector-im/element-web/issues/26524.\n olmMachine.roomKeyRequestsEnabled = false;\n var rustCrypto = new RustCrypto(logger, olmMachine, http, userId, deviceId, secretStorage, cryptoCallbacks, enableEncryptedStateEvents);\n yield olmMachine.registerRoomKeyUpdatedCallback(sessions => rustCrypto.onRoomKeysUpdated(sessions));\n yield olmMachine.registerRoomKeysWithheldCallback(withheld => rustCrypto.onRoomKeysWithheld(withheld));\n yield olmMachine.registerUserIdentityUpdatedCallback(userId => rustCrypto.onUserIdentityUpdated(userId));\n yield olmMachine.registerDevicesUpdatedCallback(userIds => rustCrypto.onDevicesUpdated(userIds));\n\n // Check if there are any key backup secrets pending processing. There may be multiple secrets to process if several devices have gossiped them.\n // The `registerReceiveSecretCallback` function will only be triggered for new secrets. If the client is restarted before processing them, the secrets will need to be manually handled.\n rustCrypto.checkSecrets(\"m.megolm_backup.v1\");\n\n // Register a callback to be notified when a new secret is received, as for now only the key backup secret is supported (the cross signing secrets are handled automatically by the OlmMachine)\n yield olmMachine.registerReceiveSecretCallback((name, _value) =>\n // Instead of directly checking the secret value, we poll the inbox to get all values for that secret type.\n // Once we have all the values, we can safely clear the secret inbox.\n rustCrypto.checkSecrets(name));\n\n // Tell the OlmMachine to think about its outgoing requests before we hand control back to the application.\n //\n // This is primarily a fudge to get it to correctly populate the `users_for_key_query` list, so that future\n // calls to getIdentity (etc) block until the key queries are performed.\n //\n // Note that we don't actually need to *make* any requests here; it is sufficient to tell the Rust side to think\n // about them.\n //\n // XXX: find a less hacky way to do this.\n yield olmMachine.outgoingRequests();\n if (legacyCryptoStore && (yield legacyCryptoStore.containsData())) {\n var migrationState = yield legacyCryptoStore.getMigrationState();\n if (migrationState < MigrationState.INITIAL_OWN_KEY_QUERY_DONE) {\n logger.debug(\"Performing initial key query after migration\");\n // We need to do an initial keys query so that the rust stack can properly update trust of\n // the user device and identity from the migrated private keys.\n // If not done, there is a short period where the own device/identity trust will be undefined after migration.\n var initialKeyQueryDone = false;\n while (!initialKeyQueryDone) {\n try {\n yield rustCrypto.userHasCrossSigningKeys(userId);\n initialKeyQueryDone = true;\n } catch (e) {\n // If the initial key query fails, we retry until it succeeds.\n logger.error(\"Failed to check for cross-signing keys after migration, retrying\", e);\n }\n }\n\n // If the private master cross-signing key was not cached in the legacy store, the rust session\n // will not be able to establish the trust of the user identity.\n // That means that after migration the session could revert to unverified.\n // In order to avoid asking the users to re-verify their sessions, we need to migrate the legacy local trust\n // (if the legacy session was already verified) to the new session.\n yield migrateLegacyLocalTrustIfNeeded({\n legacyCryptoStore,\n rustCrypto,\n logger\n });\n yield legacyCryptoStore.setMigrationState(MigrationState.INITIAL_OWN_KEY_QUERY_DONE);\n }\n }\n return rustCrypto;\n });\n return _initOlmMachine.apply(this, arguments);\n}\n//# sourceMappingURL=index.js.map"],"names":["VerificationRequestEvent","VerificationPhase","VerifierEvent","OLM_RECOVERY_KEY_PREFIX","encodeRecoveryKey","key","_base58key$match","buf","parity","i","base58key","bs58","DEFAULT_BIT_SIZE","deriveRecoveryKeyFromPassphrase","_x","_x2","_x3","_deriveRecoveryKeyFromPassphrase","_asyncToGenerator","passphrase","salt","iterations","numBits","keybits","escaped","escapes","escapeString","value","c","stringify","stringifyArray","stringifyObject","array","sep","result","object","keys","anotherJson","RoomEncryptor","prefixedLogger","olmMachine","keyClaimManager","outgoingRequestManager","room","encryptionSettings","_defineProperty","members","RustSdkCryptoJs.UserId","e","config","member","KnownMembership","UserId","globalBlacklistUnverifiedDevices","deviceIsolationMode","_this","event","_event$getTxnId","_this2","logger","LogSpan","prom","logDuration","_this3","u","userList","rustEncryptionSettings","EncryptionSettings","toRustHistoryVisibility","EncryptionAlgorithm","DeviceIsolationModeKind","_this3$room$getBlackl","onlyAllowTrustedDevices","CollectStrategy","shareMessages","RoomId","m","_this4","_this5","type","content","encryptedContent","EventType","visibility","HistoryVisibility","RustHistoryVisibility","UnstablePrefix","SECRET_STORAGE_NAME","DEHYDRATION_INTERVAL","DehydratedDeviceManager","TypedEventEmitter","http","outgoingRequestProcessor","secretStorage","CryptoEvent","Method","error","err","_arguments","opts","RustSdkCryptoJs.DehydratedDeviceKey","create","_this6","cachedKey","keyB64","bytes","decodeBase64","_this7","dehydratedDeviceResp","rehydratedDevice","RustSdkCryptoJs.DeviceId","nextBatch","toDeviceCount","roomKeyCount","path","encodeUri","eventResp","roomKeyInfos","_this8","dehydratedDevice","request","_this9","_this0","ownKeys","r","t","o","_objectSpread","OutgoingRequestProcessor","msg","uiaCallback","resp","KeysUploadRequest","KeysQueryRequest","KeysClaimRequest","SignatureUploadRequest","KeysBackupRequest","ToDeviceRequest","RoomMessageRequest","UploadSigningKeysRequest","PutDehydratedDeviceRequest","_path","DehydrationUnstablePrefix","parsedBody","messageList","userId","perUserMessages","deviceId","message","ToDeviceMessageId","method","queryParams","body","makeRequest","_ref2","auth","newBody","currentRetryCount","backoff","calculateRetryBackoff","sleep","KeyClaimManager","claimRequest","rustDeviceToJsDevice","device","keyId","verified","DeviceVerification","signatures","mayBeSignatureMap","convertedSignatures","_key","rustAlgorithms","algorithms","algorithm","RustSdkCryptoJs.EncryptionAlgorithm","Device","deviceKeysToDeviceMap","deviceKeys","_ref","downloadDeviceToJsDevice","_device$unsigned","displayName","CrossSigningIdentity","olmDeviceStatus","masterKeyFromSecretStorage","selfSigningKeyFromSecretStorage","userSigningKeyFromSecretStorage","privateKeysInSecretStorage","olmDeviceHasKeys","status","authUploadDeviceSigningKeys","outgoingRequests","req","exported","secretStorageContainsCrossSigningKeys","_secretStorageContainsCrossSigningKeys","secretStorageCanAccessSecrets","_secretStorageCanAccessSecrets","secretNames","defaultKeyId","secretName","record","VerificationMethod","RustVerificationRequest","inner","supportedVerificationMethods","TypedReEmitter","weakThis","_weakThis$deref","verification","RustSdkCryptoJs.Sas","RustQrCodeVerifier","RustSASVerifier","RustSdkCryptoJs.Qr","verifier","_this$inner$roomId","_this$inner$otherDevi","otherDeviceId","phase","RustSdkCryptoJs.VerificationRequestPhase","theirMethods","requiredMethod","verificationMethodsByIdentifier","verificationMethodIdentifierToMethod","params","targetDevice","res","uint8Array","scan","RustSdkCryptoJs.QrCodeScan","innerVerifier","_this$inner$cancelInf","_this$inner$cancelInf2","cancelInfo","BaseRustVerifer","_weakThis$deref2","QrState","_verificationRequest","_this1","emoji","decimal","sas","_confirm","requests","confirm","_weakThis$deref3","RustSdkCryptoJs.VerificationMethod","meth","isVerificationEvent","MsgType","RustBackupManager","info","signatureVerification","backupKeys","decryptionKey","backupMatchesSavedPrivateKey","force","secret","_latestBackupInfo","latestBackupInfo","backupDecryptionKey","RustSdkCryptoJs.BackupDecryptionKey","privateKeyMatches","version","jsonKeys","progress","total","_opts$progressCallbac","importOpt","ImportRoomKeyStage","backupVersion","keysByRoom","roomId","RustSdkCryptoJs.RoomId","failures","_opts$progressCallbac2","backupInfo","activeVersion","trustInfo","_this10","_this11","maxDelay","delay","numFailures","remainingToUploadCount","isFirstIteration","keyCount","keysCountInBatch","MatrixError","errCode","waitTime","batch","countKeysInBackup","_this12","requestKeyBackupVersion","signObject","_this13","randomKey","pubKey","authData","ClientPrefix","_this14","_yield$_this14$reques","_yield$_this14$reques2","current","_yield$_this14$reques3","_yield$_this14$reques4","_this15","RustBackupDecryptor","backupDecryptor","_this16","keyBackup","_this17","_opts$progressCallbac3","CHUNK_SIZE","totalKeyCount","totalImported","totalFailures","handleChunkCallback","roomChunks","_opts$progressCallbac4","currentChunk","_loop","decryptedSessions","session","groupChunkCount","chunkGroupByRoom","roomData","sessionId","sessionsForRoom","_info$auth_data","ciphertexts","_this18","sessionData","decrypted","_requestKeyBackupVersion","decryptionKeyMatchesKeyBackupInfo","keyBackupInfo","count","sessions","OutgoingRequestsManager","loopTickResolvers","successes","_ret","KEY_BACKUP_BACKOFF","KeyDownloadErrorCode","KeyDownloadError","code","KeyDownloadRateLimitError","retryMillis","PerSessionKeyBackupDownloader","backupManager","configuration","megolmSessionId","now","sid","ts","lastCheck","targetRoomId","targetSessionId","_e$getRetryAfterMs","sessionInfo","data","sessionsToImport","k","_currentServerVersion","_currentServerVersion2","_currentServerVersion4","currentServerVersion","_currentServerVersion3","keyFromAuthData","ALL_VERIFICATION_METHODS","RustCrypto","_deviceId","cryptoCallbacks","enableEncryptedStateEvents","AllDevicesIsolationMode","EventDecryptor","ClientStoppedError","_v","_room","encryptor","privKey","encodeBase64","inviter","bundleData","url","getHttpUriForMxc","encryptedBundle","bundleUrl","versions","RustSdkCryptoJs.getVersions","isolationMode","roomSettings","_this$roomEncryptors$","raw","downloadUncached","rustTrackedUsers","rustTrackedUser","userIdentity","_keyResult$master_key","keyResult","userIds","_arguments2","deviceMapByUserId","trackedUsers","rustUserId","untrackedUsers","_userId","queryResult","userDevices","deviceArray","d","queryBody","user","val","_arguments3","RustSdkCryptoJs.LocalTrust","outgoingRequest","DeviceVerificationStatus","UserVerificationStatus","wasVerified","needsUserApproval","RustSdkCryptoJs.OtherUserIdentity","_this19","RustSdkCryptoJs.OwnUserIdentity","_this20","_this21","privateKeysCachedLocally","hasKeysInCache","identity","_arguments4","_this22","CrossSigningKey","crossSigningStatus","privateKeysOnDevice","parsedKey","_this23","_this24","_this25","secretsToCheck","keyBackupEnabled","secretStored","_arguments5","_this26","createSecretStorageKey","setupNewSecretStorage","setupNewKeyBackup","isNewSecretStorageKeyNeeded","recoveryKey","crossSigningPrivateKeys","hasPrivateKeys","_this27","backupKeyBase64","secretStorageKey","_this28","_secretStorageKey$key","_secretStorageKey$key2","_this28$cryptoCallbac","_this28$cryptoCallbac2","secretStorageKeyObject","SECRET_STORAGE_ALGORITHM_V1_AES","_this29","secretStorageKeyTuple","keyInfo","_this30","publicKeysOnDevice","password","_this31","secureRandomString","_this32","_request$roomId","_this33","methods","verCont","verContObj","verificationEventContent","eventId","RustSdkCryptoJs.EventId","_this34","txId","_this35","_this36","_this37","_this38","base64Key","_this39","backupKey","_this40","_this41","_this42","_this43","_this44","_this45","_this46","obj","_this47","sigs","unsigned","userSignatures","canonalizedJson","anotherjson","map","_this48","privateKey","_this49","decodedDecryptionKey","_this50","_arguments6","_this51","secrets","_this52","secretsBundle","RustSdkCryptoJs.SecretsBundle","_this53","eventType","devices","payload","_this54","uniqueUsers","_ref4","_ref3","encryptedPayload","_this55","_this56","_this57","bundle","uploadResponse","RustSdkCryptoJs.CollectStrategy","_req","_ref5","_this58","events","oneTimeKeysCounts","unusedFallbackKeys","RustSdkCryptoJs.DeviceLists","_this59","processed","received","parsedMessage","sender","transactionId","RustSdkCryptoJs.ProcessedToDeviceEventType","_encryptionInfo$sende","encryptionInfo","isRoomKeyBundleMessage","success","_this60","mapOneTimeKeysCount","setUnusedFallbackKeys","deviceLists","_this61","_deviceLists$changed","_deviceLists$left","_this62","settings","RustSdkCryptoJs.RoomSettings","existingEncryptor","syncState","_this63","oldMembership","enc","_this64","_this65","pendingList","_loop2","ev","_e","withheld","_this66","_this67","newVerification","_this68","name","_this69","_this70","pendingValues","_this71","processEvent","_ref6","evt","TIMEOUT_DELAY","timeoutId","MatrixEventEvent","onDecrypted","decryptedEvent","_this72","senderId","isRoomVerificationRequest","_this73","perSessionBackupDownloader","MapWithDefault","_this74","trustRequirement","RustSdkCryptoJs.TrustRequirement","_res$forwarder","stringifyEvent","RustSdkCryptoJs.DecryptionSettings","RustSdkCryptoJs.MegolmDecryptionError","DecryptionError","DecryptionFailureCode","serverBackupInfo","errorDetails","RustSdkCryptoJs.DecryptionErrorCode","membership","failureCode","_this75","EventShieldColour","rustEncryptionInfoToJsEncryptionInfo","roomPendingEvents","sessionPendingEvents","shieldState","shieldColour","RustSdkCryptoJs.ShieldColor","shieldReason","RustSdkCryptoJs.ShieldStateCode","EventShieldReason","migrateFromLegacyCrypto","_migrateFromLegacyCrypto","args","_args$legacyMigration2","legacyStore","RustSdkCryptoJs.initAsync","accountPickle","IndexedDBCryptoStore","txn","acctPickle","migrationState","MigrationState","nOlmSessions","countOlmSessions","nMegolmSessions","countMegolmSessions","totalSteps","stepsDone","onProgress","steps","_args$legacyMigration","pickleKey","migrateBaseData","migrateOlmSessions","migrateMegolmSessions","_x4","_x5","_x6","_x7","_x8","_migrateBaseData","storeHandle","migrationData","RustSdkCryptoJs.BaseMigrationData","a","getAndDecryptCachedSecretKey","backupCallDone","_backupInfo$auth_data","publicKey","isValid","RustSdkCryptoJs.Migration","_x9","_x0","_countOlmSessions","nSessions","_x1","_x10","_countMegolmSessions","_x11","_x12","_x13","_x14","_x15","_migrateOlmSessions","onBatchDone","pickledSession","RustSdkCryptoJs.PickledSession","_x16","_x17","_x18","_x19","_x20","_migrateMegolmSessions","_sessionData$keysClai","RustSdkCryptoJs.PickledInboundGroupSession","migrateRoomSettingsFromLegacyCrypto","_x21","_migrateRoomSettingsFromLegacyCrypto","rooms","legacySettings","rustSettings","_x22","_x23","_x24","_getAndDecryptCachedSecretKey","legacyPickleKey","resolve","decryptAESSecretStorageItem","migrateLegacyLocalTrustIfNeeded","_x25","_migrateLegacyLocalTrustIfNeeded","legacyCryptoStore","rustCrypto","rustOwnIdentity","legacyLocallyTrustedMSK","getLegacyTrustedPublicMasterKeyBase64","mskInfo","rustSeenMSK","_x26","_getLegacyTrustedPublicMasterKeyBase","maybeTrustedKeys","msk","initRustCrypto","_initRustCrypto","StoreHandle","initOlmMachine","_initOlmMachine","RustSdkCryptoJs.OlmMachine","_value","initialKeyQueryDone"],"mappings":"8vBAqBO,IAAIA,GAAwC,SAAUA,EAA0B,CAMrF,OAAAA,EAAyB,OAAY,SAC9BA,CACT,GAAE,EAAE,EASOC,GAAiC,SAAUA,EAAmB,CAEvE,OAAAA,EAAkBA,EAAkB,OAAY,CAAC,EAAI,SAErDA,EAAkBA,EAAkB,UAAe,CAAC,EAA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