matrix-js-sdk 41.8.0 → 41.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +1 -1
- package/lib/@types/AESEncryptedSecretStoragePayload.js +3 -1
- package/lib/@types/IIdentityServerProvider.js +3 -1
- package/lib/@types/PushRules.js +7 -7
- package/lib/@types/PushRules.js.map +1 -1
- package/lib/@types/auth.js +4 -4
- package/lib/@types/auth.js.map +1 -1
- package/lib/@types/beacon.js +2 -2
- package/lib/@types/beacon.js.map +1 -1
- package/lib/@types/common.js +3 -1
- package/lib/@types/crypto.js +3 -1
- package/lib/@types/event.js +20 -20
- package/lib/@types/event.js.map +1 -1
- package/lib/@types/events.js +3 -1
- package/lib/@types/extensible_events.js +6 -6
- package/lib/@types/extensible_events.js.map +1 -1
- package/lib/@types/global.d.js.map +1 -1
- package/lib/@types/json.js +3 -1
- package/lib/@types/local_notifications.js +3 -1
- package/lib/@types/location.js +4 -4
- package/lib/@types/location.js.map +1 -1
- package/lib/@types/matrix-sdk-crypto-wasm.d.js +3 -1
- package/lib/@types/media.js +3 -1
- package/lib/@types/membership.js +1 -1
- package/lib/@types/membership.js.map +1 -1
- package/lib/@types/partials.js +6 -6
- package/lib/@types/partials.js.map +1 -1
- package/lib/@types/polls.js +5 -5
- package/lib/@types/polls.js.map +1 -1
- package/lib/@types/read_receipts.js +2 -2
- package/lib/@types/read_receipts.js.map +1 -1
- package/lib/@types/registration.js +3 -1
- package/lib/@types/requests.js +1 -1
- package/lib/@types/requests.js.map +1 -1
- package/lib/@types/retention.js +1 -1
- package/lib/@types/retention.js.map +1 -1
- package/lib/@types/search.js +1 -1
- package/lib/@types/search.js.map +1 -1
- package/lib/@types/signed.js +3 -1
- package/lib/@types/spaces.js +3 -1
- package/lib/@types/state_events.js +3 -1
- package/lib/@types/synapse.js +3 -1
- package/lib/@types/sync.js +1 -1
- package/lib/@types/sync.js.map +1 -1
- package/lib/@types/threepids.js +1 -1
- package/lib/@types/threepids.js.map +1 -1
- package/lib/@types/topic.js +1 -1
- package/lib/@types/topic.js.map +1 -1
- package/lib/@types/uia.js +3 -1
- package/lib/NamespacedValue.js +8 -8
- package/lib/NamespacedValue.js.map +1 -1
- package/lib/ReEmitter.js +9 -16
- package/lib/ReEmitter.js.map +1 -1
- package/lib/ToDeviceMessageQueue.js +49 -57
- package/lib/ToDeviceMessageQueue.js.map +1 -1
- package/lib/autodiscovery.js +232 -247
- package/lib/autodiscovery.js.map +1 -1
- package/lib/base64.js +1 -1
- package/lib/base64.js.map +1 -1
- package/lib/browser-index.d.ts +2 -2
- package/lib/browser-index.d.ts.map +1 -1
- package/lib/browser-index.js +5 -5
- package/lib/browser-index.js.map +1 -1
- package/lib/capabilityPoller.js +19 -22
- package/lib/capabilityPoller.js.map +1 -1
- package/lib/client.d.ts +2 -8
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +2043 -2487
- package/lib/client.js.map +1 -1
- package/lib/common-crypto/CryptoBackend.js +2 -2
- package/lib/common-crypto/CryptoBackend.js.map +1 -1
- package/lib/common-crypto/key-passphrase.js.map +1 -1
- package/lib/content-helpers.js +43 -48
- package/lib/content-helpers.js.map +1 -1
- package/lib/content-repo.js +14 -24
- package/lib/content-repo.js.map +1 -1
- package/lib/crypto/store/base.js +6 -6
- package/lib/crypto/store/base.js.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store-backend.js +190 -238
- package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store.js +25 -30
- package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
- package/lib/crypto/store/localStorage-crypto-store.js +113 -145
- package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
- package/lib/crypto/store/memory-crypto-store.js +74 -105
- package/lib/crypto/store/memory-crypto-store.js.map +1 -1
- package/lib/crypto-api/CryptoEvent.js +1 -1
- package/lib/crypto-api/CryptoEvent.js.map +1 -1
- package/lib/crypto-api/CryptoEventHandlerMap.js +3 -1
- package/lib/crypto-api/index.d.ts +15 -6
- package/lib/crypto-api/index.d.ts.map +1 -1
- package/lib/crypto-api/index.js +22 -22
- package/lib/crypto-api/index.js.map +1 -1
- package/lib/crypto-api/key-passphrase.js +15 -23
- package/lib/crypto-api/key-passphrase.js.map +1 -1
- package/lib/crypto-api/keybackup.js +3 -1
- package/lib/crypto-api/recovery-key.js +11 -12
- package/lib/crypto-api/recovery-key.js.map +1 -1
- package/lib/crypto-api/verification.js +3 -3
- package/lib/crypto-api/verification.js.map +1 -1
- package/lib/digest.js +7 -14
- package/lib/digest.js.map +1 -1
- package/lib/embedded.d.ts.map +1 -1
- package/lib/embedded.js +380 -505
- package/lib/embedded.js.map +1 -1
- package/lib/errors.js +2 -2
- package/lib/errors.js.map +1 -1
- package/lib/event-mapper.js +10 -12
- package/lib/event-mapper.js.map +1 -1
- package/lib/extensible_events_v1/ExtensibleEvent.js.map +1 -1
- package/lib/extensible_events_v1/InvalidEventError.js.map +1 -1
- package/lib/extensible_events_v1/MessageEvent.js +11 -13
- package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollEndEvent.js +3 -4
- package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollResponseEvent.js +5 -6
- package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollStartEvent.js +8 -10
- package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
- package/lib/extensible_events_v1/utilities.js.map +1 -1
- package/lib/feature.js +18 -31
- package/lib/feature.js.map +1 -1
- package/lib/filter-component.d.ts.map +1 -1
- package/lib/filter-component.js +20 -26
- package/lib/filter-component.js.map +1 -1
- package/lib/filter.js +14 -17
- package/lib/filter.js.map +1 -1
- package/lib/http-api/errors.js +28 -43
- package/lib/http-api/errors.js.map +1 -1
- package/lib/http-api/fetch.js +141 -159
- package/lib/http-api/fetch.js.map +1 -1
- package/lib/http-api/index.js +17 -20
- package/lib/http-api/index.js.map +1 -1
- package/lib/http-api/interface.js +1 -1
- package/lib/http-api/interface.js.map +1 -1
- package/lib/http-api/method.js +1 -1
- package/lib/http-api/method.js.map +1 -1
- package/lib/http-api/prefix.js +3 -3
- package/lib/http-api/prefix.js.map +1 -1
- package/lib/http-api/refresh.js +74 -94
- package/lib/http-api/refresh.js.map +1 -1
- package/lib/http-api/utils.d.ts +1 -1
- package/lib/http-api/utils.d.ts.map +1 -1
- package/lib/http-api/utils.js +34 -42
- package/lib/http-api/utils.js.map +1 -1
- package/lib/index.js.map +1 -1
- package/lib/indexeddb-helpers.js +3 -3
- package/lib/indexeddb-helpers.js.map +1 -1
- package/lib/indexeddb-worker.js.map +1 -1
- package/lib/interactive-auth.d.ts +5 -5
- package/lib/interactive-auth.d.ts.map +1 -1
- package/lib/interactive-auth.js +172 -204
- package/lib/interactive-auth.js.map +1 -1
- package/lib/logger.js +21 -57
- package/lib/logger.js.map +1 -1
- package/lib/matrix.js +7 -11
- package/lib/matrix.js.map +1 -1
- package/lib/matrixrtc/CallMembership.js +80 -74
- package/lib/matrixrtc/CallMembership.js.map +1 -1
- package/lib/matrixrtc/EncryptionManager.js +1 -1
- package/lib/matrixrtc/EncryptionManager.js.map +1 -1
- package/lib/matrixrtc/IKeyTransport.js +1 -1
- package/lib/matrixrtc/IKeyTransport.js.map +1 -1
- package/lib/matrixrtc/IMembershipManager.js +1 -1
- package/lib/matrixrtc/IMembershipManager.js.map +1 -1
- package/lib/matrixrtc/LivekitTransport.d.ts +1 -1
- package/lib/matrixrtc/LivekitTransport.js +4 -4
- package/lib/matrixrtc/LivekitTransport.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.js +137 -187
- package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSessionManager.js +36 -41
- package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
- package/lib/matrixrtc/MembershipManager.js +332 -378
- package/lib/matrixrtc/MembershipManager.js.map +1 -1
- package/lib/matrixrtc/MembershipManagerActionScheduler.js +54 -63
- package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
- package/lib/matrixrtc/RTCEncryptionManager.js +119 -143
- package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
- package/lib/matrixrtc/ToDeviceKeyTransport.js +53 -58
- package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
- package/lib/matrixrtc/index.js.map +1 -1
- package/lib/matrixrtc/membershipData/common.js +1 -1
- package/lib/matrixrtc/membershipData/common.js.map +1 -1
- package/lib/matrixrtc/membershipData/index.js.map +1 -1
- package/lib/matrixrtc/membershipData/rtc.js +15 -23
- package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
- package/lib/matrixrtc/membershipData/session.js +4 -5
- package/lib/matrixrtc/membershipData/session.js.map +1 -1
- package/lib/matrixrtc/types.js +4 -6
- package/lib/matrixrtc/types.js.map +1 -1
- package/lib/matrixrtc/utils.js +4 -11
- package/lib/matrixrtc/utils.js.map +1 -1
- package/lib/models/MSC3089Branch.js +91 -116
- package/lib/models/MSC3089Branch.js.map +1 -1
- package/lib/models/MSC3089TreeSpace.js +209 -245
- package/lib/models/MSC3089TreeSpace.js.map +1 -1
- package/lib/models/ToDeviceMessage.js +3 -1
- package/lib/models/beacon.js +14 -13
- package/lib/models/beacon.js.map +1 -1
- package/lib/models/compare-event-ordering.js +13 -13
- package/lib/models/compare-event-ordering.js.map +1 -1
- package/lib/models/device.js +3 -3
- package/lib/models/device.js.map +1 -1
- package/lib/models/event-context.js +5 -8
- package/lib/models/event-context.js.map +1 -1
- package/lib/models/event-status.js +1 -1
- package/lib/models/event-status.js.map +1 -1
- package/lib/models/event-timeline-set.js +88 -94
- package/lib/models/event-timeline-set.js.map +1 -1
- package/lib/models/event-timeline.js +28 -30
- package/lib/models/event-timeline.js.map +1 -1
- package/lib/models/event.js +182 -226
- package/lib/models/event.js.map +1 -1
- package/lib/models/invites-ignorer-types.js +4 -4
- package/lib/models/invites-ignorer-types.js.map +1 -1
- package/lib/models/invites-ignorer.js +159 -179
- package/lib/models/invites-ignorer.js.map +1 -1
- package/lib/models/poll.js +71 -81
- package/lib/models/poll.js.map +1 -1
- package/lib/models/profile-keys.js +2 -2
- package/lib/models/profile-keys.js.map +1 -1
- package/lib/models/read-receipt.js +40 -56
- package/lib/models/read-receipt.js.map +1 -1
- package/lib/models/related-relations.js.map +1 -1
- package/lib/models/relations-container.js +22 -23
- package/lib/models/relations-container.js.map +1 -1
- package/lib/models/relations.js +133 -159
- package/lib/models/relations.js.map +1 -1
- package/lib/models/room-member.js +24 -29
- package/lib/models/room-member.js.map +1 -1
- package/lib/models/room-receipts.js +29 -43
- package/lib/models/room-receipts.js.map +1 -1
- package/lib/models/room-retention.js +74 -83
- package/lib/models/room-retention.js.map +1 -1
- package/lib/models/room-state.js +143 -172
- package/lib/models/room-state.js.map +1 -1
- package/lib/models/room-sticky-events.d.ts +1 -0
- package/lib/models/room-sticky-events.d.ts.map +1 -1
- package/lib/models/room-sticky-events.js +45 -65
- package/lib/models/room-sticky-events.js.map +1 -1
- package/lib/models/room-summary.js.map +1 -1
- package/lib/models/room.d.ts.map +1 -1
- package/lib/models/room.js +765 -909
- package/lib/models/room.js.map +1 -1
- package/lib/models/search-result.js +5 -5
- package/lib/models/search-result.js.map +1 -1
- package/lib/models/thread.js +225 -285
- package/lib/models/thread.js.map +1 -1
- package/lib/models/typed-event-emitter.js +7 -18
- package/lib/models/typed-event-emitter.js.map +1 -1
- package/lib/models/user.js +8 -8
- package/lib/models/user.js.map +1 -1
- package/lib/oidc/authorize.js +208 -241
- package/lib/oidc/authorize.js.map +1 -1
- package/lib/oidc/discovery.js +23 -36
- package/lib/oidc/discovery.js.map +1 -1
- package/lib/oidc/error.js +1 -1
- package/lib/oidc/error.js.map +1 -1
- package/lib/oidc/index.js +1 -0
- package/lib/oidc/index.js.map +1 -1
- package/lib/oidc/register.js +60 -66
- package/lib/oidc/register.js.map +1 -1
- package/lib/oidc/tokenRefresher.js +77 -91
- package/lib/oidc/tokenRefresher.js.map +1 -1
- package/lib/oidc/validate.js +18 -18
- package/lib/oidc/validate.js.map +1 -1
- package/lib/pushprocessor.js +71 -82
- package/lib/pushprocessor.js.map +1 -1
- package/lib/randomstring.js +9 -9
- package/lib/randomstring.js.map +1 -1
- package/lib/realtime-callbacks.js +25 -28
- package/lib/realtime-callbacks.js.map +1 -1
- package/lib/receipt-accumulator.d.ts +2 -0
- package/lib/receipt-accumulator.d.ts.map +1 -1
- package/lib/receipt-accumulator.js +14 -22
- package/lib/receipt-accumulator.js.map +1 -1
- package/lib/rendezvous/MSC4108SignInWithQR.js +271 -302
- package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
- package/lib/rendezvous/RendezvousChannel.js +3 -1
- package/lib/rendezvous/RendezvousCode.js +3 -1
- package/lib/rendezvous/RendezvousError.js.map +1 -1
- package/lib/rendezvous/RendezvousFailureReason.js +2 -2
- package/lib/rendezvous/RendezvousFailureReason.js.map +1 -1
- package/lib/rendezvous/RendezvousIntent.js +1 -1
- package/lib/rendezvous/RendezvousIntent.js.map +1 -1
- package/lib/rendezvous/RendezvousTransport.js +3 -1
- package/lib/rendezvous/channels/MSC4108SecureChannel.js +123 -147
- package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
- package/lib/rendezvous/index.js +44 -69
- package/lib/rendezvous/index.js.map +1 -1
- package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +1 -1
- package/lib/rendezvous/transports/MSC4108RendezvousSession.js +134 -152
- package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
- package/lib/retentionPolicy.js +6 -9
- package/lib/retentionPolicy.js.map +1 -1
- package/lib/room-hierarchy.js +52 -60
- package/lib/room-hierarchy.js.map +1 -1
- package/lib/rust-crypto/CrossSigningIdentity.js +94 -104
- package/lib/rust-crypto/CrossSigningIdentity.js.map +1 -1
- package/lib/rust-crypto/DehydratedDeviceManager.js +157 -190
- package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
- package/lib/rust-crypto/KeyClaimManager.js +18 -22
- package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
- package/lib/rust-crypto/OutgoingRequestProcessor.js +109 -139
- package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
- package/lib/rust-crypto/OutgoingRequestsManager.js +66 -80
- package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +1 -1
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +196 -224
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
- package/lib/rust-crypto/RoomEncryptor.js +127 -143
- package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
- package/lib/rust-crypto/backup.js +453 -549
- package/lib/rust-crypto/backup.js.map +1 -1
- package/lib/rust-crypto/constants.js +1 -1
- package/lib/rust-crypto/constants.js.map +1 -1
- package/lib/rust-crypto/device-converter.js +15 -28
- package/lib/rust-crypto/device-converter.js.map +1 -1
- package/lib/rust-crypto/index.js +103 -116
- package/lib/rust-crypto/index.js.map +1 -1
- package/lib/rust-crypto/libolm_migration.js +303 -365
- package/lib/rust-crypto/libolm_migration.js.map +1 -1
- package/lib/rust-crypto/rust-crypto.d.ts +5 -1
- package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
- package/lib/rust-crypto/rust-crypto.js +1067 -1332
- package/lib/rust-crypto/rust-crypto.js.map +1 -1
- package/lib/rust-crypto/secret-storage.js +12 -25
- package/lib/rust-crypto/secret-storage.js.map +1 -1
- package/lib/rust-crypto/verification.js +137 -189
- package/lib/rust-crypto/verification.js.map +1 -1
- package/lib/scheduler.js +44 -19
- package/lib/scheduler.js.map +1 -1
- package/lib/secret-storage.js +179 -213
- package/lib/secret-storage.js.map +1 -1
- package/lib/serverCapabilities.js +6 -9
- package/lib/serverCapabilities.js.map +1 -1
- package/lib/service-types.js +1 -1
- package/lib/service-types.js.map +1 -1
- package/lib/sliding-sync-sdk.d.ts.map +1 -1
- package/lib/sliding-sync-sdk.js +368 -424
- package/lib/sliding-sync-sdk.js.map +1 -1
- package/lib/sliding-sync.js +135 -171
- package/lib/sliding-sync.js.map +1 -1
- package/lib/store/index.js +3 -1
- package/lib/store/indexeddb-backend.js +3 -1
- package/lib/store/indexeddb-local-backend.js +194 -253
- package/lib/store/indexeddb-local-backend.js.map +1 -1
- package/lib/store/indexeddb-remote-backend.js +33 -63
- package/lib/store/indexeddb-remote-backend.js.map +1 -1
- package/lib/store/indexeddb-store-worker.js +22 -23
- package/lib/store/indexeddb-store-worker.js.map +1 -1
- package/lib/store/indexeddb.js +44 -71
- package/lib/store/indexeddb.js.map +1 -1
- package/lib/store/local-storage-events-emitter.js +2 -2
- package/lib/store/local-storage-events-emitter.js.map +1 -1
- package/lib/store/memory.js +34 -57
- package/lib/store/memory.js.map +1 -1
- package/lib/store/stub.js +22 -35
- package/lib/store/stub.js.map +1 -1
- package/lib/sync-accumulator.js +54 -66
- package/lib/sync-accumulator.js.map +1 -1
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +905 -998
- package/lib/sync.js.map +1 -1
- package/lib/testing.js +63 -105
- package/lib/testing.js.map +1 -1
- package/lib/thread-utils.js +1 -4
- package/lib/thread-utils.js.map +1 -1
- package/lib/timeline-window.js +89 -102
- package/lib/timeline-window.js.map +1 -1
- package/lib/types.js +1 -1
- package/lib/types.js.map +1 -1
- package/lib/utils/decryptAESSecretStorageItem.js +14 -25
- package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
- package/lib/utils/encryptAESSecretStorageItem.js +27 -38
- package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
- package/lib/utils/internal/deriveKeys.js +25 -32
- package/lib/utils/internal/deriveKeys.js.map +1 -1
- package/lib/utils/roomVersion.js +1 -1
- package/lib/utils/roomVersion.js.map +1 -1
- package/lib/utils.js +83 -135
- package/lib/utils.js.map +1 -1
- package/lib/version-support.js +3 -3
- package/lib/version-support.js.map +1 -1
- package/lib/webrtc/audioContext.js +5 -6
- package/lib/webrtc/audioContext.js.map +1 -1
- package/lib/webrtc/call.js +1081 -1250
- package/lib/webrtc/call.js.map +1 -1
- package/lib/webrtc/callEventHandler.js +202 -214
- package/lib/webrtc/callEventHandler.js.map +1 -1
- package/lib/webrtc/callEventTypes.js +2 -2
- package/lib/webrtc/callEventTypes.js.map +1 -1
- package/lib/webrtc/callFeed.js +18 -20
- package/lib/webrtc/callFeed.js.map +1 -1
- package/lib/webrtc/groupCall.js +513 -602
- package/lib/webrtc/groupCall.js.map +1 -1
- package/lib/webrtc/groupCallEventHandler.js +59 -62
- package/lib/webrtc/groupCallEventHandler.js.map +1 -1
- package/lib/webrtc/mediaHandler.js +198 -232
- package/lib/webrtc/mediaHandler.js.map +1 -1
- package/lib/webrtc/stats/callFeedStatsReporter.js +16 -20
- package/lib/webrtc/stats/callFeedStatsReporter.js.map +1 -1
- package/lib/webrtc/stats/callStatsReportGatherer.js +67 -75
- package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
- package/lib/webrtc/stats/callStatsReportSummary.js +3 -1
- package/lib/webrtc/stats/connectionStats.js.map +1 -1
- package/lib/webrtc/stats/connectionStatsBuilder.js +2 -2
- package/lib/webrtc/stats/connectionStatsBuilder.js.map +1 -1
- package/lib/webrtc/stats/connectionStatsReportBuilder.js +20 -24
- package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
- package/lib/webrtc/stats/groupCallStats.js +6 -8
- package/lib/webrtc/stats/groupCallStats.js.map +1 -1
- package/lib/webrtc/stats/media/mediaSsrcHandler.js +7 -8
- package/lib/webrtc/stats/media/mediaSsrcHandler.js.map +1 -1
- package/lib/webrtc/stats/media/mediaTrackHandler.js +7 -9
- package/lib/webrtc/stats/media/mediaTrackHandler.js.map +1 -1
- package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
- package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
- package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +7 -7
- package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
- package/lib/webrtc/stats/statsReport.js +1 -1
- package/lib/webrtc/stats/statsReport.js.map +1 -1
- package/lib/webrtc/stats/statsReportEmitter.js.map +1 -1
- package/lib/webrtc/stats/summaryStatsReportGatherer.js +14 -14
- package/lib/webrtc/stats/summaryStatsReportGatherer.js.map +1 -1
- package/lib/webrtc/stats/trackStatsBuilder.js +32 -34
- package/lib/webrtc/stats/trackStatsBuilder.js.map +1 -1
- package/lib/webrtc/stats/transportStats.js +3 -1
- package/lib/webrtc/stats/transportStatsBuilder.js +9 -9
- package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
- package/lib/webrtc/stats/valueFormatter.js +1 -1
- package/lib/webrtc/stats/valueFormatter.js.map +1 -1
- package/package.json +18 -33
- package/src/@types/global.d.ts +2 -2
- package/src/ToDeviceMessageQueue.ts +2 -2
- package/src/browser-index.ts +4 -4
- package/src/client.ts +15 -20
- package/src/crypto-api/index.ts +17 -6
- package/src/embedded.ts +4 -6
- package/src/filter-component.ts +1 -0
- package/src/http-api/utils.ts +1 -1
- package/src/interactive-auth.ts +11 -5
- package/src/matrixrtc/LivekitTransport.ts +1 -1
- package/src/matrixrtc/MatrixRTCSession.ts +1 -1
- package/src/models/MSC3089Branch.ts +1 -1
- package/src/models/room-sticky-events.ts +1 -0
- package/src/models/room.ts +9 -11
- package/src/receipt-accumulator.ts +2 -0
- package/src/rendezvous/index.ts +1 -1
- package/src/rendezvous/transports/MSC4108RendezvousSession.ts +2 -2
- package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +1 -1
- package/src/rust-crypto/index.ts +6 -6
- package/src/rust-crypto/rust-crypto.ts +31 -7
- package/src/rust-crypto/verification.ts +1 -1
- package/src/sliding-sync-sdk.ts +5 -7
- package/src/store/indexeddb-local-backend.ts +3 -3
- package/src/sync.ts +6 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PerSessionKeyBackupDownloader.js","names":["CryptoEvent","ClientPrefix","MatrixError","Method","encodeUri","sleep","KEY_BACKUP_BACKOFF","KeyDownloadErrorCode","KeyDownloadError","Error","constructor","code","concat","name","KeyDownloadRateLimitError","retryMillis","PerSessionKeyBackupDownloader","logger","olmMachine","http","backupManager","_defineProperty","Map","hasConfigurationProblem","configuration","getOrCreateBackupConfiguration","then","downloadKeysLoop","getChild","on","KeyBackupStatus","onBackupStatusChanged","KeyBackupFailed","KeyBackupDecryptionKeyCached","isKeyBackupDownloadConfigured","getServerBackupInfo","_this","_asyncToGenerator","onDecryptionKeyMissingError","roomId","megolmSessionId","isAlreadyInQueue","trace","wasRequestedRecently","queuedRequests","push","stop","stopped","off","some","info","markAsNotFoundInBackup","now","Date","sessionLastCheckAttemptedTime","set","size","Array","from","filter","sid","ts","Math","max","lastCheck","get","getBackupDecryptionKey","_this2","getBackupKeys","_unused","requestRoomKeyFromBackup","version","sessionId","_this3","path","$roomId","$sessionId","authedRequest","Get","undefined","prefix","V3","_this4","downloadLoopRunning","length","request","result","queryKeyBackup","decryptAndImport","e","error","shift","err","MISSING_DECRYPTION_KEY","NETWORK_ERROR","STOPPED","targetRoomId","targetSessionId","_this5","debug","res","backupVersion","errCode","data","errcode","isRateLimitError","waitTime","_e$getRetryAfterMs","getRetryAfterMs","warn","sessionInfo","_this6","sessionsToImport","keys","decryptor","decryptSessions","k","room_id","importBackedUpRoomKeys","_this7","currentBackupVersionCheck","internalCheckFromServer","_this8","_currentServerVersion","_currentServerVersion2","_currentServerVersion4","currentServerVersion","algorithm","_currentServerVersion3","activeVersion","getActiveBackupVersion","backupKeys","decryptionKey","authData","auth_data","public_key","megolmV1PublicKey","publicKeyBase64","backupDecryptor","createBackupDecryptor"],"sources":["../../src/rust-crypto/PerSessionKeyBackupDownloader.ts"],"sourcesContent":["/*\nCopyright 2023 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type OlmMachine } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport type * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { type Curve25519AuthData, type KeyBackupInfo, type KeyBackupSession } from \"../crypto-api/keybackup.ts\";\nimport { CryptoEvent } from \"../crypto-api/index.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { ClientPrefix, type IHttpOpts, MatrixError, type MatrixHttpApi, Method } from \"../http-api/index.ts\";\nimport { type RustBackupManager } from \"./backup.ts\";\nimport { encodeUri, sleep } from \"../utils.ts\";\nimport { type BackupDecryptor } from \"../common-crypto/CryptoBackend.ts\";\n\n// The minimum time to wait between two retries in case of errors. To avoid hammering the server.\nconst KEY_BACKUP_BACKOFF = 5000; // ms\n\n/**\n * Enumerates the different kind of errors that can occurs when downloading and importing a key from backup.\n */\nenum KeyDownloadErrorCode {\n /** The requested key is not in the backup. */\n MISSING_DECRYPTION_KEY = \"MISSING_DECRYPTION_KEY\",\n /** A network error occurred while trying to download the key from backup. */\n NETWORK_ERROR = \"NETWORK_ERROR\",\n /** The loop has been stopped. */\n STOPPED = \"STOPPED\",\n}\n\nclass KeyDownloadError extends Error {\n public constructor(public readonly code: KeyDownloadErrorCode) {\n super(`Failed to get key from backup: ${code}`);\n this.name = \"KeyDownloadError\";\n }\n}\n\nclass KeyDownloadRateLimitError extends Error {\n public constructor(public readonly retryMillis: number) {\n super(`Failed to get key from backup: rate limited`);\n this.name = \"KeyDownloadRateLimitError\";\n }\n}\n\n/** Details of a megolm session whose key we are trying to fetch. */\ntype SessionInfo = { roomId: string; megolmSessionId: string };\n\n/** Holds the current backup decryptor and version that should be used.\n *\n * This is intended to be used as an immutable object (a new instance should be created if the configuration changes),\n * and some of the logic relies on that, so the properties are marked as `readonly`.\n */\ntype Configuration = {\n readonly backupVersion: string;\n readonly decryptor: BackupDecryptor;\n};\n\n/**\n * Used when an 'unable to decrypt' error occurs. It attempts to download the key from the backup.\n *\n * The current backup API lacks pagination, which can lead to lengthy key retrieval times for large histories (several 10s of minutes).\n * To mitigate this, keys are downloaded on demand as decryption errors occurs.\n * While this approach may result in numerous requests, it improves user experience by reducing wait times for message decryption.\n *\n * The PerSessionKeyBackupDownloader is resistant to backup configuration changes: it will automatically resume querying when\n * the backup is configured correctly.\n */\nexport class PerSessionKeyBackupDownloader {\n private stopped = false;\n\n /**\n * The version and decryption key to use with current backup if all set up correctly.\n *\n * Will not be set unless `hasConfigurationProblem` is `false`.\n */\n private configuration: Configuration | null = null;\n\n /** We remember when a session was requested and not found in backup to avoid query again too soon.\n * Map of session_id to timestamp */\n private sessionLastCheckAttemptedTime: Map<string, number> = new Map();\n\n /** The logger to use */\n private readonly logger: Logger;\n\n /** Whether the download loop is running. */\n private downloadLoopRunning = false;\n\n /** The list of requests that are queued. */\n private queuedRequests: SessionInfo[] = [];\n\n /** Remembers if we have a configuration problem. */\n private hasConfigurationProblem = false;\n\n /** The current server backup version check promise. To avoid doing a server call if one is in flight. */\n private currentBackupVersionCheck: Promise<Configuration | null> | null = null;\n\n /**\n * Creates a new instance of PerSessionKeyBackupDownloader.\n *\n * @param backupManager - The backup manager to use.\n * @param olmMachine - The olm machine to use.\n * @param http - The http instance to use.\n * @param logger - The logger to use.\n */\n public constructor(\n logger: Logger,\n private readonly olmMachine: OlmMachine,\n private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,\n private readonly backupManager: RustBackupManager,\n ) {\n this.logger = logger.getChild(\"[PerSessionKeyBackupDownloader]\");\n\n backupManager.on(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Check if key download is successfully configured and active.\n *\n * @return `true` if key download is correctly configured and active; otherwise `false`.\n */\n public isKeyBackupDownloadConfigured(): boolean {\n return this.configuration !== null;\n }\n\n /**\n * Return the details of the latest backup on the server, when we last checked.\n *\n * This is just a convenience method to expose {@link RustBackupManager.getServerBackupInfo}.\n */\n public async getServerBackupInfo(): Promise<KeyBackupInfo | null | undefined> {\n return await this.backupManager.getServerBackupInfo();\n }\n\n /**\n * Called when a MissingRoomKey or UnknownMessageIndex decryption error is encountered.\n *\n * This will try to download the key from the backup if there is a trusted active backup.\n * In case of success the key will be imported and the onRoomKeysUpdated callback will be called\n * internally by the rust-sdk and decryption will be retried.\n *\n * @param roomId - The room ID of the room where the error occurred.\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n public onDecryptionKeyMissingError(roomId: string, megolmSessionId: string): void {\n // Several messages encrypted with the same session may be decrypted at the same time,\n // so we need to be resistant and not query several time the same session.\n if (this.isAlreadyInQueue(roomId, megolmSessionId)) {\n // There is already a request queued for this session, no need to queue another one.\n this.logger.trace(`Not checking key backup for session ${megolmSessionId} as it is already queued`);\n return;\n }\n\n if (this.wasRequestedRecently(megolmSessionId)) {\n // We already tried to download this session recently and it was not in backup, no need to try again.\n this.logger.trace(\n `Not checking key backup for session ${megolmSessionId} as it was already requested recently`,\n );\n return;\n }\n\n // We always add the request to the queue, even if we have a configuration problem (can't access backup).\n // This is to make sure that if the configuration problem is resolved, we will try to download the key.\n // This will happen after an initial sync, at this point the backup will not yet be trusted and the decryption\n // key will not be available, but it will be just after the verification.\n // We don't need to persist it because currently on refresh the sdk will retry to decrypt the messages in error.\n this.queuedRequests.push({ roomId, megolmSessionId });\n\n // Start the download loop if it's not already running.\n this.downloadKeysLoop();\n }\n\n public stop(): void {\n this.stopped = true;\n this.backupManager.off(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Called when the backup status changes (CryptoEvents)\n * This will trigger a check of the backup configuration.\n */\n private onBackupStatusChanged = (): void => {\n // we want to force check configuration, so we clear the current one.\n this.hasConfigurationProblem = false;\n this.configuration = null;\n this.getOrCreateBackupConfiguration().then((configuration) => {\n if (configuration) {\n // restart the download loop if it was stopped\n this.downloadKeysLoop();\n }\n });\n };\n\n /** Returns true if the megolm session is already queued for download. */\n private isAlreadyInQueue(roomId: string, megolmSessionId: string): boolean {\n return this.queuedRequests.some((info) => {\n return info.roomId == roomId && info.megolmSessionId == megolmSessionId;\n });\n }\n\n /**\n * Marks the session as not found in backup, to avoid retrying to soon for a key not in backup\n *\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n private markAsNotFoundInBackup(megolmSessionId: string): void {\n const now = Date.now();\n this.sessionLastCheckAttemptedTime.set(megolmSessionId, now);\n // if too big make some cleaning to keep under control\n if (this.sessionLastCheckAttemptedTime.size > 100) {\n this.sessionLastCheckAttemptedTime = new Map(\n Array.from(this.sessionLastCheckAttemptedTime).filter((sid, ts) => {\n return Math.max(now - ts, 0) < KEY_BACKUP_BACKOFF;\n }),\n );\n }\n }\n\n /** Returns true if the session was requested recently. */\n private wasRequestedRecently(megolmSessionId: string): boolean {\n const lastCheck = this.sessionLastCheckAttemptedTime.get(megolmSessionId);\n if (!lastCheck) return false;\n return Math.max(Date.now() - lastCheck, 0) < KEY_BACKUP_BACKOFF;\n }\n\n private async getBackupDecryptionKey(): Promise<RustSdkCryptoJs.BackupKeys | null> {\n try {\n return await this.olmMachine.getBackupKeys();\n } catch {\n return null;\n }\n }\n\n /**\n * Requests a key from the server side backup.\n *\n * @param version - The backup version to use.\n * @param roomId - The room ID of the room where the error occurred.\n * @param sessionId - The megolm session ID that is missing.\n */\n private async requestRoomKeyFromBackup(\n version: string,\n roomId: string,\n sessionId: string,\n ): Promise<KeyBackupSession> {\n const path = encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId,\n $sessionId: sessionId,\n });\n\n return await this.http.authedRequest<KeyBackupSession>(Method.Get, path, { version }, undefined, {\n prefix: ClientPrefix.V3,\n });\n }\n\n private async downloadKeysLoop(): Promise<void> {\n if (this.downloadLoopRunning) return;\n\n // If we have a configuration problem, we don't want to try to download.\n // If any configuration change is detected, we will retry and restart the loop.\n if (this.hasConfigurationProblem) return;\n\n this.downloadLoopRunning = true;\n\n try {\n while (this.queuedRequests.length > 0) {\n // we just peek the first one without removing it, so if a new request for same key comes in while we're\n // processing this one, it won't queue another request.\n const request = this.queuedRequests[0];\n try {\n // The backup could have changed between the time we queued the request and now, so we need to check\n const configuration = await this.getOrCreateBackupConfiguration();\n if (!configuration) {\n // Backup is not configured correctly, so stop the loop.\n this.downloadLoopRunning = false;\n return;\n }\n\n const result = await this.queryKeyBackup(request.roomId, request.megolmSessionId, configuration);\n\n if (this.stopped) {\n return;\n }\n // We got the encrypted key from backup, let's try to decrypt and import it.\n try {\n await this.decryptAndImport(request, result, configuration);\n } catch (e) {\n this.logger.error(\n `Error while decrypting and importing key backup for session ${request.megolmSessionId}`,\n e,\n );\n }\n // now remove the request from the queue as we've processed it.\n this.queuedRequests.shift();\n } catch (err) {\n if (err instanceof KeyDownloadError) {\n switch (err.code) {\n case KeyDownloadErrorCode.MISSING_DECRYPTION_KEY:\n this.markAsNotFoundInBackup(request.megolmSessionId);\n // continue for next one\n this.queuedRequests.shift();\n break;\n case KeyDownloadErrorCode.NETWORK_ERROR:\n // We don't want to hammer if there is a problem, so wait a bit.\n await sleep(KEY_BACKUP_BACKOFF);\n break;\n case KeyDownloadErrorCode.STOPPED:\n // If the downloader was stopped, we don't want to retry.\n this.downloadLoopRunning = false;\n return;\n }\n } else if (err instanceof KeyDownloadRateLimitError) {\n // we want to retry after the backoff time\n await sleep(err.retryMillis);\n }\n }\n }\n } finally {\n // all pending request have been processed, we can stop the loop.\n this.downloadLoopRunning = false;\n }\n }\n\n /**\n * Query the backup for a key.\n *\n * @param targetRoomId - ID of the room that the session is used in.\n * @param targetSessionId - ID of the session for which to check backup.\n * @param configuration - The backup configuration to use.\n */\n private async queryKeyBackup(\n targetRoomId: string,\n targetSessionId: string,\n configuration: Configuration,\n ): Promise<KeyBackupSession> {\n this.logger.debug(`Checking key backup for session ${targetSessionId}`);\n if (this.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n try {\n const res = await this.requestRoomKeyFromBackup(configuration.backupVersion, targetRoomId, targetSessionId);\n this.logger.debug(`Got key from backup for sessionId:${targetSessionId}`);\n return res;\n } catch (e) {\n if (this.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n\n this.logger.info(`No luck requesting key backup for session ${targetSessionId}: ${e}`);\n if (e instanceof MatrixError) {\n const errCode = e.data.errcode;\n if (errCode == \"M_NOT_FOUND\") {\n // Unfortunately the spec doesn't give us a way to differentiate between a missing key and a wrong version.\n // Synapse will return:\n // - \"error\": \"Unknown backup version\" if the version is wrong.\n // - \"error\": \"No room_keys found\" if the key is missing.\n // It's useful to know if the key is missing or if the version is wrong.\n // As it's not spec'ed, we fall back on considering the key is not in backup.\n // Notice that this request will be lost if instead the backup got out of sync (updated from other session).\n throw new KeyDownloadError(KeyDownloadErrorCode.MISSING_DECRYPTION_KEY);\n }\n if (e.isRateLimitError()) {\n let waitTime: number | undefined;\n try {\n waitTime = e.getRetryAfterMs() ?? undefined;\n } catch (error) {\n this.logger.warn(\"Error while retrieving a rate-limit retry delay\", error);\n }\n if (waitTime && waitTime > 0) {\n this.logger.info(`Rate limited by server, waiting ${waitTime}ms`);\n }\n throw new KeyDownloadRateLimitError(waitTime ?? KEY_BACKUP_BACKOFF);\n }\n }\n throw new KeyDownloadError(KeyDownloadErrorCode.NETWORK_ERROR);\n }\n }\n\n private async decryptAndImport(\n sessionInfo: SessionInfo,\n data: KeyBackupSession,\n configuration: Configuration,\n ): Promise<void> {\n const sessionsToImport: Record<string, KeyBackupSession> = { [sessionInfo.megolmSessionId]: data };\n\n const keys = await configuration!.decryptor.decryptSessions(sessionsToImport);\n for (const k of keys) {\n k.room_id = sessionInfo.roomId;\n }\n await this.backupManager.importBackedUpRoomKeys(keys, configuration.backupVersion);\n }\n\n /**\n * Gets the current backup configuration or create one if it doesn't exist.\n *\n * When a valid configuration is found it is cached and returned for subsequent calls.\n * Otherwise, if a check is forced or a check has not yet been done, a new check is done.\n *\n * @returns The backup configuration to use or null if there is a configuration problem.\n */\n private async getOrCreateBackupConfiguration(): Promise<Configuration | null> {\n if (this.configuration) {\n return this.configuration;\n }\n\n // We already tried to check the configuration and it failed.\n // We don't want to try again immediately, we will retry if a configuration change is detected.\n if (this.hasConfigurationProblem) {\n return null;\n }\n\n // This method can be called rapidly by several emitted CryptoEvent, so we need to make sure that we don't\n // query the server several times.\n if (this.currentBackupVersionCheck != null) {\n this.logger.debug(`Already checking server version, use current promise`);\n return await this.currentBackupVersionCheck;\n }\n\n this.currentBackupVersionCheck = this.internalCheckFromServer();\n try {\n return await this.currentBackupVersionCheck;\n } finally {\n this.currentBackupVersionCheck = null;\n }\n }\n\n private async internalCheckFromServer(): Promise<Configuration | null> {\n let currentServerVersion = null;\n try {\n currentServerVersion = await this.backupManager.getServerBackupInfo();\n } catch (e) {\n this.logger.debug(`Backup: error while checking server version: ${e}`);\n this.hasConfigurationProblem = true;\n return null;\n }\n this.logger.debug(`Got current backup version from server: ${currentServerVersion?.version}`);\n\n if (currentServerVersion?.algorithm != \"m.megolm_backup.v1.curve25519-aes-sha2\") {\n this.logger.info(`Unsupported algorithm ${currentServerVersion?.algorithm}`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n if (!currentServerVersion?.version) {\n this.logger.info(`No current key backup`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const activeVersion = await this.backupManager.getActiveBackupVersion();\n if (activeVersion == null || currentServerVersion.version != activeVersion) {\n // Either the current backup version on server side is not trusted, or it is out of sync with the active version on the client side.\n this.logger.info(\n `The current backup version on the server (${currentServerVersion.version}) is not trusted. Version we are currently backing up to: ${activeVersion}`,\n );\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const backupKeys = await this.getBackupDecryptionKey();\n if (!backupKeys?.decryptionKey) {\n this.logger.debug(`Not checking key backup for session (no decryption key)`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n if (activeVersion != backupKeys.backupVersion) {\n this.logger.debug(\n `Version for which we have a decryption key (${backupKeys.backupVersion}) doesn't match the version we are backing up to (${activeVersion})`,\n );\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const authData = currentServerVersion.auth_data as Curve25519AuthData;\n if (authData.public_key != backupKeys.decryptionKey.megolmV1PublicKey.publicKeyBase64) {\n this.logger.debug(`Key backup on server does not match our decryption key`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const backupDecryptor = this.backupManager.createBackupDecryptor(backupKeys.decryptionKey);\n this.hasConfigurationProblem = false;\n this.configuration = {\n decryptor: backupDecryptor,\n backupVersion: activeVersion,\n };\n return this.configuration;\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,WAAW,QAAQ,wBAAwB;AAEpD,SAASC,YAAY,EAAkBC,WAAW,EAAsBC,MAAM,QAAQ,sBAAsB;AAE5G,SAASC,SAAS,EAAEC,KAAK,QAAQ,aAAa;AAG9C;AACA,IAAMC,kBAAkB,GAAG,IAAI,CAAC,CAAC;;AAEjC;AACA;AACA;AAFA,IAGKC,oBAAoB,0BAApBA,oBAAoB;EACrB;EADCA,oBAAoB;EAGrB;EAHCA,oBAAoB;EAKrB;EALCA,oBAAoB;EAAA,OAApBA,oBAAoB;AAAA,EAApBA,oBAAoB;AASzB,MAAMC,gBAAgB,SAASC,KAAK,CAAC;EAC1BC,WAAWA,CAAi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,QAAQ,GAAGP,oBAAoB,CAACQ,SAA+B;MACrE,IAAID,QAAQ,CAACE,UAAU,IAAIJ,UAAU,CAACC,aAAa,CAACI,iBAAiB,CAACC,eAAe,EAAE;QACnFf,MAAI,CAACzG,MAAM,CAACkF,KAAK,yDAAyD,CAAC;QAC3EuB,MAAI,CAACnG,uBAAuB,GAAG,IAAI;QACnC,OAAO,IAAI;MACf;MAEA,IAAMmH,eAAe,GAAGhB,MAAI,CAACtG,aAAa,CAACuH,qBAAqB,CAACR,UAAU,CAACC,aAAa,CAAC;MAC1FV,MAAI,CAACnG,uBAAuB,GAAG,KAAK;MACpCmG,MAAI,CAAClG,aAAa,GAAG;QACjB0F,SAAS,EAAEwB,eAAe;QAC1BrC,aAAa,EAAE4B;MACnB,CAAC;MACD,OAAOP,MAAI,CAAClG,aAAa;IAAC;EAC9B;AACJ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"PerSessionKeyBackupDownloader.js","names":[],"sources":["../../src/rust-crypto/PerSessionKeyBackupDownloader.ts"],"sourcesContent":["/*\nCopyright 2023 - 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type OlmMachine } from \"@matrix-org/matrix-sdk-crypto-wasm\";\n\nimport type * as RustSdkCryptoJs from \"@matrix-org/matrix-sdk-crypto-wasm\";\nimport { type Curve25519AuthData, type KeyBackupInfo, type KeyBackupSession } from \"../crypto-api/keybackup.ts\";\nimport { CryptoEvent } from \"../crypto-api/index.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { ClientPrefix, type IHttpOpts, MatrixError, type MatrixHttpApi, Method } from \"../http-api/index.ts\";\nimport { type RustBackupManager } from \"./backup.ts\";\nimport { encodeUri, sleep } from \"../utils.ts\";\nimport { type BackupDecryptor } from \"../common-crypto/CryptoBackend.ts\";\n\n// The minimum time to wait between two retries in case of errors. To avoid hammering the server.\nconst KEY_BACKUP_BACKOFF = 5000; // ms\n\n/**\n * Enumerates the different kind of errors that can occurs when downloading and importing a key from backup.\n */\nenum KeyDownloadErrorCode {\n /** The requested key is not in the backup. */\n MISSING_DECRYPTION_KEY = \"MISSING_DECRYPTION_KEY\",\n /** A network error occurred while trying to download the key from backup. */\n NETWORK_ERROR = \"NETWORK_ERROR\",\n /** The loop has been stopped. */\n STOPPED = \"STOPPED\",\n}\n\nclass KeyDownloadError extends Error {\n public constructor(public readonly code: KeyDownloadErrorCode) {\n super(`Failed to get key from backup: ${code}`);\n this.name = \"KeyDownloadError\";\n }\n}\n\nclass KeyDownloadRateLimitError extends Error {\n public constructor(public readonly retryMillis: number) {\n super(`Failed to get key from backup: rate limited`);\n this.name = \"KeyDownloadRateLimitError\";\n }\n}\n\n/** Details of a megolm session whose key we are trying to fetch. */\ntype SessionInfo = { roomId: string; megolmSessionId: string };\n\n/** Holds the current backup decryptor and version that should be used.\n *\n * This is intended to be used as an immutable object (a new instance should be created if the configuration changes),\n * and some of the logic relies on that, so the properties are marked as `readonly`.\n */\ntype Configuration = {\n readonly backupVersion: string;\n readonly decryptor: BackupDecryptor;\n};\n\n/**\n * Used when an 'unable to decrypt' error occurs. It attempts to download the key from the backup.\n *\n * The current backup API lacks pagination, which can lead to lengthy key retrieval times for large histories (several 10s of minutes).\n * To mitigate this, keys are downloaded on demand as decryption errors occurs.\n * While this approach may result in numerous requests, it improves user experience by reducing wait times for message decryption.\n *\n * The PerSessionKeyBackupDownloader is resistant to backup configuration changes: it will automatically resume querying when\n * the backup is configured correctly.\n */\nexport class PerSessionKeyBackupDownloader {\n private stopped = false;\n\n /**\n * The version and decryption key to use with current backup if all set up correctly.\n *\n * Will not be set unless `hasConfigurationProblem` is `false`.\n */\n private configuration: Configuration | null = null;\n\n /** We remember when a session was requested and not found in backup to avoid query again too soon.\n * Map of session_id to timestamp */\n private sessionLastCheckAttemptedTime: Map<string, number> = new Map();\n\n /** The logger to use */\n private readonly logger: Logger;\n\n /** Whether the download loop is running. */\n private downloadLoopRunning = false;\n\n /** The list of requests that are queued. */\n private queuedRequests: SessionInfo[] = [];\n\n /** Remembers if we have a configuration problem. */\n private hasConfigurationProblem = false;\n\n /** The current server backup version check promise. To avoid doing a server call if one is in flight. */\n private currentBackupVersionCheck: Promise<Configuration | null> | null = null;\n\n /**\n * Creates a new instance of PerSessionKeyBackupDownloader.\n *\n * @param backupManager - The backup manager to use.\n * @param olmMachine - The olm machine to use.\n * @param http - The http instance to use.\n * @param logger - The logger to use.\n */\n public constructor(\n logger: Logger,\n private readonly olmMachine: OlmMachine,\n private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,\n private readonly backupManager: RustBackupManager,\n ) {\n this.logger = logger.getChild(\"[PerSessionKeyBackupDownloader]\");\n\n backupManager.on(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n backupManager.on(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Check if key download is successfully configured and active.\n *\n * @returns `true` if key download is correctly configured and active; otherwise `false`.\n */\n public isKeyBackupDownloadConfigured(): boolean {\n return this.configuration !== null;\n }\n\n /**\n * Return the details of the latest backup on the server, when we last checked.\n *\n * This is just a convenience method to expose {@link RustBackupManager.getServerBackupInfo}.\n */\n public async getServerBackupInfo(): Promise<KeyBackupInfo | null | undefined> {\n return await this.backupManager.getServerBackupInfo();\n }\n\n /**\n * Called when a MissingRoomKey or UnknownMessageIndex decryption error is encountered.\n *\n * This will try to download the key from the backup if there is a trusted active backup.\n * In case of success the key will be imported and the onRoomKeysUpdated callback will be called\n * internally by the rust-sdk and decryption will be retried.\n *\n * @param roomId - The room ID of the room where the error occurred.\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n public onDecryptionKeyMissingError(roomId: string, megolmSessionId: string): void {\n // Several messages encrypted with the same session may be decrypted at the same time,\n // so we need to be resistant and not query several time the same session.\n if (this.isAlreadyInQueue(roomId, megolmSessionId)) {\n // There is already a request queued for this session, no need to queue another one.\n this.logger.trace(`Not checking key backup for session ${megolmSessionId} as it is already queued`);\n return;\n }\n\n if (this.wasRequestedRecently(megolmSessionId)) {\n // We already tried to download this session recently and it was not in backup, no need to try again.\n this.logger.trace(\n `Not checking key backup for session ${megolmSessionId} as it was already requested recently`,\n );\n return;\n }\n\n // We always add the request to the queue, even if we have a configuration problem (can't access backup).\n // This is to make sure that if the configuration problem is resolved, we will try to download the key.\n // This will happen after an initial sync, at this point the backup will not yet be trusted and the decryption\n // key will not be available, but it will be just after the verification.\n // We don't need to persist it because currently on refresh the sdk will retry to decrypt the messages in error.\n this.queuedRequests.push({ roomId, megolmSessionId });\n\n // Start the download loop if it's not already running.\n this.downloadKeysLoop();\n }\n\n public stop(): void {\n this.stopped = true;\n this.backupManager.off(CryptoEvent.KeyBackupStatus, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupFailed, this.onBackupStatusChanged);\n this.backupManager.off(CryptoEvent.KeyBackupDecryptionKeyCached, this.onBackupStatusChanged);\n }\n\n /**\n * Called when the backup status changes (CryptoEvents)\n * This will trigger a check of the backup configuration.\n */\n private onBackupStatusChanged = (): void => {\n // we want to force check configuration, so we clear the current one.\n this.hasConfigurationProblem = false;\n this.configuration = null;\n this.getOrCreateBackupConfiguration().then((configuration) => {\n if (configuration) {\n // restart the download loop if it was stopped\n this.downloadKeysLoop();\n }\n });\n };\n\n /** Returns true if the megolm session is already queued for download. */\n private isAlreadyInQueue(roomId: string, megolmSessionId: string): boolean {\n return this.queuedRequests.some((info) => {\n return info.roomId == roomId && info.megolmSessionId == megolmSessionId;\n });\n }\n\n /**\n * Marks the session as not found in backup, to avoid retrying to soon for a key not in backup\n *\n * @param megolmSessionId - The megolm session ID that is missing.\n */\n private markAsNotFoundInBackup(megolmSessionId: string): void {\n const now = Date.now();\n this.sessionLastCheckAttemptedTime.set(megolmSessionId, now);\n // if too big make some cleaning to keep under control\n if (this.sessionLastCheckAttemptedTime.size > 100) {\n this.sessionLastCheckAttemptedTime = new Map(\n Array.from(this.sessionLastCheckAttemptedTime).filter((sid, ts) => {\n return Math.max(now - ts, 0) < KEY_BACKUP_BACKOFF;\n }),\n );\n }\n }\n\n /** Returns true if the session was requested recently. */\n private wasRequestedRecently(megolmSessionId: string): boolean {\n const lastCheck = this.sessionLastCheckAttemptedTime.get(megolmSessionId);\n if (!lastCheck) return false;\n return Math.max(Date.now() - lastCheck, 0) < KEY_BACKUP_BACKOFF;\n }\n\n private async getBackupDecryptionKey(): Promise<RustSdkCryptoJs.BackupKeys | null> {\n try {\n return await this.olmMachine.getBackupKeys();\n } catch {\n return null;\n }\n }\n\n /**\n * Requests a key from the server side backup.\n *\n * @param version - The backup version to use.\n * @param roomId - The room ID of the room where the error occurred.\n * @param sessionId - The megolm session ID that is missing.\n */\n private async requestRoomKeyFromBackup(\n version: string,\n roomId: string,\n sessionId: string,\n ): Promise<KeyBackupSession> {\n const path = encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId,\n $sessionId: sessionId,\n });\n\n return await this.http.authedRequest<KeyBackupSession>(Method.Get, path, { version }, undefined, {\n prefix: ClientPrefix.V3,\n });\n }\n\n private async downloadKeysLoop(): Promise<void> {\n if (this.downloadLoopRunning) return;\n\n // If we have a configuration problem, we don't want to try to download.\n // If any configuration change is detected, we will retry and restart the loop.\n if (this.hasConfigurationProblem) return;\n\n this.downloadLoopRunning = true;\n\n try {\n while (this.queuedRequests.length > 0) {\n // we just peek the first one without removing it, so if a new request for same key comes in while we're\n // processing this one, it won't queue another request.\n const request = this.queuedRequests[0];\n try {\n // The backup could have changed between the time we queued the request and now, so we need to check\n const configuration = await this.getOrCreateBackupConfiguration();\n if (!configuration) {\n // Backup is not configured correctly, so stop the loop.\n this.downloadLoopRunning = false;\n return;\n }\n\n const result = await this.queryKeyBackup(request.roomId, request.megolmSessionId, configuration);\n\n if (this.stopped) {\n return;\n }\n // We got the encrypted key from backup, let's try to decrypt and import it.\n try {\n await this.decryptAndImport(request, result, configuration);\n } catch (e) {\n this.logger.error(\n `Error while decrypting and importing key backup for session ${request.megolmSessionId}`,\n e,\n );\n }\n // now remove the request from the queue as we've processed it.\n this.queuedRequests.shift();\n } catch (err) {\n if (err instanceof KeyDownloadError) {\n switch (err.code) {\n case KeyDownloadErrorCode.MISSING_DECRYPTION_KEY:\n this.markAsNotFoundInBackup(request.megolmSessionId);\n // continue for next one\n this.queuedRequests.shift();\n break;\n case KeyDownloadErrorCode.NETWORK_ERROR:\n // We don't want to hammer if there is a problem, so wait a bit.\n await sleep(KEY_BACKUP_BACKOFF);\n break;\n case KeyDownloadErrorCode.STOPPED:\n // If the downloader was stopped, we don't want to retry.\n this.downloadLoopRunning = false;\n return;\n }\n } else if (err instanceof KeyDownloadRateLimitError) {\n // we want to retry after the backoff time\n await sleep(err.retryMillis);\n }\n }\n }\n } finally {\n // all pending request have been processed, we can stop the loop.\n this.downloadLoopRunning = false;\n }\n }\n\n /**\n * Query the backup for a key.\n *\n * @param targetRoomId - ID of the room that the session is used in.\n * @param targetSessionId - ID of the session for which to check backup.\n * @param configuration - The backup configuration to use.\n */\n private async queryKeyBackup(\n targetRoomId: string,\n targetSessionId: string,\n configuration: Configuration,\n ): Promise<KeyBackupSession> {\n this.logger.debug(`Checking key backup for session ${targetSessionId}`);\n if (this.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n try {\n const res = await this.requestRoomKeyFromBackup(configuration.backupVersion, targetRoomId, targetSessionId);\n this.logger.debug(`Got key from backup for sessionId:${targetSessionId}`);\n return res;\n } catch (e) {\n if (this.stopped) throw new KeyDownloadError(KeyDownloadErrorCode.STOPPED);\n\n this.logger.info(`No luck requesting key backup for session ${targetSessionId}: ${e}`);\n if (e instanceof MatrixError) {\n const errCode = e.data.errcode;\n if (errCode == \"M_NOT_FOUND\") {\n // Unfortunately the spec doesn't give us a way to differentiate between a missing key and a wrong version.\n // Synapse will return:\n // - \"error\": \"Unknown backup version\" if the version is wrong.\n // - \"error\": \"No room_keys found\" if the key is missing.\n // It's useful to know if the key is missing or if the version is wrong.\n // As it's not spec'ed, we fall back on considering the key is not in backup.\n // Notice that this request will be lost if instead the backup got out of sync (updated from other session).\n throw new KeyDownloadError(KeyDownloadErrorCode.MISSING_DECRYPTION_KEY);\n }\n if (e.isRateLimitError()) {\n let waitTime: number | undefined;\n try {\n waitTime = e.getRetryAfterMs() ?? undefined;\n } catch (error) {\n this.logger.warn(\"Error while retrieving a rate-limit retry delay\", error);\n }\n if (waitTime && waitTime > 0) {\n this.logger.info(`Rate limited by server, waiting ${waitTime}ms`);\n }\n throw new KeyDownloadRateLimitError(waitTime ?? KEY_BACKUP_BACKOFF);\n }\n }\n throw new KeyDownloadError(KeyDownloadErrorCode.NETWORK_ERROR);\n }\n }\n\n private async decryptAndImport(\n sessionInfo: SessionInfo,\n data: KeyBackupSession,\n configuration: Configuration,\n ): Promise<void> {\n const sessionsToImport: Record<string, KeyBackupSession> = { [sessionInfo.megolmSessionId]: data };\n\n const keys = await configuration!.decryptor.decryptSessions(sessionsToImport);\n for (const k of keys) {\n k.room_id = sessionInfo.roomId;\n }\n await this.backupManager.importBackedUpRoomKeys(keys, configuration.backupVersion);\n }\n\n /**\n * Gets the current backup configuration or create one if it doesn't exist.\n *\n * When a valid configuration is found it is cached and returned for subsequent calls.\n * Otherwise, if a check is forced or a check has not yet been done, a new check is done.\n *\n * @returns The backup configuration to use or null if there is a configuration problem.\n */\n private async getOrCreateBackupConfiguration(): Promise<Configuration | null> {\n if (this.configuration) {\n return this.configuration;\n }\n\n // We already tried to check the configuration and it failed.\n // We don't want to try again immediately, we will retry if a configuration change is detected.\n if (this.hasConfigurationProblem) {\n return null;\n }\n\n // This method can be called rapidly by several emitted CryptoEvent, so we need to make sure that we don't\n // query the server several times.\n if (this.currentBackupVersionCheck != null) {\n this.logger.debug(`Already checking server version, use current promise`);\n return await this.currentBackupVersionCheck;\n }\n\n this.currentBackupVersionCheck = this.internalCheckFromServer();\n try {\n return await this.currentBackupVersionCheck;\n } finally {\n this.currentBackupVersionCheck = null;\n }\n }\n\n private async internalCheckFromServer(): Promise<Configuration | null> {\n let currentServerVersion = null;\n try {\n currentServerVersion = await this.backupManager.getServerBackupInfo();\n } catch (e) {\n this.logger.debug(`Backup: error while checking server version: ${e}`);\n this.hasConfigurationProblem = true;\n return null;\n }\n this.logger.debug(`Got current backup version from server: ${currentServerVersion?.version}`);\n\n if (currentServerVersion?.algorithm != \"m.megolm_backup.v1.curve25519-aes-sha2\") {\n this.logger.info(`Unsupported algorithm ${currentServerVersion?.algorithm}`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n if (!currentServerVersion?.version) {\n this.logger.info(`No current key backup`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const activeVersion = await this.backupManager.getActiveBackupVersion();\n if (activeVersion == null || currentServerVersion.version != activeVersion) {\n // Either the current backup version on server side is not trusted, or it is out of sync with the active version on the client side.\n this.logger.info(\n `The current backup version on the server (${currentServerVersion.version}) is not trusted. Version we are currently backing up to: ${activeVersion}`,\n );\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const backupKeys = await this.getBackupDecryptionKey();\n if (!backupKeys?.decryptionKey) {\n this.logger.debug(`Not checking key backup for session (no decryption key)`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n if (activeVersion != backupKeys.backupVersion) {\n this.logger.debug(\n `Version for which we have a decryption key (${backupKeys.backupVersion}) doesn't match the version we are backing up to (${activeVersion})`,\n );\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const authData = currentServerVersion.auth_data as Curve25519AuthData;\n if (authData.public_key != backupKeys.decryptionKey.megolmV1PublicKey.publicKeyBase64) {\n this.logger.debug(`Key backup on server does not match our decryption key`);\n this.hasConfigurationProblem = true;\n return null;\n }\n\n const backupDecryptor = this.backupManager.createBackupDecryptor(backupKeys.decryptionKey);\n this.hasConfigurationProblem = false;\n this.configuration = {\n decryptor: backupDecryptor,\n backupVersion: activeVersion,\n };\n return this.configuration;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAAS,WAAW,QAAQ,wBAAwB;AAEpD,SAAS,YAAY,EAAkB,WAAW,EAAsB,MAAM,QAAQ,sBAAsB;AAE5G,SAAS,SAAS,EAAE,KAAK,QAAQ,aAAa;AAG9C;AACA,MAAM,kBAAkB,GAAG,IAAI,CAAC,CAAC;;AAEjC;AACA;AACA;AAFA,IAGK,oBAAoB,0BAApB,oBAAoB;EACrB;EADC,oBAAoB;EAGrB;EAHC,oBAAoB;EAKrB;EALC,oBAAoB;EAAA,OAApB,oBAAoB;AAAA,EAApB,oBAAoB;AASzB,MAAM,gBAAgB,SAAS,KAAK,CAAC;EAC1B,WAAW,CAAiB,IAA0B,EAAE;IAC3D,KAAK,CAAC,kCAAkC,IAAI,EAAE,CAAC;IAAC,KADjB,IAA0B,GAA1B,IAA0B;IAEzD,IAAI,CAAC,IAAI,GAAG,kBAAkB;EAClC;AACJ;AAEA,MAAM,yBAAyB,SAAS,KAAK,CAAC;EACnC,WAAW,CAAiB,WAAmB,EAAE;IACpD,KAAK,CAAC,6CAA6C,CAAC;IAAC,KADtB,WAAmB,GAAnB,WAAmB;IAElD,IAAI,CAAC,IAAI,GAAG,2BAA2B;EAC3C;AACJ;;AAEA;;AAGA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,6BAA6B,CAAC;EA6BvC;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;EACW,WAAW,CACd,MAAc,EACG,UAAsB,EACtB,IA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AAuB,GAAG,IAAI;MACnC,OAAO,IAAI;IACf;IAEA,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACtD,IAAI,CAAC,UAAU,EAAE,aAAa,EAAE;MAC5B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yDAAyD,CAAC;MAC5E,IAAI,CAAC,uBAAuB,GAAG,IAAI;MACnC,OAAO,IAAI;IACf;IAEA,IAAI,aAAa,IAAI,UAAU,CAAC,aAAa,EAAE;MAC3C,IAAI,CAAC,MAAM,CAAC,KAAK,CACb,+CAA+C,UAAU,CAAC,aAAa,qDAAqD,aAAa,GAC7I,CAAC;MACD,IAAI,CAAC,uBAAuB,GAAG,IAAI;MACnC,OAAO,IAAI;IACf;IAEA,MAAM,QAAQ,GAAG,oBAAoB,CAAC,SAA+B;IACrE,IAAI,QAAQ,CAAC,UAAU,IAAI,UAAU,CAAC,aAAa,CAAC,iBAAiB,CAAC,eAAe,EAAE;MACnF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,wDAAwD,CAAC;MAC3E,IAAI,CAAC,uBAAuB,GAAG,IAAI;MACnC,OAAO,IAAI;IACf;IAEA,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,CAAC,qBAAqB,CAAC,UAAU,CAAC,aAAa,CAAC;IAC1F,IAAI,CAAC,uBAAuB,GAAG,KAAK;IACpC,IAAI,CAAC,aAAa,GAAG;MACjB,SAAS,EAAE,eAAe;MAC1B,aAAa,EAAE;IACnB,CAAC;IACD,OAAO,IAAI,CAAC,aAAa;EAC7B;AACJ","ignoreList":[]}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
|
|
2
1
|
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
|
3
2
|
/*
|
|
4
3
|
Copyright 2023 The Matrix.org Foundation C.I.C.
|
|
@@ -40,12 +39,6 @@ export class RoomEncryptor {
|
|
|
40
39
|
* @param encryptionSettings - body of the m.room.encryption event currently in force in this room
|
|
41
40
|
*/
|
|
42
41
|
constructor(prefixedLogger, olmMachine, keyClaimManager, outgoingRequestManager, room, encryptionSettings) {
|
|
43
|
-
this.prefixedLogger = prefixedLogger;
|
|
44
|
-
this.olmMachine = olmMachine;
|
|
45
|
-
this.keyClaimManager = keyClaimManager;
|
|
46
|
-
this.outgoingRequestManager = outgoingRequestManager;
|
|
47
|
-
this.room = room;
|
|
48
|
-
this.encryptionSettings = encryptionSettings;
|
|
49
42
|
/** whether the room members have been loaded and tracked for the first time */
|
|
50
43
|
_defineProperty(this, "lazyLoadedMembersResolved", false);
|
|
51
44
|
/**
|
|
@@ -54,9 +47,15 @@ export class RoomEncryptor {
|
|
|
54
47
|
* An encryption operation is either a {@link prepareForEncryption} or an {@link encryptEvent} call.
|
|
55
48
|
*/
|
|
56
49
|
_defineProperty(this, "currentEncryptionPromise", Promise.resolve());
|
|
50
|
+
this.prefixedLogger = prefixedLogger;
|
|
51
|
+
this.olmMachine = olmMachine;
|
|
52
|
+
this.keyClaimManager = keyClaimManager;
|
|
53
|
+
this.outgoingRequestManager = outgoingRequestManager;
|
|
54
|
+
this.room = room;
|
|
55
|
+
this.encryptionSettings = encryptionSettings;
|
|
57
56
|
// start tracking devices for any users already known to be in this room.
|
|
58
57
|
// Do not load members here, would defeat lazy loading.
|
|
59
|
-
|
|
58
|
+
const members = room.getJoinedMembers();
|
|
60
59
|
|
|
61
60
|
// At this point just mark the known members as tracked, it might not be the full list of members
|
|
62
61
|
// because of lazy loading. This is fine, because we will get a member list update when sending a message for
|
|
@@ -102,18 +101,15 @@ export class RoomEncryptor {
|
|
|
102
101
|
* Ignored when `deviceIsolationMode` is `OnlySignedDevicesIsolationMode`.
|
|
103
102
|
* @param deviceIsolationMode - The device isolation mode. See {@link DeviceIsolationMode}.
|
|
104
103
|
*/
|
|
105
|
-
prepareForEncryption(globalBlacklistUnverifiedDevices, deviceIsolationMode) {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
// The part where `encryptEvent` shares the room key will then usually be a no-op as it was already performed by `prepareForEncryption`.
|
|
115
|
-
yield _this.encryptEvent(null, globalBlacklistUnverifiedDevices, deviceIsolationMode);
|
|
116
|
-
})();
|
|
104
|
+
async prepareForEncryption(globalBlacklistUnverifiedDevices, deviceIsolationMode) {
|
|
105
|
+
// We consider a prepareForEncryption as an encryption promise as it will potentially share keys
|
|
106
|
+
// even if it doesn't send an event.
|
|
107
|
+
// Usually this is called when the user starts typing, so we want to make sure we have keys ready when the
|
|
108
|
+
// message is finally sent.
|
|
109
|
+
// If `encryptEvent` is invoked before `prepareForEncryption` has completed, the `encryptEvent` call will wait for
|
|
110
|
+
// `prepareForEncryption` to complete before executing.
|
|
111
|
+
// The part where `encryptEvent` shares the room key will then usually be a no-op as it was already performed by `prepareForEncryption`.
|
|
112
|
+
await this.encryptEvent(null, globalBlacklistUnverifiedDevices, deviceIsolationMode);
|
|
117
113
|
}
|
|
118
114
|
|
|
119
115
|
/**
|
|
@@ -129,24 +125,22 @@ export class RoomEncryptor {
|
|
|
129
125
|
* @param deviceIsolationMode - The device isolation mode. See {@link DeviceIsolationMode}.
|
|
130
126
|
*/
|
|
131
127
|
encryptEvent(event, globalBlacklistUnverifiedDevices, deviceIsolationMode) {
|
|
132
|
-
|
|
133
|
-
_this2 = this;
|
|
134
|
-
var logger = new LogSpan(this.prefixedLogger, event ? (_event$getTxnId = event.getTxnId()) !== null && _event$getTxnId !== void 0 ? _event$getTxnId : "" : "prepareForEncryption");
|
|
128
|
+
const logger = new LogSpan(this.prefixedLogger, event ? event.getTxnId() ?? "" : "prepareForEncryption");
|
|
135
129
|
// Ensure order of encryption to avoid message ordering issues, as the scheduler only ensures
|
|
136
130
|
// events order after they have been encrypted.
|
|
137
|
-
|
|
131
|
+
const prom = this.currentEncryptionPromise.catch(() => {
|
|
138
132
|
// Any errors in the previous call will have been reported already, so there is nothing to do here.
|
|
139
133
|
// we just throw away the error and start anew.
|
|
140
|
-
}).then(
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
})
|
|
134
|
+
}).then(async () => {
|
|
135
|
+
await logDuration(logger, "ensureEncryptionSession", async () => {
|
|
136
|
+
await this.ensureEncryptionSession(logger, globalBlacklistUnverifiedDevices, deviceIsolationMode);
|
|
137
|
+
});
|
|
144
138
|
if (event) {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
})
|
|
139
|
+
await logDuration(logger, "encryptEventInner", async () => {
|
|
140
|
+
await this.encryptEventInner(logger, event);
|
|
141
|
+
});
|
|
148
142
|
}
|
|
149
|
-
})
|
|
143
|
+
});
|
|
150
144
|
this.currentEncryptionPromise = prom;
|
|
151
145
|
return prom;
|
|
152
146
|
}
|
|
@@ -163,128 +157,118 @@ export class RoomEncryptor {
|
|
|
163
157
|
* Ignored when `deviceIsolationMode` is `OnlySignedDevicesIsolationMode`.
|
|
164
158
|
* @param deviceIsolationMode - The device isolation mode. See {@link DeviceIsolationMode}.
|
|
165
159
|
*/
|
|
166
|
-
ensureEncryptionSession(logger, globalBlacklistUnverifiedDevices, deviceIsolationMode) {
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
logger.debug("Starting encryption");
|
|
173
|
-
var members = yield _this3.room.getEncryptionTargetMembers();
|
|
160
|
+
async ensureEncryptionSession(logger, globalBlacklistUnverifiedDevices, deviceIsolationMode) {
|
|
161
|
+
if (this.encryptionSettings.algorithm !== "m.megolm.v1.aes-sha2") {
|
|
162
|
+
throw new Error(`Cannot encrypt in ${this.room.roomId} for unsupported algorithm '${this.encryptionSettings.algorithm}'`);
|
|
163
|
+
}
|
|
164
|
+
logger.debug("Starting encryption");
|
|
165
|
+
const members = await this.room.getEncryptionTargetMembers();
|
|
174
166
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
167
|
+
// If this is the first time we are sending a message to the room, we may not yet have seen all the members
|
|
168
|
+
// (so the Crypto SDK might not have a device list for them). So, if this is the first time we are encrypting
|
|
169
|
+
// for this room, give the SDK the full list of members, to be on the safe side.
|
|
170
|
+
//
|
|
171
|
+
// This could end up being racy (if two calls to ensureEncryptionSession happen at the same time), but that's
|
|
172
|
+
// not a particular problem, since `OlmMachine.updateTrackedUsers` just adds any users that weren't already tracked.
|
|
173
|
+
if (!this.lazyLoadedMembersResolved) {
|
|
174
|
+
await logDuration(logger, "loadMembersIfNeeded: updateTrackedUsers", async () => {
|
|
175
|
+
await this.olmMachine.updateTrackedUsers(members.map(u => new RustSdkCryptoJs.UserId(u.userId)));
|
|
176
|
+
});
|
|
177
|
+
logger.debug(`Updated tracked users`);
|
|
178
|
+
this.lazyLoadedMembersResolved = true;
|
|
187
179
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
180
|
+
// Query keys in case we don't have them for newly tracked members.
|
|
181
|
+
// It's important after loading members for the first time, as likely most of them won't be
|
|
182
|
+
// known yet and will be unable to decrypt messages despite being in the room for long.
|
|
183
|
+
// This must be done before ensuring sessions. If not the devices of these users are not
|
|
184
|
+
// known yet and will not get the room key.
|
|
185
|
+
// We don't have API to only get the keys queries related to this member list, so we just
|
|
186
|
+
// process the pending requests from the olmMachine. (usually these are processed
|
|
187
|
+
// at the end of the sync, but we can't wait for that).
|
|
188
|
+
// XXX future improvement process only KeysQueryRequests for the users that have never been queried.
|
|
189
|
+
logger.debug(`Processing outgoing requests`);
|
|
190
|
+
await logDuration(logger, "doProcessOutgoingRequests", async () => {
|
|
191
|
+
await this.outgoingRequestManager.doProcessOutgoingRequests();
|
|
192
|
+
});
|
|
193
|
+
} else {
|
|
194
|
+
// If members are already loaded it's less critical to await on key queries.
|
|
195
|
+
// We might still want to trigger a processOutgoingRequests here.
|
|
196
|
+
// The call to `ensureSessionsForUsers` below will wait a bit on in-flight key queries we are
|
|
197
|
+
// interested in. If a sync handling happens in the meantime, and some new members are added to the room
|
|
198
|
+
// or have new devices it would give us a chance to query them before sending.
|
|
199
|
+
// It's less critical due to the racy nature of this process.
|
|
200
|
+
logger.debug(`Processing outgoing requests in background`);
|
|
201
|
+
this.outgoingRequestManager.doProcessOutgoingRequests();
|
|
202
|
+
}
|
|
203
|
+
logger.debug(`Encrypting for users (shouldEncryptForInvitedMembers: ${this.room.shouldEncryptForInvitedMembers()}):`, members.map(u => `${u.userId} (${u.membership})`));
|
|
204
|
+
const userList = members.map(u => new UserId(u.userId));
|
|
205
|
+
await logDuration(logger, "ensureSessionsForUsers", async () => {
|
|
206
|
+
await this.keyClaimManager.ensureSessionsForUsers(logger, userList);
|
|
207
|
+
});
|
|
208
|
+
const rustEncryptionSettings = new EncryptionSettings();
|
|
209
|
+
rustEncryptionSettings.historyVisibility = toRustHistoryVisibility(this.room.getHistoryVisibility());
|
|
218
210
|
|
|
219
|
-
|
|
220
|
-
|
|
211
|
+
// We only support megolm
|
|
212
|
+
rustEncryptionSettings.algorithm = EncryptionAlgorithm.MegolmV1AesSha2;
|
|
221
213
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
rustEncryptionSettings.sharingStrategy = CollectStrategy.deviceBasedStrategy(onlyAllowTrustedDevices, deviceIsolationMode.errorOnVerifiedUserProblems);
|
|
239
|
-
}
|
|
240
|
-
break;
|
|
241
|
-
case DeviceIsolationModeKind.OnlySignedDevicesIsolationMode:
|
|
242
|
-
rustEncryptionSettings.sharingStrategy = CollectStrategy.identityBasedStrategy();
|
|
243
|
-
break;
|
|
244
|
-
}
|
|
245
|
-
yield logDuration(logger, "shareRoomKey", /*#__PURE__*/_asyncToGenerator(function* () {
|
|
246
|
-
var shareMessages = yield _this3.olmMachine.shareRoomKey(new RoomId(_this3.room.roomId),
|
|
247
|
-
// safe to pass without cloning, as it's not reused here (before or after)
|
|
248
|
-
userList, rustEncryptionSettings);
|
|
249
|
-
if (shareMessages) {
|
|
250
|
-
for (var m of shareMessages) {
|
|
251
|
-
yield _this3.outgoingRequestManager.outgoingRequestProcessor.makeOutgoingRequest(m);
|
|
252
|
-
}
|
|
214
|
+
// We need to convert the rotation period from milliseconds to microseconds
|
|
215
|
+
// See https://spec.matrix.org/v1.8/client-server-api/#mroomencryption and
|
|
216
|
+
// https://matrix-org.github.io/matrix-rust-sdk-crypto-wasm/classes/EncryptionSettings.html#rotationPeriod
|
|
217
|
+
if (typeof this.encryptionSettings.rotation_period_ms === "number") {
|
|
218
|
+
rustEncryptionSettings.rotationPeriod = BigInt(this.encryptionSettings.rotation_period_ms * 1000);
|
|
219
|
+
}
|
|
220
|
+
if (typeof this.encryptionSettings.rotation_period_msgs === "number") {
|
|
221
|
+
rustEncryptionSettings.rotationPeriodMessages = BigInt(this.encryptionSettings.rotation_period_msgs);
|
|
222
|
+
}
|
|
223
|
+
switch (deviceIsolationMode.kind) {
|
|
224
|
+
case DeviceIsolationModeKind.AllDevicesIsolationMode:
|
|
225
|
+
{
|
|
226
|
+
// When this.room.getBlacklistUnverifiedDevices() === null, the global settings should be used
|
|
227
|
+
// See Room#getBlacklistUnverifiedDevices
|
|
228
|
+
const onlyAllowTrustedDevices = this.room.getBlacklistUnverifiedDevices() ?? globalBlacklistUnverifiedDevices;
|
|
229
|
+
rustEncryptionSettings.sharingStrategy = CollectStrategy.deviceBasedStrategy(onlyAllowTrustedDevices, deviceIsolationMode.errorOnVerifiedUserProblems);
|
|
253
230
|
}
|
|
254
|
-
|
|
255
|
-
|
|
231
|
+
break;
|
|
232
|
+
case DeviceIsolationModeKind.OnlySignedDevicesIsolationMode:
|
|
233
|
+
rustEncryptionSettings.sharingStrategy = CollectStrategy.identityBasedStrategy();
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
await logDuration(logger, "shareRoomKey", async () => {
|
|
237
|
+
const shareMessages = await this.olmMachine.shareRoomKey(new RoomId(this.room.roomId),
|
|
238
|
+
// safe to pass without cloning, as it's not reused here (before or after)
|
|
239
|
+
userList, rustEncryptionSettings);
|
|
240
|
+
if (shareMessages) {
|
|
241
|
+
for (const m of shareMessages) {
|
|
242
|
+
await this.outgoingRequestManager.outgoingRequestProcessor.makeOutgoingRequest(m);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
});
|
|
256
246
|
}
|
|
257
247
|
|
|
258
248
|
/**
|
|
259
249
|
* Discard any existing group session for this room
|
|
260
250
|
*/
|
|
261
|
-
forceDiscardSession() {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
_this4.prefixedLogger.info("Discarded existing group session");
|
|
267
|
-
}
|
|
268
|
-
})();
|
|
251
|
+
async forceDiscardSession() {
|
|
252
|
+
const r = await this.olmMachine.invalidateGroupSession(new RoomId(this.room.roomId));
|
|
253
|
+
if (r) {
|
|
254
|
+
this.prefixedLogger.info("Discarded existing group session");
|
|
255
|
+
}
|
|
269
256
|
}
|
|
270
|
-
encryptEventInner(logger, event) {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
event.makeEncrypted(EventType.RoomMessageEncrypted, JSON.parse(encryptedContent), _this5.olmMachine.identityKeys.curve25519.toBase64(), _this5.olmMachine.identityKeys.ed25519.toBase64());
|
|
286
|
-
logger.debug("Encrypted event successfully");
|
|
287
|
-
})();
|
|
257
|
+
async encryptEventInner(logger, event) {
|
|
258
|
+
logger.debug("Encrypting actual message content");
|
|
259
|
+
const room = new RoomId(this.room.roomId);
|
|
260
|
+
const type = event.getType();
|
|
261
|
+
const content = JSON.stringify(event.getContent());
|
|
262
|
+
let encryptedContent;
|
|
263
|
+
if (event.isState()) {
|
|
264
|
+
encryptedContent = await this.olmMachine.encryptStateEvent(room, type,
|
|
265
|
+
// Safety: we've already checked above that this is a state event, so the state key must exist.
|
|
266
|
+
event.getStateKey(), content);
|
|
267
|
+
} else {
|
|
268
|
+
encryptedContent = await this.olmMachine.encryptRoomEvent(room, type, content);
|
|
269
|
+
}
|
|
270
|
+
event.makeEncrypted(EventType.RoomMessageEncrypted, JSON.parse(encryptedContent), this.olmMachine.identityKeys.curve25519.toBase64(), this.olmMachine.identityKeys.ed25519.toBase64());
|
|
271
|
+
logger.debug("Encrypted event successfully");
|
|
288
272
|
}
|
|
289
273
|
}
|
|
290
274
|
|