matrix-js-sdk 41.5.0 → 41.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/lib/ReEmitter.js +1 -1
  3. package/lib/ReEmitter.js.map +1 -1
  4. package/lib/ToDeviceMessageQueue.js +2 -2
  5. package/lib/ToDeviceMessageQueue.js.map +1 -1
  6. package/lib/autodiscovery.js +0 -1
  7. package/lib/autodiscovery.js.map +1 -1
  8. package/lib/client.js +112 -165
  9. package/lib/client.js.map +1 -1
  10. package/lib/common-crypto/CryptoBackend.js +0 -2
  11. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  12. package/lib/content-helpers.js +3 -5
  13. package/lib/content-helpers.js.map +1 -1
  14. package/lib/content-repo.js +7 -1
  15. package/lib/content-repo.js.map +1 -1
  16. package/lib/crypto/store/indexeddb-crypto-store-backend.js +9 -11
  17. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  18. package/lib/crypto/store/indexeddb-crypto-store.js +0 -2
  19. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  20. package/lib/crypto/store/localStorage-crypto-store.js +11 -9
  21. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  22. package/lib/crypto/store/memory-crypto-store.js +11 -9
  23. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  24. package/lib/crypto-api/index.js +58 -58
  25. package/lib/crypto-api/index.js.map +1 -1
  26. package/lib/embedded.js +29 -45
  27. package/lib/embedded.js.map +1 -1
  28. package/lib/extensible_events_v1/MessageEvent.js +15 -15
  29. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  30. package/lib/extensible_events_v1/PollEndEvent.js +8 -8
  31. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  32. package/lib/extensible_events_v1/PollResponseEvent.js +0 -1
  33. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  34. package/lib/extensible_events_v1/PollStartEvent.js +28 -28
  35. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  36. package/lib/feature.js +5 -1
  37. package/lib/feature.js.map +1 -1
  38. package/lib/filter-component.js +4 -1
  39. package/lib/filter-component.js.map +1 -1
  40. package/lib/filter.js +1 -3
  41. package/lib/filter.js.map +1 -1
  42. package/lib/http-api/errors.js +20 -16
  43. package/lib/http-api/errors.js.map +1 -1
  44. package/lib/http-api/fetch.js +4 -6
  45. package/lib/http-api/fetch.js.map +1 -1
  46. package/lib/http-api/refresh.js +10 -12
  47. package/lib/http-api/refresh.js.map +1 -1
  48. package/lib/interactive-auth.js +1 -11
  49. package/lib/interactive-auth.js.map +1 -1
  50. package/lib/logger.js +0 -2
  51. package/lib/logger.js.map +1 -1
  52. package/lib/matrixrtc/CallMembership.js +43 -57
  53. package/lib/matrixrtc/CallMembership.js.map +1 -1
  54. package/lib/matrixrtc/MatrixRTCSession.js +19 -24
  55. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  56. package/lib/matrixrtc/MatrixRTCSessionManager.js +2 -3
  57. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  58. package/lib/matrixrtc/MembershipManager.js +23 -30
  59. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  60. package/lib/matrixrtc/MembershipManagerActionScheduler.js +1 -2
  61. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  62. package/lib/matrixrtc/RTCEncryptionManager.js +8 -11
  63. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  64. package/lib/matrixrtc/ToDeviceKeyTransport.js +4 -4
  65. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  66. package/lib/matrixrtc/utils.js +7 -1
  67. package/lib/matrixrtc/utils.js.map +1 -1
  68. package/lib/models/MSC3089TreeSpace.js +5 -7
  69. package/lib/models/MSC3089TreeSpace.js.map +1 -1
  70. package/lib/models/beacon.js +5 -11
  71. package/lib/models/beacon.js.map +1 -1
  72. package/lib/models/device.js +0 -7
  73. package/lib/models/device.js.map +1 -1
  74. package/lib/models/event-context.js +1 -2
  75. package/lib/models/event-context.js.map +1 -1
  76. package/lib/models/event-timeline-set.js +16 -26
  77. package/lib/models/event-timeline-set.js.map +1 -1
  78. package/lib/models/event-timeline.js +8 -15
  79. package/lib/models/event-timeline.js.map +1 -1
  80. package/lib/models/event.js +20 -37
  81. package/lib/models/event.js.map +1 -1
  82. package/lib/models/invites-ignorer.js +8 -12
  83. package/lib/models/invites-ignorer.js.map +1 -1
  84. package/lib/models/poll.js +7 -13
  85. package/lib/models/poll.js.map +1 -1
  86. package/lib/models/read-receipt.js +8 -4
  87. package/lib/models/read-receipt.js.map +1 -1
  88. package/lib/models/related-relations.js +0 -2
  89. package/lib/models/related-relations.js.map +1 -1
  90. package/lib/models/relations-container.js +4 -6
  91. package/lib/models/relations-container.js.map +1 -1
  92. package/lib/models/relations.js +7 -10
  93. package/lib/models/relations.js.map +1 -1
  94. package/lib/models/room-member.js +2 -24
  95. package/lib/models/room-member.js.map +1 -1
  96. package/lib/models/room-receipts.js +25 -22
  97. package/lib/models/room-receipts.js.map +1 -1
  98. package/lib/models/room-state.js +2 -2
  99. package/lib/models/room-state.js.map +1 -1
  100. package/lib/models/room-sticky-events.js +20 -5
  101. package/lib/models/room-sticky-events.js.map +1 -1
  102. package/lib/models/room.js +82 -105
  103. package/lib/models/room.js.map +1 -1
  104. package/lib/models/thread.js +12 -57
  105. package/lib/models/thread.js.map +1 -1
  106. package/lib/models/user.js +1 -20
  107. package/lib/models/user.js.map +1 -1
  108. package/lib/oidc/authorize.js +23 -32
  109. package/lib/oidc/authorize.js.map +1 -1
  110. package/lib/oidc/tokenRefresher.js +8 -11
  111. package/lib/oidc/tokenRefresher.js.map +1 -1
  112. package/lib/pushprocessor.js +8 -5
  113. package/lib/pushprocessor.js.map +1 -1
  114. package/lib/receipt-accumulator.js +12 -3
  115. package/lib/receipt-accumulator.js.map +1 -1
  116. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  117. package/lib/rendezvous/MSC4108SignInWithQR.js +10 -23
  118. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  119. package/lib/rendezvous/channels/MSC4108SecureChannel.js +5 -10
  120. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  121. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +5 -15
  122. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  123. package/lib/room-hierarchy.js +7 -12
  124. package/lib/room-hierarchy.js.map +1 -1
  125. package/lib/rust-crypto/DehydratedDeviceManager.js +2 -3
  126. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  127. package/lib/rust-crypto/KeyClaimManager.js +1 -2
  128. package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
  129. package/lib/rust-crypto/OutgoingRequestProcessor.js +11 -4
  130. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  131. package/lib/rust-crypto/OutgoingRequestsManager.js +12 -12
  132. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  133. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +3 -5
  134. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  135. package/lib/rust-crypto/RoomEncryptor.js +6 -6
  136. package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
  137. package/lib/rust-crypto/backup.js +22 -16
  138. package/lib/rust-crypto/backup.js.map +1 -1
  139. package/lib/rust-crypto/device-converter.js +13 -4
  140. package/lib/rust-crypto/device-converter.js.map +1 -1
  141. package/lib/rust-crypto/index.js +1 -3
  142. package/lib/rust-crypto/index.js.map +1 -1
  143. package/lib/rust-crypto/libolm_migration.js +13 -15
  144. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  145. package/lib/rust-crypto/rust-crypto.js +52 -59
  146. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  147. package/lib/rust-crypto/verification.js +10 -10
  148. package/lib/rust-crypto/verification.js.map +1 -1
  149. package/lib/scheduler.js +2 -2
  150. package/lib/scheduler.js.map +1 -1
  151. package/lib/secret-storage.js +16 -10
  152. package/lib/secret-storage.js.map +1 -1
  153. package/lib/serverCapabilities.js +2 -5
  154. package/lib/serverCapabilities.js.map +1 -1
  155. package/lib/sliding-sync-sdk.js +4 -9
  156. package/lib/sliding-sync-sdk.js.map +1 -1
  157. package/lib/sliding-sync.js +4 -9
  158. package/lib/sliding-sync.js.map +1 -1
  159. package/lib/store/indexeddb-local-backend.js +13 -8
  160. package/lib/store/indexeddb-local-backend.js.map +1 -1
  161. package/lib/store/indexeddb-remote-backend.js +6 -7
  162. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  163. package/lib/store/indexeddb-store-worker.js +1 -2
  164. package/lib/store/indexeddb-store-worker.js.map +1 -1
  165. package/lib/store/indexeddb.js +4 -2
  166. package/lib/store/indexeddb.js.map +1 -1
  167. package/lib/store/memory.js +0 -4
  168. package/lib/store/memory.js.map +1 -1
  169. package/lib/sync-accumulator.js +2 -4
  170. package/lib/sync-accumulator.js.map +1 -1
  171. package/lib/sync.js +36 -43
  172. package/lib/sync.js.map +1 -1
  173. package/lib/timeline-window.js +2 -6
  174. package/lib/timeline-window.js.map +1 -1
  175. package/lib/utils/decryptAESSecretStorageItem.js +5 -1
  176. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  177. package/lib/utils/encryptAESSecretStorageItem.js +5 -1
  178. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  179. package/lib/utils.js +35 -20
  180. package/lib/utils.js.map +1 -1
  181. package/lib/webrtc/call.js +13 -45
  182. package/lib/webrtc/call.js.map +1 -1
  183. package/lib/webrtc/callEventHandler.js +0 -5
  184. package/lib/webrtc/callEventHandler.js.map +1 -1
  185. package/lib/webrtc/callFeed.js +0 -15
  186. package/lib/webrtc/callFeed.js.map +1 -1
  187. package/lib/webrtc/groupCall.js +82 -89
  188. package/lib/webrtc/groupCall.js.map +1 -1
  189. package/lib/webrtc/groupCallEventHandler.js +6 -7
  190. package/lib/webrtc/groupCallEventHandler.js.map +1 -1
  191. package/lib/webrtc/mediaHandler.js +8 -15
  192. package/lib/webrtc/mediaHandler.js.map +1 -1
  193. package/lib/webrtc/stats/callStatsReportGatherer.js +2 -5
  194. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  195. package/lib/webrtc/stats/connectionStatsReportBuilder.js +5 -1
  196. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  197. package/lib/webrtc/stats/groupCallStats.js +3 -4
  198. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  199. package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
  200. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  201. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +1 -1
  202. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  203. package/package.json +3 -3
  204. package/src/rendezvous/MSC4108SignInWithQR.ts +2 -1
@@ -1,4 +1,3 @@
1
- import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
1
  /*
3
2
  Copyright 2022 The Matrix.org Foundation C.I.C.
4
3
 
@@ -53,7 +52,6 @@ export class DecryptionError extends Error {
53
52
  constructor(code, msg, details) {
54
53
  super(msg);
55
54
  this.code = code;
56
- _defineProperty(this, "detailedString", void 0);
57
55
  this.name = "DecryptionError";
58
56
  this.detailedString = detailedStringForDecryptionError(this, details);
59
57
  }
@@ -1 +1 @@
1
- {"version":3,"file":"CryptoBackend.js","names":["DecryptionError","Error","constructor","code","msg","details","_defineProperty","name","detailedString","detailedStringForDecryptionError","err","result","message","Object","keys","map","k","join"],"sources":["../../src/common-crypto/CryptoBackend.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type { IDeviceLists, IToDeviceEvent, ReceivedToDeviceMessage } from \"../sync-accumulator.ts\";\nimport { type IClearEvent, type MatrixEvent } from \"../models/event.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { type CryptoApi, type DecryptionFailureCode, type ImportRoomKeysOpts } from \"../crypto-api/index.ts\";\nimport { type KeyBackupInfo, type KeyBackupSession } from \"../crypto-api/keybackup.ts\";\nimport { type IMegolmSessionData } from \"../@types/crypto.ts\";\n\n/**\n * Common interface for the crypto implementations\n *\n * @internal\n */\nexport interface CryptoBackend extends SyncCryptoCallbacks, CryptoApi {\n /**\n * Whether sendMessage in a room with unknown and unverified devices\n * should throw an error and not send the message. This has 'Global' for\n * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently\n * no room-level equivalent for this setting.\n *\n * @remarks This has no effect in Rust Crypto; it exists only for the sake of\n * the accessors in MatrixClient.\n */\n globalErrorOnUnknownDevices: boolean;\n\n /**\n * Shut down any background processes related to crypto\n */\n stop(): void;\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 encryptEvent(event: MatrixEvent, room: Room): Promise<void>;\n\n /**\n * Decrypt a received event\n *\n * @returns a promise which resolves once we have finished decrypting.\n * Rejects with an error if there is a problem decrypting the event.\n */\n decryptEvent(event: MatrixEvent): Promise<EventDecryptionResult>;\n\n /**\n * Get a backup decryptor capable of decrypting megolm session data encrypted with the given backup information.\n * @param backupInfo - The backup information\n * @param privKey - The private decryption key.\n */\n getBackupDecryptor(backupInfo: KeyBackupInfo, privKey: Uint8Array): Promise<BackupDecryptor>;\n\n /**\n * Import a list of room keys restored from backup\n *\n * @param keys - a list of session export objects\n * @param backupVersion - the version of the backup these keys came from.\n * @param opts - options object\n * @returns a promise which resolves once the keys have been imported\n */\n importBackedUpRoomKeys(keys: IMegolmSessionData[], backupVersion: string, opts?: ImportRoomKeysOpts): Promise<void>;\n\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n //\n // Room key history sharing (MSC4268)\n //\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n /**\n * Share any shareable E2EE history in the given room with the given recipient,\n * as per [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)\n */\n shareRoomHistoryWithUser(roomId: string, userId: string): Promise<void>;\n\n /**\n * Having accepted an invite for the given room from the given user, attempt to\n * find information about a room key bundle and, if found, download the\n * bundle and import the room keys, as per {@link https://github.com/matrix-org/matrix-spec-proposals/pull/4268|MSC4268}.\n *\n * @param roomId - The room we were invited to, for which we want to check if a room\n * key bundle was received.\n *\n * @param inviter - The user who invited us to the room and is expected to have\n * sent the room key bundle.\n *\n * @returns `true` if the key bundle was successfuly downloaded and imported.\n */\n maybeAcceptKeyBundle(roomId: string, inviter: string): Promise<boolean>;\n\n /**\n * Mark a room as pending a key bundle under MSC4268. The backend will listen for room key bundle messages, and if\n * it sees one matching the room specified, it will automatically import it as long as the message author's ID matches\n * the inviter's ID.\n *\n * @param roomId - The room we were invited to, for which we did not receive a key bundle before accepting the invite.\n * @param inviterId - The user who invited us to the room and is expected to send the room key bundle.\n */\n markRoomAsPendingKeyBundle(roomId: string, inviterId: string): Promise<void>;\n}\n\n/** The methods which crypto implementations should expose to the Sync api\n *\n * @internal\n */\nexport interface SyncCryptoCallbacks {\n /**\n * Called by the /sync loop whenever there are incoming to-device messages.\n *\n * The implementation may preprocess the received messages (eg, decrypt them) and return an\n * updated list of messages for dispatch to the rest of the system.\n *\n * Note that, unlike {@link ClientEvent.ToDeviceEvent} events, this is called on the raw to-device\n * messages, rather than the results of any decryption attempts.\n *\n * @param events - the received to-device messages\n * @returns A list of preprocessed to-device messages. This will not map 1:1 to the input list, as some messages may be invalid or\n * failed to decrypt, and so will be omitted from the output list.\n *\n */\n preprocessToDeviceMessages(events: IToDeviceEvent[]): Promise<ReceivedToDeviceMessage[]>;\n\n /**\n * Called by the /sync loop when one time key counts and unused fallback key details are received.\n *\n * @param oneTimeKeysCounts - the received one time key counts\n * @param unusedFallbackKeys - the received unused fallback keys\n */\n processKeyCounts(oneTimeKeysCounts?: Record<string, number>, unusedFallbackKeys?: string[]): Promise<void>;\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 processDeviceLists(deviceLists: IDeviceLists): Promise<void>;\n\n /**\n * Called by the /sync loop whenever an m.room.encryption event is received.\n *\n * This is called before RoomStateEvents are emitted for any of the events in the /sync\n * response (even if the other events technically happened first). This works around a problem\n * if the client uses a RoomStateEvent (typically a membership event) as a trigger to send a message\n * in a new room (or one where encryption has been newly enabled): that would otherwise leave the\n * crypto layer confused because it expects crypto to be set up, but it has not yet been.\n *\n * @param room - in which the event was received\n * @param event - encryption event to be processed\n */\n onCryptoEvent(room: Room, event: MatrixEvent): Promise<void>;\n\n /**\n * Called by the /sync loop after each /sync response is processed.\n *\n * Used to complete batch processing, or to initiate background processes\n *\n * @param syncState - information about the completed sync.\n */\n onSyncCompleted(syncState: OnSyncCompletedData): void;\n\n /**\n * Mark all tracked users' device lists as dirty.\n *\n * This method will cause additional `/keys/query` requests on the server, so should be used only\n * when the client has desynced tracking device list deltas from the server.\n * In MSC4186: Simplified Sliding Sync, this can happen when the server expires the connection.\n */\n markAllTrackedUsersAsDirty(): Promise<void>;\n}\n\n/**\n * @internal\n */\nexport interface OnSyncCompletedData {\n /**\n * The 'next_batch' result from /sync, which will become the 'since' token for the next call to /sync.\n */\n nextSyncToken?: string;\n\n /**\n * True if we are working our way through a backlog of events after connecting.\n */\n catchingUp?: boolean;\n}\n\n/**\n * The result of a (successful) call to {@link CryptoBackend.decryptEvent}\n */\nexport interface EventDecryptionResult {\n /**\n * The plaintext payload for the event (typically containing <tt>type</tt> and <tt>content</tt> fields).\n */\n clearEvent: IClearEvent;\n /**\n * No longer used.\n * See {@link MatrixEvent#getForwardingCurve25519KeyChain}.\n * @deprecated\n */\n forwardingCurve25519KeyChain?: string[];\n /**\n * Key owned by the sender of this event. See {@link MatrixEvent#getSenderKey}.\n */\n senderCurve25519Key?: string;\n /**\n * ed25519 key claimed by the sender of this event. See {@link MatrixEvent#getClaimedEd25519Key}.\n */\n claimedEd25519Key?: string;\n\n /**\n * If another user forwarded the key to this message\n * (eg via [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)),\n * the ID of that user.\n */\n keyForwardedBy?: string;\n}\n\n/**\n * Responsible for decrypting megolm session data retrieved from a remote backup.\n * The result of {@link CryptoBackend#getBackupDecryptor}.\n */\nexport interface BackupDecryptor {\n /**\n * Whether keys retrieved from this backup can be trusted.\n *\n * Depending on the backup algorithm, keys retrieved from the backup can be trusted or not.\n * If false, keys retrieved from the backup must be considered unsafe (authenticity cannot be guaranteed).\n * It could be by design (deniability) or for some technical reason (eg asymmetric encryption).\n */\n readonly sourceTrusted: boolean;\n\n /**\n *\n * Decrypt megolm session data retrieved from backup.\n *\n * @param ciphertexts - a Record of sessionId to session data.\n *\n * @returns An array of decrypted `IMegolmSessionData`\n */\n decryptSessions(ciphertexts: Record<string, KeyBackupSession>): Promise<IMegolmSessionData[]>;\n\n /**\n * Free any resources held by this decryptor.\n *\n * Should be called once the decryptor is no longer needed.\n */\n free(): void;\n}\n\n/**\n * Exception thrown when decryption fails\n *\n * @param code - Reason code for the failure.\n *\n * @param msg - user-visible message describing the problem\n *\n * @param details - key/value pairs reported in the logs but not shown\n * to the user.\n */\nexport class DecryptionError extends Error {\n public readonly detailedString: string;\n\n public constructor(\n public readonly code: DecryptionFailureCode,\n msg: string,\n details?: Record<string, string | Error>,\n ) {\n super(msg);\n this.name = \"DecryptionError\";\n this.detailedString = detailedStringForDecryptionError(this, details);\n }\n}\n\nfunction detailedStringForDecryptionError(err: DecryptionError, details?: Record<string, string | Error>): string {\n let result = err.name + \"[msg: \" + err.message;\n\n if (details) {\n result +=\n \", \" +\n Object.keys(details)\n .map((k) => k + \": \" + details[k])\n .join(\", \");\n }\n\n result += \"]\";\n\n return result;\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACA;;AA6FA;AACA;AACA;AACA;;AAmEA;AACA;AACA;;AAaA;AACA;AACA;;AA6BA;AACA;AACA;AACA;;AA6BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMA,eAAe,SAASC,KAAK,CAAC;EAGhCC,WAAWA,CACEC,IAA2B,EAC3CC,GAAW,EACXC,OAAwC,EAC1C;IACE,KAAK,CAACD,GAAG,CAAC;IAAC,KAJKD,IAA2B,GAA3BA,IAA2B;IAAAG,eAAA;IAK3C,IAAI,CAACC,IAAI,GAAG,iBAAiB;IAC7B,IAAI,CAACC,cAAc,GAAGC,gCAAgC,CAAC,IAAI,EAAEJ,OAAO,CAAC;EACzE;AACJ;AAEA,SAASI,gCAAgCA,CAACC,GAAoB,EAAEL,OAAwC,EAAU;EAC9G,IAAIM,MAAM,GAAGD,GAAG,CAACH,IAAI,GAAG,QAAQ,GAAGG,GAAG,CAACE,OAAO;EAE9C,IAAIP,OAAO,EAAE;IACTM,MAAM,IACF,IAAI,GACJE,MAAM,CAACC,IAAI,CAACT,OAAO,CAAC,CACfU,GAAG,CAAEC,CAAC,IAAKA,CAAC,GAAG,IAAI,GAAGX,OAAO,CAACW,CAAC,CAAC,CAAC,CACjCC,IAAI,CAAC,IAAI,CAAC;EACvB;EAEAN,MAAM,IAAI,GAAG;EAEb,OAAOA,MAAM;AACjB","ignoreList":[]}
1
+ {"version":3,"file":"CryptoBackend.js","names":["DecryptionError","Error","constructor","code","msg","details","name","detailedString","detailedStringForDecryptionError","err","result","message","Object","keys","map","k","join"],"sources":["../../src/common-crypto/CryptoBackend.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type { IDeviceLists, IToDeviceEvent, ReceivedToDeviceMessage } from \"../sync-accumulator.ts\";\nimport { type IClearEvent, type MatrixEvent } from \"../models/event.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { type CryptoApi, type DecryptionFailureCode, type ImportRoomKeysOpts } from \"../crypto-api/index.ts\";\nimport { type KeyBackupInfo, type KeyBackupSession } from \"../crypto-api/keybackup.ts\";\nimport { type IMegolmSessionData } from \"../@types/crypto.ts\";\n\n/**\n * Common interface for the crypto implementations\n *\n * @internal\n */\nexport interface CryptoBackend extends SyncCryptoCallbacks, CryptoApi {\n /**\n * Whether sendMessage in a room with unknown and unverified devices\n * should throw an error and not send the message. This has 'Global' for\n * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently\n * no room-level equivalent for this setting.\n *\n * @remarks This has no effect in Rust Crypto; it exists only for the sake of\n * the accessors in MatrixClient.\n */\n globalErrorOnUnknownDevices: boolean;\n\n /**\n * Shut down any background processes related to crypto\n */\n stop(): void;\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 encryptEvent(event: MatrixEvent, room: Room): Promise<void>;\n\n /**\n * Decrypt a received event\n *\n * @returns a promise which resolves once we have finished decrypting.\n * Rejects with an error if there is a problem decrypting the event.\n */\n decryptEvent(event: MatrixEvent): Promise<EventDecryptionResult>;\n\n /**\n * Get a backup decryptor capable of decrypting megolm session data encrypted with the given backup information.\n * @param backupInfo - The backup information\n * @param privKey - The private decryption key.\n */\n getBackupDecryptor(backupInfo: KeyBackupInfo, privKey: Uint8Array): Promise<BackupDecryptor>;\n\n /**\n * Import a list of room keys restored from backup\n *\n * @param keys - a list of session export objects\n * @param backupVersion - the version of the backup these keys came from.\n * @param opts - options object\n * @returns a promise which resolves once the keys have been imported\n */\n importBackedUpRoomKeys(keys: IMegolmSessionData[], backupVersion: string, opts?: ImportRoomKeysOpts): Promise<void>;\n\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n //\n // Room key history sharing (MSC4268)\n //\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n /**\n * Share any shareable E2EE history in the given room with the given recipient,\n * as per [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)\n */\n shareRoomHistoryWithUser(roomId: string, userId: string): Promise<void>;\n\n /**\n * Having accepted an invite for the given room from the given user, attempt to\n * find information about a room key bundle and, if found, download the\n * bundle and import the room keys, as per {@link https://github.com/matrix-org/matrix-spec-proposals/pull/4268|MSC4268}.\n *\n * @param roomId - The room we were invited to, for which we want to check if a room\n * key bundle was received.\n *\n * @param inviter - The user who invited us to the room and is expected to have\n * sent the room key bundle.\n *\n * @returns `true` if the key bundle was successfuly downloaded and imported.\n */\n maybeAcceptKeyBundle(roomId: string, inviter: string): Promise<boolean>;\n\n /**\n * Mark a room as pending a key bundle under MSC4268. The backend will listen for room key bundle messages, and if\n * it sees one matching the room specified, it will automatically import it as long as the message author's ID matches\n * the inviter's ID.\n *\n * @param roomId - The room we were invited to, for which we did not receive a key bundle before accepting the invite.\n * @param inviterId - The user who invited us to the room and is expected to send the room key bundle.\n */\n markRoomAsPendingKeyBundle(roomId: string, inviterId: string): Promise<void>;\n}\n\n/** The methods which crypto implementations should expose to the Sync api\n *\n * @internal\n */\nexport interface SyncCryptoCallbacks {\n /**\n * Called by the /sync loop whenever there are incoming to-device messages.\n *\n * The implementation may preprocess the received messages (eg, decrypt them) and return an\n * updated list of messages for dispatch to the rest of the system.\n *\n * Note that, unlike {@link ClientEvent.ToDeviceEvent} events, this is called on the raw to-device\n * messages, rather than the results of any decryption attempts.\n *\n * @param events - the received to-device messages\n * @returns A list of preprocessed to-device messages. This will not map 1:1 to the input list, as some messages may be invalid or\n * failed to decrypt, and so will be omitted from the output list.\n *\n */\n preprocessToDeviceMessages(events: IToDeviceEvent[]): Promise<ReceivedToDeviceMessage[]>;\n\n /**\n * Called by the /sync loop when one time key counts and unused fallback key details are received.\n *\n * @param oneTimeKeysCounts - the received one time key counts\n * @param unusedFallbackKeys - the received unused fallback keys\n */\n processKeyCounts(oneTimeKeysCounts?: Record<string, number>, unusedFallbackKeys?: string[]): Promise<void>;\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 processDeviceLists(deviceLists: IDeviceLists): Promise<void>;\n\n /**\n * Called by the /sync loop whenever an m.room.encryption event is received.\n *\n * This is called before RoomStateEvents are emitted for any of the events in the /sync\n * response (even if the other events technically happened first). This works around a problem\n * if the client uses a RoomStateEvent (typically a membership event) as a trigger to send a message\n * in a new room (or one where encryption has been newly enabled): that would otherwise leave the\n * crypto layer confused because it expects crypto to be set up, but it has not yet been.\n *\n * @param room - in which the event was received\n * @param event - encryption event to be processed\n */\n onCryptoEvent(room: Room, event: MatrixEvent): Promise<void>;\n\n /**\n * Called by the /sync loop after each /sync response is processed.\n *\n * Used to complete batch processing, or to initiate background processes\n *\n * @param syncState - information about the completed sync.\n */\n onSyncCompleted(syncState: OnSyncCompletedData): void;\n\n /**\n * Mark all tracked users' device lists as dirty.\n *\n * This method will cause additional `/keys/query` requests on the server, so should be used only\n * when the client has desynced tracking device list deltas from the server.\n * In MSC4186: Simplified Sliding Sync, this can happen when the server expires the connection.\n */\n markAllTrackedUsersAsDirty(): Promise<void>;\n}\n\n/**\n * @internal\n */\nexport interface OnSyncCompletedData {\n /**\n * The 'next_batch' result from /sync, which will become the 'since' token for the next call to /sync.\n */\n nextSyncToken?: string;\n\n /**\n * True if we are working our way through a backlog of events after connecting.\n */\n catchingUp?: boolean;\n}\n\n/**\n * The result of a (successful) call to {@link CryptoBackend.decryptEvent}\n */\nexport interface EventDecryptionResult {\n /**\n * The plaintext payload for the event (typically containing <tt>type</tt> and <tt>content</tt> fields).\n */\n clearEvent: IClearEvent;\n /**\n * No longer used.\n * See {@link MatrixEvent#getForwardingCurve25519KeyChain}.\n * @deprecated\n */\n forwardingCurve25519KeyChain?: string[];\n /**\n * Key owned by the sender of this event. See {@link MatrixEvent#getSenderKey}.\n */\n senderCurve25519Key?: string;\n /**\n * ed25519 key claimed by the sender of this event. See {@link MatrixEvent#getClaimedEd25519Key}.\n */\n claimedEd25519Key?: string;\n\n /**\n * If another user forwarded the key to this message\n * (eg via [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268)),\n * the ID of that user.\n */\n keyForwardedBy?: string;\n}\n\n/**\n * Responsible for decrypting megolm session data retrieved from a remote backup.\n * The result of {@link CryptoBackend#getBackupDecryptor}.\n */\nexport interface BackupDecryptor {\n /**\n * Whether keys retrieved from this backup can be trusted.\n *\n * Depending on the backup algorithm, keys retrieved from the backup can be trusted or not.\n * If false, keys retrieved from the backup must be considered unsafe (authenticity cannot be guaranteed).\n * It could be by design (deniability) or for some technical reason (eg asymmetric encryption).\n */\n readonly sourceTrusted: boolean;\n\n /**\n *\n * Decrypt megolm session data retrieved from backup.\n *\n * @param ciphertexts - a Record of sessionId to session data.\n *\n * @returns An array of decrypted `IMegolmSessionData`\n */\n decryptSessions(ciphertexts: Record<string, KeyBackupSession>): Promise<IMegolmSessionData[]>;\n\n /**\n * Free any resources held by this decryptor.\n *\n * Should be called once the decryptor is no longer needed.\n */\n free(): void;\n}\n\n/**\n * Exception thrown when decryption fails\n *\n * @param code - Reason code for the failure.\n *\n * @param msg - user-visible message describing the problem\n *\n * @param details - key/value pairs reported in the logs but not shown\n * to the user.\n */\nexport class DecryptionError extends Error {\n public readonly detailedString: string;\n\n public constructor(\n public readonly code: DecryptionFailureCode,\n msg: string,\n details?: Record<string, string | Error>,\n ) {\n super(msg);\n this.name = \"DecryptionError\";\n this.detailedString = detailedStringForDecryptionError(this, details);\n }\n}\n\nfunction detailedStringForDecryptionError(err: DecryptionError, details?: Record<string, string | Error>): string {\n let result = err.name + \"[msg: \" + err.message;\n\n if (details) {\n result +=\n \", \" +\n Object.keys(details)\n .map((k) => k + \": \" + details[k])\n .join(\", \");\n }\n\n result += \"]\";\n\n return result;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACA;;AA6FA;AACA;AACA;AACA;;AAmEA;AACA;AACA;;AAaA;AACA;AACA;;AA6BA;AACA;AACA;AACA;;AA6BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMA,eAAe,SAASC,KAAK,CAAC;EAGhCC,WAAWA,CACEC,IAA2B,EAC3CC,GAAW,EACXC,OAAwC,EAC1C;IACE,KAAK,CAACD,GAAG,CAAC;IAAC,KAJKD,IAA2B,GAA3BA,IAA2B;IAK3C,IAAI,CAACG,IAAI,GAAG,iBAAiB;IAC7B,IAAI,CAACC,cAAc,GAAGC,gCAAgC,CAAC,IAAI,EAAEH,OAAO,CAAC;EACzE;AACJ;AAEA,SAASG,gCAAgCA,CAACC,GAAoB,EAAEJ,OAAwC,EAAU;EAC9G,IAAIK,MAAM,GAAGD,GAAG,CAACH,IAAI,GAAG,QAAQ,GAAGG,GAAG,CAACE,OAAO;EAE9C,IAAIN,OAAO,EAAE;IACTK,MAAM,IACF,IAAI,GACJE,MAAM,CAACC,IAAI,CAACR,OAAO,CAAC,CACfS,GAAG,CAAEC,CAAC,IAAKA,CAAC,GAAG,IAAI,GAAGV,OAAO,CAACU,CAAC,CAAC,CAAC,CACjCC,IAAI,CAAC,IAAI,CAAC;EACvB;EAEAN,MAAM,IAAI,GAAG;EAEb,OAAOA,MAAM;AACjB","ignoreList":[]}
@@ -223,11 +223,9 @@ export var makeBeaconInfoContent = (timeout, isLive, description, assetType, tim
223
223
  */
224
224
  export var parseBeaconInfoContent = content => {
225
225
  var _M_TIMESTAMP$findIn;
226
- var {
227
- description,
228
- timeout,
229
- live
230
- } = content;
226
+ var description = content.description,
227
+ timeout = content.timeout,
228
+ live = content.live;
231
229
  var timestamp = (_M_TIMESTAMP$findIn = M_TIMESTAMP.findIn(content)) !== null && _M_TIMESTAMP$findIn !== void 0 ? _M_TIMESTAMP$findIn : undefined;
232
230
  var asset = M_ASSET.findIn(content);
233
231
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"content-helpers.js","names":["MsgType","M_TEXT","REFERENCE_RELATION","isProvided","M_ASSET","LocationAssetType","M_LOCATION","M_TIMESTAMP","M_TOPIC","makeHtmlMessage","body","htmlBody","msgtype","Text","format","formatted_body","makeHtmlNotice","Notice","makeHtmlEmote","Emote","makeTextMessage","makeNotice","makeEmoteMessage","getTextForLocationEvent","uri","assetType","timestamp","description","date","concat","Date","toISOString","assetName","Self","undefined","quotedDescription","filter","Boolean","join","makeLocationContent","text","defaultedText","timestampEvent","name","_objectSpread","Location","geo_uri","type","parseLocationEvent","wireEventContent","_location$uri","_asset$type","location","findIn","asset","geoUri","fallbackText","makeTopicContent","topic","htmlTopic","renderings","push","mimetype","parseTopicContent","content","_ref","_mtopic$find$body","_mtopic$find","_mtopic$find2","mtopicParent","mtopic","Array","isArray","_content$topic","find","r","html","makeBeaconInfoContent","timeout","isLive","live","now","parseBeaconInfoContent","_M_TIMESTAMP$findIn","makeBeaconContent","beaconInfoEventId","rel_type","event_id","parseBeaconContent","_M_TIMESTAMP$findIn2"],"sources":["../src/content-helpers.ts"],"sourcesContent":["/*\nCopyright 2018 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type MBeaconEventContent, type MBeaconInfoContent, type MBeaconInfoEventContent } from \"./@types/beacon.ts\";\nimport { MsgType } from \"./@types/event.ts\";\nimport { type IMessageRendering, M_TEXT, REFERENCE_RELATION } from \"./@types/extensible_events.ts\";\nimport { isProvided } from \"./extensible_events_v1/utilities.ts\";\nimport {\n M_ASSET,\n LocationAssetType,\n M_LOCATION,\n M_TIMESTAMP,\n type LocationEventWireContent,\n type MLocationEventContent,\n type MLocationContent,\n type MAssetContent,\n type LegacyLocationEventContent,\n} from \"./@types/location.ts\";\nimport { type MRoomTopicEventContent, type MTopicContent, M_TOPIC, type MTopicEvent } from \"./@types/topic.ts\";\nimport { type RoomMessageEventContent } from \"./@types/events.ts\";\n\n/**\n * Generates the content for a HTML Message event\n * @param body - the plaintext body of the message\n * @param htmlBody - the HTML representation of the message\n * @returns\n */\nexport function makeHtmlMessage(body: string, htmlBody: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Text,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Notice event\n * @param body - the plaintext body of the notice\n * @param htmlBody - the HTML representation of the notice\n * @returns\n */\nexport function makeHtmlNotice(body: string, htmlBody: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Notice,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Emote event\n * @param body - the plaintext body of the emote\n * @param htmlBody - the HTML representation of the emote\n * @returns\n */\nexport function makeHtmlEmote(body: string, htmlBody: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Emote,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a Plaintext Message event\n * @param body - the plaintext body of the emote\n * @returns\n */\nexport function makeTextMessage(body: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Text,\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Notice event\n * @param body - the plaintext body of the notice\n * @returns\n */\nexport function makeNotice(body: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Notice,\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Emote event\n * @param body - the plaintext body of the emote\n * @returns\n */\nexport function makeEmoteMessage(body: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Emote,\n body: body,\n };\n}\n\n/** Location content helpers */\n\nexport const getTextForLocationEvent = (\n uri: string | undefined,\n assetType: LocationAssetType,\n timestamp?: number,\n description?: string | null,\n): string => {\n const date = `at ${new Date(timestamp!).toISOString()}`;\n const assetName = assetType === LocationAssetType.Self ? \"User\" : undefined;\n const quotedDescription = description ? `\"${description}\"` : undefined;\n\n return [assetName, \"Location\", quotedDescription, uri, date].filter(Boolean).join(\" \");\n};\n\n/**\n * Generates the content for a Location event\n * @param uri - a geo:// uri for the location\n * @param timestamp - the timestamp when the location was correct (milliseconds since the UNIX epoch)\n * @param description - the (optional) label for this location on the map\n * @param assetType - the (optional) asset type of this location e.g. \"m.self\"\n * @param text - optional. A text for the location\n */\nexport const makeLocationContent = (\n // this is first but optional\n // to avoid a breaking change\n text?: string,\n uri?: string,\n timestamp?: number,\n description?: string | null,\n assetType?: LocationAssetType,\n): LegacyLocationEventContent & MLocationEventContent => {\n const defaultedText =\n text ?? getTextForLocationEvent(uri, assetType || LocationAssetType.Self, timestamp, description);\n const timestampEvent = timestamp ? { [M_TIMESTAMP.name]: timestamp } : {};\n return {\n msgtype: MsgType.Location,\n body: defaultedText,\n geo_uri: uri,\n [M_LOCATION.name]: {\n description,\n uri,\n },\n [M_ASSET.name]: {\n type: assetType || LocationAssetType.Self,\n },\n [M_TEXT.name]: defaultedText,\n ...timestampEvent,\n } as LegacyLocationEventContent & MLocationEventContent;\n};\n\n/**\n * Parse location event content and transform to\n * a backwards compatible modern m.location event format\n */\nexport const parseLocationEvent = (wireEventContent: LocationEventWireContent): MLocationEventContent => {\n const location = M_LOCATION.findIn<MLocationContent>(wireEventContent);\n const asset = M_ASSET.findIn<MAssetContent>(wireEventContent);\n const timestamp = M_TIMESTAMP.findIn<number>(wireEventContent);\n const text = M_TEXT.findIn<string>(wireEventContent);\n\n const geoUri = location?.uri ?? wireEventContent?.geo_uri;\n const description = location?.description;\n const assetType = asset?.type ?? LocationAssetType.Self;\n const fallbackText = text ?? wireEventContent.body;\n\n return makeLocationContent(fallbackText, geoUri, timestamp ?? undefined, description, assetType);\n};\n\n/**\n * Topic event helpers\n */\nexport type MakeTopicContent = (topic: string | null | undefined, htmlTopic?: string) => MRoomTopicEventContent;\n\nexport const makeTopicContent: MakeTopicContent = (topic, htmlTopic) => {\n const renderings = [];\n // Put HTML first because clients will render the first type in\n // the array that they understand\n if (isProvided(htmlTopic)) {\n renderings.push({ body: htmlTopic, mimetype: \"text/html\" });\n }\n if (isProvided(topic)) {\n renderings.push({ body: topic, mimetype: \"text/plain\" });\n }\n return { topic, [M_TOPIC.name]: { \"m.text\": renderings } };\n};\n\nexport type TopicState = {\n text?: string;\n html?: string;\n};\n\nexport const parseTopicContent = (content: MRoomTopicEventContent): TopicState => {\n const mtopicParent = M_TOPIC.findIn<MTopicContent | IMessageRendering[]>(content as MTopicEvent);\n const mtopic = Array.isArray(mtopicParent) ? mtopicParent : mtopicParent?.[\"m.text\"];\n // TODO remove support for the old malformed m.topic arrays after a few releases (only allow array in m.text)\n // https://github.com/matrix-org/matrix-js-sdk/pull/4984#pullrequestreview-3174251065\n //const mtopic = M_TOPIC.findIn<MTopicContent>(content)?.[\"m.text\"];\n if (!Array.isArray(mtopic)) {\n return { text: content.topic ?? undefined };\n }\n const text =\n mtopic?.find((r) => !isProvided(r.mimetype) || r.mimetype === \"text/plain\")?.body ?? content.topic ?? undefined;\n const html = mtopic?.find((r) => r.mimetype === \"text/html\")?.body;\n return { text, html };\n};\n\n/**\n * Beacon event helpers\n */\nexport type MakeBeaconInfoContent = (\n timeout: number,\n isLive?: boolean,\n description?: string,\n assetType?: LocationAssetType,\n timestamp?: number,\n) => MBeaconInfoEventContent;\n\nexport const makeBeaconInfoContent: MakeBeaconInfoContent = (timeout, isLive, description, assetType, timestamp) => ({\n description,\n timeout,\n live: isLive,\n [M_TIMESTAMP.name]: timestamp || Date.now(),\n [M_ASSET.name]: {\n type: assetType ?? LocationAssetType.Self,\n },\n});\n\nexport type BeaconInfoState = MBeaconInfoContent & {\n assetType?: LocationAssetType;\n timestamp?: number;\n};\n/**\n * Flatten beacon info event content\n */\nexport const parseBeaconInfoContent = (content: MBeaconInfoEventContent): BeaconInfoState => {\n const { description, timeout, live } = content;\n const timestamp = M_TIMESTAMP.findIn<number>(content) ?? undefined;\n const asset = M_ASSET.findIn<MAssetContent>(content);\n\n return {\n description,\n timeout,\n live,\n assetType: asset?.type,\n timestamp,\n };\n};\n\nexport type MakeBeaconContent = (\n uri: string,\n timestamp: number,\n beaconInfoEventId: string,\n description?: string,\n) => MBeaconEventContent;\n\nexport const makeBeaconContent: MakeBeaconContent = (uri, timestamp, beaconInfoEventId, description) => ({\n [M_LOCATION.name]: {\n description,\n uri,\n },\n [M_TIMESTAMP.name]: timestamp,\n \"m.relates_to\": {\n rel_type: REFERENCE_RELATION.name,\n event_id: beaconInfoEventId,\n },\n});\n\nexport type BeaconLocationState = Omit<MLocationContent, \"uri\"> & {\n uri?: string; // override from MLocationContent to allow optionals\n timestamp?: number;\n};\n\nexport const parseBeaconContent = (content: MBeaconEventContent): BeaconLocationState => {\n const location = M_LOCATION.findIn<MLocationContent>(content);\n const timestamp = M_TIMESTAMP.findIn<number>(content) ?? undefined;\n\n return {\n description: location?.description,\n uri: location?.uri,\n timestamp,\n };\n};\n"],"mappings":";;;AA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BAAA,cAAAA,mBAAA,GAAIjD,SAAS;EAClE,IAAMoB,KAAK,GAAGlD,OAAO,CAACiD,MAAM,CAAgBW,OAAO,CAAC;EAEpD,OAAO;IACHrC,WAAW;IACXmD,OAAO;IACPE,IAAI;IACJvD,SAAS,EAAE6B,KAAK,aAALA,KAAK,uBAALA,KAAK,CAAEP,IAAI;IACtBrB;EACJ,CAAC;AACL,CAAC;AASD,OAAO,IAAM0D,iBAAoC,GAAGA,CAAC5D,GAAG,EAAEE,SAAS,EAAE2D,iBAAiB,EAAE1D,WAAW,MAAM;EACrG,CAACrB,UAAU,CAACqC,IAAI,GAAG;IACfhB,WAAW;IACXH;EACJ,CAAC;EACD,CAACjB,WAAW,CAACoC,IAAI,GAAGjB,SAAS;EAC7B,cAAc,EAAE;IACZ4D,QAAQ,EAAEpF,kBAAkB,CAACyC,IAAI;IACjC4C,QAAQ,EAAEF;EACd;AACJ,CAAC,CAAC;AAOF,OAAO,IAAMG,kBAAkB,GAAIxB,OAA4B,IAA0B;EAAA,IAAAyB,oBAAA;EACrF,IAAMrC,QAAQ,GAAG9C,UAAU,CAAC+C,MAAM,CAAmBW,OAAO,CAAC;EAC7D,IAAMtC,SAAS,IAAA+D,oBAAA,GAAGlF,WAAW,CAAC8C,MAAM,CAASW,OAAO,CAAC,cAAAyB,oBAAA,cAAAA,oBAAA,GAAIvD,SAAS;EAElE,OAAO;IACHP,WAAW,EAAEyB,QAAQ,aAARA,QAAQ,uBAARA,QAAQ,CAAEzB,WAAW;IAClCH,GAAG,EAAE4B,QAAQ,aAARA,QAAQ,uBAARA,QAAQ,CAAE5B,GAAG;IAClBE;EACJ,CAAC;AACL,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"content-helpers.js","names":["MsgType","M_TEXT","REFERENCE_RELATION","isProvided","M_ASSET","LocationAssetType","M_LOCATION","M_TIMESTAMP","M_TOPIC","makeHtmlMessage","body","htmlBody","msgtype","Text","format","formatted_body","makeHtmlNotice","Notice","makeHtmlEmote","Emote","makeTextMessage","makeNotice","makeEmoteMessage","getTextForLocationEvent","uri","assetType","timestamp","description","date","concat","Date","toISOString","assetName","Self","undefined","quotedDescription","filter","Boolean","join","makeLocationContent","text","defaultedText","timestampEvent","name","_objectSpread","Location","geo_uri","type","parseLocationEvent","wireEventContent","_location$uri","_asset$type","location","findIn","asset","geoUri","fallbackText","makeTopicContent","topic","htmlTopic","renderings","push","mimetype","parseTopicContent","content","_ref","_mtopic$find$body","_mtopic$find","_mtopic$find2","mtopicParent","mtopic","Array","isArray","_content$topic","find","r","html","makeBeaconInfoContent","timeout","isLive","live","now","parseBeaconInfoContent","_M_TIMESTAMP$findIn","makeBeaconContent","beaconInfoEventId","rel_type","event_id","parseBeaconContent","_M_TIMESTAMP$findIn2"],"sources":["../src/content-helpers.ts"],"sourcesContent":["/*\nCopyright 2018 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type MBeaconEventContent, type MBeaconInfoContent, type MBeaconInfoEventContent } from \"./@types/beacon.ts\";\nimport { MsgType } from \"./@types/event.ts\";\nimport { type IMessageRendering, M_TEXT, REFERENCE_RELATION } from \"./@types/extensible_events.ts\";\nimport { isProvided } from \"./extensible_events_v1/utilities.ts\";\nimport {\n M_ASSET,\n LocationAssetType,\n M_LOCATION,\n M_TIMESTAMP,\n type LocationEventWireContent,\n type MLocationEventContent,\n type MLocationContent,\n type MAssetContent,\n type LegacyLocationEventContent,\n} from \"./@types/location.ts\";\nimport { type MRoomTopicEventContent, type MTopicContent, M_TOPIC, type MTopicEvent } from \"./@types/topic.ts\";\nimport { type RoomMessageEventContent } from \"./@types/events.ts\";\n\n/**\n * Generates the content for a HTML Message event\n * @param body - the plaintext body of the message\n * @param htmlBody - the HTML representation of the message\n * @returns\n */\nexport function makeHtmlMessage(body: string, htmlBody: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Text,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Notice event\n * @param body - the plaintext body of the notice\n * @param htmlBody - the HTML representation of the notice\n * @returns\n */\nexport function makeHtmlNotice(body: string, htmlBody: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Notice,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Emote event\n * @param body - the plaintext body of the emote\n * @param htmlBody - the HTML representation of the emote\n * @returns\n */\nexport function makeHtmlEmote(body: string, htmlBody: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Emote,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a Plaintext Message event\n * @param body - the plaintext body of the emote\n * @returns\n */\nexport function makeTextMessage(body: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Text,\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Notice event\n * @param body - the plaintext body of the notice\n * @returns\n */\nexport function makeNotice(body: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Notice,\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Emote event\n * @param body - the plaintext body of the emote\n * @returns\n */\nexport function makeEmoteMessage(body: string): RoomMessageEventContent {\n return {\n msgtype: MsgType.Emote,\n body: body,\n };\n}\n\n/** Location content helpers */\n\nexport const getTextForLocationEvent = (\n uri: string | undefined,\n assetType: LocationAssetType,\n timestamp?: number,\n description?: string | null,\n): string => {\n const date = `at ${new Date(timestamp!).toISOString()}`;\n const assetName = assetType === LocationAssetType.Self ? \"User\" : undefined;\n const quotedDescription = description ? `\"${description}\"` : undefined;\n\n return [assetName, \"Location\", quotedDescription, uri, date].filter(Boolean).join(\" \");\n};\n\n/**\n * Generates the content for a Location event\n * @param uri - a geo:// uri for the location\n * @param timestamp - the timestamp when the location was correct (milliseconds since the UNIX epoch)\n * @param description - the (optional) label for this location on the map\n * @param assetType - the (optional) asset type of this location e.g. \"m.self\"\n * @param text - optional. A text for the location\n */\nexport const makeLocationContent = (\n // this is first but optional\n // to avoid a breaking change\n text?: string,\n uri?: string,\n timestamp?: number,\n description?: string | null,\n assetType?: LocationAssetType,\n): LegacyLocationEventContent & MLocationEventContent => {\n const defaultedText =\n text ?? getTextForLocationEvent(uri, assetType || LocationAssetType.Self, timestamp, description);\n const timestampEvent = timestamp ? { [M_TIMESTAMP.name]: timestamp } : {};\n return {\n msgtype: MsgType.Location,\n body: defaultedText,\n geo_uri: uri,\n [M_LOCATION.name]: {\n description,\n uri,\n },\n [M_ASSET.name]: {\n type: assetType || LocationAssetType.Self,\n },\n [M_TEXT.name]: defaultedText,\n ...timestampEvent,\n } as LegacyLocationEventContent & MLocationEventContent;\n};\n\n/**\n * Parse location event content and transform to\n * a backwards compatible modern m.location event format\n */\nexport const parseLocationEvent = (wireEventContent: LocationEventWireContent): MLocationEventContent => {\n const location = M_LOCATION.findIn<MLocationContent>(wireEventContent);\n const asset = M_ASSET.findIn<MAssetContent>(wireEventContent);\n const timestamp = M_TIMESTAMP.findIn<number>(wireEventContent);\n const text = M_TEXT.findIn<string>(wireEventContent);\n\n const geoUri = location?.uri ?? wireEventContent?.geo_uri;\n const description = location?.description;\n const assetType = asset?.type ?? LocationAssetType.Self;\n const fallbackText = text ?? wireEventContent.body;\n\n return makeLocationContent(fallbackText, geoUri, timestamp ?? undefined, description, assetType);\n};\n\n/**\n * Topic event helpers\n */\nexport type MakeTopicContent = (topic: string | null | undefined, htmlTopic?: string) => MRoomTopicEventContent;\n\nexport const makeTopicContent: MakeTopicContent = (topic, htmlTopic) => {\n const renderings = [];\n // Put HTML first because clients will render the first type in\n // the array that they understand\n if (isProvided(htmlTopic)) {\n renderings.push({ body: htmlTopic, mimetype: \"text/html\" });\n }\n if (isProvided(topic)) {\n renderings.push({ body: topic, mimetype: \"text/plain\" });\n }\n return { topic, [M_TOPIC.name]: { \"m.text\": renderings } };\n};\n\nexport type TopicState = {\n text?: string;\n html?: string;\n};\n\nexport const parseTopicContent = (content: MRoomTopicEventContent): TopicState => {\n const mtopicParent = M_TOPIC.findIn<MTopicContent | IMessageRendering[]>(content as MTopicEvent);\n const mtopic = Array.isArray(mtopicParent) ? mtopicParent : mtopicParent?.[\"m.text\"];\n // TODO remove support for the old malformed m.topic arrays after a few releases (only allow array in m.text)\n // https://github.com/matrix-org/matrix-js-sdk/pull/4984#pullrequestreview-3174251065\n //const mtopic = M_TOPIC.findIn<MTopicContent>(content)?.[\"m.text\"];\n if (!Array.isArray(mtopic)) {\n return { text: content.topic ?? undefined };\n }\n const text =\n mtopic?.find((r) => !isProvided(r.mimetype) || r.mimetype === \"text/plain\")?.body ?? content.topic ?? undefined;\n const html = mtopic?.find((r) => r.mimetype === \"text/html\")?.body;\n return { text, html };\n};\n\n/**\n * Beacon event helpers\n */\nexport type MakeBeaconInfoContent = (\n timeout: number,\n isLive?: boolean,\n description?: string,\n assetType?: LocationAssetType,\n timestamp?: number,\n) => MBeaconInfoEventContent;\n\nexport const makeBeaconInfoContent: MakeBeaconInfoContent = (timeout, isLive, description, assetType, timestamp) => ({\n description,\n timeout,\n live: isLive,\n [M_TIMESTAMP.name]: timestamp || Date.now(),\n [M_ASSET.name]: {\n type: assetType ?? LocationAssetType.Self,\n },\n});\n\nexport type BeaconInfoState = MBeaconInfoContent & {\n assetType?: LocationAssetType;\n timestamp?: number;\n};\n/**\n * Flatten beacon info event content\n */\nexport const parseBeaconInfoContent = (content: MBeaconInfoEventContent): BeaconInfoState => {\n const { description, timeout, live } = content;\n const timestamp = M_TIMESTAMP.findIn<number>(content) ?? undefined;\n const asset = M_ASSET.findIn<MAssetContent>(content);\n\n return {\n description,\n timeout,\n live,\n assetType: asset?.type,\n timestamp,\n };\n};\n\nexport type MakeBeaconContent = (\n uri: string,\n timestamp: number,\n beaconInfoEventId: string,\n description?: string,\n) => MBeaconEventContent;\n\nexport const makeBeaconContent: MakeBeaconContent = (uri, timestamp, beaconInfoEventId, description) => ({\n [M_LOCATION.name]: {\n description,\n uri,\n },\n [M_TIMESTAMP.name]: timestamp,\n \"m.relates_to\": {\n rel_type: REFERENCE_RELATION.name,\n event_id: beaconInfoEventId,\n },\n});\n\nexport type BeaconLocationState = Omit<MLocationContent, \"uri\"> & {\n uri?: string; // override from MLocationContent to allow optionals\n timestamp?: number;\n};\n\nexport const parseBeaconContent = (content: MBeaconEventContent): BeaconLocationState => {\n const location = M_LOCATION.findIn<MLocationContent>(content);\n const timestamp = M_TIMESTAMP.findIn<number>(content) ?? undefined;\n\n return {\n description: location?.description,\n uri: location?.uri,\n timestamp,\n };\n};\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,OAAO,QAAQ,mBAAmB;AAC3C,SAAiCC,MAAM,EAAEC,kBAAkB,QAAQ,+BAA+B;AAClG,SAASC,UAAU,QAAQ,qCAAqC;AAChE,SACIC,OAAO,EACPC,iBAAiB,EACjBC,UAAU,EACVC,WAAW,QAMR,sBAAsB;AAC7B,SAA0DC,OAAO,QAA0B,mBAAmB;AAG9G;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,eAAeA,CAACC,IAAY,EAAEC,QAAgB,EAA2B;EACrF,OAAO;IACHC,OAAO,EAAEZ,OAAO,CAACa,IAAI;IACrBC,MAAM,EAAE,wBAAwB;IAChCJ,IAAI,EAAEA,IAAI;IACVK,cAAc,EAAEJ;EACpB,CAAC;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASK,cAAcA,CAACN,IAAY,EAAEC,QAAgB,EAA2B;EACpF,OAAO;IACHC,OAAO,EA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AO,IAAMG,kBAAkB,GAAIxB,OAA4B,IAA0B;EAAA,IAAAyB,oBAAA;EACrF,IAAMrC,QAAQ,GAAG9C,UAAU,CAAC+C,MAAM,CAAmBW,OAAO,CAAC;EAC7D,IAAMtC,SAAS,IAAA+D,oBAAA,GAAGlF,WAAW,CAAC8C,MAAM,CAASW,OAAO,CAAC,cAAAyB,oBAAA,cAAAA,oBAAA,GAAIvD,SAAS;EAElE,OAAO;IACHP,WAAW,EAAEyB,QAAQ,aAARA,QAAQ,uBAARA,QAAQ,CAAEzB,WAAW;IAClCH,GAAG,EAAE4B,QAAQ,aAARA,QAAQ,uBAARA,QAAQ,CAAE5B,GAAG;IAClBE;EACJ,CAAC;AACL,CAAC","ignoreList":[]}
@@ -1,3 +1,5 @@
1
+ import _toArray from "@babel/runtime/helpers/toArray";
2
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
1
3
  /*
2
4
  Copyright 2015 - 2024 The Matrix.org Foundation C.I.C.
3
5
 
@@ -68,7 +70,11 @@ export function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod) {
68
70
  return "";
69
71
  }
70
72
  }
71
- var [serverName, mediaId, ...rest] = mxc.slice(6).split("/");
73
+ var _mxc$slice$split = mxc.slice(6).split("/"),
74
+ _mxc$slice$split2 = _toArray(_mxc$slice$split),
75
+ serverName = _mxc$slice$split2[0],
76
+ mediaId = _mxc$slice$split2[1],
77
+ rest = _arrayLikeToArray(_mxc$slice$split2).slice(2);
72
78
  if (rest.length > 0 || !validateServerName(serverName) || !validateMediaId(mediaId)) {
73
79
  return "";
74
80
  }
@@ -1 +1 @@
1
- {"version":3,"file":"content-repo.js","names":["serverNameRegex","validateServerName","serverName","matches","exec","mediaIdRegex","validateMediaId","mediaId","getHttpUriForMxc","baseUrl","mxc","width","height","resizeMethod","allowDirectLinks","arguments","length","undefined","allowRedirects","useAuthentication","animated","startsWith","rest","slice","split","prefix","isThumbnailRequest","verb","concat","url","URL","searchParams","set","Math","round","toString","String","JSON","stringify","href"],"sources":["../src/content-repo.ts"],"sourcesContent":["/*\nCopyright 2015 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Validation based on https://spec.matrix.org/v1.12/appendices/#server-name\n// We do not use the validation described in https://spec.matrix.org/v1.12/client-server-api/#security-considerations-5\n// as it'd wrongly make all MXCs invalid due to not allowing `[].:` in server names.\nconst serverNameRegex =\n /^(?:(?:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(?:\\[[\\dA-Fa-f:.]{2,45}])|(?:[A-Za-z\\d\\-.]{1,255}))(?::\\d{1,5})?$/;\nfunction validateServerName(serverName: string): boolean {\n const matches = serverNameRegex.exec(serverName);\n return matches?.[0] === serverName;\n}\n\n// Validation based on https://spec.matrix.org/v1.12/client-server-api/#security-considerations-5\nconst mediaIdRegex = /^[\\w-]+$/;\nfunction validateMediaId(mediaId: string): boolean {\n const matches = mediaIdRegex.exec(mediaId);\n return matches?.[0] === mediaId;\n}\n\n/**\n * Get the HTTP URL for an MXC URI.\n * @param baseUrl - The base homeserver url which has a content repo.\n * @param mxc - The mxc:// URI.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return the emptry string\n * for such URLs.\n * @param allowRedirects - If true, the caller supports the URL being 307 or\n * 308 redirected to another resource upon request. If false, redirects\n * are not expected. Implied `true` when `useAuthentication` is `true`.\n * @param useAuthentication - If true, the caller supports authenticated\n * media and wants an authentication-required URL. Note that server support\n * for authenticated media will *not* be checked - it is the caller's responsibility\n * to do so before calling this function. Note also that `useAuthentication`\n * implies `allowRedirects`. Defaults to false (unauthenticated endpoints).\n * @param animated - Whether the desired thumbnail should be animated.\n * @returns The complete URL to the content, may be an empty string if the provided mxc is not valid.\n */\nexport function getHttpUriForMxc(\n baseUrl: string,\n mxc?: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks = false,\n allowRedirects?: boolean,\n useAuthentication?: boolean,\n animated?: boolean,\n): string {\n if (typeof mxc !== \"string\" || !mxc) {\n return \"\";\n }\n if (!mxc.startsWith(\"mxc://\")) {\n if (allowDirectLinks) {\n return mxc;\n } else {\n return \"\";\n }\n }\n\n const [serverName, mediaId, ...rest] = mxc.slice(6).split(\"/\");\n if (rest.length > 0 || !validateServerName(serverName) || !validateMediaId(mediaId)) {\n return \"\";\n }\n\n if (useAuthentication) {\n allowRedirects = true; // per docs (MSC3916 always expects redirects)\n\n // Dev note: MSC3916 removes `allow_redirect` entirely, but\n // for explicitness we set it here. This makes it slightly more obvious to\n // callers, hopefully.\n }\n\n let prefix: string;\n const isThumbnailRequest = !!width || !!height || !!resizeMethod;\n const verb = isThumbnailRequest ? \"thumbnail\" : \"download\";\n if (useAuthentication) {\n prefix = `/_matrix/client/v1/media/${verb}`;\n } else {\n prefix = `/_matrix/media/v3/${verb}`;\n }\n\n const url = new URL(`${prefix}/${serverName}/${mediaId}`, baseUrl);\n\n if (width) {\n url.searchParams.set(\"width\", Math.round(width).toString());\n }\n if (height) {\n url.searchParams.set(\"height\", Math.round(height).toString());\n }\n if (resizeMethod) {\n url.searchParams.set(\"method\", resizeMethod);\n }\n if (animated !== undefined) {\n url.searchParams.set(\"animated\", String(animated));\n }\n\n if (typeof allowRedirects === \"boolean\") {\n // We add this after, so we don't convert everything to a thumbnail request.\n url.searchParams.set(\"allow_redirect\", JSON.stringify(allowRedirects));\n }\n\n return url.href;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAMA,eAAe,GACjB,8GAA8G;AAClH,SAASC,kBAAkBA,CAACC,UAAkB,EAAW;EACrD,IAAMC,OAAO,GAAGH,eAAe,CAACI,IAAI,CAACF,UAAU,CAAC;EAChD,OAAO,CAAAC,OAAO,aAAPA,OAAO,uBAAPA,OAAO,CAAG,CAAC,CAAC,MAAKD,UAAU;AACtC;;AAEA;AACA,IAAMG,YAAY,GAAG,UAAU;AAC/B,SAASC,eAAeA,CAACC,OAAe,EAAW;EAC/C,IAAMJ,OAAO,GAAGE,YAAY,CAACD,IAAI,CAACG,OAAO,CAAC;EAC1C,OAAO,CAAAJ,OAAO,aAAPA,OAAO,uBAAPA,OAAO,CAAG,CAAC,CAAC,MAAKI,OAAO;AACnC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,gBAAgBA,CAC5BC,OAAe,EACfC,GAAY,EACZC,KAAc,EACdC,MAAe,EACfC,YAAqB,EAKf;EAAA,IAJNC,gBAAgB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,KAAK;EAAA,IACxBG,cAAwB,GAAAH,SAAA,CAAAC,MAAA,OAAAD,SAAA,MAAAE,SAAA;EAAA,IACxBE,iBAA2B,GAAAJ,SAAA,CAAAC,MAAA,OAAAD,SAAA,MAAAE,SAAA;EAAA,IAC3BG,QAAkB,GAAAL,SAAA,CAAAC,MAAA,OAAAD,SAAA,MAAAE,SAAA;EAElB,IAAI,OAAOP,GAAG,KAAK,QAAQ,IAAI,CAACA,GAAG,EAAE;IACjC,OAAO,EAAE;EAC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,IAAI,CAACC,KAAK,CAACtB,MAAM,CAAC,CAACuB,QAAQ,CAAC,CAAC,CAAC;EACjE;EACA,IAAItB,YAAY,EAAE;IACdgB,GAAG,CAACE,YAAY,CAACC,GAAG,CAAC,QAAQ,EAAEnB,YAAY,CAAC;EAChD;EACA,IAAIO,QAAQ,KAAKH,SAAS,EAAE;IACxBY,GAAG,CAACE,YAAY,CAACC,GAAG,CAAC,UAAU,EAAEI,MAAM,CAAChB,QAAQ,CAAC,CAAC;EACtD;EAEA,IAAI,OAAOF,cAAc,KAAK,SAAS,EAAE;IACrC;IACAW,GAAG,CAACE,YAAY,CAACC,GAAG,CAAC,gBAAgB,EAAEK,IAAI,CAACC,SAAS,CAACpB,cAAc,CAAC,CAAC;EAC1E;EAEA,OAAOW,GAAG,CAACU,IAAI;AACnB","ignoreList":[]}
1
+ {"version":3,"file":"content-repo.js","names":["serverNameRegex","validateServerName","serverName","matches","exec","mediaIdRegex","validateMediaId","mediaId","getHttpUriForMxc","baseUrl","mxc","width","height","resizeMethod","allowDirectLinks","arguments","length","undefined","allowRedirects","useAuthentication","animated","startsWith","_mxc$slice$split","slice","split","_mxc$slice$split2","_toArray","rest","_arrayLikeToArray","prefix","isThumbnailRequest","verb","concat","url","URL","searchParams","set","Math","round","toString","String","JSON","stringify","href"],"sources":["../src/content-repo.ts"],"sourcesContent":["/*\nCopyright 2015 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Validation based on https://spec.matrix.org/v1.12/appendices/#server-name\n// We do not use the validation described in https://spec.matrix.org/v1.12/client-server-api/#security-considerations-5\n// as it'd wrongly make all MXCs invalid due to not allowing `[].:` in server names.\nconst serverNameRegex =\n /^(?:(?:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(?:\\[[\\dA-Fa-f:.]{2,45}])|(?:[A-Za-z\\d\\-.]{1,255}))(?::\\d{1,5})?$/;\nfunction validateServerName(serverName: string): boolean {\n const matches = serverNameRegex.exec(serverName);\n return matches?.[0] === serverName;\n}\n\n// Validation based on https://spec.matrix.org/v1.12/client-server-api/#security-considerations-5\nconst mediaIdRegex = /^[\\w-]+$/;\nfunction validateMediaId(mediaId: string): boolean {\n const matches = mediaIdRegex.exec(mediaId);\n return matches?.[0] === mediaId;\n}\n\n/**\n * Get the HTTP URL for an MXC URI.\n * @param baseUrl - The base homeserver url which has a content repo.\n * @param mxc - The mxc:// URI.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return the emptry string\n * for such URLs.\n * @param allowRedirects - If true, the caller supports the URL being 307 or\n * 308 redirected to another resource upon request. If false, redirects\n * are not expected. Implied `true` when `useAuthentication` is `true`.\n * @param useAuthentication - If true, the caller supports authenticated\n * media and wants an authentication-required URL. Note that server support\n * for authenticated media will *not* be checked - it is the caller's responsibility\n * to do so before calling this function. Note also that `useAuthentication`\n * implies `allowRedirects`. Defaults to false (unauthenticated endpoints).\n * @param animated - Whether the desired thumbnail should be animated.\n * @returns The complete URL to the content, may be an empty string if the provided mxc is not valid.\n */\nexport function getHttpUriForMxc(\n baseUrl: string,\n mxc?: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks = false,\n allowRedirects?: boolean,\n useAuthentication?: boolean,\n animated?: boolean,\n): string {\n if (typeof mxc !== \"string\" || !mxc) {\n return \"\";\n }\n if (!mxc.startsWith(\"mxc://\")) {\n if (allowDirectLinks) {\n return mxc;\n } else {\n return \"\";\n }\n }\n\n const [serverName, mediaId, ...rest] = mxc.slice(6).split(\"/\");\n if (rest.length > 0 || !validateServerName(serverName) || !validateMediaId(mediaId)) {\n return \"\";\n }\n\n if (useAuthentication) {\n allowRedirects = true; // per docs (MSC3916 always expects redirects)\n\n // Dev note: MSC3916 removes `allow_redirect` entirely, but\n // for explicitness we set it here. This makes it slightly more obvious to\n // callers, hopefully.\n }\n\n let prefix: string;\n const isThumbnailRequest = !!width || !!height || !!resizeMethod;\n const verb = isThumbnailRequest ? \"thumbnail\" : \"download\";\n if (useAuthentication) {\n prefix = `/_matrix/client/v1/media/${verb}`;\n } else {\n prefix = `/_matrix/media/v3/${verb}`;\n }\n\n const url = new URL(`${prefix}/${serverName}/${mediaId}`, baseUrl);\n\n if (width) {\n url.searchParams.set(\"width\", Math.round(width).toString());\n }\n if (height) {\n url.searchParams.set(\"height\", Math.round(height).toString());\n }\n if (resizeMethod) {\n url.searchParams.set(\"method\", resizeMethod);\n }\n if (animated !== undefined) {\n url.searchParams.set(\"animated\", String(animated));\n }\n\n if (typeof allowRedirects === \"boolean\") {\n // We add this after, so we don't convert everything to a thumbnail request.\n url.searchParams.set(\"allow_redirect\", JSON.stringify(allowRedirects));\n }\n\n return url.href;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAMA,eAAe,GACjB,8GAA8G;AAClH,SAASC,kBAAkBA,CAACC,UAAkB,EAAW;EACrD,IAAMC,OAAO,GAAGH,eAAe,CAACI,IAAI,CAACF,UAAU,CAAC;EAChD,OAAO,CAAAC,OAAO,aAAPA,OAAO,uBAAPA,OAAO,CAAG,CAAC,CAAC,MAAKD,UAAU;AACtC;;AAEA;AACA,IAAMG,YAAY,GAAG,UAAU;AAC/B,SAASC,eAAeA,CAACC,OAAe,EAAW;EAC/C,IAAMJ,OAAO,GAAGE,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ACAe,GAAG,CAACE,YAAY,CAACC,GAAG,CAAC,gBAAgB,EAAEK,IAAI,CAACC,SAAS,CAACxB,cAAc,CAAC,CAAC;EAC1E;EAEA,OAAOe,GAAG,CAACU,IAAI;AACnB","ignoreList":[]}
@@ -32,8 +32,8 @@ export class Backend {
32
32
  /**
33
33
  */
34
34
  constructor(db) {
35
- this.db = db;
36
35
  _defineProperty(this, "nextTxnId", 0);
36
+ this.db = db;
37
37
  // make sure we close the db on `onversionchange` - otherwise
38
38
  // attempts to delete the database will block (and subsequent
39
39
  // attempts to re-create it will also block).
@@ -253,15 +253,14 @@ export class Backend {
253
253
  try {
254
254
  var objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_SESSIONS);
255
255
  var _loop = function* _loop() {
256
+ var deviceKey = _ref3.deviceKey;
257
+ var sessionId = _ref3.sessionId;
256
258
  var req = objectStore.delete([deviceKey, sessionId]);
257
259
  yield new Promise(resolve => {
258
260
  req.onsuccess = resolve;
259
261
  });
260
262
  };
261
- for (var {
262
- deviceKey,
263
- sessionId
264
- } of sessions) {
263
+ for (var _ref3 of sessions) {
265
264
  yield* _loop();
266
265
  }
267
266
  } catch (e) {
@@ -398,19 +397,18 @@ export class Backend {
398
397
  var _this8 = this;
399
398
  return _asyncToGenerator(function* () {
400
399
  yield _this8.doTxn("readwrite", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], /*#__PURE__*/function () {
401
- var _ref2 = _asyncToGenerator(function* (txn) {
400
+ var _ref4 = _asyncToGenerator(function* (txn) {
402
401
  try {
403
402
  var objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);
404
403
  var _loop2 = function* _loop2() {
404
+ var senderKey = _ref6.senderKey;
405
+ var sessionId = _ref6.sessionId;
405
406
  var req = objectStore.delete([senderKey, sessionId]);
406
407
  yield new Promise(resolve => {
407
408
  req.onsuccess = resolve;
408
409
  });
409
410
  };
410
- for (var {
411
- senderKey,
412
- sessionId
413
- } of sessions) {
411
+ for (var _ref6 of sessions) {
414
412
  yield* _loop2();
415
413
  }
416
414
  } catch (e) {
@@ -418,7 +416,7 @@ export class Backend {
418
416
  }
419
417
  });
420
418
  return function (_x2) {
421
- return _ref2.apply(this, arguments);
419
+ return _ref4.apply(this, arguments);
422
420
  };
423
421
  }());
424
422
  })();
@@ -1 +1 @@
1
- {"version":3,"file":"indexeddb-crypto-store-backend.js","names":["logger","MigrationState","SESSION_BATCH_SIZE","ACCOUNT_OBJECT_KEY_MIGRATION_STATE","IndexedDBCryptoStore","PROFILE_TRANSACTIONS","Backend","constructor","db","_defineProperty","onversionchange","log","concat","name","close","containsData","_asyncToGenerator","Error","startup","_this","deleteAllData","getMigrationState","_this2","migrationState","NOT_STARTED","doTxn","STORE_ACCOUNT","txn","objectStore","getReq","get","onsuccess","_getReq$result","result","setMigrationState","_this3","put","getAccount","func","e","abortWithException","storeAccount","accountPickle","getCrossSigningKeys","getSecretStorePrivateKey","type","storeSecretStorePrivateKey","key","countEndToEndSessions","countReq","count","getEndToEndSessions","deviceKey","idx","index","openCursor","results","cursor","value","sessionId","session","lastReceivedMessageTs","continue","getEndToEndSession","storeEndToEndSession","sessionInfo","getEndToEndSessionsBatch","_this4","STORE_SESSIONS","push","length","deleteEndToEndSessionsBatch","sessions","_this5","_ref","_loop","req","delete","Promise","resolve","_x","apply","arguments","getEndToEndInboundGroupSession","senderCurve25519Key","withheld","withheldObjectStore","withheldGetReq","storeEndToEndInboundGroupSession","sessionData","countEndToEndInboundGroupSessions","_this6","STORE_INBOUND_GROUP_SESSIONS","sessionStore","getEndToEndInboundGroupSessionsBatch","_this7","STORE_BACKUP","backupStore","backupGetReq","senderKey","needsBackup","undefined","deleteEndToEndInboundGroupSessionsBatch","_this8","_ref2","_loop2","_x2","getEndToEndDeviceData","getEndToEndRooms","rooms","markSessionsNeedingBackup","_this9","transaction","all","map","reject","onerror","mode","stores","startTime","description","txnId","nextTxnId","Date","now","debug","promise","promiseifyTxn","then","elapsedTime","error","DB_MIGRATIONS","createDatabase","createObjectStore","sessionsStore","keyPath","createIndex","problemsStore","VERSION","upgradeDatabase","oldVersion","forEach","migration","outgoingRoomKeyRequestsStore","_mx_abortexception","abort","_unused","oncomplete","event","onabort"],"sources":["../../../src/crypto/store/indexeddb-crypto-store-backend.ts"],"sourcesContent":["/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type Logger, logger } from \"../../logger.ts\";\nimport {\n type CryptoStore,\n type IDeviceData,\n type ISession,\n type SessionExtended,\n type ISessionInfo,\n type IWithheld,\n MigrationState,\n type Mode,\n type SecretStorePrivateKeys,\n SESSION_BATCH_SIZE,\n ACCOUNT_OBJECT_KEY_MIGRATION_STATE,\n type InboundGroupSessionData,\n type IRoomEncryption,\n} from \"./base.ts\";\nimport { IndexedDBCryptoStore } from \"./indexeddb-crypto-store.ts\";\nimport { type CrossSigningKeyInfo } from \"../../crypto-api/index.ts\";\n\nconst PROFILE_TRANSACTIONS = false;\n\n/**\n * Implementation of a CryptoStore which is backed by an existing\n * IndexedDB connection. Generally you want IndexedDBCryptoStore\n * which connects to the database and defers to one of these.\n *\n * @internal\n */\nexport class Backend implements CryptoStore {\n private nextTxnId = 0;\n\n /**\n */\n public constructor(private db: IDBDatabase) {\n // make sure we close the db on `onversionchange` - otherwise\n // attempts to delete the database will block (and subsequent\n // attempts to re-create it will also block).\n db.onversionchange = (): void => {\n logger.log(`versionchange for indexeddb ${this.db.name}: closing`);\n db.close();\n };\n }\n\n public async containsData(): Promise<boolean> {\n throw Error(\"Not implemented for Backend\");\n }\n\n public async startup(): Promise<CryptoStore> {\n // No work to do, as the startup is done by the caller (e.g IndexedDBCryptoStore)\n // by passing us a ready IDBDatabase instance\n return this;\n }\n\n public async deleteAllData(): Promise<void> {\n throw Error(\"This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.\");\n }\n\n /**\n * Get data on how much of the libolm to Rust Crypto migration has been done.\n *\n * Implementation of {@link CryptoStore.getMigrationState}.\n */\n public async getMigrationState(): Promise<MigrationState> {\n let migrationState = MigrationState.NOT_STARTED;\n await this.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_ACCOUNT);\n const getReq = objectStore.get(ACCOUNT_OBJECT_KEY_MIGRATION_STATE);\n getReq.onsuccess = (): void => {\n migrationState = getReq.result ?? MigrationState.NOT_STARTED;\n };\n });\n return migrationState;\n }\n\n /**\n * Set data on how much of the libolm to Rust Crypto migration has been done.\n *\n * Implementation of {@link CryptoStore.setMigrationState}.\n */\n public async setMigrationState(migrationState: MigrationState): Promise<void> {\n await this.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_ACCOUNT);\n objectStore.put(migrationState, ACCOUNT_OBJECT_KEY_MIGRATION_STATE);\n });\n }\n\n // Olm Account\n\n public getAccount(txn: IDBTransaction, func: (accountPickle: string | null) => void): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(\"-\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public storeAccount(txn: IDBTransaction, accountPickle: string): void {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(accountPickle, \"-\");\n }\n\n public getCrossSigningKeys(\n txn: IDBTransaction,\n func: (keys: Record<string, CrossSigningKeyInfo> | null) => void,\n ): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(\"crossSigningKeys\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public getSecretStorePrivateKey<K extends keyof SecretStorePrivateKeys>(\n txn: IDBTransaction,\n func: (key: SecretStorePrivateKeys[K] | null) => void,\n type: K,\n ): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(`ssss_cache:${type}`);\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public storeSecretStorePrivateKey<K extends keyof SecretStorePrivateKeys>(\n txn: IDBTransaction,\n type: K,\n key: SecretStorePrivateKeys[K],\n ): void {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(key, `ssss_cache:${type}`);\n }\n\n // Olm Sessions\n\n public countEndToEndSessions(txn: IDBTransaction, func: (count: number) => void): void {\n const objectStore = txn.objectStore(\"sessions\");\n const countReq = objectStore.count();\n countReq.onsuccess = function (): void {\n try {\n func(countReq.result);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public getEndToEndSessions(\n deviceKey: string,\n txn: IDBTransaction,\n func: (sessions: { [sessionId: string]: ISessionInfo }) => void,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n const idx = objectStore.index(\"deviceKey\");\n const getReq = idx.openCursor(deviceKey);\n const results: Parameters<Parameters<Backend[\"getEndToEndSessions\"]>[2]>[0] = {};\n getReq.onsuccess = function (): void {\n const cursor = getReq.result;\n if (cursor) {\n results[cursor.value.sessionId] = {\n session: cursor.value.session,\n lastReceivedMessageTs: cursor.value.lastReceivedMessageTs,\n };\n cursor.continue();\n } else {\n try {\n func(results);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n }\n };\n }\n\n public getEndToEndSession(\n deviceKey: string,\n sessionId: string,\n txn: IDBTransaction,\n func: (session: ISessionInfo | null) => void,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n const getReq = objectStore.get([deviceKey, sessionId]);\n getReq.onsuccess = function (): void {\n try {\n if (getReq.result) {\n func({\n session: getReq.result.session,\n lastReceivedMessageTs: getReq.result.lastReceivedMessageTs,\n });\n } else {\n func(null);\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public storeEndToEndSession(\n deviceKey: string,\n sessionId: string,\n sessionInfo: ISessionInfo,\n txn: IDBTransaction,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n objectStore.put({\n deviceKey,\n sessionId,\n session: sessionInfo.session,\n lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs,\n });\n }\n\n /**\n * Fetch a batch of Olm sessions from the database.\n *\n * Implementation of {@link CryptoStore.getEndToEndSessionsBatch}.\n */\n public async getEndToEndSessionsBatch(): Promise<null | ISessionInfo[]> {\n const result: ISessionInfo[] = [];\n await this.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_SESSIONS], (txn) => {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_SESSIONS);\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function (): void {\n try {\n const cursor = getReq.result;\n if (cursor) {\n result.push(cursor.value);\n if (result.length < SESSION_BATCH_SIZE) {\n cursor.continue();\n }\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n });\n\n if (result.length === 0) {\n // No sessions left.\n return null;\n }\n\n return result;\n }\n\n /**\n * Delete a batch of Olm sessions from the database.\n *\n * Implementation of {@link CryptoStore.deleteEndToEndSessionsBatch}.\n *\n * @internal\n */\n public async deleteEndToEndSessionsBatch(sessions: { deviceKey: string; sessionId: string }[]): Promise<void> {\n await this.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_SESSIONS], async (txn) => {\n try {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_SESSIONS);\n for (const { deviceKey, sessionId } of sessions) {\n const req = objectStore.delete([deviceKey, sessionId]);\n await new Promise((resolve) => {\n req.onsuccess = resolve;\n });\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n });\n }\n\n // Inbound group sessions\n\n public getEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n txn: IDBTransaction,\n func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,\n ): void {\n let session: InboundGroupSessionData | null | boolean = false;\n let withheld: IWithheld | null | boolean = false;\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n const getReq = objectStore.get([senderCurve25519Key, sessionId]);\n getReq.onsuccess = function (): void {\n try {\n if (getReq.result) {\n session = getReq.result.session;\n } else {\n session = null;\n }\n if (withheld !== false) {\n func(session as InboundGroupSessionData, withheld as IWithheld);\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n\n const withheldObjectStore = txn.objectStore(\"inbound_group_sessions_withheld\");\n const withheldGetReq = withheldObjectStore.get([senderCurve25519Key, sessionId]);\n withheldGetReq.onsuccess = function (): void {\n try {\n if (withheldGetReq.result) {\n withheld = withheldGetReq.result.session;\n } else {\n withheld = null;\n }\n if (session !== false) {\n func(session as InboundGroupSessionData, withheld as IWithheld);\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public storeEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: IDBTransaction,\n ): void {\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n objectStore.put({\n senderCurve25519Key,\n sessionId,\n session: sessionData,\n });\n }\n\n /**\n * Count the number of Megolm sessions in the database.\n *\n * Implementation of {@link CryptoStore.countEndToEndInboundGroupSessions}.\n *\n * @internal\n */\n public async countEndToEndInboundGroupSessions(): Promise<number> {\n let result = 0;\n await this.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], (txn) => {\n const sessionStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);\n const countReq = sessionStore.count();\n countReq.onsuccess = (): void => {\n result = countReq.result;\n };\n });\n return result;\n }\n\n /**\n * Fetch a batch of Megolm sessions from the database.\n *\n * Implementation of {@link CryptoStore.getEndToEndInboundGroupSessionsBatch}.\n */\n public async getEndToEndInboundGroupSessionsBatch(): Promise<null | SessionExtended[]> {\n const result: SessionExtended[] = [];\n await this.doTxn(\n \"readonly\",\n [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, IndexedDBCryptoStore.STORE_BACKUP],\n (txn) => {\n const sessionStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);\n const backupStore = txn.objectStore(IndexedDBCryptoStore.STORE_BACKUP);\n\n const getReq = sessionStore.openCursor();\n getReq.onsuccess = function (): void {\n try {\n const cursor = getReq.result;\n if (cursor) {\n const backupGetReq = backupStore.get(cursor.key);\n backupGetReq.onsuccess = (): void => {\n result.push({\n senderKey: cursor.value.senderCurve25519Key,\n sessionId: cursor.value.sessionId,\n sessionData: cursor.value.session,\n needsBackup: backupGetReq.result !== undefined,\n });\n if (result.length < SESSION_BATCH_SIZE) {\n cursor.continue();\n }\n };\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n },\n );\n\n if (result.length === 0) {\n // No sessions left.\n return null;\n }\n\n return result;\n }\n\n /**\n * Delete a batch of Megolm sessions from the database.\n *\n * Implementation of {@link CryptoStore.deleteEndToEndInboundGroupSessionsBatch}.\n *\n * @internal\n */\n public async deleteEndToEndInboundGroupSessionsBatch(\n sessions: { senderKey: string; sessionId: string }[],\n ): Promise<void> {\n await this.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], async (txn) => {\n try {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);\n for (const { senderKey, sessionId } of sessions) {\n const req = objectStore.delete([senderKey, sessionId]);\n await new Promise((resolve) => {\n req.onsuccess = resolve;\n });\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n });\n }\n\n public getEndToEndDeviceData(txn: IDBTransaction, func: (deviceData: IDeviceData | null) => void): void {\n const objectStore = txn.objectStore(\"device_data\");\n const getReq = objectStore.get(\"-\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public getEndToEndRooms(txn: IDBTransaction, func: (rooms: Record<string, IRoomEncryption>) => void): void {\n const rooms: Parameters<Parameters<Backend[\"getEndToEndRooms\"]>[1]>[0] = {};\n const objectStore = txn.objectStore(\"rooms\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function (): void {\n const cursor = getReq.result;\n if (cursor) {\n rooms[cursor.key as string] = cursor.value;\n cursor.continue();\n } else {\n try {\n func(rooms);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n }\n };\n }\n\n public async markSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise<void> {\n if (!txn) {\n txn = this.db.transaction(\"sessions_needing_backup\", \"readwrite\");\n }\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n await Promise.all(\n sessions.map((session) => {\n return new Promise((resolve, reject) => {\n const req = objectStore.put({\n senderCurve25519Key: session.senderKey,\n sessionId: session.sessionId,\n });\n req.onsuccess = resolve;\n req.onerror = reject;\n });\n }),\n );\n }\n\n public doTxn<T>(\n mode: Mode,\n stores: string | string[],\n func: (txn: IDBTransaction) => T,\n log: Logger = logger,\n ): Promise<T> {\n let startTime: number;\n let description: string;\n if (PROFILE_TRANSACTIONS) {\n const txnId = this.nextTxnId++;\n startTime = Date.now();\n description = `${mode} crypto store transaction ${txnId} in ${stores}`;\n log.debug(`Starting ${description}`);\n }\n const txn = this.db.transaction(stores, mode);\n const promise = promiseifyTxn(txn);\n const result = func(txn);\n if (PROFILE_TRANSACTIONS) {\n promise.then(\n () => {\n const elapsedTime = Date.now() - startTime;\n log.debug(`Finished ${description}, took ${elapsedTime} ms`);\n },\n () => {\n const elapsedTime = Date.now() - startTime;\n log.error(`Failed ${description}, took ${elapsedTime} ms`);\n },\n );\n }\n return promise.then(() => {\n return result;\n });\n }\n}\n\ntype DbMigration = (db: IDBDatabase) => void;\nconst DB_MIGRATIONS: DbMigration[] = [\n (db): void => {\n createDatabase(db);\n },\n (db): void => {\n db.createObjectStore(\"account\");\n },\n (db): void => {\n const sessionsStore = db.createObjectStore(\"sessions\", {\n keyPath: [\"deviceKey\", \"sessionId\"],\n });\n sessionsStore.createIndex(\"deviceKey\", \"deviceKey\");\n },\n (db): void => {\n db.createObjectStore(\"inbound_group_sessions\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"device_data\");\n },\n (db): void => {\n db.createObjectStore(\"rooms\");\n },\n (db): void => {\n db.createObjectStore(\"sessions_needing_backup\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"inbound_group_sessions_withheld\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n const problemsStore = db.createObjectStore(\"session_problems\", {\n keyPath: [\"deviceKey\", \"time\"],\n });\n problemsStore.createIndex(\"deviceKey\", \"deviceKey\");\n\n db.createObjectStore(\"notified_error_devices\", {\n keyPath: [\"userId\", \"deviceId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"shared_history_inbound_group_sessions\", {\n keyPath: [\"roomId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"parked_shared_history\", {\n keyPath: [\"roomId\"],\n });\n },\n // Expand as needed.\n];\nexport const VERSION = DB_MIGRATIONS.length;\n\nexport function upgradeDatabase(db: IDBDatabase, oldVersion: number): void {\n logger.log(`Upgrading IndexedDBCryptoStore from version ${oldVersion}` + ` to ${VERSION}`);\n DB_MIGRATIONS.forEach((migration, index) => {\n if (oldVersion <= index) migration(db);\n });\n}\n\nfunction createDatabase(db: IDBDatabase): void {\n const outgoingRoomKeyRequestsStore = db.createObjectStore(\"outgoingRoomKeyRequests\", { keyPath: \"requestId\" });\n\n // we assume that the RoomKeyRequestBody will have room_id and session_id\n // properties, to make the index efficient.\n outgoingRoomKeyRequestsStore.createIndex(\"session\", [\"requestBody.room_id\", \"requestBody.session_id\"]);\n\n outgoingRoomKeyRequestsStore.createIndex(\"state\", \"state\");\n}\n\ninterface IWrappedIDBTransaction extends IDBTransaction {\n _mx_abortexception: Error; // eslint-disable-line camelcase\n}\n\n/*\n * Aborts a transaction with a given exception\n * The transaction promise will be rejected with this exception.\n */\nfunction abortWithException(txn: IDBTransaction, e: Error): void {\n // We cheekily stick our exception onto the transaction object here\n // We could alternatively make the thing we pass back to the app\n // an object containing the transaction and exception.\n (txn as IWrappedIDBTransaction)._mx_abortexception = e;\n try {\n txn.abort();\n } catch {\n // sometimes we won't be able to abort the transaction\n // (ie. if it's aborted or completed)\n }\n}\n\nfunction promiseifyTxn<T>(txn: IDBTransaction): Promise<T | null> {\n return new Promise((resolve, reject) => {\n txn.oncomplete = (): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n }\n resolve(null);\n };\n txn.onerror = (event): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n } else {\n logger.log(\"Error performing indexeddb txn\", event);\n reject(txn.error);\n }\n };\n txn.onabort = (event): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n } else {\n logger.log(\"Error performing indexeddb txn\", event);\n reject(txn.error);\n }\n };\n });\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAsBA,MAAM,QAAQ,iBAAiB;AACrD,SAOIC,cAAc,EAGdC,kBAAkB,EAClBC,kCAAkC,QAG/B,WAAW;AAClB,SAASC,oBAAoB,QAAQ,6BAA6B;AAGlE,IAAMC,o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,kBAAkB,KAAK3C,SAAS,EAAE;QAClEc,MAAM,CAAExF,GAAG,CAA4BqH,kBAAkB,CAAC;MAC9D;MACAjE,OAAO,CAAC,IAAI,CAAC;IACjB,CAAC;IACDpD,GAAG,CAACyF,OAAO,GAAIgC,KAAK,IAAW;MAC3B,IAAKzH,GAAG,CAA4BqH,kBAAkB,KAAK3C,SAAS,EAAE;QAClEc,MAAM,CAAExF,GAAG,CAA4BqH,kBAAkB,CAAC;MAC9D,CAAC,MAAM;QACHhJ,MAAM,CAACW,GAAG,CAAC,gCAAgC,EAAEyI,KAAK,CAAC;QACnDjC,MAAM,CAACxF,GAAG,CAACuG,KAAK,CAAC;MACrB;IACJ,CAAC;IACDvG,GAAG,CAAC0H,OAAO,GAAID,KAAK,IAAW;MAC3B,IAAKzH,GAAG,CAA4BqH,kBAAkB,KAAK3C,SAAS,EAAE;QAClEc,MAAM,CAAExF,GAAG,CAA4BqH,kBAAkB,CAAC;MAC9D,CAAC,MAAM;QACHhJ,MAAM,CAACW,GAAG,CAAC,gCAAgC,EAAEyI,KAAK,CAAC;QACnDjC,MAAM,CAACxF,GAAG,CAACuG,KAAK,CAAC;MACrB;IACJ,CAAC;EACL,CAAC,CAAC;AACN","ignoreList":[]}
1
+ {"version":3,"file":"indexeddb-crypto-store-backend.js","names":["logger","MigrationState","SESSION_BATCH_SIZE","ACCOUNT_OBJECT_KEY_MIGRATION_STATE","IndexedDBCryptoStore","PROFILE_TRANSACTIONS","Backend","constructor","db","_defineProperty","onversionchange","log","concat","name","close","containsData","_asyncToGenerator","Error","startup","_this","deleteAllData","getMigrationState","_this2","migrationState","NOT_STARTED","doTxn","STORE_ACCOUNT","txn","objectStore","getReq","get","onsuccess","_getReq$result","result","setMigrationState","_this3","put","getAccount","func","e","abortWithException","storeAccount","accountPickle","getCrossSigningKeys","getSecretStorePrivateKey","type","storeSecretStorePrivateKey","key","countEndToEndSessions","countReq","count","getEndToEndSessions","deviceKey","idx","index","openCursor","results","cursor","value","sessionId","session","lastReceivedMessageTs","continue","getEndToEndSession","storeEndToEndSession","sessionInfo","getEndToEndSessionsBatch","_this4","STORE_SESSIONS","push","length","deleteEndToEndSessionsBatch","sessions","_this5","_ref","_loop","_ref3","req","delete","Promise","resolve","_x","apply","arguments","getEndToEndInboundGroupSession","senderCurve25519Key","withheld","withheldObjectStore","withheldGetReq","storeEndToEndInboundGroupSession","sessionData","countEndToEndInboundGroupSessions","_this6","STORE_INBOUND_GROUP_SESSIONS","sessionStore","getEndToEndInboundGroupSessionsBatch","_this7","STORE_BACKUP","backupStore","backupGetReq","senderKey","needsBackup","undefined","deleteEndToEndInboundGroupSessionsBatch","_this8","_ref4","_loop2","_ref6","_x2","getEndToEndDeviceData","getEndToEndRooms","rooms","markSessionsNeedingBackup","_this9","transaction","all","map","reject","onerror","mode","stores","startTime","description","txnId","nextTxnId","Date","now","debug","promise","promiseifyTxn","then","elapsedTime","error","DB_MIGRATIONS","createDatabase","createObjectStore","sessionsStore","keyPath","createIndex","problemsStore","VERSION","upgradeDatabase","oldVersion","forEach","migration","outgoingRoomKeyRequestsStore","_mx_abortexception","abort","_unused","oncomplete","event","onabort"],"sources":["../../../src/crypto/store/indexeddb-crypto-store-backend.ts"],"sourcesContent":["/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type Logger, logger } from \"../../logger.ts\";\nimport {\n type CryptoStore,\n type IDeviceData,\n type ISession,\n type SessionExtended,\n type ISessionInfo,\n type IWithheld,\n MigrationState,\n type Mode,\n type SecretStorePrivateKeys,\n SESSION_BATCH_SIZE,\n ACCOUNT_OBJECT_KEY_MIGRATION_STATE,\n type InboundGroupSessionData,\n type IRoomEncryption,\n} from \"./base.ts\";\nimport { IndexedDBCryptoStore } from \"./indexeddb-crypto-store.ts\";\nimport { type CrossSigningKeyInfo } from \"../../crypto-api/index.ts\";\n\nconst PROFILE_TRANSACTIONS = false;\n\n/**\n * Implementation of a CryptoStore which is backed by an existing\n * IndexedDB connection. Generally you want IndexedDBCryptoStore\n * which connects to the database and defers to one of these.\n *\n * @internal\n */\nexport class Backend implements CryptoStore {\n private nextTxnId = 0;\n\n /**\n */\n public constructor(private db: IDBDatabase) {\n // make sure we close the db on `onversionchange` - otherwise\n // attempts to delete the database will block (and subsequent\n // attempts to re-create it will also block).\n db.onversionchange = (): void => {\n logger.log(`versionchange for indexeddb ${this.db.name}: closing`);\n db.close();\n };\n }\n\n public async containsData(): Promise<boolean> {\n throw Error(\"Not implemented for Backend\");\n }\n\n public async startup(): Promise<CryptoStore> {\n // No work to do, as the startup is done by the caller (e.g IndexedDBCryptoStore)\n // by passing us a ready IDBDatabase instance\n return this;\n }\n\n public async deleteAllData(): Promise<void> {\n throw Error(\"This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.\");\n }\n\n /**\n * Get data on how much of the libolm to Rust Crypto migration has been done.\n *\n * Implementation of {@link CryptoStore.getMigrationState}.\n */\n public async getMigrationState(): Promise<MigrationState> {\n let migrationState = MigrationState.NOT_STARTED;\n await this.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_ACCOUNT);\n const getReq = objectStore.get(ACCOUNT_OBJECT_KEY_MIGRATION_STATE);\n getReq.onsuccess = (): void => {\n migrationState = getReq.result ?? MigrationState.NOT_STARTED;\n };\n });\n return migrationState;\n }\n\n /**\n * Set data on how much of the libolm to Rust Crypto migration has been done.\n *\n * Implementation of {@link CryptoStore.setMigrationState}.\n */\n public async setMigrationState(migrationState: MigrationState): Promise<void> {\n await this.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_ACCOUNT);\n objectStore.put(migrationState, ACCOUNT_OBJECT_KEY_MIGRATION_STATE);\n });\n }\n\n // Olm Account\n\n public getAccount(txn: IDBTransaction, func: (accountPickle: string | null) => void): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(\"-\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public storeAccount(txn: IDBTransaction, accountPickle: string): void {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(accountPickle, \"-\");\n }\n\n public getCrossSigningKeys(\n txn: IDBTransaction,\n func: (keys: Record<string, CrossSigningKeyInfo> | null) => void,\n ): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(\"crossSigningKeys\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public getSecretStorePrivateKey<K extends keyof SecretStorePrivateKeys>(\n txn: IDBTransaction,\n func: (key: SecretStorePrivateKeys[K] | null) => void,\n type: K,\n ): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(`ssss_cache:${type}`);\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public storeSecretStorePrivateKey<K extends keyof SecretStorePrivateKeys>(\n txn: IDBTransaction,\n type: K,\n key: SecretStorePrivateKeys[K],\n ): void {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(key, `ssss_cache:${type}`);\n }\n\n // Olm Sessions\n\n public countEndToEndSessions(txn: IDBTransaction, func: (count: number) => void): void {\n const objectStore = txn.objectStore(\"sessions\");\n const countReq = objectStore.count();\n countReq.onsuccess = function (): void {\n try {\n func(countReq.result);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public getEndToEndSessions(\n deviceKey: string,\n txn: IDBTransaction,\n func: (sessions: { [sessionId: string]: ISessionInfo }) => void,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n const idx = objectStore.index(\"deviceKey\");\n const getReq = idx.openCursor(deviceKey);\n const results: Parameters<Parameters<Backend[\"getEndToEndSessions\"]>[2]>[0] = {};\n getReq.onsuccess = function (): void {\n const cursor = getReq.result;\n if (cursor) {\n results[cursor.value.sessionId] = {\n session: cursor.value.session,\n lastReceivedMessageTs: cursor.value.lastReceivedMessageTs,\n };\n cursor.continue();\n } else {\n try {\n func(results);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n }\n };\n }\n\n public getEndToEndSession(\n deviceKey: string,\n sessionId: string,\n txn: IDBTransaction,\n func: (session: ISessionInfo | null) => void,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n const getReq = objectStore.get([deviceKey, sessionId]);\n getReq.onsuccess = function (): void {\n try {\n if (getReq.result) {\n func({\n session: getReq.result.session,\n lastReceivedMessageTs: getReq.result.lastReceivedMessageTs,\n });\n } else {\n func(null);\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public storeEndToEndSession(\n deviceKey: string,\n sessionId: string,\n sessionInfo: ISessionInfo,\n txn: IDBTransaction,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n objectStore.put({\n deviceKey,\n sessionId,\n session: sessionInfo.session,\n lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs,\n });\n }\n\n /**\n * Fetch a batch of Olm sessions from the database.\n *\n * Implementation of {@link CryptoStore.getEndToEndSessionsBatch}.\n */\n public async getEndToEndSessionsBatch(): Promise<null | ISessionInfo[]> {\n const result: ISessionInfo[] = [];\n await this.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_SESSIONS], (txn) => {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_SESSIONS);\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function (): void {\n try {\n const cursor = getReq.result;\n if (cursor) {\n result.push(cursor.value);\n if (result.length < SESSION_BATCH_SIZE) {\n cursor.continue();\n }\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n });\n\n if (result.length === 0) {\n // No sessions left.\n return null;\n }\n\n return result;\n }\n\n /**\n * Delete a batch of Olm sessions from the database.\n *\n * Implementation of {@link CryptoStore.deleteEndToEndSessionsBatch}.\n *\n * @internal\n */\n public async deleteEndToEndSessionsBatch(sessions: { deviceKey: string; sessionId: string }[]): Promise<void> {\n await this.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_SESSIONS], async (txn) => {\n try {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_SESSIONS);\n for (const { deviceKey, sessionId } of sessions) {\n const req = objectStore.delete([deviceKey, sessionId]);\n await new Promise((resolve) => {\n req.onsuccess = resolve;\n });\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n });\n }\n\n // Inbound group sessions\n\n public getEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n txn: IDBTransaction,\n func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,\n ): void {\n let session: InboundGroupSessionData | null | boolean = false;\n let withheld: IWithheld | null | boolean = false;\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n const getReq = objectStore.get([senderCurve25519Key, sessionId]);\n getReq.onsuccess = function (): void {\n try {\n if (getReq.result) {\n session = getReq.result.session;\n } else {\n session = null;\n }\n if (withheld !== false) {\n func(session as InboundGroupSessionData, withheld as IWithheld);\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n\n const withheldObjectStore = txn.objectStore(\"inbound_group_sessions_withheld\");\n const withheldGetReq = withheldObjectStore.get([senderCurve25519Key, sessionId]);\n withheldGetReq.onsuccess = function (): void {\n try {\n if (withheldGetReq.result) {\n withheld = withheldGetReq.result.session;\n } else {\n withheld = null;\n }\n if (session !== false) {\n func(session as InboundGroupSessionData, withheld as IWithheld);\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public storeEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: IDBTransaction,\n ): void {\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n objectStore.put({\n senderCurve25519Key,\n sessionId,\n session: sessionData,\n });\n }\n\n /**\n * Count the number of Megolm sessions in the database.\n *\n * Implementation of {@link CryptoStore.countEndToEndInboundGroupSessions}.\n *\n * @internal\n */\n public async countEndToEndInboundGroupSessions(): Promise<number> {\n let result = 0;\n await this.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], (txn) => {\n const sessionStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);\n const countReq = sessionStore.count();\n countReq.onsuccess = (): void => {\n result = countReq.result;\n };\n });\n return result;\n }\n\n /**\n * Fetch a batch of Megolm sessions from the database.\n *\n * Implementation of {@link CryptoStore.getEndToEndInboundGroupSessionsBatch}.\n */\n public async getEndToEndInboundGroupSessionsBatch(): Promise<null | SessionExtended[]> {\n const result: SessionExtended[] = [];\n await this.doTxn(\n \"readonly\",\n [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, IndexedDBCryptoStore.STORE_BACKUP],\n (txn) => {\n const sessionStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);\n const backupStore = txn.objectStore(IndexedDBCryptoStore.STORE_BACKUP);\n\n const getReq = sessionStore.openCursor();\n getReq.onsuccess = function (): void {\n try {\n const cursor = getReq.result;\n if (cursor) {\n const backupGetReq = backupStore.get(cursor.key);\n backupGetReq.onsuccess = (): void => {\n result.push({\n senderKey: cursor.value.senderCurve25519Key,\n sessionId: cursor.value.sessionId,\n sessionData: cursor.value.session,\n needsBackup: backupGetReq.result !== undefined,\n });\n if (result.length < SESSION_BATCH_SIZE) {\n cursor.continue();\n }\n };\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n },\n );\n\n if (result.length === 0) {\n // No sessions left.\n return null;\n }\n\n return result;\n }\n\n /**\n * Delete a batch of Megolm sessions from the database.\n *\n * Implementation of {@link CryptoStore.deleteEndToEndInboundGroupSessionsBatch}.\n *\n * @internal\n */\n public async deleteEndToEndInboundGroupSessionsBatch(\n sessions: { senderKey: string; sessionId: string }[],\n ): Promise<void> {\n await this.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], async (txn) => {\n try {\n const objectStore = txn.objectStore(IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS);\n for (const { senderKey, sessionId } of sessions) {\n const req = objectStore.delete([senderKey, sessionId]);\n await new Promise((resolve) => {\n req.onsuccess = resolve;\n });\n }\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n });\n }\n\n public getEndToEndDeviceData(txn: IDBTransaction, func: (deviceData: IDeviceData | null) => void): void {\n const objectStore = txn.objectStore(\"device_data\");\n const getReq = objectStore.get(\"-\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n };\n }\n\n public getEndToEndRooms(txn: IDBTransaction, func: (rooms: Record<string, IRoomEncryption>) => void): void {\n const rooms: Parameters<Parameters<Backend[\"getEndToEndRooms\"]>[1]>[0] = {};\n const objectStore = txn.objectStore(\"rooms\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function (): void {\n const cursor = getReq.result;\n if (cursor) {\n rooms[cursor.key as string] = cursor.value;\n cursor.continue();\n } else {\n try {\n func(rooms);\n } catch (e) {\n abortWithException(txn, <Error>e);\n }\n }\n };\n }\n\n public async markSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise<void> {\n if (!txn) {\n txn = this.db.transaction(\"sessions_needing_backup\", \"readwrite\");\n }\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n await Promise.all(\n sessions.map((session) => {\n return new Promise((resolve, reject) => {\n const req = objectStore.put({\n senderCurve25519Key: session.senderKey,\n sessionId: session.sessionId,\n });\n req.onsuccess = resolve;\n req.onerror = reject;\n });\n }),\n );\n }\n\n public doTxn<T>(\n mode: Mode,\n stores: string | string[],\n func: (txn: IDBTransaction) => T,\n log: Logger = logger,\n ): Promise<T> {\n let startTime: number;\n let description: string;\n if (PROFILE_TRANSACTIONS) {\n const txnId = this.nextTxnId++;\n startTime = Date.now();\n description = `${mode} crypto store transaction ${txnId} in ${stores}`;\n log.debug(`Starting ${description}`);\n }\n const txn = this.db.transaction(stores, mode);\n const promise = promiseifyTxn(txn);\n const result = func(txn);\n if (PROFILE_TRANSACTIONS) {\n promise.then(\n () => {\n const elapsedTime = Date.now() - startTime;\n log.debug(`Finished ${description}, took ${elapsedTime} ms`);\n },\n () => {\n const elapsedTime = Date.now() - startTime;\n log.error(`Failed ${description}, took ${elapsedTime} ms`);\n },\n );\n }\n return promise.then(() => {\n return result;\n });\n }\n}\n\ntype DbMigration = (db: IDBDatabase) => void;\nconst DB_MIGRATIONS: DbMigration[] = [\n (db): void => {\n createDatabase(db);\n },\n (db): void => {\n db.createObjectStore(\"account\");\n },\n (db): void => {\n const sessionsStore = db.createObjectStore(\"sessions\", {\n keyPath: [\"deviceKey\", \"sessionId\"],\n });\n sessionsStore.createIndex(\"deviceKey\", \"deviceKey\");\n },\n (db): void => {\n db.createObjectStore(\"inbound_group_sessions\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"device_data\");\n },\n (db): void => {\n db.createObjectStore(\"rooms\");\n },\n (db): void => {\n db.createObjectStore(\"sessions_needing_backup\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"inbound_group_sessions_withheld\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n const problemsStore = db.createObjectStore(\"session_problems\", {\n keyPath: [\"deviceKey\", \"time\"],\n });\n problemsStore.createIndex(\"deviceKey\", \"deviceKey\");\n\n db.createObjectStore(\"notified_error_devices\", {\n keyPath: [\"userId\", \"deviceId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"shared_history_inbound_group_sessions\", {\n keyPath: [\"roomId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"parked_shared_history\", {\n keyPath: [\"roomId\"],\n });\n },\n // Expand as needed.\n];\nexport const VERSION = DB_MIGRATIONS.length;\n\nexport function upgradeDatabase(db: IDBDatabase, oldVersion: number): void {\n logger.log(`Upgrading IndexedDBCryptoStore from version ${oldVersion}` + ` to ${VERSION}`);\n DB_MIGRATIONS.forEach((migration, index) => {\n if (oldVersion <= index) migration(db);\n });\n}\n\nfunction createDatabase(db: IDBDatabase): void {\n const outgoingRoomKeyRequestsStore = db.createObjectStore(\"outgoingRoomKeyRequests\", { keyPath: \"requestId\" });\n\n // we assume that the RoomKeyRequestBody will have room_id and session_id\n // properties, to make the index efficient.\n outgoingRoomKeyRequestsStore.createIndex(\"session\", [\"requestBody.room_id\", \"requestBody.session_id\"]);\n\n outgoingRoomKeyRequestsStore.createIndex(\"state\", \"state\");\n}\n\ninterface IWrappedIDBTransaction extends IDBTransaction {\n _mx_abortexception: Error; // eslint-disable-line camelcase\n}\n\n/*\n * Aborts a transaction with a given exception\n * The transaction promise will be rejected with this exception.\n */\nfunction abortWithException(txn: IDBTransaction, e: Error): void {\n // We cheekily stick our exception onto the transaction object here\n // We could alternatively make the thing we pass back to the app\n // an object containing the transaction and exception.\n (txn as IWrappedIDBTransaction)._mx_abortexception = e;\n try {\n txn.abort();\n } catch {\n // sometimes we won't be able to abort the transaction\n // (ie. if it's aborted or completed)\n }\n}\n\nfunction promiseifyTxn<T>(txn: IDBTransaction): Promise<T | null> {\n return new Promise((resolve, reject) => {\n txn.oncomplete = (): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n }\n resolve(null);\n };\n txn.onerror = (event): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n } else {\n logger.log(\"Error performing indexeddb txn\", event);\n reject(txn.error);\n }\n };\n txn.onabort = (event): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n } else {\n logger.log(\"Error performing indexeddb txn\", event);\n reject(txn.error);\n }\n };\n });\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAsBA,MAAM,QAAQ,iBAAiB;AACrD,SAOIC,cAAc,EAGdC,kBAAkB,EAClBC,kCAAkC,QAG/B,WAAW;AAClB,SAASC,oBAAoB,QAAQ,6BAA6B;AAGlE,IAAMC,oBAAoB,GAAG,KAAK;;AAElC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,OAAO,CAAwB;EAGxC;AACJ;EACWC,WAAWA,CAASC,EAAe,EAAE;IAAAC,eAAA,oBAJxB,CAAC;IAAA,KAIMD,EAAe,GAAfA,EAAe;IACtC;IACA;IACA;IACAA,EAAE,CAACE,eAAe,GAAG,MAAY;MAC7BV,MAAM,CAACW,GAAG,gCAAAC,MAAA,CAAgC,IAAI,CAACJ,EAAE,CAACK,IAAI,cAAW,CAAC;MAClEL,EAAE,CAACM,KAAK,CAAC,CAAC;IACd,CAAC;EACL;EAEaC,YAAYA,CAAA,EAAqB;IAAA,OAAAC,iBAAA;MAC1C,MAAMC,KAAK,CAAC,6BAA6B,CAAC;IAAC;EAC/C;EAEaC,OAAOA,CAAA,EAAyB;IAAA,IAAAC,KAAA;IAAA,OAAAH,iBAAA;MACzC;MACA;MACA,OAAOG,KAAI;IAAC;EAChB;EAEaC,aAAaA,CAAA,EAAkB;IAAA,OAAAJ,iBAAA;MACxC,MAAMC,KAAK,C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AAK5C,SAAS,EAAE;QAClEe,MAAM,CAAE1F,GAAG,CAA4BuH,kBAAkB,CAAC;MAC9D,CAAC,MAAM;QACHlJ,MAAM,CAACW,GAAG,CAAC,gCAAgC,EAAE2I,KAAK,CAAC;QACnDjC,MAAM,CAAC1F,GAAG,CAACyG,KAAK,CAAC;MACrB;IACJ,CAAC;EACL,CAAC,CAAC;AACN","ignoreList":[]}
@@ -88,8 +88,6 @@ export class IndexedDBCryptoStore {
88
88
  constructor(indexedDB, dbName) {
89
89
  this.indexedDB = indexedDB;
90
90
  this.dbName = dbName;
91
- _defineProperty(this, "backendPromise", void 0);
92
- _defineProperty(this, "backend", void 0);
93
91
  }
94
92
 
95
93
  /**