matrix-js-sdk 41.8.0 → 41.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +1 -1
- package/lib/@types/AESEncryptedSecretStoragePayload.js +3 -1
- package/lib/@types/IIdentityServerProvider.js +3 -1
- package/lib/@types/PushRules.js +7 -7
- package/lib/@types/PushRules.js.map +1 -1
- package/lib/@types/auth.js +4 -4
- package/lib/@types/auth.js.map +1 -1
- package/lib/@types/beacon.js +2 -2
- package/lib/@types/beacon.js.map +1 -1
- package/lib/@types/common.js +3 -1
- package/lib/@types/crypto.js +3 -1
- package/lib/@types/event.js +20 -20
- package/lib/@types/event.js.map +1 -1
- package/lib/@types/events.js +3 -1
- package/lib/@types/extensible_events.js +6 -6
- package/lib/@types/extensible_events.js.map +1 -1
- package/lib/@types/global.d.js.map +1 -1
- package/lib/@types/json.js +3 -1
- package/lib/@types/local_notifications.js +3 -1
- package/lib/@types/location.js +4 -4
- package/lib/@types/location.js.map +1 -1
- package/lib/@types/matrix-sdk-crypto-wasm.d.js +3 -1
- package/lib/@types/media.js +3 -1
- package/lib/@types/membership.js +1 -1
- package/lib/@types/membership.js.map +1 -1
- package/lib/@types/partials.js +6 -6
- package/lib/@types/partials.js.map +1 -1
- package/lib/@types/polls.js +5 -5
- package/lib/@types/polls.js.map +1 -1
- package/lib/@types/read_receipts.js +2 -2
- package/lib/@types/read_receipts.js.map +1 -1
- package/lib/@types/registration.js +3 -1
- package/lib/@types/requests.js +1 -1
- package/lib/@types/requests.js.map +1 -1
- package/lib/@types/retention.js +1 -1
- package/lib/@types/retention.js.map +1 -1
- package/lib/@types/search.js +1 -1
- package/lib/@types/search.js.map +1 -1
- package/lib/@types/signed.js +3 -1
- package/lib/@types/spaces.js +3 -1
- package/lib/@types/state_events.js +3 -1
- package/lib/@types/synapse.js +3 -1
- package/lib/@types/sync.js +1 -1
- package/lib/@types/sync.js.map +1 -1
- package/lib/@types/threepids.js +1 -1
- package/lib/@types/threepids.js.map +1 -1
- package/lib/@types/topic.js +1 -1
- package/lib/@types/topic.js.map +1 -1
- package/lib/@types/uia.js +3 -1
- package/lib/NamespacedValue.js +8 -8
- package/lib/NamespacedValue.js.map +1 -1
- package/lib/ReEmitter.js +9 -16
- package/lib/ReEmitter.js.map +1 -1
- package/lib/ToDeviceMessageQueue.js +49 -57
- package/lib/ToDeviceMessageQueue.js.map +1 -1
- package/lib/autodiscovery.js +232 -247
- package/lib/autodiscovery.js.map +1 -1
- package/lib/base64.js +1 -1
- package/lib/base64.js.map +1 -1
- package/lib/browser-index.d.ts +2 -2
- package/lib/browser-index.d.ts.map +1 -1
- package/lib/browser-index.js +5 -5
- package/lib/browser-index.js.map +1 -1
- package/lib/capabilityPoller.js +19 -22
- package/lib/capabilityPoller.js.map +1 -1
- package/lib/client.d.ts +2 -8
- package/lib/client.d.ts.map +1 -1
- package/lib/client.js +2043 -2487
- package/lib/client.js.map +1 -1
- package/lib/common-crypto/CryptoBackend.js +2 -2
- package/lib/common-crypto/CryptoBackend.js.map +1 -1
- package/lib/common-crypto/key-passphrase.js.map +1 -1
- package/lib/content-helpers.js +43 -48
- package/lib/content-helpers.js.map +1 -1
- package/lib/content-repo.js +14 -24
- package/lib/content-repo.js.map +1 -1
- package/lib/crypto/store/base.js +6 -6
- package/lib/crypto/store/base.js.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store-backend.js +190 -238
- package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
- package/lib/crypto/store/indexeddb-crypto-store.js +25 -30
- package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
- package/lib/crypto/store/localStorage-crypto-store.js +113 -145
- package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
- package/lib/crypto/store/memory-crypto-store.js +74 -105
- package/lib/crypto/store/memory-crypto-store.js.map +1 -1
- package/lib/crypto-api/CryptoEvent.js +1 -1
- package/lib/crypto-api/CryptoEvent.js.map +1 -1
- package/lib/crypto-api/CryptoEventHandlerMap.js +3 -1
- package/lib/crypto-api/index.d.ts +15 -6
- package/lib/crypto-api/index.d.ts.map +1 -1
- package/lib/crypto-api/index.js +22 -22
- package/lib/crypto-api/index.js.map +1 -1
- package/lib/crypto-api/key-passphrase.js +15 -23
- package/lib/crypto-api/key-passphrase.js.map +1 -1
- package/lib/crypto-api/keybackup.js +3 -1
- package/lib/crypto-api/recovery-key.js +11 -12
- package/lib/crypto-api/recovery-key.js.map +1 -1
- package/lib/crypto-api/verification.js +3 -3
- package/lib/crypto-api/verification.js.map +1 -1
- package/lib/digest.js +7 -14
- package/lib/digest.js.map +1 -1
- package/lib/embedded.d.ts.map +1 -1
- package/lib/embedded.js +380 -505
- package/lib/embedded.js.map +1 -1
- package/lib/errors.js +2 -2
- package/lib/errors.js.map +1 -1
- package/lib/event-mapper.js +10 -12
- package/lib/event-mapper.js.map +1 -1
- package/lib/extensible_events_v1/ExtensibleEvent.js.map +1 -1
- package/lib/extensible_events_v1/InvalidEventError.js.map +1 -1
- package/lib/extensible_events_v1/MessageEvent.js +11 -13
- package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollEndEvent.js +3 -4
- package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollResponseEvent.js +5 -6
- package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
- package/lib/extensible_events_v1/PollStartEvent.js +8 -10
- package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
- package/lib/extensible_events_v1/utilities.js.map +1 -1
- package/lib/feature.js +18 -31
- package/lib/feature.js.map +1 -1
- package/lib/filter-component.d.ts.map +1 -1
- package/lib/filter-component.js +20 -26
- package/lib/filter-component.js.map +1 -1
- package/lib/filter.js +14 -17
- package/lib/filter.js.map +1 -1
- package/lib/http-api/errors.js +28 -43
- package/lib/http-api/errors.js.map +1 -1
- package/lib/http-api/fetch.js +141 -159
- package/lib/http-api/fetch.js.map +1 -1
- package/lib/http-api/index.js +17 -20
- package/lib/http-api/index.js.map +1 -1
- package/lib/http-api/interface.js +1 -1
- package/lib/http-api/interface.js.map +1 -1
- package/lib/http-api/method.js +1 -1
- package/lib/http-api/method.js.map +1 -1
- package/lib/http-api/prefix.js +3 -3
- package/lib/http-api/prefix.js.map +1 -1
- package/lib/http-api/refresh.js +74 -94
- package/lib/http-api/refresh.js.map +1 -1
- package/lib/http-api/utils.d.ts +1 -1
- package/lib/http-api/utils.d.ts.map +1 -1
- package/lib/http-api/utils.js +34 -42
- package/lib/http-api/utils.js.map +1 -1
- package/lib/index.js.map +1 -1
- package/lib/indexeddb-helpers.js +3 -3
- package/lib/indexeddb-helpers.js.map +1 -1
- package/lib/indexeddb-worker.js.map +1 -1
- package/lib/interactive-auth.d.ts +5 -5
- package/lib/interactive-auth.d.ts.map +1 -1
- package/lib/interactive-auth.js +172 -204
- package/lib/interactive-auth.js.map +1 -1
- package/lib/logger.js +21 -57
- package/lib/logger.js.map +1 -1
- package/lib/matrix.js +7 -11
- package/lib/matrix.js.map +1 -1
- package/lib/matrixrtc/CallMembership.js +80 -74
- package/lib/matrixrtc/CallMembership.js.map +1 -1
- package/lib/matrixrtc/EncryptionManager.js +1 -1
- package/lib/matrixrtc/EncryptionManager.js.map +1 -1
- package/lib/matrixrtc/IKeyTransport.js +1 -1
- package/lib/matrixrtc/IKeyTransport.js.map +1 -1
- package/lib/matrixrtc/IMembershipManager.js +1 -1
- package/lib/matrixrtc/IMembershipManager.js.map +1 -1
- package/lib/matrixrtc/LivekitTransport.d.ts +1 -1
- package/lib/matrixrtc/LivekitTransport.js +4 -4
- package/lib/matrixrtc/LivekitTransport.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSession.js +137 -187
- package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
- package/lib/matrixrtc/MatrixRTCSessionManager.js +36 -41
- package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
- package/lib/matrixrtc/MembershipManager.js +332 -378
- package/lib/matrixrtc/MembershipManager.js.map +1 -1
- package/lib/matrixrtc/MembershipManagerActionScheduler.js +54 -63
- package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
- package/lib/matrixrtc/RTCEncryptionManager.js +119 -143
- package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
- package/lib/matrixrtc/ToDeviceKeyTransport.js +53 -58
- package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
- package/lib/matrixrtc/index.js.map +1 -1
- package/lib/matrixrtc/membershipData/common.js +1 -1
- package/lib/matrixrtc/membershipData/common.js.map +1 -1
- package/lib/matrixrtc/membershipData/index.js.map +1 -1
- package/lib/matrixrtc/membershipData/rtc.js +15 -23
- package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
- package/lib/matrixrtc/membershipData/session.js +4 -5
- package/lib/matrixrtc/membershipData/session.js.map +1 -1
- package/lib/matrixrtc/types.js +4 -6
- package/lib/matrixrtc/types.js.map +1 -1
- package/lib/matrixrtc/utils.js +4 -11
- package/lib/matrixrtc/utils.js.map +1 -1
- package/lib/models/MSC3089Branch.js +91 -116
- package/lib/models/MSC3089Branch.js.map +1 -1
- package/lib/models/MSC3089TreeSpace.js +209 -245
- package/lib/models/MSC3089TreeSpace.js.map +1 -1
- package/lib/models/ToDeviceMessage.js +3 -1
- package/lib/models/beacon.js +14 -13
- package/lib/models/beacon.js.map +1 -1
- package/lib/models/compare-event-ordering.js +13 -13
- package/lib/models/compare-event-ordering.js.map +1 -1
- package/lib/models/device.js +3 -3
- package/lib/models/device.js.map +1 -1
- package/lib/models/event-context.js +5 -8
- package/lib/models/event-context.js.map +1 -1
- package/lib/models/event-status.js +1 -1
- package/lib/models/event-status.js.map +1 -1
- package/lib/models/event-timeline-set.js +88 -94
- package/lib/models/event-timeline-set.js.map +1 -1
- package/lib/models/event-timeline.js +28 -30
- package/lib/models/event-timeline.js.map +1 -1
- package/lib/models/event.js +182 -226
- package/lib/models/event.js.map +1 -1
- package/lib/models/invites-ignorer-types.js +4 -4
- package/lib/models/invites-ignorer-types.js.map +1 -1
- package/lib/models/invites-ignorer.js +159 -179
- package/lib/models/invites-ignorer.js.map +1 -1
- package/lib/models/poll.js +71 -81
- package/lib/models/poll.js.map +1 -1
- package/lib/models/profile-keys.js +2 -2
- package/lib/models/profile-keys.js.map +1 -1
- package/lib/models/read-receipt.js +40 -56
- package/lib/models/read-receipt.js.map +1 -1
- package/lib/models/related-relations.js.map +1 -1
- package/lib/models/relations-container.js +22 -23
- package/lib/models/relations-container.js.map +1 -1
- package/lib/models/relations.js +133 -159
- package/lib/models/relations.js.map +1 -1
- package/lib/models/room-member.js +24 -29
- package/lib/models/room-member.js.map +1 -1
- package/lib/models/room-receipts.js +29 -43
- package/lib/models/room-receipts.js.map +1 -1
- package/lib/models/room-retention.js +74 -83
- package/lib/models/room-retention.js.map +1 -1
- package/lib/models/room-state.js +143 -172
- package/lib/models/room-state.js.map +1 -1
- package/lib/models/room-sticky-events.d.ts +1 -0
- package/lib/models/room-sticky-events.d.ts.map +1 -1
- package/lib/models/room-sticky-events.js +45 -65
- package/lib/models/room-sticky-events.js.map +1 -1
- package/lib/models/room-summary.js.map +1 -1
- package/lib/models/room.d.ts.map +1 -1
- package/lib/models/room.js +765 -909
- package/lib/models/room.js.map +1 -1
- package/lib/models/search-result.js +5 -5
- package/lib/models/search-result.js.map +1 -1
- package/lib/models/thread.js +225 -285
- package/lib/models/thread.js.map +1 -1
- package/lib/models/typed-event-emitter.js +7 -18
- package/lib/models/typed-event-emitter.js.map +1 -1
- package/lib/models/user.js +8 -8
- package/lib/models/user.js.map +1 -1
- package/lib/oidc/authorize.js +208 -241
- package/lib/oidc/authorize.js.map +1 -1
- package/lib/oidc/discovery.js +23 -36
- package/lib/oidc/discovery.js.map +1 -1
- package/lib/oidc/error.js +1 -1
- package/lib/oidc/error.js.map +1 -1
- package/lib/oidc/index.js +1 -0
- package/lib/oidc/index.js.map +1 -1
- package/lib/oidc/register.js +60 -66
- package/lib/oidc/register.js.map +1 -1
- package/lib/oidc/tokenRefresher.js +77 -91
- package/lib/oidc/tokenRefresher.js.map +1 -1
- package/lib/oidc/validate.js +18 -18
- package/lib/oidc/validate.js.map +1 -1
- package/lib/pushprocessor.js +71 -82
- package/lib/pushprocessor.js.map +1 -1
- package/lib/randomstring.js +9 -9
- package/lib/randomstring.js.map +1 -1
- package/lib/realtime-callbacks.js +25 -28
- package/lib/realtime-callbacks.js.map +1 -1
- package/lib/receipt-accumulator.d.ts +2 -0
- package/lib/receipt-accumulator.d.ts.map +1 -1
- package/lib/receipt-accumulator.js +14 -22
- package/lib/receipt-accumulator.js.map +1 -1
- package/lib/rendezvous/MSC4108SignInWithQR.js +271 -302
- package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
- package/lib/rendezvous/RendezvousChannel.js +3 -1
- package/lib/rendezvous/RendezvousCode.js +3 -1
- package/lib/rendezvous/RendezvousError.js.map +1 -1
- package/lib/rendezvous/RendezvousFailureReason.js +2 -2
- package/lib/rendezvous/RendezvousFailureReason.js.map +1 -1
- package/lib/rendezvous/RendezvousIntent.js +1 -1
- package/lib/rendezvous/RendezvousIntent.js.map +1 -1
- package/lib/rendezvous/RendezvousTransport.js +3 -1
- package/lib/rendezvous/channels/MSC4108SecureChannel.js +123 -147
- package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
- package/lib/rendezvous/index.js +44 -69
- package/lib/rendezvous/index.js.map +1 -1
- package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +1 -1
- package/lib/rendezvous/transports/MSC4108RendezvousSession.js +134 -152
- package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
- package/lib/retentionPolicy.js +6 -9
- package/lib/retentionPolicy.js.map +1 -1
- package/lib/room-hierarchy.js +52 -60
- package/lib/room-hierarchy.js.map +1 -1
- package/lib/rust-crypto/CrossSigningIdentity.js +94 -104
- package/lib/rust-crypto/CrossSigningIdentity.js.map +1 -1
- package/lib/rust-crypto/DehydratedDeviceManager.js +157 -190
- package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
- package/lib/rust-crypto/KeyClaimManager.js +18 -22
- package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
- package/lib/rust-crypto/OutgoingRequestProcessor.js +109 -139
- package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
- package/lib/rust-crypto/OutgoingRequestsManager.js +66 -80
- package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +1 -1
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +196 -224
- package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
- package/lib/rust-crypto/RoomEncryptor.js +127 -143
- package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
- package/lib/rust-crypto/backup.js +453 -549
- package/lib/rust-crypto/backup.js.map +1 -1
- package/lib/rust-crypto/constants.js +1 -1
- package/lib/rust-crypto/constants.js.map +1 -1
- package/lib/rust-crypto/device-converter.js +15 -28
- package/lib/rust-crypto/device-converter.js.map +1 -1
- package/lib/rust-crypto/index.js +103 -116
- package/lib/rust-crypto/index.js.map +1 -1
- package/lib/rust-crypto/libolm_migration.js +303 -365
- package/lib/rust-crypto/libolm_migration.js.map +1 -1
- package/lib/rust-crypto/rust-crypto.d.ts +5 -1
- package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
- package/lib/rust-crypto/rust-crypto.js +1067 -1332
- package/lib/rust-crypto/rust-crypto.js.map +1 -1
- package/lib/rust-crypto/secret-storage.js +12 -25
- package/lib/rust-crypto/secret-storage.js.map +1 -1
- package/lib/rust-crypto/verification.js +137 -189
- package/lib/rust-crypto/verification.js.map +1 -1
- package/lib/scheduler.js +44 -19
- package/lib/scheduler.js.map +1 -1
- package/lib/secret-storage.js +179 -213
- package/lib/secret-storage.js.map +1 -1
- package/lib/serverCapabilities.js +6 -9
- package/lib/serverCapabilities.js.map +1 -1
- package/lib/service-types.js +1 -1
- package/lib/service-types.js.map +1 -1
- package/lib/sliding-sync-sdk.d.ts.map +1 -1
- package/lib/sliding-sync-sdk.js +368 -424
- package/lib/sliding-sync-sdk.js.map +1 -1
- package/lib/sliding-sync.js +135 -171
- package/lib/sliding-sync.js.map +1 -1
- package/lib/store/index.js +3 -1
- package/lib/store/indexeddb-backend.js +3 -1
- package/lib/store/indexeddb-local-backend.js +194 -253
- package/lib/store/indexeddb-local-backend.js.map +1 -1
- package/lib/store/indexeddb-remote-backend.js +33 -63
- package/lib/store/indexeddb-remote-backend.js.map +1 -1
- package/lib/store/indexeddb-store-worker.js +22 -23
- package/lib/store/indexeddb-store-worker.js.map +1 -1
- package/lib/store/indexeddb.js +44 -71
- package/lib/store/indexeddb.js.map +1 -1
- package/lib/store/local-storage-events-emitter.js +2 -2
- package/lib/store/local-storage-events-emitter.js.map +1 -1
- package/lib/store/memory.js +34 -57
- package/lib/store/memory.js.map +1 -1
- package/lib/store/stub.js +22 -35
- package/lib/store/stub.js.map +1 -1
- package/lib/sync-accumulator.js +54 -66
- package/lib/sync-accumulator.js.map +1 -1
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +905 -998
- package/lib/sync.js.map +1 -1
- package/lib/testing.js +63 -105
- package/lib/testing.js.map +1 -1
- package/lib/thread-utils.js +1 -4
- package/lib/thread-utils.js.map +1 -1
- package/lib/timeline-window.js +89 -102
- package/lib/timeline-window.js.map +1 -1
- package/lib/types.js +1 -1
- package/lib/types.js.map +1 -1
- package/lib/utils/decryptAESSecretStorageItem.js +14 -25
- package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
- package/lib/utils/encryptAESSecretStorageItem.js +27 -38
- package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
- package/lib/utils/internal/deriveKeys.js +25 -32
- package/lib/utils/internal/deriveKeys.js.map +1 -1
- package/lib/utils/roomVersion.js +1 -1
- package/lib/utils/roomVersion.js.map +1 -1
- package/lib/utils.js +83 -135
- package/lib/utils.js.map +1 -1
- package/lib/version-support.js +3 -3
- package/lib/version-support.js.map +1 -1
- package/lib/webrtc/audioContext.js +5 -6
- package/lib/webrtc/audioContext.js.map +1 -1
- package/lib/webrtc/call.js +1081 -1250
- package/lib/webrtc/call.js.map +1 -1
- package/lib/webrtc/callEventHandler.js +202 -214
- package/lib/webrtc/callEventHandler.js.map +1 -1
- package/lib/webrtc/callEventTypes.js +2 -2
- package/lib/webrtc/callEventTypes.js.map +1 -1
- package/lib/webrtc/callFeed.js +18 -20
- package/lib/webrtc/callFeed.js.map +1 -1
- package/lib/webrtc/groupCall.js +513 -602
- package/lib/webrtc/groupCall.js.map +1 -1
- package/lib/webrtc/groupCallEventHandler.js +59 -62
- package/lib/webrtc/groupCallEventHandler.js.map +1 -1
- package/lib/webrtc/mediaHandler.js +198 -232
- package/lib/webrtc/mediaHandler.js.map +1 -1
- package/lib/webrtc/stats/callFeedStatsReporter.js +16 -20
- package/lib/webrtc/stats/callFeedStatsReporter.js.map +1 -1
- package/lib/webrtc/stats/callStatsReportGatherer.js +67 -75
- package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
- package/lib/webrtc/stats/callStatsReportSummary.js +3 -1
- package/lib/webrtc/stats/connectionStats.js.map +1 -1
- package/lib/webrtc/stats/connectionStatsBuilder.js +2 -2
- package/lib/webrtc/stats/connectionStatsBuilder.js.map +1 -1
- package/lib/webrtc/stats/connectionStatsReportBuilder.js +20 -24
- package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
- package/lib/webrtc/stats/groupCallStats.js +6 -8
- package/lib/webrtc/stats/groupCallStats.js.map +1 -1
- package/lib/webrtc/stats/media/mediaSsrcHandler.js +7 -8
- package/lib/webrtc/stats/media/mediaSsrcHandler.js.map +1 -1
- package/lib/webrtc/stats/media/mediaTrackHandler.js +7 -9
- package/lib/webrtc/stats/media/mediaTrackHandler.js.map +1 -1
- package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
- package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
- package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +7 -7
- package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
- package/lib/webrtc/stats/statsReport.js +1 -1
- package/lib/webrtc/stats/statsReport.js.map +1 -1
- package/lib/webrtc/stats/statsReportEmitter.js.map +1 -1
- package/lib/webrtc/stats/summaryStatsReportGatherer.js +14 -14
- package/lib/webrtc/stats/summaryStatsReportGatherer.js.map +1 -1
- package/lib/webrtc/stats/trackStatsBuilder.js +32 -34
- package/lib/webrtc/stats/trackStatsBuilder.js.map +1 -1
- package/lib/webrtc/stats/transportStats.js +3 -1
- package/lib/webrtc/stats/transportStatsBuilder.js +9 -9
- package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
- package/lib/webrtc/stats/valueFormatter.js +1 -1
- package/lib/webrtc/stats/valueFormatter.js.map +1 -1
- package/package.json +18 -33
- package/src/@types/global.d.ts +2 -2
- package/src/ToDeviceMessageQueue.ts +2 -2
- package/src/browser-index.ts +4 -4
- package/src/client.ts +15 -20
- package/src/crypto-api/index.ts +17 -6
- package/src/embedded.ts +4 -6
- package/src/filter-component.ts +1 -0
- package/src/http-api/utils.ts +1 -1
- package/src/interactive-auth.ts +11 -5
- package/src/matrixrtc/LivekitTransport.ts +1 -1
- package/src/matrixrtc/MatrixRTCSession.ts +1 -1
- package/src/models/MSC3089Branch.ts +1 -1
- package/src/models/room-sticky-events.ts +1 -0
- package/src/models/room.ts +9 -11
- package/src/receipt-accumulator.ts +2 -0
- package/src/rendezvous/index.ts +1 -1
- package/src/rendezvous/transports/MSC4108RendezvousSession.ts +2 -2
- package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +1 -1
- package/src/rust-crypto/index.ts +6 -6
- package/src/rust-crypto/rust-crypto.ts +31 -7
- package/src/rust-crypto/verification.ts +1 -1
- package/src/sliding-sync-sdk.ts +5 -7
- package/src/store/indexeddb-local-backend.ts +3 -3
- package/src/sync.ts +6 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authorize.js","names":["Log","OidcClient","SigninResponse","SigninState","WebStorageStateStore","logger","secureRandomString","OidcError","validateBearerTokenResponse","validateIdToken","validateStoredUserState","sha256","encodeUnpaddedBase64Url","OAuthGrantType","sleep","Method","generateScope","deviceId","safeDeviceId","concat","generateCodeChallenge","_ref","_asyncToGenerator","codeVerifier","globalThis","crypto","subtle","warn","hashBuffer","_x","apply","arguments","generateAuthorizationParams","_ref2","redirectUri","scope","state","nonce","generateAuthorizationUrl","_ref4","authorizationUrl","clientId","_ref3","url","URL","searchParams","append","toString","_x2","_x3","_x4","generateOidcAuthorizationUrl","_ref6","_ref5","metadata","homeserverUrl","identityServerUrl","prompt","urlState","loginHint","_ref5$responseMode","responseMode","oidcClient","_objectSpread","client_id","redirect_uri","authority","issuer","response_mode","response_type","stateStore","prefix","store","window","sessionStorage","userState","request","createSigninRequest","url_state","login_hint","_x5","normalizeBearerTokenResponseTokenType","response","id_token","expires_at","refresh_token","access_token","token_type","completeAuthorizationCodeGrant","_ref7","code","length","undefined","reconstructedUrl","location","origin","params","URLSearchParams","search","hash","setLogger","stateString","get","Error","MissingOrInvalidStoredState","signInState","fromStorageString","client","signinResponse","processSigninResponse","href","settings","normalizedTokenResponse","oidcClientSettings","tokenResponse","idTokenClaims","profile","error","errorType","message","Object","values","includes","CodeExchangeFailed","_x6","_x7","startDeviceAuthorization","_ref9","_ref8","body","device_authorization_endpoint","fetch","method","Post","headers","json","_x8","waitForDeviceAuthorization","_ref1","_ref0","_session$interval","session","interval","expiration","Date","now","expires_in","device_code","grant_type","DeviceAuthorization","token_endpoint","ok","errorResponse","_x9"],"sources":["../../src/oidc/authorize.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type IdTokenClaims,\n Log,\n OidcClient,\n type SigninRequestCreateArgs,\n SigninResponse,\n SigninState,\n WebStorageStateStore,\n} from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { OidcError } from \"./error.ts\";\nimport {\n type BearerTokenResponse,\n type UserState,\n validateBearerTokenResponse,\n type ValidatedAuthMetadata,\n validateIdToken,\n validateStoredUserState,\n} from \"./validate.ts\";\nimport { sha256 } from \"../digest.ts\";\nimport { encodeUnpaddedBase64Url } from \"../base64.ts\";\nimport { OAuthGrantType } from \"./register.ts\";\nimport { sleep } from \"../utils.ts\";\nimport { Method } from \"../http-api/index.ts\";\n\n// reexport for backwards compatibility\nexport type { BearerTokenResponse };\n\n/**\n * Authorization parameters which are used in the authentication request of an OIDC auth code flow.\n *\n * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.\n */\nexport type AuthorizationParams = {\n state: string;\n scope: string;\n redirectUri: string;\n codeVerifier: string;\n nonce: string;\n};\n\n/**\n * @experimental\n * Generate the scope used in authorization request with OIDC OP\n * @returns scope\n */\nexport const generateScope = (deviceId?: string): string => {\n const safeDeviceId = deviceId ?? secureRandomString(10);\n return `openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${safeDeviceId}`;\n};\n\n// https://www.rfc-editor.org/rfc/rfc7636\nconst generateCodeChallenge = async (codeVerifier: string): Promise<string> => {\n if (!globalThis.crypto.subtle) {\n // @TODO(kerrya) should this be allowed? configurable?\n logger.warn(\"A secure context is required to generate code challenge. Using plain text code challenge\");\n return codeVerifier;\n }\n\n const hashBuffer = await sha256(codeVerifier);\n return encodeUnpaddedBase64Url(hashBuffer);\n};\n\n/**\n * Generate authorization params to pass to {@link generateAuthorizationUrl}.\n *\n * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.\n *\n * @param redirectUri - absolute url for OP to redirect to after authorization\n * @returns AuthorizationParams\n */\nexport const generateAuthorizationParams = ({ redirectUri }: { redirectUri: string }): AuthorizationParams => ({\n scope: generateScope(),\n redirectUri,\n state: secureRandomString(8),\n nonce: secureRandomString(8),\n codeVerifier: secureRandomString(64), // https://tools.ietf.org/html/rfc7636#section-4.1 length needs to be 43-128 characters\n});\n\n/**\n * @deprecated use generateOidcAuthorizationUrl\n * Generate a URL to attempt authorization with the OP\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\n * @param authorizationUrl - endpoint to attempt authorization with the OP\n * @param clientId - id of this client as registered with the OP\n * @param authorizationParams - params to be used in the url\n * @returns a Promise with the url as a string\n */\nexport const generateAuthorizationUrl = async (\n authorizationUrl: string,\n clientId: string,\n { scope, redirectUri, state, nonce, codeVerifier }: AuthorizationParams,\n): Promise<string> => {\n const url = new URL(authorizationUrl);\n url.searchParams.append(\"response_mode\", \"query\");\n url.searchParams.append(\"response_type\", \"code\");\n url.searchParams.append(\"redirect_uri\", redirectUri);\n url.searchParams.append(\"client_id\", clientId);\n url.searchParams.append(\"state\", state);\n url.searchParams.append(\"scope\", scope);\n url.searchParams.append(\"nonce\", nonce);\n\n url.searchParams.append(\"code_challenge_method\", \"S256\");\n url.searchParams.append(\"code_challenge\", await generateCodeChallenge(codeVerifier));\n\n return url.toString();\n};\n\n/**\n * @experimental\n * Generate a URL to attempt authorization with the OP\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\n * @param metadata - validated metadata from OP discovery\n * @param clientId - this client's id as registered with the OP\n * @param homeserverUrl - used to establish the session on return from the OP\n * @param identityServerUrl - used to establish the session on return from the OP\n * @param nonce - state\n * @param prompt - indicates to the OP which flow the user should see - eg login or registration\n * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter\n * @param urlState - value to append to the opaque state identifier to uniquely identify the callback\n * @param loginHint - value to send as the `login_hint` to the OP, giving a hint about the login identifier the user might use to log in.\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\n * @param responseMode - value to send as the `response_mode` to the OP, selecting how auth is passed back during redirect.\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\n * @returns a Promise with the url as a string\n */\nexport const generateOidcAuthorizationUrl = async ({\n metadata,\n redirectUri,\n clientId,\n homeserverUrl,\n identityServerUrl,\n nonce,\n prompt,\n urlState,\n loginHint,\n responseMode = \"query\",\n}: {\n clientId: string;\n metadata: ValidatedAuthMetadata;\n homeserverUrl: string;\n identityServerUrl?: string;\n redirectUri: string;\n nonce: string;\n prompt?: string;\n urlState?: string;\n loginHint?: string;\n responseMode?: SigninRequestCreateArgs[\"response_mode\"];\n}): Promise<string> => {\n const scope = generateScope();\n const oidcClient = new OidcClient({\n ...metadata,\n client_id: clientId,\n redirect_uri: redirectUri,\n authority: metadata.issuer,\n response_mode: responseMode,\n response_type: \"code\",\n scope,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n const userState: UserState = { homeserverUrl, nonce, identityServerUrl };\n const request = await oidcClient.createSigninRequest({\n state: userState,\n nonce,\n prompt,\n url_state: urlState,\n login_hint: loginHint,\n });\n\n return request.url;\n};\n\n/**\n * Normalize token_type to use capital case to make consuming the token response easier\n * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: \"bearer\"\n * Later, when used in auth headers it is case sensitive and must be Bearer\n * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n *\n * @param response - validated token response\n * @returns response with token_type set to 'Bearer'\n */\nconst normalizeBearerTokenResponseTokenType = (response: SigninResponse): BearerTokenResponse =>\n ({\n id_token: response.id_token,\n scope: response.scope,\n expires_at: response.expires_at,\n refresh_token: response.refresh_token,\n access_token: response.access_token,\n token_type: \"Bearer\",\n }) as BearerTokenResponse;\n\n/**\n * @experimental\n * Attempt to exchange authorization code for bearer token.\n *\n * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a\n * request to the Token Endpoint, to obtain the access token, refresh token, etc.\n *\n * @param code - authorization code as returned by OP during authorization\n * @param state - authorization state param as returned by OP during authorization\n * @param responseMode - the response mode used for authentication\n * @returns valid bearer token response\n * @throws An `Error` with `message` set to an entry in {@link OidcError},\n * when the request fails, or the returned token response is invalid.\n */\nexport const completeAuthorizationCodeGrant = async (\n code: string,\n state: string,\n responseMode: SigninRequestCreateArgs[\"response_mode\"] = \"query\",\n): Promise<{\n oidcClientSettings: { clientId: string; issuer: string };\n tokenResponse: BearerTokenResponse;\n homeserverUrl: string;\n idTokenClaims: IdTokenClaims;\n identityServerUrl?: string;\n}> => {\n /**\n * Element Web strips and changes the url on starting the app\n * Use the code and state from query params to rebuild a url\n * so that oidc-client can parse it\n */\n const reconstructedUrl = new URL(window.location.origin);\n\n const params = new URLSearchParams({ code, state });\n if (responseMode === \"query\") {\n reconstructedUrl.search = params.toString();\n } else {\n reconstructedUrl.hash = `#${params.toString()}`;\n }\n\n // set oidc-client to use our logger\n Log.setLogger(logger);\n try {\n const response = new SigninResponse(params);\n\n const stateStore = new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage });\n\n // retrieve the state we put in storage at the start of oidc auth flow\n const stateString = await stateStore.get(response.state!);\n if (!stateString) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n\n // hydrate the sign in state and create a client\n // the stored sign in state includes oidc configuration we set at the start of the oidc login flow\n const signInState = await SigninState.fromStorageString(stateString);\n const client = new OidcClient({ ...signInState, stateStore });\n\n // validate the code and state, and attempt to swap the code for tokens\n const signinResponse = await client.processSigninResponse(reconstructedUrl.href);\n\n // extra values we stored at the start of the login flow\n // used to complete login in the client\n const userState = signinResponse.userState;\n validateStoredUserState(userState);\n\n // throws when response is invalid\n validateBearerTokenResponse(signinResponse);\n if (signinResponse.id_token) {\n // The token is not yet in the Matrix spec so consider it optional\n // throws when token is invalid\n validateIdToken(\n signinResponse.id_token,\n client.settings.authority,\n client.settings.client_id,\n userState.nonce,\n );\n }\n const normalizedTokenResponse = normalizeBearerTokenResponseTokenType(signinResponse);\n\n return {\n oidcClientSettings: {\n clientId: client.settings.client_id,\n issuer: client.settings.authority,\n },\n tokenResponse: normalizedTokenResponse,\n homeserverUrl: userState.homeserverUrl,\n identityServerUrl: userState.identityServerUrl,\n idTokenClaims: signinResponse.profile,\n };\n } catch (error) {\n logger.error(\"Oidc login failed\", error);\n const errorType = (error as Error).message;\n\n // rethrow errors that we recognise\n if (Object.values(OidcError).includes(errorType as any)) {\n throw error;\n }\n throw new Error(OidcError.CodeExchangeFailed);\n }\n};\n\n/**\n * Response from the OIDC token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenResponse {\n id_token?: string;\n access_token: string;\n token_type: string;\n refresh_token?: string;\n scope?: string;\n expires_in?: number;\n session_state?: string;\n}\n\n/**\n * Error from the OIDC token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenError {\n error: string;\n error_description?: string;\n error_uri?: string;\n session_state?: string;\n}\n\n/**\n * Response from the OIDC device authorization endpoint.\n */\nexport interface DeviceAuthorizationResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n expires_in: number;\n interval?: number;\n}\n\n/**\n * Begin OIDC device authorization flow.\n * @param options - The device authorization parameters.\n * @param options.clientId - the client ID returned from client registration.\n * @param options.scope - the scope to request for authorization.\n * @param options.metadata - the validated OIDC metadata for the Identity Provider.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const startDeviceAuthorization = async ({\n clientId,\n scope,\n metadata,\n}: {\n clientId: string;\n scope: string;\n metadata: ValidatedAuthMetadata;\n}): Promise<DeviceAuthorizationResponse> => {\n const body = new URLSearchParams({ client_id: clientId, scope: scope }).toString();\n\n const url = metadata.device_authorization_endpoint;\n if (!url) {\n throw new Error(\"No device_authorization_endpoint given\");\n }\n\n const response = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body,\n });\n\n return (await response.json()) as DeviceAuthorizationResponse;\n};\n\n/**\n * Polls the OIDC token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param options - The device authorization parameters.\n * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.\n * @param options.metadata - The validated OIDC metadata for the Identity Provider.\n * @param options.clientId - The client ID returned from client registration.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const waitForDeviceAuthorization = async ({\n session,\n metadata,\n clientId,\n}: {\n session: DeviceAuthorizationResponse;\n metadata: ValidatedAuthMetadata;\n clientId: string;\n}): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> => {\n let interval = (session.interval ?? 5) * 1000; // poll interval\n const expiration = Date.now() + session.expires_in * 1000;\n do {\n const body = new URLSearchParams({\n device_code: session.device_code,\n grant_type: OAuthGrantType.DeviceAuthorization,\n client_id: clientId,\n }).toString();\n const response = await fetch(metadata.token_endpoint, {\n method: Method.Post,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n\n if (response.ok) {\n return (await response.json()) as DeviceAccessTokenResponse;\n }\n const errorResponse = (await response.json()) as DeviceAccessTokenError;\n switch (errorResponse.error) {\n case \"authorization_pending\":\n break;\n case \"slow_down\":\n interval += 5000;\n break;\n case \"access_denied\":\n case \"expired_token\":\n return errorResponse;\n }\n await sleep(interval);\n } while (Date.now() < expiration);\n return { error: \"expired\" };\n};\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAEIA,GAAG,EACHC,UAAU,EAEVC,cAAc,EACdC,WAAW,EACXC,oBAAoB,QACjB,gBAAgB;AAEvB,SAASC,MAAM,QAAQ,cAAc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;QAC9CrF,SAAS,EAAEvB;MACf,CAAC,CAAC,CAACM,QAAQ,CAAC,CAAC;MACb,IAAMmC,QAAQ,SAASiD,KAAK,CAAC7E,QAAQ,CAACgG,cAAc,EAAE;QAClDlB,MAAM,EAAErH,MAAM,CAACsH,IAAI;QACnBC,OAAO,EAAE;UAAE,cAAc,EAAE;QAAoC,CAAC;QAChEL;MACJ,CAAC,CAAC;MAEF,IAAI/C,QAAQ,CAACqE,EAAE,EAAE;QACb,aAAcrE,QAAQ,CAACqD,IAAI,CAAC,CAAC;MACjC;MACA,IAAMiB,aAAa,SAAUtE,QAAQ,CAACqD,IAAI,CAAC,CAA4B;MACvE,QAAQiB,aAAa,CAACnC,KAAK;QACvB,KAAK,uBAAuB;UACxB;QACJ,KAAK,WAAW;UACZyB,QAAQ,IAAI,IAAI;UAChB;QACJ,KAAK,eAAe;QACpB,KAAK,eAAe;UAChB,OAAOU,aAAa;MAC5B;MACA,MAAM1I,KAAK,CAACgI,QAAQ,CAAC;IACzB,CAAC,QAAQE,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGF,UAAU;IAChC,OAAO;MAAE1B,KAAK,EAAE;IAAU,CAAC;EAC/B,CAAC;EAAA,gBAxCYoB,0BAA0BA,CAAAgB,GAAA;IAAA,OAAAf,KAAA,CAAA5G,KAAA,OAAAC,SAAA;EAAA;AAAA,GAwCtC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"authorize.js","names":[],"sources":["../../src/oidc/authorize.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type IdTokenClaims,\n Log,\n OidcClient,\n type SigninRequestCreateArgs,\n SigninResponse,\n SigninState,\n WebStorageStateStore,\n} from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { OidcError } from \"./error.ts\";\nimport {\n type BearerTokenResponse,\n type UserState,\n validateBearerTokenResponse,\n type ValidatedAuthMetadata,\n validateIdToken,\n validateStoredUserState,\n} from \"./validate.ts\";\nimport { sha256 } from \"../digest.ts\";\nimport { encodeUnpaddedBase64Url } from \"../base64.ts\";\nimport { OAuthGrantType } from \"./register.ts\";\nimport { sleep } from \"../utils.ts\";\nimport { Method } from \"../http-api/index.ts\";\n\n// reexport for backwards compatibility\nexport type { BearerTokenResponse };\n\n/**\n * Authorization parameters which are used in the authentication request of an OIDC auth code flow.\n *\n * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.\n */\nexport type AuthorizationParams = {\n state: string;\n scope: string;\n redirectUri: string;\n codeVerifier: string;\n nonce: string;\n};\n\n/**\n * @experimental\n * Generate the scope used in authorization request with OIDC OP\n * @returns scope\n */\nexport const generateScope = (deviceId?: string): string => {\n const safeDeviceId = deviceId ?? secureRandomString(10);\n return `openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${safeDeviceId}`;\n};\n\n// https://www.rfc-editor.org/rfc/rfc7636\nconst generateCodeChallenge = async (codeVerifier: string): Promise<string> => {\n if (!globalThis.crypto.subtle) {\n // @TODO(kerrya) should this be allowed? configurable?\n logger.warn(\"A secure context is required to generate code challenge. Using plain text code challenge\");\n return codeVerifier;\n }\n\n const hashBuffer = await sha256(codeVerifier);\n return encodeUnpaddedBase64Url(hashBuffer);\n};\n\n/**\n * Generate authorization params to pass to {@link generateAuthorizationUrl}.\n *\n * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.\n *\n * @param redirectUri - absolute url for OP to redirect to after authorization\n * @returns AuthorizationParams\n */\nexport const generateAuthorizationParams = ({ redirectUri }: { redirectUri: string }): AuthorizationParams => ({\n scope: generateScope(),\n redirectUri,\n state: secureRandomString(8),\n nonce: secureRandomString(8),\n codeVerifier: secureRandomString(64), // https://tools.ietf.org/html/rfc7636#section-4.1 length needs to be 43-128 characters\n});\n\n/**\n * @deprecated use generateOidcAuthorizationUrl\n * Generate a URL to attempt authorization with the OP\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\n * @param authorizationUrl - endpoint to attempt authorization with the OP\n * @param clientId - id of this client as registered with the OP\n * @param authorizationParams - params to be used in the url\n * @returns a Promise with the url as a string\n */\nexport const generateAuthorizationUrl = async (\n authorizationUrl: string,\n clientId: string,\n { scope, redirectUri, state, nonce, codeVerifier }: AuthorizationParams,\n): Promise<string> => {\n const url = new URL(authorizationUrl);\n url.searchParams.append(\"response_mode\", \"query\");\n url.searchParams.append(\"response_type\", \"code\");\n url.searchParams.append(\"redirect_uri\", redirectUri);\n url.searchParams.append(\"client_id\", clientId);\n url.searchParams.append(\"state\", state);\n url.searchParams.append(\"scope\", scope);\n url.searchParams.append(\"nonce\", nonce);\n\n url.searchParams.append(\"code_challenge_method\", \"S256\");\n url.searchParams.append(\"code_challenge\", await generateCodeChallenge(codeVerifier));\n\n return url.toString();\n};\n\n/**\n * @experimental\n * Generate a URL to attempt authorization with the OP\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\n * @param metadata - validated metadata from OP discovery\n * @param clientId - this client's id as registered with the OP\n * @param homeserverUrl - used to establish the session on return from the OP\n * @param identityServerUrl - used to establish the session on return from the OP\n * @param nonce - state\n * @param prompt - indicates to the OP which flow the user should see - eg login or registration\n * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter\n * @param urlState - value to append to the opaque state identifier to uniquely identify the callback\n * @param loginHint - value to send as the `login_hint` to the OP, giving a hint about the login identifier the user might use to log in.\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\n * @param responseMode - value to send as the `response_mode` to the OP, selecting how auth is passed back during redirect.\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\n * @returns a Promise with the url as a string\n */\nexport const generateOidcAuthorizationUrl = async ({\n metadata,\n redirectUri,\n clientId,\n homeserverUrl,\n identityServerUrl,\n nonce,\n prompt,\n urlState,\n loginHint,\n responseMode = \"query\",\n}: {\n clientId: string;\n metadata: ValidatedAuthMetadata;\n homeserverUrl: string;\n identityServerUrl?: string;\n redirectUri: string;\n nonce: string;\n prompt?: string;\n urlState?: string;\n loginHint?: string;\n responseMode?: SigninRequestCreateArgs[\"response_mode\"];\n}): Promise<string> => {\n const scope = generateScope();\n const oidcClient = new OidcClient({\n ...metadata,\n client_id: clientId,\n redirect_uri: redirectUri,\n authority: metadata.issuer,\n response_mode: responseMode,\n response_type: \"code\",\n scope,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n const userState: UserState = { homeserverUrl, nonce, identityServerUrl };\n const request = await oidcClient.createSigninRequest({\n state: userState,\n nonce,\n prompt,\n url_state: urlState,\n login_hint: loginHint,\n });\n\n return request.url;\n};\n\n/**\n * Normalize token_type to use capital case to make consuming the token response easier\n * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: \"bearer\"\n * Later, when used in auth headers it is case sensitive and must be Bearer\n * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\n *\n * @param response - validated token response\n * @returns response with token_type set to 'Bearer'\n */\nconst normalizeBearerTokenResponseTokenType = (response: SigninResponse): BearerTokenResponse =>\n ({\n id_token: response.id_token,\n scope: response.scope,\n expires_at: response.expires_at,\n refresh_token: response.refresh_token,\n access_token: response.access_token,\n token_type: \"Bearer\",\n }) as BearerTokenResponse;\n\n/**\n * @experimental\n * Attempt to exchange authorization code for bearer token.\n *\n * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a\n * request to the Token Endpoint, to obtain the access token, refresh token, etc.\n *\n * @param code - authorization code as returned by OP during authorization\n * @param state - authorization state param as returned by OP during authorization\n * @param responseMode - the response mode used for authentication\n * @returns valid bearer token response\n * @throws An `Error` with `message` set to an entry in {@link OidcError},\n * when the request fails, or the returned token response is invalid.\n */\nexport const completeAuthorizationCodeGrant = async (\n code: string,\n state: string,\n responseMode: SigninRequestCreateArgs[\"response_mode\"] = \"query\",\n): Promise<{\n oidcClientSettings: { clientId: string; issuer: string };\n tokenResponse: BearerTokenResponse;\n homeserverUrl: string;\n idTokenClaims: IdTokenClaims;\n identityServerUrl?: string;\n}> => {\n /**\n * Element Web strips and changes the url on starting the app\n * Use the code and state from query params to rebuild a url\n * so that oidc-client can parse it\n */\n const reconstructedUrl = new URL(window.location.origin);\n\n const params = new URLSearchParams({ code, state });\n if (responseMode === \"query\") {\n reconstructedUrl.search = params.toString();\n } else {\n reconstructedUrl.hash = `#${params.toString()}`;\n }\n\n // set oidc-client to use our logger\n Log.setLogger(logger);\n try {\n const response = new SigninResponse(params);\n\n const stateStore = new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage });\n\n // retrieve the state we put in storage at the start of oidc auth flow\n const stateString = await stateStore.get(response.state!);\n if (!stateString) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n\n // hydrate the sign in state and create a client\n // the stored sign in state includes oidc configuration we set at the start of the oidc login flow\n const signInState = await SigninState.fromStorageString(stateString);\n const client = new OidcClient({ ...signInState, stateStore });\n\n // validate the code and state, and attempt to swap the code for tokens\n const signinResponse = await client.processSigninResponse(reconstructedUrl.href);\n\n // extra values we stored at the start of the login flow\n // used to complete login in the client\n const userState = signinResponse.userState;\n validateStoredUserState(userState);\n\n // throws when response is invalid\n validateBearerTokenResponse(signinResponse);\n if (signinResponse.id_token) {\n // The token is not yet in the Matrix spec so consider it optional\n // throws when token is invalid\n validateIdToken(\n signinResponse.id_token,\n client.settings.authority,\n client.settings.client_id,\n userState.nonce,\n );\n }\n const normalizedTokenResponse = normalizeBearerTokenResponseTokenType(signinResponse);\n\n return {\n oidcClientSettings: {\n clientId: client.settings.client_id,\n issuer: client.settings.authority,\n },\n tokenResponse: normalizedTokenResponse,\n homeserverUrl: userState.homeserverUrl,\n identityServerUrl: userState.identityServerUrl,\n idTokenClaims: signinResponse.profile,\n };\n } catch (error) {\n logger.error(\"Oidc login failed\", error);\n const errorType = (error as Error).message;\n\n // rethrow errors that we recognise\n if (Object.values(OidcError).includes(errorType as any)) {\n throw error;\n }\n throw new Error(OidcError.CodeExchangeFailed);\n }\n};\n\n/**\n * Response from the OIDC token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenResponse {\n id_token?: string;\n access_token: string;\n token_type: string;\n refresh_token?: string;\n scope?: string;\n expires_in?: number;\n session_state?: string;\n}\n\n/**\n * Error from the OIDC token endpoint when exchanging a token for grant_type device_code.\n */\nexport interface DeviceAccessTokenError {\n error: string;\n error_description?: string;\n error_uri?: string;\n session_state?: string;\n}\n\n/**\n * Response from the OIDC device authorization endpoint.\n */\nexport interface DeviceAuthorizationResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n expires_in: number;\n interval?: number;\n}\n\n/**\n * Begin OIDC device authorization flow.\n * @param options - The device authorization parameters.\n * @param options.clientId - the client ID returned from client registration.\n * @param options.scope - the scope to request for authorization.\n * @param options.metadata - the validated OIDC metadata for the Identity Provider.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const startDeviceAuthorization = async ({\n clientId,\n scope,\n metadata,\n}: {\n clientId: string;\n scope: string;\n metadata: ValidatedAuthMetadata;\n}): Promise<DeviceAuthorizationResponse> => {\n const body = new URLSearchParams({ client_id: clientId, scope: scope }).toString();\n\n const url = metadata.device_authorization_endpoint;\n if (!url) {\n throw new Error(\"No device_authorization_endpoint given\");\n }\n\n const response = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body,\n });\n\n return (await response.json()) as DeviceAuthorizationResponse;\n};\n\n/**\n * Polls the OIDC token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param options - The device authorization parameters.\n * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.\n * @param options.metadata - The validated OIDC metadata for the Identity Provider.\n * @param options.clientId - The client ID returned from client registration.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\nexport const waitForDeviceAuthorization = async ({\n session,\n metadata,\n clientId,\n}: {\n session: DeviceAuthorizationResponse;\n metadata: ValidatedAuthMetadata;\n clientId: string;\n}): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> => {\n let interval = (session.interval ?? 5) * 1000; // poll interval\n const expiration = Date.now() + session.expires_in * 1000;\n do {\n const body = new URLSearchParams({\n device_code: session.device_code,\n grant_type: OAuthGrantType.DeviceAuthorization,\n client_id: clientId,\n }).toString();\n const response = await fetch(metadata.token_endpoint, {\n method: Method.Post,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n\n if (response.ok) {\n return (await response.json()) as DeviceAccessTokenResponse;\n }\n const errorResponse = (await response.json()) as DeviceAccessTokenError;\n switch (errorResponse.error) {\n case \"authorization_pending\":\n break;\n case \"slow_down\":\n interval += 5000;\n break;\n case \"access_denied\":\n case \"expired_token\":\n return errorResponse;\n }\n await sleep(interval);\n } while (Date.now() < expiration);\n return { error: \"expired\" };\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAEI,GAAG,EACH,UAAU,EAEV,cAAc,EACd,WAAW,EACX,oBAAoB,QACjB,gBAAgB;AAEvB,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,kBAAkB,QAAQ,oBAAoB;AACvD,SAAS,SAAS,QAAQ,YAAY;AACtC,SAGI,2BAA2B,EAE3B,eAAe,EACf,uBAAuB,QACpB,eAAe;AACtB,SAAS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AAC,CAAC;EAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI;EACzD,GAAG;IACC,MAAM,IAAI,GAAG,IAAI,eAAe,CAAC;MAC7B,WAAW,EAAE,OAAO,CAAC,WAAW;MAChC,UAAU,EAAE,cAAc,CAAC,mBAAmB;MAC9C,SAAS,EAAE;IACf,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;IACb,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,QAAQ,CAAC,cAAc,EAAE;MAClD,MAAM,EAAE,MAAM,CAAC,IAAI;MACnB,OAAO,EAAE;QAAE,cAAc,EAAE;MAAoC,CAAC;MAChE;IACJ,CAAC,CAAC;IAEF,IAAI,QAAQ,CAAC,EAAE,EAAE;MACb,OAAQ,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;IACjC;IACA,MAAM,aAAa,GAAI,MAAM,QAAQ,CAAC,IAAI,CAAC,CAA4B;IACvE,QAAQ,aAAa,CAAC,KAAK;MACvB,KAAK,uBAAuB;QACxB;MACJ,KAAK,WAAW;QACZ,QAAQ,IAAI,IAAI;QAChB;MACJ,KAAK,eAAe;MACpB,KAAK,eAAe;QAChB,OAAO,aAAa;IAC5B;IACA,MAAM,KAAK,CAAC,QAAQ,CAAC;EACzB,CAAC,QAAQ,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,UAAU;EAChC,OAAO;IAAE,KAAK,EAAE;EAAU,CAAC;AAC/B,CAAC","ignoreList":[]}
|
package/lib/oidc/discovery.js
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
|
|
3
|
-
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; }
|
|
4
|
-
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";
|
|
5
2
|
/*
|
|
6
3
|
Copyright 2023 The Matrix.org Foundation C.I.C.
|
|
7
4
|
|
|
@@ -33,20 +30,15 @@ import { Method, timeoutSignal } from "../http-api/index.js";
|
|
|
33
30
|
* @throws when delegated auth config is invalid or unreachable
|
|
34
31
|
* @deprecated in favour of {@link MatrixClient#getAuthMetadata}
|
|
35
32
|
*/
|
|
36
|
-
export
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
signal: timeoutSignal(5000)
|
|
42
|
-
});
|
|
43
|
-
var issuerWellKnown = yield issuerWellKnownResponse.json();
|
|
44
|
-
return validateAuthMetadataAndKeys(issuerWellKnown);
|
|
33
|
+
export const discoverAndValidateOIDCIssuerWellKnown = async issuer => {
|
|
34
|
+
const issuerOpenIdConfigUrl = new URL(".well-known/openid-configuration", issuer);
|
|
35
|
+
const issuerWellKnownResponse = await fetch(issuerOpenIdConfigUrl, {
|
|
36
|
+
method: Method.Get,
|
|
37
|
+
signal: timeoutSignal(5000)
|
|
45
38
|
});
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}();
|
|
39
|
+
const issuerWellKnown = await issuerWellKnownResponse.json();
|
|
40
|
+
return validateAuthMetadataAndKeys(issuerWellKnown);
|
|
41
|
+
};
|
|
50
42
|
|
|
51
43
|
/**
|
|
52
44
|
* @experimental
|
|
@@ -54,25 +46,20 @@ export var discoverAndValidateOIDCIssuerWellKnown = /*#__PURE__*/function () {
|
|
|
54
46
|
* @param authMetadata - the authentication metadata to validate
|
|
55
47
|
* @returns validated authentication metadata and signing keys
|
|
56
48
|
*/
|
|
57
|
-
export
|
|
58
|
-
|
|
59
|
-
var validatedIssuerConfig = validateAuthMetadata(authMetadata);
|
|
49
|
+
export const validateAuthMetadataAndKeys = async authMetadata => {
|
|
50
|
+
const validatedIssuerConfig = validateAuthMetadata(authMetadata);
|
|
60
51
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
});
|
|
69
|
-
var metadataService = new MetadataService(settings);
|
|
70
|
-
return _objectSpread(_objectSpread({}, validatedIssuerConfig), {}, {
|
|
71
|
-
signingKeys: validatedIssuerConfig.jwks_uri ? yield metadataService.getSigningKeys() : null
|
|
72
|
-
});
|
|
52
|
+
// create a temporary settings store, so we can use metadata service for discovery
|
|
53
|
+
const settings = new OidcClientSettingsStore({
|
|
54
|
+
authority: validatedIssuerConfig.issuer,
|
|
55
|
+
metadata: validatedIssuerConfig,
|
|
56
|
+
redirect_uri: "",
|
|
57
|
+
// Not known yet, this is here to make the type checker happy
|
|
58
|
+
client_id: "" // Not known yet, this is here to make the type checker happy
|
|
73
59
|
});
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
60
|
+
const metadataService = new MetadataService(settings);
|
|
61
|
+
return _objectSpread(_objectSpread({}, validatedIssuerConfig), {}, {
|
|
62
|
+
signingKeys: validatedIssuerConfig.jwks_uri ? await metadataService.getSigningKeys() : null
|
|
63
|
+
});
|
|
64
|
+
};
|
|
78
65
|
//# sourceMappingURL=discovery.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discovery.js","names":[
|
|
1
|
+
{"version":3,"file":"discovery.js","names":[],"sources":["../../src/oidc/discovery.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MetadataService, OidcClientSettingsStore } from \"oidc-client-ts\";\n\nimport { validateAuthMetadata } from \"./validate.ts\";\nimport { Method, timeoutSignal } from \"../http-api/index.ts\";\nimport { type OidcClientConfig } from \"./index.ts\";\n\n/**\n * @experimental\n * Discover and validate delegated auth configuration\n * - delegated auth issuer openid-configuration is reachable\n * - delegated auth issuer openid-configuration is configured correctly for us\n * Fetches https://oidc-issuer.example.com/.well-known/openid-configuration and other files linked therein.\n * When successful, validated metadata is returned\n * @param issuer - the OIDC issuer as returned by the /auth_issuer API\n * @returns validated authentication metadata and optionally signing keys\n * @throws when delegated auth config is invalid or unreachable\n * @deprecated in favour of {@link MatrixClient#getAuthMetadata}\n */\nexport const discoverAndValidateOIDCIssuerWellKnown = async (issuer: string): Promise<OidcClientConfig> => {\n const issuerOpenIdConfigUrl = new URL(\".well-known/openid-configuration\", issuer);\n const issuerWellKnownResponse = await fetch(issuerOpenIdConfigUrl, {\n method: Method.Get,\n signal: timeoutSignal(5000),\n });\n const issuerWellKnown = await issuerWellKnownResponse.json();\n return validateAuthMetadataAndKeys(issuerWellKnown);\n};\n\n/**\n * @experimental\n * Validate the authentication metadata and fetch the signing keys from the jwks_uri in the metadata\n * @param authMetadata - the authentication metadata to validate\n * @returns validated authentication metadata and signing keys\n */\nexport const validateAuthMetadataAndKeys = async (authMetadata: unknown): Promise<OidcClientConfig> => {\n const validatedIssuerConfig = validateAuthMetadata(authMetadata);\n\n // create a temporary settings store, so we can use metadata service for discovery\n const settings = new OidcClientSettingsStore({\n authority: validatedIssuerConfig.issuer,\n metadata: validatedIssuerConfig,\n redirect_uri: \"\", // Not known yet, this is here to make the type checker happy\n client_id: \"\", // Not known yet, this is here to make the type checker happy\n });\n const metadataService = new MetadataService(settings);\n\n return {\n ...validatedIssuerConfig,\n signingKeys: validatedIssuerConfig.jwks_uri ? await metadataService.getSigningKeys() : null,\n };\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,eAAe,EAAE,uBAAuB,QAAQ,gBAAgB;AAEzE,SAAS,oBAAoB,QAAQ,eAAe;AACpD,SAAS,MAAM,EAAE,aAAa,QAAQ,sBAAsB;AAG5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,sCAAsC,GAAG,MAAO,MAAc,IAAgC;EACvG,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,kCAAkC,EAAE,MAAM,CAAC;EACjF,MAAM,uBAAuB,GAAG,MAAM,KAAK,CAAC,qBAAqB,EAAE;IAC/D,MAAM,EAAE,MAAM,CAAC,GAAG;IAClB,MAAM,EAAE,aAAa,CAAC,IAAI;EAC9B,CAAC,CAAC;EACF,MAAM,eAAe,GAAG,MAAM,uBAAuB,CAAC,IAAI,CAAC,CAAC;EAC5D,OAAO,2BAA2B,CAAC,eAAe,CAAC;AACvD,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,2BAA2B,GAAG,MAAO,YAAqB,IAAgC;EACnG,MAAM,qBAAqB,GAAG,oBAAoB,CAAC,YAAY,CAAC;;EAEhE;EACA,MAAM,QAAQ,GAAG,IAAI,uBAAuB,CAAC;IACzC,SAAS,EAAE,qBAAqB,CAAC,MAAM;IACvC,QAAQ,EAAE,qBAAqB;IAC/B,YAAY,EAAE,EAAE;IAAE;IAClB,SAAS,EAAE,EAAE,CAAE;EACnB,CAAC,CAAC;EACF,MAAM,eAAe,GAAG,IAAI,eAAe,CAAC,QAAQ,CAAC;EAErD,uCACO,qBAAqB;IACxB,WAAW,EAAE,qBAAqB,CAAC,QAAQ,GAAG,MAAM,eAAe,CAAC,cAAc,CAAC,CAAC,GAAG;EAAI;AAEnG,CAAC","ignoreList":[]}
|
package/lib/oidc/error.js
CHANGED
|
@@ -18,7 +18,7 @@ limitations under the License.
|
|
|
18
18
|
* Errors expected to be encountered during OIDC discovery, client registration, and authentication.
|
|
19
19
|
* Not intended to be displayed directly to the user.
|
|
20
20
|
*/
|
|
21
|
-
export
|
|
21
|
+
export let OidcError = /*#__PURE__*/function (OidcError) {
|
|
22
22
|
OidcError["NotSupported"] = "OIDC authentication not supported";
|
|
23
23
|
OidcError["Misconfigured"] = "OIDC is misconfigured";
|
|
24
24
|
OidcError["General"] = "Something went wrong with OIDC discovery";
|
package/lib/oidc/error.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","names":[
|
|
1
|
+
{"version":3,"file":"error.js","names":[],"sources":["../../src/oidc/error.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Errors expected to be encountered during OIDC discovery, client registration, and authentication.\n * Not intended to be displayed directly to the user.\n */\nexport enum OidcError {\n NotSupported = \"OIDC authentication not supported\",\n Misconfigured = \"OIDC is misconfigured\",\n General = \"Something went wrong with OIDC discovery\",\n OpSupport = \"Configured OIDC OP does not support required functions\",\n DynamicRegistrationNotSupported = \"Dynamic registration not supported\",\n DynamicRegistrationFailed = \"Dynamic registration failed\",\n DynamicRegistrationInvalid = \"Dynamic registration invalid response\",\n CodeExchangeFailed = \"Failed to exchange code for token\",\n InvalidBearerTokenResponse = \"Invalid bearer token response\",\n InvalidIdToken = \"Invalid ID token\",\n MissingOrInvalidStoredState = \"State required to finish logging in is not found in storage.\",\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAY,SAAS,0BAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAT,SAAS;EAAA,OAAT,SAAS;AAAA","ignoreList":[]}
|
package/lib/oidc/index.js
CHANGED
package/lib/oidc/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/oidc/index.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type { SigningKey } from \"oidc-client-ts\";\nimport { type ValidatedAuthMetadata } from \"./validate.ts\";\n\nexport * from \"./authorize.ts\";\nexport * from \"./discovery.ts\";\nexport * from \"./error.ts\";\nexport * from \"./register.ts\";\nexport * from \"./tokenRefresher.ts\";\nexport * from \"./validate.ts\";\n\n/**\n * Validated config for native OIDC authentication, as returned by {@link discoverAndValidateOIDCIssuerWellKnown}.\n * Contains metadata and signing keys from the issuer's well-known (https://oidc-issuer.example.com/.well-known/openid-configuration).\n */\nexport interface OidcClientConfig extends ValidatedAuthMetadata {\n signingKeys: SigningKey[] | null;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,cAAc,gBAAgB;AAC9B,cAAc,gBAAgB;AAC9B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,qBAAqB;AACnC,cAAc,eAAe;;AAE7B;AACA;AACA;AACA;AAHA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/oidc/index.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type { SigningKey } from \"oidc-client-ts\";\nimport { type ValidatedAuthMetadata } from \"./validate.ts\";\n\nexport * from \"./authorize.ts\";\nexport * from \"./discovery.ts\";\nexport * from \"./error.ts\";\nexport * from \"./register.ts\";\nexport * from \"./tokenRefresher.ts\";\nexport * from \"./validate.ts\";\n\n/**\n * Validated config for native OIDC authentication, as returned by {@link discoverAndValidateOIDCIssuerWellKnown}.\n * Contains metadata and signing keys from the issuer's well-known (https://oidc-issuer.example.com/.well-known/openid-configuration).\n */\nexport interface OidcClientConfig extends ValidatedAuthMetadata {\n signingKeys: SigningKey[] | null;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,cAAc,gBAAgB;AAC9B,cAAc,gBAAgB;AAC9B,cAAc,YAAY;AAC1B,cAAc,eAAe;AAC7B,cAAc,qBAAqB;AACnC,cAAc,eAAe;;AAE7B;AACA;AACA;AACA;AAHA;AAAA","ignoreList":[]}
|
package/lib/oidc/register.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
|
|
2
1
|
/*
|
|
3
2
|
Copyright 2023 The Matrix.org Foundation C.I.C.
|
|
4
3
|
|
|
@@ -30,7 +29,7 @@ import { logger } from "../logger.js";
|
|
|
30
29
|
/**
|
|
31
30
|
* The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
|
|
32
31
|
*/
|
|
33
|
-
export
|
|
32
|
+
export let OAuthGrantType = /*#__PURE__*/function (OAuthGrantType) {
|
|
34
33
|
/**
|
|
35
34
|
* See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant
|
|
36
35
|
*/
|
|
@@ -55,14 +54,14 @@ export var OAuthGrantType = /*#__PURE__*/function (OAuthGrantType) {
|
|
|
55
54
|
*
|
|
56
55
|
* @deprecated use `OAuthGrantType.DeviceAuthorization` instead
|
|
57
56
|
*/
|
|
58
|
-
export
|
|
57
|
+
export const DEVICE_CODE_SCOPE = OAuthGrantType.DeviceAuthorization;
|
|
59
58
|
|
|
60
59
|
// Check that URIs have a common base, as per the MSC2966 definition
|
|
61
|
-
|
|
60
|
+
const urlHasCommonBase = (base, urlStr) => {
|
|
62
61
|
if (!urlStr) return false;
|
|
63
|
-
|
|
62
|
+
const url = new URL(urlStr);
|
|
64
63
|
if (url.protocol !== base.protocol) return false;
|
|
65
|
-
if (url.hostname !== base.hostname && !url.hostname.endsWith(
|
|
64
|
+
if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;
|
|
66
65
|
return true;
|
|
67
66
|
};
|
|
68
67
|
|
|
@@ -74,67 +73,62 @@ var urlHasCommonBase = (base, urlStr) => {
|
|
|
74
73
|
* @returns Promise<string> resolved with registered clientId
|
|
75
74
|
* @throws when registration is not supported, on failed request or invalid response
|
|
76
75
|
*/
|
|
77
|
-
export
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
}
|
|
76
|
+
export const registerOidcClient = async (delegatedAuthConfig, clientMetadata) => {
|
|
77
|
+
if (!delegatedAuthConfig.registration_endpoint) {
|
|
78
|
+
throw new Error(OidcError.DynamicRegistrationNotSupported);
|
|
79
|
+
}
|
|
80
|
+
const grantTypes = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];
|
|
81
|
+
if (grantTypes.some(scope => !delegatedAuthConfig.grant_types_supported.includes(scope))) {
|
|
82
|
+
throw new Error(OidcError.DynamicRegistrationNotSupported);
|
|
83
|
+
}
|
|
86
84
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
85
|
+
// ask for device authorization grant if supported
|
|
86
|
+
if (delegatedAuthConfig.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
|
|
87
|
+
grantTypes.push(OAuthGrantType.DeviceAuthorization);
|
|
88
|
+
}
|
|
89
|
+
const commonBase = new URL(clientMetadata.clientUri);
|
|
92
90
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
};
|
|
112
|
-
try {
|
|
113
|
-
var response = yield fetch(delegatedAuthConfig.registration_endpoint, {
|
|
114
|
-
method: Method.Post,
|
|
115
|
-
headers,
|
|
116
|
-
body: JSON.stringify(metadata)
|
|
117
|
-
});
|
|
118
|
-
if (response.status >= 400) {
|
|
119
|
-
throw new Error(OidcError.DynamicRegistrationFailed);
|
|
120
|
-
}
|
|
121
|
-
var body = yield response.json();
|
|
122
|
-
var clientId = body["client_id"];
|
|
123
|
-
if (!clientId || typeof clientId !== "string") {
|
|
124
|
-
throw new Error(OidcError.DynamicRegistrationInvalid);
|
|
125
|
-
}
|
|
126
|
-
return clientId;
|
|
127
|
-
} catch (error) {
|
|
128
|
-
if (Object.values(OidcError).includes(error.message)) {
|
|
129
|
-
throw error;
|
|
130
|
-
} else {
|
|
131
|
-
logger.error("Dynamic registration request failed", error);
|
|
132
|
-
throw new Error(OidcError.DynamicRegistrationFailed);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
});
|
|
136
|
-
return function registerOidcClient(_x, _x2) {
|
|
137
|
-
return _ref.apply(this, arguments);
|
|
91
|
+
// https://openid.net/specs/openid-connect-registration-1_0.html
|
|
92
|
+
const metadata = {
|
|
93
|
+
client_name: clientMetadata.clientName,
|
|
94
|
+
client_uri: clientMetadata.clientUri,
|
|
95
|
+
response_types: ["code"],
|
|
96
|
+
grant_types: grantTypes,
|
|
97
|
+
redirect_uris: clientMetadata.redirectUris,
|
|
98
|
+
id_token_signed_response_alg: "RS256",
|
|
99
|
+
token_endpoint_auth_method: "none",
|
|
100
|
+
application_type: clientMetadata.applicationType,
|
|
101
|
+
contacts: clientMetadata.contacts,
|
|
102
|
+
logo_uri: urlHasCommonBase(commonBase, clientMetadata.logoUri) ? clientMetadata.logoUri : undefined,
|
|
103
|
+
policy_uri: urlHasCommonBase(commonBase, clientMetadata.policyUri) ? clientMetadata.policyUri : undefined,
|
|
104
|
+
tos_uri: urlHasCommonBase(commonBase, clientMetadata.tosUri) ? clientMetadata.tosUri : undefined
|
|
105
|
+
};
|
|
106
|
+
const headers = {
|
|
107
|
+
"Accept": "application/json",
|
|
108
|
+
"Content-Type": "application/json"
|
|
138
109
|
};
|
|
139
|
-
|
|
110
|
+
try {
|
|
111
|
+
const response = await fetch(delegatedAuthConfig.registration_endpoint, {
|
|
112
|
+
method: Method.Post,
|
|
113
|
+
headers,
|
|
114
|
+
body: JSON.stringify(metadata)
|
|
115
|
+
});
|
|
116
|
+
if (response.status >= 400) {
|
|
117
|
+
throw new Error(OidcError.DynamicRegistrationFailed);
|
|
118
|
+
}
|
|
119
|
+
const body = await response.json();
|
|
120
|
+
const clientId = body["client_id"];
|
|
121
|
+
if (!clientId || typeof clientId !== "string") {
|
|
122
|
+
throw new Error(OidcError.DynamicRegistrationInvalid);
|
|
123
|
+
}
|
|
124
|
+
return clientId;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (Object.values(OidcError).includes(error.message)) {
|
|
127
|
+
throw error;
|
|
128
|
+
} else {
|
|
129
|
+
logger.error("Dynamic registration request failed", error);
|
|
130
|
+
throw new Error(OidcError.DynamicRegistrationFailed);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
140
134
|
//# sourceMappingURL=register.js.map
|
package/lib/oidc/register.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.js","names":["OidcError","Method","logger","OAuthGrantType","DEVICE_CODE_SCOPE","DeviceAuthorization","urlHasCommonBase","base","urlStr","url","URL","protocol","hostname","endsWith","concat","registerOidcClient","_ref","_asyncToGenerator","delegatedAuthConfig","clientMetadata","registration_endpoint","Error","DynamicRegistrationNotSupported","grantTypes","AuthorizationCode","RefreshToken","some","scope","grant_types_supported","includes","push","commonBase","clientUri","metadata","client_name","clientName","client_uri","response_types","grant_types","redirect_uris","redirectUris","id_token_signed_response_alg","token_endpoint_auth_method","application_type","applicationType","contacts","logo_uri","logoUri","undefined","policy_uri","policyUri","tos_uri","tosUri","headers","response","fetch","method","Post","body","JSON","stringify","status","DynamicRegistrationFailed","json","clientId","DynamicRegistrationInvalid","error","Object","values","message","_x","_x2","apply","arguments"],"sources":["../../src/oidc/register.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type OidcClientConfig } from \"./index.ts\";\nimport { OidcError } from \"./error.ts\";\nimport { Method } from \"../http-api/index.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type NonEmptyArray } from \"../@types/common.ts\";\n\n/**\n * Client metadata passed to registration endpoint\n */\nexport type OidcRegistrationClientMetadata = {\n clientName: OidcRegistrationRequestBody[\"client_name\"];\n clientUri: OidcRegistrationRequestBody[\"client_uri\"];\n logoUri?: OidcRegistrationRequestBody[\"logo_uri\"];\n applicationType: OidcRegistrationRequestBody[\"application_type\"];\n redirectUris: OidcRegistrationRequestBody[\"redirect_uris\"];\n contacts: OidcRegistrationRequestBody[\"contacts\"];\n tosUri: OidcRegistrationRequestBody[\"tos_uri\"];\n policyUri: OidcRegistrationRequestBody[\"policy_uri\"];\n};\n\n/**\n * Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966\n */\ninterface OidcRegistrationRequestBody {\n client_name?: string;\n client_uri: string;\n logo_uri?: string;\n contacts?: string[];\n tos_uri?: string;\n policy_uri?: string;\n redirect_uris?: NonEmptyArray<string>;\n response_types?: NonEmptyArray<string>;\n grant_types?: NonEmptyArray<string>;\n id_token_signed_response_alg?: string;\n token_endpoint_auth_method: string;\n application_type: \"web\" | \"native\";\n}\n\n/**\n * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types\n */\nexport enum OAuthGrantType {\n /**\n * See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant\n */\n AuthorizationCode = \"authorization_code\",\n /**\n * https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant\n */\n RefreshToken = \"refresh_token\",\n /**\n * The OAuth 2.0 Device Authorization Grant type identifier as per\n * https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from\n * [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).\n *\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\n DeviceAuthorization = \"urn:ietf:params:oauth:grant-type:device_code\",\n}\n\n/**\n * The name \"scope\" is a misnomer here as it is actually a \"grant type\".\n *\n * @deprecated use `OAuthGrantType.DeviceAuthorization` instead\n */\nexport const DEVICE_CODE_SCOPE: string = OAuthGrantType.DeviceAuthorization;\n\n// Check that URIs have a common base, as per the MSC2966 definition\nconst urlHasCommonBase = (base: URL, urlStr?: string): boolean => {\n if (!urlStr) return false;\n const url = new URL(urlStr);\n if (url.protocol !== base.protocol) return false;\n if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;\n return true;\n};\n\n/**\n * Attempts dynamic registration against the configured registration endpoint.\n * Will ignore any URIs that do not use client_uri as a common base as per the spec.\n * @param delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}\n * @param clientMetadata - The metadata for the client which to register\n * @returns Promise<string> resolved with registered clientId\n * @throws when registration is not supported, on failed request or invalid response\n */\nexport const registerOidcClient = async (\n delegatedAuthConfig: OidcClientConfig,\n clientMetadata: OidcRegistrationClientMetadata,\n): Promise<string> => {\n if (!delegatedAuthConfig.registration_endpoint) {\n throw new Error(OidcError.DynamicRegistrationNotSupported);\n }\n\n const grantTypes: NonEmptyArray<string> = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];\n if (grantTypes.some((scope) => !delegatedAuthConfig.grant_types_supported.includes(scope))) {\n throw new Error(OidcError.DynamicRegistrationNotSupported);\n }\n\n // ask for device authorization grant if supported\n if (delegatedAuthConfig.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n grantTypes.push(OAuthGrantType.DeviceAuthorization);\n }\n\n const commonBase = new URL(clientMetadata.clientUri);\n\n // https://openid.net/specs/openid-connect-registration-1_0.html\n const metadata: OidcRegistrationRequestBody = {\n client_name: clientMetadata.clientName,\n client_uri: clientMetadata.clientUri,\n response_types: [\"code\"],\n grant_types: grantTypes,\n redirect_uris: clientMetadata.redirectUris,\n id_token_signed_response_alg: \"RS256\",\n token_endpoint_auth_method: \"none\",\n application_type: clientMetadata.applicationType,\n contacts: clientMetadata.contacts,\n logo_uri: urlHasCommonBase(commonBase, clientMetadata.logoUri) ? clientMetadata.logoUri : undefined,\n policy_uri: urlHasCommonBase(commonBase, clientMetadata.policyUri) ? clientMetadata.policyUri : undefined,\n tos_uri: urlHasCommonBase(commonBase, clientMetadata.tosUri) ? clientMetadata.tosUri : undefined,\n };\n\n const headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n };\n\n try {\n const response = await fetch(delegatedAuthConfig.registration_endpoint, {\n method: Method.Post,\n headers,\n body: JSON.stringify(metadata),\n });\n\n if (response.status >= 400) {\n throw new Error(OidcError.DynamicRegistrationFailed);\n }\n\n const body = await response.json();\n const clientId = body[\"client_id\"];\n if (!clientId || typeof clientId !== \"string\") {\n throw new Error(OidcError.DynamicRegistrationInvalid);\n }\n\n return clientId;\n } catch (error) {\n if (Object.values(OidcError).includes((error as Error).message as OidcError)) {\n throw error;\n } else {\n logger.error(\"Dynamic registration request failed\", error);\n throw new Error(OidcError.DynamicRegistrationFailed);\n }\n }\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,SAAS,QAAQ,YAAY;AACtC,SAASC,MAAM,QAAQ,sBAAsB;AAC7C,SAASC,MAAM,QAAQ,cAAc;;AAGrC;AACA;AACA;;AAYA;AACA;AACA;;AAgBA;AACA;AACA;AACA,WAAYC,cAAc,0BAAdA,cAAc;EACtB;AACJ;AACA;EAHYA,cAAc;EAKtB;AACJ;AACA;EAPYA,cAAc;EAStB;AACJ;AACA;AACA;AACA;AACA;AACA;EAfYA,cAAc;EAAA,OAAdA,cAAc;AAAA;;AAmB1B;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,iBAAyB,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AAQ,GAAGN,IAAI,CAAC,WAAW,CAAC;MAClC,IAAI,CAACM,QAAQ,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;QAC3C,MAAM,IAAI3C,KAAK,CAACrB,SAAS,CAACiE,0BAA0B,CAAC;MACzD;MAEA,OAAOD,QAAQ;IACnB,CAAC,CAAC,OAAOE,KAAK,EAAE;MACZ,IAAIC,MAAM,CAACC,MAAM,CAACpE,SAAS,CAAC,CAAC6B,QAAQ,CAAEqC,KAAK,CAAWG,OAAoB,CAAC,EAAE;QAC1E,MAAMH,KAAK;MACf,CAAC,MAAM;QACHhE,MAAM,CAACgE,KAAK,CAAC,qCAAqC,EAAEA,KAAK,CAAC;QAC1D,MAAM,IAAI7C,KAAK,CAACrB,SAAS,CAAC8D,yBAAyB,CAAC;MACxD;IACJ;EACJ,CAAC;EAAA,gBAnEY/C,kBAAkBA,CAAAuD,EAAA,EAAAC,GAAA;IAAA,OAAAvD,IAAA,CAAAwD,KAAA,OAAAC,SAAA;EAAA;AAAA,GAmE9B","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"register.js","names":[],"sources":["../../src/oidc/register.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type OidcClientConfig } from \"./index.ts\";\nimport { OidcError } from \"./error.ts\";\nimport { Method } from \"../http-api/index.ts\";\nimport { logger } from \"../logger.ts\";\nimport { type NonEmptyArray } from \"../@types/common.ts\";\n\n/**\n * Client metadata passed to registration endpoint\n */\nexport type OidcRegistrationClientMetadata = {\n clientName: OidcRegistrationRequestBody[\"client_name\"];\n clientUri: OidcRegistrationRequestBody[\"client_uri\"];\n logoUri?: OidcRegistrationRequestBody[\"logo_uri\"];\n applicationType: OidcRegistrationRequestBody[\"application_type\"];\n redirectUris: OidcRegistrationRequestBody[\"redirect_uris\"];\n contacts: OidcRegistrationRequestBody[\"contacts\"];\n tosUri: OidcRegistrationRequestBody[\"tos_uri\"];\n policyUri: OidcRegistrationRequestBody[\"policy_uri\"];\n};\n\n/**\n * Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966\n */\ninterface OidcRegistrationRequestBody {\n client_name?: string;\n client_uri: string;\n logo_uri?: string;\n contacts?: string[];\n tos_uri?: string;\n policy_uri?: string;\n redirect_uris?: NonEmptyArray<string>;\n response_types?: NonEmptyArray<string>;\n grant_types?: NonEmptyArray<string>;\n id_token_signed_response_alg?: string;\n token_endpoint_auth_method: string;\n application_type: \"web\" | \"native\";\n}\n\n/**\n * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types\n */\nexport enum OAuthGrantType {\n /**\n * See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant\n */\n AuthorizationCode = \"authorization_code\",\n /**\n * https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant\n */\n RefreshToken = \"refresh_token\",\n /**\n * The OAuth 2.0 Device Authorization Grant type identifier as per\n * https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from\n * [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).\n *\n * @experimental Note that this is UNSTABLE and may have breaking changes without notice.\n */\n DeviceAuthorization = \"urn:ietf:params:oauth:grant-type:device_code\",\n}\n\n/**\n * The name \"scope\" is a misnomer here as it is actually a \"grant type\".\n *\n * @deprecated use `OAuthGrantType.DeviceAuthorization` instead\n */\nexport const DEVICE_CODE_SCOPE: string = OAuthGrantType.DeviceAuthorization;\n\n// Check that URIs have a common base, as per the MSC2966 definition\nconst urlHasCommonBase = (base: URL, urlStr?: string): boolean => {\n if (!urlStr) return false;\n const url = new URL(urlStr);\n if (url.protocol !== base.protocol) return false;\n if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;\n return true;\n};\n\n/**\n * Attempts dynamic registration against the configured registration endpoint.\n * Will ignore any URIs that do not use client_uri as a common base as per the spec.\n * @param delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}\n * @param clientMetadata - The metadata for the client which to register\n * @returns Promise<string> resolved with registered clientId\n * @throws when registration is not supported, on failed request or invalid response\n */\nexport const registerOidcClient = async (\n delegatedAuthConfig: OidcClientConfig,\n clientMetadata: OidcRegistrationClientMetadata,\n): Promise<string> => {\n if (!delegatedAuthConfig.registration_endpoint) {\n throw new Error(OidcError.DynamicRegistrationNotSupported);\n }\n\n const grantTypes: NonEmptyArray<string> = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];\n if (grantTypes.some((scope) => !delegatedAuthConfig.grant_types_supported.includes(scope))) {\n throw new Error(OidcError.DynamicRegistrationNotSupported);\n }\n\n // ask for device authorization grant if supported\n if (delegatedAuthConfig.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n grantTypes.push(OAuthGrantType.DeviceAuthorization);\n }\n\n const commonBase = new URL(clientMetadata.clientUri);\n\n // https://openid.net/specs/openid-connect-registration-1_0.html\n const metadata: OidcRegistrationRequestBody = {\n client_name: clientMetadata.clientName,\n client_uri: clientMetadata.clientUri,\n response_types: [\"code\"],\n grant_types: grantTypes,\n redirect_uris: clientMetadata.redirectUris,\n id_token_signed_response_alg: \"RS256\",\n token_endpoint_auth_method: \"none\",\n application_type: clientMetadata.applicationType,\n contacts: clientMetadata.contacts,\n logo_uri: urlHasCommonBase(commonBase, clientMetadata.logoUri) ? clientMetadata.logoUri : undefined,\n policy_uri: urlHasCommonBase(commonBase, clientMetadata.policyUri) ? clientMetadata.policyUri : undefined,\n tos_uri: urlHasCommonBase(commonBase, clientMetadata.tosUri) ? clientMetadata.tosUri : undefined,\n };\n\n const headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n };\n\n try {\n const response = await fetch(delegatedAuthConfig.registration_endpoint, {\n method: Method.Post,\n headers,\n body: JSON.stringify(metadata),\n });\n\n if (response.status >= 400) {\n throw new Error(OidcError.DynamicRegistrationFailed);\n }\n\n const body = await response.json();\n const clientId = body[\"client_id\"];\n if (!clientId || typeof clientId !== \"string\") {\n throw new Error(OidcError.DynamicRegistrationInvalid);\n }\n\n return clientId;\n } catch (error) {\n if (Object.values(OidcError).includes((error as Error).message as OidcError)) {\n throw error;\n } else {\n logger.error(\"Dynamic registration request failed\", error);\n throw new Error(OidcError.DynamicRegistrationFailed);\n }\n }\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAAS,SAAS,QAAQ,YAAY;AACtC,SAAS,MAAM,QAAQ,sBAAsB;AAC7C,SAAS,MAAM,QAAQ,cAAc;;AAGrC;AACA;AACA;;AAYA;AACA;AACA;;AAgBA;AACA;AACA;AACA,WAAY,cAAc,0BAAd,cAAc;EACtB;AACJ;AACA;EAHY,cAAc;EAKtB;AACJ;AACA;EAPY,cAAc;EAStB;AACJ;AACA;AACA;AACA;AACA;AACA;EAfY,cAAc;EAAA,OAAd,cAAc;AAAA;;AAmB1B;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,iBAAyB,GAAG,cAAc,CAAC,mBAAmB;;AAE3E;AACA,MAAM,gBAAgB,GAAG,CAAC,IAAS,EAAE,MAAe,KAAc;EAC9D,IAAI,CAAC,MAAM,EAAE,OAAO,KAAK;EACzB,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC;EAC3B,IAAI,GAAG,CAAC,QAAQ,KAAK,IAAI,CAAC,QAAQ,EAAE,OAAO,KAAK;EAChD,IAAI,GAAG,CAAC,QAAQ,KAAK,IAAI,CAAC,QAAQ,IAAI,CAAC,GAA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