@unwanted/matrix-sdk-mini 34.12.0-2 → 34.12.0-3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (467) hide show
  1. package/git-revision.txt +1 -1
  2. package/lib/@types/global.d.js +0 -2
  3. package/lib/@types/global.d.js.map +1 -1
  4. package/lib/browser-index.d.ts.map +1 -1
  5. package/lib/browser-index.js +0 -11
  6. package/lib/browser-index.js.map +1 -1
  7. package/lib/client.d.ts +2 -1176
  8. package/lib/client.d.ts.map +1 -1
  9. package/lib/client.js +346 -2717
  10. package/lib/client.js.map +1 -1
  11. package/lib/embedded.d.ts +0 -22
  12. package/lib/embedded.d.ts.map +1 -1
  13. package/lib/embedded.js +24 -166
  14. package/lib/embedded.js.map +1 -1
  15. package/lib/event-mapper.d.ts.map +1 -1
  16. package/lib/event-mapper.js +0 -4
  17. package/lib/event-mapper.js.map +1 -1
  18. package/lib/matrix.d.ts +0 -19
  19. package/lib/matrix.d.ts.map +1 -1
  20. package/lib/matrix.js +1 -26
  21. package/lib/matrix.js.map +1 -1
  22. package/lib/models/MSC3089Branch.d.ts.map +1 -1
  23. package/lib/models/MSC3089Branch.js +0 -3
  24. package/lib/models/MSC3089Branch.js.map +1 -1
  25. package/lib/models/event.d.ts +0 -94
  26. package/lib/models/event.d.ts.map +1 -1
  27. package/lib/models/event.js +0 -274
  28. package/lib/models/event.js.map +1 -1
  29. package/lib/models/poll.d.ts.map +1 -1
  30. package/lib/models/poll.js +1 -5
  31. package/lib/models/poll.js.map +1 -1
  32. package/lib/models/relations-container.d.ts.map +1 -1
  33. package/lib/models/relations-container.js +1 -7
  34. package/lib/models/relations-container.js.map +1 -1
  35. package/lib/models/relations.d.ts +0 -1
  36. package/lib/models/relations.d.ts.map +1 -1
  37. package/lib/models/relations.js +0 -8
  38. package/lib/models/relations.js.map +1 -1
  39. package/lib/models/room-state.d.ts.map +1 -1
  40. package/lib/models/room-state.js +10 -26
  41. package/lib/models/room-state.js.map +1 -1
  42. package/lib/models/room.d.ts +0 -18
  43. package/lib/models/room.d.ts.map +1 -1
  44. package/lib/models/room.js +94 -148
  45. package/lib/models/room.js.map +1 -1
  46. package/lib/models/thread.d.ts.map +1 -1
  47. package/lib/models/thread.js +0 -1
  48. package/lib/models/thread.js.map +1 -1
  49. package/lib/sliding-sync-sdk.d.ts +2 -3
  50. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  51. package/lib/sliding-sync-sdk.js +41 -90
  52. package/lib/sliding-sync-sdk.js.map +1 -1
  53. package/lib/sync.d.ts +0 -12
  54. package/lib/sync.d.ts.map +1 -1
  55. package/lib/sync.js +1 -73
  56. package/lib/sync.js.map +1 -1
  57. package/lib/testing.d.ts +0 -48
  58. package/lib/testing.d.ts.map +1 -1
  59. package/lib/testing.js +0 -105
  60. package/lib/testing.js.map +1 -1
  61. package/package.json +1 -3
  62. package/src/@types/global.d.ts +0 -3
  63. package/src/browser-index.ts +0 -11
  64. package/src/client.ts +57 -2732
  65. package/src/embedded.ts +3 -130
  66. package/src/event-mapper.ts +0 -4
  67. package/src/matrix.ts +0 -28
  68. package/src/models/MSC3089Branch.ts +0 -3
  69. package/src/models/event.ts +0 -289
  70. package/src/models/poll.ts +0 -6
  71. package/src/models/relations-container.ts +1 -8
  72. package/src/models/relations.ts +0 -8
  73. package/src/models/room-state.ts +2 -8
  74. package/src/models/room.ts +0 -62
  75. package/src/models/thread.ts +0 -1
  76. package/src/sliding-sync-sdk.ts +2 -72
  77. package/src/sync.ts +1 -98
  78. package/src/testing.ts +0 -108
  79. package/lib/@types/crypto.d.ts +0 -47
  80. package/lib/@types/crypto.d.ts.map +0 -1
  81. package/lib/@types/crypto.js +0 -1
  82. package/lib/@types/crypto.js.map +0 -1
  83. package/lib/@types/matrix-sdk-crypto-wasm.d.js +0 -1
  84. package/lib/@types/matrix-sdk-crypto-wasm.d.js.map +0 -1
  85. package/lib/common-crypto/CryptoBackend.d.ts +0 -240
  86. package/lib/common-crypto/CryptoBackend.d.ts.map +0 -1
  87. package/lib/common-crypto/CryptoBackend.js +0 -73
  88. package/lib/common-crypto/CryptoBackend.js.map +0 -1
  89. package/lib/common-crypto/key-passphrase.d.ts +0 -14
  90. package/lib/common-crypto/key-passphrase.d.ts.map +0 -1
  91. package/lib/common-crypto/key-passphrase.js +0 -33
  92. package/lib/common-crypto/key-passphrase.js.map +0 -1
  93. package/lib/crypto/CrossSigning.d.ts +0 -184
  94. package/lib/crypto/CrossSigning.d.ts.map +0 -1
  95. package/lib/crypto/CrossSigning.js +0 -718
  96. package/lib/crypto/CrossSigning.js.map +0 -1
  97. package/lib/crypto/DeviceList.d.ts +0 -216
  98. package/lib/crypto/DeviceList.d.ts.map +0 -1
  99. package/lib/crypto/DeviceList.js +0 -892
  100. package/lib/crypto/DeviceList.js.map +0 -1
  101. package/lib/crypto/EncryptionSetup.d.ts +0 -152
  102. package/lib/crypto/EncryptionSetup.d.ts.map +0 -1
  103. package/lib/crypto/EncryptionSetup.js +0 -356
  104. package/lib/crypto/EncryptionSetup.js.map +0 -1
  105. package/lib/crypto/OlmDevice.d.ts +0 -457
  106. package/lib/crypto/OlmDevice.d.ts.map +0 -1
  107. package/lib/crypto/OlmDevice.js +0 -1241
  108. package/lib/crypto/OlmDevice.js.map +0 -1
  109. package/lib/crypto/OutgoingRoomKeyRequestManager.d.ts +0 -109
  110. package/lib/crypto/OutgoingRoomKeyRequestManager.d.ts.map +0 -1
  111. package/lib/crypto/OutgoingRoomKeyRequestManager.js +0 -415
  112. package/lib/crypto/OutgoingRoomKeyRequestManager.js.map +0 -1
  113. package/lib/crypto/RoomList.d.ts +0 -26
  114. package/lib/crypto/RoomList.d.ts.map +0 -1
  115. package/lib/crypto/RoomList.js +0 -71
  116. package/lib/crypto/RoomList.js.map +0 -1
  117. package/lib/crypto/SecretSharing.d.ts +0 -24
  118. package/lib/crypto/SecretSharing.d.ts.map +0 -1
  119. package/lib/crypto/SecretSharing.js +0 -194
  120. package/lib/crypto/SecretSharing.js.map +0 -1
  121. package/lib/crypto/SecretStorage.d.ts +0 -55
  122. package/lib/crypto/SecretStorage.d.ts.map +0 -1
  123. package/lib/crypto/SecretStorage.js +0 -118
  124. package/lib/crypto/SecretStorage.js.map +0 -1
  125. package/lib/crypto/aes.d.ts +0 -6
  126. package/lib/crypto/aes.d.ts.map +0 -1
  127. package/lib/crypto/aes.js +0 -24
  128. package/lib/crypto/aes.js.map +0 -1
  129. package/lib/crypto/algorithms/base.d.ts +0 -156
  130. package/lib/crypto/algorithms/base.d.ts.map +0 -1
  131. package/lib/crypto/algorithms/base.js +0 -187
  132. package/lib/crypto/algorithms/base.js.map +0 -1
  133. package/lib/crypto/algorithms/index.d.ts +0 -4
  134. package/lib/crypto/algorithms/index.d.ts.map +0 -1
  135. package/lib/crypto/algorithms/index.js +0 -20
  136. package/lib/crypto/algorithms/index.js.map +0 -1
  137. package/lib/crypto/algorithms/megolm.d.ts +0 -385
  138. package/lib/crypto/algorithms/megolm.d.ts.map +0 -1
  139. package/lib/crypto/algorithms/megolm.js +0 -1822
  140. package/lib/crypto/algorithms/megolm.js.map +0 -1
  141. package/lib/crypto/algorithms/olm.d.ts +0 -5
  142. package/lib/crypto/algorithms/olm.d.ts.map +0 -1
  143. package/lib/crypto/algorithms/olm.js +0 -299
  144. package/lib/crypto/algorithms/olm.js.map +0 -1
  145. package/lib/crypto/api.d.ts +0 -32
  146. package/lib/crypto/api.d.ts.map +0 -1
  147. package/lib/crypto/api.js +0 -22
  148. package/lib/crypto/api.js.map +0 -1
  149. package/lib/crypto/backup.d.ts +0 -227
  150. package/lib/crypto/backup.d.ts.map +0 -1
  151. package/lib/crypto/backup.js +0 -824
  152. package/lib/crypto/backup.js.map +0 -1
  153. package/lib/crypto/crypto.d.ts +0 -3
  154. package/lib/crypto/crypto.d.ts.map +0 -1
  155. package/lib/crypto/crypto.js +0 -19
  156. package/lib/crypto/crypto.js.map +0 -1
  157. package/lib/crypto/dehydration.d.ts +0 -34
  158. package/lib/crypto/dehydration.d.ts.map +0 -1
  159. package/lib/crypto/dehydration.js +0 -252
  160. package/lib/crypto/dehydration.js.map +0 -1
  161. package/lib/crypto/device-converter.d.ts +0 -9
  162. package/lib/crypto/device-converter.d.ts.map +0 -1
  163. package/lib/crypto/device-converter.js +0 -42
  164. package/lib/crypto/device-converter.js.map +0 -1
  165. package/lib/crypto/deviceinfo.d.ts +0 -99
  166. package/lib/crypto/deviceinfo.d.ts.map +0 -1
  167. package/lib/crypto/deviceinfo.js +0 -148
  168. package/lib/crypto/deviceinfo.js.map +0 -1
  169. package/lib/crypto/index.d.ts +0 -1209
  170. package/lib/crypto/index.d.ts.map +0 -1
  171. package/lib/crypto/index.js +0 -4097
  172. package/lib/crypto/index.js.map +0 -1
  173. package/lib/crypto/key_passphrase.d.ts +0 -14
  174. package/lib/crypto/key_passphrase.d.ts.map +0 -1
  175. package/lib/crypto/key_passphrase.js +0 -44
  176. package/lib/crypto/key_passphrase.js.map +0 -1
  177. package/lib/crypto/keybackup.d.ts +0 -18
  178. package/lib/crypto/keybackup.d.ts.map +0 -1
  179. package/lib/crypto/keybackup.js +0 -1
  180. package/lib/crypto/keybackup.js.map +0 -1
  181. package/lib/crypto/olmlib.d.ts +0 -129
  182. package/lib/crypto/olmlib.d.ts.map +0 -1
  183. package/lib/crypto/olmlib.js +0 -492
  184. package/lib/crypto/olmlib.js.map +0 -1
  185. package/lib/crypto/recoverykey.d.ts +0 -2
  186. package/lib/crypto/recoverykey.d.ts.map +0 -1
  187. package/lib/crypto/recoverykey.js +0 -19
  188. package/lib/crypto/recoverykey.js.map +0 -1
  189. package/lib/crypto/store/base.d.ts +0 -252
  190. package/lib/crypto/store/base.d.ts.map +0 -1
  191. package/lib/crypto/store/base.js +0 -64
  192. package/lib/crypto/store/base.js.map +0 -1
  193. package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts +0 -187
  194. package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts.map +0 -1
  195. package/lib/crypto/store/indexeddb-crypto-store-backend.js +0 -1145
  196. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +0 -1
  197. package/lib/crypto/store/indexeddb-crypto-store.d.ts +0 -432
  198. package/lib/crypto/store/indexeddb-crypto-store.d.ts.map +0 -1
  199. package/lib/crypto/store/indexeddb-crypto-store.js +0 -728
  200. package/lib/crypto/store/indexeddb-crypto-store.js.map +0 -1
  201. package/lib/crypto/store/localStorage-crypto-store.d.ts +0 -119
  202. package/lib/crypto/store/localStorage-crypto-store.d.ts.map +0 -1
  203. package/lib/crypto/store/localStorage-crypto-store.js +0 -531
  204. package/lib/crypto/store/localStorage-crypto-store.js.map +0 -1
  205. package/lib/crypto/store/memory-crypto-store.d.ts +0 -215
  206. package/lib/crypto/store/memory-crypto-store.d.ts.map +0 -1
  207. package/lib/crypto/store/memory-crypto-store.js +0 -622
  208. package/lib/crypto/store/memory-crypto-store.js.map +0 -1
  209. package/lib/crypto/verification/Base.d.ts +0 -105
  210. package/lib/crypto/verification/Base.d.ts.map +0 -1
  211. package/lib/crypto/verification/Base.js +0 -372
  212. package/lib/crypto/verification/Base.js.map +0 -1
  213. package/lib/crypto/verification/Error.d.ts +0 -35
  214. package/lib/crypto/verification/Error.d.ts.map +0 -1
  215. package/lib/crypto/verification/Error.js +0 -86
  216. package/lib/crypto/verification/Error.js.map +0 -1
  217. package/lib/crypto/verification/IllegalMethod.d.ts +0 -15
  218. package/lib/crypto/verification/IllegalMethod.d.ts.map +0 -1
  219. package/lib/crypto/verification/IllegalMethod.js +0 -43
  220. package/lib/crypto/verification/IllegalMethod.js.map +0 -1
  221. package/lib/crypto/verification/QRCode.d.ts +0 -51
  222. package/lib/crypto/verification/QRCode.d.ts.map +0 -1
  223. package/lib/crypto/verification/QRCode.js +0 -277
  224. package/lib/crypto/verification/QRCode.js.map +0 -1
  225. package/lib/crypto/verification/SAS.d.ts +0 -27
  226. package/lib/crypto/verification/SAS.d.ts.map +0 -1
  227. package/lib/crypto/verification/SAS.js +0 -485
  228. package/lib/crypto/verification/SAS.js.map +0 -1
  229. package/lib/crypto/verification/SASDecimal.d.ts +0 -8
  230. package/lib/crypto/verification/SASDecimal.d.ts.map +0 -1
  231. package/lib/crypto/verification/SASDecimal.js +0 -34
  232. package/lib/crypto/verification/SASDecimal.js.map +0 -1
  233. package/lib/crypto/verification/request/Channel.d.ts +0 -18
  234. package/lib/crypto/verification/request/Channel.d.ts.map +0 -1
  235. package/lib/crypto/verification/request/Channel.js +0 -1
  236. package/lib/crypto/verification/request/Channel.js.map +0 -1
  237. package/lib/crypto/verification/request/InRoomChannel.d.ts +0 -113
  238. package/lib/crypto/verification/request/InRoomChannel.d.ts.map +0 -1
  239. package/lib/crypto/verification/request/InRoomChannel.js +0 -351
  240. package/lib/crypto/verification/request/InRoomChannel.js.map +0 -1
  241. package/lib/crypto/verification/request/ToDeviceChannel.d.ts +0 -105
  242. package/lib/crypto/verification/request/ToDeviceChannel.d.ts.map +0 -1
  243. package/lib/crypto/verification/request/ToDeviceChannel.js +0 -328
  244. package/lib/crypto/verification/request/ToDeviceChannel.js.map +0 -1
  245. package/lib/crypto/verification/request/VerificationRequest.d.ts +0 -227
  246. package/lib/crypto/verification/request/VerificationRequest.d.ts.map +0 -1
  247. package/lib/crypto/verification/request/VerificationRequest.js +0 -937
  248. package/lib/crypto/verification/request/VerificationRequest.js.map +0 -1
  249. package/lib/crypto-api/CryptoEvent.d.ts +0 -69
  250. package/lib/crypto-api/CryptoEvent.d.ts.map +0 -1
  251. package/lib/crypto-api/CryptoEvent.js +0 -33
  252. package/lib/crypto-api/CryptoEvent.js.map +0 -1
  253. package/lib/crypto-api/CryptoEventHandlerMap.d.ts +0 -16
  254. package/lib/crypto-api/CryptoEventHandlerMap.d.ts.map +0 -1
  255. package/lib/crypto-api/CryptoEventHandlerMap.js +0 -22
  256. package/lib/crypto-api/CryptoEventHandlerMap.js.map +0 -1
  257. package/lib/crypto-api/index.d.ts +0 -978
  258. package/lib/crypto-api/index.d.ts.map +0 -1
  259. package/lib/crypto-api/index.js +0 -304
  260. package/lib/crypto-api/index.js.map +0 -1
  261. package/lib/crypto-api/key-passphrase.d.ts +0 -11
  262. package/lib/crypto-api/key-passphrase.d.ts.map +0 -1
  263. package/lib/crypto-api/key-passphrase.js +0 -51
  264. package/lib/crypto-api/key-passphrase.js.map +0 -1
  265. package/lib/crypto-api/keybackup.d.ts +0 -88
  266. package/lib/crypto-api/keybackup.d.ts.map +0 -1
  267. package/lib/crypto-api/keybackup.js +0 -1
  268. package/lib/crypto-api/keybackup.js.map +0 -1
  269. package/lib/crypto-api/recovery-key.d.ts +0 -11
  270. package/lib/crypto-api/recovery-key.d.ts.map +0 -1
  271. package/lib/crypto-api/recovery-key.js +0 -65
  272. package/lib/crypto-api/recovery-key.js.map +0 -1
  273. package/lib/crypto-api/verification.d.ts +0 -344
  274. package/lib/crypto-api/verification.d.ts.map +0 -1
  275. package/lib/crypto-api/verification.js +0 -91
  276. package/lib/crypto-api/verification.js.map +0 -1
  277. package/lib/rendezvous/MSC4108SignInWithQR.d.ts +0 -112
  278. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +0 -1
  279. package/lib/rendezvous/MSC4108SignInWithQR.js +0 -392
  280. package/lib/rendezvous/MSC4108SignInWithQR.js.map +0 -1
  281. package/lib/rendezvous/RendezvousChannel.d.ts +0 -27
  282. package/lib/rendezvous/RendezvousChannel.d.ts.map +0 -1
  283. package/lib/rendezvous/RendezvousChannel.js +0 -1
  284. package/lib/rendezvous/RendezvousChannel.js.map +0 -1
  285. package/lib/rendezvous/RendezvousCode.d.ts +0 -9
  286. package/lib/rendezvous/RendezvousCode.d.ts.map +0 -1
  287. package/lib/rendezvous/RendezvousCode.js +0 -1
  288. package/lib/rendezvous/RendezvousCode.js.map +0 -1
  289. package/lib/rendezvous/RendezvousError.d.ts +0 -6
  290. package/lib/rendezvous/RendezvousError.d.ts.map +0 -1
  291. package/lib/rendezvous/RendezvousError.js +0 -23
  292. package/lib/rendezvous/RendezvousError.js.map +0 -1
  293. package/lib/rendezvous/RendezvousFailureReason.d.ts +0 -31
  294. package/lib/rendezvous/RendezvousFailureReason.d.ts.map +0 -1
  295. package/lib/rendezvous/RendezvousFailureReason.js +0 -38
  296. package/lib/rendezvous/RendezvousFailureReason.js.map +0 -1
  297. package/lib/rendezvous/RendezvousIntent.d.ts +0 -5
  298. package/lib/rendezvous/RendezvousIntent.d.ts.map +0 -1
  299. package/lib/rendezvous/RendezvousIntent.js +0 -22
  300. package/lib/rendezvous/RendezvousIntent.js.map +0 -1
  301. package/lib/rendezvous/RendezvousTransport.d.ts +0 -36
  302. package/lib/rendezvous/RendezvousTransport.d.ts.map +0 -1
  303. package/lib/rendezvous/RendezvousTransport.js +0 -1
  304. package/lib/rendezvous/RendezvousTransport.js.map +0 -1
  305. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts +0 -58
  306. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts.map +0 -1
  307. package/lib/rendezvous/channels/MSC4108SecureChannel.js +0 -246
  308. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +0 -1
  309. package/lib/rendezvous/channels/index.d.ts +0 -2
  310. package/lib/rendezvous/channels/index.d.ts.map +0 -1
  311. package/lib/rendezvous/channels/index.js +0 -18
  312. package/lib/rendezvous/channels/index.js.map +0 -1
  313. package/lib/rendezvous/index.d.ts +0 -10
  314. package/lib/rendezvous/index.d.ts.map +0 -1
  315. package/lib/rendezvous/index.js +0 -23
  316. package/lib/rendezvous/index.js.map +0 -1
  317. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +0 -61
  318. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +0 -1
  319. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +0 -253
  320. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +0 -1
  321. package/lib/rendezvous/transports/index.d.ts +0 -2
  322. package/lib/rendezvous/transports/index.d.ts.map +0 -1
  323. package/lib/rendezvous/transports/index.js +0 -18
  324. package/lib/rendezvous/transports/index.js.map +0 -1
  325. package/lib/rust-crypto/CrossSigningIdentity.d.ts +0 -33
  326. package/lib/rust-crypto/CrossSigningIdentity.d.ts.map +0 -1
  327. package/lib/rust-crypto/CrossSigningIdentity.js +0 -157
  328. package/lib/rust-crypto/CrossSigningIdentity.js.map +0 -1
  329. package/lib/rust-crypto/DehydratedDeviceManager.d.ts +0 -98
  330. package/lib/rust-crypto/DehydratedDeviceManager.d.ts.map +0 -1
  331. package/lib/rust-crypto/DehydratedDeviceManager.js +0 -285
  332. package/lib/rust-crypto/DehydratedDeviceManager.js.map +0 -1
  333. package/lib/rust-crypto/KeyClaimManager.d.ts +0 -33
  334. package/lib/rust-crypto/KeyClaimManager.d.ts.map +0 -1
  335. package/lib/rust-crypto/KeyClaimManager.js +0 -82
  336. package/lib/rust-crypto/KeyClaimManager.js.map +0 -1
  337. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts +0 -43
  338. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +0 -1
  339. package/lib/rust-crypto/OutgoingRequestProcessor.js +0 -195
  340. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +0 -1
  341. package/lib/rust-crypto/OutgoingRequestsManager.d.ts +0 -47
  342. package/lib/rust-crypto/OutgoingRequestsManager.d.ts.map +0 -1
  343. package/lib/rust-crypto/OutgoingRequestsManager.js +0 -148
  344. package/lib/rust-crypto/OutgoingRequestsManager.js.map +0 -1
  345. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +0 -120
  346. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts.map +0 -1
  347. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +0 -467
  348. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +0 -1
  349. package/lib/rust-crypto/RoomEncryptor.d.ts +0 -98
  350. package/lib/rust-crypto/RoomEncryptor.d.ts.map +0 -1
  351. package/lib/rust-crypto/RoomEncryptor.js +0 -299
  352. package/lib/rust-crypto/RoomEncryptor.js.map +0 -1
  353. package/lib/rust-crypto/backup.d.ts +0 -254
  354. package/lib/rust-crypto/backup.d.ts.map +0 -1
  355. package/lib/rust-crypto/backup.js +0 -837
  356. package/lib/rust-crypto/backup.js.map +0 -1
  357. package/lib/rust-crypto/constants.d.ts +0 -3
  358. package/lib/rust-crypto/constants.d.ts.map +0 -1
  359. package/lib/rust-crypto/constants.js +0 -19
  360. package/lib/rust-crypto/constants.js.map +0 -1
  361. package/lib/rust-crypto/device-converter.d.ts +0 -28
  362. package/lib/rust-crypto/device-converter.d.ts.map +0 -1
  363. package/lib/rust-crypto/device-converter.js +0 -123
  364. package/lib/rust-crypto/device-converter.js.map +0 -1
  365. package/lib/rust-crypto/index.d.ts +0 -61
  366. package/lib/rust-crypto/index.d.ts.map +0 -1
  367. package/lib/rust-crypto/index.js +0 -152
  368. package/lib/rust-crypto/index.js.map +0 -1
  369. package/lib/rust-crypto/libolm_migration.d.ts +0 -81
  370. package/lib/rust-crypto/libolm_migration.d.ts.map +0 -1
  371. package/lib/rust-crypto/libolm_migration.js +0 -459
  372. package/lib/rust-crypto/libolm_migration.js.map +0 -1
  373. package/lib/rust-crypto/rust-crypto.d.ts +0 -556
  374. package/lib/rust-crypto/rust-crypto.d.ts.map +0 -1
  375. package/lib/rust-crypto/rust-crypto.js +0 -2016
  376. package/lib/rust-crypto/rust-crypto.js.map +0 -1
  377. package/lib/rust-crypto/secret-storage.d.ts +0 -22
  378. package/lib/rust-crypto/secret-storage.d.ts.map +0 -1
  379. package/lib/rust-crypto/secret-storage.js +0 -63
  380. package/lib/rust-crypto/secret-storage.js.map +0 -1
  381. package/lib/rust-crypto/verification.d.ts +0 -319
  382. package/lib/rust-crypto/verification.d.ts.map +0 -1
  383. package/lib/rust-crypto/verification.js +0 -816
  384. package/lib/rust-crypto/verification.js.map +0 -1
  385. package/lib/secret-storage.d.ts +0 -370
  386. package/lib/secret-storage.d.ts.map +0 -1
  387. package/lib/secret-storage.js +0 -466
  388. package/lib/secret-storage.js.map +0 -1
  389. package/src/@types/crypto.ts +0 -73
  390. package/src/@types/matrix-sdk-crypto-wasm.d.ts +0 -44
  391. package/src/common-crypto/CryptoBackend.ts +0 -302
  392. package/src/common-crypto/README.md +0 -4
  393. package/src/common-crypto/key-passphrase.ts +0 -43
  394. package/src/crypto/CrossSigning.ts +0 -773
  395. package/src/crypto/DeviceList.ts +0 -989
  396. package/src/crypto/EncryptionSetup.ts +0 -351
  397. package/src/crypto/OlmDevice.ts +0 -1500
  398. package/src/crypto/OutgoingRoomKeyRequestManager.ts +0 -485
  399. package/src/crypto/RoomList.ts +0 -70
  400. package/src/crypto/SecretSharing.ts +0 -240
  401. package/src/crypto/SecretStorage.ts +0 -136
  402. package/src/crypto/aes.ts +0 -23
  403. package/src/crypto/algorithms/base.ts +0 -236
  404. package/src/crypto/algorithms/index.ts +0 -20
  405. package/src/crypto/algorithms/megolm.ts +0 -2216
  406. package/src/crypto/algorithms/olm.ts +0 -381
  407. package/src/crypto/api.ts +0 -70
  408. package/src/crypto/backup.ts +0 -922
  409. package/src/crypto/crypto.ts +0 -18
  410. package/src/crypto/dehydration.ts +0 -272
  411. package/src/crypto/device-converter.ts +0 -45
  412. package/src/crypto/deviceinfo.ts +0 -158
  413. package/src/crypto/index.ts +0 -4414
  414. package/src/crypto/key_passphrase.ts +0 -42
  415. package/src/crypto/keybackup.ts +0 -47
  416. package/src/crypto/olmlib.ts +0 -539
  417. package/src/crypto/recoverykey.ts +0 -18
  418. package/src/crypto/store/base.ts +0 -348
  419. package/src/crypto/store/indexeddb-crypto-store-backend.ts +0 -1250
  420. package/src/crypto/store/indexeddb-crypto-store.ts +0 -845
  421. package/src/crypto/store/localStorage-crypto-store.ts +0 -579
  422. package/src/crypto/store/memory-crypto-store.ts +0 -680
  423. package/src/crypto/verification/Base.ts +0 -409
  424. package/src/crypto/verification/Error.ts +0 -76
  425. package/src/crypto/verification/IllegalMethod.ts +0 -50
  426. package/src/crypto/verification/QRCode.ts +0 -310
  427. package/src/crypto/verification/SAS.ts +0 -494
  428. package/src/crypto/verification/SASDecimal.ts +0 -37
  429. package/src/crypto/verification/request/Channel.ts +0 -34
  430. package/src/crypto/verification/request/InRoomChannel.ts +0 -371
  431. package/src/crypto/verification/request/ToDeviceChannel.ts +0 -354
  432. package/src/crypto/verification/request/VerificationRequest.ts +0 -976
  433. package/src/crypto-api/CryptoEvent.ts +0 -93
  434. package/src/crypto-api/CryptoEventHandlerMap.ts +0 -32
  435. package/src/crypto-api/index.ts +0 -1175
  436. package/src/crypto-api/key-passphrase.ts +0 -58
  437. package/src/crypto-api/keybackup.ts +0 -115
  438. package/src/crypto-api/recovery-key.ts +0 -69
  439. package/src/crypto-api/verification.ts +0 -408
  440. package/src/rendezvous/MSC4108SignInWithQR.ts +0 -444
  441. package/src/rendezvous/RendezvousChannel.ts +0 -48
  442. package/src/rendezvous/RendezvousCode.ts +0 -25
  443. package/src/rendezvous/RendezvousError.ts +0 -26
  444. package/src/rendezvous/RendezvousFailureReason.ts +0 -49
  445. package/src/rendezvous/RendezvousIntent.ts +0 -20
  446. package/src/rendezvous/RendezvousTransport.ts +0 -58
  447. package/src/rendezvous/channels/MSC4108SecureChannel.ts +0 -270
  448. package/src/rendezvous/channels/index.ts +0 -17
  449. package/src/rendezvous/index.ts +0 -25
  450. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +0 -270
  451. package/src/rendezvous/transports/index.ts +0 -17
  452. package/src/rust-crypto/CrossSigningIdentity.ts +0 -183
  453. package/src/rust-crypto/DehydratedDeviceManager.ts +0 -306
  454. package/src/rust-crypto/KeyClaimManager.ts +0 -86
  455. package/src/rust-crypto/OutgoingRequestProcessor.ts +0 -236
  456. package/src/rust-crypto/OutgoingRequestsManager.ts +0 -143
  457. package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +0 -501
  458. package/src/rust-crypto/RoomEncryptor.ts +0 -352
  459. package/src/rust-crypto/backup.ts +0 -881
  460. package/src/rust-crypto/constants.ts +0 -18
  461. package/src/rust-crypto/device-converter.ts +0 -128
  462. package/src/rust-crypto/index.ts +0 -237
  463. package/src/rust-crypto/libolm_migration.ts +0 -530
  464. package/src/rust-crypto/rust-crypto.ts +0 -2205
  465. package/src/rust-crypto/secret-storage.ts +0 -60
  466. package/src/rust-crypto/verification.ts +0 -830
  467. package/src/secret-storage.ts +0 -693
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["anotherjson","v4","uuidv4","EventType","ToDeviceMessageId","TypedReEmitter","logger","OlmDevice","olmlib","DeviceList","DeviceInfo","algorithms","createCryptoStoreCacheCallbacks","CrossSigningInfo","DeviceTrustLevel","UserTrustLevel","EncryptionSetupBuilder","SecretStorage","LegacySecretStorage","CrossSigningKey","OutgoingRoomKeyRequestManager","IndexedDBCryptoStore","ReciprocateQRCode","SCAN_QR_CODE_METHOD","SHOW_QR_CODE_METHOD","SAS","SASVerification","keyFromPassphrase","VerificationRequest","InRoomChannel","InRoomRequests","ToDeviceChannel","ToDeviceRequests","IllegalMethod","KeySignatureUploadError","DehydrationManager","BackupManager","LibOlmBackupDecryptor","backupTrustInfoFromLegacyTrustInfo","RoomEvent","RoomMemberEvent","EventStatus","MatrixEvent","MatrixEventEvent","ClientEvent","MatrixClient","RoomList","TypedEventEmitter","DecryptionError","RoomStateEvent","MapWithDefault","recursiveMapToObject","calculateKeyCheck","SECRET_STORAGE_ALGORITHM_V1_AES","ServerSideSecretStorageImpl","decodeRecoveryKey","DecryptionFailureCode","encodeRecoveryKey","EventShieldColour","EventShieldReason","CryptoEvent","CryptoApiCryptoEvent","deviceInfoToDevice","ClientPrefix","MatrixError","Method","decodeBase64","encodeBase64","KnownMembership","decryptAESSecretStorageItem","encryptAESSecretStorageItem","DeviceVerification","defaultVerificationMethods","NAME","verificationMethods","RECIPROCATE_QR_CODE","MIN_FORCE_SESSION_INTERVAL_MS","FORCE_SESSION_RETRY_INTERVAL_MS","UserTrustStatusChanged","KeyBackupStatus","KeyBackupFailed","KeyBackupSessionsRemaining","KeyBackupDecryptionKeyCached","VerificationRequestReceived","WillUpdateDevices","DevicesUpdated","KeysChanged","LegacyCryptoStoreMigrationProgress","Crypto","getOlmVersion","constructor","baseApis","userId","deviceId","clientStore","cryptoStore","_this","this","_defineProperty","Map","_ref","_asyncToGenerator","newCrossSigning","deviceList","getStoredCrossSigningForUser","seenPubkey","getId","currentPubkey","crossSigningInfo","changed","checkOwnCrossSigningTrust","storeTrustedSelfKeys","emit","checkUserTrust","checkDeviceVerifications","crossSigning","updateCrossSigningVerifiedBefore","isCrossSigningVerified","setRawStoredCrossSigningForUser","toStorage","_x","apply","arguments","event","member","oldMembership","onRoomMembership","e","error","log","concat","getType","getSender","getContent","onRoomKeyEvent","onRoomKeyRequestEvent","secretStorage","onRequestReceived","onSecretReceived","onRoomKeyWithheldEvent","transaction_id","onKeyVerificationMessage","msgtype","onToDeviceBadEncrypted","isBeingDecrypted","shouldAttemptDecryption","attemptDecryption","once","Decrypted","ev","onToDeviceEvent","room","atStart","removed","liveEvent","length","undefined","validateEvent","createRequest","channel","getRoomId","handleVerificationEvent","inRoomVerificationRequests","debug","roomList","reEmitter","method","set","warn","Object","entries","backupManager","cachedKey","getSessionBackupPrivateKey","storedKey","get","fixedKey","fixBackupKey","keys","getKey","store","cryptoCallbacks","getBackupKey","Error","olmDevice","on","UserCrossSigningUpdated","onDeviceListUserCrossSigningUpdated","reEmit","supportedAlgorithms","Array","from","DECRYPTION_CLASSES","outgoingRoomKeyRequestManager","toDeviceVerificationRequests","cacheCallbacks","dehydrationManager","getCrossSigningKey","getSecretStorageKey","_ref3","type","getFromSecretStorage","_x2","init","_arguments","_this2","exportedOlmDevice","pickleKey","globalThis","Olm","fromExportedDevice","load","deviceKeys","deviceEd25519Key","deviceCurve25519Key","myDevices","getRawStoredDevicesForUser","deviceInfo","verified","VERIFIED","known","storeDevicesForUser","saveIfDirty","doTxn","STORE_ACCOUNT","txn","getCrossSigningKeys","setKeys","startTrackingDeviceList","checkAndStart","setDeviceIsolationMode","isolationMode","getVersion","olmVersionTuple","getTrustCrossSignedDevices","trustCrossSignedDevices","getCryptoTrustCrossSignedDevices","setTrustCrossSignedDevices","val","getKnownUserIds","devices","deviceTrust","checkDeviceTrust","isLocallyVerified","deviceObj","getStoredDevice","DeviceVerificationChanged","setCryptoTrustCrossSignedDevices","createRecoveryKeyFromPassphrase","password","decryption","PkDecryption","derivation","init_with_private_key","key","privateKey","get_private_key","keyInfo","passphrase","algorithm","iterations","salt","encodedPrivateKey","generate_key","free","userHasCrossSigningKeys","_arguments2","_this3","downloadKeys","isCrossSigningReady","_this4","publicKeysOnDevice","privateKeysExistSomewhere","isStoredInKeyCache","isStoredInSecretStorage","isSecretStorageReady","_this5","secretStorageKeyInAccount","hasKey","privateKeysInStorage","sessionBackupInStorage","getKeyBackupEnabled","isKeyBackupKeyStored","getCrossSigningStatus","_this6","_cacheCallbacks$getCr","_cacheCallbacks$getCr2","_cacheCallbacks$getCr3","Boolean","privateKeysInSecretStorage","getCacheCallbacks","masterKey","getCrossSigningKeyCache","call","selfSigningKey","userSigningKey","privateKeysCachedLocally","bootstrapCrossSigning","_arguments3","_this7","authUploadDeviceSigningKeys","setupNewCrossSigning","delegateCryptoCallbacks","builder","accountData","crossSigningCallbacks","resetCrossSigning","_ref4","resetKeys","signObject","master","addCrossSigningKeys","device","deviceSignature","signDevice","addKeySignature","backupInfo","auth_data","addSessionBackup","privateKeysInCache","allowPrivateKeyRequests","crossSigningPrivateKeys","privateKeys","size","saveCrossSigningKeys","accountDataClientAdapter","ssssCryptoCallbacks","storeInSecretStorage","operation","buildOperation","persist","bootstrapSecretStorage","_arguments4","_this8","createSecretStorageKey","keyBackupInfo","setupNewKeyBackup","setupNewSecretStorage","getKeyBackupPassphrase","newKeyId","createSSSS","_ref6","opts","keyId","addKey","addPrivateKey","setDefaultKeyId","_x3","ensureCanCheckPassphrase","_ref7","mac","_this8$baseApis$crypt","_this8$baseApis$crypt2","iv","setAccountData","_x4","_x5","signKeyBackupWithCrossSigning","_ref8","keyBackupAuthData","_x6","oldSSSSKey","oldKeyId","oldKeyInfo","storageExists","name","backupKey","private_key_salt","private_key_iterations","bits","getCrossSigningKeysFromCache","info","prepareKeyBackupVersion","secureSecretStorage","recovery_key","data","sessionBackupKey","fixedBackupKey","decodedBackupKey","Uint8Array","addSessionBackupPrivateKeyToCache","resetKeyBackup","_this9","deleteAllKeyBackupVersions","version","http","authedRequest","Post","prefix","V3","storeSessionBackupPrivateKey","scheduleAllGroupSessionsForBackup","deleteKeyBackupVersion","_this10","addSecretStorageKey","keyID","hasSecretStorageKey","storeSecret","secret","getSecret","isSecretStored","isStored","requestSecret","request","getDefaultSecretStorageKeyId","getDefaultKeyId","setDefaultSecretStorageKeyId","k","checkSecretStorageKey","checkKey","checkSecretStoragePrivateKey","expectedPublicKey","gotPubkey","_decryption","_this11","encodedKey","Promise","resolve","getSecretStorePrivateKey","Buffer","decrypted","_this12","encryptedKey","storeSecretStorePrivateKey","loadSessionBackupPrivateKeyFromSecretStorage","getActiveSessionBackupVersion","_this13","_this13$backupManager","getKeyBackupInfo","isKeyBackupTrusted","_this14","trustInfo","checkKeyBackupAndEnable","_this15","checkResult","checkKeyBackup","checkCrossSigningPrivateKey","signing","PkSigning","init_with_seed","_signing","afterCrossSigningLocalKeyChange","_this16","signedDevice","upload","_ref9","shouldEmit","uploadKeySignatures","then","response","failures","KeySignatureUploadFailure","catch","shouldUpgradeCb","shouldUpgradeDeviceVerifications","users","upgradeInfo","checkForDeviceVerificationUpgrade","fromStorage","usersToUpgrade","setDeviceVerified","_this17","trustLevel","firstUse","isVerified","deviceIds","checkForValidDeviceSignature","map","_this18","signatures","signame","split","verifySignature","push","_unused","getCrossSigningKeyId","Master","getCrossSigningId","userCrossSigning","getUserVerificationStatus","_this19","pinCurrentUserIdentity","getDeviceVerificationStatus","_this20","checkDeviceInfoTrust","trustedLocally","trustCrossSig","checkIfOwnDeviceCrossSigned","_userCrossSigning$che","_arguments5","_this21","masterChanged","masterExistsNotLocallyCached","has","ret","_signing2","oldSelfSigningId","oldUserSigningId","selfSigningChanged","userSigningChanged","selfSigningExistsNotLocallyCached","userSigningExistsNotLocallyCached","keySignatures","_signing4","_signing6","deviceSig","assign","keysToUpload","_ref10","getBackupDecryptor","privKey","makeAlgorithm","keyMatches","reject","errcode","RESTORE_BACKUP_ERROR_BAD_KEY","importBackedUpRoomKeys","backupVersion","source","importRoomKeys","_this22","clearKeys","storeCrossSigningKeys","_this23","user_signing","includes","enableLazyLoading","lazyLoadMembers","registerEventHandlers","eventEmitter","Membership","onMembership","ToDeviceEvent","Timeline","onTimelineEvent","start","stop","getDeviceEd25519Key","getDeviceCurve25519Key","getOwnDeviceKeys","_this24","ed25519","curve25519","setGlobalBlacklistUnverifiedDevices","value","globalBlacklistUnverifiedDevices","getGlobalBlacklistUnverifiedDevices","uploadDeviceKeys","device_id","user_id","uploadKeysRequest","device_keys","getNeedsNewFallback","needsNewFallback","maybeUploadOneTimeKeys","_this25","uploadPeriod","maxKeysPerCycle","oneTimeKeyCheckInProgress","now","Date","lastOneTimeKeyCheck","maxOneTimeKeys","maxNumberOfOneTimeKeys","keyLimit","Math","floor","uploadLoop","_ref12","keyCount","keysThisLoop","min","generateOneTimeKeys","fallbackKeys","getFallbackKey","fallbackCleanup","clearTimeout","generateFallbackKey","res","uploadOneTimeKeys","one_time_key_counts","signed_curve25519","_x7","oneTimeKeyCount","stack","finally","_this26","promises","fallbackJson","fallback","oneTimeKeys","getOneTimeKeys","oneTimeJson","hasOwnProperty","all","requestBody","one_time_keys","setTimeout","forgetOldFallbackKey","markKeysAsPublished","userIds","forceDownload","getStoredDevicesForUser","getUserDeviceInfo","_arguments6","_this27","downloadUncached","deviceMapByUserId","usersWithoutDeviceInfo","_loop","_userId4","deviceInfos","deviceMap","newDeviceInfoMap","forEach","deviceInfoMap","saveDeviceList","delay","_arguments7","_this28","setDeviceVerification","crossSignDevice","_this29","_arguments8","_this30","blocked","xsk","gotKeyId","values","signUser","_ref14","_ref13","_x8","dev","verificationStatus","UNVERIFIED","BLOCKED","knownStatus","_ref16","_ref15","_x9","findVerificationRequestDMInProgress","roomId","findRequestInProgress","getVerificationRequestsToDeviceInProgress","getRequestsInProgress","requestVerificationDM","existingRequest","requestVerificationWithChannel","requestVerification","makeTransactionId","requestOwnUserVerification","requestDeviceVerification","requestsMap","_this31","transactionId","setRequestByChannel","sendRequest","racingRequest","getRequestByChannel","beginKeyVerification","getRequestBySenderAndTxnId","setRequestBySenderAndTxnId","legacyDeviceVerification","_this32","verifier","race","verify","waitFor","r","started","getOlmSessionsForUser","_this33","result","deviceKey","getIdentityKey","sessions","getSessionInfoForDevice","deviceIdKey","getEventSenderDeviceInfo","senderKey","getSenderKey","getWireContent","isKeySourceUntrusted","getDeviceByIdentityKey","claimedKey","getClaimedEd25519Key","getFingerprint","getEventEncryptionInfo","_event$getSenderKey","_this$deviceList$getD","encrypted","authenticated","sender","mismatchedSender","getEncryptionInfoForEvent","_this34","encryptionInfo","senderId","shieldColour","RED","shieldReason","MISMATCHED_SENDER_KEY","userTrust","GREY","AUTHENTICITY_NOT_GUARANTEED","NONE","eventSenderTrust","UNKNOWN_DEVICE","UNSIGNED_DEVICE","forceDiscardSession","alg","roomEncryptors","setRoomEncryption","config","inhibitDeviceQuery","_this35","getRoom","setRoomEncryptionImpl","refreshOutdatedDeviceLists","_this36","existingConfig","getRoomEncryption","JSON","stringify","existingAlg","storeConfigPromise","AlgClass","ENCRYPTION_CLASSES","crypto","membersLoaded","trackRoomDevicesImpl","onState","_state","off","Update","trackRoomDevices","_this37","trackMembers","_ref17","members","getEncryptionTargetMembers","m","promise","roomDeviceTrackingState","err","ensureOlmSessionsForUsers","force","devicesByUser","userDevices","ensureOlmSessionsForDevices","exportRoomKeys","_this38","exportedSessions","STORE_INBOUND_GROUP_SESSIONS","getAllEndToEndInboundGroupSessions","s","sess","exportInboundGroupSession","sessionId","sessionData","first_known_index","MEGOLM_ALGORITHM","exportRoomKeysAsJson","_this39","successes","total","updateProgress","_opts$progressCallbac","progressCallback","stage","room_id","getRoomDecryptor","importRoomKey","importRoomKeysAsJson","_this40","parse","countSessionsNeedingBackup","prepareToEncrypt","encryptEvent","_this41","content","mRelatesTo","elementPerfMetrics","encryptedContent","encryptMessage","makeEncrypted","decryptEvent","_this42","isRedacted","redactionEvent","_objectSpread","getUnsigned","redacted_because","redactedBecause","isEncrypted","decryptedEvent","clearEvent","unsigned","processDeviceLists","deviceLists","_this43","evalDeviceListChanges","requestRoomKey","recipients","resend","queueRoomKeyRequest","sendKeyRequestsImmediately","sendQueuedRequests","cancelRoomKeyRequest","cancelAndResendAllOutgoingKeyRequests","_this44","cancelAndResendAllOutgoingRequests","onCryptoEvent","_this45","onSyncWillProcess","syncData","_this46","oldSyncToken","stopTrackingAllDeviceLists","onSyncCompleted","_this47","_syncData$nextSyncTok","setSyncToken","nextSyncToken","catchingUp","processReceivedRoomKeyRequests","_this48","isArray","u","invalidateUserDeviceList","left","e2eUserIds","Set","getTrackedE2eUsers","stopTrackingDeviceList","_this49","getTrackedE2eRooms","getRooms","filter","myMembership","getMyMembership","Join","Invite","encryptAndSendToDevices","userDeviceInfoArr","payload","_this50","toDeviceBatch","prepareToDeviceBatch","queueToDevice","_this51","eventType","RoomMessageEncrypted","batch","_ref19","_ref18","OLM_ALGORITHM","sender_key","ciphertext","encryptMessageForDevice","_x10","msg","encryptToDeviceMessages","_this52","_ref20","_ref21","preprocessToDeviceMessages","events","toDevice","_toDevice$content","updateOneTimeKeyCount","currentCount","isFinite","TypeError","processKeyCounts","oneTimeKeysCounts","unusedFallbackKeys","checkedForBackup","code","session_id","reason","roomDecryptors","getRoomDecryptors","decryptor","retryDecryptionFromSender","canCreateRequest","getEventType","from_device","_arguments9","_this53","isLiveEvent","isSending","status","SENT","eventIdListener","statusListener","CANCELLED","LocalEventIdReplaced","Status","removeListener","getRequest","isNewRequest","setRequest","setVerificationRequest","handleEvent","initiatedByMe","invalid","observeOnly","_this54","UndecryptableToDeviceEvent","retryDecryption","forceNewSessionRetryTimeDevices","forceNewSessionRetryTime","getOrCreate","toUTCString","recordSessionProblem","sendToDevice","requestsToResend","getOutgoingSentRoomKeyRequest","keyReq","_this$clientStore$get","membership","shouldEncryptForInvitedMembers","action","req","IncomingRoomKeyRequest","receivedRoomKeyRequests","IncomingRoomKeyRequestCancellation","receivedRoomKeyRequestCancellations","_this55","processingRoomKeyRequests","requests","cancellations","processReceivedRoomKeyRequest","cancellation","processReceivedRoomKeyRequestCancellation","_this56","body","requestId","encryptor","reshareKeyWithDevice","hasKeysForKeyRequest","share","shareKeysWithDevice","RoomKeyRequest","_this57","RoomKeyRequestCancellation","decryptors","UNKNOWN_ENCRYPTION_ALGORITHM","d","obj","_this58","sigs","userSignatures","sign","isRoomEncrypted","isEncryptionEnabledInRoom","_this59","isDehydrationSupported","startDehydration","createNewKey","restoreKeyBackup","restoreKeyBackupWithPassphrase","indexOf","x","parseInt","requesting_device_id","request_id"],"sources":["../../src/crypto/index.ts"],"sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2018-2019 New Vector Ltd\nCopyright 2019-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport anotherjson from \"another-json\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport type { IDeviceKeys, IEventDecryptionResult, IMegolmSessionData, IOneTimeKey } from \"../@types/crypto.ts\";\nimport type { PkDecryption, PkSigning } from \"@matrix-org/olm\";\nimport { EventType, ToDeviceMessageId } from \"../@types/event.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport { logger } from \"../logger.ts\";\nimport { IExportedDevice, OlmDevice } from \"./OlmDevice.ts\";\nimport { IOlmDevice } from \"./algorithms/megolm.ts\";\nimport * as olmlib from \"./olmlib.ts\";\nimport { DeviceInfoMap, DeviceList } from \"./DeviceList.ts\";\nimport { DeviceInfo, IDevice } from \"./deviceinfo.ts\";\nimport type { DecryptionAlgorithm, EncryptionAlgorithm } from \"./algorithms/index.ts\";\nimport * as algorithms from \"./algorithms/index.ts\";\nimport { createCryptoStoreCacheCallbacks, CrossSigningInfo, DeviceTrustLevel, UserTrustLevel } from \"./CrossSigning.ts\";\nimport { EncryptionSetupBuilder } from \"./EncryptionSetup.ts\";\nimport { SecretStorage as LegacySecretStorage } from \"./SecretStorage.ts\";\nimport { CrossSigningKey, ICreateSecretStorageOpts, IEncryptedEventInfo, IRecoveryKey } from \"./api.ts\";\nimport { OutgoingRoomKeyRequestManager } from \"./OutgoingRoomKeyRequestManager.ts\";\nimport { IndexedDBCryptoStore } from \"./store/indexeddb-crypto-store.ts\";\nimport { VerificationBase } from \"./verification/Base.ts\";\nimport { ReciprocateQRCode, SCAN_QR_CODE_METHOD, SHOW_QR_CODE_METHOD } from \"./verification/QRCode.ts\";\nimport { SAS as SASVerification } from \"./verification/SAS.ts\";\nimport { keyFromPassphrase } from \"./key_passphrase.ts\";\nimport { VerificationRequest } from \"./verification/request/VerificationRequest.ts\";\nimport { InRoomChannel, InRoomRequests } from \"./verification/request/InRoomChannel.ts\";\nimport { Request, ToDeviceChannel, ToDeviceRequests } from \"./verification/request/ToDeviceChannel.ts\";\nimport { IllegalMethod } from \"./verification/IllegalMethod.ts\";\nimport { KeySignatureUploadError } from \"../errors.ts\";\nimport { DehydrationManager } from \"./dehydration.ts\";\nimport { BackupManager, LibOlmBackupDecryptor, backupTrustInfoFromLegacyTrustInfo } from \"./backup.ts\";\nimport { IStore } from \"../store/index.ts\";\nimport { Room, RoomEvent } from \"../models/room.ts\";\nimport { RoomMember, RoomMemberEvent } from \"../models/room-member.ts\";\nimport { EventStatus, IContent, IEvent, MatrixEvent, MatrixEventEvent } from \"../models/event.ts\";\nimport { ToDeviceBatch, ToDevicePayload } from \"../models/ToDeviceMessage.ts\";\nimport { ClientEvent, IKeysUploadResponse, ISignedKey, IUploadKeySignaturesResponse, MatrixClient } from \"../client.ts\";\nimport { IRoomEncryption, RoomList } from \"./RoomList.ts\";\nimport { IKeyBackupInfo } from \"./keybackup.ts\";\nimport { ISyncStateData } from \"../sync.ts\";\nimport { CryptoStore } from \"./store/base.ts\";\nimport { IVerificationChannel } from \"./verification/request/Channel.ts\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { IDeviceLists, ISyncResponse, IToDeviceEvent } from \"../sync-accumulator.ts\";\nimport { ISignatures } from \"../@types/signed.ts\";\nimport { IMessage } from \"./algorithms/olm.ts\";\nimport {\n BackupDecryptor,\n CryptoBackend,\n DecryptionError,\n OnSyncCompletedData,\n} from \"../common-crypto/CryptoBackend.ts\";\nimport { RoomState, RoomStateEvent } from \"../models/room-state.ts\";\nimport { MapWithDefault, recursiveMapToObject } from \"../utils.ts\";\nimport {\n AccountDataClient,\n AddSecretStorageKeyOpts,\n calculateKeyCheck,\n SECRET_STORAGE_ALGORITHM_V1_AES,\n SecretStorageKeyDescription,\n SecretStorageKeyObject,\n SecretStorageKeyTuple,\n ServerSideSecretStorageImpl,\n} from \"../secret-storage.ts\";\nimport { ISecretRequest } from \"./SecretSharing.ts\";\nimport {\n BackupTrustInfo,\n BootstrapCrossSigningOpts,\n CrossSigningKeyInfo,\n CrossSigningStatus,\n decodeRecoveryKey,\n DecryptionFailureCode,\n DeviceIsolationMode,\n DeviceVerificationStatus,\n encodeRecoveryKey,\n EventEncryptionInfo,\n EventShieldColour,\n EventShieldReason,\n ImportRoomKeysOpts,\n KeyBackupCheck,\n KeyBackupInfo,\n OwnDeviceKeys,\n CryptoEvent as CryptoApiCryptoEvent,\n CryptoEventHandlerMap as CryptoApiCryptoEventHandlerMap,\n KeyBackupRestoreResult,\n KeyBackupRestoreOpts,\n} from \"../crypto-api/index.ts\";\nimport { Device, DeviceMap } from \"../models/device.ts\";\nimport { deviceInfoToDevice } from \"./device-converter.ts\";\nimport { ClientPrefix, MatrixError, Method } from \"../http-api/index.ts\";\nimport { decodeBase64, encodeBase64 } from \"../base64.ts\";\nimport { KnownMembership } from \"../@types/membership.ts\";\nimport decryptAESSecretStorageItem from \"../utils/decryptAESSecretStorageItem.ts\";\nimport encryptAESSecretStorageItem from \"../utils/encryptAESSecretStorageItem.ts\";\nimport { AESEncryptedSecretStoragePayload } from \"../@types/AESEncryptedSecretStoragePayload.ts\";\n\n/* re-exports for backwards compatibility */\nexport type {\n BootstrapCrossSigningOpts as IBootstrapCrossSigningOpts,\n CryptoCallbacks as ICryptoCallbacks,\n} from \"../crypto-api/index.ts\";\n\nconst DeviceVerification = DeviceInfo.DeviceVerification;\n\nconst defaultVerificationMethods = {\n [ReciprocateQRCode.NAME]: ReciprocateQRCode,\n [SASVerification.NAME]: SASVerification,\n\n // These two can't be used for actual verification, but we do\n // need to be able to define them here for the verification flows\n // to start.\n [SHOW_QR_CODE_METHOD]: IllegalMethod,\n [SCAN_QR_CODE_METHOD]: IllegalMethod,\n} as const;\n\n/**\n * verification method names\n */\n// legacy export identifier\nexport const verificationMethods = {\n RECIPROCATE_QR_CODE: ReciprocateQRCode.NAME,\n SAS: SASVerification.NAME,\n} as const;\n\nexport type VerificationMethod = keyof typeof verificationMethods | string;\n\n// minimum time between attempting to unwedge an Olm session, if we succeeded\n// in creating a new session\nconst MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000; // 1 hour\n// minimum time between attempting to unwedge an Olm session, if we failed\n// to create a new session\nconst FORCE_SESSION_RETRY_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\n\ninterface IInitOpts {\n exportedOlmDevice?: IExportedDevice;\n pickleKey?: string;\n}\n\n/* eslint-disable camelcase */\ninterface IRoomKey {\n room_id: string;\n algorithm: string;\n}\n\n/**\n * The parameters of a room key request. The details of the request may\n * vary with the crypto algorithm, but the management and storage layers for\n * outgoing requests expect it to have 'room_id' and 'session_id' properties.\n */\nexport interface IRoomKeyRequestBody extends IRoomKey {\n session_id: string;\n sender_key: string;\n}\n\n/* eslint-enable camelcase */\n\ninterface IDeviceVerificationUpgrade {\n devices: DeviceInfo[];\n crossSigningInfo: CrossSigningInfo;\n}\n\nexport interface ICheckOwnCrossSigningTrustOpts {\n allowPrivateKeyRequests?: boolean;\n}\n\ninterface IUserOlmSession {\n deviceIdKey: string;\n sessions: {\n sessionId: string;\n hasReceivedMessage: boolean;\n }[];\n}\n\nexport interface IRoomKeyRequestRecipient {\n userId: string;\n deviceId: string;\n}\n\ninterface ISignableObject {\n signatures?: ISignatures;\n unsigned?: object;\n}\n\nexport interface IRequestsMap {\n getRequest(event: MatrixEvent): VerificationRequest | undefined;\n getRequestByChannel(channel: IVerificationChannel): VerificationRequest | undefined;\n setRequest(event: MatrixEvent, request: VerificationRequest): void;\n setRequestByChannel(channel: IVerificationChannel, request: VerificationRequest): void;\n}\n\n/* eslint-disable camelcase */\nexport interface IOlmEncryptedContent {\n algorithm: typeof olmlib.OLM_ALGORITHM;\n sender_key: string;\n ciphertext: Record<string, IMessage>;\n [ToDeviceMessageId]?: string;\n}\n\nexport interface IMegolmEncryptedContent {\n algorithm: typeof olmlib.MEGOLM_ALGORITHM;\n sender_key: string;\n session_id: string;\n device_id: string;\n ciphertext: string;\n [ToDeviceMessageId]?: string;\n}\n/* eslint-enable camelcase */\n\nexport type IEncryptedContent = IOlmEncryptedContent | IMegolmEncryptedContent;\n\nexport enum CryptoEvent {\n /** @deprecated Event not fired by the rust crypto */\n DeviceVerificationChanged = \"deviceVerificationChanged\",\n UserTrustStatusChanged = CryptoApiCryptoEvent.UserTrustStatusChanged,\n /** @deprecated Event not fired by the rust crypto */\n UserCrossSigningUpdated = \"userCrossSigningUpdated\",\n /** @deprecated Event not fired by the rust crypto */\n RoomKeyRequest = \"crypto.roomKeyRequest\",\n /** @deprecated Event not fired by the rust crypto */\n RoomKeyRequestCancellation = \"crypto.roomKeyRequestCancellation\",\n KeyBackupStatus = CryptoApiCryptoEvent.KeyBackupStatus,\n KeyBackupFailed = CryptoApiCryptoEvent.KeyBackupFailed,\n KeyBackupSessionsRemaining = CryptoApiCryptoEvent.KeyBackupSessionsRemaining,\n\n /**\n * Fires when a new valid backup decryption key is in cache.\n * This will happen when a secret is received from another session, from secret storage,\n * or when a new backup is created from this session.\n *\n * The payload is the version of the backup for which we have the key for.\n *\n * This event is only fired by the rust crypto backend.\n */\n KeyBackupDecryptionKeyCached = CryptoApiCryptoEvent.KeyBackupDecryptionKeyCached,\n\n /** @deprecated Event not fired by the rust crypto */\n KeySignatureUploadFailure = \"crypto.keySignatureUploadFailure\",\n /** @deprecated Use `VerificationRequestReceived`. */\n VerificationRequest = \"crypto.verification.request\",\n\n /**\n * Fires when a key verification request is received.\n *\n * The payload is a {@link Crypto.VerificationRequest}.\n */\n VerificationRequestReceived = CryptoApiCryptoEvent.VerificationRequestReceived,\n\n /** @deprecated Event not fired by the rust crypto */\n Warning = \"crypto.warning\",\n /** @deprecated Use {@link DevicesUpdated} instead when using rust crypto */\n WillUpdateDevices = CryptoApiCryptoEvent.WillUpdateDevices,\n DevicesUpdated = CryptoApiCryptoEvent.DevicesUpdated,\n KeysChanged = CryptoApiCryptoEvent.KeysChanged,\n\n /**\n * Fires when data is being migrated from legacy crypto to rust crypto.\n *\n * The payload is a pair `(progress, total)`, where `progress` is the number of steps completed so far, and\n * `total` is the total number of steps. When migration is complete, a final instance of the event is emitted, with\n * `progress === total === -1`.\n */\n LegacyCryptoStoreMigrationProgress = CryptoApiCryptoEvent.LegacyCryptoStoreMigrationProgress,\n}\n\nexport type CryptoEventHandlerMap = CryptoApiCryptoEventHandlerMap & {\n /**\n * Fires when a device is marked as verified/unverified/blocked/unblocked by\n * {@link MatrixClient#setDeviceVerified | MatrixClient.setDeviceVerified} or\n * {@link MatrixClient#setDeviceBlocked | MatrixClient.setDeviceBlocked}.\n *\n * @param userId - the owner of the verified device\n * @param deviceId - the id of the verified device\n * @param deviceInfo - updated device information\n */\n [CryptoEvent.DeviceVerificationChanged]: (userId: string, deviceId: string, deviceInfo: DeviceInfo) => void;\n /**\n * Fires when we receive a room key request\n *\n * @param request - request details\n */\n [CryptoEvent.RoomKeyRequest]: (request: IncomingRoomKeyRequest) => void;\n /**\n * Fires when we receive a room key request cancellation\n */\n [CryptoEvent.RoomKeyRequestCancellation]: (request: IncomingRoomKeyRequestCancellation) => void;\n [CryptoEvent.KeySignatureUploadFailure]: (\n failures: IUploadKeySignaturesResponse[\"failures\"],\n source: \"checkOwnCrossSigningTrust\" | \"afterCrossSigningLocalKeyChange\" | \"setDeviceVerification\",\n upload: (opts: { shouldEmit: boolean }) => Promise<void>,\n ) => void;\n /**\n * Fires when a key verification is requested.\n *\n * Deprecated: use `CryptoEvent.VerificationRequestReceived`.\n */\n [CryptoEvent.VerificationRequest]: (request: VerificationRequest<any>) => void;\n /**\n * Fires when the app may wish to warn the user about something related\n * the end-to-end crypto.\n *\n * @param type - One of the strings listed above\n */\n [CryptoEvent.Warning]: (type: string) => void;\n [CryptoEvent.UserCrossSigningUpdated]: (userId: string) => void;\n\n [CryptoEvent.LegacyCryptoStoreMigrationProgress]: (progress: number, total: number) => void;\n};\n\nexport class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap> implements CryptoBackend {\n /**\n * @returns The version of Olm.\n */\n public static getOlmVersion(): [number, number, number] {\n return OlmDevice.getOlmVersion();\n }\n\n public readonly backupManager: BackupManager;\n public readonly crossSigningInfo: CrossSigningInfo;\n public readonly olmDevice: OlmDevice;\n public readonly deviceList: DeviceList;\n public readonly dehydrationManager: DehydrationManager;\n public readonly secretStorage: LegacySecretStorage;\n\n private readonly roomList: RoomList;\n private readonly reEmitter: TypedReEmitter<CryptoEvent, CryptoEventHandlerMap>;\n private readonly verificationMethods: Map<VerificationMethod, typeof VerificationBase>;\n public readonly supportedAlgorithms: string[];\n private readonly outgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager;\n private readonly toDeviceVerificationRequests: ToDeviceRequests;\n public readonly inRoomVerificationRequests: InRoomRequests;\n\n private trustCrossSignedDevices = true;\n // the last time we did a check for the number of one-time-keys on the server.\n private lastOneTimeKeyCheck: number | null = null;\n private oneTimeKeyCheckInProgress = false;\n\n // EncryptionAlgorithm instance for each room\n private roomEncryptors = new Map<string, EncryptionAlgorithm>();\n // map from algorithm to DecryptionAlgorithm instance, for each room\n private roomDecryptors = new Map<string, Map<string, DecryptionAlgorithm>>();\n\n private deviceKeys: Record<string, string> = {}; // type: key\n\n public globalBlacklistUnverifiedDevices = false;\n public globalErrorOnUnknownDevices = true;\n\n // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations\n // we received in the current sync.\n private receivedRoomKeyRequests: IncomingRoomKeyRequest[] = [];\n private receivedRoomKeyRequestCancellations: IncomingRoomKeyRequestCancellation[] = [];\n // true if we are currently processing received room key requests\n private processingRoomKeyRequests = false;\n // controls whether device tracking is delayed\n // until calling encryptEvent or trackRoomDevices,\n // or done immediately upon enabling room encryption.\n private lazyLoadMembers = false;\n // in case lazyLoadMembers is true,\n // track if an initial tracking of all the room members\n // has happened for a given room. This is delayed\n // to avoid loading room members as long as possible.\n private roomDeviceTrackingState: { [roomId: string]: Promise<void> } = {};\n\n // The timestamp of the minimum time at which we will retry forcing establishment\n // of a new session for each device, in milliseconds.\n // {\n // userId: {\n // deviceId: 1234567890000,\n // },\n // }\n // Map: user Id → device Id → timestamp\n private forceNewSessionRetryTime: MapWithDefault<string, MapWithDefault<string, number>> = new MapWithDefault(\n () => new MapWithDefault(() => 0),\n );\n\n // This flag will be unset whilst the client processes a sync response\n // so that we don't start requesting keys until we've actually finished\n // processing the response.\n private sendKeyRequestsImmediately = false;\n\n private oneTimeKeyCount?: number;\n private needsNewFallback?: boolean;\n private fallbackCleanup?: ReturnType<typeof setTimeout>;\n\n /**\n * Cryptography bits\n *\n * This module is internal to the js-sdk; the public API is via MatrixClient.\n *\n * @internal\n *\n * @param baseApis - base matrix api interface\n *\n * @param userId - The user ID for the local user\n *\n * @param deviceId - The identifier for this device.\n *\n * @param clientStore - the MatrixClient data store.\n *\n * @param cryptoStore - storage for the crypto layer.\n *\n * @param verificationMethods - Array of verification methods to use.\n * Each element can either be a string from MatrixClient.verificationMethods\n * or a class that implements a verification method.\n */\n public constructor(\n public readonly baseApis: MatrixClient,\n public readonly userId: string,\n private readonly deviceId: string,\n private readonly clientStore: IStore,\n public readonly cryptoStore: CryptoStore,\n verificationMethods: Array<VerificationMethod | (typeof VerificationBase & { NAME: string })>,\n ) {\n super();\n\n logger.debug(\"Crypto: initialising roomlist...\");\n this.roomList = new RoomList(cryptoStore);\n\n this.reEmitter = new TypedReEmitter(this);\n\n if (verificationMethods) {\n this.verificationMethods = new Map();\n for (const method of verificationMethods) {\n if (typeof method === \"string\") {\n if (defaultVerificationMethods[method]) {\n this.verificationMethods.set(\n method,\n <typeof VerificationBase>defaultVerificationMethods[method],\n );\n }\n } else if (method[\"NAME\"]) {\n this.verificationMethods.set(method[\"NAME\"], method as typeof VerificationBase);\n } else {\n logger.warn(`Excluding unknown verification method ${method}`);\n }\n }\n } else {\n this.verificationMethods = new Map(Object.entries(defaultVerificationMethods)) as Map<\n VerificationMethod,\n typeof VerificationBase\n >;\n }\n\n this.backupManager = new BackupManager(baseApis, async () => {\n // try to get key from cache\n const cachedKey = await this.getSessionBackupPrivateKey();\n if (cachedKey) {\n return cachedKey;\n }\n\n // try to get key from secret storage\n const storedKey = await this.secretStorage.get(\"m.megolm_backup.v1\");\n\n if (storedKey) {\n // ensure that the key is in the right format. If not, fix the key and\n // store the fixed version\n const fixedKey = fixBackupKey(storedKey);\n if (fixedKey) {\n const keys = await this.secretStorage.getKey();\n await this.secretStorage.store(\"m.megolm_backup.v1\", fixedKey, [keys![0]]);\n }\n\n return decodeBase64(fixedKey || storedKey);\n }\n\n // try to get key from app\n if (this.baseApis.cryptoCallbacks && this.baseApis.cryptoCallbacks.getBackupKey) {\n return this.baseApis.cryptoCallbacks.getBackupKey();\n }\n\n throw new Error(\"Unable to get private key\");\n });\n\n this.olmDevice = new OlmDevice(cryptoStore);\n this.deviceList = new DeviceList(baseApis, cryptoStore, this.olmDevice);\n\n // XXX: This isn't removed at any point, but then none of the event listeners\n // this class sets seem to be removed at any point... :/\n this.deviceList.on(CryptoEvent.UserCrossSigningUpdated, this.onDeviceListUserCrossSigningUpdated);\n this.reEmitter.reEmit(this.deviceList, [CryptoEvent.DevicesUpdated, CryptoEvent.WillUpdateDevices]);\n\n this.supportedAlgorithms = Array.from(algorithms.DECRYPTION_CLASSES.keys());\n\n this.outgoingRoomKeyRequestManager = new OutgoingRoomKeyRequestManager(\n baseApis,\n this.deviceId,\n this.cryptoStore,\n );\n\n this.toDeviceVerificationRequests = new ToDeviceRequests();\n this.inRoomVerificationRequests = new InRoomRequests();\n\n const cryptoCallbacks = this.baseApis.cryptoCallbacks || {};\n const cacheCallbacks = createCryptoStoreCacheCallbacks(cryptoStore, this.olmDevice);\n\n this.crossSigningInfo = new CrossSigningInfo(userId, cryptoCallbacks, cacheCallbacks);\n // Yes, we pass the client twice here: see SecretStorage\n this.secretStorage = new LegacySecretStorage(baseApis as AccountDataClient, cryptoCallbacks, baseApis);\n this.dehydrationManager = new DehydrationManager(this);\n\n // Assuming no app-supplied callback, default to getting from SSSS.\n if (!cryptoCallbacks.getCrossSigningKey && cryptoCallbacks.getSecretStorageKey) {\n cryptoCallbacks.getCrossSigningKey = async (type): Promise<Uint8Array | null> => {\n return CrossSigningInfo.getFromSecretStorage(type, this.secretStorage);\n };\n }\n }\n\n /**\n * Initialise the crypto module so that it is ready for use\n *\n * Returns a promise which resolves once the crypto module is ready for use.\n *\n * @param exportedOlmDevice - (Optional) data from exported device\n * that must be re-created.\n */\n public async init({ exportedOlmDevice, pickleKey }: IInitOpts = {}): Promise<void> {\n logger.log(\"Crypto: initialising Olm...\");\n await globalThis.Olm.init();\n logger.log(\n exportedOlmDevice\n ? \"Crypto: initialising Olm device from exported device...\"\n : \"Crypto: initialising Olm device...\",\n );\n await this.olmDevice.init({ fromExportedDevice: exportedOlmDevice, pickleKey });\n logger.log(\"Crypto: loading device list...\");\n await this.deviceList.load();\n\n // build our device keys: these will later be uploaded\n this.deviceKeys[\"ed25519:\" + this.deviceId] = this.olmDevice.deviceEd25519Key!;\n this.deviceKeys[\"curve25519:\" + this.deviceId] = this.olmDevice.deviceCurve25519Key!;\n\n logger.log(\"Crypto: fetching own devices...\");\n let myDevices = this.deviceList.getRawStoredDevicesForUser(this.userId);\n\n if (!myDevices) {\n myDevices = {};\n }\n\n if (!myDevices[this.deviceId]) {\n // add our own deviceinfo to the cryptoStore\n logger.log(\"Crypto: adding this device to the store...\");\n const deviceInfo = {\n keys: this.deviceKeys,\n algorithms: this.supportedAlgorithms,\n verified: DeviceVerification.VERIFIED,\n known: true,\n };\n\n myDevices[this.deviceId] = deviceInfo;\n this.deviceList.storeDevicesForUser(this.userId, myDevices);\n this.deviceList.saveIfDirty();\n }\n\n await this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.getCrossSigningKeys(txn, (keys) => {\n // can be an empty object after resetting cross-signing keys, see storeTrustedSelfKeys\n if (keys && Object.keys(keys).length !== 0) {\n logger.log(\"Loaded cross-signing public keys from crypto store\");\n this.crossSigningInfo.setKeys(keys);\n }\n });\n });\n // make sure we are keeping track of our own devices\n // (this is important for key backups & things)\n this.deviceList.startTrackingDeviceList(this.userId);\n\n logger.debug(\"Crypto: initialising roomlist...\");\n await this.roomList.init();\n\n logger.log(\"Crypto: checking for key backup...\");\n this.backupManager.checkAndStart();\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi#setDeviceIsolationMode}.\n */\n public setDeviceIsolationMode(isolationMode: DeviceIsolationMode): void {\n throw new Error(\"Not supported\");\n }\n /**\n * Implementation of {@link Crypto.CryptoApi#getVersion}.\n */\n public getVersion(): string {\n const olmVersionTuple = Crypto.getOlmVersion();\n return `Olm ${olmVersionTuple[0]}.${olmVersionTuple[1]}.${olmVersionTuple[2]}`;\n }\n\n /**\n * Whether to trust a others users signatures of their devices.\n * If false, devices will only be considered 'verified' if we have\n * verified that device individually (effectively disabling cross-signing).\n *\n * Default: true\n *\n * @returns True if trusting cross-signed devices\n */\n public getTrustCrossSignedDevices(): boolean {\n return this.trustCrossSignedDevices;\n }\n\n /**\n * @deprecated Use {@link Crypto.CryptoApi#getTrustCrossSignedDevices}.\n */\n public getCryptoTrustCrossSignedDevices(): boolean {\n return this.trustCrossSignedDevices;\n }\n\n /**\n * See getCryptoTrustCrossSignedDevices\n *\n * @param val - True to trust cross-signed devices\n */\n public setTrustCrossSignedDevices(val: boolean): void {\n this.trustCrossSignedDevices = val;\n\n for (const userId of this.deviceList.getKnownUserIds()) {\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n for (const deviceId of Object.keys(devices)) {\n const deviceTrust = this.checkDeviceTrust(userId, deviceId);\n // If the device is locally verified then isVerified() is always true,\n // so this will only have caused the value to change if the device is\n // cross-signing verified but not locally verified\n if (!deviceTrust.isLocallyVerified() && deviceTrust.isCrossSigningVerified()) {\n const deviceObj = this.deviceList.getStoredDevice(userId, deviceId)!;\n this.emit(CryptoEvent.DeviceVerificationChanged, userId, deviceId, deviceObj);\n }\n }\n }\n }\n\n /**\n * @deprecated Use {@link Crypto.CryptoApi#setTrustCrossSignedDevices}.\n */\n public setCryptoTrustCrossSignedDevices(val: boolean): void {\n this.setTrustCrossSignedDevices(val);\n }\n\n /**\n * Create a recovery key from a user-supplied passphrase.\n *\n * @param password - Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n * @returns Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n */\n public async createRecoveryKeyFromPassphrase(password?: string): Promise<IRecoveryKey> {\n const decryption = new globalThis.Olm.PkDecryption();\n try {\n if (password) {\n const derivation = await keyFromPassphrase(password);\n\n decryption.init_with_private_key(derivation.key);\n const privateKey = decryption.get_private_key();\n return {\n keyInfo: {\n passphrase: {\n algorithm: \"m.pbkdf2\",\n iterations: derivation.iterations,\n salt: derivation.salt,\n },\n },\n privateKey: privateKey,\n encodedPrivateKey: encodeRecoveryKey(privateKey),\n };\n } else {\n decryption.generate_key();\n const privateKey = decryption.get_private_key();\n return {\n privateKey: privateKey,\n encodedPrivateKey: encodeRecoveryKey(privateKey),\n };\n }\n } finally {\n decryption?.free();\n }\n }\n\n /**\n * Checks if the user has previously published cross-signing keys\n *\n * This means downloading the devicelist for the user and checking if the list includes\n * the cross-signing pseudo-device.\n *\n * @internal\n */\n public async userHasCrossSigningKeys(userId = this.userId): Promise<boolean> {\n await this.downloadKeys([userId]);\n return this.deviceList.getStoredCrossSigningForUser(userId) !== null;\n }\n\n /**\n * Checks whether cross signing:\n * - is enabled on this account and trusted by this device\n * - has private keys either cached locally or stored in secret storage\n *\n * If this function returns false, bootstrapCrossSigning() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapCrossSigning() completes successfully, this function should\n * return true.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @returns True if cross-signing is ready to be used on this device\n */\n public async isCrossSigningReady(): Promise<boolean> {\n const publicKeysOnDevice = this.crossSigningInfo.getId();\n const privateKeysExistSomewhere =\n (await this.crossSigningInfo.isStoredInKeyCache()) ||\n (await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage));\n\n return !!(publicKeysOnDevice && privateKeysExistSomewhere);\n }\n\n /**\n * Checks whether secret storage:\n * - is enabled on this account\n * - is storing cross-signing private keys\n * - is storing session backup key (if enabled)\n *\n * If this function returns false, bootstrapSecretStorage() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapSecretStorage() completes successfully, this function should\n * return true.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @returns True if secret storage is ready to be used on this device\n */\n public async isSecretStorageReady(): Promise<boolean> {\n const secretStorageKeyInAccount = await this.secretStorage.hasKey();\n const privateKeysInStorage = await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);\n const sessionBackupInStorage =\n !this.backupManager.getKeyBackupEnabled() || (await this.baseApis.isKeyBackupKeyStored());\n\n return !!(secretStorageKeyInAccount && privateKeysInStorage && sessionBackupInStorage);\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi#getCrossSigningStatus}\n */\n public async getCrossSigningStatus(): Promise<CrossSigningStatus> {\n const publicKeysOnDevice = Boolean(this.crossSigningInfo.getId());\n const privateKeysInSecretStorage = Boolean(\n await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),\n );\n const cacheCallbacks = this.crossSigningInfo.getCacheCallbacks();\n const masterKey = Boolean(await cacheCallbacks.getCrossSigningKeyCache?.(\"master\"));\n const selfSigningKey = Boolean(await cacheCallbacks.getCrossSigningKeyCache?.(\"self_signing\"));\n const userSigningKey = Boolean(await cacheCallbacks.getCrossSigningKeyCache?.(\"user_signing\"));\n\n return {\n publicKeysOnDevice,\n privateKeysInSecretStorage,\n privateKeysCachedLocally: {\n masterKey,\n selfSigningKey,\n userSigningKey,\n },\n };\n }\n\n /**\n * Bootstrap cross-signing by creating keys if needed. If everything is already\n * set up, then no changes are made, so this is safe to run to ensure\n * cross-signing is ready for use.\n *\n * This function:\n * - creates new cross-signing keys if they are not found locally cached nor in\n * secret storage (if it has been setup)\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n */\n public async bootstrapCrossSigning({\n authUploadDeviceSigningKeys,\n setupNewCrossSigning,\n }: BootstrapCrossSigningOpts = {}): Promise<void> {\n logger.log(\"Bootstrapping cross-signing\");\n\n const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;\n const builder = new EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks);\n const crossSigningInfo = new CrossSigningInfo(\n this.userId,\n builder.crossSigningCallbacks,\n builder.crossSigningCallbacks,\n );\n\n // Reset the cross-signing keys\n const resetCrossSigning = async (): Promise<void> => {\n crossSigningInfo.resetKeys();\n // Sign master key with device key\n await this.signObject(crossSigningInfo.keys.master);\n\n // Store auth flow helper function, as we need to call it when uploading\n // to ensure we handle auth errors properly.\n builder.addCrossSigningKeys(authUploadDeviceSigningKeys, crossSigningInfo.keys);\n\n // Cross-sign own device\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId)!;\n const deviceSignature = await crossSigningInfo.signDevice(this.userId, device);\n builder.addKeySignature(this.userId, this.deviceId, deviceSignature!);\n\n // Sign message key backup with cross-signing master key\n if (this.backupManager.backupInfo) {\n await crossSigningInfo.signObject(this.backupManager.backupInfo.auth_data, \"master\");\n builder.addSessionBackup(this.backupManager.backupInfo);\n }\n };\n\n const publicKeysOnDevice = this.crossSigningInfo.getId();\n const privateKeysInCache = await this.crossSigningInfo.isStoredInKeyCache();\n const privateKeysInStorage = await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);\n const privateKeysExistSomewhere = privateKeysInCache || privateKeysInStorage;\n\n // Log all relevant state for easier parsing of debug logs.\n logger.log({\n setupNewCrossSigning,\n publicKeysOnDevice,\n privateKeysInCache,\n privateKeysInStorage,\n privateKeysExistSomewhere,\n });\n\n if (!privateKeysExistSomewhere || setupNewCrossSigning) {\n logger.log(\"Cross-signing private keys not found locally or in secret storage, \" + \"creating new keys\");\n // If a user has multiple devices, it important to only call bootstrap\n // as part of some UI flow (and not silently during startup), as they\n // may have setup cross-signing on a platform which has not saved keys\n // to secret storage, and this would reset them. In such a case, you\n // should prompt the user to verify any existing devices first (and\n // request private keys from those devices) before calling bootstrap.\n await resetCrossSigning();\n } else if (publicKeysOnDevice && privateKeysInCache) {\n logger.log(\"Cross-signing public keys trusted and private keys found locally\");\n } else if (privateKeysInStorage) {\n logger.log(\n \"Cross-signing private keys not found locally, but they are available \" +\n \"in secret storage, reading storage and caching locally\",\n );\n await this.checkOwnCrossSigningTrust({\n allowPrivateKeyRequests: true,\n });\n }\n\n // Assuming no app-supplied callback, default to storing new private keys in\n // secret storage if it exists. If it does not, it is assumed this will be\n // done as part of setting up secret storage later.\n const crossSigningPrivateKeys = builder.crossSigningCallbacks.privateKeys;\n if (crossSigningPrivateKeys.size && !this.baseApis.cryptoCallbacks.saveCrossSigningKeys) {\n const secretStorage = new ServerSideSecretStorageImpl(\n builder.accountDataClientAdapter,\n builder.ssssCryptoCallbacks,\n );\n if (await secretStorage.hasKey()) {\n logger.log(\"Storing new cross-signing private keys in secret storage\");\n // This is writing to in-memory account data in\n // builder.accountDataClientAdapter so won't fail\n await CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage);\n }\n }\n\n const operation = builder.buildOperation();\n await operation.apply(this);\n // This persists private keys and public keys as trusted,\n // only do this if apply succeeded for now as retry isn't in place yet\n await builder.persist(this);\n\n logger.log(\"Cross-signing ready\");\n }\n\n /**\n * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is\n * already set up, then no changes are made, so this is safe to run to ensure secret\n * storage is ready for use.\n *\n * This function\n * - creates a new Secure Secret Storage key if no default key exists\n * - if a key backup exists, it is migrated to store the key in the Secret\n * Storage\n * - creates a backup if none exists, and one is requested\n * - migrates Secure Secret Storage to use the latest algorithm, if an outdated\n * algorithm is found\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * Returns:\n * A promise which resolves to key creation data for\n * SecretStorage#addKey: an object with `passphrase` etc fields.\n */\n // TODO this does not resolve with what it says it does\n public async bootstrapSecretStorage({\n createSecretStorageKey = async (): Promise<IRecoveryKey> => ({}) as IRecoveryKey,\n keyBackupInfo,\n setupNewKeyBackup,\n setupNewSecretStorage,\n getKeyBackupPassphrase,\n }: ICreateSecretStorageOpts = {}): Promise<void> {\n logger.log(\"Bootstrapping Secure Secret Storage\");\n const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;\n const builder = new EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks);\n const secretStorage = new ServerSideSecretStorageImpl(\n builder.accountDataClientAdapter,\n builder.ssssCryptoCallbacks,\n );\n\n // the ID of the new SSSS key, if we create one\n let newKeyId: string | null = null;\n\n // create a new SSSS key and set it as default\n const createSSSS = async (opts: AddSecretStorageKeyOpts): Promise<string> => {\n const { keyId, keyInfo } = await secretStorage.addKey(SECRET_STORAGE_ALGORITHM_V1_AES, opts);\n\n // make the private key available to encrypt 4S secrets\n builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, opts.key);\n\n await secretStorage.setDefaultKeyId(keyId);\n return keyId;\n };\n\n const ensureCanCheckPassphrase = async (keyId: string, keyInfo: SecretStorageKeyDescription): Promise<void> => {\n if (!keyInfo.mac) {\n const key = await this.baseApis.cryptoCallbacks.getSecretStorageKey?.(\n { keys: { [keyId]: keyInfo } },\n \"\",\n );\n if (key) {\n const privateKey = key[1];\n builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);\n const { iv, mac } = await calculateKeyCheck(privateKey);\n keyInfo.iv = iv;\n keyInfo.mac = mac;\n\n await builder.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo);\n }\n }\n };\n\n const signKeyBackupWithCrossSigning = async (keyBackupAuthData: IKeyBackupInfo[\"auth_data\"]): Promise<void> => {\n if (this.crossSigningInfo.getId() && (await this.crossSigningInfo.isStoredInKeyCache(\"master\"))) {\n try {\n logger.log(\"Adding cross-signing signature to key backup\");\n await this.crossSigningInfo.signObject(keyBackupAuthData, \"master\");\n } catch (e) {\n // This step is not critical (just helpful), so we catch here\n // and continue if it fails.\n logger.error(\"Signing key backup with cross-signing keys failed\", e);\n }\n } else {\n logger.warn(\"Cross-signing keys not available, skipping signature on key backup\");\n }\n };\n\n const oldSSSSKey = await this.secretStorage.getKey();\n const [oldKeyId, oldKeyInfo] = oldSSSSKey || [null, null];\n const storageExists =\n !setupNewSecretStorage && oldKeyInfo && oldKeyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES;\n\n // Log all relevant state for easier parsing of debug logs.\n logger.log({\n keyBackupInfo,\n setupNewKeyBackup,\n setupNewSecretStorage,\n storageExists,\n oldKeyInfo,\n });\n\n if (!storageExists && !keyBackupInfo) {\n // either we don't have anything, or we've been asked to restart\n // from scratch\n logger.log(\"Secret storage does not exist, creating new storage key\");\n\n // if we already have a usable default SSSS key and aren't resetting\n // SSSS just use it. otherwise, create a new one\n // Note: we leave the old SSSS key in place: there could be other\n // secrets using it, in theory. We could move them to the new key but a)\n // that would mean we'd need to prompt for the old passphrase, and b)\n // it's not clear that would be the right thing to do anyway.\n const { keyInfo, privateKey } = await createSecretStorageKey();\n newKeyId = await createSSSS({ passphrase: keyInfo?.passphrase, key: privateKey, name: keyInfo?.name });\n } else if (!storageExists && keyBackupInfo) {\n // we have an existing backup, but no SSSS\n logger.log(\"Secret storage does not exist, using key backup key\");\n\n // if we have the backup key already cached, use it; otherwise use the\n // callback to prompt for the key\n const backupKey = (await this.getSessionBackupPrivateKey()) || (await getKeyBackupPassphrase?.());\n\n // create a new SSSS key and use the backup key as the new SSSS key\n const opts = { key: backupKey } as AddSecretStorageKeyOpts;\n\n if (keyBackupInfo.auth_data.private_key_salt && keyBackupInfo.auth_data.private_key_iterations) {\n // FIXME: ???\n opts.passphrase = {\n algorithm: \"m.pbkdf2\",\n iterations: keyBackupInfo.auth_data.private_key_iterations,\n salt: keyBackupInfo.auth_data.private_key_salt,\n bits: 256,\n };\n }\n\n newKeyId = await createSSSS(opts);\n\n // store the backup key in secret storage\n await secretStorage.store(\"m.megolm_backup.v1\", encodeBase64(backupKey!), [newKeyId]);\n\n // The backup is trusted because the user provided the private key.\n // Sign the backup with the cross-signing key so the key backup can\n // be trusted via cross-signing.\n await signKeyBackupWithCrossSigning(keyBackupInfo.auth_data);\n\n builder.addSessionBackup(keyBackupInfo);\n } else {\n // 4S is already set up\n logger.log(\"Secret storage exists\");\n\n if (oldKeyInfo && oldKeyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n // make sure that the default key has the information needed to\n // check the passphrase\n await ensureCanCheckPassphrase(oldKeyId, oldKeyInfo);\n }\n }\n\n // If we have cross-signing private keys cached, store them in secret\n // storage if they are not there already.\n if (\n !this.baseApis.cryptoCallbacks.saveCrossSigningKeys &&\n (await this.isCrossSigningReady()) &&\n (newKeyId || !(await this.crossSigningInfo.isStoredInSecretStorage(secretStorage)))\n ) {\n logger.log(\"Copying cross-signing private keys from cache to secret storage\");\n const crossSigningPrivateKeys = await this.crossSigningInfo.getCrossSigningKeysFromCache();\n // This is writing to in-memory account data in\n // builder.accountDataClientAdapter so won't fail\n await CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage);\n }\n\n if (setupNewKeyBackup && !keyBackupInfo) {\n logger.log(\"Creating new message key backup version\");\n const info = await this.baseApis.prepareKeyBackupVersion(\n null /* random key */,\n // don't write to secret storage, as it will write to this.secretStorage.\n // Here, we want to capture all the side-effects of bootstrapping,\n // and want to write to the local secretStorage object\n { secureSecretStorage: false },\n );\n // write the key to 4S\n const privateKey = decodeRecoveryKey(info.recovery_key);\n await secretStorage.store(\"m.megolm_backup.v1\", encodeBase64(privateKey));\n\n // create keyBackupInfo object to add to builder\n const data: IKeyBackupInfo = {\n algorithm: info.algorithm,\n auth_data: info.auth_data,\n };\n\n // Sign with cross-signing master key\n await signKeyBackupWithCrossSigning(data.auth_data);\n\n // sign with the device fingerprint\n await this.signObject(data.auth_data);\n\n builder.addSessionBackup(data);\n }\n\n // Cache the session backup key\n const sessionBackupKey = await secretStorage.get(\"m.megolm_backup.v1\");\n if (sessionBackupKey) {\n logger.info(\"Got session backup key from secret storage: caching\");\n // fix up the backup key if it's in the wrong format, and replace\n // in secret storage\n const fixedBackupKey = fixBackupKey(sessionBackupKey);\n if (fixedBackupKey) {\n const keyId = newKeyId || oldKeyId;\n await secretStorage.store(\"m.megolm_backup.v1\", fixedBackupKey, keyId ? [keyId] : null);\n }\n const decodedBackupKey = new Uint8Array(decodeBase64(fixedBackupKey || sessionBackupKey));\n builder.addSessionBackupPrivateKeyToCache(decodedBackupKey);\n } else if (this.backupManager.getKeyBackupEnabled()) {\n // key backup is enabled but we don't have a session backup key in SSSS: see if we have one in\n // the cache or the user can provide one, and if so, write it to SSSS\n const backupKey = (await this.getSessionBackupPrivateKey()) || (await getKeyBackupPassphrase?.());\n if (!backupKey) {\n // This will require user intervention to recover from since we don't have the key\n // backup key anywhere. The user should probably just set up a new key backup and\n // the key for the new backup will be stored. If we hit this scenario in the wild\n // with any frequency, we should do more than just log an error.\n logger.error(\"Key backup is enabled but couldn't get key backup key!\");\n return;\n }\n logger.info(\"Got session backup key from cache/user that wasn't in SSSS: saving to SSSS\");\n await secretStorage.store(\"m.megolm_backup.v1\", encodeBase64(backupKey));\n }\n\n const operation = builder.buildOperation();\n await operation.apply(this);\n // this persists private keys and public keys as trusted,\n // only do this if apply succeeded for now as retry isn't in place yet\n await builder.persist(this);\n\n logger.log(\"Secure Secret Storage ready\");\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi#resetKeyBackup}.\n */\n public async resetKeyBackup(): Promise<void> {\n // Delete existing ones\n // There is no use case for having several key backup version live server side.\n // Even if not deleted it would be lost as the key to restore is lost.\n // There should be only one backup at a time.\n await this.backupManager.deleteAllKeyBackupVersions();\n\n const info = await this.backupManager.prepareKeyBackupVersion();\n\n await this.signObject(info.auth_data);\n\n // add new key backup\n const { version } = await this.baseApis.http.authedRequest<{ version: string }>(\n Method.Post,\n \"/room_keys/version\",\n undefined,\n info,\n {\n prefix: ClientPrefix.V3,\n },\n );\n\n logger.log(`Created backup version ${version}`);\n\n // write the key to 4S\n const privateKey = info.privateKey;\n await this.secretStorage.store(\"m.megolm_backup.v1\", encodeBase64(privateKey));\n await this.storeSessionBackupPrivateKey(privateKey);\n\n await this.backupManager.checkAndStart();\n await this.backupManager.scheduleAllGroupSessionsForBackup();\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi#deleteKeyBackupVersion}.\n */\n public async deleteKeyBackupVersion(version: string): Promise<void> {\n await this.backupManager.deleteKeyBackupVersion(version);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#addKey}.\n */\n public addSecretStorageKey(\n algorithm: string,\n opts: AddSecretStorageKeyOpts,\n keyID?: string,\n ): Promise<SecretStorageKeyObject> {\n return this.secretStorage.addKey(algorithm, opts, keyID);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#hasKey}.\n */\n public hasSecretStorageKey(keyID?: string): Promise<boolean> {\n return this.secretStorage.hasKey(keyID);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#getKey}.\n */\n public getSecretStorageKey(keyID?: string): Promise<SecretStorageKeyTuple | null> {\n return this.secretStorage.getKey(keyID);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#store}.\n */\n public storeSecret(name: string, secret: string, keys?: string[]): Promise<void> {\n return this.secretStorage.store(name, secret, keys);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#get}.\n */\n public getSecret(name: string): Promise<string | undefined> {\n return this.secretStorage.get(name);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#isStored}.\n */\n public isSecretStored(name: string): Promise<Record<string, SecretStorageKeyDescription> | null> {\n return this.secretStorage.isStored(name);\n }\n\n public requestSecret(name: string, devices: string[]): ISecretRequest {\n if (!devices) {\n devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId));\n }\n return this.secretStorage.request(name, devices);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#getDefaultKeyId}.\n */\n public getDefaultSecretStorageKeyId(): Promise<string | null> {\n return this.secretStorage.getDefaultKeyId();\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#setDefaultKeyId}.\n */\n public setDefaultSecretStorageKeyId(k: string): Promise<void> {\n return this.secretStorage.setDefaultKeyId(k);\n }\n\n /**\n * @deprecated Use {@link MatrixClient#secretStorage} and {@link SecretStorage.ServerSideSecretStorage#checkKey}.\n */\n public checkSecretStorageKey(key: Uint8Array, info: SecretStorageKeyDescription): Promise<boolean> {\n return this.secretStorage.checkKey(key, info);\n }\n\n /**\n * Checks that a given secret storage private key matches a given public key.\n * This can be used by the getSecretStorageKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n */\n public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n let decryption: PkDecryption | null = null;\n try {\n decryption = new globalThis.Olm.PkDecryption();\n const gotPubkey = decryption.init_with_private_key(privateKey);\n // make sure it agrees with the given pubkey\n return gotPubkey === expectedPublicKey;\n } finally {\n decryption?.free();\n }\n }\n\n /**\n * Fetches the backup private key, if cached\n * @returns the key, if any, or null\n */\n public async getSessionBackupPrivateKey(): Promise<Uint8Array | null> {\n const encodedKey = await new Promise<Uint8Array | AESEncryptedSecretStoragePayload | string | null>(\n (resolve) => {\n this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.getSecretStorePrivateKey(txn, resolve, \"m.megolm_backup.v1\");\n });\n },\n );\n\n let key: Uint8Array | null = null;\n\n // make sure we have a Uint8Array, rather than a string\n if (typeof encodedKey === \"string\") {\n key = new Uint8Array(decodeBase64(fixBackupKey(encodedKey) || encodedKey));\n await this.storeSessionBackupPrivateKey(key);\n }\n if (encodedKey && typeof encodedKey === \"object\" && \"ciphertext\" in encodedKey) {\n const pickleKey = Buffer.from(this.olmDevice.pickleKey);\n const decrypted = await decryptAESSecretStorageItem(encodedKey, pickleKey, \"m.megolm_backup.v1\");\n key = decodeBase64(decrypted);\n }\n return key;\n }\n\n /**\n * Stores the session backup key to the cache\n * @param key - the private key\n * @returns a promise so you can catch failures\n */\n public async storeSessionBackupPrivateKey(key: ArrayLike<number>, version?: string): Promise<void> {\n if (!(key instanceof Uint8Array)) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${key}`);\n }\n const pickleKey = Buffer.from(this.olmDevice.pickleKey);\n const encryptedKey = await encryptAESSecretStorageItem(encodeBase64(key), pickleKey, \"m.megolm_backup.v1\");\n return this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.storeSecretStorePrivateKey(txn, \"m.megolm_backup.v1\", encryptedKey);\n });\n }\n\n /**\n * Implementation of {@link Crypto.loadSessionBackupPrivateKeyFromSecretStorage}.\n */\n public loadSessionBackupPrivateKeyFromSecretStorage(): Promise<void> {\n throw new Error(\"Not implmeented\");\n }\n\n /**\n * Get the current status of key backup.\n *\n * Implementation of {@link Crypto.CryptoApi.getActiveSessionBackupVersion}.\n */\n public async getActiveSessionBackupVersion(): Promise<string | null> {\n if (this.backupManager.getKeyBackupEnabled()) {\n return this.backupManager.version ?? null;\n }\n return null;\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi#getKeyBackupInfo}.\n */\n public async getKeyBackupInfo(): Promise<KeyBackupInfo | null> {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Determine if a key backup can be trusted.\n *\n * Implementation of {@link Crypto.CryptoApi.isKeyBackupTrusted}.\n */\n public async isKeyBackupTrusted(info: KeyBackupInfo): Promise<BackupTrustInfo> {\n const trustInfo = await this.backupManager.isKeyBackupTrusted(info);\n return backupTrustInfoFromLegacyTrustInfo(trustInfo);\n }\n\n /**\n * Force a re-check of the key backup and enable/disable it as appropriate.\n *\n * Implementation of {@link Crypto.CryptoApi.checkKeyBackupAndEnable}.\n */\n public async checkKeyBackupAndEnable(): Promise<KeyBackupCheck | null> {\n const checkResult = await this.backupManager.checkKeyBackup();\n if (!checkResult || !checkResult.backupInfo) return null;\n return {\n backupInfo: checkResult.backupInfo,\n trustInfo: backupTrustInfoFromLegacyTrustInfo(checkResult.trustInfo),\n };\n }\n\n /**\n * Checks that a given cross-signing private key matches a given public key.\n * This can be used by the getCrossSigningKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n */\n public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n let signing: PkSigning | null = null;\n try {\n signing = new globalThis.Olm.PkSigning();\n const gotPubkey = signing.init_with_seed(privateKey);\n // make sure it agrees with the given pubkey\n return gotPubkey === expectedPublicKey;\n } finally {\n signing?.free();\n }\n }\n\n /**\n * Run various follow-up actions after cross-signing keys have changed locally\n * (either by resetting the keys for the account or by getting them from secret\n * storage), such as signing the current device, upgrading device\n * verifications, etc.\n */\n private async afterCrossSigningLocalKeyChange(): Promise<void> {\n logger.info(\"Starting cross-signing key change post-processing\");\n\n // sign the current device with the new key, and upload to the server\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId)!;\n const signedDevice = await this.crossSigningInfo.signDevice(this.userId, device);\n logger.info(`Starting background key sig upload for ${this.deviceId}`);\n\n const upload = ({ shouldEmit = false }): Promise<void> => {\n return this.baseApis\n .uploadKeySignatures({\n [this.userId]: {\n [this.deviceId]: signedDevice!,\n },\n })\n .then((response) => {\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n CryptoEvent.KeySignatureUploadFailure,\n failures,\n \"afterCrossSigningLocalKeyChange\",\n upload, // continuation\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n logger.info(`Finished background key sig upload for ${this.deviceId}`);\n })\n .catch((e) => {\n logger.error(`Error during background key sig upload for ${this.deviceId}`, e);\n });\n };\n upload({ shouldEmit: true });\n\n const shouldUpgradeCb = this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;\n if (shouldUpgradeCb) {\n logger.info(\"Starting device verification upgrade\");\n\n // Check all users for signatures if upgrade callback present\n // FIXME: do this in batches\n const users: Record<string, IDeviceVerificationUpgrade> = {};\n for (const [userId, crossSigningInfo] of Object.entries(this.deviceList.crossSigningInfo)) {\n const upgradeInfo = await this.checkForDeviceVerificationUpgrade(\n userId,\n CrossSigningInfo.fromStorage(crossSigningInfo, userId),\n );\n if (upgradeInfo) {\n users[userId] = upgradeInfo;\n }\n }\n\n if (Object.keys(users).length > 0) {\n logger.info(`Found ${Object.keys(users).length} verif users to upgrade`);\n try {\n const usersToUpgrade = await shouldUpgradeCb({ users: users });\n if (usersToUpgrade) {\n for (const userId of usersToUpgrade) {\n if (userId in users) {\n await this.baseApis.setDeviceVerified(userId, users[userId].crossSigningInfo.getId()!);\n }\n }\n }\n } catch (e) {\n logger.log(\"shouldUpgradeDeviceVerifications threw an error: not upgrading\", e);\n }\n }\n\n logger.info(\"Finished device verification upgrade\");\n }\n\n logger.info(\"Finished cross-signing key change post-processing\");\n }\n\n /**\n * Check if a user's cross-signing key is a candidate for upgrading from device\n * verification.\n *\n * @param userId - the user whose cross-signing information is to be checked\n * @param crossSigningInfo - the cross-signing information to check\n */\n private async checkForDeviceVerificationUpgrade(\n userId: string,\n crossSigningInfo: CrossSigningInfo,\n ): Promise<IDeviceVerificationUpgrade | undefined> {\n // only upgrade if this is the first cross-signing key that we've seen for\n // them, and if their cross-signing key isn't already verified\n const trustLevel = this.crossSigningInfo.checkUserTrust(crossSigningInfo);\n if (crossSigningInfo.firstUse && !trustLevel.isVerified()) {\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n const deviceIds = await this.checkForValidDeviceSignature(userId, crossSigningInfo.keys.master, devices);\n if (deviceIds.length) {\n return {\n devices: deviceIds.map((deviceId) => DeviceInfo.fromStorage(devices[deviceId], deviceId)),\n crossSigningInfo,\n };\n }\n }\n }\n\n /**\n * Check if the cross-signing key is signed by a verified device.\n *\n * @param userId - the user ID whose key is being checked\n * @param key - the key that is being checked\n * @param devices - the user's devices. Should be a map from device ID\n * to device info\n */\n private async checkForValidDeviceSignature(\n userId: string,\n key: CrossSigningKeyInfo,\n devices: Record<string, IDevice>,\n ): Promise<string[]> {\n const deviceIds: string[] = [];\n if (devices && key.signatures && key.signatures[userId]) {\n for (const signame of Object.keys(key.signatures[userId])) {\n const [, deviceId] = signame.split(\":\", 2);\n if (deviceId in devices && devices[deviceId].verified === DeviceVerification.VERIFIED) {\n try {\n await olmlib.verifySignature(\n this.olmDevice,\n key,\n userId,\n deviceId,\n devices[deviceId].keys[signame],\n );\n deviceIds.push(deviceId);\n } catch {}\n }\n }\n }\n return deviceIds;\n }\n\n /**\n * Get the user's cross-signing key ID.\n *\n * @param type - The type of key to get the ID of. One of\n * \"master\", \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns the key ID\n */\n public getCrossSigningKeyId(type: CrossSigningKey = CrossSigningKey.Master): Promise<string | null> {\n return Promise.resolve(this.getCrossSigningId(type));\n }\n\n // old name, for backwards compatibility\n public getCrossSigningId(type: string): string | null {\n return this.crossSigningInfo.getId(type);\n }\n\n /**\n * Get the cross signing information for a given user.\n *\n * @param userId - the user ID to get the cross-signing info for.\n *\n * @returns the cross signing information for the user.\n */\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo | null {\n return this.deviceList.getStoredCrossSigningForUser(userId);\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * @param userId - The ID of the user to check.\n *\n * @returns\n */\n public checkUserTrust(userId: string): UserTrustLevel {\n const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (!userCrossSigning) {\n return new UserTrustLevel(false, false, false);\n }\n return this.crossSigningInfo.checkUserTrust(userCrossSigning);\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi.getUserVerificationStatus}.\n */\n public async getUserVerificationStatus(userId: string): Promise<UserTrustLevel> {\n return this.checkUserTrust(userId);\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi.pinCurrentUserIdentity}.\n */\n public async pinCurrentUserIdentity(userId: string): Promise<void> {\n throw new Error(\"not implemented\");\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * @param userId - The ID of the user whose device is to be checked.\n * @param deviceId - The ID of the device to check\n */\n public async getDeviceVerificationStatus(\n userId: string,\n deviceId: string,\n ): Promise<DeviceVerificationStatus | null> {\n const device = this.deviceList.getStoredDevice(userId, deviceId);\n if (!device) {\n return null;\n }\n return this.checkDeviceInfoTrust(userId, device);\n }\n\n /**\n * @deprecated Use {@link Crypto.CryptoApi.getDeviceVerificationStatus}.\n */\n public checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel {\n const device = this.deviceList.getStoredDevice(userId, deviceId);\n return this.checkDeviceInfoTrust(userId, device);\n }\n\n /**\n * Check whether a given deviceinfo is trusted.\n *\n * @param userId - The ID of the user whose devices is to be checked.\n * @param device - The device info object to check\n *\n * @deprecated Use {@link Crypto.CryptoApi.getDeviceVerificationStatus}.\n */\n public checkDeviceInfoTrust(userId: string, device?: DeviceInfo): DeviceTrustLevel {\n const trustedLocally = !!device?.isVerified();\n\n const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (device && userCrossSigning) {\n // The trustCrossSignedDevices only affects trust of other people's cross-signing\n // signatures\n const trustCrossSig = this.trustCrossSignedDevices || userId === this.userId;\n return this.crossSigningInfo.checkDeviceTrust(userCrossSigning, device, trustedLocally, trustCrossSig);\n } else {\n return new DeviceTrustLevel(false, false, trustedLocally, false);\n }\n }\n\n /**\n * Check whether one of our own devices is cross-signed by our\n * user's stored keys, regardless of whether we trust those keys yet.\n *\n * @param deviceId - The ID of the device to check\n *\n * @returns true if the device is cross-signed\n */\n public checkIfOwnDeviceCrossSigned(deviceId: string): boolean {\n const device = this.deviceList.getStoredDevice(this.userId, deviceId);\n if (!device) return false;\n const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(this.userId);\n return (\n userCrossSigning?.checkDeviceTrust(userCrossSigning, device, false, true).isCrossSigningVerified() ?? false\n );\n }\n\n /*\n * Event handler for DeviceList's userNewDevices event\n */\n private onDeviceListUserCrossSigningUpdated = async (userId: string): Promise<void> => {\n if (userId === this.userId) {\n // An update to our own cross-signing key.\n // Get the new key first:\n const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n const seenPubkey = newCrossSigning ? newCrossSigning.getId() : null;\n const currentPubkey = this.crossSigningInfo.getId();\n const changed = currentPubkey !== seenPubkey;\n\n if (currentPubkey && seenPubkey && !changed) {\n // If it's not changed, just make sure everything is up to date\n await this.checkOwnCrossSigningTrust();\n } else {\n // We'll now be in a state where cross-signing on the account is not trusted\n // because our locally stored cross-signing keys will not match the ones\n // on the server for our account. So we clear our own stored cross-signing keys,\n // effectively disabling cross-signing until the user gets verified by the device\n // that reset the keys\n this.storeTrustedSelfKeys(null);\n // emit cross-signing has been disabled\n this.emit(CryptoEvent.KeysChanged, {});\n // as the trust for our own user has changed,\n // also emit an event for this\n this.emit(CryptoEvent.UserTrustStatusChanged, this.userId, this.checkUserTrust(userId));\n }\n } else {\n await this.checkDeviceVerifications(userId);\n\n // Update verified before latch using the current state and save the new\n // latch value in the device list store.\n const crossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (crossSigning) {\n crossSigning.updateCrossSigningVerifiedBefore(this.checkUserTrust(userId).isCrossSigningVerified());\n this.deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage());\n }\n\n this.emit(CryptoEvent.UserTrustStatusChanged, userId, this.checkUserTrust(userId));\n }\n };\n\n /**\n * Check the copy of our cross-signing key that we have in the device list and\n * see if we can get the private key. If so, mark it as trusted.\n */\n public async checkOwnCrossSigningTrust({\n allowPrivateKeyRequests = false,\n }: ICheckOwnCrossSigningTrustOpts = {}): Promise<void> {\n const userId = this.userId;\n\n // Before proceeding, ensure our cross-signing public keys have been\n // downloaded via the device list.\n await this.downloadKeys([this.userId]);\n\n // Also check which private keys are locally cached.\n const crossSigningPrivateKeys = await this.crossSigningInfo.getCrossSigningKeysFromCache();\n\n // If we see an update to our own master key, check it against the master\n // key we have and, if it matches, mark it as verified\n\n // First, get the new cross-signing info\n const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (!newCrossSigning) {\n logger.error(\n \"Got cross-signing update event for user \" + userId + \" but no new cross-signing information found!\",\n );\n return;\n }\n\n const seenPubkey = newCrossSigning.getId()!;\n const masterChanged = this.crossSigningInfo.getId() !== seenPubkey;\n const masterExistsNotLocallyCached = newCrossSigning.getId() && !crossSigningPrivateKeys.has(\"master\");\n if (masterChanged) {\n logger.info(\"Got new master public key\", seenPubkey);\n }\n if (allowPrivateKeyRequests && (masterChanged || masterExistsNotLocallyCached)) {\n logger.info(\"Attempting to retrieve cross-signing master private key\");\n let signing: PkSigning | null = null;\n // It's important for control flow that we leave any errors alone for\n // higher levels to handle so that e.g. cancelling access properly\n // aborts any larger operation as well.\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\"master\", seenPubkey);\n signing = ret[1];\n logger.info(\"Got cross-signing master private key\");\n } finally {\n signing?.free();\n }\n }\n\n const oldSelfSigningId = this.crossSigningInfo.getId(\"self_signing\");\n const oldUserSigningId = this.crossSigningInfo.getId(\"user_signing\");\n\n // Update the version of our keys in our cross-signing object and the local store\n this.storeTrustedSelfKeys(newCrossSigning.keys);\n\n const selfSigningChanged = oldSelfSigningId !== newCrossSigning.getId(\"self_signing\");\n const userSigningChanged = oldUserSigningId !== newCrossSigning.getId(\"user_signing\");\n\n const selfSigningExistsNotLocallyCached =\n newCrossSigning.getId(\"self_signing\") && !crossSigningPrivateKeys.has(\"self_signing\");\n const userSigningExistsNotLocallyCached =\n newCrossSigning.getId(\"user_signing\") && !crossSigningPrivateKeys.has(\"user_signing\");\n\n const keySignatures: Record<string, ISignedKey> = {};\n\n if (selfSigningChanged) {\n logger.info(\"Got new self-signing key\", newCrossSigning.getId(\"self_signing\"));\n }\n if (allowPrivateKeyRequests && (selfSigningChanged || selfSigningExistsNotLocallyCached)) {\n logger.info(\"Attempting to retrieve cross-signing self-signing private key\");\n let signing: PkSigning | null = null;\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\n \"self_signing\",\n newCrossSigning.getId(\"self_signing\")!,\n );\n signing = ret[1];\n logger.info(\"Got cross-signing self-signing private key\");\n } finally {\n signing?.free();\n }\n\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId)!;\n const signedDevice = await this.crossSigningInfo.signDevice(this.userId, device);\n keySignatures[this.deviceId] = signedDevice!;\n }\n if (userSigningChanged) {\n logger.info(\"Got new user-signing key\", newCrossSigning.getId(\"user_signing\"));\n }\n if (allowPrivateKeyRequests && (userSigningChanged || userSigningExistsNotLocallyCached)) {\n logger.info(\"Attempting to retrieve cross-signing user-signing private key\");\n let signing: PkSigning | null = null;\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\n \"user_signing\",\n newCrossSigning.getId(\"user_signing\")!,\n );\n signing = ret[1];\n logger.info(\"Got cross-signing user-signing private key\");\n } finally {\n signing?.free();\n }\n }\n\n if (masterChanged) {\n const masterKey = this.crossSigningInfo.keys.master;\n await this.signObject(masterKey);\n const deviceSig = masterKey.signatures![this.userId][\"ed25519:\" + this.deviceId];\n // Include only the _new_ device signature in the upload.\n // We may have existing signatures from deleted devices, which will cause\n // the entire upload to fail.\n keySignatures[this.crossSigningInfo.getId()!] = Object.assign({} as ISignedKey, masterKey, {\n signatures: {\n [this.userId]: {\n [\"ed25519:\" + this.deviceId]: deviceSig,\n },\n },\n });\n }\n\n const keysToUpload = Object.keys(keySignatures);\n if (keysToUpload.length) {\n const upload = ({ shouldEmit = false }): Promise<void> => {\n logger.info(`Starting background key sig upload for ${keysToUpload}`);\n return this.baseApis\n .uploadKeySignatures({ [this.userId]: keySignatures })\n .then((response) => {\n const { failures } = response || {};\n logger.info(`Finished background key sig upload for ${keysToUpload}`);\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n CryptoEvent.KeySignatureUploadFailure,\n failures,\n \"checkOwnCrossSigningTrust\",\n upload,\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n })\n .catch((e) => {\n logger.error(`Error during background key sig upload for ${keysToUpload}`, e);\n });\n };\n upload({ shouldEmit: true });\n }\n\n this.emit(CryptoEvent.UserTrustStatusChanged, userId, this.checkUserTrust(userId));\n\n if (masterChanged) {\n this.emit(CryptoEvent.KeysChanged, {});\n await this.afterCrossSigningLocalKeyChange();\n }\n\n // Now we may be able to trust our key backup\n await this.backupManager.checkKeyBackup();\n // FIXME: if we previously trusted the backup, should we automatically sign\n // the backup with the new key (if not already signed)?\n }\n\n /**\n * Implementation of {@link CryptoBackend#getBackupDecryptor}.\n */\n public async getBackupDecryptor(backupInfo: KeyBackupInfo, privKey: ArrayLike<number>): Promise<BackupDecryptor> {\n if (!(privKey instanceof Uint8Array)) {\n throw new Error(`getBackupDecryptor expects Uint8Array`);\n }\n\n const algorithm = await BackupManager.makeAlgorithm(backupInfo, async () => {\n return privKey;\n });\n\n // If the pubkey computed from the private data we've been given\n // doesn't match the one in the auth_data, the user has entered\n // a different recovery key / the wrong passphrase.\n if (!(await algorithm.keyMatches(privKey))) {\n return Promise.reject(new MatrixError({ errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY }));\n }\n\n return new LibOlmBackupDecryptor(algorithm);\n }\n\n /**\n * Implementation of {@link CryptoBackend#importBackedUpRoomKeys}.\n */\n public importBackedUpRoomKeys(\n keys: IMegolmSessionData[],\n backupVersion: string,\n opts: ImportRoomKeysOpts = {},\n ): Promise<void> {\n opts.source = \"backup\";\n return this.importRoomKeys(keys, opts);\n }\n\n /**\n * Store a set of keys as our own, trusted, cross-signing keys.\n *\n * @param keys - The new trusted set of keys\n */\n private async storeTrustedSelfKeys(keys: Record<string, CrossSigningKeyInfo> | null): Promise<void> {\n if (keys) {\n this.crossSigningInfo.setKeys(keys);\n } else {\n this.crossSigningInfo.clearKeys();\n }\n await this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.storeCrossSigningKeys(txn, this.crossSigningInfo.keys);\n });\n }\n\n /**\n * Check if the master key is signed by a verified device, and if so, prompt\n * the application to mark it as verified.\n *\n * @param userId - the user ID whose key should be checked\n */\n private async checkDeviceVerifications(userId: string): Promise<void> {\n const shouldUpgradeCb = this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;\n if (!shouldUpgradeCb) {\n // Upgrading skipped when callback is not present.\n return;\n }\n logger.info(`Starting device verification upgrade for ${userId}`);\n if (this.crossSigningInfo.keys.user_signing) {\n const crossSigningInfo = this.deviceList.getStoredCrossSigningForUser(userId);\n if (crossSigningInfo) {\n const upgradeInfo = await this.checkForDeviceVerificationUpgrade(userId, crossSigningInfo);\n if (upgradeInfo) {\n const usersToUpgrade = await shouldUpgradeCb({\n users: {\n [userId]: upgradeInfo,\n },\n });\n if (usersToUpgrade.includes(userId)) {\n await this.baseApis.setDeviceVerified(userId, crossSigningInfo.getId()!);\n }\n }\n }\n }\n logger.info(`Finished device verification upgrade for ${userId}`);\n }\n\n /**\n */\n public enableLazyLoading(): void {\n this.lazyLoadMembers = true;\n }\n\n /**\n * Tell the crypto module to register for MatrixClient events which it needs to\n * listen for\n *\n * @param eventEmitter - event source where we can register\n * for event notifications\n */\n public registerEventHandlers(\n eventEmitter: TypedEventEmitter<\n RoomMemberEvent.Membership | ClientEvent.ToDeviceEvent | RoomEvent.Timeline | MatrixEventEvent.Decrypted,\n any\n >,\n ): void {\n eventEmitter.on(RoomMemberEvent.Membership, this.onMembership);\n eventEmitter.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n eventEmitter.on(RoomEvent.Timeline, this.onTimelineEvent);\n eventEmitter.on(MatrixEventEvent.Decrypted, this.onTimelineEvent);\n }\n\n /**\n * @deprecated this does nothing and will be removed in a future version\n */\n public start(): void {\n logger.warn(\"MatrixClient.crypto.start() is deprecated\");\n }\n\n /** Stop background processes related to crypto */\n public stop(): void {\n this.outgoingRoomKeyRequestManager.stop();\n this.deviceList.stop();\n this.dehydrationManager.stop();\n this.backupManager.stop();\n }\n\n /**\n * Get the Ed25519 key for this device\n *\n * @returns base64-encoded ed25519 key.\n *\n * @deprecated Use {@link Crypto.CryptoApi#getOwnDeviceKeys}.\n */\n public getDeviceEd25519Key(): string | null {\n return this.olmDevice.deviceEd25519Key;\n }\n\n /**\n * Get the Curve25519 key for this device\n *\n * @returns base64-encoded curve25519 key.\n *\n * @deprecated Use {@link Crypto.CryptoApi#getOwnDeviceKeys}\n */\n public getDeviceCurve25519Key(): string | null {\n return this.olmDevice.deviceCurve25519Key;\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi#getOwnDeviceKeys}.\n */\n public async getOwnDeviceKeys(): Promise<OwnDeviceKeys> {\n if (!this.olmDevice.deviceCurve25519Key) {\n throw new Error(\"Curve25519 key not yet created\");\n }\n if (!this.olmDevice.deviceEd25519Key) {\n throw new Error(\"Ed25519 key not yet created\");\n }\n return {\n ed25519: this.olmDevice.deviceEd25519Key,\n curve25519: this.olmDevice.deviceCurve25519Key,\n };\n }\n\n /**\n * Set the global override for whether the client should ever send encrypted\n * messages to unverified devices. This provides the default for rooms which\n * do not specify a value.\n *\n * @param value - whether to blacklist all unverified devices by default\n *\n * @deprecated Set {@link Crypto.CryptoApi#globalBlacklistUnverifiedDevices | CryptoApi.globalBlacklistUnverifiedDevices} directly.\n */\n public setGlobalBlacklistUnverifiedDevices(value: boolean): void {\n this.globalBlacklistUnverifiedDevices = value;\n }\n\n /**\n * @returns whether to blacklist all unverified devices by default\n *\n * @deprecated Reference {@link Crypto.CryptoApi#globalBlacklistUnverifiedDevices | CryptoApi.globalBlacklistUnverifiedDevices} directly.\n */\n public getGlobalBlacklistUnverifiedDevices(): boolean {\n return this.globalBlacklistUnverifiedDevices;\n }\n\n /**\n * Upload the device keys to the homeserver.\n * @returns A promise that will resolve when the keys are uploaded.\n */\n public uploadDeviceKeys(): Promise<IKeysUploadResponse> {\n const deviceKeys = {\n algorithms: this.supportedAlgorithms,\n device_id: this.deviceId,\n keys: this.deviceKeys,\n user_id: this.userId,\n };\n\n return this.signObject(deviceKeys).then(() => {\n return this.baseApis.uploadKeysRequest({\n device_keys: deviceKeys as Required<IDeviceKeys>,\n });\n });\n }\n\n public getNeedsNewFallback(): boolean {\n return !!this.needsNewFallback;\n }\n\n // check if it's time to upload one-time keys, and do so if so.\n private maybeUploadOneTimeKeys(): void {\n // frequency with which to check & upload one-time keys\n const uploadPeriod = 1000 * 60; // one minute\n\n // max number of keys to upload at once\n // Creating keys can be an expensive operation so we limit the\n // number we generate in one go to avoid blocking the application\n // for too long.\n const maxKeysPerCycle = 5;\n\n if (this.oneTimeKeyCheckInProgress) {\n return;\n }\n\n const now = Date.now();\n if (this.lastOneTimeKeyCheck !== null && now - this.lastOneTimeKeyCheck < uploadPeriod) {\n // we've done a key upload recently.\n return;\n }\n\n this.lastOneTimeKeyCheck = now;\n\n // We need to keep a pool of one time public keys on the server so that\n // other devices can start conversations with us. But we can only store\n // a finite number of private keys in the olm Account object.\n // To complicate things further then can be a delay between a device\n // claiming a public one time key from the server and it sending us a\n // message. We need to keep the corresponding private key locally until\n // we receive the message.\n // But that message might never arrive leaving us stuck with duff\n // private keys clogging up our local storage.\n // So we need some kind of engineering compromise to balance all of\n // these factors.\n\n // Check how many keys we can store in the Account object.\n const maxOneTimeKeys = this.olmDevice.maxNumberOfOneTimeKeys();\n // Try to keep at most half that number on the server. This leaves the\n // rest of the slots free to hold keys that have been claimed from the\n // server but we haven't received a message for.\n // If we run out of slots when generating new keys then olm will\n // discard the oldest private keys first. This will eventually clean\n // out stale private keys that won't receive a message.\n const keyLimit = Math.floor(maxOneTimeKeys / 2);\n\n const uploadLoop = async (keyCount: number): Promise<void> => {\n while (keyLimit > keyCount || this.getNeedsNewFallback()) {\n // Ask olm to generate new one time keys, then upload them to synapse.\n if (keyLimit > keyCount) {\n logger.info(\"generating oneTimeKeys\");\n const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle);\n await this.olmDevice.generateOneTimeKeys(keysThisLoop);\n }\n\n if (this.getNeedsNewFallback()) {\n const fallbackKeys = await this.olmDevice.getFallbackKey();\n // if fallbackKeys is non-empty, we've already generated a\n // fallback key, but it hasn't been published yet, so we\n // can use that instead of generating a new one\n if (!fallbackKeys.curve25519 || Object.keys(fallbackKeys.curve25519).length == 0) {\n logger.info(\"generating fallback key\");\n if (this.fallbackCleanup) {\n // cancel any pending fallback cleanup because generating\n // a new fallback key will already drop the old fallback\n // that would have been dropped, and we don't want to kill\n // the current key\n clearTimeout(this.fallbackCleanup);\n delete this.fallbackCleanup;\n }\n await this.olmDevice.generateFallbackKey();\n }\n }\n\n logger.info(\"calling uploadOneTimeKeys\");\n const res = await this.uploadOneTimeKeys();\n if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) {\n // if the response contains a more up to date value use this\n // for the next loop\n keyCount = res.one_time_key_counts.signed_curve25519;\n } else {\n throw new Error(\n \"response for uploading keys does not contain \" + \"one_time_key_counts.signed_curve25519\",\n );\n }\n }\n };\n\n this.oneTimeKeyCheckInProgress = true;\n Promise.resolve()\n .then(() => {\n if (this.oneTimeKeyCount !== undefined) {\n // We already have the current one_time_key count from a /sync response.\n // Use this value instead of asking the server for the current key count.\n return Promise.resolve(this.oneTimeKeyCount);\n }\n // ask the server how many keys we have\n return this.baseApis.uploadKeysRequest({}).then((res) => {\n return res.one_time_key_counts.signed_curve25519 || 0;\n });\n })\n .then((keyCount) => {\n // Start the uploadLoop with the current keyCount. The function checks if\n // we need to upload new keys or not.\n // If there are too many keys on the server then we don't need to\n // create any more keys.\n return uploadLoop(keyCount);\n })\n .catch((e) => {\n logger.error(\"Error uploading one-time keys\", e.stack || e);\n })\n .finally(() => {\n // reset oneTimeKeyCount to prevent start uploading based on old data.\n // it will be set again on the next /sync-response\n this.oneTimeKeyCount = undefined;\n this.oneTimeKeyCheckInProgress = false;\n });\n }\n\n // returns a promise which resolves to the response\n private async uploadOneTimeKeys(): Promise<IKeysUploadResponse> {\n const promises: Promise<unknown>[] = [];\n\n let fallbackJson: Record<string, IOneTimeKey> | undefined;\n if (this.getNeedsNewFallback()) {\n fallbackJson = {};\n const fallbackKeys = await this.olmDevice.getFallbackKey();\n for (const [keyId, key] of Object.entries(fallbackKeys.curve25519)) {\n const k = { key, fallback: true };\n fallbackJson[\"signed_curve25519:\" + keyId] = k;\n promises.push(this.signObject(k));\n }\n this.needsNewFallback = false;\n }\n\n const oneTimeKeys = await this.olmDevice.getOneTimeKeys();\n const oneTimeJson: Record<string, { key: string }> = {};\n\n for (const keyId in oneTimeKeys.curve25519) {\n if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) {\n const k = {\n key: oneTimeKeys.curve25519[keyId],\n };\n oneTimeJson[\"signed_curve25519:\" + keyId] = k;\n promises.push(this.signObject(k));\n }\n }\n\n await Promise.all(promises);\n\n const requestBody: Record<string, any> = {\n one_time_keys: oneTimeJson,\n };\n\n if (fallbackJson) {\n requestBody[\"org.matrix.msc2732.fallback_keys\"] = fallbackJson;\n requestBody[\"fallback_keys\"] = fallbackJson;\n }\n\n const res = await this.baseApis.uploadKeysRequest(requestBody);\n\n if (fallbackJson) {\n this.fallbackCleanup = setTimeout(\n () => {\n delete this.fallbackCleanup;\n this.olmDevice.forgetOldFallbackKey();\n },\n 60 * 60 * 1000,\n );\n }\n\n await this.olmDevice.markKeysAsPublished();\n return res;\n }\n\n /**\n * Download the keys for a list of users and stores the keys in the session\n * store.\n * @param userIds - The users to fetch.\n * @param forceDownload - Always download the keys even if cached.\n *\n * @returns A promise which resolves to a map `userId->deviceId->{@link DeviceInfo}`.\n */\n public downloadKeys(userIds: string[], forceDownload?: boolean): Promise<DeviceInfoMap> {\n return this.deviceList.downloadKeys(userIds, !!forceDownload);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param userId - the user to list keys for.\n *\n * @returns list of devices, or null if we haven't\n * managed to get a list of devices for this user yet.\n */\n public getStoredDevicesForUser(userId: string): Array<DeviceInfo> | null {\n return this.deviceList.getStoredDevicesForUser(userId);\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 public async getUserDeviceInfo(userIds: string[], downloadUncached = false): Promise<DeviceMap> {\n const deviceMapByUserId = new Map<string, Map<string, Device>>();\n // Keep the users without device to download theirs keys\n const usersWithoutDeviceInfo: string[] = [];\n\n for (const userId of userIds) {\n const deviceInfos = await this.getStoredDevicesForUser(userId);\n // If there are device infos for a userId, we transform it into a map\n // Else, the keys will be downloaded after\n if (deviceInfos) {\n const deviceMap = new Map(\n // Convert DeviceInfo to Device\n deviceInfos.map((deviceInfo) => [deviceInfo.deviceId, deviceInfoToDevice(deviceInfo, userId)]),\n );\n deviceMapByUserId.set(userId, deviceMap);\n } else {\n usersWithoutDeviceInfo.push(userId);\n }\n }\n\n // Download device info for users without device infos\n if (downloadUncached && usersWithoutDeviceInfo.length > 0) {\n const newDeviceInfoMap = await this.downloadKeys(usersWithoutDeviceInfo);\n\n newDeviceInfoMap.forEach((deviceInfoMap, userId) => {\n const deviceMap = new Map<string, Device>();\n // Convert DeviceInfo to Device\n deviceInfoMap.forEach((deviceInfo, deviceId) =>\n deviceMap.set(deviceId, deviceInfoToDevice(deviceInfo, userId)),\n );\n\n // Put the new device infos into the returned map\n deviceMapByUserId.set(userId, deviceMap);\n });\n }\n\n return deviceMapByUserId;\n }\n\n /**\n * Get the stored keys for a single device\n *\n *\n * @returns device, or undefined\n * if we don't know about this device\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo | undefined {\n return this.deviceList.getStoredDevice(userId, deviceId);\n }\n\n /**\n * Save the device list, if necessary\n *\n * @param delay - Time in ms before which the save actually happens.\n * By default, the save is delayed for a short period in order to batch\n * multiple writes, but this behaviour can be disabled by passing 0.\n *\n * @returns true if the data was saved, false if\n * it was not (eg. because no changes were pending). The promise\n * will only resolve once the data is saved, so may take some time\n * to resolve.\n */\n public saveDeviceList(delay: number): Promise<boolean> {\n return this.deviceList.saveIfDirty(delay);\n }\n\n /**\n * Mark the given device as locally verified.\n *\n * Implementation of {@link Crypto.CryptoApi#setDeviceVerified}.\n */\n public async setDeviceVerified(userId: string, deviceId: string, verified = true): Promise<void> {\n await this.setDeviceVerification(userId, deviceId, verified);\n }\n\n /**\n * Blindly cross-sign one of our other devices.\n *\n * Implementation of {@link Crypto.CryptoApi#crossSignDevice}.\n */\n public async crossSignDevice(deviceId: string): Promise<void> {\n await this.setDeviceVerified(this.userId, deviceId, true);\n }\n\n /**\n * Update the blocked/verified state of the given device\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param verified - whether to mark the device as verified. Null to\n * leave unchanged.\n *\n * @param blocked - whether to mark the device as blocked. Null to\n * leave unchanged.\n *\n * @param known - whether to mark that the user has been made aware of\n * the existence of this device. Null to leave unchanged\n *\n * @param keys - The list of keys that was present\n * during the device verification. This will be double checked with the list\n * of keys the given device has currently.\n *\n * @returns updated DeviceInfo\n */\n public async setDeviceVerification(\n userId: string,\n deviceId: string,\n verified: boolean | null = null,\n blocked: boolean | null = null,\n known: boolean | null = null,\n keys?: Record<string, string>,\n ): Promise<DeviceInfo | CrossSigningInfo | CrossSigningKeyInfo | undefined> {\n // Check if the 'device' is actually a cross signing key\n // The js-sdk's verification treats cross-signing keys as devices\n // and so uses this method to mark them verified.\n const xsk = this.deviceList.getStoredCrossSigningForUser(userId);\n if (xsk?.getId() === deviceId) {\n if (blocked !== null || known !== null) {\n throw new Error(\"Cannot set blocked or known for a cross-signing key\");\n }\n if (!verified) {\n throw new Error(\"Cannot set a cross-signing key as unverified\");\n }\n const gotKeyId = keys ? Object.values(keys)[0] : null;\n if (keys && (Object.values(keys).length !== 1 || gotKeyId !== xsk.getId())) {\n throw new Error(`Key did not match expected value: expected ${xsk.getId()}, got ${gotKeyId}`);\n }\n\n if (!this.crossSigningInfo.getId() && userId === this.crossSigningInfo.userId) {\n this.storeTrustedSelfKeys(xsk.keys);\n // This will cause our own user trust to change, so emit the event\n this.emit(CryptoEvent.UserTrustStatusChanged, this.userId, this.checkUserTrust(userId));\n }\n\n // Now sign the master key with our user signing key (unless it's ourself)\n if (userId !== this.userId) {\n logger.info(\"Master key \" + xsk.getId() + \" for \" + userId + \" marked verified. Signing...\");\n const device = await this.crossSigningInfo.signUser(xsk);\n if (device) {\n const upload = async ({ shouldEmit = false }): Promise<void> => {\n logger.info(\"Uploading signature for \" + userId + \"...\");\n const response = await this.baseApis.uploadKeySignatures({\n [userId]: {\n [deviceId]: device,\n },\n });\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n CryptoEvent.KeySignatureUploadFailure,\n failures,\n \"setDeviceVerification\",\n upload,\n );\n }\n /* Throwing here causes the process to be cancelled and the other\n * user to be notified */\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n };\n await upload({ shouldEmit: true });\n\n // This will emit events when it comes back down the sync\n // (we could do local echo to speed things up)\n }\n return device!;\n } else {\n return xsk;\n }\n }\n\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n if (!devices || !devices[deviceId]) {\n throw new Error(\"Unknown device \" + userId + \":\" + deviceId);\n }\n\n const dev = devices[deviceId];\n let verificationStatus = dev.verified;\n\n if (verified) {\n if (keys) {\n for (const [keyId, key] of Object.entries(keys)) {\n if (dev.keys[keyId] !== key) {\n throw new Error(`Key did not match expected value: expected ${key}, got ${dev.keys[keyId]}`);\n }\n }\n }\n verificationStatus = DeviceVerification.VERIFIED;\n } else if (verified !== null && verificationStatus == DeviceVerification.VERIFIED) {\n verificationStatus = DeviceVerification.UNVERIFIED;\n }\n\n if (blocked) {\n verificationStatus = DeviceVerification.BLOCKED;\n } else if (blocked !== null && verificationStatus == DeviceVerification.BLOCKED) {\n verificationStatus = DeviceVerification.UNVERIFIED;\n }\n\n let knownStatus = dev.known;\n if (known !== null) {\n knownStatus = known;\n }\n\n if (dev.verified !== verificationStatus || dev.known !== knownStatus) {\n dev.verified = verificationStatus;\n dev.known = knownStatus;\n this.deviceList.storeDevicesForUser(userId, devices);\n this.deviceList.saveIfDirty();\n }\n\n // do cross-signing\n if (verified && userId === this.userId) {\n logger.info(\"Own device \" + deviceId + \" marked verified: signing\");\n\n // Signing only needed if other device not already signed\n let device: ISignedKey | undefined;\n const deviceTrust = this.checkDeviceTrust(userId, deviceId);\n if (deviceTrust.isCrossSigningVerified()) {\n logger.log(`Own device ${deviceId} already cross-signing verified`);\n } else {\n device = (await this.crossSigningInfo.signDevice(userId, DeviceInfo.fromStorage(dev, deviceId)))!;\n }\n\n if (device) {\n const upload = async ({ shouldEmit = false }): Promise<void> => {\n logger.info(\"Uploading signature for \" + deviceId);\n const response = await this.baseApis.uploadKeySignatures({\n [userId]: {\n [deviceId]: device!,\n },\n });\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n CryptoEvent.KeySignatureUploadFailure,\n failures,\n \"setDeviceVerification\",\n upload, // continuation\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n };\n await upload({ shouldEmit: true });\n // XXX: we'll need to wait for the device list to be updated\n }\n }\n\n const deviceObj = DeviceInfo.fromStorage(dev, deviceId);\n this.emit(CryptoEvent.DeviceVerificationChanged, userId, deviceId, deviceObj);\n return deviceObj;\n }\n\n public findVerificationRequestDMInProgress(roomId: string, userId?: string): VerificationRequest | undefined {\n return this.inRoomVerificationRequests.findRequestInProgress(roomId, userId);\n }\n\n public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[] {\n return this.toDeviceVerificationRequests.getRequestsInProgress(userId);\n }\n\n public requestVerificationDM(userId: string, roomId: string): Promise<VerificationRequest> {\n const existingRequest = this.inRoomVerificationRequests.findRequestInProgress(roomId);\n if (existingRequest) {\n return Promise.resolve(existingRequest);\n }\n const channel = new InRoomChannel(this.baseApis, roomId, userId);\n return this.requestVerificationWithChannel(userId, channel, this.inRoomVerificationRequests);\n }\n\n /** @deprecated Use `requestOwnUserVerificationToDevice` or `requestDeviceVerification` */\n public requestVerification(userId: string, devices?: string[]): Promise<VerificationRequest> {\n if (!devices) {\n devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(userId));\n }\n const existingRequest = this.toDeviceVerificationRequests.findRequestInProgress(userId, devices);\n if (existingRequest) {\n return Promise.resolve(existingRequest);\n }\n const channel = new ToDeviceChannel(this.baseApis, userId, devices, ToDeviceChannel.makeTransactionId());\n return this.requestVerificationWithChannel(userId, channel, this.toDeviceVerificationRequests);\n }\n\n public requestOwnUserVerification(): Promise<VerificationRequest> {\n return this.requestVerification(this.userId);\n }\n\n public requestDeviceVerification(userId: string, deviceId: string): Promise<VerificationRequest> {\n return this.requestVerification(userId, [deviceId]);\n }\n\n private async requestVerificationWithChannel(\n userId: string,\n channel: IVerificationChannel,\n requestsMap: IRequestsMap,\n ): Promise<VerificationRequest> {\n let request = new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n // if transaction id is already known, add request\n if (channel.transactionId) {\n requestsMap.setRequestByChannel(channel, request);\n }\n await request.sendRequest();\n // don't replace the request created by a racing remote echo\n const racingRequest = requestsMap.getRequestByChannel(channel);\n if (racingRequest) {\n request = racingRequest;\n } else {\n logger.log(\n `Crypto: adding new request to ` + `requestsByTxnId with id ${channel.transactionId} ${channel.roomId}`,\n );\n requestsMap.setRequestByChannel(channel, request);\n }\n return request;\n }\n\n public beginKeyVerification(\n method: string,\n userId: string,\n deviceId: string,\n transactionId: string | null = null,\n ): VerificationBase<any, any> {\n let request: Request | undefined;\n if (transactionId) {\n request = this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(userId, transactionId);\n if (!request) {\n throw new Error(`No request found for user ${userId} with ` + `transactionId ${transactionId}`);\n }\n } else {\n transactionId = ToDeviceChannel.makeTransactionId();\n const channel = new ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId);\n request = new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request);\n }\n return request.beginKeyVerification(method, { userId, deviceId });\n }\n\n public async legacyDeviceVerification(\n userId: string,\n deviceId: string,\n method: VerificationMethod,\n ): Promise<VerificationRequest> {\n const transactionId = ToDeviceChannel.makeTransactionId();\n const channel = new ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId);\n const request = new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request);\n const verifier = request.beginKeyVerification(method, { userId, deviceId });\n // either reject by an error from verify() while sending .start\n // or resolve when the request receives the\n // local (fake remote) echo for sending the .start event\n await Promise.race([verifier.verify(), request.waitFor((r) => r.started)]);\n return request;\n }\n\n /**\n * Get information on the active olm sessions with a user\n * <p>\n * Returns a map from device id to an object with keys 'deviceIdKey' (the\n * device's curve25519 identity key) and 'sessions' (an array of objects in the\n * same format as that returned by\n * {@link OlmDevice#getSessionInfoForDevice}).\n * <p>\n * This method is provided for debugging purposes.\n *\n * @param userId - id of user to inspect\n */\n public async getOlmSessionsForUser(userId: string): Promise<Record<string, IUserOlmSession>> {\n const devices = this.getStoredDevicesForUser(userId) || [];\n const result: { [deviceId: string]: IUserOlmSession } = {};\n for (const device of devices) {\n const deviceKey = device.getIdentityKey();\n const sessions = await this.olmDevice.getSessionInfoForDevice(deviceKey);\n\n result[device.deviceId] = {\n deviceIdKey: deviceKey,\n sessions: sessions,\n };\n }\n return result;\n }\n\n /**\n * Get the device which sent an event\n *\n * @param event - event to be checked\n */\n public getEventSenderDeviceInfo(event: MatrixEvent): DeviceInfo | null {\n const senderKey = event.getSenderKey();\n const algorithm = event.getWireContent().algorithm;\n\n if (!senderKey || !algorithm) {\n return null;\n }\n\n if (event.isKeySourceUntrusted()) {\n // we got the key for this event from a source that we consider untrusted\n return null;\n }\n\n // senderKey is the Curve25519 identity key of the device which the event\n // was sent from. In the case of Megolm, it's actually the Curve25519\n // identity key of the device which set up the Megolm session.\n\n const device = this.deviceList.getDeviceByIdentityKey(algorithm, senderKey);\n\n if (device === null) {\n // we haven't downloaded the details of this device yet.\n return null;\n }\n\n // so far so good, but now we need to check that the sender of this event\n // hadn't advertised someone else's Curve25519 key as their own. We do that\n // by checking the Ed25519 claimed by the event (or, in the case of megolm,\n // the event which set up the megolm session), to check that it matches the\n // fingerprint of the purported sending device.\n //\n // (see https://github.com/vector-im/vector-web/issues/2215)\n\n const claimedKey = event.getClaimedEd25519Key();\n if (!claimedKey) {\n logger.warn(\"Event \" + event.getId() + \" claims no ed25519 key: \" + \"cannot verify sending device\");\n return null;\n }\n\n if (claimedKey !== device.getFingerprint()) {\n logger.warn(\n \"Event \" +\n event.getId() +\n \" claims ed25519 key \" +\n claimedKey +\n \" but sender device has key \" +\n device.getFingerprint(),\n );\n return null;\n }\n\n return device;\n }\n\n /**\n * Get information about the encryption of an event\n *\n * @param event - event to be checked\n *\n * @returns An object with the fields:\n * - encrypted: whether the event is encrypted (if not encrypted, some of the\n * other properties may not be set)\n * - senderKey: the sender's key\n * - algorithm: the algorithm used to encrypt the event\n * - authenticated: whether we can be sure that the owner of the senderKey\n * sent the event\n * - sender: the sender's device information, if available\n * - mismatchedSender: if the event's ed25519 and curve25519 keys don't match\n * (only meaningful if `sender` is set)\n */\n public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo {\n const ret: Partial<IEncryptedEventInfo> = {};\n\n ret.senderKey = event.getSenderKey() ?? undefined;\n ret.algorithm = event.getWireContent().algorithm;\n\n if (!ret.senderKey || !ret.algorithm) {\n ret.encrypted = false;\n return ret as IEncryptedEventInfo;\n }\n ret.encrypted = true;\n\n if (event.isKeySourceUntrusted()) {\n // we got the key this event from somewhere else\n // TODO: check if we can trust the forwarders.\n ret.authenticated = false;\n } else {\n ret.authenticated = true;\n }\n\n // senderKey is the Curve25519 identity key of the device which the event\n // was sent from. In the case of Megolm, it's actually the Curve25519\n // identity key of the device which set up the Megolm session.\n\n ret.sender = this.deviceList.getDeviceByIdentityKey(ret.algorithm, ret.senderKey) ?? undefined;\n\n // so far so good, but now we need to check that the sender of this event\n // hadn't advertised someone else's Curve25519 key as their own. We do that\n // by checking the Ed25519 claimed by the event (or, in the case of megolm,\n // the event which set up the megolm session), to check that it matches the\n // fingerprint of the purported sending device.\n //\n // (see https://github.com/vector-im/vector-web/issues/2215)\n\n const claimedKey = event.getClaimedEd25519Key();\n if (!claimedKey) {\n logger.warn(\"Event \" + event.getId() + \" claims no ed25519 key: \" + \"cannot verify sending device\");\n ret.mismatchedSender = true;\n }\n\n if (ret.sender && claimedKey !== ret.sender.getFingerprint()) {\n logger.warn(\n \"Event \" +\n event.getId() +\n \" claims ed25519 key \" +\n claimedKey +\n \"but sender device has key \" +\n ret.sender.getFingerprint(),\n );\n ret.mismatchedSender = true;\n }\n\n return ret as IEncryptedEventInfo;\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi.getEncryptionInfoForEvent}.\n */\n public async getEncryptionInfoForEvent(event: MatrixEvent): Promise<EventEncryptionInfo | null> {\n const encryptionInfo = this.getEventEncryptionInfo(event);\n if (!encryptionInfo.encrypted) {\n return null;\n }\n\n const senderId = event.getSender();\n if (!senderId || encryptionInfo.mismatchedSender) {\n // something definitely wrong is going on here\n\n // previously: E2EState.Warning -> E2ePadlockUnverified -> Red/\"Encrypted by an unverified session\"\n return {\n shieldColour: EventShieldColour.RED,\n shieldReason: EventShieldReason.MISMATCHED_SENDER_KEY,\n };\n }\n\n const userTrust = this.checkUserTrust(senderId);\n if (!userTrust.isCrossSigningVerified()) {\n // If the message is unauthenticated, then display a grey\n // shield, otherwise if the user isn't cross-signed then\n // nothing's needed\n if (!encryptionInfo.authenticated) {\n // previously: E2EState.Unauthenticated -> E2ePadlockUnauthenticated -> Grey/\"The authenticity of this encrypted message can't be guaranteed on this device.\"\n return {\n shieldColour: EventShieldColour.GREY,\n shieldReason: EventShieldReason.AUTHENTICITY_NOT_GUARANTEED,\n };\n } else {\n // previously: E2EState.Normal -> no icon\n return { shieldColour: EventShieldColour.NONE, shieldReason: null };\n }\n }\n\n const eventSenderTrust =\n senderId &&\n encryptionInfo.sender &&\n (await this.getDeviceVerificationStatus(senderId, encryptionInfo.sender.deviceId));\n\n if (!eventSenderTrust) {\n // previously: E2EState.Unknown -> E2ePadlockUnknown -> Grey/\"Encrypted by a deleted session\"\n return {\n shieldColour: EventShieldColour.GREY,\n shieldReason: EventShieldReason.UNKNOWN_DEVICE,\n };\n }\n\n if (!eventSenderTrust.isVerified()) {\n // previously: E2EState.Warning -> E2ePadlockUnverified -> Red/\"Encrypted by an unverified session\"\n return {\n shieldColour: EventShieldColour.RED,\n shieldReason: EventShieldReason.UNSIGNED_DEVICE,\n };\n }\n\n if (!encryptionInfo.authenticated) {\n // previously: E2EState.Unauthenticated -> E2ePadlockUnauthenticated -> Grey/\"The authenticity of this encrypted message can't be guaranteed on this device.\"\n return {\n shieldColour: EventShieldColour.GREY,\n shieldReason: EventShieldReason.AUTHENTICITY_NOT_GUARANTEED,\n };\n }\n\n // previously: E2EState.Verified -> no icon\n return { shieldColour: EventShieldColour.NONE, shieldReason: null };\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * @param roomId - The ID of the room to discard the session for\n *\n * This should not normally be necessary.\n */\n public forceDiscardSession(roomId: string): Promise<void> {\n const alg = this.roomEncryptors.get(roomId);\n if (alg === undefined) throw new Error(\"Room not encrypted\");\n if (alg.forceDiscardSession === undefined) {\n throw new Error(\"Room encryption algorithm doesn't support session discarding\");\n }\n alg.forceDiscardSession();\n return Promise.resolve();\n }\n\n /**\n * Configure a room to use encryption (ie, save a flag in the cryptoStore).\n *\n * @param roomId - The room ID to enable encryption in.\n *\n * @param config - The encryption config for the room.\n *\n * @param inhibitDeviceQuery - true to suppress device list query for\n * users in the room (for now). In case lazy loading is enabled,\n * the device query is always inhibited as the members are not tracked.\n *\n * @deprecated It is normally incorrect to call this method directly. Encryption\n * is enabled by receiving an `m.room.encryption` event (which we may have sent\n * previously).\n */\n public async setRoomEncryption(\n roomId: string,\n config: IRoomEncryption,\n inhibitDeviceQuery?: boolean,\n ): Promise<void> {\n const room = this.clientStore.getRoom(roomId);\n if (!room) {\n throw new Error(`Unable to enable encryption tracking devices in unknown room ${roomId}`);\n }\n await this.setRoomEncryptionImpl(room, config);\n if (!this.lazyLoadMembers && !inhibitDeviceQuery) {\n this.deviceList.refreshOutdatedDeviceLists();\n }\n }\n\n /**\n * Set up encryption for a room.\n *\n * This is called when an <tt>m.room.encryption</tt> event is received. It saves a flag\n * for the room in the cryptoStore (if it wasn't already set), sets up an \"encryptor\" for\n * the room, and enables device-list tracking for the room.\n *\n * It does <em>not</em> initiate a device list query for the room. That is normally\n * done once we finish processing the sync, in onSyncCompleted.\n *\n * @param room - The room to enable encryption in.\n * @param config - The encryption config for the room.\n */\n private async setRoomEncryptionImpl(room: Room, config: IRoomEncryption): Promise<void> {\n const roomId = room.roomId;\n\n // ignore crypto events with no algorithm defined\n // This will happen if a crypto event is redacted before we fetch the room state\n // It would otherwise just throw later as an unknown algorithm would, but we may\n // as well catch this here\n if (!config.algorithm) {\n logger.log(\"Ignoring setRoomEncryption with no algorithm\");\n return;\n }\n\n // if state is being replayed from storage, we might already have a configuration\n // for this room as they are persisted as well.\n // We just need to make sure the algorithm is initialized in this case.\n // However, if the new config is different,\n // we should bail out as room encryption can't be changed once set.\n const existingConfig = this.roomList.getRoomEncryption(roomId);\n if (existingConfig) {\n if (JSON.stringify(existingConfig) != JSON.stringify(config)) {\n logger.error(\"Ignoring m.room.encryption event which requests \" + \"a change of config in \" + roomId);\n return;\n }\n }\n // if we already have encryption in this room, we should ignore this event,\n // as it would reset the encryption algorithm.\n // This is at least expected to be called twice, as sync calls onCryptoEvent\n // for both the timeline and state sections in the /sync response,\n // the encryption event would appear in both.\n // If it's called more than twice though,\n // it signals a bug on client or server.\n const existingAlg = this.roomEncryptors.get(roomId);\n if (existingAlg) {\n return;\n }\n\n // _roomList.getRoomEncryption will not race with _roomList.setRoomEncryption\n // because it first stores in memory. We should await the promise only\n // after all the in-memory state (roomEncryptors and _roomList) has been updated\n // to avoid races when calling this method multiple times. Hence keep a hold of the promise.\n let storeConfigPromise: Promise<void> | null = null;\n if (!existingConfig) {\n storeConfigPromise = this.roomList.setRoomEncryption(roomId, config);\n }\n\n const AlgClass = algorithms.ENCRYPTION_CLASSES.get(config.algorithm);\n if (!AlgClass) {\n throw new Error(\"Unable to encrypt with \" + config.algorithm);\n }\n\n const alg = new AlgClass({\n userId: this.userId,\n deviceId: this.deviceId,\n crypto: this,\n olmDevice: this.olmDevice,\n baseApis: this.baseApis,\n roomId,\n config,\n });\n this.roomEncryptors.set(roomId, alg);\n\n if (storeConfigPromise) {\n await storeConfigPromise;\n }\n\n logger.log(`Enabling encryption in ${roomId}`);\n\n // we don't want to force a download of the full membership list of this room, but as soon as we have that\n // list we can start tracking the device list.\n if (room.membersLoaded()) {\n await this.trackRoomDevicesImpl(room);\n } else {\n // wait for the membership list to be loaded\n const onState = (_state: RoomState): void => {\n room.off(RoomStateEvent.Update, onState);\n if (room.membersLoaded()) {\n this.trackRoomDevicesImpl(room).catch((e) => {\n logger.error(`Error enabling device tracking in ${roomId}`, e);\n });\n }\n };\n room.on(RoomStateEvent.Update, onState);\n }\n }\n\n /**\n * Make sure we are tracking the device lists for all users in this room.\n *\n * @param roomId - The room ID to start tracking devices in.\n * @returns when all devices for the room have been fetched and marked to track\n * @deprecated there's normally no need to call this function: device list tracking\n * will be enabled as soon as we have the full membership list.\n */\n public trackRoomDevices(roomId: string): Promise<void> {\n const room = this.clientStore.getRoom(roomId);\n if (!room) {\n throw new Error(`Unable to start tracking devices in unknown room ${roomId}`);\n }\n return this.trackRoomDevicesImpl(room);\n }\n\n /**\n * Make sure we are tracking the device lists for all users in this room.\n *\n * This is normally called when we are about to send an encrypted event, to make sure\n * we have all the devices in the room; but it is also called when processing an\n * m.room.encryption state event (if lazy-loading is disabled), or when members are\n * loaded (if lazy-loading is enabled), to prepare the device list.\n *\n * @param room - Room to enable device-list tracking in\n */\n private trackRoomDevicesImpl(room: Room): Promise<void> {\n const roomId = room.roomId;\n const trackMembers = async (): Promise<void> => {\n // not an encrypted room\n if (!this.roomEncryptors.has(roomId)) {\n return;\n }\n logger.log(`Starting to track devices for room ${roomId} ...`);\n const members = await room.getEncryptionTargetMembers();\n members.forEach((m) => {\n this.deviceList.startTrackingDeviceList(m.userId);\n });\n };\n\n let promise = this.roomDeviceTrackingState[roomId];\n if (!promise) {\n promise = trackMembers();\n this.roomDeviceTrackingState[roomId] = promise.catch((err) => {\n delete this.roomDeviceTrackingState[roomId];\n throw err;\n });\n }\n return promise;\n }\n\n /**\n * Try to make sure we have established olm sessions for all known devices for\n * the given users.\n *\n * @param users - list of user ids\n * @param force - If true, force a new Olm session to be created. Default false.\n *\n * @returns resolves once the sessions are complete, to\n * an Object mapping from userId to deviceId to\n * `IOlmSessionResult`\n */\n public ensureOlmSessionsForUsers(\n users: string[],\n force?: boolean,\n ): Promise<Map<string, Map<string, olmlib.IOlmSessionResult>>> {\n // map user Id → DeviceInfo[]\n const devicesByUser: Map<string, DeviceInfo[]> = new Map();\n\n for (const userId of users) {\n const userDevices: DeviceInfo[] = [];\n devicesByUser.set(userId, userDevices);\n\n const devices = this.getStoredDevicesForUser(userId) || [];\n for (const deviceInfo of devices) {\n const key = deviceInfo.getIdentityKey();\n if (key == this.olmDevice.deviceCurve25519Key) {\n // don't bother setting up session to ourself\n continue;\n }\n if (deviceInfo.verified == DeviceVerification.BLOCKED) {\n // don't bother setting up sessions with blocked users\n continue;\n }\n\n userDevices.push(deviceInfo);\n }\n }\n\n return olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, force);\n }\n\n /**\n * Get a list containing all of the room keys\n *\n * @returns a list of session export objects\n */\n public async exportRoomKeys(): Promise<IMegolmSessionData[]> {\n const exportedSessions: IMegolmSessionData[] = [];\n await this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], (txn) => {\n this.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (s) => {\n if (s === null) return;\n\n const sess = this.olmDevice.exportInboundGroupSession(s.senderKey, s.sessionId, s.sessionData!);\n delete sess.first_known_index;\n sess.algorithm = olmlib.MEGOLM_ALGORITHM;\n exportedSessions.push(sess);\n });\n });\n\n return exportedSessions;\n }\n\n /**\n * Get a JSON list containing all of the room keys\n *\n * @returns a JSON string encoding a list of session\n * export objects, each of which is an IMegolmSessionData\n */\n public async exportRoomKeysAsJson(): Promise<string> {\n return JSON.stringify(await this.exportRoomKeys());\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 * @returns a promise which resolves once the keys have been imported\n */\n public importRoomKeys(keys: IMegolmSessionData[], opts: ImportRoomKeysOpts = {}): Promise<void> {\n let successes = 0;\n let failures = 0;\n const total = keys.length;\n\n function updateProgress(): void {\n opts.progressCallback?.({\n stage: \"load_keys\",\n successes,\n failures,\n total,\n });\n }\n\n return Promise.all(\n keys.map((key) => {\n if (!key.room_id || !key.algorithm) {\n logger.warn(\"ignoring room key entry with missing fields\", key);\n failures++;\n if (opts.progressCallback) {\n updateProgress();\n }\n return null;\n }\n\n const alg = this.getRoomDecryptor(key.room_id, key.algorithm);\n return alg.importRoomKey(key, opts).finally(() => {\n successes++;\n if (opts.progressCallback) {\n updateProgress();\n }\n });\n }),\n ).then();\n }\n\n /**\n * Import a JSON string encoding a list of room keys previously\n * exported by exportRoomKeysAsJson\n *\n * @param keys - a JSON string encoding a list of session export\n * objects, 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 public async importRoomKeysAsJson(keys: string, opts?: ImportRoomKeysOpts): Promise<void> {\n return await this.importRoomKeys(JSON.parse(keys));\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns Promise which resolves to the number of sessions requiring backup\n */\n public countSessionsNeedingBackup(): Promise<number> {\n return this.backupManager.countSessionsNeedingBackup();\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n *\n * @param room - the room the event is in\n */\n public prepareToEncrypt(room: Room): void {\n const alg = this.roomEncryptors.get(room.roomId);\n if (alg) {\n alg.prepareToEncrypt(room);\n }\n }\n\n /**\n * Encrypt an event according to the configuration of the room.\n *\n * @param event - event to be sent\n *\n * @param room - destination room.\n *\n * @returns Promise which resolves when the event has been\n * encrypted, or null if nothing was needed\n */\n public async encryptEvent(event: MatrixEvent, room: Room): Promise<void> {\n const roomId = event.getRoomId()!;\n\n const alg = this.roomEncryptors.get(roomId);\n if (!alg) {\n // MatrixClient has already checked that this room should be encrypted,\n // so this is an unexpected situation.\n throw new Error(\n \"Room \" +\n roomId +\n \" was previously configured to use encryption, but is \" +\n \"no longer. Perhaps the homeserver is hiding the \" +\n \"configuration event.\",\n );\n }\n\n // wait for all the room devices to be loaded\n await this.trackRoomDevicesImpl(room);\n\n let content = event.getContent();\n // If event has an m.relates_to then we need\n // to put this on the wrapping event instead\n const mRelatesTo = content[\"m.relates_to\"];\n if (mRelatesTo) {\n // Clone content here so we don't remove `m.relates_to` from the local-echo\n content = Object.assign({}, content);\n delete content[\"m.relates_to\"];\n }\n\n // Treat element's performance metrics the same as `m.relates_to` (when present)\n const elementPerfMetrics = content[\"io.element.performance_metrics\"];\n if (elementPerfMetrics) {\n content = Object.assign({}, content);\n delete content[\"io.element.performance_metrics\"];\n }\n\n const encryptedContent = (await alg.encryptMessage(room, event.getType(), content)) as IContent;\n\n if (mRelatesTo) {\n encryptedContent[\"m.relates_to\"] = mRelatesTo;\n }\n if (elementPerfMetrics) {\n encryptedContent[\"io.element.performance_metrics\"] = elementPerfMetrics;\n }\n\n event.makeEncrypted(\n \"m.room.encrypted\",\n encryptedContent,\n this.olmDevice.deviceCurve25519Key!,\n this.olmDevice.deviceEd25519Key!,\n );\n }\n\n /**\n * Decrypt a received event\n *\n *\n * @returns resolves once we have\n * finished decrypting. Rejects with an `algorithms.DecryptionError` if there\n * is a problem decrypting the event.\n */\n public async decryptEvent(event: MatrixEvent): Promise<IEventDecryptionResult> {\n if (event.isRedacted()) {\n // Try to decrypt the redaction event, to support encrypted\n // redaction reasons. If we can't decrypt, just fall back to using\n // the original redacted_because.\n const redactionEvent = new MatrixEvent({\n room_id: event.getRoomId(),\n ...event.getUnsigned().redacted_because,\n });\n let redactedBecause: IEvent = event.getUnsigned().redacted_because!;\n if (redactionEvent.isEncrypted()) {\n try {\n const decryptedEvent = await this.decryptEvent(redactionEvent);\n redactedBecause = decryptedEvent.clearEvent as IEvent;\n } catch (e) {\n logger.warn(\"Decryption of redaction failed. Falling back to unencrypted event.\", e);\n }\n }\n\n return {\n clearEvent: {\n room_id: event.getRoomId(),\n type: \"m.room.message\",\n content: {},\n unsigned: {\n redacted_because: redactedBecause,\n },\n },\n };\n } else {\n const content = event.getWireContent();\n const alg = this.getRoomDecryptor(event.getRoomId()!, content.algorithm);\n return alg.decryptEvent(event);\n }\n }\n\n /**\n * Handle the notification from /sync that device lists have\n * been changed.\n *\n * @param deviceLists - device_lists field from /sync\n */\n public async processDeviceLists(deviceLists: IDeviceLists): Promise<void> {\n // Here, we're relying on the fact that we only ever save the sync data after\n // sucessfully saving the device list data, so we're guaranteed that the device\n // list store is at least as fresh as the sync token from the sync store, ie.\n // any device changes received in sync tokens prior to the 'next' token here\n // have been processed and are reflected in the current device list.\n // If we didn't make this assumption, we'd have to use the /keys/changes API\n // to get key changes between the sync token in the device list and the 'old'\n // sync token used here to make sure we didn't miss any.\n await this.evalDeviceListChanges(deviceLists);\n }\n\n /**\n * Send a request for some room keys, if we have not already done so\n *\n * @param resend - whether to resend the key request if there is\n * already one\n *\n * @returns a promise that resolves when the key request is queued\n */\n public requestRoomKey(\n requestBody: IRoomKeyRequestBody,\n recipients: IRoomKeyRequestRecipient[],\n resend = false,\n ): Promise<void> {\n return this.outgoingRoomKeyRequestManager\n .queueRoomKeyRequest(requestBody, recipients, resend)\n .then(() => {\n if (this.sendKeyRequestsImmediately) {\n this.outgoingRoomKeyRequestManager.sendQueuedRequests();\n }\n })\n .catch((e) => {\n // this normally means we couldn't talk to the store\n logger.error(\"Error requesting key for event\", e);\n });\n }\n\n /**\n * Cancel any earlier room key request\n *\n * @param requestBody - parameters to match for cancellation\n */\n public cancelRoomKeyRequest(requestBody: IRoomKeyRequestBody): void {\n this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody).catch((e) => {\n logger.warn(\"Error clearing pending room key requests\", e);\n });\n }\n\n /**\n * Re-send any outgoing key requests, eg after verification\n * @returns\n */\n public async cancelAndResendAllOutgoingKeyRequests(): Promise<void> {\n await this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests();\n }\n\n /**\n * handle an m.room.encryption event\n *\n * @param room - in which the event was received\n * @param event - encryption event to be processed\n */\n public async onCryptoEvent(room: Room, event: MatrixEvent): Promise<void> {\n const content = event.getContent<IRoomEncryption>();\n await this.setRoomEncryptionImpl(room, content);\n }\n\n /**\n * Called before the result of a sync is processed\n *\n * @param syncData - the data from the 'MatrixClient.sync' event\n */\n public async onSyncWillProcess(syncData: ISyncStateData): Promise<void> {\n if (!syncData.oldSyncToken) {\n // If there is no old sync token, we start all our tracking from\n // scratch, so mark everything as untracked. onCryptoEvent will\n // be called for all e2e rooms during the processing of the sync,\n // at which point we'll start tracking all the users of that room.\n logger.log(\"Initial sync performed - resetting device tracking state\");\n this.deviceList.stopTrackingAllDeviceLists();\n // we always track our own device list (for key backups etc)\n this.deviceList.startTrackingDeviceList(this.userId);\n this.roomDeviceTrackingState = {};\n }\n\n this.sendKeyRequestsImmediately = false;\n }\n\n /**\n * handle the completion of a /sync\n *\n * This is called after the processing of each successful /sync response.\n * It is an opportunity to do a batch process on the information received.\n *\n * @param syncData - the data from the 'MatrixClient.sync' event\n */\n public async onSyncCompleted(syncData: OnSyncCompletedData): Promise<void> {\n this.deviceList.setSyncToken(syncData.nextSyncToken ?? null);\n this.deviceList.saveIfDirty();\n\n // we always track our own device list (for key backups etc)\n this.deviceList.startTrackingDeviceList(this.userId);\n\n this.deviceList.refreshOutdatedDeviceLists();\n\n // we don't start uploading one-time keys until we've caught up with\n // to-device messages, to help us avoid throwing away one-time-keys that we\n // are about to receive messages for\n // (https://github.com/vector-im/element-web/issues/2782).\n if (!syncData.catchingUp) {\n this.maybeUploadOneTimeKeys();\n this.processReceivedRoomKeyRequests();\n\n // likewise don't start requesting keys until we've caught up\n // on to_device messages, otherwise we'll request keys that we're\n // just about to get.\n this.outgoingRoomKeyRequestManager.sendQueuedRequests();\n\n // Sync has finished so send key requests straight away.\n this.sendKeyRequestsImmediately = true;\n }\n }\n\n /**\n * Trigger the appropriate invalidations and removes for a given\n * device list\n *\n * @param deviceLists - device_lists field from /sync, or response from\n * /keys/changes\n */\n private async evalDeviceListChanges(deviceLists: Required<ISyncResponse>[\"device_lists\"]): Promise<void> {\n if (Array.isArray(deviceLists?.changed)) {\n deviceLists.changed.forEach((u) => {\n this.deviceList.invalidateUserDeviceList(u);\n });\n }\n\n if (Array.isArray(deviceLists?.left) && deviceLists.left.length) {\n // Check we really don't share any rooms with these users\n // any more: the server isn't required to give us the\n // exact correct set.\n const e2eUserIds = new Set(await this.getTrackedE2eUsers());\n\n deviceLists.left.forEach((u) => {\n if (!e2eUserIds.has(u)) {\n this.deviceList.stopTrackingDeviceList(u);\n }\n });\n }\n }\n\n /**\n * Get a list of all the IDs of users we share an e2e room with\n * for which we are tracking devices already\n *\n * @returns List of user IDs\n */\n private async getTrackedE2eUsers(): Promise<string[]> {\n const e2eUserIds: string[] = [];\n for (const room of this.getTrackedE2eRooms()) {\n const members = await room.getEncryptionTargetMembers();\n for (const member of members) {\n e2eUserIds.push(member.userId);\n }\n }\n return e2eUserIds;\n }\n\n /**\n * Get a list of the e2e-enabled rooms we are members of,\n * and for which we are already tracking the devices\n *\n * @returns\n */\n private getTrackedE2eRooms(): Room[] {\n return this.clientStore.getRooms().filter((room) => {\n // check for rooms with encryption enabled\n const alg = this.roomEncryptors.get(room.roomId);\n if (!alg) {\n return false;\n }\n if (!this.roomDeviceTrackingState[room.roomId]) {\n return false;\n }\n\n // ignore any rooms which we have left\n const myMembership = room.getMyMembership();\n return myMembership === KnownMembership.Join || myMembership === KnownMembership.Invite;\n });\n }\n\n /**\n * Encrypts and sends a given object via Olm to-device messages to a given\n * set of devices.\n * @param userDeviceInfoArr - the devices to send to\n * @param payload - fields to include in the encrypted payload\n * @returns Promise which\n * resolves once the message has been encrypted and sent to the given\n * userDeviceMap, and returns the `{ contentMap, deviceInfoByDeviceId }`\n * of the successfully sent messages.\n *\n * @deprecated Instead use {@link encryptToDeviceMessages} followed by {@link MatrixClient.queueToDevice}.\n */\n public async encryptAndSendToDevices(userDeviceInfoArr: IOlmDevice<DeviceInfo>[], payload: object): Promise<void> {\n try {\n const toDeviceBatch = await this.prepareToDeviceBatch(userDeviceInfoArr, payload);\n\n try {\n await this.baseApis.queueToDevice(toDeviceBatch);\n } catch (e) {\n logger.error(\"sendToDevice failed\", e);\n throw e;\n }\n } catch (e) {\n logger.error(\"encryptAndSendToDevices promises failed\", e);\n throw e;\n }\n }\n\n private async prepareToDeviceBatch(\n userDeviceInfoArr: IOlmDevice<DeviceInfo>[],\n payload: object,\n ): Promise<ToDeviceBatch> {\n const toDeviceBatch: ToDeviceBatch = {\n eventType: EventType.RoomMessageEncrypted,\n batch: [],\n };\n\n await Promise.all(\n userDeviceInfoArr.map(async ({ userId, deviceInfo }) => {\n const deviceId = deviceInfo.deviceId;\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n\n toDeviceBatch.batch.push({\n userId,\n deviceId,\n payload: encryptedContent,\n });\n\n await olmlib.ensureOlmSessionsForDevices(\n this.olmDevice,\n this.baseApis,\n new Map([[userId, [deviceInfo]]]),\n );\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n userId,\n deviceInfo,\n payload,\n );\n }),\n );\n\n // prune out any devices that encryptMessageForDevice could not encrypt for,\n // in which case it will have just not added anything to the ciphertext object.\n // There's no point sending messages to devices if we couldn't encrypt to them,\n // since that's effectively a blank message.\n toDeviceBatch.batch = toDeviceBatch.batch.filter((msg) => {\n if (Object.keys(msg.payload.ciphertext).length > 0) {\n return true;\n } else {\n logger.log(`No ciphertext for device ${msg.userId}:${msg.deviceId}: pruning`);\n return false;\n }\n });\n\n return toDeviceBatch;\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi#encryptToDeviceMessages}.\n */\n public async encryptToDeviceMessages(\n eventType: string,\n devices: { userId: string; deviceId: string }[],\n payload: ToDevicePayload,\n ): Promise<ToDeviceBatch> {\n const userIds = new Set(devices.map(({ userId }) => userId));\n const deviceInfoMap = await this.downloadKeys(Array.from(userIds), false);\n\n const userDeviceInfoArr: IOlmDevice<DeviceInfo>[] = [];\n\n devices.forEach(({ userId, deviceId }) => {\n const devices = deviceInfoMap.get(userId);\n if (!devices) {\n logger.warn(`No devices found for user ${userId}`);\n return;\n }\n\n if (devices.has(deviceId)) {\n // Send the message to a specific device\n userDeviceInfoArr.push({ userId, deviceInfo: devices.get(deviceId)! });\n } else {\n logger.warn(`No device found for user ${userId} with id ${deviceId}`);\n }\n });\n\n return this.prepareToDeviceBatch(userDeviceInfoArr, payload);\n }\n\n private onMembership = (event: MatrixEvent, member: RoomMember, oldMembership?: string): void => {\n try {\n this.onRoomMembership(event, member, oldMembership);\n } catch (e) {\n logger.error(\"Error handling membership change:\", e);\n }\n };\n\n public async preprocessToDeviceMessages(events: IToDeviceEvent[]): Promise<IToDeviceEvent[]> {\n // all we do here is filter out encrypted to-device messages with the wrong algorithm. Decryption\n // happens later in decryptEvent, via the EventMapper\n return events.filter((toDevice) => {\n if (\n toDevice.type === EventType.RoomMessageEncrypted &&\n ![\"m.olm.v1.curve25519-aes-sha2\"].includes(toDevice.content?.algorithm)\n ) {\n logger.log(\"Ignoring invalid encrypted to-device event from \" + toDevice.sender);\n return false;\n }\n return true;\n });\n }\n\n /**\n * Stores the current one_time_key count which will be handled later (in a call of\n * onSyncCompleted).\n *\n * @param currentCount - The current count of one_time_keys to be stored\n */\n private updateOneTimeKeyCount(currentCount: number): void {\n if (isFinite(currentCount)) {\n this.oneTimeKeyCount = currentCount;\n } else {\n throw new TypeError(\"Parameter for updateOneTimeKeyCount has to be a number\");\n }\n }\n\n public processKeyCounts(oneTimeKeysCounts?: Record<string, number>, unusedFallbackKeys?: string[]): Promise<void> {\n if (oneTimeKeysCounts !== undefined) {\n this.updateOneTimeKeyCount(oneTimeKeysCounts[\"signed_curve25519\"] || 0);\n }\n\n if (unusedFallbackKeys !== undefined) {\n // If `unusedFallbackKeys` is defined, that means `device_unused_fallback_key_types`\n // is present in the sync response, which indicates that the server supports fallback keys.\n //\n // If there's no unused signed_curve25519 fallback key, we need a new one.\n this.needsNewFallback = !unusedFallbackKeys.includes(\"signed_curve25519\");\n }\n\n return Promise.resolve();\n }\n\n private onToDeviceEvent = (event: MatrixEvent): void => {\n try {\n logger.log(\n `received to-device ${event.getType()} from: ` +\n `${event.getSender()} id: ${event.getContent()[ToDeviceMessageId]}`,\n );\n\n if (event.getType() == \"m.room_key\" || event.getType() == \"m.forwarded_room_key\") {\n this.onRoomKeyEvent(event);\n } else if (event.getType() == \"m.room_key_request\") {\n this.onRoomKeyRequestEvent(event);\n } else if (event.getType() === \"m.secret.request\") {\n this.secretStorage.onRequestReceived(event);\n } else if (event.getType() === \"m.secret.send\") {\n this.secretStorage.onSecretReceived(event);\n } else if (event.getType() === \"m.room_key.withheld\") {\n this.onRoomKeyWithheldEvent(event);\n } else if (event.getContent().transaction_id) {\n this.onKeyVerificationMessage(event);\n } else if (event.getContent().msgtype === \"m.bad.encrypted\") {\n this.onToDeviceBadEncrypted(event);\n } else if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {\n if (!event.isBeingDecrypted()) {\n event.attemptDecryption(this);\n }\n // once the event has been decrypted, try again\n event.once(MatrixEventEvent.Decrypted, (ev) => {\n this.onToDeviceEvent(ev);\n });\n }\n } catch (e) {\n logger.error(\"Error handling toDeviceEvent:\", e);\n }\n };\n\n /**\n * Handle a key event\n *\n * @internal\n * @param event - key event\n */\n private onRoomKeyEvent(event: MatrixEvent): void {\n const content = event.getContent();\n\n if (!content.room_id || !content.algorithm) {\n logger.error(\"key event is missing fields\");\n return;\n }\n\n if (!this.backupManager.checkedForBackup) {\n // don't bother awaiting on this - the important thing is that we retry if we\n // haven't managed to check before\n this.backupManager.checkAndStart();\n }\n\n const alg = this.getRoomDecryptor(content.room_id, content.algorithm);\n alg.onRoomKeyEvent(event);\n }\n\n /**\n * Handle a key withheld event\n *\n * @internal\n * @param event - key withheld event\n */\n private onRoomKeyWithheldEvent(event: MatrixEvent): void {\n const content = event.getContent();\n\n if (\n (content.code !== \"m.no_olm\" && (!content.room_id || !content.session_id)) ||\n !content.algorithm ||\n !content.sender_key\n ) {\n logger.error(\"key withheld event is missing fields\");\n return;\n }\n\n logger.info(\n `Got room key withheld event from ${event.getSender()} ` +\n `for ${content.algorithm} session ${content.sender_key}|${content.session_id} ` +\n `in room ${content.room_id} with code ${content.code} (${content.reason})`,\n );\n\n const alg = this.getRoomDecryptor(content.room_id, content.algorithm);\n if (alg.onRoomKeyWithheldEvent) {\n alg.onRoomKeyWithheldEvent(event);\n }\n if (!content.room_id) {\n // retry decryption for all events sent by the sender_key. This will\n // update the events to show a message indicating that the olm session was\n // wedged.\n const roomDecryptors = this.getRoomDecryptors(content.algorithm);\n for (const decryptor of roomDecryptors) {\n decryptor.retryDecryptionFromSender(content.sender_key);\n }\n }\n }\n\n /**\n * Handle a general key verification event.\n *\n * @internal\n * @param event - verification start event\n */\n private onKeyVerificationMessage(event: MatrixEvent): void {\n if (!ToDeviceChannel.validateEvent(event, this.baseApis)) {\n return;\n }\n const createRequest = (event: MatrixEvent): VerificationRequest | undefined => {\n if (!ToDeviceChannel.canCreateRequest(ToDeviceChannel.getEventType(event))) {\n return;\n }\n const content = event.getContent();\n const deviceId = content && content.from_device;\n if (!deviceId) {\n return;\n }\n const userId = event.getSender()!;\n const channel = new ToDeviceChannel(this.baseApis, userId, [deviceId]);\n return new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n };\n this.handleVerificationEvent(event, this.toDeviceVerificationRequests, createRequest);\n }\n\n /**\n * Handle key verification requests sent as timeline events\n *\n * @internal\n * @param event - the timeline event\n * @param room - not used\n * @param atStart - not used\n * @param removed - not used\n * @param whether - this is a live event\n */\n private onTimelineEvent = (\n event: MatrixEvent,\n room: Room,\n atStart: boolean,\n removed: boolean,\n { liveEvent = true } = {},\n ): void => {\n if (!InRoomChannel.validateEvent(event, this.baseApis)) {\n return;\n }\n const createRequest = (event: MatrixEvent): VerificationRequest => {\n const channel = new InRoomChannel(this.baseApis, event.getRoomId()!);\n return new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n };\n this.handleVerificationEvent(event, this.inRoomVerificationRequests, createRequest, liveEvent);\n };\n\n private async handleVerificationEvent(\n event: MatrixEvent,\n requestsMap: IRequestsMap,\n createRequest: (event: MatrixEvent) => VerificationRequest | undefined,\n isLiveEvent = true,\n ): Promise<void> {\n // Wait for event to get its final ID with pendingEventOrdering: \"chronological\", since DM channels depend on it.\n if (event.isSending() && event.status != EventStatus.SENT) {\n let eventIdListener: () => void;\n let statusListener: () => void;\n try {\n await new Promise<void>((resolve, reject) => {\n eventIdListener = resolve;\n statusListener = (): void => {\n if (event.status == EventStatus.CANCELLED) {\n reject(new Error(\"Event status set to CANCELLED.\"));\n }\n };\n event.once(MatrixEventEvent.LocalEventIdReplaced, eventIdListener);\n event.on(MatrixEventEvent.Status, statusListener);\n });\n } catch (err) {\n logger.error(\"error while waiting for the verification event to be sent: \", err);\n return;\n } finally {\n event.removeListener(MatrixEventEvent.LocalEventIdReplaced, eventIdListener!);\n event.removeListener(MatrixEventEvent.Status, statusListener!);\n }\n }\n let request: VerificationRequest | undefined = requestsMap.getRequest(event);\n let isNewRequest = false;\n if (!request) {\n request = createRequest(event);\n // a request could not be made from this event, so ignore event\n if (!request) {\n logger.log(\n `Crypto: could not find VerificationRequest for ` +\n `${event.getType()}, and could not create one, so ignoring.`,\n );\n return;\n }\n isNewRequest = true;\n requestsMap.setRequest(event, request);\n }\n event.setVerificationRequest(request);\n try {\n await request.channel.handleEvent(event, request, isLiveEvent);\n } catch (err) {\n logger.error(\"error while handling verification event\", err);\n }\n const shouldEmit =\n isNewRequest &&\n !request.initiatedByMe &&\n !request.invalid && // check it has enough events to pass the UNSENT stage\n !request.observeOnly;\n if (shouldEmit) {\n this.baseApis.emit(CryptoEvent.VerificationRequest, request);\n this.baseApis.emit(CryptoEvent.VerificationRequestReceived, request);\n }\n }\n\n /**\n * Handle a toDevice event that couldn't be decrypted\n *\n * @internal\n * @param event - undecryptable event\n */\n private async onToDeviceBadEncrypted(event: MatrixEvent): Promise<void> {\n const content = event.getWireContent();\n const sender = event.getSender();\n const algorithm = content.algorithm;\n const deviceKey = content.sender_key;\n\n this.baseApis.emit(ClientEvent.UndecryptableToDeviceEvent, event);\n\n // retry decryption for all events sent by the sender_key. This will\n // update the events to show a message indicating that the olm session was\n // wedged.\n const retryDecryption = (): void => {\n const roomDecryptors = this.getRoomDecryptors(olmlib.MEGOLM_ALGORITHM);\n for (const decryptor of roomDecryptors) {\n decryptor.retryDecryptionFromSender(deviceKey);\n }\n };\n\n if (sender === undefined || deviceKey === undefined || deviceKey === undefined) {\n return;\n }\n\n // check when we can force a new session with this device: if we've already done so\n // recently, don't do it again.\n const forceNewSessionRetryTimeDevices = this.forceNewSessionRetryTime.getOrCreate(sender);\n const forceNewSessionRetryTime = forceNewSessionRetryTimeDevices.getOrCreate(deviceKey);\n if (forceNewSessionRetryTime > Date.now()) {\n logger.debug(\n `New session already forced with device ${sender}:${deviceKey}: ` +\n `not forcing another until at least ${new Date(forceNewSessionRetryTime).toUTCString()}`,\n );\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", true);\n retryDecryption();\n return;\n }\n\n // make sure we don't retry to unwedge too soon even if we fail to create a new session\n forceNewSessionRetryTimeDevices.set(deviceKey, Date.now() + FORCE_SESSION_RETRY_INTERVAL_MS);\n\n // establish a new olm session with this device since we're failing to decrypt messages\n // on a current session.\n // Note that an undecryptable message from another device could easily be spoofed -\n // is there anything we can do to mitigate this?\n let device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey);\n if (!device) {\n // if we don't know about the device, fetch the user's devices again\n // and retry before giving up\n await this.downloadKeys([sender], false);\n device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey);\n if (!device) {\n logger.info(\"Couldn't find device for identity key \" + deviceKey + \": not re-establishing session\");\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", false);\n retryDecryption();\n return;\n }\n }\n const devicesByUser = new Map([[sender, [device]]]);\n await olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, true);\n\n forceNewSessionRetryTimeDevices.set(deviceKey, Date.now() + MIN_FORCE_SESSION_INTERVAL_MS);\n\n // Now send a blank message on that session so the other side knows about it.\n // (The keyshare request is sent in the clear so that won't do)\n // We send this first such that, as long as the toDevice messages arrive in the\n // same order we sent them, the other end will get this first, set up the new session,\n // then get the keyshare request and send the key over this new session (because it\n // is the session it has most recently received a message on).\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n sender,\n device,\n { type: \"m.dummy\" },\n );\n\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", true);\n retryDecryption();\n\n await this.baseApis.sendToDevice(\n \"m.room.encrypted\",\n new Map([[sender, new Map([[device.deviceId, encryptedContent]])]]),\n );\n\n // Most of the time this probably won't be necessary since we'll have queued up a key request when\n // we failed to decrypt the message and will be waiting a bit for the key to arrive before sending\n // it. This won't always be the case though so we need to re-send any that have already been sent\n // to avoid races.\n const requestsToResend = await this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(\n sender,\n device.deviceId,\n );\n for (const keyReq of requestsToResend) {\n this.requestRoomKey(keyReq.requestBody, keyReq.recipients, true);\n }\n }\n\n /**\n * Handle a change in the membership state of a member of a room\n *\n * @internal\n * @param event - event causing the change\n * @param member - user whose membership changed\n * @param oldMembership - previous membership\n */\n private onRoomMembership(event: MatrixEvent, member: RoomMember, oldMembership?: string): void {\n // this event handler is registered on the *client* (as opposed to the room\n // member itself), which means it is only called on changes to the *live*\n // membership state (ie, it is not called when we back-paginate, nor when\n // we load the state in the initialsync).\n //\n // Further, it is automatically registered and called when new members\n // arrive in the room.\n\n const roomId = member.roomId;\n\n const alg = this.roomEncryptors.get(roomId);\n if (!alg) {\n // not encrypting in this room\n return;\n }\n // only mark users in this room as tracked if we already started tracking in this room\n // this way we don't start device queries after sync on behalf of this room which we won't use\n // the result of anyway, as we'll need to do a query again once all the members are fetched\n // by calling _trackRoomDevices\n if (roomId in this.roomDeviceTrackingState) {\n if (member.membership == KnownMembership.Join) {\n logger.log(\"Join event for \" + member.userId + \" in \" + roomId);\n // make sure we are tracking the deviceList for this user\n this.deviceList.startTrackingDeviceList(member.userId);\n } else if (\n member.membership == KnownMembership.Invite &&\n this.clientStore.getRoom(roomId)?.shouldEncryptForInvitedMembers()\n ) {\n logger.log(\"Invite event for \" + member.userId + \" in \" + roomId);\n this.deviceList.startTrackingDeviceList(member.userId);\n }\n }\n\n alg.onRoomMembership(event, member, oldMembership);\n }\n\n /**\n * Called when we get an m.room_key_request event.\n *\n * @internal\n * @param event - key request event\n */\n private onRoomKeyRequestEvent(event: MatrixEvent): void {\n const content = event.getContent();\n if (content.action === \"request\") {\n // Queue it up for now, because they tend to arrive before the room state\n // events at initial sync, and we want to see if we know anything about the\n // room before passing them on to the app.\n const req = new IncomingRoomKeyRequest(event);\n this.receivedRoomKeyRequests.push(req);\n } else if (content.action === \"request_cancellation\") {\n const req = new IncomingRoomKeyRequestCancellation(event);\n this.receivedRoomKeyRequestCancellations.push(req);\n }\n }\n\n /**\n * Process any m.room_key_request events which were queued up during the\n * current sync.\n *\n * @internal\n */\n private async processReceivedRoomKeyRequests(): Promise<void> {\n if (this.processingRoomKeyRequests) {\n // we're still processing last time's requests; keep queuing new ones\n // up for now.\n return;\n }\n this.processingRoomKeyRequests = true;\n\n try {\n // we need to grab and clear the queues in the synchronous bit of this method,\n // so that we don't end up racing with the next /sync.\n const requests = this.receivedRoomKeyRequests;\n this.receivedRoomKeyRequests = [];\n const cancellations = this.receivedRoomKeyRequestCancellations;\n this.receivedRoomKeyRequestCancellations = [];\n\n // Process all of the requests, *then* all of the cancellations.\n //\n // This makes sure that if we get a request and its cancellation in the\n // same /sync result, then we process the request before the\n // cancellation (and end up with a cancelled request), rather than the\n // cancellation before the request (and end up with an outstanding\n // request which should have been cancelled.)\n await Promise.all(requests.map((req) => this.processReceivedRoomKeyRequest(req)));\n await Promise.all(\n cancellations.map((cancellation) => this.processReceivedRoomKeyRequestCancellation(cancellation)),\n );\n } catch (e) {\n logger.error(`Error processing room key requsts: ${e}`);\n } finally {\n this.processingRoomKeyRequests = false;\n }\n }\n\n /**\n * Helper for processReceivedRoomKeyRequests\n *\n */\n private async processReceivedRoomKeyRequest(req: IncomingRoomKeyRequest): Promise<void> {\n const userId = req.userId;\n const deviceId = req.deviceId;\n\n const body = req.requestBody;\n const roomId = body.room_id;\n const alg = body.algorithm;\n\n logger.log(\n `m.room_key_request from ${userId}:${deviceId}` +\n ` for ${roomId} / ${body.session_id} (id ${req.requestId})`,\n );\n\n if (userId !== this.userId) {\n if (!this.roomEncryptors.get(roomId)) {\n logger.debug(`room key request for unencrypted room ${roomId}`);\n return;\n }\n const encryptor = this.roomEncryptors.get(roomId)!;\n const device = this.deviceList.getStoredDevice(userId, deviceId);\n if (!device) {\n logger.debug(`Ignoring keyshare for unknown device ${userId}:${deviceId}`);\n return;\n }\n\n try {\n await encryptor.reshareKeyWithDevice!(body.sender_key, body.session_id, userId, device);\n } catch (e) {\n logger.warn(\n \"Failed to re-share keys for session \" +\n body.session_id +\n \" with device \" +\n userId +\n \":\" +\n device.deviceId,\n e,\n );\n }\n return;\n }\n\n if (deviceId === this.deviceId) {\n // We'll always get these because we send room key requests to\n // '*' (ie. 'all devices') which includes the sending device,\n // so ignore requests from ourself because apart from it being\n // very silly, it won't work because an Olm session cannot send\n // messages to itself.\n // The log here is probably superfluous since we know this will\n // always happen, but let's log anyway for now just in case it\n // causes issues.\n logger.log(\"Ignoring room key request from ourselves\");\n return;\n }\n\n // todo: should we queue up requests we don't yet have keys for,\n // in case they turn up later?\n\n // if we don't have a decryptor for this room/alg, we don't have\n // the keys for the requested events, and can drop the requests.\n if (!this.roomDecryptors.has(roomId)) {\n logger.log(`room key request for unencrypted room ${roomId}`);\n return;\n }\n\n const decryptor = this.roomDecryptors.get(roomId)!.get(alg);\n if (!decryptor) {\n logger.log(`room key request for unknown alg ${alg} in room ${roomId}`);\n return;\n }\n\n if (!(await decryptor.hasKeysForKeyRequest(req))) {\n logger.log(`room key request for unknown session ${roomId} / ` + body.session_id);\n return;\n }\n\n req.share = (): void => {\n decryptor.shareKeysWithDevice(req);\n };\n\n // if the device is verified already, share the keys\n if (this.checkDeviceTrust(userId, deviceId).isVerified()) {\n logger.log(\"device is already verified: sharing keys\");\n req.share();\n return;\n }\n\n this.emit(CryptoEvent.RoomKeyRequest, req);\n }\n\n /**\n * Helper for processReceivedRoomKeyRequests\n *\n */\n private async processReceivedRoomKeyRequestCancellation(\n cancellation: IncomingRoomKeyRequestCancellation,\n ): Promise<void> {\n logger.log(\n `m.room_key_request cancellation for ${cancellation.userId}:` +\n `${cancellation.deviceId} (id ${cancellation.requestId})`,\n );\n\n // we should probably only notify the app of cancellations we told it\n // about, but we don't currently have a record of that, so we just pass\n // everything through.\n this.emit(CryptoEvent.RoomKeyRequestCancellation, cancellation);\n }\n\n /**\n * Get a decryptor for a given room and algorithm.\n *\n * If we already have a decryptor for the given room and algorithm, return\n * it. Otherwise try to instantiate it.\n *\n * @internal\n *\n * @param roomId - room id for decryptor. If undefined, a temporary\n * decryptor is instantiated.\n *\n * @param algorithm - crypto algorithm\n *\n * @throws `DecryptionError` if the algorithm is unknown\n */\n public getRoomDecryptor(roomId: string | null, algorithm: string): DecryptionAlgorithm {\n let decryptors: Map<string, DecryptionAlgorithm> | undefined;\n let alg: DecryptionAlgorithm | undefined;\n\n if (roomId) {\n decryptors = this.roomDecryptors.get(roomId);\n if (!decryptors) {\n decryptors = new Map<string, DecryptionAlgorithm>();\n this.roomDecryptors.set(roomId, decryptors);\n }\n\n alg = decryptors.get(algorithm);\n if (alg) {\n return alg;\n }\n }\n\n const AlgClass = algorithms.DECRYPTION_CLASSES.get(algorithm);\n if (!AlgClass) {\n throw new DecryptionError(\n DecryptionFailureCode.UNKNOWN_ENCRYPTION_ALGORITHM,\n 'Unknown encryption algorithm \"' + algorithm + '\".',\n );\n }\n alg = new AlgClass({\n userId: this.userId,\n crypto: this,\n olmDevice: this.olmDevice,\n baseApis: this.baseApis,\n roomId: roomId ?? undefined,\n });\n\n if (decryptors) {\n decryptors.set(algorithm, alg);\n }\n return alg;\n }\n\n /**\n * Get all the room decryptors for a given encryption algorithm.\n *\n * @param algorithm - The encryption algorithm\n *\n * @returns An array of room decryptors\n */\n private getRoomDecryptors(algorithm: string): DecryptionAlgorithm[] {\n const decryptors: DecryptionAlgorithm[] = [];\n for (const d of this.roomDecryptors.values()) {\n if (d.has(algorithm)) {\n decryptors.push(d.get(algorithm)!);\n }\n }\n return decryptors;\n }\n\n /**\n * sign the given object with our ed25519 key\n *\n * @param obj - Object to which we will add a 'signatures' property\n */\n public async signObject<T extends ISignableObject & object>(obj: T): Promise<void> {\n const sigs = new Map(Object.entries(obj.signatures || {}));\n const unsigned = obj.unsigned;\n\n delete obj.signatures;\n delete obj.unsigned;\n\n const userSignatures = sigs.get(this.userId) || {};\n sigs.set(this.userId, userSignatures);\n userSignatures[\"ed25519:\" + this.deviceId] = await this.olmDevice.sign(anotherjson.stringify(obj));\n obj.signatures = recursiveMapToObject(sigs);\n if (unsigned !== undefined) obj.unsigned = unsigned;\n }\n\n /**\n * @returns true if the room with the supplied ID is encrypted. False if the\n * room is not encrypted, or is unknown to us.\n */\n public isRoomEncrypted(roomId: string): boolean {\n return this.roomList.isRoomEncrypted(roomId);\n }\n\n /**\n * Implementation of {@link Crypto.CryptoApi#isEncryptionEnabledInRoom}.\n */\n public async isEncryptionEnabledInRoom(roomId: string): Promise<boolean> {\n return this.isRoomEncrypted(roomId);\n }\n\n /**\n * @returns information about the encryption on the room with the supplied\n * ID, or null if the room is not encrypted or unknown to us.\n */\n public getRoomEncryption(roomId: string): IRoomEncryption | null {\n return this.roomList.getRoomEncryption(roomId);\n }\n\n /**\n * Returns whether dehydrated devices are supported by the crypto backend\n * and by the server.\n */\n public async isDehydrationSupported(): Promise<boolean> {\n return false;\n }\n\n /**\n * Stub function -- dehydration is not implemented here, so throw error\n */\n public async startDehydration(createNewKey?: boolean): Promise<void> {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Stub function -- restoreKeyBackup is not implemented here, so throw error\n */\n public restoreKeyBackup(opts: KeyBackupRestoreOpts): Promise<KeyBackupRestoreResult> {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Stub function -- restoreKeyBackupWithPassphrase is not implemented here, so throw error\n */\n public restoreKeyBackupWithPassphrase(\n passphrase: string,\n opts: KeyBackupRestoreOpts,\n ): Promise<KeyBackupRestoreResult> {\n throw new Error(\"Not implemented\");\n }\n}\n\n/**\n * Fix up the backup key, that may be in the wrong format due to a bug in a\n * migration step. Some backup keys were stored as a comma-separated list of\n * integers, rather than a base64-encoded byte array. If this function is\n * passed a string that looks like a list of integers rather than a base64\n * string, it will attempt to convert it to the right format.\n *\n * @param key - the key to check\n * @returns If the key is in the wrong format, then the fixed\n * key will be returned. Otherwise null will be returned.\n *\n */\nexport function fixBackupKey(key?: string): string | null {\n if (typeof key !== \"string\" || key.indexOf(\",\") < 0) {\n return null;\n }\n const fixedKey = Uint8Array.from(key.split(\",\"), (x) => parseInt(x));\n return encodeBase64(fixedKey);\n}\n\n/**\n * Represents a received m.room_key_request event\n */\nexport class IncomingRoomKeyRequest {\n /** user requesting the key */\n public readonly userId: string;\n /** device requesting the key */\n public readonly deviceId: string;\n /** unique id for the request */\n public readonly requestId: string;\n public readonly requestBody: IRoomKeyRequestBody;\n /**\n * callback which, when called, will ask\n * the relevant crypto algorithm implementation to share the keys for\n * this request.\n */\n public share: () => void;\n\n public constructor(event: MatrixEvent) {\n const content = event.getContent();\n\n this.userId = event.getSender()!;\n this.deviceId = content.requesting_device_id;\n this.requestId = content.request_id;\n this.requestBody = content.body || {};\n this.share = (): void => {\n throw new Error(\"don't know how to share keys for this request yet\");\n };\n }\n}\n\n/**\n * Represents a received m.room_key_request cancellation\n */\nclass IncomingRoomKeyRequestCancellation {\n /** user requesting the cancellation */\n public readonly userId: string;\n /** device requesting the cancellation */\n public readonly deviceId: string;\n /** unique id for the request to be cancelled */\n public readonly requestId: string;\n\n public constructor(event: MatrixEvent) {\n const content = event.getContent();\n\n this.userId = event.getSender()!;\n this.deviceId = content.requesting_device_id;\n this.requestId = content.request_id;\n }\n}\n\n// a number of types are re-exported for backwards compatibility, in case any applications are referencing it.\nexport type { IEventDecryptionResult, IMegolmSessionData } from \"../@types/crypto.ts\";\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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