@textrp/briij-js-sdk 41.0.1 → 43.0.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 (380) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/LICENSE +177 -177
  3. package/README.md +85 -3
  4. package/lib/@types/AESEncryptedSecretStoragePayload.js.map +1 -1
  5. package/lib/@types/IIdentityServerProvider.js.map +1 -1
  6. package/lib/@types/PushRules.js +14 -14
  7. package/lib/@types/PushRules.js.map +1 -1
  8. package/lib/@types/another-json.d.js.map +1 -1
  9. package/lib/@types/auth.d.ts +72 -1
  10. package/lib/@types/auth.d.ts.map +1 -1
  11. package/lib/@types/auth.js +57 -54
  12. package/lib/@types/auth.js.map +1 -1
  13. package/lib/@types/beacon.js +100 -100
  14. package/lib/@types/beacon.js.map +1 -1
  15. package/lib/@types/common.js.map +1 -1
  16. package/lib/@types/crypto.js.map +1 -1
  17. package/lib/@types/event.d.ts +59 -0
  18. package/lib/@types/event.d.ts.map +1 -1
  19. package/lib/@types/event.js +105 -102
  20. package/lib/@types/event.js.map +1 -1
  21. package/lib/@types/events.js.map +1 -1
  22. package/lib/@types/extensible_events.js +53 -53
  23. package/lib/@types/extensible_events.js.map +1 -1
  24. package/lib/@types/local_notifications.js.map +1 -1
  25. package/lib/@types/location.js +41 -41
  26. package/lib/@types/location.js.map +1 -1
  27. package/lib/@types/matrix-sdk-crypto-wasm.d.js.map +1 -1
  28. package/lib/@types/media.js.map +1 -1
  29. package/lib/@types/membership.js +39 -39
  30. package/lib/@types/membership.js.map +1 -1
  31. package/lib/@types/partials.js +25 -25
  32. package/lib/@types/partials.js.map +1 -1
  33. package/lib/@types/polls.js +46 -46
  34. package/lib/@types/polls.js.map +1 -1
  35. package/lib/@types/read_receipts.js +14 -14
  36. package/lib/@types/read_receipts.js.map +1 -1
  37. package/lib/@types/registration.js.map +1 -1
  38. package/lib/@types/search.js +14 -14
  39. package/lib/@types/search.js.map +1 -1
  40. package/lib/@types/signed.js.map +1 -1
  41. package/lib/@types/spaces.js.map +1 -1
  42. package/lib/@types/state_events.js.map +1 -1
  43. package/lib/@types/synapse.js.map +1 -1
  44. package/lib/@types/sync.js +18 -18
  45. package/lib/@types/sync.js.map +1 -1
  46. package/lib/@types/threepids.js +14 -14
  47. package/lib/@types/threepids.js.map +1 -1
  48. package/lib/@types/topic.js +47 -47
  49. package/lib/@types/topic.js.map +1 -1
  50. package/lib/@types/uia.js.map +1 -1
  51. package/lib/NamespacedValue.js +20 -20
  52. package/lib/NamespacedValue.js.map +1 -1
  53. package/lib/ReEmitter.js +16 -16
  54. package/lib/ReEmitter.js.map +1 -1
  55. package/lib/base64.js +32 -32
  56. package/lib/base64.js.map +1 -1
  57. package/lib/briij.d.ts +4 -0
  58. package/lib/briij.d.ts.map +1 -1
  59. package/lib/briij.js +4 -0
  60. package/lib/briij.js.map +1 -1
  61. package/lib/client.d.ts +48 -1
  62. package/lib/client.d.ts.map +1 -1
  63. package/lib/client.js +262 -108
  64. package/lib/client.js.map +1 -1
  65. package/lib/common-crypto/key-passphrase.js +19 -19
  66. package/lib/common-crypto/key-passphrase.js.map +1 -1
  67. package/lib/content-helpers.js +57 -57
  68. package/lib/content-helpers.js.map +1 -1
  69. package/lib/content-repo.js +36 -36
  70. package/lib/content-repo.js.map +1 -1
  71. package/lib/crypto/store/base.js +69 -69
  72. package/lib/crypto/store/base.js.map +1 -1
  73. package/lib/crypto/store/indexeddb-crypto-store-backend.js +58 -58
  74. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  75. package/lib/crypto/store/indexeddb-crypto-store.js +193 -193
  76. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  77. package/lib/crypto/store/localStorage-crypto-store.js +72 -72
  78. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  79. package/lib/crypto/store/memory-crypto-store.js +74 -74
  80. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  81. package/lib/crypto-api/CryptoEventHandlerMap.js.map +1 -1
  82. package/lib/crypto-api/key-passphrase.js +22 -22
  83. package/lib/crypto-api/key-passphrase.js.map +1 -1
  84. package/lib/crypto-api/keybackup.js.map +1 -1
  85. package/lib/crypto-api/recovery-key.js +20 -20
  86. package/lib/crypto-api/recovery-key.js.map +1 -1
  87. package/lib/digest.js +21 -21
  88. package/lib/digest.js.map +1 -1
  89. package/lib/extensible_events_v1/ExtensibleEvent.js +39 -39
  90. package/lib/extensible_events_v1/ExtensibleEvent.js.map +1 -1
  91. package/lib/extensible_events_v1/InvalidEventError.js +16 -16
  92. package/lib/extensible_events_v1/InvalidEventError.js.map +1 -1
  93. package/lib/extensible_events_v1/MessageEvent.js +39 -39
  94. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  95. package/lib/extensible_events_v1/PollEndEvent.js +29 -29
  96. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  97. package/lib/extensible_events_v1/PollResponseEvent.js +39 -39
  98. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  99. package/lib/extensible_events_v1/PollStartEvent.js +52 -52
  100. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  101. package/lib/extensible_events_v1/utilities.js +22 -22
  102. package/lib/extensible_events_v1/utilities.js.map +1 -1
  103. package/lib/feature.js +16 -16
  104. package/lib/feature.js.map +1 -1
  105. package/lib/http-api/method.js +14 -14
  106. package/lib/http-api/method.js.map +1 -1
  107. package/lib/http-api/prefix.js +26 -26
  108. package/lib/http-api/prefix.js.map +1 -1
  109. package/lib/indexeddb-helpers.js +21 -21
  110. package/lib/indexeddb-helpers.js.map +1 -1
  111. package/lib/indexeddb-worker.js +18 -18
  112. package/lib/indexeddb-worker.js.map +1 -1
  113. package/lib/matrixrtc/IKeyTransport.js +17 -17
  114. package/lib/matrixrtc/IKeyTransport.js.map +1 -1
  115. package/lib/matrixrtc/IMembershipManager.js +27 -27
  116. package/lib/matrixrtc/IMembershipManager.js.map +1 -1
  117. package/lib/matrixrtc/LivekitTransport.js +19 -19
  118. package/lib/matrixrtc/LivekitTransport.js.map +1 -1
  119. package/lib/matrixrtc/index.js +14 -14
  120. package/lib/matrixrtc/index.js.map +1 -1
  121. package/lib/matrixrtc/utils.js +27 -27
  122. package/lib/matrixrtc/utils.js.map +1 -1
  123. package/lib/models/ToDeviceMessage.js.map +1 -1
  124. package/lib/models/device.js +24 -24
  125. package/lib/models/device.js.map +1 -1
  126. package/lib/models/event-status.js +17 -17
  127. package/lib/models/event-status.js.map +1 -1
  128. package/lib/models/invites-ignorer-types.js +25 -25
  129. package/lib/models/invites-ignorer-types.js.map +1 -1
  130. package/lib/models/profile-keys.js +26 -26
  131. package/lib/models/profile-keys.js.map +1 -1
  132. package/lib/models/room-summary.js +26 -26
  133. package/lib/models/room-summary.js.map +1 -1
  134. package/lib/models/search-result.js +22 -22
  135. package/lib/models/search-result.js.map +1 -1
  136. package/lib/models/typed-event-emitter.js +122 -122
  137. package/lib/models/typed-event-emitter.js.map +1 -1
  138. package/lib/oidc/authorize.js +76 -76
  139. package/lib/oidc/authorize.js.map +1 -1
  140. package/lib/oidc/error.js +17 -17
  141. package/lib/oidc/error.js.map +1 -1
  142. package/lib/oidc/index.js +17 -17
  143. package/lib/oidc/index.js.map +1 -1
  144. package/lib/oidc/register.js +41 -41
  145. package/lib/oidc/register.js.map +1 -1
  146. package/lib/oidc/tokenRefresher.js +51 -51
  147. package/lib/oidc/tokenRefresher.js.map +1 -1
  148. package/lib/oidc/validate.js +59 -59
  149. package/lib/oidc/validate.js.map +1 -1
  150. package/lib/randomstring.js +35 -35
  151. package/lib/randomstring.js.map +1 -1
  152. package/lib/realtime-callbacks.js +39 -39
  153. package/lib/realtime-callbacks.js.map +1 -1
  154. package/lib/receipt-accumulator.js +44 -44
  155. package/lib/receipt-accumulator.js.map +1 -1
  156. package/lib/rendezvous/RendezvousChannel.js.map +1 -1
  157. package/lib/rendezvous/RendezvousCode.js.map +1 -1
  158. package/lib/rendezvous/RendezvousError.js +14 -14
  159. package/lib/rendezvous/RendezvousError.js.map +1 -1
  160. package/lib/rendezvous/RendezvousFailureReason.js +14 -14
  161. package/lib/rendezvous/RendezvousFailureReason.js.map +1 -1
  162. package/lib/rendezvous/RendezvousIntent.js +14 -14
  163. package/lib/rendezvous/RendezvousIntent.js.map +1 -1
  164. package/lib/rendezvous/RendezvousTransport.js.map +1 -1
  165. package/lib/rendezvous/channels/MSC4108SecureChannel.js +63 -63
  166. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  167. package/lib/rendezvous/channels/index.js +14 -14
  168. package/lib/rendezvous/channels/index.js.map +1 -1
  169. package/lib/rendezvous/index.js +14 -14
  170. package/lib/rendezvous/index.js.map +1 -1
  171. package/lib/rendezvous/transports/index.js +14 -14
  172. package/lib/rendezvous/transports/index.js.map +1 -1
  173. package/lib/rust-crypto/CrossSigningIdentity.js +29 -29
  174. package/lib/rust-crypto/CrossSigningIdentity.js.map +1 -1
  175. package/lib/rust-crypto/OutgoingRequestsManager.js +37 -37
  176. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  177. package/lib/rust-crypto/device-converter.js +30 -30
  178. package/lib/rust-crypto/device-converter.js.map +1 -1
  179. package/lib/rust-crypto/secret-storage.js +30 -30
  180. package/lib/rust-crypto/secret-storage.js.map +1 -1
  181. package/lib/service-types.js +14 -14
  182. package/lib/service-types.js.map +1 -1
  183. package/lib/store/local-storage-events-emitter.js +21 -21
  184. package/lib/store/local-storage-events-emitter.js.map +1 -1
  185. package/lib/sync-accumulator.js +50 -50
  186. package/lib/sync-accumulator.js.map +1 -1
  187. package/lib/thread-utils.js +20 -20
  188. package/lib/thread-utils.js.map +1 -1
  189. package/lib/types.js +34 -34
  190. package/lib/types.js.map +1 -1
  191. package/lib/utils/decryptAESSecretStorageItem.js +22 -22
  192. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  193. package/lib/utils/encryptAESSecretStorageItem.js +26 -26
  194. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  195. package/lib/utils/internal/deriveKeys.js +21 -21
  196. package/lib/utils/internal/deriveKeys.js.map +1 -1
  197. package/lib/utils/roomVersion.js +26 -26
  198. package/lib/utils/roomVersion.js.map +1 -1
  199. package/lib/version-support.js +26 -26
  200. package/lib/version-support.js.map +1 -1
  201. package/lib/wallet-recovery.d.ts +24 -0
  202. package/lib/wallet-recovery.d.ts.map +1 -0
  203. package/lib/wallet-recovery.js +232 -0
  204. package/lib/wallet-recovery.js.map +1 -0
  205. package/lib/webrtc/audioContext.js +24 -24
  206. package/lib/webrtc/audioContext.js.map +1 -1
  207. package/lib/webrtc/callEventTypes.js.map +1 -1
  208. package/lib/webrtc/stats/callFeedStatsReporter.js +14 -14
  209. package/lib/webrtc/stats/callFeedStatsReporter.js.map +1 -1
  210. package/lib/webrtc/stats/callStatsReportGatherer.js +14 -14
  211. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  212. package/lib/webrtc/stats/callStatsReportSummary.js.map +1 -1
  213. package/lib/webrtc/stats/connectionStats.js +14 -14
  214. package/lib/webrtc/stats/connectionStats.js.map +1 -1
  215. package/lib/webrtc/stats/connectionStatsBuilder.js +14 -14
  216. package/lib/webrtc/stats/connectionStatsBuilder.js.map +1 -1
  217. package/lib/webrtc/stats/connectionStatsReportBuilder.js +14 -14
  218. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  219. package/lib/webrtc/stats/groupCallStats.js +14 -14
  220. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  221. package/lib/webrtc/stats/media/mediaSsrcHandler.js +14 -14
  222. package/lib/webrtc/stats/media/mediaSsrcHandler.js.map +1 -1
  223. package/lib/webrtc/stats/media/mediaTrackHandler.js +14 -14
  224. package/lib/webrtc/stats/media/mediaTrackHandler.js.map +1 -1
  225. package/lib/webrtc/stats/media/mediaTrackStats.js +27 -27
  226. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  227. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +20 -20
  228. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  229. package/lib/webrtc/stats/statsReport.js +14 -14
  230. package/lib/webrtc/stats/statsReport.js.map +1 -1
  231. package/lib/webrtc/stats/statsReportEmitter.js +14 -14
  232. package/lib/webrtc/stats/statsReportEmitter.js.map +1 -1
  233. package/lib/webrtc/stats/trackStatsBuilder.js +4 -4
  234. package/lib/webrtc/stats/trackStatsBuilder.js.map +1 -1
  235. package/lib/webrtc/stats/transportStats.js.map +1 -1
  236. package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
  237. package/lib/webrtc/stats/valueFormatter.js +11 -11
  238. package/lib/webrtc/stats/valueFormatter.js.map +1 -1
  239. package/lib/xrpl/identity.d.ts +28 -0
  240. package/lib/xrpl/identity.d.ts.map +1 -0
  241. package/lib/xrpl/identity.js +213 -0
  242. package/lib/xrpl/identity.js.map +1 -0
  243. package/lib/xrpl/trust.d.ts +8 -0
  244. package/lib/xrpl/trust.d.ts.map +1 -0
  245. package/lib/xrpl/trust.js +61 -0
  246. package/lib/xrpl/trust.js.map +1 -0
  247. package/lib/xrpl/verification.d.ts +26 -0
  248. package/lib/xrpl/verification.d.ts.map +1 -0
  249. package/lib/xrpl/verification.js +295 -0
  250. package/lib/xrpl/verification.js.map +1 -0
  251. package/package.json +130 -129
  252. package/src/@types/AESEncryptedSecretStoragePayload.ts +29 -29
  253. package/src/@types/IIdentityServerProvider.ts +24 -24
  254. package/src/@types/PushRules.ts +208 -208
  255. package/src/@types/another-json.d.ts +19 -19
  256. package/src/@types/auth.ts +340 -258
  257. package/src/@types/beacon.ts +140 -140
  258. package/src/@types/common.ts +24 -24
  259. package/src/@types/crypto.ts +71 -71
  260. package/src/@types/event.ts +508 -449
  261. package/src/@types/events.ts +119 -119
  262. package/src/@types/extensible_events.ts +147 -147
  263. package/src/@types/local_notifications.ts +19 -19
  264. package/src/@types/location.ts +92 -92
  265. package/src/@types/matrix-sdk-crypto-wasm.d.ts +39 -39
  266. package/src/@types/media.ts +245 -245
  267. package/src/@types/membership.ts +57 -57
  268. package/src/@types/partials.ts +103 -103
  269. package/src/@types/polls.ts +120 -120
  270. package/src/@types/read_receipts.ts +61 -61
  271. package/src/@types/registration.ts +102 -102
  272. package/src/@types/search.ts +119 -119
  273. package/src/@types/signed.ts +25 -25
  274. package/src/@types/spaces.ts +37 -37
  275. package/src/@types/state_events.ts +153 -153
  276. package/src/@types/synapse.ts +40 -40
  277. package/src/@types/sync.ts +27 -27
  278. package/src/@types/threepids.ts +29 -29
  279. package/src/@types/topic.ts +69 -69
  280. package/src/@types/uia.ts +24 -24
  281. package/src/NamespacedValue.ts +121 -121
  282. package/src/ReEmitter.ts +93 -93
  283. package/src/base64.ts +86 -86
  284. package/src/briij.ts +4 -0
  285. package/src/client.ts +183 -10
  286. package/src/common-crypto/README.md +4 -4
  287. package/src/common-crypto/key-passphrase.ts +43 -43
  288. package/src/content-helpers.ts +298 -298
  289. package/src/content-repo.ts +122 -122
  290. package/src/crypto/store/base.ts +388 -388
  291. package/src/crypto/store/indexeddb-crypto-store-backend.ts +655 -655
  292. package/src/crypto/store/indexeddb-crypto-store.ts +555 -555
  293. package/src/crypto/store/localStorage-crypto-store.ts +409 -409
  294. package/src/crypto/store/memory-crypto-store.ts +326 -326
  295. package/src/crypto-api/CryptoEventHandlerMap.ts +42 -42
  296. package/src/crypto-api/key-passphrase.ts +58 -58
  297. package/src/crypto-api/keybackup.ts +114 -114
  298. package/src/crypto-api/recovery-key.ts +69 -69
  299. package/src/digest.ts +34 -34
  300. package/src/extensible_events_v1/ExtensibleEvent.ts +58 -58
  301. package/src/extensible_events_v1/InvalidEventError.ts +24 -24
  302. package/src/extensible_events_v1/MessageEvent.ts +143 -143
  303. package/src/extensible_events_v1/PollEndEvent.ts +97 -97
  304. package/src/extensible_events_v1/PollResponseEvent.ts +148 -148
  305. package/src/extensible_events_v1/PollStartEvent.ts +207 -207
  306. package/src/extensible_events_v1/utilities.ts +35 -35
  307. package/src/feature.ts +88 -88
  308. package/src/http-api/method.ts +25 -25
  309. package/src/http-api/prefix.ts +48 -48
  310. package/src/indexeddb-helpers.ts +50 -50
  311. package/src/indexeddb-worker.ts +24 -24
  312. package/src/matrixrtc/IKeyTransport.ts +63 -63
  313. package/src/matrixrtc/IMembershipManager.ts +120 -120
  314. package/src/matrixrtc/LivekitTransport.ts +46 -46
  315. package/src/matrixrtc/index.ts +24 -24
  316. package/src/matrixrtc/utils.ts +71 -71
  317. package/src/models/ToDeviceMessage.ts +38 -38
  318. package/src/models/device.ts +85 -85
  319. package/src/models/event-status.ts +39 -39
  320. package/src/models/invites-ignorer-types.ts +58 -58
  321. package/src/models/profile-keys.ts +33 -33
  322. package/src/models/room-summary.ts +78 -78
  323. package/src/models/search-result.ts +57 -57
  324. package/src/models/typed-event-emitter.ts +246 -246
  325. package/src/oidc/authorize.ts +279 -279
  326. package/src/oidc/error.ts +33 -33
  327. package/src/oidc/index.ts +33 -33
  328. package/src/oidc/register.ts +163 -163
  329. package/src/oidc/tokenRefresher.ts +184 -184
  330. package/src/oidc/validate.ts +265 -265
  331. package/src/randomstring.ts +103 -103
  332. package/src/realtime-callbacks.ts +191 -191
  333. package/src/receipt-accumulator.ts +189 -189
  334. package/src/rendezvous/RendezvousChannel.ts +48 -48
  335. package/src/rendezvous/RendezvousCode.ts +25 -25
  336. package/src/rendezvous/RendezvousError.ts +26 -26
  337. package/src/rendezvous/RendezvousFailureReason.ts +49 -49
  338. package/src/rendezvous/RendezvousIntent.ts +20 -20
  339. package/src/rendezvous/RendezvousTransport.ts +58 -58
  340. package/src/rendezvous/channels/MSC4108SecureChannel.ts +270 -270
  341. package/src/rendezvous/channels/index.ts +17 -17
  342. package/src/rendezvous/index.ts +25 -25
  343. package/src/rendezvous/transports/index.ts +17 -17
  344. package/src/rust-crypto/CrossSigningIdentity.ts +195 -195
  345. package/src/rust-crypto/OutgoingRequestsManager.ts +170 -170
  346. package/src/rust-crypto/device-converter.ts +128 -128
  347. package/src/rust-crypto/secret-storage.ts +60 -60
  348. package/src/service-types.ts +20 -20
  349. package/src/store/local-storage-events-emitter.ts +46 -46
  350. package/src/sync-accumulator.ts +779 -779
  351. package/src/thread-utils.ts +31 -31
  352. package/src/types.ts +59 -59
  353. package/src/utils/decryptAESSecretStorageItem.ts +54 -54
  354. package/src/utils/encryptAESSecretStorageItem.ts +73 -73
  355. package/src/utils/internal/deriveKeys.ts +63 -63
  356. package/src/utils/roomVersion.ts +35 -35
  357. package/src/version-support.ts +50 -50
  358. package/src/wallet-recovery.ts +252 -0
  359. package/src/webrtc/audioContext.ts +44 -44
  360. package/src/webrtc/callEventTypes.ts +101 -101
  361. package/src/webrtc/stats/callFeedStatsReporter.ts +91 -91
  362. package/src/webrtc/stats/callStatsReportGatherer.ts +219 -219
  363. package/src/webrtc/stats/callStatsReportSummary.ts +30 -30
  364. package/src/webrtc/stats/connectionStats.ts +47 -47
  365. package/src/webrtc/stats/connectionStatsBuilder.ts +28 -28
  366. package/src/webrtc/stats/connectionStatsReportBuilder.ts +140 -140
  367. package/src/webrtc/stats/groupCallStats.ts +93 -93
  368. package/src/webrtc/stats/media/mediaSsrcHandler.ts +57 -57
  369. package/src/webrtc/stats/media/mediaTrackHandler.ts +70 -70
  370. package/src/webrtc/stats/media/mediaTrackStats.ts +176 -176
  371. package/src/webrtc/stats/media/mediaTrackStatsHandler.ts +90 -90
  372. package/src/webrtc/stats/statsReport.ts +133 -133
  373. package/src/webrtc/stats/statsReportEmitter.ts +49 -49
  374. package/src/webrtc/stats/trackStatsBuilder.ts +207 -207
  375. package/src/webrtc/stats/transportStats.ts +26 -26
  376. package/src/webrtc/stats/transportStatsBuilder.ts +48 -48
  377. package/src/webrtc/stats/valueFormatter.ts +27 -27
  378. package/src/xrpl/identity.ts +245 -0
  379. package/src/xrpl/trust.ts +64 -0
  380. package/src/xrpl/verification.ts +284 -0
@@ -1 +1 @@
1
- {"version":3,"file":"typed-event-emitter.js","names":["EventEmitter","EventEmitterEvents","TypedEventEmitter","addListener","event","listener","emit","_len","arguments","length","args","Array","_key","emitPromised","_arguments","_this","_asyncToGenerator","_len2","_key2","listeners","Promise","allSettled","map","l","then","listenerCount","off","on","once","prependListener","prependOnceListener","removeAllListeners","undefined","removeListener","rawListeners"],"sources":["../../src/models/typed-event-emitter.ts"],"sourcesContent":["/*\r\nCopyright 2021 The Matrix.org Foundation C.I.C.\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\n// eslint-disable-next-line no-restricted-imports\r\nimport { EventEmitter } from \"events\";\r\n\r\n/** Events emitted by EventEmitter itself */\r\nexport enum EventEmitterEvents {\r\n NewListener = \"newListener\",\r\n RemoveListener = \"removeListener\",\r\n Error = \"error\",\r\n}\r\n\r\ntype AnyListener = (...args: any) => any;\r\n\r\n/** Base class for types mapping from event name to the type of listeners to that event */\r\nexport type ListenerMap<E extends string> = { [eventName in E]: AnyListener };\r\n\r\ntype EventEmitterEventListener = (eventName: string, listener: AnyListener) => void;\r\ntype EventEmitterErrorListener = (error: Error) => void;\r\n\r\n/**\r\n * The expected type of a listener function for a particular event.\r\n *\r\n * Type parameters:\r\n * * `E` - List of all events emitted by the `TypedEventEmitter`. Normally an enum type.\r\n * * `A` - A type providing mappings from event names to listener types.\r\n * * `T` - The name of the actual event that this listener is for. Normally one of the types in `E` or\r\n * {@link EventEmitterEvents}.\r\n */\r\nexport type Listener<E extends string, A extends ListenerMap<E>, T extends E | EventEmitterEvents> = T extends E\r\n ? A[T]\r\n : T extends EventEmitterEvents\r\n ? EventEmitterErrorListener\r\n : EventEmitterEventListener;\r\n\r\n/**\r\n * Typed Event Emitter class which can act as a Base Model for all our model\r\n * and communication events.\r\n * This makes it much easier for us to distinguish between events, as we now need\r\n * to properly type this, so that our events are not stringly-based and prone\r\n * to silly typos.\r\n *\r\n * Type parameters:\r\n * * `Events` - List of all events emitted by this `TypedEventEmitter`. Normally an enum type.\r\n * * `Arguments` - A {@link ListenerMap} type providing mappings from event names to listener types.\r\n * * `SuperclassArguments` - TODO: not really sure. Alternative listener mappings, I think? But only honoured for `.emit`?\r\n */\r\nexport class TypedEventEmitter<\r\n Events extends string,\r\n Arguments extends ListenerMap<Events>,\r\n SuperclassArguments extends ListenerMap<any> = Arguments,\r\n> extends EventEmitter {\r\n /**\r\n * Alias for {@link on}.\r\n */\r\n public addListener<T extends Events | EventEmitterEvents>(\r\n event: T,\r\n listener: Listener<Events, Arguments, T>,\r\n ): this {\r\n return super.addListener(event, listener);\r\n }\r\n\r\n /**\r\n * Synchronously calls each of the listeners registered for the event named\r\n * `event`, in the order they were registered, passing the supplied arguments\r\n * to each.\r\n *\r\n * @param event - The name of the event to emit\r\n * @param args - Arguments to pass to the listener\r\n * @returns `true` if the event had listeners, `false` otherwise.\r\n */\r\n public emit<T extends Events>(event: T, ...args: Parameters<SuperclassArguments[T]>): boolean;\r\n public emit<T extends Events>(event: T, ...args: Parameters<Arguments[T]>): boolean;\r\n public emit<T extends Events>(event: T, ...args: any[]): boolean {\r\n return super.emit(event, ...args);\r\n }\r\n\r\n /**\r\n * Similar to `emit` but calls all listeners within a `Promise.all` and returns the promise chain\r\n * @param event - The name of the event to emit\r\n * @param args - Arguments to pass to the listener\r\n * @returns `true` if the event had listeners, `false` otherwise.\r\n */\r\n public async emitPromised<T extends Events>(\r\n event: T,\r\n ...args: Parameters<SuperclassArguments[T]>\r\n ): Promise<boolean>;\r\n public async emitPromised<T extends Events>(event: T, ...args: Parameters<Arguments[T]>): Promise<boolean>;\r\n public async emitPromised<T extends Events>(event: T, ...args: any[]): Promise<boolean> {\r\n const listeners = this.listeners(event);\r\n return Promise.allSettled(listeners.map((l) => l(...args))).then(() => {\r\n return listeners.length > 0;\r\n });\r\n }\r\n\r\n /**\r\n * Returns the number of listeners listening to the event named `event`.\r\n *\r\n * @param event - The name of the event being listened for\r\n */\r\n public listenerCount(event: Events | EventEmitterEvents): number {\r\n return super.listenerCount(event);\r\n }\r\n\r\n /**\r\n * Returns a copy of the array of listeners for the event named `event`.\r\n */\r\n public listeners(event: Events | EventEmitterEvents): ReturnType<EventEmitter[\"listeners\"]> {\r\n return super.listeners(event);\r\n }\r\n\r\n /**\r\n * Alias for {@link removeListener}\r\n */\r\n public off<T extends Events | EventEmitterEvents>(event: T, listener: Listener<Events, Arguments, T>): this {\r\n return super.off(event, listener);\r\n }\r\n\r\n /**\r\n * Adds the `listener` function to the end of the listeners array for the\r\n * event named `event`.\r\n *\r\n * No checks are made to see if the `listener` has already been added. Multiple calls\r\n * passing the same combination of `event` and `listener` will result in the `listener`\r\n * being added, and called, multiple times.\r\n *\r\n * By default, event listeners are invoked in the order they are added. The\r\n * {@link prependListener} method can be used as an alternative to add the\r\n * event listener to the beginning of the listeners array.\r\n *\r\n * @param event - The name of the event.\r\n * @param listener - The callback function\r\n *\r\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\r\n */\r\n public on<T extends Events | EventEmitterEvents>(event: T, listener: Listener<Events, Arguments, T>): this {\r\n return super.on(event, listener);\r\n }\r\n\r\n /**\r\n * Adds a **one-time** `listener` function for the event named `event`. The\r\n * next time `event` is triggered, this listener is removed and then invoked.\r\n *\r\n * Returns a reference to the `EventEmitter`, so that calls can be chained.\r\n *\r\n * By default, event listeners are invoked in the order they are added.\r\n * The {@link prependOnceListener} method can be used as an alternative to add the\r\n * event listener to the beginning of the listeners array.\r\n *\r\n * @param event - The name of the event.\r\n * @param listener - The callback function\r\n *\r\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\r\n */\r\n public once<T extends Events | EventEmitterEvents>(event: T, listener: Listener<Events, Arguments, T>): this {\r\n return super.once(event, listener);\r\n }\r\n\r\n /**\r\n * Adds the `listener` function to the _beginning_ of the listeners array for the\r\n * event named `event`.\r\n *\r\n * No checks are made to see if the `listener` has already been added. Multiple calls\r\n * passing the same combination of `event` and `listener` will result in the `listener`\r\n * being added, and called, multiple times.\r\n *\r\n * @param event - The name of the event.\r\n * @param listener - The callback function\r\n *\r\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\r\n */\r\n public prependListener<T extends Events | EventEmitterEvents>(\r\n event: T,\r\n listener: Listener<Events, Arguments, T>,\r\n ): this {\r\n return super.prependListener(event, listener);\r\n }\r\n\r\n /**\r\n * Adds a **one-time**`listener` function for the event named `event` to the _beginning_ of the listeners array.\r\n * The next time `event` is triggered, this listener is removed, and then invoked.\r\n *\r\n * @param event - The name of the event.\r\n * @param listener - The callback function\r\n *\r\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\r\n */\r\n public prependOnceListener<T extends Events | EventEmitterEvents>(\r\n event: T,\r\n listener: Listener<Events, Arguments, T>,\r\n ): this {\r\n return super.prependOnceListener(event, listener);\r\n }\r\n\r\n /**\r\n * Removes all listeners, or those of the specified `event`.\r\n *\r\n * It is bad practice to remove listeners added elsewhere in the code,\r\n * particularly when the `EventEmitter` instance was created by some other\r\n * component or module (e.g. sockets or file streams).\r\n *\r\n * @param event - The name of the event. If undefined, all listeners everywhere are removed.\r\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\r\n */\r\n public removeAllListeners(event?: Events | EventEmitterEvents): this {\r\n // EventEmitter::removeAllListeners uses `arguments.length` to determine undefined case\r\n if (event === undefined) {\r\n return super.removeAllListeners();\r\n }\r\n return super.removeAllListeners(event);\r\n }\r\n\r\n /**\r\n * Removes the specified `listener` from the listener array for the event named `event`.\r\n *\r\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\r\n */\r\n public removeListener<T extends Events | EventEmitterEvents>(\r\n event: T,\r\n listener: Listener<Events, Arguments, T>,\r\n ): this {\r\n return super.removeListener(event, listener);\r\n }\r\n\r\n /**\r\n * Returns a copy of the array of listeners for the event named `eventName`,\r\n * including any wrappers (such as those created by `.once()`).\r\n */\r\n public rawListeners(event: Events | EventEmitterEvents): ReturnType<EventEmitter[\"rawListeners\"]> {\r\n return super.rawListeners(event);\r\n }\r\n}\r\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,SAASA,YAAY,QAAQ,QAAQ;;AAErC;AACA,WAAYC,kBAAkB,0BAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAA,OAAlBA,kBAAkB;AAAA;;AAQ9B;;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,iBAAiB,SAIpBF,YAAY,CAAC;EACnB;AACJ;AACA;EACWG,WAAWA,CACdC,KAAQ,EACRC,QAAwC,EACpC;IACJ,OAAO,KAAK,CAACF,WAAW,CAACC,KAAK,EAAEC,QAAQ,CAAC;EAC7C;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;EAGWC,IAAIA,CAAmBF,KAAQ,EAA2B;IAAA,SAAAG,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAAtBC,IAAI,OAAAC,KAAA,CAAAJ,IAAA,OAAAA,IAAA,WAAAK,IAAA,MAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA;MAAJF,IAAI,CAAAE,IAAA,QAAAJ,SAAA,CAAAI,IAAA;IAAA;IAC3C,OAAO,KAAK,CAACN,IAAI,CAACF,KAAK,EAAE,GAAGM,IAAI,CAAC;EACrC;;EAEA;AACJ;AACA;AACA;AACA;AACA;;EAMiBG,YAAYA,CAAmBT,KAAQ,EAAoC;IAAA,IAAAU,UAAA,GAAAN,SAAA;MAAAO,KAAA;IAAA,OAAAC,iBAAA;MA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ACxB,KAAK,EAAEC,QAAQ,CAAC;EACtC;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACWwB,eAAeA,CAClBzB,KAAQ,EACRC,QAAwC,EACpC;IACJ,OAAO,KAAK,CAACwB,eAAe,CAACzB,KAAK,EAAEC,QAAQ,CAAC;EACjD;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACWyB,mBAAmBA,CACtB1B,KAAQ,EACRC,QAAwC,EACpC;IACJ,OAAO,KAAK,CAACyB,mBAAmB,CAAC1B,KAAK,EAAEC,QAAQ,CAAC;EACrD;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACW0B,kBAAkBA,CAAC3B,KAAmC,EAAQ;IACjE;IACA,IAAIA,KAAK,KAAK4B,SAAS,EAAE;MACrB,OAAO,KAAK,CAACD,kBAAkB,CAAC,CAAC;IACrC;IACA,OAAO,KAAK,CAACA,kBAAkB,CAAC3B,KAAK,CAAC;EAC1C;;EAEA;AACJ;AACA;AACA;AACA;EACW6B,cAAcA,CACjB7B,KAAQ,EACRC,QAAwC,EACpC;IACJ,OAAO,KAAK,CAAC4B,cAAc,CAAC7B,KAAK,EAAEC,QAAQ,CAAC;EAChD;;EAEA;AACJ;AACA;AACA;EACW6B,YAAYA,CAAC9B,KAAkC,EAA4C;IAC9F,OAAO,KAAK,CAAC8B,YAAY,CAAC9B,KAAK,CAAC;EACpC;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"typed-event-emitter.js","names":["EventEmitter","EventEmitterEvents","TypedEventEmitter","addListener","event","listener","emit","_len","arguments","length","args","Array","_key","emitPromised","_arguments","_this","_asyncToGenerator","_len2","_key2","listeners","Promise","allSettled","map","l","then","listenerCount","off","on","once","prependListener","prependOnceListener","removeAllListeners","undefined","removeListener","rawListeners"],"sources":["../../src/models/typed-event-emitter.ts"],"sourcesContent":["/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// eslint-disable-next-line no-restricted-imports\nimport { EventEmitter } from \"events\";\n\n/** Events emitted by EventEmitter itself */\nexport enum EventEmitterEvents {\n NewListener = \"newListener\",\n RemoveListener = \"removeListener\",\n Error = \"error\",\n}\n\ntype AnyListener = (...args: any) => any;\n\n/** Base class for types mapping from event name to the type of listeners to that event */\nexport type ListenerMap<E extends string> = { [eventName in E]: AnyListener };\n\ntype EventEmitterEventListener = (eventName: string, listener: AnyListener) => void;\ntype EventEmitterErrorListener = (error: Error) => void;\n\n/**\n * The expected type of a listener function for a particular event.\n *\n * Type parameters:\n * * `E` - List of all events emitted by the `TypedEventEmitter`. Normally an enum type.\n * * `A` - A type providing mappings from event names to listener types.\n * * `T` - The name of the actual event that this listener is for. Normally one of the types in `E` or\n * {@link EventEmitterEvents}.\n */\nexport type Listener<E extends string, A extends ListenerMap<E>, T extends E | EventEmitterEvents> = T extends E\n ? A[T]\n : T extends EventEmitterEvents\n ? EventEmitterErrorListener\n : EventEmitterEventListener;\n\n/**\n * Typed Event Emitter class which can act as a Base Model for all our model\n * and communication events.\n * This makes it much easier for us to distinguish between events, as we now need\n * to properly type this, so that our events are not stringly-based and prone\n * to silly typos.\n *\n * Type parameters:\n * * `Events` - List of all events emitted by this `TypedEventEmitter`. Normally an enum type.\n * * `Arguments` - A {@link ListenerMap} type providing mappings from event names to listener types.\n * * `SuperclassArguments` - TODO: not really sure. Alternative listener mappings, I think? But only honoured for `.emit`?\n */\nexport class TypedEventEmitter<\n Events extends string,\n Arguments extends ListenerMap<Events>,\n SuperclassArguments extends ListenerMap<any> = Arguments,\n> extends EventEmitter {\n /**\n * Alias for {@link on}.\n */\n public addListener<T extends Events | EventEmitterEvents>(\n event: T,\n listener: Listener<Events, Arguments, T>,\n ): this {\n return super.addListener(event, listener);\n }\n\n /**\n * Synchronously calls each of the listeners registered for the event named\n * `event`, in the order they were registered, passing the supplied arguments\n * to each.\n *\n * @param event - The name of the event to emit\n * @param args - Arguments to pass to the listener\n * @returns `true` if the event had listeners, `false` otherwise.\n */\n public emit<T extends Events>(event: T, ...args: Parameters<SuperclassArguments[T]>): boolean;\n public emit<T extends Events>(event: T, ...args: Parameters<Arguments[T]>): boolean;\n public emit<T extends Events>(event: T, ...args: any[]): boolean {\n return super.emit(event, ...args);\n }\n\n /**\n * Similar to `emit` but calls all listeners within a `Promise.all` and returns the promise chain\n * @param event - The name of the event to emit\n * @param args - Arguments to pass to the listener\n * @returns `true` if the event had listeners, `false` otherwise.\n */\n public async emitPromised<T extends Events>(\n event: T,\n ...args: Parameters<SuperclassArguments[T]>\n ): Promise<boolean>;\n public async emitPromised<T extends Events>(event: T, ...args: Parameters<Arguments[T]>): Promise<boolean>;\n public async emitPromised<T extends Events>(event: T, ...args: any[]): Promise<boolean> {\n const listeners = this.listeners(event);\n return Promise.allSettled(listeners.map((l) => l(...args))).then(() => {\n return listeners.length > 0;\n });\n }\n\n /**\n * Returns the number of listeners listening to the event named `event`.\n *\n * @param event - The name of the event being listened for\n */\n public listenerCount(event: Events | EventEmitterEvents): number {\n return super.listenerCount(event);\n }\n\n /**\n * Returns a copy of the array of listeners for the event named `event`.\n */\n public listeners(event: Events | EventEmitterEvents): ReturnType<EventEmitter[\"listeners\"]> {\n return super.listeners(event);\n }\n\n /**\n * Alias for {@link removeListener}\n */\n public off<T extends Events | EventEmitterEvents>(event: T, listener: Listener<Events, Arguments, T>): this {\n return super.off(event, listener);\n }\n\n /**\n * Adds the `listener` function to the end of the listeners array for the\n * event named `event`.\n *\n * No checks are made to see if the `listener` has already been added. Multiple calls\n * passing the same combination of `event` and `listener` will result in the `listener`\n * being added, and called, multiple times.\n *\n * By default, event listeners are invoked in the order they are added. The\n * {@link prependListener} method can be used as an alternative to add the\n * event listener to the beginning of the listeners array.\n *\n * @param event - The name of the event.\n * @param listener - The callback function\n *\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\n */\n public on<T extends Events | EventEmitterEvents>(event: T, listener: Listener<Events, Arguments, T>): this {\n return super.on(event, listener);\n }\n\n /**\n * Adds a **one-time** `listener` function for the event named `event`. The\n * next time `event` is triggered, this listener is removed and then invoked.\n *\n * Returns a reference to the `EventEmitter`, so that calls can be chained.\n *\n * By default, event listeners are invoked in the order they are added.\n * The {@link prependOnceListener} method can be used as an alternative to add the\n * event listener to the beginning of the listeners array.\n *\n * @param event - The name of the event.\n * @param listener - The callback function\n *\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\n */\n public once<T extends Events | EventEmitterEvents>(event: T, listener: Listener<Events, Arguments, T>): this {\n return super.once(event, listener);\n }\n\n /**\n * Adds the `listener` function to the _beginning_ of the listeners array for the\n * event named `event`.\n *\n * No checks are made to see if the `listener` has already been added. Multiple calls\n * passing the same combination of `event` and `listener` will result in the `listener`\n * being added, and called, multiple times.\n *\n * @param event - The name of the event.\n * @param listener - The callback function\n *\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\n */\n public prependListener<T extends Events | EventEmitterEvents>(\n event: T,\n listener: Listener<Events, Arguments, T>,\n ): this {\n return super.prependListener(event, listener);\n }\n\n /**\n * Adds a **one-time**`listener` function for the event named `event` to the _beginning_ of the listeners array.\n * The next time `event` is triggered, this listener is removed, and then invoked.\n *\n * @param event - The name of the event.\n * @param listener - The callback function\n *\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\n */\n public prependOnceListener<T extends Events | EventEmitterEvents>(\n event: T,\n listener: Listener<Events, Arguments, T>,\n ): this {\n return super.prependOnceListener(event, listener);\n }\n\n /**\n * Removes all listeners, or those of the specified `event`.\n *\n * It is bad practice to remove listeners added elsewhere in the code,\n * particularly when the `EventEmitter` instance was created by some other\n * component or module (e.g. sockets or file streams).\n *\n * @param event - The name of the event. If undefined, all listeners everywhere are removed.\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\n */\n public removeAllListeners(event?: Events | EventEmitterEvents): this {\n // EventEmitter::removeAllListeners uses `arguments.length` to determine undefined case\n if (event === undefined) {\n return super.removeAllListeners();\n }\n return super.removeAllListeners(event);\n }\n\n /**\n * Removes the specified `listener` from the listener array for the event named `event`.\n *\n * @returns a reference to the `EventEmitter`, so that calls can be chained.\n */\n public removeListener<T extends Events | EventEmitterEvents>(\n event: T,\n listener: Listener<Events, Arguments, T>,\n ): this {\n return super.removeListener(event, listener);\n }\n\n /**\n * Returns a copy of the array of listeners for the event named `eventName`,\n * including any wrappers (such as those created by `.once()`).\n */\n public rawListeners(event: Events | EventEmitterEvents): ReturnType<EventEmitter[\"rawListeners\"]> {\n return super.rawListeners(event);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,SAASA,YAAY,QAAQ,QAAQ;;AAErC;AACA,WAAYC,kBAAkB,0BAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAA,OAAlBA,kBAAkB;AAAA;;AAQ9B;;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,iBAAiB,SAIpBF,YAAY,CAAC;EACnB;AACJ;AACA;EACWG,WAAWA,CACdC,KAAQ,EACRC,QAAwC,EACpC;IACJ,OAAO,KAAK,CAACF,WAAW,CAACC,KAAK,EAAEC,QAAQ,CAAC;EAC7C;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;EAGWC,IAAIA,CAAmBF,KAAQ,EAA2B;IAAA,SAAAG,IAAA,GAAAC,SAAA,CAAAC,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kC,EAA4C;IAC9F,OAAO,KAAK,CAAC8B,YAAY,CAAC9B,KAAK,CAAC;EACpC;AACJ","ignoreList":[]}
@@ -2,20 +2,20 @@ import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
2
  import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
3
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
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; }
5
- /*
6
- Copyright 2023 The Matrix.org Foundation C.I.C.
7
-
8
- Licensed under the Apache License, Version 2.0 (the "License");
9
- you may not use this file except in compliance with the License.
10
- You may obtain a copy of the License at
11
-
12
- http://www.apache.org/licenses/LICENSE-2.0
13
-
14
- Unless required by applicable law or agreed to in writing, software
15
- distributed under the License is distributed on an "AS IS" BASIS,
16
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
- See the License for the specific language governing permissions and
18
- limitations under the License.
5
+ /*
6
+ Copyright 2023 The Matrix.org Foundation C.I.C.
7
+
8
+ Licensed under the Apache License, Version 2.0 (the "License");
9
+ you may not use this file except in compliance with the License.
10
+ You may obtain a copy of the License at
11
+
12
+ http://www.apache.org/licenses/LICENSE-2.0
13
+
14
+ Unless required by applicable law or agreed to in writing, software
15
+ distributed under the License is distributed on an "AS IS" BASIS,
16
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ See the License for the specific language governing permissions and
18
+ limitations under the License.
19
19
  */
20
20
 
21
21
  import { Log, OidcClient, SigninResponse, SigninState, WebStorageStateStore } from "oidc-client-ts";
@@ -28,16 +28,16 @@ import { encodeUnpaddedBase64Url } from "../base64.js";
28
28
 
29
29
  // reexport for backwards compatibility
30
30
 
31
- /**
32
- * Authorization parameters which are used in the authentication request of an OIDC auth code flow.
33
- *
34
- * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.
31
+ /**
32
+ * Authorization parameters which are used in the authentication request of an OIDC auth code flow.
33
+ *
34
+ * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.
35
35
  */
36
36
 
37
- /**
38
- * @experimental
39
- * Generate the scope used in authorization request with OIDC OP
40
- * @returns scope
37
+ /**
38
+ * @experimental
39
+ * Generate the scope used in authorization request with OIDC OP
40
+ * @returns scope
41
41
  */
42
42
  export var generateScope = deviceId => {
43
43
  var safeDeviceId = deviceId !== null && deviceId !== void 0 ? deviceId : secureRandomString(10);
@@ -60,13 +60,13 @@ var generateCodeChallenge = /*#__PURE__*/function () {
60
60
  };
61
61
  }();
62
62
 
63
- /**
64
- * Generate authorization params to pass to {@link generateAuthorizationUrl}.
65
- *
66
- * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.
67
- *
68
- * @param redirectUri - absolute url for OP to redirect to after authorization
69
- * @returns AuthorizationParams
63
+ /**
64
+ * Generate authorization params to pass to {@link generateAuthorizationUrl}.
65
+ *
66
+ * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.
67
+ *
68
+ * @param redirectUri - absolute url for OP to redirect to after authorization
69
+ * @returns AuthorizationParams
70
70
  */
71
71
  export var generateAuthorizationParams = _ref2 => {
72
72
  var {
@@ -81,14 +81,14 @@ export var generateAuthorizationParams = _ref2 => {
81
81
  };
82
82
  };
83
83
 
84
- /**
85
- * @deprecated use generateOidcAuthorizationUrl
86
- * Generate a URL to attempt authorization with the OP
87
- * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
88
- * @param authorizationUrl - endpoint to attempt authorization with the OP
89
- * @param clientId - id of this client as registered with the OP
90
- * @param authorizationParams - params to be used in the url
91
- * @returns a Promise with the url as a string
84
+ /**
85
+ * @deprecated use generateOidcAuthorizationUrl
86
+ * Generate a URL to attempt authorization with the OP
87
+ * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
88
+ * @param authorizationUrl - endpoint to attempt authorization with the OP
89
+ * @param clientId - id of this client as registered with the OP
90
+ * @param authorizationParams - params to be used in the url
91
+ * @returns a Promise with the url as a string
92
92
  */
93
93
  export var generateAuthorizationUrl = /*#__PURE__*/function () {
94
94
  var _ref4 = _asyncToGenerator(function* (authorizationUrl, clientId, _ref3) {
@@ -116,21 +116,21 @@ export var generateAuthorizationUrl = /*#__PURE__*/function () {
116
116
  };
117
117
  }();
118
118
 
119
- /**
120
- * @experimental
121
- * Generate a URL to attempt authorization with the OP
122
- * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
123
- * @param metadata - validated metadata from OP discovery
124
- * @param clientId - this client's id as registered with the OP
125
- * @param homeserverUrl - used to establish the session on return from the OP
126
- * @param identityServerUrl - used to establish the session on return from the OP
127
- * @param nonce - state
128
- * @param prompt - indicates to the OP which flow the user should see - eg login or registration
129
- * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter
130
- * @param urlState - value to append to the opaque state identifier to uniquely identify the callback
131
- * @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.
132
- * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.
133
- * @returns a Promise with the url as a string
119
+ /**
120
+ * @experimental
121
+ * Generate a URL to attempt authorization with the OP
122
+ * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
123
+ * @param metadata - validated metadata from OP discovery
124
+ * @param clientId - this client's id as registered with the OP
125
+ * @param homeserverUrl - used to establish the session on return from the OP
126
+ * @param identityServerUrl - used to establish the session on return from the OP
127
+ * @param nonce - state
128
+ * @param prompt - indicates to the OP which flow the user should see - eg login or registration
129
+ * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter
130
+ * @param urlState - value to append to the opaque state identifier to uniquely identify the callback
131
+ * @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.
132
+ * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.
133
+ * @returns a Promise with the url as a string
134
134
  */
135
135
  export var generateOidcAuthorizationUrl = /*#__PURE__*/function () {
136
136
  var _ref6 = _asyncToGenerator(function* (_ref5) {
@@ -177,14 +177,14 @@ export var generateOidcAuthorizationUrl = /*#__PURE__*/function () {
177
177
  };
178
178
  }();
179
179
 
180
- /**
181
- * Normalize token_type to use capital case to make consuming the token response easier
182
- * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: "bearer"
183
- * Later, when used in auth headers it is case sensitive and must be Bearer
184
- * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4
185
- *
186
- * @param response - validated token response
187
- * @returns response with token_type set to 'Bearer'
180
+ /**
181
+ * Normalize token_type to use capital case to make consuming the token response easier
182
+ * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: "bearer"
183
+ * Later, when used in auth headers it is case sensitive and must be Bearer
184
+ * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4
185
+ *
186
+ * @param response - validated token response
187
+ * @returns response with token_type set to 'Bearer'
188
188
  */
189
189
  var normalizeBearerTokenResponseTokenType = response => ({
190
190
  id_token: response.id_token,
@@ -195,25 +195,25 @@ var normalizeBearerTokenResponseTokenType = response => ({
195
195
  token_type: "Bearer"
196
196
  });
197
197
 
198
- /**
199
- * @experimental
200
- * Attempt to exchange authorization code for bearer token.
201
- *
202
- * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a
203
- * request to the Token Endpoint, to obtain the access token, refresh token, etc.
204
- *
205
- * @param code - authorization code as returned by OP during authorization
206
- * @param storedAuthorizationParams - stored params from start of oidc login flow
207
- * @returns valid bearer token response
208
- * @throws An `Error` with `message` set to an entry in {@link OidcError},
209
- * when the request fails, or the returned token response is invalid.
198
+ /**
199
+ * @experimental
200
+ * Attempt to exchange authorization code for bearer token.
201
+ *
202
+ * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a
203
+ * request to the Token Endpoint, to obtain the access token, refresh token, etc.
204
+ *
205
+ * @param code - authorization code as returned by OP during authorization
206
+ * @param storedAuthorizationParams - stored params from start of oidc login flow
207
+ * @returns valid bearer token response
208
+ * @throws An `Error` with `message` set to an entry in {@link OidcError},
209
+ * when the request fails, or the returned token response is invalid.
210
210
  */
211
211
  export var completeAuthorizationCodeGrant = /*#__PURE__*/function () {
212
212
  var _ref7 = _asyncToGenerator(function* (code, state) {
213
- /**
214
- * Element Web strips and changes the url on starting the app
215
- * Use the code and state from query params to rebuild a url
216
- * so that oidc-client can parse it
213
+ /**
214
+ * Element Web strips and changes the url on starting the app
215
+ * Use the code and state from query params to rebuild a url
216
+ * so that oidc-client can parse it
217
217
  */
218
218
  var reconstructedUrl = new URL(window.location.origin);
219
219
  reconstructedUrl.searchParams.append("code", code);
@@ -1 +1 @@
1
- {"version":3,"file":"authorize.js","names":["Log","OidcClient","SigninResponse","SigninState","WebStorageStateStore","logger","secureRandomString","OidcError","validateBearerTokenResponse","validateIdToken","validateStoredUserState","sha256","encodeUnpaddedBase64Url","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","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","reconstructedUrl","location","origin","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"],"sources":["../../src/oidc/authorize.ts"],"sourcesContent":["/*\r\nCopyright 2023 The Matrix.org Foundation C.I.C.\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\nimport { type IdTokenClaims, Log, OidcClient, SigninResponse, SigninState, WebStorageStateStore } from \"oidc-client-ts\";\r\n\r\nimport { logger } from \"../logger.ts\";\r\nimport { secureRandomString } from \"../randomstring.ts\";\r\nimport { OidcError } from \"./error.ts\";\r\nimport {\r\n type BearerTokenResponse,\r\n type UserState,\r\n validateBearerTokenResponse,\r\n type ValidatedAuthMetadata,\r\n validateIdToken,\r\n validateStoredUserState,\r\n} from \"./validate.ts\";\r\nimport { sha256 } from \"../digest.ts\";\r\nimport { encodeUnpaddedBase64Url } from \"../base64.ts\";\r\n\r\n// reexport for backwards compatibility\r\nexport type { BearerTokenResponse };\r\n\r\n/**\r\n * Authorization parameters which are used in the authentication request of an OIDC auth code flow.\r\n *\r\n * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.\r\n */\r\nexport type AuthorizationParams = {\r\n state: string;\r\n scope: string;\r\n redirectUri: string;\r\n codeVerifier: string;\r\n nonce: string;\r\n};\r\n\r\n/**\r\n * @experimental\r\n * Generate the scope used in authorization request with OIDC OP\r\n * @returns scope\r\n */\r\nexport const generateScope = (deviceId?: string): string => {\r\n const safeDeviceId = deviceId ?? secureRandomString(10);\r\n return `openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${safeDeviceId}`;\r\n};\r\n\r\n// https://www.rfc-editor.org/rfc/rfc7636\r\nconst generateCodeChallenge = async (codeVerifier: string): Promise<string> => {\r\n if (!globalThis.crypto.subtle) {\r\n // @TODO(kerrya) should this be allowed? configurable?\r\n logger.warn(\"A secure context is required to generate code challenge. Using plain text code challenge\");\r\n return codeVerifier;\r\n }\r\n\r\n const hashBuffer = await sha256(codeVerifier);\r\n return encodeUnpaddedBase64Url(hashBuffer);\r\n};\r\n\r\n/**\r\n * Generate authorization params to pass to {@link generateAuthorizationUrl}.\r\n *\r\n * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.\r\n *\r\n * @param redirectUri - absolute url for OP to redirect to after authorization\r\n * @returns AuthorizationParams\r\n */\r\nexport const generateAuthorizationParams = ({ redirectUri }: { redirectUri: string }): AuthorizationParams => ({\r\n scope: generateScope(),\r\n redirectUri,\r\n state: secureRandomString(8),\r\n nonce: secureRandomString(8),\r\n codeVerifier: secureRandomString(64), // https://tools.ietf.org/html/rfc7636#section-4.1 length needs to be 43-128 characters\r\n});\r\n\r\n/**\r\n * @deprecated use generateOidcAuthorizationUrl\r\n * Generate a URL to attempt authorization with the OP\r\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\r\n * @param authorizationUrl - endpoint to attempt authorization with the OP\r\n * @param clientId - id of this client as registered with the OP\r\n * @param authorizationParams - params to be used in the url\r\n * @returns a Promise with the url as a string\r\n */\r\nexport const generateAuthorizationUrl = async (\r\n authorizationUrl: string,\r\n clientId: string,\r\n { scope, redirectUri, state, nonce, codeVerifier }: AuthorizationParams,\r\n): Promise<string> => {\r\n const url = new URL(authorizationUrl);\r\n url.searchParams.append(\"response_mode\", \"query\");\r\n url.searchParams.append(\"response_type\", \"code\");\r\n url.searchParams.append(\"redirect_uri\", redirectUri);\r\n url.searchParams.append(\"client_id\", clientId);\r\n url.searchParams.append(\"state\", state);\r\n url.searchParams.append(\"scope\", scope);\r\n url.searchParams.append(\"nonce\", nonce);\r\n\r\n url.searchParams.append(\"code_challenge_method\", \"S256\");\r\n url.searchParams.append(\"code_challenge\", await generateCodeChallenge(codeVerifier));\r\n\r\n return url.toString();\r\n};\r\n\r\n/**\r\n * @experimental\r\n * Generate a URL to attempt authorization with the OP\r\n * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest\r\n * @param metadata - validated metadata from OP discovery\r\n * @param clientId - this client's id as registered with the OP\r\n * @param homeserverUrl - used to establish the session on return from the OP\r\n * @param identityServerUrl - used to establish the session on return from the OP\r\n * @param nonce - state\r\n * @param prompt - indicates to the OP which flow the user should see - eg login or registration\r\n * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter\r\n * @param urlState - value to append to the opaque state identifier to uniquely identify the callback\r\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.\r\n * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.\r\n * @returns a Promise with the url as a string\r\n */\r\nexport const generateOidcAuthorizationUrl = async ({\r\n metadata,\r\n redirectUri,\r\n clientId,\r\n homeserverUrl,\r\n identityServerUrl,\r\n nonce,\r\n prompt,\r\n urlState,\r\n loginHint,\r\n}: {\r\n clientId: string;\r\n metadata: ValidatedAuthMetadata;\r\n homeserverUrl: string;\r\n identityServerUrl?: string;\r\n redirectUri: string;\r\n nonce: string;\r\n prompt?: string;\r\n urlState?: string;\r\n loginHint?: string;\r\n}): Promise<string> => {\r\n const scope = generateScope();\r\n const oidcClient = new OidcClient({\r\n ...metadata,\r\n client_id: clientId,\r\n redirect_uri: redirectUri,\r\n authority: metadata.issuer,\r\n response_mode: \"query\",\r\n response_type: \"code\",\r\n scope,\r\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\r\n });\r\n const userState: UserState = { homeserverUrl, nonce, identityServerUrl };\r\n const request = await oidcClient.createSigninRequest({\r\n state: userState,\r\n nonce,\r\n prompt,\r\n url_state: urlState,\r\n login_hint: loginHint,\r\n });\r\n\r\n return request.url;\r\n};\r\n\r\n/**\r\n * Normalize token_type to use capital case to make consuming the token response easier\r\n * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: \"bearer\"\r\n * Later, when used in auth headers it is case sensitive and must be Bearer\r\n * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4\r\n *\r\n * @param response - validated token response\r\n * @returns response with token_type set to 'Bearer'\r\n */\r\nconst normalizeBearerTokenResponseTokenType = (response: SigninResponse): BearerTokenResponse =>\r\n ({\r\n id_token: response.id_token,\r\n scope: response.scope,\r\n expires_at: response.expires_at,\r\n refresh_token: response.refresh_token,\r\n access_token: response.access_token,\r\n token_type: \"Bearer\",\r\n }) as BearerTokenResponse;\r\n\r\n/**\r\n * @experimental\r\n * Attempt to exchange authorization code for bearer token.\r\n *\r\n * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a\r\n * request to the Token Endpoint, to obtain the access token, refresh token, etc.\r\n *\r\n * @param code - authorization code as returned by OP during authorization\r\n * @param storedAuthorizationParams - stored params from start of oidc login flow\r\n * @returns valid bearer token response\r\n * @throws An `Error` with `message` set to an entry in {@link OidcError},\r\n * when the request fails, or the returned token response is invalid.\r\n */\r\nexport const completeAuthorizationCodeGrant = async (\r\n code: string,\r\n state: string,\r\n): Promise<{\r\n oidcClientSettings: { clientId: string; issuer: string };\r\n tokenResponse: BearerTokenResponse;\r\n homeserverUrl: string;\r\n idTokenClaims: IdTokenClaims;\r\n identityServerUrl?: string;\r\n}> => {\r\n /**\r\n * Element Web strips and changes the url on starting the app\r\n * Use the code and state from query params to rebuild a url\r\n * so that oidc-client can parse it\r\n */\r\n const reconstructedUrl = new URL(window.location.origin);\r\n reconstructedUrl.searchParams.append(\"code\", code);\r\n reconstructedUrl.searchParams.append(\"state\", state);\r\n\r\n // set oidc-client to use our logger\r\n Log.setLogger(logger);\r\n try {\r\n const response = new SigninResponse(reconstructedUrl.searchParams);\r\n\r\n const stateStore = new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage });\r\n\r\n // retrieve the state we put in storage at the start of oidc auth flow\r\n const stateString = await stateStore.get(response.state!);\r\n if (!stateString) {\r\n throw new Error(OidcError.MissingOrInvalidStoredState);\r\n }\r\n\r\n // hydrate the sign in state and create a client\r\n // the stored sign in state includes oidc configuration we set at the start of the oidc login flow\r\n const signInState = await SigninState.fromStorageString(stateString);\r\n const client = new OidcClient({ ...signInState, stateStore });\r\n\r\n // validate the code and state, and attempt to swap the code for tokens\r\n const signinResponse = await client.processSigninResponse(reconstructedUrl.href);\r\n\r\n // extra values we stored at the start of the login flow\r\n // used to complete login in the client\r\n const userState = signinResponse.userState;\r\n validateStoredUserState(userState);\r\n\r\n // throws when response is invalid\r\n validateBearerTokenResponse(signinResponse);\r\n // throws when token is invalid\r\n validateIdToken(signinResponse.id_token, client.settings.authority, client.settings.client_id, userState.nonce);\r\n const normalizedTokenResponse = normalizeBearerTokenResponseTokenType(signinResponse);\r\n\r\n return {\r\n oidcClientSettings: {\r\n clientId: client.settings.client_id,\r\n issuer: client.settings.authority,\r\n },\r\n tokenResponse: normalizedTokenResponse,\r\n homeserverUrl: userState.homeserverUrl,\r\n identityServerUrl: userState.identityServerUrl,\r\n idTokenClaims: signinResponse.profile,\r\n };\r\n } catch (error) {\r\n logger.error(\"Oidc login failed\", error);\r\n const errorType = (error as Error).message;\r\n\r\n // rethrow errors that we recognise\r\n if (Object.values(OidcError).includes(errorType as any)) {\r\n throw error;\r\n }\r\n throw new Error(OidcError.CodeExchangeFailed);\r\n }\r\n};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,CAACJ,SAAgB,CAAC,EAAE;QACrD,MAAMD,KAAK;MACf;MACA,MAAM,IAAId,KAAK,CAACrF,SAAS,CAACyG,kBAAkB,CAAC;IACjD;EACJ,CAAC;EAAA,gBAvEY7B,8BAA8BA,CAAA8B,GAAA,EAAAC,GAAA;IAAA,OAAA9B,KAAA,CAAAzD,KAAA,OAAAC,SAAA;EAAA;AAAA,GAuE1C","ignoreList":[]}
1
+ {"version":3,"file":"authorize.js","names":["Log","OidcClient","SigninResponse","SigninState","WebStorageStateStore","logger","secureRandomString","OidcError","validateBearerTokenResponse","validateIdToken","validateStoredUserState","sha256","encodeUnpaddedBase64Url","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","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","reconstructedUrl","location","origin","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"],"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 { type IdTokenClaims, Log, OidcClient, SigninResponse, SigninState, WebStorageStateStore } 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\";\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 * @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}: {\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}): 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: \"query\",\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 storedAuthorizationParams - stored params from start of oidc login flow\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): 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 reconstructedUrl.searchParams.append(\"code\", code);\n reconstructedUrl.searchParams.append(\"state\", state);\n\n // set oidc-client to use our logger\n Log.setLogger(logger);\n try {\n const response = new SigninResponse(reconstructedUrl.searchParams);\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 // throws when token is invalid\n validateIdToken(signinResponse.id_token, client.settings.authority, client.settings.client_id, userState.nonce);\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"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA6BA,GAAG,EAAEC,UAAU,EAAEC,cAAc,EAAEC,WAAW,EAAEC,oBAAoB,QAAQ,gBAAgB;AAEvH,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,kBAAkB,QAAQ,oBAAoB;AACvD,SAASC,SAAS,QAAQ,YAAY;AACtC,SAGIC,2BAA2B,EAE3BC,eAAe,EACfC,uBAAuB,QACpB,eAAe;AACtB,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,uBAAuB,QAAQ,cAAc;;AAEtD;;AAGA;AACA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,aAAa,GAAIC,QAAiB,IAAa;EACxD,IAAMC,YAAY,GAAGD,QAAQ,aAARA,QAAQ,cAARA,QAAQ,GAAIR,kBAAkB,CAAC,EAAE,CAAC;EACvD,wGAAAU,MAAA,CAAwGD,YAAY;AACxH,CAAC;;AAED;AACA,IAAME,qBAAqB;EAAA,IAAAC,IAAA,GAAAC,iBAAA,CAAG,WAAOC,YAAoB,EAAsB;IAC3E,IAAI,CAACC,UAAU,CAACC,MAAM,CAACC,MAAM,EAAE;MAC3B;MACAlB,MAAM,CAACmB,IAAI,CAAC,0FAA0F,CAAC;MACvG,OAAOJ,YAAY;IACvB;IAEA,IAAMK,UAAU,SAASd,MAAM,CAACS,YAAY,CAAC;IAC7C,OAAOR,uBAAuB,CAACa,UAAU,CAAC;EAC9C,CAAC;EAAA,gBATKR,qBAAqBA,CAAAS,EAAA;IAAA,OAAAR,IAAA,CAAAS,KAAA,OAAAC,SAAA;EAAA;AAAA,GAS1B;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,2BAA2B,GAAGC,KAAA;EAAA,IAA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A,IAAIC,MAAM,CAACC,MAAM,CAACvG,SAAS,CAAC,CAACwG,QAAQ,CAACJ,SAAgB,CAAC,EAAE;QACrD,MAAMD,KAAK;MACf;MACA,MAAM,IAAId,KAAK,CAACrF,SAAS,CAACyG,kBAAkB,CAAC;IACjD;EACJ,CAAC;EAAA,gBAvEY7B,8BAA8BA,CAAA8B,GAAA,EAAAC,GAAA;IAAA,OAAA9B,KAAA,CAAAzD,KAAA,OAAAC,SAAA;EAAA;AAAA,GAuE1C","ignoreList":[]}
package/lib/oidc/error.js CHANGED
@@ -1,22 +1,22 @@
1
- /*
2
- Copyright 2023 The Matrix.org Foundation C.I.C.
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
1
+ /*
2
+ Copyright 2023 The Matrix.org Foundation C.I.C.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
15
  */
16
16
 
17
- /**
18
- * Errors expected to be encountered during OIDC discovery, client registration, and authentication.
19
- * Not intended to be displayed directly to the user.
17
+ /**
18
+ * Errors expected to be encountered during OIDC discovery, client registration, and authentication.
19
+ * Not intended to be displayed directly to the user.
20
20
  */
21
21
  export var OidcError = /*#__PURE__*/function (OidcError) {
22
22
  OidcError["NotSupported"] = "OIDC authentication not supported";
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","names":["OidcError"],"sources":["../../src/oidc/error.ts"],"sourcesContent":["/*\r\nCopyright 2023 The Matrix.org Foundation C.I.C.\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\n/**\r\n * Errors expected to be encountered during OIDC discovery, client registration, and authentication.\r\n * Not intended to be displayed directly to the user.\r\n */\r\nexport enum OidcError {\r\n NotSupported = \"OIDC authentication not supported\",\r\n Misconfigured = \"OIDC is misconfigured\",\r\n General = \"Something went wrong with OIDC discovery\",\r\n OpSupport = \"Configured OIDC OP does not support required functions\",\r\n DynamicRegistrationNotSupported = \"Dynamic registration not supported\",\r\n DynamicRegistrationFailed = \"Dynamic registration failed\",\r\n DynamicRegistrationInvalid = \"Dynamic registration invalid response\",\r\n CodeExchangeFailed = \"Failed to exchange code for token\",\r\n InvalidBearerTokenResponse = \"Invalid bearer token response\",\r\n InvalidIdToken = \"Invalid ID token\",\r\n MissingOrInvalidStoredState = \"State required to finish logging in is not found in storage.\",\r\n}\r\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAYA,SAAS,0BAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAAA,OAATA,SAAS;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"error.js","names":["OidcError"],"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,WAAYA,SAAS,0BAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAATA,SAAS;EAAA,OAATA,SAAS;AAAA","ignoreList":[]}
package/lib/oidc/index.js CHANGED
@@ -1,17 +1,17 @@
1
- /*
2
- Copyright 2023 The Matrix.org Foundation C.I.C.
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
1
+ /*
2
+ Copyright 2023 The Matrix.org Foundation C.I.C.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
15
  */
16
16
 
17
17
  export * from "./authorize.js";
@@ -21,9 +21,9 @@ export * from "./register.js";
21
21
  export * from "./tokenRefresher.js";
22
22
  export * from "./validate.js";
23
23
 
24
- /**
25
- * Validated config for native OIDC authentication, as returned by {@link discoverAndValidateOIDCIssuerWellKnown}.
26
- * Contains metadata and signing keys from the issuer's well-known (https://oidc-issuer.example.com/.well-known/openid-configuration).
24
+ /**
25
+ * Validated config for native OIDC authentication, as returned by {@link discoverAndValidateOIDCIssuerWellKnown}.
26
+ * Contains metadata and signing keys from the issuer's well-known (https://oidc-issuer.example.com/.well-known/openid-configuration).
27
27
  */
28
28
  export {};
29
29
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/oidc/index.ts"],"sourcesContent":["/*\r\nCopyright 2023 The Matrix.org Foundation C.I.C.\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*/\r\n\r\nimport type { SigningKey } from \"oidc-client-ts\";\r\nimport { type ValidatedAuthMetadata } from \"./validate.ts\";\r\n\r\nexport * from \"./authorize.ts\";\r\nexport * from \"./discovery.ts\";\r\nexport * from \"./error.ts\";\r\nexport * from \"./register.ts\";\r\nexport * from \"./tokenRefresher.ts\";\r\nexport * from \"./validate.ts\";\r\n\r\n/**\r\n * Validated config for native OIDC authentication, as returned by {@link discoverAndValidateOIDCIssuerWellKnown}.\r\n * Contains metadata and signing keys from the issuer's well-known (https://oidc-issuer.example.com/.well-known/openid-configuration).\r\n */\r\nexport interface OidcClientConfig extends ValidatedAuthMetadata {\r\n signingKeys: SigningKey[] | null;\r\n}\r\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","ignoreList":[]}
@@ -1,59 +1,59 @@
1
1
  import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
2
- /*
3
- Copyright 2023 The Matrix.org Foundation C.I.C.
4
-
5
- Licensed under the Apache License, Version 2.0 (the "License");
6
- you may not use this file except in compliance with the License.
7
- You may obtain a copy of the License at
8
-
9
- http://www.apache.org/licenses/LICENSE-2.0
10
-
11
- Unless required by applicable law or agreed to in writing, software
12
- distributed under the License is distributed on an "AS IS" BASIS,
13
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- See the License for the specific language governing permissions and
15
- limitations under the License.
2
+ /*
3
+ Copyright 2023 The Matrix.org Foundation C.I.C.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
16
  */
17
17
 
18
18
  import { OidcError } from "./error.js";
19
19
  import { Method } from "../http-api/index.js";
20
20
  import { logger } from "../logger.js";
21
21
 
22
- /**
23
- * Client metadata passed to registration endpoint
22
+ /**
23
+ * Client metadata passed to registration endpoint
24
24
  */
25
25
 
26
- /**
27
- * Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966
26
+ /**
27
+ * Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966
28
28
  */
29
29
 
30
- /**
31
- * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
30
+ /**
31
+ * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
32
32
  */
33
33
  export var OAuthGrantType = /*#__PURE__*/function (OAuthGrantType) {
34
- /**
35
- * See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant
34
+ /**
35
+ * See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant
36
36
  */
37
37
  OAuthGrantType["AuthorizationCode"] = "authorization_code";
38
- /**
39
- * https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant
38
+ /**
39
+ * https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant
40
40
  */
41
41
  OAuthGrantType["RefreshToken"] = "refresh_token";
42
- /**
43
- * The OAuth 2.0 Device Authorization Grant type identifier as per
44
- * https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from
45
- * [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).
46
- *
47
- * @experimental Note that this is UNSTABLE and may have breaking changes without notice.
42
+ /**
43
+ * The OAuth 2.0 Device Authorization Grant type identifier as per
44
+ * https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from
45
+ * [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).
46
+ *
47
+ * @experimental Note that this is UNSTABLE and may have breaking changes without notice.
48
48
  */
49
49
  OAuthGrantType["DeviceAuthorization"] = "urn:ietf:params:oauth:grant-type:device_code";
50
50
  return OAuthGrantType;
51
51
  }({});
52
52
 
53
- /**
54
- * The name "scope" is a misnomer here as it is actually a "grant type".
55
- *
56
- * @deprecated use `OAuthGrantType.DeviceAuthorization` instead
53
+ /**
54
+ * The name "scope" is a misnomer here as it is actually a "grant type".
55
+ *
56
+ * @deprecated use `OAuthGrantType.DeviceAuthorization` instead
57
57
  */
58
58
  export var DEVICE_CODE_SCOPE = OAuthGrantType.DeviceAuthorization;
59
59
 
@@ -66,13 +66,13 @@ var urlHasCommonBase = (base, urlStr) => {
66
66
  return true;
67
67
  };
68
68
 
69
- /**
70
- * Attempts dynamic registration against the configured registration endpoint.
71
- * Will ignore any URIs that do not use client_uri as a common base as per the spec.
72
- * @param delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}
73
- * @param clientMetadata - The metadata for the client which to register
74
- * @returns Promise<string> resolved with registered clientId
75
- * @throws when registration is not supported, on failed request or invalid response
69
+ /**
70
+ * Attempts dynamic registration against the configured registration endpoint.
71
+ * Will ignore any URIs that do not use client_uri as a common base as per the spec.
72
+ * @param delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}
73
+ * @param clientMetadata - The metadata for the client which to register
74
+ * @returns Promise<string> resolved with registered clientId
75
+ * @throws when registration is not supported, on failed request or invalid response
76
76
  */
77
77
  export var registerOidcClient = /*#__PURE__*/function () {
78
78
  var _ref = _asyncToGenerator(function* (delegatedAuthConfig, clientMetadata) {