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
|
@@ -52,14 +52,14 @@ limitations under the License.
|
|
|
52
52
|
export class DecryptionError extends Error {
|
|
53
53
|
constructor(code, msg, details) {
|
|
54
54
|
super(msg);
|
|
55
|
-
this.code = code;
|
|
56
55
|
_defineProperty(this, "detailedString", void 0);
|
|
56
|
+
this.code = code;
|
|
57
57
|
this.name = "DecryptionError";
|
|
58
58
|
this.detailedString = detailedStringForDecryptionError(this, details);
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
61
|
function detailedStringForDecryptionError(err, details) {
|
|
62
|
-
|
|
62
|
+
let result = err.name + "[msg: " + err.message;
|
|
63
63
|
if (details) {
|
|
64
64
|
result += ", " + Object.keys(details).map(k => k + ": " + details[k]).join(", ");
|
|
65
65
|
}
|
|
@@ -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":[],"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,MAAM,eAAe,SAAS,KAAK,CAAC;EAGhC,WAAW,CACE,IAA2B,EAC3C,GAAW,EACX,OAAwC,EAC1C;IACE,KAAK,CAAC,GAAG,CAAC;IAAC;IAAA,KAJK,IAA2B,GAA3B,IAA2B;IAK3C,IAAI,CAAC,IAAI,GAAG,iBAAiB;IAC7B,IAAI,CAAC,cAAc,GAAG,gCAAgC,CAAC,IAAI,EAAE,OAAO,CAAC;EACzE;AACJ;AAEA,SAAS,gCAAgC,CAAC,GAAoB,EAAE,OAAwC,EAAU;EAC9G,IAAI,MAAM,GAAG,GAAG,CAAC,IAAI,GAAG,QAAQ,GAAG,GAAG,CAAC,OAAO;EAE9C,IAAI,OAAO,EAAE;IACT,MAAM,IACF,IAAI,GACJ,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CACf,GAAG,CAAE,CAAC,IAAK,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CACjC,IAAI,CAAC,IAAI,CAAC;EACvB;EAEA,MAAM,IAAI,GAAG;EAEb,OAAO,MAAM;AACjB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"key-passphrase.js","names":[
|
|
1
|
+
{"version":3,"file":"key-passphrase.js","names":[],"sources":["../../src/common-crypto/key-passphrase.ts"],"sourcesContent":["/*\n * Copyright 2024 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deriveRecoveryKeyFromPassphrase } from \"../crypto-api/index.ts\";\n\n/* eslint-disable camelcase */\ninterface IAuthData {\n private_key_salt?: string;\n private_key_iterations?: number;\n private_key_bits?: number;\n}\n\n/**\n * Derive a backup key from a passphrase using the salt and iterations from the auth data.\n * @param authData - The auth data containing the salt and iterations\n * @param passphrase - The passphrase to derive the key from\n * @deprecated Deriving a backup key from a passphrase is not part of the matrix spec. Instead, a random key is generated and stored/shared via 4S.\n */\nexport function keyFromAuthData(authData: IAuthData, passphrase: string): Promise<Uint8Array> {\n if (!authData.private_key_salt || !authData.private_key_iterations) {\n throw new Error(\"Salt and/or iterations not found: \" + \"this backup cannot be restored with a passphrase\");\n }\n\n return deriveRecoveryKeyFromPassphrase(\n passphrase,\n authData.private_key_salt,\n authData.private_key_iterations,\n authData.private_key_bits,\n );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,+BAA+B,QAAQ,wBAAwB;;AAExE;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,eAAe,CAAC,QAAmB,EAAE,UAAkB,EAAuB;EAC1F,IAAI,CAAC,QAAQ,CAAC,gBAAgB,IAAI,CAAC,QAAQ,CAAC,sBAAsB,EAAE;IAChE,MAAM,IAAI,KAAK,CAAC,oCAAoC,GAAG,kDAAkD,CAAC;EAC9G;EAEA,OAAO,+BAA+B,CAClC,UAAU,EACV,QAAQ,CAAC,gBAAgB,EACzB,QAAQ,CAAC,sBAAsB,EAC/B,QAAQ,CAAC,gBACb,CAAC;AACL","ignoreList":[]}
|
package/lib/content-helpers.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
3
|
-
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
|
|
1
|
+
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
|
|
4
2
|
/*
|
|
5
3
|
Copyright 2018 - 2022 The Matrix.org Foundation C.I.C.
|
|
6
4
|
|
|
@@ -105,10 +103,10 @@ export function makeEmoteMessage(body) {
|
|
|
105
103
|
|
|
106
104
|
/** Location content helpers */
|
|
107
105
|
|
|
108
|
-
export
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
106
|
+
export const getTextForLocationEvent = (uri, assetType, timestamp, description) => {
|
|
107
|
+
const date = `at ${new Date(timestamp).toISOString()}`;
|
|
108
|
+
const assetName = assetType === LocationAssetType.Self ? "User" : undefined;
|
|
109
|
+
const quotedDescription = description ? `"${description}"` : undefined;
|
|
112
110
|
return [assetName, "Location", quotedDescription, uri, date].filter(Boolean).join(" ");
|
|
113
111
|
};
|
|
114
112
|
|
|
@@ -120,9 +118,9 @@ export var getTextForLocationEvent = (uri, assetType, timestamp, description) =>
|
|
|
120
118
|
* @param assetType - the (optional) asset type of this location e.g. "m.self"
|
|
121
119
|
* @param text - optional. A text for the location
|
|
122
120
|
*/
|
|
123
|
-
export
|
|
124
|
-
|
|
125
|
-
|
|
121
|
+
export const makeLocationContent = (text, uri, timestamp, description, assetType) => {
|
|
122
|
+
const defaultedText = text ?? getTextForLocationEvent(uri, assetType || LocationAssetType.Self, timestamp, description);
|
|
123
|
+
const timestampEvent = timestamp ? {
|
|
126
124
|
[M_TIMESTAMP.name]: timestamp
|
|
127
125
|
} : {};
|
|
128
126
|
return _objectSpread({
|
|
@@ -144,25 +142,24 @@ export var makeLocationContent = (text, uri, timestamp, description, assetType)
|
|
|
144
142
|
* Parse location event content and transform to
|
|
145
143
|
* a backwards compatible modern m.location event format
|
|
146
144
|
*/
|
|
147
|
-
export
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
return makeLocationContent(fallbackText, geoUri, timestamp !== null && timestamp !== void 0 ? timestamp : undefined, description, assetType);
|
|
145
|
+
export const parseLocationEvent = wireEventContent => {
|
|
146
|
+
const location = M_LOCATION.findIn(wireEventContent);
|
|
147
|
+
const asset = M_ASSET.findIn(wireEventContent);
|
|
148
|
+
const timestamp = M_TIMESTAMP.findIn(wireEventContent);
|
|
149
|
+
const text = M_TEXT.findIn(wireEventContent);
|
|
150
|
+
const geoUri = location?.uri ?? wireEventContent?.geo_uri;
|
|
151
|
+
const description = location?.description;
|
|
152
|
+
const assetType = asset?.type ?? LocationAssetType.Self;
|
|
153
|
+
const fallbackText = text ?? wireEventContent.body;
|
|
154
|
+
return makeLocationContent(fallbackText, geoUri, timestamp ?? undefined, description, assetType);
|
|
158
155
|
};
|
|
159
156
|
|
|
160
157
|
/**
|
|
161
158
|
* Topic event helpers
|
|
162
159
|
*/
|
|
163
160
|
|
|
164
|
-
export
|
|
165
|
-
|
|
161
|
+
export const makeTopicContent = (topic, htmlTopic) => {
|
|
162
|
+
const renderings = [];
|
|
166
163
|
// Put HTML first because clients will render the first type in
|
|
167
164
|
// the array that they understand
|
|
168
165
|
if (isProvided(htmlTopic)) {
|
|
@@ -184,21 +181,19 @@ export var makeTopicContent = (topic, htmlTopic) => {
|
|
|
184
181
|
}
|
|
185
182
|
};
|
|
186
183
|
};
|
|
187
|
-
export
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
var mtopic = Array.isArray(mtopicParent) ? mtopicParent : mtopicParent === null || mtopicParent === void 0 ? void 0 : mtopicParent["m.text"];
|
|
184
|
+
export const parseTopicContent = content => {
|
|
185
|
+
const mtopicParent = M_TOPIC.findIn(content);
|
|
186
|
+
const mtopic = Array.isArray(mtopicParent) ? mtopicParent : mtopicParent?.["m.text"];
|
|
191
187
|
// TODO remove support for the old malformed m.topic arrays after a few releases (only allow array in m.text)
|
|
192
188
|
// https://github.com/matrix-org/matrix-js-sdk/pull/4984#pullrequestreview-3174251065
|
|
193
189
|
//const mtopic = M_TOPIC.findIn<MTopicContent>(content)?.["m.text"];
|
|
194
190
|
if (!Array.isArray(mtopic)) {
|
|
195
|
-
var _content$topic;
|
|
196
191
|
return {
|
|
197
|
-
text:
|
|
192
|
+
text: content.topic ?? undefined
|
|
198
193
|
};
|
|
199
194
|
}
|
|
200
|
-
|
|
201
|
-
|
|
195
|
+
const text = mtopic?.find(r => !isProvided(r.mimetype) || r.mimetype === "text/plain")?.body ?? content.topic ?? undefined;
|
|
196
|
+
const html = mtopic?.find(r => r.mimetype === "text/html")?.body;
|
|
202
197
|
return {
|
|
203
198
|
text,
|
|
204
199
|
html
|
|
@@ -209,34 +204,35 @@ export var parseTopicContent = content => {
|
|
|
209
204
|
* Beacon event helpers
|
|
210
205
|
*/
|
|
211
206
|
|
|
212
|
-
export
|
|
207
|
+
export const makeBeaconInfoContent = (timeout, isLive, description, assetType, timestamp) => ({
|
|
213
208
|
description,
|
|
214
209
|
timeout,
|
|
215
210
|
live: isLive,
|
|
216
211
|
[M_TIMESTAMP.name]: timestamp || Date.now(),
|
|
217
212
|
[M_ASSET.name]: {
|
|
218
|
-
type: assetType
|
|
213
|
+
type: assetType ?? LocationAssetType.Self
|
|
219
214
|
}
|
|
220
215
|
});
|
|
221
216
|
/**
|
|
222
217
|
* Flatten beacon info event content
|
|
223
218
|
*/
|
|
224
|
-
export
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
timeout
|
|
228
|
-
live
|
|
229
|
-
|
|
230
|
-
|
|
219
|
+
export const parseBeaconInfoContent = content => {
|
|
220
|
+
const {
|
|
221
|
+
description,
|
|
222
|
+
timeout,
|
|
223
|
+
live
|
|
224
|
+
} = content;
|
|
225
|
+
const timestamp = M_TIMESTAMP.findIn(content) ?? undefined;
|
|
226
|
+
const asset = M_ASSET.findIn(content);
|
|
231
227
|
return {
|
|
232
228
|
description,
|
|
233
229
|
timeout,
|
|
234
230
|
live,
|
|
235
|
-
assetType: asset
|
|
231
|
+
assetType: asset?.type,
|
|
236
232
|
timestamp
|
|
237
233
|
};
|
|
238
234
|
};
|
|
239
|
-
export
|
|
235
|
+
export const makeBeaconContent = (uri, timestamp, beaconInfoEventId, description) => ({
|
|
240
236
|
[M_LOCATION.name]: {
|
|
241
237
|
description,
|
|
242
238
|
uri
|
|
@@ -247,13 +243,12 @@ export var makeBeaconContent = (uri, timestamp, beaconInfoEventId, description)
|
|
|
247
243
|
event_id: beaconInfoEventId
|
|
248
244
|
}
|
|
249
245
|
});
|
|
250
|
-
export
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
var timestamp = (_M_TIMESTAMP$findIn2 = M_TIMESTAMP.findIn(content)) !== null && _M_TIMESTAMP$findIn2 !== void 0 ? _M_TIMESTAMP$findIn2 : undefined;
|
|
246
|
+
export const parseBeaconContent = content => {
|
|
247
|
+
const location = M_LOCATION.findIn(content);
|
|
248
|
+
const timestamp = M_TIMESTAMP.findIn(content) ?? undefined;
|
|
254
249
|
return {
|
|
255
|
-
description: location
|
|
256
|
-
uri: location
|
|
250
|
+
description: location?.description,
|
|
251
|
+
uri: location?.uri,
|
|
257
252
|
timestamp
|
|
258
253
|
};
|
|
259
254
|
};
|
|
@@ -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":";;;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,EAAEZ,OAAO,CAACiB,MAAM;IACvBH,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B,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":[],"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,SAAS,OAAO,QAAQ,mBAAmB;AAC3C,SAAiC,MAAM,EAAE,kBAAkB,QAAQ,+BAA+B;AAClG,SAAS,UAAU,QAAQ,qCAAqC;AAChE,SACI,OAAO,EACP,iBAAiB,EACjB,UAAU,EACV,WAAW,QAMR,sBAAsB;AAC7B,SAA0D,OAAO,QAA0B,mBAAmB;AAG9G;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,eAAe,CAAC,IAAY,EAAE,QAAgB,EAA2B;EACrF,OAAO;IACH,OAAO,EAAE,OAAO,CAAC,IAAI;IACrB,MAAM,EAAE,wBAAwB;IAChC,IAAI,EAAE,IAAI;IACV,cAAc,EAAE;EACpB,CAAC;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,cAAc,CAAC,IAAY,EAAE,QAAgB,EAA2B;EACpF,OAAO;IACH,OAAO,EAAE,OAAO,CAAC,MAAM;IACvB,MAAM,EA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,CAAC;EAC7D,MAAM,SAAS,GAAG,WAAW,CAAC,MAAM,CAAS,OAAO,CAAC,IAAI,SAAS;EAElE,OAAO;IACH,WAAW,EAAE,QAAQ,EAAE,WAAW;IAClC,GAAG,EAAE,QAAQ,EAAE,GAAG;IAClB;EACJ,CAAC;AACL,CAAC","ignoreList":[]}
|
package/lib/content-repo.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
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; }
|
|
3
1
|
/*
|
|
4
2
|
Copyright 2015 - 2024 The Matrix.org Foundation C.I.C.
|
|
5
3
|
|
|
@@ -19,17 +17,17 @@ limitations under the License.
|
|
|
19
17
|
// Validation based on https://spec.matrix.org/v1.12/appendices/#server-name
|
|
20
18
|
// We do not use the validation described in https://spec.matrix.org/v1.12/client-server-api/#security-considerations-5
|
|
21
19
|
// as it'd wrongly make all MXCs invalid due to not allowing `[].:` in server names.
|
|
22
|
-
|
|
20
|
+
const serverNameRegex = /^(?:(?:\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})?$/;
|
|
23
21
|
function validateServerName(serverName) {
|
|
24
|
-
|
|
25
|
-
return
|
|
22
|
+
const matches = serverNameRegex.exec(serverName);
|
|
23
|
+
return matches?.[0] === serverName;
|
|
26
24
|
}
|
|
27
25
|
|
|
28
26
|
// Validation based on https://spec.matrix.org/v1.12/client-server-api/#security-considerations-5
|
|
29
|
-
|
|
27
|
+
const mediaIdRegex = /^[\w-]+$/;
|
|
30
28
|
function validateMediaId(mediaId) {
|
|
31
|
-
|
|
32
|
-
return
|
|
29
|
+
const matches = mediaIdRegex.exec(mediaId);
|
|
30
|
+
return matches?.[0] === mediaId;
|
|
33
31
|
}
|
|
34
32
|
|
|
35
33
|
/**
|
|
@@ -55,11 +53,7 @@ function validateMediaId(mediaId) {
|
|
|
55
53
|
* @param animated - Whether the desired thumbnail should be animated.
|
|
56
54
|
* @returns The complete URL to the content, may be an empty string if the provided mxc is not valid.
|
|
57
55
|
*/
|
|
58
|
-
export function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod) {
|
|
59
|
-
var allowDirectLinks = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
|
|
60
|
-
var allowRedirects = arguments.length > 6 ? arguments[6] : undefined;
|
|
61
|
-
var useAuthentication = arguments.length > 7 ? arguments[7] : undefined;
|
|
62
|
-
var animated = arguments.length > 8 ? arguments[8] : undefined;
|
|
56
|
+
export function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod, allowDirectLinks = false, allowRedirects, useAuthentication, animated) {
|
|
63
57
|
if (typeof mxc !== "string" || !mxc) {
|
|
64
58
|
return "";
|
|
65
59
|
}
|
|
@@ -70,11 +64,7 @@ export function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod) {
|
|
|
70
64
|
return "";
|
|
71
65
|
}
|
|
72
66
|
}
|
|
73
|
-
|
|
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);
|
|
67
|
+
const [serverName, mediaId, ...rest] = mxc.slice(6).split("/");
|
|
78
68
|
if (rest.length > 0 || !validateServerName(serverName) || !validateMediaId(mediaId)) {
|
|
79
69
|
return "";
|
|
80
70
|
}
|
|
@@ -85,15 +75,15 @@ export function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod) {
|
|
|
85
75
|
// for explicitness we set it here. This makes it slightly more obvious to
|
|
86
76
|
// callers, hopefully.
|
|
87
77
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
78
|
+
let prefix;
|
|
79
|
+
const isThumbnailRequest = !!width || !!height || !!resizeMethod;
|
|
80
|
+
const verb = isThumbnailRequest ? "thumbnail" : "download";
|
|
91
81
|
if (useAuthentication) {
|
|
92
|
-
prefix =
|
|
82
|
+
prefix = `/_matrix/client/v1/media/${verb}`;
|
|
93
83
|
} else {
|
|
94
|
-
prefix =
|
|
84
|
+
prefix = `/_matrix/media/v3/${verb}`;
|
|
95
85
|
}
|
|
96
|
-
|
|
86
|
+
const url = new URL(`${prefix}/${serverName}/${mediaId}`, baseUrl);
|
|
97
87
|
if (width) {
|
|
98
88
|
url.searchParams.set("width", Math.round(width).toString());
|
|
99
89
|
}
|
package/lib/content-repo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content-repo.js","names":[
|
|
1
|
+
{"version":3,"file":"content-repo.js","names":[],"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,MAAM,eAAe,GACjB,8GAA8G;AAClH,SAAS,kBAAkB,CAAC,UAAkB,EAAW;EACrD,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,UAAU,CAAC;EAChD,OAAO,OAAO,GAAG,CAAC,CAAC,KAAK,UAAU;AACtC;;AAEA;AACA,MAAM,YAAY,GAAG,UAAU;AAC/B,SAAS,eAAe,CAAC,OAAe,EAAW;EAC/C,MAAM,OAAO,GAAG,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC;EAC1C,OAAO,OAAO,GAAG,CAAC,CAAC,KAAK,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,SAAS,gBAAgB,CAC5B,OAAe,EACf,GAAY,EACZ,KAAc,EACd,MAAe,EACf,YAAqB,EACrB,gBAAgB,GAAG,KAAK,EACxB,cAAwB,EACxB,i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G,CAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;EACjE;EACA,IAAI,YAAY,EAAE;IACd,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,YAAY,CAAC;EAChD;EACA,IAAI,QAAQ,KAAK,SAAS,EAAE;IACxB,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;EACtD;EAEA,IAAI,OAAO,cAAc,KAAK,SAAS,EAAE;IACrC;IACA,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC;EAC1E;EAEA,OAAO,GAAG,CAAC,IAAI;AACnB","ignoreList":[]}
|
package/lib/crypto/store/base.js
CHANGED
|
@@ -37,7 +37,7 @@ limitations under the License.
|
|
|
37
37
|
* Values are defined in `MigrationState`.
|
|
38
38
|
* @internal
|
|
39
39
|
*/
|
|
40
|
-
export
|
|
40
|
+
export const ACCOUNT_OBJECT_KEY_MIGRATION_STATE = "migrationState";
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
43
|
* A record of which steps have been completed in the libolm to Rust Crypto migration.
|
|
@@ -46,7 +46,7 @@ export var ACCOUNT_OBJECT_KEY_MIGRATION_STATE = "migrationState";
|
|
|
46
46
|
*
|
|
47
47
|
* @internal
|
|
48
48
|
*/
|
|
49
|
-
export
|
|
49
|
+
export let MigrationState = /*#__PURE__*/function (MigrationState) {
|
|
50
50
|
/** No migration steps have yet been completed. */
|
|
51
51
|
MigrationState[MigrationState["NOT_STARTED"] = 0] = "NOT_STARTED";
|
|
52
52
|
/** We have migrated the account data, cross-signing keys, etc. */
|
|
@@ -67,13 +67,13 @@ export var MigrationState = /*#__PURE__*/function (MigrationState) {
|
|
|
67
67
|
* The size of batches to be returned by {@link CryptoStore#getEndToEndSessionsBatch} and
|
|
68
68
|
* {@link CryptoStore#getEndToEndInboundGroupSessionsBatch}.
|
|
69
69
|
*/
|
|
70
|
-
export
|
|
70
|
+
export const SESSION_BATCH_SIZE = 50;
|
|
71
71
|
|
|
72
72
|
/* eslint-disable camelcase */
|
|
73
73
|
|
|
74
74
|
/* eslint-enable camelcase */
|
|
75
75
|
|
|
76
|
-
export
|
|
76
|
+
export let TrackingStatus = /*#__PURE__*/function (TrackingStatus) {
|
|
77
77
|
TrackingStatus[TrackingStatus["NotTracked"] = 0] = "NotTracked";
|
|
78
78
|
TrackingStatus[TrackingStatus["PendingDownload"] = 1] = "PendingDownload";
|
|
79
79
|
TrackingStatus[TrackingStatus["DownloadInProgress"] = 2] = "DownloadInProgress";
|
|
@@ -110,7 +110,7 @@ export var TrackingStatus = /*#__PURE__*/function (TrackingStatus) {
|
|
|
110
110
|
* (deleted) <---------------------------+
|
|
111
111
|
* ```
|
|
112
112
|
*/
|
|
113
|
-
export
|
|
113
|
+
export let RoomKeyRequestState = /*#__PURE__*/function (RoomKeyRequestState) {
|
|
114
114
|
/** request not yet sent */
|
|
115
115
|
RoomKeyRequestState[RoomKeyRequestState["Unsent"] = 0] = "Unsent";
|
|
116
116
|
/** request sent, awaiting reply */
|
|
@@ -136,7 +136,7 @@ export var RoomKeyRequestState = /*#__PURE__*/function (RoomKeyRequestState) {
|
|
|
136
136
|
/* eslint-enable camelcase */
|
|
137
137
|
|
|
138
138
|
/** State of the verification of the device. */
|
|
139
|
-
export
|
|
139
|
+
export let DeviceVerification = /*#__PURE__*/function (DeviceVerification) {
|
|
140
140
|
DeviceVerification[DeviceVerification["Blocked"] = -1] = "Blocked";
|
|
141
141
|
DeviceVerification[DeviceVerification["Unverified"] = 0] = "Unverified";
|
|
142
142
|
DeviceVerification[DeviceVerification["Verified"] = 1] = "Verified";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":["ACCOUNT_OBJECT_KEY_MIGRATION_STATE","MigrationState","SESSION_BATCH_SIZE","TrackingStatus","RoomKeyRequestState","DeviceVerification"],"sources":["../../../src/crypto/store/base.ts"],"sourcesContent":["/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type Logger } from \"../../logger.ts\";\nimport { type CrossSigningKeyInfo } from \"../../crypto-api/index.ts\";\nimport { type AESEncryptedSecretStoragePayload } from \"../../@types/AESEncryptedSecretStoragePayload.ts\";\nimport { type ISignatures } from \"../../@types/signed.ts\";\n\n/**\n * Internal module. Definitions for storage for the crypto module\n */\n\nexport interface SecretStorePrivateKeys {\n \"m.megolm_backup.v1\": AESEncryptedSecretStoragePayload;\n}\n\n/**\n * Abstraction of things that can store data required for end-to-end encryption\n */\nexport interface CryptoStore {\n /**\n * Returns true if this CryptoStore has ever been initialised (ie, it might contain data).\n *\n * Unlike the rest of the methods in this interface, can be called before {@link CryptoStore#startup}.\n *\n * @internal\n */\n containsData(): Promise<boolean>;\n\n /**\n * Initialise this crypto store.\n *\n * Typically, this involves provisioning storage, and migrating any existing data to the current version of the\n * storage schema where appropriate.\n *\n * Must be called before any of the rest of the methods in this interface.\n */\n startup(): Promise<CryptoStore>;\n\n deleteAllData(): Promise<void>;\n\n /**\n * Get data on how much of the libolm to Rust Crypto migration has been done.\n *\n * @internal\n */\n getMigrationState(): Promise<MigrationState>;\n\n /**\n * Set data on how much of the libolm to Rust Crypto migration has been done.\n *\n * @internal\n */\n setMigrationState(migrationState: MigrationState): Promise<void>;\n\n // Olm Account\n getAccount(txn: unknown, func: (accountPickle: string | null) => void): void;\n storeAccount(txn: unknown, accountPickle: string): void;\n getCrossSigningKeys(txn: unknown, func: (keys: Record<string, CrossSigningKeyInfo> | null) => void): void;\n getSecretStorePrivateKey<K extends keyof SecretStorePrivateKeys>(\n txn: unknown,\n func: (key: SecretStorePrivateKeys[K] | null) => void,\n type: K,\n ): void;\n storeSecretStorePrivateKey<K extends keyof SecretStorePrivateKeys>(\n txn: unknown,\n type: K,\n key: SecretStorePrivateKeys[K],\n ): void;\n\n // Olm Sessions\n countEndToEndSessions(txn: unknown, func: (count: number) => void): void;\n getEndToEndSession(\n deviceKey: string,\n sessionId: string,\n txn: unknown,\n func: (session: ISessionInfo | null) => void,\n ): void;\n getEndToEndSessions(\n deviceKey: string,\n txn: unknown,\n func: (sessions: { [sessionId: string]: ISessionInfo }) => void,\n ): void;\n\n storeEndToEndSession(deviceKey: string, sessionId: string, sessionInfo: ISessionInfo, txn: unknown): void;\n\n /**\n * Get a batch of end-to-end sessions from the database.\n *\n * @returns A batch of Olm Sessions, or `null` if no sessions are left.\n * @internal\n */\n getEndToEndSessionsBatch(): Promise<ISessionInfo[] | null>;\n\n /**\n * Delete a batch of end-to-end sessions from the database.\n *\n * Any sessions in the list which are not found are silently ignored.\n *\n * @internal\n */\n deleteEndToEndSessionsBatch(sessions: { deviceKey?: string; sessionId?: string }[]): Promise<void>;\n\n // Inbound Group Sessions\n getEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n txn: unknown,\n func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,\n ): void;\n storeEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: unknown,\n ): void;\n\n /**\n * Count the number of Megolm sessions in the database.\n *\n * @internal\n */\n countEndToEndInboundGroupSessions(): Promise<number>;\n\n /**\n * Get a batch of Megolm sessions from the database.\n *\n * @returns A batch of Megolm Sessions, or `null` if no sessions are left.\n * @internal\n */\n getEndToEndInboundGroupSessionsBatch(): Promise<SessionExtended[] | null>;\n\n /**\n * Delete a batch of Megolm sessions from the database.\n *\n * Any sessions in the list which are not found are silently ignored.\n *\n * @internal\n */\n deleteEndToEndInboundGroupSessionsBatch(sessions: { senderKey: string; sessionId: string }[]): Promise<void>;\n\n // Device Data\n getEndToEndRooms(txn: unknown, func: (rooms: Record<string, IRoomEncryption>) => void): void;\n markSessionsNeedingBackup(sessions: ISession[], txn?: unknown): Promise<void>;\n\n // Session key backups\n doTxn<T>(mode: Mode, stores: Iterable<string>, func: (txn: unknown) => T, log?: Logger): Promise<T>;\n}\n\nexport type Mode = \"readonly\" | \"readwrite\";\n\n/** Data on a Megolm session */\nexport interface ISession {\n senderKey: string;\n sessionId: string;\n sessionData?: InboundGroupSessionData;\n}\n\n/** Extended data on a Megolm session */\nexport interface SessionExtended extends ISession {\n needsBackup: boolean;\n}\n\n/** Data on an Olm session */\nexport interface ISessionInfo {\n deviceKey?: string;\n sessionId?: string;\n session?: string;\n lastReceivedMessageTs?: number;\n}\n\nexport interface IDeviceData {\n devices: {\n [userId: string]: {\n [deviceId: string]: IDevice;\n };\n };\n trackingStatus: {\n [userId: string]: TrackingStatus;\n };\n crossSigningInfo?: Record<string, ICrossSigningInfo>;\n syncToken?: string;\n}\n\nexport interface IWithheld {\n // eslint-disable-next-line camelcase\n room_id: string;\n code: string;\n reason: string;\n}\n\n/**\n * Represents an outgoing room key request\n */\nexport interface OutgoingRoomKeyRequest {\n /**\n * Unique id for this request. Used for both an id within the request for later pairing with a cancellation,\n * and for the transaction id when sending the to_device messages to our local server.\n */\n requestId: string;\n requestTxnId?: string;\n /**\n * Transaction id for the cancellation, if any\n */\n cancellationTxnId?: string;\n /**\n * List of recipients for the request\n */\n recipients: IRoomKeyRequestRecipient[];\n /**\n * Parameters for the request\n */\n requestBody: IRoomKeyRequestBody;\n /**\n * current state of this request\n */\n state: RoomKeyRequestState;\n}\n\n/**\n * Keys for the `account` object store to store the migration state.\n * Values are defined in `MigrationState`.\n * @internal\n */\nexport const ACCOUNT_OBJECT_KEY_MIGRATION_STATE = \"migrationState\";\n\n/**\n * A record of which steps have been completed in the libolm to Rust Crypto migration.\n *\n * Used by {@link CryptoStore#getMigrationState} and {@link CryptoStore#setMigrationState}.\n *\n * @internal\n */\nexport enum MigrationState {\n /** No migration steps have yet been completed. */\n NOT_STARTED,\n\n /** We have migrated the account data, cross-signing keys, etc. */\n INITIAL_DATA_MIGRATED,\n\n /** INITIAL_DATA_MIGRATED, and in addition, we have migrated all the Olm sessions. */\n OLM_SESSIONS_MIGRATED,\n\n /** OLM_SESSIONS_MIGRATED, and in addition, we have migrated all the Megolm sessions. */\n MEGOLM_SESSIONS_MIGRATED,\n\n /** MEGOLM_SESSIONS_MIGRATED, and in addition, we have migrated all the room settings. */\n ROOM_SETTINGS_MIGRATED,\n\n /** ROOM_SETTINGS_MIGRATED, and in addition, we have done the first own keys query in order to\n * load the public part of the keys that have been migrated */\n INITIAL_OWN_KEY_QUERY_DONE,\n}\n\n/**\n * The size of batches to be returned by {@link CryptoStore#getEndToEndSessionsBatch} and\n * {@link CryptoStore#getEndToEndInboundGroupSessionsBatch}.\n */\nexport const SESSION_BATCH_SIZE = 50;\n\nexport interface InboundGroupSessionData {\n room_id: string; // eslint-disable-line camelcase\n /** pickled Olm.InboundGroupSession */\n session: string;\n keysClaimed?: Record<string, string>;\n /** Devices involved in forwarding this session to us (normally empty). */\n forwardingCurve25519KeyChain: string[];\n /** whether this session is untrusted. */\n untrusted?: boolean;\n /** whether this session exists during the room being set to shared history. */\n sharedHistory?: boolean;\n}\n\nexport interface ICrossSigningInfo {\n keys: Record<string, CrossSigningKeyInfo>;\n firstUse: boolean;\n crossSigningVerifiedBefore: boolean;\n}\n\n/* eslint-disable camelcase */\nexport interface IRoomEncryption {\n algorithm: string;\n rotation_period_ms?: number;\n rotation_period_msgs?: number;\n}\n/* eslint-enable camelcase */\n\nexport enum TrackingStatus {\n NotTracked,\n PendingDownload,\n DownloadInProgress,\n UpToDate,\n}\n\n/**\n * possible states for a room key request\n *\n * The state machine looks like:\n * ```\n *\n * | (cancellation sent)\n * | .-------------------------------------------------.\n * | | |\n * V V (cancellation requested) |\n * UNSENT -----------------------------+ |\n * | | |\n * | | |\n * | (send successful) | CANCELLATION_PENDING_AND_WILL_RESEND\n * V | Λ\n * SENT | |\n * |-------------------------------- | --------------'\n * | | (cancellation requested with intent\n * | | to resend the original request)\n * | |\n * | (cancellation requested) |\n * V |\n * CANCELLATION_PENDING |\n * | |\n * | (cancellation sent) |\n * V |\n * (deleted) <---------------------------+\n * ```\n */\nexport enum RoomKeyRequestState {\n /** request not yet sent */\n Unsent,\n /** request sent, awaiting reply */\n Sent,\n /** reply received, cancellation not yet sent */\n CancellationPending,\n /**\n * Cancellation not yet sent and will transition to UNSENT instead of\n * being deleted once the cancellation has been sent.\n */\n CancellationPendingAndWillResend,\n}\n\n/* eslint-disable camelcase */\ninterface IRoomKey {\n room_id: string;\n algorithm: string;\n}\n\n/**\n * The parameters of a room key request. The details of the request may\n * vary with the crypto algorithm, but the management and storage layers for\n * outgoing requests expect it to have 'room_id' and 'session_id' properties.\n */\nexport interface IRoomKeyRequestBody extends IRoomKey {\n session_id: string;\n sender_key: string;\n}\n\n/* eslint-enable camelcase */\n\nexport interface IRoomKeyRequestRecipient {\n userId: string;\n deviceId: string;\n}\n\ninterface IDevice {\n keys: Record<string, string>;\n algorithms: string[];\n verified: DeviceVerification;\n known: boolean;\n unsigned?: Record<string, any>;\n signatures?: ISignatures;\n}\n\n/** State of the verification of the device. */\nexport enum DeviceVerification {\n Blocked = -1,\n Unverified = 0,\n Verified = 1,\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA;AACA;AACA;;AAMA;AACA;AACA;;AAqIA;;AAOA;;AAKA;;AA4BA;AACA;AACA;;AA0BA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMA,kCAAkC,GAAG,gBAAgB;;AAElE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAYC,cAAc,0BAAdA,cAAc;EACtB;EADQA,cAAc,CAAdA,cAAc;EAItB;EAJQA,cAAc,CAAdA,cAAc;EAOtB;EAPQA,cAAc,CAAdA,cAAc;EAUtB;EAVQA,cAAc,CAAdA,cAAc;EAatB;EAbQA,cAAc,CAAdA,cAAc;EAgBtB;AACJ;EAjBYA,cAAc,CAAdA,cAAc;EAAA,OAAdA,cAAc;AAAA;;AAqB1B;AACA;AACA;AACA;AACA,OAAO,IAAMC,kBAAkB,GAAG,EAAE;;AAqBpC;;AAMA;;AAEA,WAAYC,cAAc,0BAAdA,cAAc;EAAdA,cAAc,CAAdA,cAAc;EAAdA,cAAc,CAAdA,cAAc;EAAdA,cAAc,CAAdA,cAAc;EAAdA,cAAc,CAAdA,cAAc;EAAA,OAAdA,cAAc;AAAA;;AAO1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAYC,mBAAmB,0BAAnBA,mBAAmB;EAC3B;EADQA,mBAAmB,CAAnBA,mBAAmB;EAG3B;EAHQA,mBAAmB,CAAnBA,mBAAmB;EAK3B;EALQA,mBAAmB,CAAnBA,mBAAmB;EAO3B;AACJ;AACA;AACA;EAVYA,mBAAmB,CAAnBA,mBAAmB;EAAA,OAAnBA,mBAAmB;AAAA;;AAc/B;;AAMA;AACA;AACA;AACA;AACA;;AAMA;;AAgBA;AACA,WAAYC,kBAAkB,0BAAlBA,kBAAkB;EAAlBA,kBAAkB,CAAlBA,kBAAkB;EAAlBA,kBAAkB,CAAlBA,kBAAkB;EAAlBA,kBAAkB,CAAlBA,kBAAkB;EAAA,OAAlBA,kBAAkB;AAAA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../../src/crypto/store/base.ts"],"sourcesContent":["/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type Logger } from \"../../logger.ts\";\nimport { type CrossSigningKeyInfo } from \"../../crypto-api/index.ts\";\nimport { type AESEncryptedSecretStoragePayload } from \"../../@types/AESEncryptedSecretStoragePayload.ts\";\nimport { type ISignatures } from \"../../@types/signed.ts\";\n\n/**\n * Internal module. Definitions for storage for the crypto module\n */\n\nexport interface SecretStorePrivateKeys {\n \"m.megolm_backup.v1\": AESEncryptedSecretStoragePayload;\n}\n\n/**\n * Abstraction of things that can store data required for end-to-end encryption\n */\nexport interface CryptoStore {\n /**\n * Returns true if this CryptoStore has ever been initialised (ie, it might contain data).\n *\n * Unlike the rest of the methods in this interface, can be called before {@link CryptoStore#startup}.\n *\n * @internal\n */\n containsData(): Promise<boolean>;\n\n /**\n * Initialise this crypto store.\n *\n * Typically, this involves provisioning storage, and migrating any existing data to the current version of the\n * storage schema where appropriate.\n *\n * Must be called before any of the rest of the methods in this interface.\n */\n startup(): Promise<CryptoStore>;\n\n deleteAllData(): Promise<void>;\n\n /**\n * Get data on how much of the libolm to Rust Crypto migration has been done.\n *\n * @internal\n */\n getMigrationState(): Promise<MigrationState>;\n\n /**\n * Set data on how much of the libolm to Rust Crypto migration has been done.\n *\n * @internal\n */\n setMigrationState(migrationState: MigrationState): Promise<void>;\n\n // Olm Account\n getAccount(txn: unknown, func: (accountPickle: string | null) => void): void;\n storeAccount(txn: unknown, accountPickle: string): void;\n getCrossSigningKeys(txn: unknown, func: (keys: Record<string, CrossSigningKeyInfo> | null) => void): void;\n getSecretStorePrivateKey<K extends keyof SecretStorePrivateKeys>(\n txn: unknown,\n func: (key: SecretStorePrivateKeys[K] | null) => void,\n type: K,\n ): void;\n storeSecretStorePrivateKey<K extends keyof SecretStorePrivateKeys>(\n txn: unknown,\n type: K,\n key: SecretStorePrivateKeys[K],\n ): void;\n\n // Olm Sessions\n countEndToEndSessions(txn: unknown, func: (count: number) => void): void;\n getEndToEndSession(\n deviceKey: string,\n sessionId: string,\n txn: unknown,\n func: (session: ISessionInfo | null) => void,\n ): void;\n getEndToEndSessions(\n deviceKey: string,\n txn: unknown,\n func: (sessions: { [sessionId: string]: ISessionInfo }) => void,\n ): void;\n\n storeEndToEndSession(deviceKey: string, sessionId: string, sessionInfo: ISessionInfo, txn: unknown): void;\n\n /**\n * Get a batch of end-to-end sessions from the database.\n *\n * @returns A batch of Olm Sessions, or `null` if no sessions are left.\n * @internal\n */\n getEndToEndSessionsBatch(): Promise<ISessionInfo[] | null>;\n\n /**\n * Delete a batch of end-to-end sessions from the database.\n *\n * Any sessions in the list which are not found are silently ignored.\n *\n * @internal\n */\n deleteEndToEndSessionsBatch(sessions: { deviceKey?: string; sessionId?: string }[]): Promise<void>;\n\n // Inbound Group Sessions\n getEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n txn: unknown,\n func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,\n ): void;\n storeEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: unknown,\n ): void;\n\n /**\n * Count the number of Megolm sessions in the database.\n *\n * @internal\n */\n countEndToEndInboundGroupSessions(): Promise<number>;\n\n /**\n * Get a batch of Megolm sessions from the database.\n *\n * @returns A batch of Megolm Sessions, or `null` if no sessions are left.\n * @internal\n */\n getEndToEndInboundGroupSessionsBatch(): Promise<SessionExtended[] | null>;\n\n /**\n * Delete a batch of Megolm sessions from the database.\n *\n * Any sessions in the list which are not found are silently ignored.\n *\n * @internal\n */\n deleteEndToEndInboundGroupSessionsBatch(sessions: { senderKey: string; sessionId: string }[]): Promise<void>;\n\n // Device Data\n getEndToEndRooms(txn: unknown, func: (rooms: Record<string, IRoomEncryption>) => void): void;\n markSessionsNeedingBackup(sessions: ISession[], txn?: unknown): Promise<void>;\n\n // Session key backups\n doTxn<T>(mode: Mode, stores: Iterable<string>, func: (txn: unknown) => T, log?: Logger): Promise<T>;\n}\n\nexport type Mode = \"readonly\" | \"readwrite\";\n\n/** Data on a Megolm session */\nexport interface ISession {\n senderKey: string;\n sessionId: string;\n sessionData?: InboundGroupSessionData;\n}\n\n/** Extended data on a Megolm session */\nexport interface SessionExtended extends ISession {\n needsBackup: boolean;\n}\n\n/** Data on an Olm session */\nexport interface ISessionInfo {\n deviceKey?: string;\n sessionId?: string;\n session?: string;\n lastReceivedMessageTs?: number;\n}\n\nexport interface IDeviceData {\n devices: {\n [userId: string]: {\n [deviceId: string]: IDevice;\n };\n };\n trackingStatus: {\n [userId: string]: TrackingStatus;\n };\n crossSigningInfo?: Record<string, ICrossSigningInfo>;\n syncToken?: string;\n}\n\nexport interface IWithheld {\n // eslint-disable-next-line camelcase\n room_id: string;\n code: string;\n reason: string;\n}\n\n/**\n * Represents an outgoing room key request\n */\nexport interface OutgoingRoomKeyRequest {\n /**\n * Unique id for this request. Used for both an id within the request for later pairing with a cancellation,\n * and for the transaction id when sending the to_device messages to our local server.\n */\n requestId: string;\n requestTxnId?: string;\n /**\n * Transaction id for the cancellation, if any\n */\n cancellationTxnId?: string;\n /**\n * List of recipients for the request\n */\n recipients: IRoomKeyRequestRecipient[];\n /**\n * Parameters for the request\n */\n requestBody: IRoomKeyRequestBody;\n /**\n * current state of this request\n */\n state: RoomKeyRequestState;\n}\n\n/**\n * Keys for the `account` object store to store the migration state.\n * Values are defined in `MigrationState`.\n * @internal\n */\nexport const ACCOUNT_OBJECT_KEY_MIGRATION_STATE = \"migrationState\";\n\n/**\n * A record of which steps have been completed in the libolm to Rust Crypto migration.\n *\n * Used by {@link CryptoStore#getMigrationState} and {@link CryptoStore#setMigrationState}.\n *\n * @internal\n */\nexport enum MigrationState {\n /** No migration steps have yet been completed. */\n NOT_STARTED,\n\n /** We have migrated the account data, cross-signing keys, etc. */\n INITIAL_DATA_MIGRATED,\n\n /** INITIAL_DATA_MIGRATED, and in addition, we have migrated all the Olm sessions. */\n OLM_SESSIONS_MIGRATED,\n\n /** OLM_SESSIONS_MIGRATED, and in addition, we have migrated all the Megolm sessions. */\n MEGOLM_SESSIONS_MIGRATED,\n\n /** MEGOLM_SESSIONS_MIGRATED, and in addition, we have migrated all the room settings. */\n ROOM_SETTINGS_MIGRATED,\n\n /** ROOM_SETTINGS_MIGRATED, and in addition, we have done the first own keys query in order to\n * load the public part of the keys that have been migrated */\n INITIAL_OWN_KEY_QUERY_DONE,\n}\n\n/**\n * The size of batches to be returned by {@link CryptoStore#getEndToEndSessionsBatch} and\n * {@link CryptoStore#getEndToEndInboundGroupSessionsBatch}.\n */\nexport const SESSION_BATCH_SIZE = 50;\n\nexport interface InboundGroupSessionData {\n room_id: string; // eslint-disable-line camelcase\n /** pickled Olm.InboundGroupSession */\n session: string;\n keysClaimed?: Record<string, string>;\n /** Devices involved in forwarding this session to us (normally empty). */\n forwardingCurve25519KeyChain: string[];\n /** whether this session is untrusted. */\n untrusted?: boolean;\n /** whether this session exists during the room being set to shared history. */\n sharedHistory?: boolean;\n}\n\nexport interface ICrossSigningInfo {\n keys: Record<string, CrossSigningKeyInfo>;\n firstUse: boolean;\n crossSigningVerifiedBefore: boolean;\n}\n\n/* eslint-disable camelcase */\nexport interface IRoomEncryption {\n algorithm: string;\n rotation_period_ms?: number;\n rotation_period_msgs?: number;\n}\n/* eslint-enable camelcase */\n\nexport enum TrackingStatus {\n NotTracked,\n PendingDownload,\n DownloadInProgress,\n UpToDate,\n}\n\n/**\n * possible states for a room key request\n *\n * The state machine looks like:\n * ```\n *\n * | (cancellation sent)\n * | .-------------------------------------------------.\n * | | |\n * V V (cancellation requested) |\n * UNSENT -----------------------------+ |\n * | | |\n * | | |\n * | (send successful) | CANCELLATION_PENDING_AND_WILL_RESEND\n * V | Λ\n * SENT | |\n * |-------------------------------- | --------------'\n * | | (cancellation requested with intent\n * | | to resend the original request)\n * | |\n * | (cancellation requested) |\n * V |\n * CANCELLATION_PENDING |\n * | |\n * | (cancellation sent) |\n * V |\n * (deleted) <---------------------------+\n * ```\n */\nexport enum RoomKeyRequestState {\n /** request not yet sent */\n Unsent,\n /** request sent, awaiting reply */\n Sent,\n /** reply received, cancellation not yet sent */\n CancellationPending,\n /**\n * Cancellation not yet sent and will transition to UNSENT instead of\n * being deleted once the cancellation has been sent.\n */\n CancellationPendingAndWillResend,\n}\n\n/* eslint-disable camelcase */\ninterface IRoomKey {\n room_id: string;\n algorithm: string;\n}\n\n/**\n * The parameters of a room key request. The details of the request may\n * vary with the crypto algorithm, but the management and storage layers for\n * outgoing requests expect it to have 'room_id' and 'session_id' properties.\n */\nexport interface IRoomKeyRequestBody extends IRoomKey {\n session_id: string;\n sender_key: string;\n}\n\n/* eslint-enable camelcase */\n\nexport interface IRoomKeyRequestRecipient {\n userId: string;\n deviceId: string;\n}\n\ninterface IDevice {\n keys: Record<string, string>;\n algorithms: string[];\n verified: DeviceVerification;\n known: boolean;\n unsigned?: Record<string, any>;\n signatures?: ISignatures;\n}\n\n/** State of the verification of the device. */\nexport enum DeviceVerification {\n Blocked = -1,\n Unverified = 0,\n Verified = 1,\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA;AACA;AACA;;AAMA;AACA;AACA;;AAqIA;;AAOA;;AAKA;;AA4BA;AACA;AACA;;AA0BA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,kCAAkC,GAAG,gBAAgB;;AAElE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAY,cAAc,0BAAd,cAAc;EACtB;EADQ,cAAc,CAAd,cAAc;EAItB;EAJQ,cAAc,CAAd,cAAc;EAOtB;EAPQ,cAAc,CAAd,cAAc;EAUtB;EAV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