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.
Files changed (458) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -1
  3. package/lib/@types/AESEncryptedSecretStoragePayload.js +3 -1
  4. package/lib/@types/IIdentityServerProvider.js +3 -1
  5. package/lib/@types/PushRules.js +7 -7
  6. package/lib/@types/PushRules.js.map +1 -1
  7. package/lib/@types/auth.js +4 -4
  8. package/lib/@types/auth.js.map +1 -1
  9. package/lib/@types/beacon.js +2 -2
  10. package/lib/@types/beacon.js.map +1 -1
  11. package/lib/@types/common.js +3 -1
  12. package/lib/@types/crypto.js +3 -1
  13. package/lib/@types/event.js +20 -20
  14. package/lib/@types/event.js.map +1 -1
  15. package/lib/@types/events.js +3 -1
  16. package/lib/@types/extensible_events.js +6 -6
  17. package/lib/@types/extensible_events.js.map +1 -1
  18. package/lib/@types/global.d.js.map +1 -1
  19. package/lib/@types/json.js +3 -1
  20. package/lib/@types/local_notifications.js +3 -1
  21. package/lib/@types/location.js +4 -4
  22. package/lib/@types/location.js.map +1 -1
  23. package/lib/@types/matrix-sdk-crypto-wasm.d.js +3 -1
  24. package/lib/@types/media.js +3 -1
  25. package/lib/@types/membership.js +1 -1
  26. package/lib/@types/membership.js.map +1 -1
  27. package/lib/@types/partials.js +6 -6
  28. package/lib/@types/partials.js.map +1 -1
  29. package/lib/@types/polls.js +5 -5
  30. package/lib/@types/polls.js.map +1 -1
  31. package/lib/@types/read_receipts.js +2 -2
  32. package/lib/@types/read_receipts.js.map +1 -1
  33. package/lib/@types/registration.js +3 -1
  34. package/lib/@types/requests.js +1 -1
  35. package/lib/@types/requests.js.map +1 -1
  36. package/lib/@types/retention.js +1 -1
  37. package/lib/@types/retention.js.map +1 -1
  38. package/lib/@types/search.js +1 -1
  39. package/lib/@types/search.js.map +1 -1
  40. package/lib/@types/signed.js +3 -1
  41. package/lib/@types/spaces.js +3 -1
  42. package/lib/@types/state_events.js +3 -1
  43. package/lib/@types/synapse.js +3 -1
  44. package/lib/@types/sync.js +1 -1
  45. package/lib/@types/sync.js.map +1 -1
  46. package/lib/@types/threepids.js +1 -1
  47. package/lib/@types/threepids.js.map +1 -1
  48. package/lib/@types/topic.js +1 -1
  49. package/lib/@types/topic.js.map +1 -1
  50. package/lib/@types/uia.js +3 -1
  51. package/lib/NamespacedValue.js +8 -8
  52. package/lib/NamespacedValue.js.map +1 -1
  53. package/lib/ReEmitter.js +9 -16
  54. package/lib/ReEmitter.js.map +1 -1
  55. package/lib/ToDeviceMessageQueue.js +49 -57
  56. package/lib/ToDeviceMessageQueue.js.map +1 -1
  57. package/lib/autodiscovery.js +232 -247
  58. package/lib/autodiscovery.js.map +1 -1
  59. package/lib/base64.js +1 -1
  60. package/lib/base64.js.map +1 -1
  61. package/lib/browser-index.d.ts +2 -2
  62. package/lib/browser-index.d.ts.map +1 -1
  63. package/lib/browser-index.js +5 -5
  64. package/lib/browser-index.js.map +1 -1
  65. package/lib/capabilityPoller.js +19 -22
  66. package/lib/capabilityPoller.js.map +1 -1
  67. package/lib/client.d.ts +2 -8
  68. package/lib/client.d.ts.map +1 -1
  69. package/lib/client.js +2043 -2487
  70. package/lib/client.js.map +1 -1
  71. package/lib/common-crypto/CryptoBackend.js +2 -2
  72. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  73. package/lib/common-crypto/key-passphrase.js.map +1 -1
  74. package/lib/content-helpers.js +43 -48
  75. package/lib/content-helpers.js.map +1 -1
  76. package/lib/content-repo.js +14 -24
  77. package/lib/content-repo.js.map +1 -1
  78. package/lib/crypto/store/base.js +6 -6
  79. package/lib/crypto/store/base.js.map +1 -1
  80. package/lib/crypto/store/indexeddb-crypto-store-backend.js +190 -238
  81. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  82. package/lib/crypto/store/indexeddb-crypto-store.js +25 -30
  83. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  84. package/lib/crypto/store/localStorage-crypto-store.js +113 -145
  85. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  86. package/lib/crypto/store/memory-crypto-store.js +74 -105
  87. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  88. package/lib/crypto-api/CryptoEvent.js +1 -1
  89. package/lib/crypto-api/CryptoEvent.js.map +1 -1
  90. package/lib/crypto-api/CryptoEventHandlerMap.js +3 -1
  91. package/lib/crypto-api/index.d.ts +15 -6
  92. package/lib/crypto-api/index.d.ts.map +1 -1
  93. package/lib/crypto-api/index.js +22 -22
  94. package/lib/crypto-api/index.js.map +1 -1
  95. package/lib/crypto-api/key-passphrase.js +15 -23
  96. package/lib/crypto-api/key-passphrase.js.map +1 -1
  97. package/lib/crypto-api/keybackup.js +3 -1
  98. package/lib/crypto-api/recovery-key.js +11 -12
  99. package/lib/crypto-api/recovery-key.js.map +1 -1
  100. package/lib/crypto-api/verification.js +3 -3
  101. package/lib/crypto-api/verification.js.map +1 -1
  102. package/lib/digest.js +7 -14
  103. package/lib/digest.js.map +1 -1
  104. package/lib/embedded.d.ts.map +1 -1
  105. package/lib/embedded.js +380 -505
  106. package/lib/embedded.js.map +1 -1
  107. package/lib/errors.js +2 -2
  108. package/lib/errors.js.map +1 -1
  109. package/lib/event-mapper.js +10 -12
  110. package/lib/event-mapper.js.map +1 -1
  111. package/lib/extensible_events_v1/ExtensibleEvent.js.map +1 -1
  112. package/lib/extensible_events_v1/InvalidEventError.js.map +1 -1
  113. package/lib/extensible_events_v1/MessageEvent.js +11 -13
  114. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  115. package/lib/extensible_events_v1/PollEndEvent.js +3 -4
  116. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  117. package/lib/extensible_events_v1/PollResponseEvent.js +5 -6
  118. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  119. package/lib/extensible_events_v1/PollStartEvent.js +8 -10
  120. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  121. package/lib/extensible_events_v1/utilities.js.map +1 -1
  122. package/lib/feature.js +18 -31
  123. package/lib/feature.js.map +1 -1
  124. package/lib/filter-component.d.ts.map +1 -1
  125. package/lib/filter-component.js +20 -26
  126. package/lib/filter-component.js.map +1 -1
  127. package/lib/filter.js +14 -17
  128. package/lib/filter.js.map +1 -1
  129. package/lib/http-api/errors.js +28 -43
  130. package/lib/http-api/errors.js.map +1 -1
  131. package/lib/http-api/fetch.js +141 -159
  132. package/lib/http-api/fetch.js.map +1 -1
  133. package/lib/http-api/index.js +17 -20
  134. package/lib/http-api/index.js.map +1 -1
  135. package/lib/http-api/interface.js +1 -1
  136. package/lib/http-api/interface.js.map +1 -1
  137. package/lib/http-api/method.js +1 -1
  138. package/lib/http-api/method.js.map +1 -1
  139. package/lib/http-api/prefix.js +3 -3
  140. package/lib/http-api/prefix.js.map +1 -1
  141. package/lib/http-api/refresh.js +74 -94
  142. package/lib/http-api/refresh.js.map +1 -1
  143. package/lib/http-api/utils.d.ts +1 -1
  144. package/lib/http-api/utils.d.ts.map +1 -1
  145. package/lib/http-api/utils.js +34 -42
  146. package/lib/http-api/utils.js.map +1 -1
  147. package/lib/index.js.map +1 -1
  148. package/lib/indexeddb-helpers.js +3 -3
  149. package/lib/indexeddb-helpers.js.map +1 -1
  150. package/lib/indexeddb-worker.js.map +1 -1
  151. package/lib/interactive-auth.d.ts +5 -5
  152. package/lib/interactive-auth.d.ts.map +1 -1
  153. package/lib/interactive-auth.js +172 -204
  154. package/lib/interactive-auth.js.map +1 -1
  155. package/lib/logger.js +21 -57
  156. package/lib/logger.js.map +1 -1
  157. package/lib/matrix.js +7 -11
  158. package/lib/matrix.js.map +1 -1
  159. package/lib/matrixrtc/CallMembership.js +80 -74
  160. package/lib/matrixrtc/CallMembership.js.map +1 -1
  161. package/lib/matrixrtc/EncryptionManager.js +1 -1
  162. package/lib/matrixrtc/EncryptionManager.js.map +1 -1
  163. package/lib/matrixrtc/IKeyTransport.js +1 -1
  164. package/lib/matrixrtc/IKeyTransport.js.map +1 -1
  165. package/lib/matrixrtc/IMembershipManager.js +1 -1
  166. package/lib/matrixrtc/IMembershipManager.js.map +1 -1
  167. package/lib/matrixrtc/LivekitTransport.d.ts +1 -1
  168. package/lib/matrixrtc/LivekitTransport.js +4 -4
  169. package/lib/matrixrtc/LivekitTransport.js.map +1 -1
  170. package/lib/matrixrtc/MatrixRTCSession.js +137 -187
  171. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  172. package/lib/matrixrtc/MatrixRTCSessionManager.js +36 -41
  173. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  174. package/lib/matrixrtc/MembershipManager.js +332 -378
  175. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  176. package/lib/matrixrtc/MembershipManagerActionScheduler.js +54 -63
  177. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  178. package/lib/matrixrtc/RTCEncryptionManager.js +119 -143
  179. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  180. package/lib/matrixrtc/ToDeviceKeyTransport.js +53 -58
  181. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  182. package/lib/matrixrtc/index.js.map +1 -1
  183. package/lib/matrixrtc/membershipData/common.js +1 -1
  184. package/lib/matrixrtc/membershipData/common.js.map +1 -1
  185. package/lib/matrixrtc/membershipData/index.js.map +1 -1
  186. package/lib/matrixrtc/membershipData/rtc.js +15 -23
  187. package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
  188. package/lib/matrixrtc/membershipData/session.js +4 -5
  189. package/lib/matrixrtc/membershipData/session.js.map +1 -1
  190. package/lib/matrixrtc/types.js +4 -6
  191. package/lib/matrixrtc/types.js.map +1 -1
  192. package/lib/matrixrtc/utils.js +4 -11
  193. package/lib/matrixrtc/utils.js.map +1 -1
  194. package/lib/models/MSC3089Branch.js +91 -116
  195. package/lib/models/MSC3089Branch.js.map +1 -1
  196. package/lib/models/MSC3089TreeSpace.js +209 -245
  197. package/lib/models/MSC3089TreeSpace.js.map +1 -1
  198. package/lib/models/ToDeviceMessage.js +3 -1
  199. package/lib/models/beacon.js +14 -13
  200. package/lib/models/beacon.js.map +1 -1
  201. package/lib/models/compare-event-ordering.js +13 -13
  202. package/lib/models/compare-event-ordering.js.map +1 -1
  203. package/lib/models/device.js +3 -3
  204. package/lib/models/device.js.map +1 -1
  205. package/lib/models/event-context.js +5 -8
  206. package/lib/models/event-context.js.map +1 -1
  207. package/lib/models/event-status.js +1 -1
  208. package/lib/models/event-status.js.map +1 -1
  209. package/lib/models/event-timeline-set.js +88 -94
  210. package/lib/models/event-timeline-set.js.map +1 -1
  211. package/lib/models/event-timeline.js +28 -30
  212. package/lib/models/event-timeline.js.map +1 -1
  213. package/lib/models/event.js +182 -226
  214. package/lib/models/event.js.map +1 -1
  215. package/lib/models/invites-ignorer-types.js +4 -4
  216. package/lib/models/invites-ignorer-types.js.map +1 -1
  217. package/lib/models/invites-ignorer.js +159 -179
  218. package/lib/models/invites-ignorer.js.map +1 -1
  219. package/lib/models/poll.js +71 -81
  220. package/lib/models/poll.js.map +1 -1
  221. package/lib/models/profile-keys.js +2 -2
  222. package/lib/models/profile-keys.js.map +1 -1
  223. package/lib/models/read-receipt.js +40 -56
  224. package/lib/models/read-receipt.js.map +1 -1
  225. package/lib/models/related-relations.js.map +1 -1
  226. package/lib/models/relations-container.js +22 -23
  227. package/lib/models/relations-container.js.map +1 -1
  228. package/lib/models/relations.js +133 -159
  229. package/lib/models/relations.js.map +1 -1
  230. package/lib/models/room-member.js +24 -29
  231. package/lib/models/room-member.js.map +1 -1
  232. package/lib/models/room-receipts.js +29 -43
  233. package/lib/models/room-receipts.js.map +1 -1
  234. package/lib/models/room-retention.js +74 -83
  235. package/lib/models/room-retention.js.map +1 -1
  236. package/lib/models/room-state.js +143 -172
  237. package/lib/models/room-state.js.map +1 -1
  238. package/lib/models/room-sticky-events.d.ts +1 -0
  239. package/lib/models/room-sticky-events.d.ts.map +1 -1
  240. package/lib/models/room-sticky-events.js +45 -65
  241. package/lib/models/room-sticky-events.js.map +1 -1
  242. package/lib/models/room-summary.js.map +1 -1
  243. package/lib/models/room.d.ts.map +1 -1
  244. package/lib/models/room.js +765 -909
  245. package/lib/models/room.js.map +1 -1
  246. package/lib/models/search-result.js +5 -5
  247. package/lib/models/search-result.js.map +1 -1
  248. package/lib/models/thread.js +225 -285
  249. package/lib/models/thread.js.map +1 -1
  250. package/lib/models/typed-event-emitter.js +7 -18
  251. package/lib/models/typed-event-emitter.js.map +1 -1
  252. package/lib/models/user.js +8 -8
  253. package/lib/models/user.js.map +1 -1
  254. package/lib/oidc/authorize.js +208 -241
  255. package/lib/oidc/authorize.js.map +1 -1
  256. package/lib/oidc/discovery.js +23 -36
  257. package/lib/oidc/discovery.js.map +1 -1
  258. package/lib/oidc/error.js +1 -1
  259. package/lib/oidc/error.js.map +1 -1
  260. package/lib/oidc/index.js +1 -0
  261. package/lib/oidc/index.js.map +1 -1
  262. package/lib/oidc/register.js +60 -66
  263. package/lib/oidc/register.js.map +1 -1
  264. package/lib/oidc/tokenRefresher.js +77 -91
  265. package/lib/oidc/tokenRefresher.js.map +1 -1
  266. package/lib/oidc/validate.js +18 -18
  267. package/lib/oidc/validate.js.map +1 -1
  268. package/lib/pushprocessor.js +71 -82
  269. package/lib/pushprocessor.js.map +1 -1
  270. package/lib/randomstring.js +9 -9
  271. package/lib/randomstring.js.map +1 -1
  272. package/lib/realtime-callbacks.js +25 -28
  273. package/lib/realtime-callbacks.js.map +1 -1
  274. package/lib/receipt-accumulator.d.ts +2 -0
  275. package/lib/receipt-accumulator.d.ts.map +1 -1
  276. package/lib/receipt-accumulator.js +14 -22
  277. package/lib/receipt-accumulator.js.map +1 -1
  278. package/lib/rendezvous/MSC4108SignInWithQR.js +271 -302
  279. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  280. package/lib/rendezvous/RendezvousChannel.js +3 -1
  281. package/lib/rendezvous/RendezvousCode.js +3 -1
  282. package/lib/rendezvous/RendezvousError.js.map +1 -1
  283. package/lib/rendezvous/RendezvousFailureReason.js +2 -2
  284. package/lib/rendezvous/RendezvousFailureReason.js.map +1 -1
  285. package/lib/rendezvous/RendezvousIntent.js +1 -1
  286. package/lib/rendezvous/RendezvousIntent.js.map +1 -1
  287. package/lib/rendezvous/RendezvousTransport.js +3 -1
  288. package/lib/rendezvous/channels/MSC4108SecureChannel.js +123 -147
  289. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  290. package/lib/rendezvous/index.js +44 -69
  291. package/lib/rendezvous/index.js.map +1 -1
  292. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +1 -1
  293. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +134 -152
  294. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  295. package/lib/retentionPolicy.js +6 -9
  296. package/lib/retentionPolicy.js.map +1 -1
  297. package/lib/room-hierarchy.js +52 -60
  298. package/lib/room-hierarchy.js.map +1 -1
  299. package/lib/rust-crypto/CrossSigningIdentity.js +94 -104
  300. package/lib/rust-crypto/CrossSigningIdentity.js.map +1 -1
  301. package/lib/rust-crypto/DehydratedDeviceManager.js +157 -190
  302. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  303. package/lib/rust-crypto/KeyClaimManager.js +18 -22
  304. package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
  305. package/lib/rust-crypto/OutgoingRequestProcessor.js +109 -139
  306. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  307. package/lib/rust-crypto/OutgoingRequestsManager.js +66 -80
  308. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  309. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +1 -1
  310. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +196 -224
  311. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  312. package/lib/rust-crypto/RoomEncryptor.js +127 -143
  313. package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
  314. package/lib/rust-crypto/backup.js +453 -549
  315. package/lib/rust-crypto/backup.js.map +1 -1
  316. package/lib/rust-crypto/constants.js +1 -1
  317. package/lib/rust-crypto/constants.js.map +1 -1
  318. package/lib/rust-crypto/device-converter.js +15 -28
  319. package/lib/rust-crypto/device-converter.js.map +1 -1
  320. package/lib/rust-crypto/index.js +103 -116
  321. package/lib/rust-crypto/index.js.map +1 -1
  322. package/lib/rust-crypto/libolm_migration.js +303 -365
  323. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  324. package/lib/rust-crypto/rust-crypto.d.ts +5 -1
  325. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  326. package/lib/rust-crypto/rust-crypto.js +1067 -1332
  327. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  328. package/lib/rust-crypto/secret-storage.js +12 -25
  329. package/lib/rust-crypto/secret-storage.js.map +1 -1
  330. package/lib/rust-crypto/verification.js +137 -189
  331. package/lib/rust-crypto/verification.js.map +1 -1
  332. package/lib/scheduler.js +44 -19
  333. package/lib/scheduler.js.map +1 -1
  334. package/lib/secret-storage.js +179 -213
  335. package/lib/secret-storage.js.map +1 -1
  336. package/lib/serverCapabilities.js +6 -9
  337. package/lib/serverCapabilities.js.map +1 -1
  338. package/lib/service-types.js +1 -1
  339. package/lib/service-types.js.map +1 -1
  340. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  341. package/lib/sliding-sync-sdk.js +368 -424
  342. package/lib/sliding-sync-sdk.js.map +1 -1
  343. package/lib/sliding-sync.js +135 -171
  344. package/lib/sliding-sync.js.map +1 -1
  345. package/lib/store/index.js +3 -1
  346. package/lib/store/indexeddb-backend.js +3 -1
  347. package/lib/store/indexeddb-local-backend.js +194 -253
  348. package/lib/store/indexeddb-local-backend.js.map +1 -1
  349. package/lib/store/indexeddb-remote-backend.js +33 -63
  350. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  351. package/lib/store/indexeddb-store-worker.js +22 -23
  352. package/lib/store/indexeddb-store-worker.js.map +1 -1
  353. package/lib/store/indexeddb.js +44 -71
  354. package/lib/store/indexeddb.js.map +1 -1
  355. package/lib/store/local-storage-events-emitter.js +2 -2
  356. package/lib/store/local-storage-events-emitter.js.map +1 -1
  357. package/lib/store/memory.js +34 -57
  358. package/lib/store/memory.js.map +1 -1
  359. package/lib/store/stub.js +22 -35
  360. package/lib/store/stub.js.map +1 -1
  361. package/lib/sync-accumulator.js +54 -66
  362. package/lib/sync-accumulator.js.map +1 -1
  363. package/lib/sync.d.ts.map +1 -1
  364. package/lib/sync.js +905 -998
  365. package/lib/sync.js.map +1 -1
  366. package/lib/testing.js +63 -105
  367. package/lib/testing.js.map +1 -1
  368. package/lib/thread-utils.js +1 -4
  369. package/lib/thread-utils.js.map +1 -1
  370. package/lib/timeline-window.js +89 -102
  371. package/lib/timeline-window.js.map +1 -1
  372. package/lib/types.js +1 -1
  373. package/lib/types.js.map +1 -1
  374. package/lib/utils/decryptAESSecretStorageItem.js +14 -25
  375. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  376. package/lib/utils/encryptAESSecretStorageItem.js +27 -38
  377. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  378. package/lib/utils/internal/deriveKeys.js +25 -32
  379. package/lib/utils/internal/deriveKeys.js.map +1 -1
  380. package/lib/utils/roomVersion.js +1 -1
  381. package/lib/utils/roomVersion.js.map +1 -1
  382. package/lib/utils.js +83 -135
  383. package/lib/utils.js.map +1 -1
  384. package/lib/version-support.js +3 -3
  385. package/lib/version-support.js.map +1 -1
  386. package/lib/webrtc/audioContext.js +5 -6
  387. package/lib/webrtc/audioContext.js.map +1 -1
  388. package/lib/webrtc/call.js +1081 -1250
  389. package/lib/webrtc/call.js.map +1 -1
  390. package/lib/webrtc/callEventHandler.js +202 -214
  391. package/lib/webrtc/callEventHandler.js.map +1 -1
  392. package/lib/webrtc/callEventTypes.js +2 -2
  393. package/lib/webrtc/callEventTypes.js.map +1 -1
  394. package/lib/webrtc/callFeed.js +18 -20
  395. package/lib/webrtc/callFeed.js.map +1 -1
  396. package/lib/webrtc/groupCall.js +513 -602
  397. package/lib/webrtc/groupCall.js.map +1 -1
  398. package/lib/webrtc/groupCallEventHandler.js +59 -62
  399. package/lib/webrtc/groupCallEventHandler.js.map +1 -1
  400. package/lib/webrtc/mediaHandler.js +198 -232
  401. package/lib/webrtc/mediaHandler.js.map +1 -1
  402. package/lib/webrtc/stats/callFeedStatsReporter.js +16 -20
  403. package/lib/webrtc/stats/callFeedStatsReporter.js.map +1 -1
  404. package/lib/webrtc/stats/callStatsReportGatherer.js +67 -75
  405. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  406. package/lib/webrtc/stats/callStatsReportSummary.js +3 -1
  407. package/lib/webrtc/stats/connectionStats.js.map +1 -1
  408. package/lib/webrtc/stats/connectionStatsBuilder.js +2 -2
  409. package/lib/webrtc/stats/connectionStatsBuilder.js.map +1 -1
  410. package/lib/webrtc/stats/connectionStatsReportBuilder.js +20 -24
  411. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  412. package/lib/webrtc/stats/groupCallStats.js +6 -8
  413. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  414. package/lib/webrtc/stats/media/mediaSsrcHandler.js +7 -8
  415. package/lib/webrtc/stats/media/mediaSsrcHandler.js.map +1 -1
  416. package/lib/webrtc/stats/media/mediaTrackHandler.js +7 -9
  417. package/lib/webrtc/stats/media/mediaTrackHandler.js.map +1 -1
  418. package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
  419. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  420. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +7 -7
  421. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  422. package/lib/webrtc/stats/statsReport.js +1 -1
  423. package/lib/webrtc/stats/statsReport.js.map +1 -1
  424. package/lib/webrtc/stats/statsReportEmitter.js.map +1 -1
  425. package/lib/webrtc/stats/summaryStatsReportGatherer.js +14 -14
  426. package/lib/webrtc/stats/summaryStatsReportGatherer.js.map +1 -1
  427. package/lib/webrtc/stats/trackStatsBuilder.js +32 -34
  428. package/lib/webrtc/stats/trackStatsBuilder.js.map +1 -1
  429. package/lib/webrtc/stats/transportStats.js +3 -1
  430. package/lib/webrtc/stats/transportStatsBuilder.js +9 -9
  431. package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
  432. package/lib/webrtc/stats/valueFormatter.js +1 -1
  433. package/lib/webrtc/stats/valueFormatter.js.map +1 -1
  434. package/package.json +18 -33
  435. package/src/@types/global.d.ts +2 -2
  436. package/src/ToDeviceMessageQueue.ts +2 -2
  437. package/src/browser-index.ts +4 -4
  438. package/src/client.ts +15 -20
  439. package/src/crypto-api/index.ts +17 -6
  440. package/src/embedded.ts +4 -6
  441. package/src/filter-component.ts +1 -0
  442. package/src/http-api/utils.ts +1 -1
  443. package/src/interactive-auth.ts +11 -5
  444. package/src/matrixrtc/LivekitTransport.ts +1 -1
  445. package/src/matrixrtc/MatrixRTCSession.ts +1 -1
  446. package/src/models/MSC3089Branch.ts +1 -1
  447. package/src/models/room-sticky-events.ts +1 -0
  448. package/src/models/room.ts +9 -11
  449. package/src/receipt-accumulator.ts +2 -0
  450. package/src/rendezvous/index.ts +1 -1
  451. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +2 -2
  452. package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +1 -1
  453. package/src/rust-crypto/index.ts +6 -6
  454. package/src/rust-crypto/rust-crypto.ts +31 -7
  455. package/src/rust-crypto/verification.ts +1 -1
  456. package/src/sliding-sync-sdk.ts +5 -7
  457. package/src/store/indexeddb-local-backend.ts +3 -3
  458. package/src/sync.ts +6 -8
@@ -1,4 +1,3 @@
1
- import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
2
1
  import _defineProperty from "@babel/runtime/helpers/defineProperty";
3
2
  /*
4
3
  Copyright 2023 The Matrix.org Foundation C.I.C.
@@ -52,11 +51,6 @@ export class OidcTokenRefresher {
52
51
  * used to validate tokens
53
52
  */
54
53
  idTokenClaims) {
55
- this.issuer = issuer;
56
- this.clientId = clientId;
57
- this.redirectUri = redirectUri;
58
- this.deviceId = deviceId;
59
- this.idTokenClaims = idTokenClaims;
60
54
  /**
61
55
  * This is now just a resolved promise and will be removed in a future version.
62
56
  * Initialisation is done lazily at token refresh time.
@@ -67,6 +61,11 @@ export class OidcTokenRefresher {
67
61
  _defineProperty(this, "initPromise", void 0);
68
62
  _defineProperty(this, "oidcClient", void 0);
69
63
  _defineProperty(this, "inflightRefreshRequest", void 0);
64
+ this.issuer = issuer;
65
+ this.clientId = clientId;
66
+ this.redirectUri = redirectUri;
67
+ this.deviceId = deviceId;
68
+ this.idTokenClaims = idTokenClaims;
70
69
  this.oidcClientReady = Promise.resolve();
71
70
  }
72
71
 
@@ -75,46 +74,39 @@ export class OidcTokenRefresher {
75
74
  * @returns Promise that resolves when initialisation is complete
76
75
  * @throws if initialisation fails
77
76
  */
78
- ensureInit() {
79
- var _this = this;
80
- return _asyncToGenerator(function* () {
81
- if (!_this.oidcClient) {
82
- if (_this.initPromise) {
83
- return _this.initPromise;
84
- }
85
- _this.initPromise = _this.initialiseOidcClient(_this.issuer, _this.clientId, _this.deviceId, _this.redirectUri);
86
- try {
87
- yield _this.initPromise;
88
- } finally {
89
- _this.initPromise = undefined;
90
- }
77
+ async ensureInit() {
78
+ if (!this.oidcClient) {
79
+ if (this.initPromise) {
80
+ return this.initPromise;
91
81
  }
92
- })();
93
- }
94
- initialiseOidcClient(issuer, clientId, deviceId, redirectUri) {
95
- var _this2 = this;
96
- return _asyncToGenerator(function* () {
82
+ this.initPromise = this.initialiseOidcClient(this.issuer, this.clientId, this.deviceId, this.redirectUri);
97
83
  try {
98
- var _config$signingKeys;
99
- var config = yield discoverAndValidateOIDCIssuerWellKnown(issuer);
100
- var scope = generateScope(deviceId);
101
- _this2.oidcClient = new OidcClient({
102
- metadata: config,
103
- signingKeys: (_config$signingKeys = config.signingKeys) !== null && _config$signingKeys !== void 0 ? _config$signingKeys : undefined,
104
- client_id: clientId,
105
- scope,
106
- redirect_uri: redirectUri,
107
- authority: config.issuer,
108
- stateStore: new WebStorageStateStore({
109
- prefix: "mx_oidc_",
110
- store: window.sessionStorage
111
- })
112
- });
113
- } catch (error) {
114
- logger.error("Failed to initialise OIDC client.", error);
115
- throw new Error("Failed to initialise OIDC client.");
84
+ await this.initPromise;
85
+ } finally {
86
+ this.initPromise = undefined;
116
87
  }
117
- })();
88
+ }
89
+ }
90
+ async initialiseOidcClient(issuer, clientId, deviceId, redirectUri) {
91
+ try {
92
+ const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);
93
+ const scope = generateScope(deviceId);
94
+ this.oidcClient = new OidcClient({
95
+ metadata: config,
96
+ signingKeys: config.signingKeys ?? undefined,
97
+ client_id: clientId,
98
+ scope,
99
+ redirect_uri: redirectUri,
100
+ authority: config.issuer,
101
+ stateStore: new WebStorageStateStore({
102
+ prefix: "mx_oidc_",
103
+ store: window.sessionStorage
104
+ })
105
+ });
106
+ } catch (error) {
107
+ logger.error("Failed to initialise OIDC client.", error);
108
+ throw new Error("Failed to initialise OIDC client.");
109
+ }
118
110
  }
119
111
 
120
112
  /**
@@ -123,26 +115,23 @@ export class OidcTokenRefresher {
123
115
  * @returns tokens - Promise that resolves with new access and refresh tokens
124
116
  * @throws when token refresh fails
125
117
  */
126
- doRefreshAccessToken(refreshToken) {
127
- var _this3 = this;
128
- return _asyncToGenerator(function* () {
129
- yield _this3.ensureInit();
130
- if (!_this3.inflightRefreshRequest) {
131
- _this3.inflightRefreshRequest = _this3.getNewTokens(refreshToken);
132
- }
133
- try {
134
- var tokens = yield _this3.inflightRefreshRequest;
135
- return tokens;
136
- } catch (e) {
137
- // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError
138
- if (e instanceof ErrorResponse) {
139
- throw new TokenRefreshLogoutError(e);
140
- }
141
- throw e;
142
- } finally {
143
- _this3.inflightRefreshRequest = undefined;
118
+ async doRefreshAccessToken(refreshToken) {
119
+ await this.ensureInit();
120
+ if (!this.inflightRefreshRequest) {
121
+ this.inflightRefreshRequest = this.getNewTokens(refreshToken);
122
+ }
123
+ try {
124
+ const tokens = await this.inflightRefreshRequest;
125
+ return tokens;
126
+ } catch (e) {
127
+ // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError
128
+ if (e instanceof ErrorResponse) {
129
+ throw new TokenRefreshLogoutError(e);
144
130
  }
145
- })();
131
+ throw e;
132
+ } finally {
133
+ this.inflightRefreshRequest = undefined;
134
+ }
146
135
  }
147
136
 
148
137
  /**
@@ -153,35 +142,32 @@ export class OidcTokenRefresher {
153
142
  * @param tokens.accessToken - new access token
154
143
  * @param tokens.refreshToken - OPTIONAL new refresh token
155
144
  */
156
- persistTokens(tokens) {
157
- return _asyncToGenerator(function* () {})();
158
- } // NOOP
159
- getNewTokens(refreshToken) {
160
- var _this4 = this;
161
- return _asyncToGenerator(function* () {
162
- if (!_this4.oidcClient) {
163
- throw new Error("Cannot get new token before OIDC client is initialised.");
164
- }
165
- var refreshTokenState = {
166
- refresh_token: refreshToken,
167
- session_state: "test",
168
- data: undefined,
169
- profile: _this4.idTokenClaims
170
- };
171
- var requestStart = Date.now();
172
- var response = yield _this4.oidcClient.useRefreshToken({
173
- state: refreshTokenState,
174
- timeoutInSeconds: 300
175
- });
176
- var tokens = {
177
- accessToken: response.access_token,
178
- refreshToken: response.refresh_token,
179
- // We use the request start time to calculate the expiry time as we don't know when the server received our request
180
- expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined
181
- };
182
- yield _this4.persistTokens(tokens);
183
- return tokens;
184
- })();
145
+ async persistTokens(tokens) {
146
+ // NOOP
147
+ }
148
+ async getNewTokens(refreshToken) {
149
+ if (!this.oidcClient) {
150
+ throw new Error("Cannot get new token before OIDC client is initialised.");
151
+ }
152
+ const refreshTokenState = {
153
+ refresh_token: refreshToken,
154
+ session_state: "test",
155
+ data: undefined,
156
+ profile: this.idTokenClaims
157
+ };
158
+ const requestStart = Date.now();
159
+ const response = await this.oidcClient.useRefreshToken({
160
+ state: refreshTokenState,
161
+ timeoutInSeconds: 300
162
+ });
163
+ const tokens = {
164
+ accessToken: response.access_token,
165
+ refreshToken: response.refresh_token,
166
+ // We use the request start time to calculate the expiry time as we don't know when the server received our request
167
+ expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined
168
+ };
169
+ await this.persistTokens(tokens);
170
+ return tokens;
185
171
  }
186
172
  }
187
173
  //# sourceMappingURL=tokenRefresher.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tokenRefresher.js","names":["OidcClient","WebStorageStateStore","ErrorResponse","TokenRefreshLogoutError","generateScope","discoverAndValidateOIDCIssuerWellKnown","logger","OidcTokenRefresher","constructor","issuer","clientId","redirectUri","deviceId","idTokenClaims","_defineProperty","oidcClientReady","Promise","resolve","ensureInit","_this","_asyncToGenerator","oidcClient","initPromise","initialiseOidcClient","undefined","_this2","_config$signingKeys","config","scope","metadata","signingKeys","client_id","redirect_uri","authority","stateStore","prefix","store","window","sessionStorage","error","Error","doRefreshAccessToken","refreshToken","_this3","inflightRefreshRequest","getNewTokens","tokens","e","persistTokens","_this4","refreshTokenState","refresh_token","session_state","data","profile","requestStart","Date","now","response","useRefreshToken","state","timeoutInSeconds","accessToken","access_token","expiry","expires_in"],"sources":["../../src/oidc/tokenRefresher.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 IdTokenClaims, OidcClient, WebStorageStateStore, ErrorResponse } from \"oidc-client-ts\";\n\nimport { type AccessTokens, TokenRefreshLogoutError } from \"../http-api/index.ts\";\nimport { generateScope } from \"./authorize.ts\";\nimport { discoverAndValidateOIDCIssuerWellKnown } from \"./discovery.ts\";\nimport { logger } from \"../logger.ts\";\n\n/**\n * @experimental\n * Class responsible for refreshing OIDC access tokens\n *\n * Client implementations will likely want to override {@link persistTokens} to persist tokens after successful refresh\n *\n */\nexport class OidcTokenRefresher {\n /**\n * This is now just a resolved promise and will be removed in a future version.\n * Initialisation is done lazily at token refresh time.\n * @deprecated Consumers no longer need to wait for this promise.\n */\n public readonly oidcClientReady!: Promise<void>;\n\n // If there is a initialisation attempt in progress, we keep track of it here.\n private initPromise?: Promise<void>;\n\n private oidcClient!: OidcClient;\n private inflightRefreshRequest?: Promise<AccessTokens>;\n\n public constructor(\n /**\n * The OIDC issuer as returned by the /auth_issuer API\n */\n private issuer: string,\n /**\n * id of this client as registered with the OP\n */\n private clientId: string,\n /**\n * redirectUri as registered with OP\n */\n private redirectUri: string,\n /**\n * Device ID of current session\n */\n protected deviceId: string,\n /**\n * idTokenClaims as returned from authorization grant\n * used to validate tokens\n */\n private readonly idTokenClaims: IdTokenClaims,\n ) {\n this.oidcClientReady = Promise.resolve();\n }\n\n /**\n * Ensures that the client is initialised.\n * @returns Promise that resolves when initialisation is complete\n * @throws if initialisation fails\n */\n private async ensureInit(): Promise<void> {\n if (!this.oidcClient) {\n if (this.initPromise) {\n return this.initPromise;\n }\n\n this.initPromise = this.initialiseOidcClient(this.issuer, this.clientId, this.deviceId, this.redirectUri);\n try {\n await this.initPromise;\n } finally {\n this.initPromise = undefined;\n }\n }\n }\n\n private async initialiseOidcClient(\n issuer: string,\n clientId: string,\n deviceId: string,\n redirectUri: string,\n ): Promise<void> {\n try {\n const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);\n\n const scope = generateScope(deviceId);\n\n this.oidcClient = new OidcClient({\n metadata: config,\n signingKeys: config.signingKeys ?? undefined,\n client_id: clientId,\n scope,\n redirect_uri: redirectUri,\n authority: config.issuer,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n } catch (error) {\n logger.error(\"Failed to initialise OIDC client.\", error);\n throw new Error(\"Failed to initialise OIDC client.\");\n }\n }\n\n /**\n * Attempt token refresh using given refresh token\n * @param refreshToken - refresh token to use in request with token issuer\n * @returns tokens - Promise that resolves with new access and refresh tokens\n * @throws when token refresh fails\n */\n public async doRefreshAccessToken(refreshToken: string): Promise<AccessTokens> {\n await this.ensureInit();\n\n if (!this.inflightRefreshRequest) {\n this.inflightRefreshRequest = this.getNewTokens(refreshToken);\n }\n try {\n const tokens = await this.inflightRefreshRequest;\n return tokens;\n } catch (e) {\n // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError\n if (e instanceof ErrorResponse) {\n throw new TokenRefreshLogoutError(e);\n }\n throw e;\n } finally {\n this.inflightRefreshRequest = undefined;\n }\n }\n\n /**\n * Persist the new tokens, called after tokens are successfully refreshed.\n *\n * This function is intended to be overriden by the consumer when persistence is necessary.\n *\n * @param tokens.accessToken - new access token\n * @param tokens.refreshToken - OPTIONAL new refresh token\n */\n protected async persistTokens(tokens: { accessToken: string; refreshToken?: string }): Promise<void> {\n // NOOP\n }\n\n private async getNewTokens(refreshToken: string): Promise<AccessTokens> {\n if (!this.oidcClient) {\n throw new Error(\"Cannot get new token before OIDC client is initialised.\");\n }\n\n const refreshTokenState = {\n refresh_token: refreshToken,\n session_state: \"test\",\n data: undefined,\n profile: this.idTokenClaims,\n };\n\n const requestStart = Date.now();\n const response = await this.oidcClient.useRefreshToken({\n state: refreshTokenState,\n timeoutInSeconds: 300,\n });\n\n const tokens = {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n // We use the request start time to calculate the expiry time as we don't know when the server received our request\n expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined,\n } satisfies AccessTokens;\n\n await this.persistTokens(tokens);\n\n return tokens;\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA6BA,UAAU,EAAEC,oBAAoB,EAAEC,aAAa,QAAQ,gBAAgB;AAEpG,SAA4BC,uBAAuB,QAAQ,sBAAsB;AACjF,SAASC,aAAa,QAAQ,gBAAgB;AAC9C,SAASC,sCAAsC,QAAQ,gBAAgB;AACvE,SAASC,MAAM,QAAQ,cAAc;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,kBAAkB,CAAC;EAcrBC,WAAWA;EACd;AACR;AACA;EACgBC,MAAc;EACtB;AACR;AACA;EACgBC,QAAgB;EACxB;AACR;AACA;EACgBC,WAAmB;EAC3B;AACR;AACA;EACkBC,QAAgB;EAC1B;AACR;AACA;AACA;EACyBC,aAA4B,EAC/C;IAAA,KAlBUJ,MAAc,GAAdA,MAAc;IAAA,KAIdC,QAAgB,GAAhBA,QAAgB;IAAA,KAIhBC,WAAmB,GAAnBA,WAAmB;IAAA,KAIjBC,QAAgB,GAAhBA,QAAgB;IAAA,KAKTC,aAA4B,GAA5BA,aAA4B;IAlCjD;AACJ;AACA;AACA;AACA;IAJIC,eAAA;IAOA;IAAAA,eAAA;IAAAA,eAAA;IAAAA,eAAA;IA6BI,IAAI,CAACC,eAAe,GAAGC,OAAO,CAACC,OAAO,CAAC,CAAC;EAC5C;;EAEA;AACJ;AACA;AACA;AACA;EACkBC,UAAUA,CAAA,EAAkB;IAAA,IAAAC,KAAA;IAAA,OAAAC,iBAAA;MACtC,IAAI,CAACD,KAAI,CAACE,UAAU,EAAE;QAClB,IAAIF,KAAI,CAACG,WAAW,EAAE;UAClB,OAAOH,KAAI,CAACG,WAAW;QAC3B;QAEAH,KAAI,CAACG,WAAW,GAAGH,KAAI,CAACI,oBAAoB,CAACJ,KAAI,CAACV,MAAM,EAAE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,CAACO,UAAU,GAAG,IAAI,CAAC,GAAGzC;MACxF,CAAwB;MAExB,MAAMyB,MAAI,CAACD,aAAa,CAACF,MAAM,CAAC;MAEhC,OAAOA,MAAM;IAAC;EAClB;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"tokenRefresher.js","names":[],"sources":["../../src/oidc/tokenRefresher.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 IdTokenClaims, OidcClient, WebStorageStateStore, ErrorResponse } from \"oidc-client-ts\";\n\nimport { type AccessTokens, TokenRefreshLogoutError } from \"../http-api/index.ts\";\nimport { generateScope } from \"./authorize.ts\";\nimport { discoverAndValidateOIDCIssuerWellKnown } from \"./discovery.ts\";\nimport { logger } from \"../logger.ts\";\n\n/**\n * @experimental\n * Class responsible for refreshing OIDC access tokens\n *\n * Client implementations will likely want to override {@link persistTokens} to persist tokens after successful refresh\n *\n */\nexport class OidcTokenRefresher {\n /**\n * This is now just a resolved promise and will be removed in a future version.\n * Initialisation is done lazily at token refresh time.\n * @deprecated Consumers no longer need to wait for this promise.\n */\n public readonly oidcClientReady!: Promise<void>;\n\n // If there is a initialisation attempt in progress, we keep track of it here.\n private initPromise?: Promise<void>;\n\n private oidcClient!: OidcClient;\n private inflightRefreshRequest?: Promise<AccessTokens>;\n\n public constructor(\n /**\n * The OIDC issuer as returned by the /auth_issuer API\n */\n private issuer: string,\n /**\n * id of this client as registered with the OP\n */\n private clientId: string,\n /**\n * redirectUri as registered with OP\n */\n private redirectUri: string,\n /**\n * Device ID of current session\n */\n protected deviceId: string,\n /**\n * idTokenClaims as returned from authorization grant\n * used to validate tokens\n */\n private readonly idTokenClaims: IdTokenClaims,\n ) {\n this.oidcClientReady = Promise.resolve();\n }\n\n /**\n * Ensures that the client is initialised.\n * @returns Promise that resolves when initialisation is complete\n * @throws if initialisation fails\n */\n private async ensureInit(): Promise<void> {\n if (!this.oidcClient) {\n if (this.initPromise) {\n return this.initPromise;\n }\n\n this.initPromise = this.initialiseOidcClient(this.issuer, this.clientId, this.deviceId, this.redirectUri);\n try {\n await this.initPromise;\n } finally {\n this.initPromise = undefined;\n }\n }\n }\n\n private async initialiseOidcClient(\n issuer: string,\n clientId: string,\n deviceId: string,\n redirectUri: string,\n ): Promise<void> {\n try {\n const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);\n\n const scope = generateScope(deviceId);\n\n this.oidcClient = new OidcClient({\n metadata: config,\n signingKeys: config.signingKeys ?? undefined,\n client_id: clientId,\n scope,\n redirect_uri: redirectUri,\n authority: config.issuer,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n } catch (error) {\n logger.error(\"Failed to initialise OIDC client.\", error);\n throw new Error(\"Failed to initialise OIDC client.\");\n }\n }\n\n /**\n * Attempt token refresh using given refresh token\n * @param refreshToken - refresh token to use in request with token issuer\n * @returns tokens - Promise that resolves with new access and refresh tokens\n * @throws when token refresh fails\n */\n public async doRefreshAccessToken(refreshToken: string): Promise<AccessTokens> {\n await this.ensureInit();\n\n if (!this.inflightRefreshRequest) {\n this.inflightRefreshRequest = this.getNewTokens(refreshToken);\n }\n try {\n const tokens = await this.inflightRefreshRequest;\n return tokens;\n } catch (e) {\n // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError\n if (e instanceof ErrorResponse) {\n throw new TokenRefreshLogoutError(e);\n }\n throw e;\n } finally {\n this.inflightRefreshRequest = undefined;\n }\n }\n\n /**\n * Persist the new tokens, called after tokens are successfully refreshed.\n *\n * This function is intended to be overriden by the consumer when persistence is necessary.\n *\n * @param tokens.accessToken - new access token\n * @param tokens.refreshToken - OPTIONAL new refresh token\n */\n protected async persistTokens(tokens: { accessToken: string; refreshToken?: string }): Promise<void> {\n // NOOP\n }\n\n private async getNewTokens(refreshToken: string): Promise<AccessTokens> {\n if (!this.oidcClient) {\n throw new Error(\"Cannot get new token before OIDC client is initialised.\");\n }\n\n const refreshTokenState = {\n refresh_token: refreshToken,\n session_state: \"test\",\n data: undefined,\n profile: this.idTokenClaims,\n };\n\n const requestStart = Date.now();\n const response = await this.oidcClient.useRefreshToken({\n state: refreshTokenState,\n timeoutInSeconds: 300,\n });\n\n const tokens = {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n // We use the request start time to calculate the expiry time as we don't know when the server received our request\n expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined,\n } satisfies AccessTokens;\n\n await this.persistTokens(tokens);\n\n return tokens;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA6B,UAAU,EAAE,oBAAoB,EAAE,aAAa,QAAQ,gBAAgB;AAEpG,SAA4B,uBAAuB,QAAQ,sBAAsB;AACjF,SAAS,aAAa,QAAQ,gBAAgB;AAC9C,SAAS,sCAAsC,QAAQ,gBAAgB;AACvE,SAAS,MAAM,QAAQ,cAAc;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,kBAAkB,CAAC;EAcrB,WAAW;EACd;AACR;AACA;EACgB,MAAc;EACtB;AACR;AACA;EACgB,QAAgB;EACxB;AACR;AACA;EACgB,WAAmB;EAC3B;AACR;AACA;EACkB,QAAgB;EAC1B;AACR;AACA;AACA;EACyB,aAA4B,EAC/C;IAnCF;AACJ;AACA;AACA;AACA;IAJI;IAOA;IAAA;IAAA;IAAA;IAAA,KAUY,MAAc,GAAd,MAAc;IAAA,KAId,QAAgB,GAAhB,QAAgB;IAAA,KAIhB,WAAmB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AAM,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI,IAAI,CAAC,YAAY,GAAG,QAAQ,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG;IACxF,CAAwB;IAExB,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;IAEhC,OAAO,MAAM;EACjB;AACJ","ignoreList":[]}
@@ -25,32 +25,32 @@ import { OAuthGrantType } from "./index.js";
25
25
  * With validated properties required in type
26
26
  */
27
27
 
28
- var isRecord = value => !!value && typeof value === "object" && !Array.isArray(value);
29
- var requiredStringProperty = (wellKnown, key) => {
28
+ const isRecord = value => !!value && typeof value === "object" && !Array.isArray(value);
29
+ const requiredStringProperty = (wellKnown, key) => {
30
30
  if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {
31
- logger.error("Missing or invalid property: ".concat(key));
31
+ logger.error(`Missing or invalid property: ${key}`);
32
32
  return false;
33
33
  }
34
34
  return true;
35
35
  };
36
- var optionalStringProperty = (wellKnown, key) => {
36
+ const optionalStringProperty = (wellKnown, key) => {
37
37
  if (!!wellKnown[key] && typeof wellKnown[key] !== "string") {
38
- logger.error("Invalid property: ".concat(key));
38
+ logger.error(`Invalid property: ${key}`);
39
39
  return false;
40
40
  }
41
41
  return true;
42
42
  };
43
- var optionalStringArrayProperty = (wellKnown, key) => {
43
+ const optionalStringArrayProperty = (wellKnown, key) => {
44
44
  if (!!wellKnown[key] && (!Array.isArray(wellKnown[key]) || !wellKnown[key].every(v => typeof v === "string"))) {
45
- logger.error("Invalid property: ".concat(key));
45
+ logger.error(`Invalid property: ${key}`);
46
46
  return false;
47
47
  }
48
48
  return true;
49
49
  };
50
- var requiredArrayValue = (wellKnown, key, value) => {
51
- var array = wellKnown[key];
50
+ const requiredArrayValue = (wellKnown, key, value) => {
51
+ const array = wellKnown[key];
52
52
  if (!array || !Array.isArray(array) || !array.includes(value)) {
53
- logger.error("Invalid property: ".concat(key, ". ").concat(value, " is required."));
53
+ logger.error(`Invalid property: ${key}. ${value} is required.`);
54
54
  return false;
55
55
  }
56
56
  return true;
@@ -64,19 +64,19 @@ var requiredArrayValue = (wellKnown, key, value) => {
64
64
  * @returns valid issuer config
65
65
  * @throws Error - when issuer config is not found or is invalid
66
66
  */
67
- export var validateAuthMetadata = authMetadata => {
67
+ export const validateAuthMetadata = authMetadata => {
68
68
  if (!isRecord(authMetadata)) {
69
69
  logger.error("Issuer configuration not found or malformed");
70
70
  throw new Error(OidcError.OpSupport);
71
71
  }
72
- var isInvalid = [requiredStringProperty(authMetadata, "issuer"), requiredStringProperty(authMetadata, "authorization_endpoint"), requiredStringProperty(authMetadata, "token_endpoint"), requiredStringProperty(authMetadata, "revocation_endpoint"), optionalStringProperty(authMetadata, "registration_endpoint"), optionalStringProperty(authMetadata, "account_management_uri"), optionalStringProperty(authMetadata, "device_authorization_endpoint"), optionalStringArrayProperty(authMetadata, "account_management_actions_supported"), requiredArrayValue(authMetadata, "response_types_supported", "code"), requiredArrayValue(authMetadata, "grant_types_supported", OAuthGrantType.AuthorizationCode), requiredArrayValue(authMetadata, "code_challenge_methods_supported", "S256"), optionalStringArrayProperty(authMetadata, "prompt_values_supported")].some(isValid => !isValid);
72
+ const isInvalid = [requiredStringProperty(authMetadata, "issuer"), requiredStringProperty(authMetadata, "authorization_endpoint"), requiredStringProperty(authMetadata, "token_endpoint"), requiredStringProperty(authMetadata, "revocation_endpoint"), optionalStringProperty(authMetadata, "registration_endpoint"), optionalStringProperty(authMetadata, "account_management_uri"), optionalStringProperty(authMetadata, "device_authorization_endpoint"), optionalStringArrayProperty(authMetadata, "account_management_actions_supported"), requiredArrayValue(authMetadata, "response_types_supported", "code"), requiredArrayValue(authMetadata, "grant_types_supported", OAuthGrantType.AuthorizationCode), requiredArrayValue(authMetadata, "code_challenge_methods_supported", "S256"), optionalStringArrayProperty(authMetadata, "prompt_values_supported")].some(isValid => !isValid);
73
73
  if (!isInvalid) {
74
74
  return authMetadata;
75
75
  }
76
76
  logger.error("Issuer configuration not valid");
77
77
  throw new Error(OidcError.OpSupport);
78
78
  };
79
- export var decodeIdToken = token => {
79
+ export const decodeIdToken = token => {
80
80
  try {
81
81
  return jwtDecode(token);
82
82
  } catch (error) {
@@ -94,12 +94,12 @@ export var decodeIdToken = token => {
94
94
  * @param nonce - nonce used in the authentication request
95
95
  * @throws when id token is invalid
96
96
  */
97
- export var validateIdToken = (idToken, issuer, clientId, nonce) => {
97
+ export const validateIdToken = (idToken, issuer, clientId, nonce) => {
98
98
  try {
99
99
  if (!idToken) {
100
100
  throw new Error("No ID token");
101
101
  }
102
- var claims = decodeIdToken(idToken);
102
+ const claims = decodeIdToken(idToken);
103
103
 
104
104
  // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.
105
105
  if (claims.iss !== issuer) {
@@ -111,7 +111,7 @@ export var validateIdToken = (idToken, issuer, clientId, nonce) => {
111
111
  * The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.
112
112
  * EW: Don't accept tokens with other untrusted audiences
113
113
  * */
114
- var sanitisedAuds = typeof claims.aud === "string" ? [claims.aud] : claims.aud;
114
+ const sanitisedAuds = typeof claims.aud === "string" ? [claims.aud] : claims.aud;
115
115
  if (!sanitisedAuds.includes(clientId)) {
116
116
  throw new Error("Invalid audience");
117
117
  }
@@ -152,7 +152,7 @@ export function validateStoredUserState(userState) {
152
152
  logger.error("Stored user state not found");
153
153
  throw new Error(OidcError.MissingOrInvalidStoredState);
154
154
  }
155
- var isInvalid = [requiredStringProperty(userState, "homeserverUrl"), requiredStringProperty(userState, "nonce"), optionalStringProperty(userState, "identityServerUrl")].some(isValid => !isValid);
155
+ const isInvalid = [requiredStringProperty(userState, "homeserverUrl"), requiredStringProperty(userState, "nonce"), optionalStringProperty(userState, "identityServerUrl")].some(isValid => !isValid);
156
156
  if (isInvalid) {
157
157
  throw new Error(OidcError.MissingOrInvalidStoredState);
158
158
  }
@@ -170,7 +170,7 @@ export function validateStoredUserState(userState) {
170
170
  * Make required properties required in type
171
171
  */
172
172
 
173
- var isValidBearerTokenResponse = response => isRecord(response) && requiredStringProperty(response, "token_type") &&
173
+ const isValidBearerTokenResponse = response => isRecord(response) && requiredStringProperty(response, "token_type") &&
174
174
  // token_type is case insensitive, some OPs return `token_type: "bearer"`
175
175
  response["token_type"].toLowerCase() === "bearer" && requiredStringProperty(response, "access_token") && requiredStringProperty(response, "refresh_token") && (!("expires_in" in response) || typeof response["expires_in"] === "number");
176
176
  export function validateBearerTokenResponse(response) {
@@ -1 +1 @@
1
- {"version":3,"file":"validate.js","names":["jwtDecode","logger","OidcError","OAuthGrantType","isRecord","value","Array","isArray","requiredStringProperty","wellKnown","key","optionalStringProperty","error","concat","optionalStringArrayProperty","every","v","requiredArrayValue","array","includes","validateAuthMetadata","authMetadata","Error","OpSupport","isInvalid","AuthorizationCode","some","isValid","decodeIdToken","token","validateIdToken","idToken","issuer","clientId","nonce","claims","iss","sanitisedAuds","aud","undefined","exp","Date","now","InvalidIdToken","validateStoredUserState","userState","MissingOrInvalidStoredState","isValidBearerTokenResponse","response","toLowerCase","validateBearerTokenResponse","InvalidBearerTokenResponse"],"sources":["../../src/oidc/validate.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 { jwtDecode } from \"jwt-decode\";\nimport { type IdTokenClaims, type OidcMetadata, type SigninResponse } from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { OidcError } from \"./error.ts\";\nimport { OAuthGrantType } from \"./index.ts\";\n\n/**\n * Metadata from OAuth 2.0 client authentication API as per\n * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata\n * With validated properties required in type\n */\nexport type ValidatedAuthMetadata = Partial<OidcMetadata> &\n Pick<\n // These values are from [RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)\n // so we can reuse the OidcMetadata definitions from oidc-client-ts\n OidcMetadata,\n | \"issuer\"\n | \"authorization_endpoint\"\n | \"token_endpoint\"\n | \"revocation_endpoint\"\n | \"response_types_supported\"\n | \"grant_types_supported\"\n | \"code_challenge_methods_supported\"\n > & {\n // These values aren't part of RFC8414 so we add them here\n // Account management fields from stable MSC4191:\n account_management_uri?: string;\n account_management_actions_supported?: string[];\n // Value from [Initiating User Registration via OpenID Connect](https://openid.net/specs/openid-connect-prompt-create-1_0.html):\n prompt_values_supported?: string[];\n // Experimental MSC4341 value from [RFC8628](https://datatracker.ietf.org/doc/html/rfc8628#section-4):\n device_authorization_endpoint?: string;\n };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\nconst requiredStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {\n logger.error(`Missing or invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!!wellKnown[key] && typeof wellKnown[key] !== \"string\") {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringArrayProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (\n !!wellKnown[key] &&\n (!Array.isArray(wellKnown[key]) || !(<unknown[]>wellKnown[key]).every((v) => typeof v === \"string\"))\n ) {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst requiredArrayValue = (wellKnown: Record<string, unknown>, key: string, value: any): boolean => {\n const array = wellKnown[key];\n if (!array || !Array.isArray(array) || !array.includes(value)) {\n logger.error(`Invalid property: ${key}. ${value} is required.`);\n return false;\n }\n return true;\n};\n\n/**\n * Validates OAuth 2.0 auth metadata as defined by\n * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata\n * is compatible with Element's OAuth/OIDC flow\n * @param authMetadata - json object\n * @returns valid issuer config\n * @throws Error - when issuer config is not found or is invalid\n */\nexport const validateAuthMetadata = (authMetadata: unknown): ValidatedAuthMetadata => {\n if (!isRecord(authMetadata)) {\n logger.error(\"Issuer configuration not found or malformed\");\n throw new Error(OidcError.OpSupport);\n }\n\n const isInvalid = [\n requiredStringProperty(authMetadata, \"issuer\"),\n requiredStringProperty(authMetadata, \"authorization_endpoint\"),\n requiredStringProperty(authMetadata, \"token_endpoint\"),\n requiredStringProperty(authMetadata, \"revocation_endpoint\"),\n optionalStringProperty(authMetadata, \"registration_endpoint\"),\n optionalStringProperty(authMetadata, \"account_management_uri\"),\n optionalStringProperty(authMetadata, \"device_authorization_endpoint\"),\n optionalStringArrayProperty(authMetadata, \"account_management_actions_supported\"),\n requiredArrayValue(authMetadata, \"response_types_supported\", \"code\"),\n requiredArrayValue(authMetadata, \"grant_types_supported\", OAuthGrantType.AuthorizationCode),\n requiredArrayValue(authMetadata, \"code_challenge_methods_supported\", \"S256\"),\n optionalStringArrayProperty(authMetadata, \"prompt_values_supported\"),\n ].some((isValid) => !isValid);\n\n if (!isInvalid) {\n return authMetadata as ValidatedAuthMetadata;\n }\n\n logger.error(\"Issuer configuration not valid\");\n throw new Error(OidcError.OpSupport);\n};\n\nexport const decodeIdToken = (token: string): IdTokenClaims => {\n try {\n return jwtDecode<IdTokenClaims>(token);\n } catch (error) {\n logger.error(\"Could not decode id_token\", error);\n throw error;\n }\n};\n\n/**\n * Validate idToken\n * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation\n * @param idToken - id token from token endpoint\n * @param issuer - issuer for the OP as found during discovery\n * @param clientId - this client's id as registered with the OP\n * @param nonce - nonce used in the authentication request\n * @throws when id token is invalid\n */\nexport const validateIdToken = (\n idToken: string | undefined,\n issuer: string,\n clientId: string,\n nonce: string | undefined,\n): void => {\n try {\n if (!idToken) {\n throw new Error(\"No ID token\");\n }\n const claims = decodeIdToken(idToken);\n\n // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.\n if (claims.iss !== issuer) {\n throw new Error(\"Invalid issuer\");\n }\n /**\n * The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience.\n * The aud (audience) Claim MAY contain an array with more than one element.\n * The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.\n * EW: Don't accept tokens with other untrusted audiences\n * */\n const sanitisedAuds = typeof claims.aud === \"string\" ? [claims.aud] : claims.aud;\n if (!sanitisedAuds.includes(clientId)) {\n throw new Error(\"Invalid audience\");\n }\n\n /**\n * If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked\n * to verify that it is the same value as the one that was sent in the Authentication Request.\n */\n if (nonce !== undefined && claims.nonce !== nonce) {\n throw new Error(\"Invalid nonce\");\n }\n\n /**\n * The current time MUST be before the time represented by the exp Claim.\n * exp is an epoch timestamp in seconds\n * */\n if (!claims.exp || Date.now() > claims.exp * 1000) {\n throw new Error(\"Invalid expiry\");\n }\n } catch (error) {\n logger.error(\"Invalid ID token\", error);\n throw new Error(OidcError.InvalidIdToken);\n }\n};\n\n/**\n * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)\n * so that we can access it on return from the OP and complete login\n */\nexport type UserState = {\n /**\n * Remember which server we were trying to login to\n */\n homeserverUrl: string;\n identityServerUrl?: string;\n /**\n * Used to validate id token\n */\n nonce: string;\n};\n/**\n * Validate stored user state exists and is valid\n * @param userState - userState returned by oidcClient.processSigninResponse\n * @throws when userState is invalid\n */\nexport function validateStoredUserState(userState: unknown): asserts userState is UserState {\n if (!isRecord(userState)) {\n logger.error(\"Stored user state not found\");\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n const isInvalid = [\n requiredStringProperty(userState, \"homeserverUrl\"),\n requiredStringProperty(userState, \"nonce\"),\n optionalStringProperty(userState, \"identityServerUrl\"),\n ].some((isValid) => !isValid);\n\n if (isInvalid) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n}\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,\n * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.\n */\nexport type BearerTokenResponse = {\n token_type: \"Bearer\";\n access_token: string;\n scope: string;\n refresh_token?: string;\n expires_in?: number;\n // from oidc-client-ts\n expires_at?: number;\n id_token: string;\n};\n\n/**\n * Make required properties required in type\n */\ntype ValidSignInResponse = SigninResponse &\n BearerTokenResponse & {\n token_type: \"Bearer\" | \"bearer\";\n };\n\nconst isValidBearerTokenResponse = (response: unknown): response is ValidSignInResponse =>\n isRecord(response) &&\n requiredStringProperty(response, \"token_type\") &&\n // token_type is case insensitive, some OPs return `token_type: \"bearer\"`\n (response[\"token_type\"] as string).toLowerCase() === \"bearer\" &&\n requiredStringProperty(response, \"access_token\") &&\n requiredStringProperty(response, \"refresh_token\") &&\n (!(\"expires_in\" in response) || typeof response[\"expires_in\"] === \"number\");\n\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidSignInResponse {\n if (!isValidBearerTokenResponse(response)) {\n throw new Error(OidcError.InvalidBearerTokenResponse);\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,YAAY;AAGtC,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,SAAS,QAAQ,YAAY;AACtC,SAASC,cAAc,QAAQ,YAAY;;AAE3C;AACA;AACA;AACA;AACA;;AAwBA,IAAMC,QAAQ,GAAIC,KAAc,IAC5B,CAAC,CAACA,KAAK,IAAI,OAAOA,KAAK,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,KAChD,EAAE,YAAY,IAAIA,QAAQ,CAAC,IAAI,OAAOA,QAAQ,CAAC,YAAY,CAAC,KAAK,QAAQ,CAAC;AAE/E,OAAO,SAASE,2BAA2BA,CAACF,QAAiB,EAA2C;EACpG,IAAI,CAACD,0BAA0B,CAACC,QAAQ,CAAC,EAAE;IACvC,MAAM,IAAI1B,KAAK,CAACpB,SAAS,CAACiD,0BAA0B,CAAC;EACzD;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"validate.js","names":[],"sources":["../../src/oidc/validate.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 { jwtDecode } from \"jwt-decode\";\nimport { type IdTokenClaims, type OidcMetadata, type SigninResponse } from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { OidcError } from \"./error.ts\";\nimport { OAuthGrantType } from \"./index.ts\";\n\n/**\n * Metadata from OAuth 2.0 client authentication API as per\n * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata\n * With validated properties required in type\n */\nexport type ValidatedAuthMetadata = Partial<OidcMetadata> &\n Pick<\n // These values are from [RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)\n // so we can reuse the OidcMetadata definitions from oidc-client-ts\n OidcMetadata,\n | \"issuer\"\n | \"authorization_endpoint\"\n | \"token_endpoint\"\n | \"revocation_endpoint\"\n | \"response_types_supported\"\n | \"grant_types_supported\"\n | \"code_challenge_methods_supported\"\n > & {\n // These values aren't part of RFC8414 so we add them here\n // Account management fields from stable MSC4191:\n account_management_uri?: string;\n account_management_actions_supported?: string[];\n // Value from [Initiating User Registration via OpenID Connect](https://openid.net/specs/openid-connect-prompt-create-1_0.html):\n prompt_values_supported?: string[];\n // Experimental MSC4341 value from [RFC8628](https://datatracker.ietf.org/doc/html/rfc8628#section-4):\n device_authorization_endpoint?: string;\n };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\nconst requiredStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {\n logger.error(`Missing or invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!!wellKnown[key] && typeof wellKnown[key] !== \"string\") {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringArrayProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (\n !!wellKnown[key] &&\n (!Array.isArray(wellKnown[key]) || !(<unknown[]>wellKnown[key]).every((v) => typeof v === \"string\"))\n ) {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst requiredArrayValue = (wellKnown: Record<string, unknown>, key: string, value: any): boolean => {\n const array = wellKnown[key];\n if (!array || !Array.isArray(array) || !array.includes(value)) {\n logger.error(`Invalid property: ${key}. ${value} is required.`);\n return false;\n }\n return true;\n};\n\n/**\n * Validates OAuth 2.0 auth metadata as defined by\n * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata\n * is compatible with Element's OAuth/OIDC flow\n * @param authMetadata - json object\n * @returns valid issuer config\n * @throws Error - when issuer config is not found or is invalid\n */\nexport const validateAuthMetadata = (authMetadata: unknown): ValidatedAuthMetadata => {\n if (!isRecord(authMetadata)) {\n logger.error(\"Issuer configuration not found or malformed\");\n throw new Error(OidcError.OpSupport);\n }\n\n const isInvalid = [\n requiredStringProperty(authMetadata, \"issuer\"),\n requiredStringProperty(authMetadata, \"authorization_endpoint\"),\n requiredStringProperty(authMetadata, \"token_endpoint\"),\n requiredStringProperty(authMetadata, \"revocation_endpoint\"),\n optionalStringProperty(authMetadata, \"registration_endpoint\"),\n optionalStringProperty(authMetadata, \"account_management_uri\"),\n optionalStringProperty(authMetadata, \"device_authorization_endpoint\"),\n optionalStringArrayProperty(authMetadata, \"account_management_actions_supported\"),\n requiredArrayValue(authMetadata, \"response_types_supported\", \"code\"),\n requiredArrayValue(authMetadata, \"grant_types_supported\", OAuthGrantType.AuthorizationCode),\n requiredArrayValue(authMetadata, \"code_challenge_methods_supported\", \"S256\"),\n optionalStringArrayProperty(authMetadata, \"prompt_values_supported\"),\n ].some((isValid) => !isValid);\n\n if (!isInvalid) {\n return authMetadata as ValidatedAuthMetadata;\n }\n\n logger.error(\"Issuer configuration not valid\");\n throw new Error(OidcError.OpSupport);\n};\n\nexport const decodeIdToken = (token: string): IdTokenClaims => {\n try {\n return jwtDecode<IdTokenClaims>(token);\n } catch (error) {\n logger.error(\"Could not decode id_token\", error);\n throw error;\n }\n};\n\n/**\n * Validate idToken\n * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation\n * @param idToken - id token from token endpoint\n * @param issuer - issuer for the OP as found during discovery\n * @param clientId - this client's id as registered with the OP\n * @param nonce - nonce used in the authentication request\n * @throws when id token is invalid\n */\nexport const validateIdToken = (\n idToken: string | undefined,\n issuer: string,\n clientId: string,\n nonce: string | undefined,\n): void => {\n try {\n if (!idToken) {\n throw new Error(\"No ID token\");\n }\n const claims = decodeIdToken(idToken);\n\n // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.\n if (claims.iss !== issuer) {\n throw new Error(\"Invalid issuer\");\n }\n /**\n * The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience.\n * The aud (audience) Claim MAY contain an array with more than one element.\n * The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.\n * EW: Don't accept tokens with other untrusted audiences\n * */\n const sanitisedAuds = typeof claims.aud === \"string\" ? [claims.aud] : claims.aud;\n if (!sanitisedAuds.includes(clientId)) {\n throw new Error(\"Invalid audience\");\n }\n\n /**\n * If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked\n * to verify that it is the same value as the one that was sent in the Authentication Request.\n */\n if (nonce !== undefined && claims.nonce !== nonce) {\n throw new Error(\"Invalid nonce\");\n }\n\n /**\n * The current time MUST be before the time represented by the exp Claim.\n * exp is an epoch timestamp in seconds\n * */\n if (!claims.exp || Date.now() > claims.exp * 1000) {\n throw new Error(\"Invalid expiry\");\n }\n } catch (error) {\n logger.error(\"Invalid ID token\", error);\n throw new Error(OidcError.InvalidIdToken);\n }\n};\n\n/**\n * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)\n * so that we can access it on return from the OP and complete login\n */\nexport type UserState = {\n /**\n * Remember which server we were trying to login to\n */\n homeserverUrl: string;\n identityServerUrl?: string;\n /**\n * Used to validate id token\n */\n nonce: string;\n};\n/**\n * Validate stored user state exists and is valid\n * @param userState - userState returned by oidcClient.processSigninResponse\n * @throws when userState is invalid\n */\nexport function validateStoredUserState(userState: unknown): asserts userState is UserState {\n if (!isRecord(userState)) {\n logger.error(\"Stored user state not found\");\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n const isInvalid = [\n requiredStringProperty(userState, \"homeserverUrl\"),\n requiredStringProperty(userState, \"nonce\"),\n optionalStringProperty(userState, \"identityServerUrl\"),\n ].some((isValid) => !isValid);\n\n if (isInvalid) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n}\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,\n * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.\n */\nexport type BearerTokenResponse = {\n token_type: \"Bearer\";\n access_token: string;\n scope: string;\n refresh_token?: string;\n expires_in?: number;\n // from oidc-client-ts\n expires_at?: number;\n id_token: string;\n};\n\n/**\n * Make required properties required in type\n */\ntype ValidSignInResponse = SigninResponse &\n BearerTokenResponse & {\n token_type: \"Bearer\" | \"bearer\";\n };\n\nconst isValidBearerTokenResponse = (response: unknown): response is ValidSignInResponse =>\n isRecord(response) &&\n requiredStringProperty(response, \"token_type\") &&\n // token_type is case insensitive, some OPs return `token_type: \"bearer\"`\n (response[\"token_type\"] as string).toLowerCase() === \"bearer\" &&\n requiredStringProperty(response, \"access_token\") &&\n requiredStringProperty(response, \"refresh_token\") &&\n (!(\"expires_in\" in response) || typeof response[\"expires_in\"] === \"number\");\n\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidSignInResponse {\n if (!isValidBearerTokenResponse(response)) {\n throw new Error(OidcError.InvalidBearerTokenResponse);\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,SAAS,QAAQ,YAAY;AAGtC,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,SAAS,QAAQ,YAAY;AACtC,SAAS,cAAc,QAAQ,YAAY;;AAE3C;AACA;AACA;AACA;AACA;;AAwBA,MAAM,QAAQ,GAAI,KAAc,IAC5B,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;AACjE,MAAM,sBAAsB,GAAG,CAAC,SAAkC,EAAE,GAAW,KAAc;EACzF,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,sBAAsB,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE;IAC5D,MAAM,CAAC,KAAK,CAAC,gCAAgC,GAAG,EAAE,CAAC;IACnD,OAAO,KAAK;EAChB;EACA,OAAO,IAAI;AACf,CAAC;AACD,MAAM,sBAAsB,GAAG,CAAC,SAAkC,EAAE,GAAW,KAAc;EACzF,IAAI,C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