matrix-js-sdk 41.5.0 → 41.6.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 (204) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/lib/ReEmitter.js +1 -1
  3. package/lib/ReEmitter.js.map +1 -1
  4. package/lib/ToDeviceMessageQueue.js +2 -2
  5. package/lib/ToDeviceMessageQueue.js.map +1 -1
  6. package/lib/autodiscovery.js +0 -1
  7. package/lib/autodiscovery.js.map +1 -1
  8. package/lib/client.js +112 -165
  9. package/lib/client.js.map +1 -1
  10. package/lib/common-crypto/CryptoBackend.js +0 -2
  11. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  12. package/lib/content-helpers.js +3 -5
  13. package/lib/content-helpers.js.map +1 -1
  14. package/lib/content-repo.js +7 -1
  15. package/lib/content-repo.js.map +1 -1
  16. package/lib/crypto/store/indexeddb-crypto-store-backend.js +9 -11
  17. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  18. package/lib/crypto/store/indexeddb-crypto-store.js +0 -2
  19. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  20. package/lib/crypto/store/localStorage-crypto-store.js +11 -9
  21. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  22. package/lib/crypto/store/memory-crypto-store.js +11 -9
  23. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  24. package/lib/crypto-api/index.js +58 -58
  25. package/lib/crypto-api/index.js.map +1 -1
  26. package/lib/embedded.js +29 -45
  27. package/lib/embedded.js.map +1 -1
  28. package/lib/extensible_events_v1/MessageEvent.js +15 -15
  29. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  30. package/lib/extensible_events_v1/PollEndEvent.js +8 -8
  31. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  32. package/lib/extensible_events_v1/PollResponseEvent.js +0 -1
  33. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  34. package/lib/extensible_events_v1/PollStartEvent.js +28 -28
  35. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  36. package/lib/feature.js +5 -1
  37. package/lib/feature.js.map +1 -1
  38. package/lib/filter-component.js +4 -1
  39. package/lib/filter-component.js.map +1 -1
  40. package/lib/filter.js +1 -3
  41. package/lib/filter.js.map +1 -1
  42. package/lib/http-api/errors.js +20 -16
  43. package/lib/http-api/errors.js.map +1 -1
  44. package/lib/http-api/fetch.js +4 -6
  45. package/lib/http-api/fetch.js.map +1 -1
  46. package/lib/http-api/refresh.js +10 -12
  47. package/lib/http-api/refresh.js.map +1 -1
  48. package/lib/interactive-auth.js +1 -11
  49. package/lib/interactive-auth.js.map +1 -1
  50. package/lib/logger.js +0 -2
  51. package/lib/logger.js.map +1 -1
  52. package/lib/matrixrtc/CallMembership.js +43 -57
  53. package/lib/matrixrtc/CallMembership.js.map +1 -1
  54. package/lib/matrixrtc/MatrixRTCSession.js +19 -24
  55. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  56. package/lib/matrixrtc/MatrixRTCSessionManager.js +2 -3
  57. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  58. package/lib/matrixrtc/MembershipManager.js +23 -30
  59. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  60. package/lib/matrixrtc/MembershipManagerActionScheduler.js +1 -2
  61. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  62. package/lib/matrixrtc/RTCEncryptionManager.js +8 -11
  63. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  64. package/lib/matrixrtc/ToDeviceKeyTransport.js +4 -4
  65. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  66. package/lib/matrixrtc/utils.js +7 -1
  67. package/lib/matrixrtc/utils.js.map +1 -1
  68. package/lib/models/MSC3089TreeSpace.js +5 -7
  69. package/lib/models/MSC3089TreeSpace.js.map +1 -1
  70. package/lib/models/beacon.js +5 -11
  71. package/lib/models/beacon.js.map +1 -1
  72. package/lib/models/device.js +0 -7
  73. package/lib/models/device.js.map +1 -1
  74. package/lib/models/event-context.js +1 -2
  75. package/lib/models/event-context.js.map +1 -1
  76. package/lib/models/event-timeline-set.js +16 -26
  77. package/lib/models/event-timeline-set.js.map +1 -1
  78. package/lib/models/event-timeline.js +8 -15
  79. package/lib/models/event-timeline.js.map +1 -1
  80. package/lib/models/event.js +20 -37
  81. package/lib/models/event.js.map +1 -1
  82. package/lib/models/invites-ignorer.js +8 -12
  83. package/lib/models/invites-ignorer.js.map +1 -1
  84. package/lib/models/poll.js +7 -13
  85. package/lib/models/poll.js.map +1 -1
  86. package/lib/models/read-receipt.js +8 -4
  87. package/lib/models/read-receipt.js.map +1 -1
  88. package/lib/models/related-relations.js +0 -2
  89. package/lib/models/related-relations.js.map +1 -1
  90. package/lib/models/relations-container.js +4 -6
  91. package/lib/models/relations-container.js.map +1 -1
  92. package/lib/models/relations.js +7 -10
  93. package/lib/models/relations.js.map +1 -1
  94. package/lib/models/room-member.js +2 -24
  95. package/lib/models/room-member.js.map +1 -1
  96. package/lib/models/room-receipts.js +25 -22
  97. package/lib/models/room-receipts.js.map +1 -1
  98. package/lib/models/room-state.js +2 -2
  99. package/lib/models/room-state.js.map +1 -1
  100. package/lib/models/room-sticky-events.js +20 -5
  101. package/lib/models/room-sticky-events.js.map +1 -1
  102. package/lib/models/room.js +82 -105
  103. package/lib/models/room.js.map +1 -1
  104. package/lib/models/thread.js +12 -57
  105. package/lib/models/thread.js.map +1 -1
  106. package/lib/models/user.js +1 -20
  107. package/lib/models/user.js.map +1 -1
  108. package/lib/oidc/authorize.js +23 -32
  109. package/lib/oidc/authorize.js.map +1 -1
  110. package/lib/oidc/tokenRefresher.js +8 -11
  111. package/lib/oidc/tokenRefresher.js.map +1 -1
  112. package/lib/pushprocessor.js +8 -5
  113. package/lib/pushprocessor.js.map +1 -1
  114. package/lib/receipt-accumulator.js +12 -3
  115. package/lib/receipt-accumulator.js.map +1 -1
  116. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  117. package/lib/rendezvous/MSC4108SignInWithQR.js +10 -23
  118. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  119. package/lib/rendezvous/channels/MSC4108SecureChannel.js +5 -10
  120. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  121. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +5 -15
  122. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  123. package/lib/room-hierarchy.js +7 -12
  124. package/lib/room-hierarchy.js.map +1 -1
  125. package/lib/rust-crypto/DehydratedDeviceManager.js +2 -3
  126. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  127. package/lib/rust-crypto/KeyClaimManager.js +1 -2
  128. package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
  129. package/lib/rust-crypto/OutgoingRequestProcessor.js +11 -4
  130. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  131. package/lib/rust-crypto/OutgoingRequestsManager.js +12 -12
  132. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  133. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +3 -5
  134. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  135. package/lib/rust-crypto/RoomEncryptor.js +6 -6
  136. package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
  137. package/lib/rust-crypto/backup.js +22 -16
  138. package/lib/rust-crypto/backup.js.map +1 -1
  139. package/lib/rust-crypto/device-converter.js +13 -4
  140. package/lib/rust-crypto/device-converter.js.map +1 -1
  141. package/lib/rust-crypto/index.js +1 -3
  142. package/lib/rust-crypto/index.js.map +1 -1
  143. package/lib/rust-crypto/libolm_migration.js +13 -15
  144. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  145. package/lib/rust-crypto/rust-crypto.js +52 -59
  146. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  147. package/lib/rust-crypto/verification.js +10 -10
  148. package/lib/rust-crypto/verification.js.map +1 -1
  149. package/lib/scheduler.js +2 -2
  150. package/lib/scheduler.js.map +1 -1
  151. package/lib/secret-storage.js +16 -10
  152. package/lib/secret-storage.js.map +1 -1
  153. package/lib/serverCapabilities.js +2 -5
  154. package/lib/serverCapabilities.js.map +1 -1
  155. package/lib/sliding-sync-sdk.js +4 -9
  156. package/lib/sliding-sync-sdk.js.map +1 -1
  157. package/lib/sliding-sync.js +4 -9
  158. package/lib/sliding-sync.js.map +1 -1
  159. package/lib/store/indexeddb-local-backend.js +13 -8
  160. package/lib/store/indexeddb-local-backend.js.map +1 -1
  161. package/lib/store/indexeddb-remote-backend.js +6 -7
  162. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  163. package/lib/store/indexeddb-store-worker.js +1 -2
  164. package/lib/store/indexeddb-store-worker.js.map +1 -1
  165. package/lib/store/indexeddb.js +4 -2
  166. package/lib/store/indexeddb.js.map +1 -1
  167. package/lib/store/memory.js +0 -4
  168. package/lib/store/memory.js.map +1 -1
  169. package/lib/sync-accumulator.js +2 -4
  170. package/lib/sync-accumulator.js.map +1 -1
  171. package/lib/sync.js +36 -43
  172. package/lib/sync.js.map +1 -1
  173. package/lib/timeline-window.js +2 -6
  174. package/lib/timeline-window.js.map +1 -1
  175. package/lib/utils/decryptAESSecretStorageItem.js +5 -1
  176. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  177. package/lib/utils/encryptAESSecretStorageItem.js +5 -1
  178. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  179. package/lib/utils.js +35 -20
  180. package/lib/utils.js.map +1 -1
  181. package/lib/webrtc/call.js +13 -45
  182. package/lib/webrtc/call.js.map +1 -1
  183. package/lib/webrtc/callEventHandler.js +0 -5
  184. package/lib/webrtc/callEventHandler.js.map +1 -1
  185. package/lib/webrtc/callFeed.js +0 -15
  186. package/lib/webrtc/callFeed.js.map +1 -1
  187. package/lib/webrtc/groupCall.js +82 -89
  188. package/lib/webrtc/groupCall.js.map +1 -1
  189. package/lib/webrtc/groupCallEventHandler.js +6 -7
  190. package/lib/webrtc/groupCallEventHandler.js.map +1 -1
  191. package/lib/webrtc/mediaHandler.js +8 -15
  192. package/lib/webrtc/mediaHandler.js.map +1 -1
  193. package/lib/webrtc/stats/callStatsReportGatherer.js +2 -5
  194. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  195. package/lib/webrtc/stats/connectionStatsReportBuilder.js +5 -1
  196. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  197. package/lib/webrtc/stats/groupCallStats.js +3 -4
  198. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  199. package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
  200. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  201. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +1 -1
  202. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  203. package/package.json +3 -3
  204. package/src/rendezvous/MSC4108SignInWithQR.ts +2 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ Changes in [41.6.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v41.6.0) (2026-05-26)
2
+ ==================================================================================================
3
+ ## 🐛 Bug Fixes
4
+
5
+ * Throw sane error on completeLoginOnNewDevice IdP rejection ([#5321](https://github.com/matrix-org/matrix-js-sdk/pull/5321)). Contributed by @t3chguy.
6
+
7
+
1
8
  Changes in [41.5.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v41.5.0) (2026-05-12)
2
9
  ==================================================================================================
3
10
  ## ✨ Features
package/lib/ReEmitter.js CHANGED
@@ -21,9 +21,9 @@ limitations under the License.
21
21
 
22
22
  export class ReEmitter {
23
23
  constructor(target) {
24
- this.target = target;
25
24
  // Map from emitter to event name to re-emitter
26
25
  _defineProperty(this, "reEmitters", new WeakMap());
26
+ this.target = target;
27
27
  }
28
28
  reEmit(source, eventNames) {
29
29
  var _this = this;
@@ -1 +1 @@
1
- {"version":3,"file":"ReEmitter.js","names":["ReEmitter","constructor","target","_defineProperty","WeakMap","reEmit","source","eventNames","_this","reEmittersByEvent","reEmitters","get","Map","set","_loop","eventName","has","forSource","listenerCount","_len","arguments","length","args","Array","_key","emit","on","stopReEmitting","off","delete","size","TypedReEmitter"],"sources":["../src/ReEmitter.ts"],"sourcesContent":["/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2017 New Vector Ltd\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 { type EventEmitter } from \"events\";\n\nimport { type ListenerMap, type TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\n\nexport class ReEmitter {\n public constructor(private readonly target: EventEmitter) {}\n\n // Map from emitter to event name to re-emitter\n private reEmitters = new WeakMap<EventEmitter, Map<string, (...args: any[]) => void>>();\n\n public reEmit(source: EventEmitter, eventNames: string[]): void {\n let reEmittersByEvent = this.reEmitters.get(source);\n if (!reEmittersByEvent) {\n reEmittersByEvent = new Map();\n this.reEmitters.set(source, reEmittersByEvent);\n }\n\n for (const eventName of eventNames) {\n if (reEmittersByEvent.has(eventName)) continue;\n\n // We include the source as the last argument for event handlers which may need it,\n // such as read receipt listeners on the client class which won't have the context\n // of the room.\n const forSource = (...args: any[]): void => {\n // EventEmitter special cases 'error' to make the emit function throw if no\n // handler is attached, which sort of makes sense for making sure that something\n // handles an error, but for re-emitting, there could be a listener on the original\n // source object so the test doesn't really work. We *could* try to replicate the\n // same logic and throw if there is no listener on either the source or the target,\n // but this behaviour is fairly undesireable for us anyway: the main place we throw\n // 'error' events is for calls, where error events are usually emitted some time\n // later by a different part of the code where 'emit' throwing because the app hasn't\n // added an error handler isn't terribly helpful. (A better fix in retrospect may\n // have been to just avoid using the event name 'error', but backwards compat...)\n if (eventName === \"error\" && this.target.listenerCount(\"error\") === 0) return;\n this.target.emit(eventName, ...args, source);\n };\n source.on(eventName, forSource);\n reEmittersByEvent.set(eventName, forSource);\n }\n }\n\n public stopReEmitting(source: EventEmitter, eventNames: string[]): void {\n const reEmittersByEvent = this.reEmitters.get(source);\n if (!reEmittersByEvent) return; // We were never re-emitting these events in the first place\n\n for (const eventName of eventNames) {\n source.off(eventName, reEmittersByEvent.get(eventName)!);\n reEmittersByEvent.delete(eventName);\n }\n\n if (reEmittersByEvent.size === 0) this.reEmitters.delete(source);\n }\n}\n\nexport class TypedReEmitter<Events extends string, Arguments extends ListenerMap<Events>> extends ReEmitter {\n public constructor(target: TypedEventEmitter<Events, Arguments>) {\n super(target);\n }\n\n public reEmit<ReEmittedEvents extends string, T extends Events & ReEmittedEvents>(\n source: TypedEventEmitter<ReEmittedEvents, any>,\n eventNames: T[],\n ): void {\n super.reEmit(source, eventNames);\n }\n\n public stopReEmitting<ReEmittedEvents extends string, T extends Events & ReEmittedEvents>(\n source: TypedEventEmitter<ReEmittedEvents, any>,\n eventNames: T[],\n ): void {\n super.stopReEmitting(source, eventNames);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAKA,OAAO,MAAMA,SAAS,CAAC;EACZC,WAAWA,CAAkBC,MAAoB,EAAE;IAAA,KAAtBA,MAAoB,GAApBA,MAAoB;IAExD;IAAAC,eAAA,qBACqB,IAAIC,OAAO,CAAsD,CAAC;EAH5B;EAKpDC,MAAMA,CAACC,MAAoB,EAAEC,UAAoB,EAAQ;IAAA,IAAAC,KAAA;IAC5D,IAAIC,iBAAiB,GAAG,IAAI,CAACC,UAAU,CAACC,GAAG,CAACL,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;MAChCD,MAAM,CAACsB,GAAG,CAACb,SAAS,EAAEN,iBAAiB,CAACE,GAAG,CAACI,SAAS,CAAE,CAAC;MACxDN,iBAAiB,CAACoB,MAAM,CAACd,SAAS,CAAC;IACvC;IAEA,IAAIN,iBAAiB,CAACqB,IAAI,KAAK,CAAC,EAAE,IAAI,CAACpB,UAAU,CAACmB,MAAM,CAACvB,MAAM,CAAC;EACpE;AACJ;AAEA,OAAO,MAAMyB,cAAc,SAAuE/B,SAAS,CAAC;EACjGC,WAAWA,CAACC,MAA4C,EAAE;IAC7D,KAAK,CAACA,MAAM,CAAC;EACjB;EAEOG,MAAMA,CACTC,MAA+C,EAC/CC,UAAe,EACX;IACJ,KAAK,CAACF,MAAM,CAACC,MAAM,EAAEC,UAAU,CAAC;EACpC;EAEOoB,cAAcA,CACjBrB,MAA+C,EAC/CC,UAAe,EACX;IACJ,KAAK,CAACoB,cAAc,CAACrB,MAAM,EAAEC,UAAU,CAAC;EAC5C;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"ReEmitter.js","names":["ReEmitter","constructor","target","_defineProperty","WeakMap","reEmit","source","eventNames","_this","reEmittersByEvent","reEmitters","get","Map","set","_loop","eventName","has","forSource","listenerCount","_len","arguments","length","args","Array","_key","emit","on","stopReEmitting","off","delete","size","TypedReEmitter"],"sources":["../src/ReEmitter.ts"],"sourcesContent":["/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2017 New Vector Ltd\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 { type EventEmitter } from \"events\";\n\nimport { type ListenerMap, type TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\n\nexport class ReEmitter {\n public constructor(private readonly target: EventEmitter) {}\n\n // Map from emitter to event name to re-emitter\n private reEmitters = new WeakMap<EventEmitter, Map<string, (...args: any[]) => void>>();\n\n public reEmit(source: EventEmitter, eventNames: string[]): void {\n let reEmittersByEvent = this.reEmitters.get(source);\n if (!reEmittersByEvent) {\n reEmittersByEvent = new Map();\n this.reEmitters.set(source, reEmittersByEvent);\n }\n\n for (const eventName of eventNames) {\n if (reEmittersByEvent.has(eventName)) continue;\n\n // We include the source as the last argument for event handlers which may need it,\n // such as read receipt listeners on the client class which won't have the context\n // of the room.\n const forSource = (...args: any[]): void => {\n // EventEmitter special cases 'error' to make the emit function throw if no\n // handler is attached, which sort of makes sense for making sure that something\n // handles an error, but for re-emitting, there could be a listener on the original\n // source object so the test doesn't really work. We *could* try to replicate the\n // same logic and throw if there is no listener on either the source or the target,\n // but this behaviour is fairly undesireable for us anyway: the main place we throw\n // 'error' events is for calls, where error events are usually emitted some time\n // later by a different part of the code where 'emit' throwing because the app hasn't\n // added an error handler isn't terribly helpful. (A better fix in retrospect may\n // have been to just avoid using the event name 'error', but backwards compat...)\n if (eventName === \"error\" && this.target.listenerCount(\"error\") === 0) return;\n this.target.emit(eventName, ...args, source);\n };\n source.on(eventName, forSource);\n reEmittersByEvent.set(eventName, forSource);\n }\n }\n\n public stopReEmitting(source: EventEmitter, eventNames: string[]): void {\n const reEmittersByEvent = this.reEmitters.get(source);\n if (!reEmittersByEvent) return; // We were never re-emitting these events in the first place\n\n for (const eventName of eventNames) {\n source.off(eventName, reEmittersByEvent.get(eventName)!);\n reEmittersByEvent.delete(eventName);\n }\n\n if (reEmittersByEvent.size === 0) this.reEmitters.delete(source);\n }\n}\n\nexport class TypedReEmitter<Events extends string, Arguments extends ListenerMap<Events>> extends ReEmitter {\n public constructor(target: TypedEventEmitter<Events, Arguments>) {\n super(target);\n }\n\n public reEmit<ReEmittedEvents extends string, T extends Events & ReEmittedEvents>(\n source: TypedEventEmitter<ReEmittedEvents, any>,\n eventNames: T[],\n ): void {\n super.reEmit(source, eventNames);\n }\n\n public stopReEmitting<ReEmittedEvents extends string, T extends Events & ReEmittedEvents>(\n source: TypedEventEmitter<ReEmittedEvents, any>,\n eventNames: T[],\n ): void {\n super.stopReEmitting(source, eventNames);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAKA,OAAO,MAAMA,SAAS,CAAC;EACZC,WAAWA,CAAkBC,MAAoB,EAAE;IAE1D;IAAAC,eAAA,qBACqB,IAAIC,OAAO,CAAsD,CAAC;IAAA,KAHnDF,MAAoB,GAApBA,MAAoB;EAAG;EAKpDG,MAAMA,CAACC,MAAoB,EAAEC,UAAoB,EAAQ;IAAA,IAAAC,KAAA;IAC5D,IAAIC,iBAAiB,GAAG,IAAI,CAACC,UAAU,CAACC,GAAG,CAACL,MAAM,CAAC;IACnD,IAAI,CAACG,iBAAiB,EAAE;MACpBA,iBAAiB,GAAG,IAAIG,GAAG,CAAC,CAAC;MAC7B,IAAI,CAACF,UAAU,CAACG,GAAG,CAACP,MAAM,EAAEG,iBAAiB,CAAC;IAClD;IAAC,IAAAK,KAAA,YAAAA,MAAAC,SAAA,EAEmC;MAChC,IAAIN,iBAAiB,CAACO,GAAG,CAACD,SAAS,CAAC;;MAEpC;MACA;MACA;MACA,IAAME,SAAS,GAAG,SAAZA,SAASA,CAAA,EAA6B;QACxC;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,IAAIF,SAAS,KAAK,OAAO,IAAIP,KAAI,CAACN,MAAM,CAACgB,aAAa,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QAAO,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAX5DC,IAAI,OAAAC,KAAA,CAAAJ,IAAA,GAAAK,IAAA,MAAAA,IAAA,G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AACJ","ignoreList":[]}
@@ -30,8 +30,6 @@ var MAX_BATCH_SIZE = 20;
30
30
  export class ToDeviceMessageQueue {
31
31
  constructor(client, logger) {
32
32
  var _this = this;
33
- this.client = client;
34
- this.logger = logger;
35
33
  _defineProperty(this, "sending", false);
36
34
  _defineProperty(this, "running", true);
37
35
  _defineProperty(this, "retryTimeout", null);
@@ -87,6 +85,8 @@ export class ToDeviceMessageQueue {
87
85
  this.sendQueue();
88
86
  }
89
87
  });
88
+ this.client = client;
89
+ this.logger = logger;
90
90
  }
91
91
  start() {
92
92
  this.running = true;
@@ -1 +1 @@
1
- {"version":3,"file":"ToDeviceMessageQueue.js","names":["ToDeviceMessageId","ClientEvent","MatrixScheduler","SyncState","MapWithDefault","MAX_BATCH_SIZE","ToDeviceMessageQueue","constructor","client","logger","_this","_defineProperty","_asyncToGenerator","retryTimeout","clearTimeout","sending","running","debug","headBatch","store","getOldestToDeviceBatch","sendBatch","removeToDeviceBatch","id","retryAttempts","e","retryDelay","RETRY_BACKOFF_RATELIMIT","Math","floor","httpStatus","error","info","concat","setTimeout","sendQueue","state","oldState","Syncing","start","on","Sync","onResumedSync","stop","removeListener","queueBatch","batch","_this2","batches","i","length","batchWithTxnId","eventType","slice","txnId","makeTxnId","push","msgmap","map","msg","userId","deviceId","payload","saveToDeviceBatches","_this3","contentMap","Map","item","getOrCreate","set","sendToDevice"],"sources":["../src/ToDeviceMessageQueue.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ToDeviceMessageId } from \"./@types/event.ts\";\nimport { type Logger } from \"./logger.ts\";\nimport { type MatrixClient, ClientEvent } from \"./client.ts\";\nimport { type MatrixError } from \"./http-api/index.ts\";\nimport {\n type IndexedToDeviceBatch,\n type ToDeviceBatch,\n type ToDeviceBatchWithTxnId,\n type ToDevicePayload,\n} from \"./models/ToDeviceMessage.ts\";\nimport { MatrixScheduler } from \"./scheduler.ts\";\nimport { SyncState } from \"./sync.ts\";\nimport { MapWithDefault } from \"./utils.ts\";\n\nconst MAX_BATCH_SIZE = 20;\n\n/**\n * Maintains a queue of outgoing to-device messages, sending them\n * as soon as the homeserver is reachable.\n */\nexport class ToDeviceMessageQueue {\n private sending = false;\n private running = true;\n private retryTimeout: ReturnType<typeof setTimeout> | null = null;\n private retryAttempts = 0;\n\n public constructor(\n private client: MatrixClient,\n private readonly logger: Logger,\n ) {}\n\n public start(): void {\n this.running = true;\n this.sendQueue();\n this.client.on(ClientEvent.Sync, this.onResumedSync);\n }\n\n public stop(): void {\n this.running = false;\n if (this.retryTimeout !== null) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n this.client.removeListener(ClientEvent.Sync, this.onResumedSync);\n }\n\n public async queueBatch(batch: ToDeviceBatch): Promise<void> {\n const batches: ToDeviceBatchWithTxnId[] = [];\n for (let i = 0; i < batch.batch.length; i += MAX_BATCH_SIZE) {\n const batchWithTxnId = {\n eventType: batch.eventType,\n batch: batch.batch.slice(i, i + MAX_BATCH_SIZE),\n txnId: this.client.makeTxnId(),\n };\n batches.push(batchWithTxnId);\n const msgmap = batchWithTxnId.batch.map(\n (msg) => `${msg.userId}/${msg.deviceId} (msgid ${msg.payload[ToDeviceMessageId]})`,\n );\n this.logger.info(\n `Enqueuing batch of to-device messages. type=${batch.eventType} txnid=${batchWithTxnId.txnId}`,\n msgmap,\n );\n }\n\n await this.client.store.saveToDeviceBatches(batches);\n this.sendQueue();\n }\n\n public sendQueue = async (): Promise<void> => {\n if (this.retryTimeout !== null) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n\n if (this.sending || !this.running) return;\n\n this.logger.debug(\"Attempting to send queued to-device messages\");\n\n this.sending = true;\n let headBatch: IndexedToDeviceBatch | null;\n try {\n while (this.running) {\n headBatch = await this.client.store.getOldestToDeviceBatch();\n if (headBatch === null) break;\n await this.sendBatch(headBatch);\n await this.client.store.removeToDeviceBatch(headBatch.id);\n this.retryAttempts = 0;\n }\n\n // Make sure we're still running after the async tasks: if not, stop.\n if (!this.running) return;\n\n this.logger.debug(\"All queued to-device messages sent\");\n } catch (e) {\n ++this.retryAttempts;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n // eslint-disable-next-line new-cap\n const retryDelay = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null, this.retryAttempts, <MatrixError>e);\n if (retryDelay === -1) {\n // the scheduler function doesn't differentiate between fatal errors and just getting\n // bored and giving up for now\n if (Math.floor((<MatrixError>e).httpStatus! / 100) === 4) {\n this.logger.error(\"Fatal error when sending to-device message - dropping to-device batch!\", e);\n await this.client.store.removeToDeviceBatch(headBatch!.id);\n } else {\n this.logger.info(\"Automatic retry limit reached for to-device messages.\");\n }\n return;\n }\n\n this.logger.info(`Failed to send batch of to-device messages. Will retry in ${retryDelay}ms`, e);\n this.retryTimeout = setTimeout(this.sendQueue, retryDelay);\n } finally {\n this.sending = false;\n }\n };\n\n /**\n * Attempts to send a batch of to-device messages.\n */\n private async sendBatch(batch: IndexedToDeviceBatch): Promise<void> {\n const contentMap: MapWithDefault<string, Map<string, ToDevicePayload>> = new MapWithDefault(() => new Map());\n for (const item of batch.batch) {\n contentMap.getOrCreate(item.userId).set(item.deviceId, item.payload);\n }\n\n this.logger.info(\n `Sending batch of ${batch.batch.length} to-device messages with ID ${batch.id} and txnId ${batch.txnId}`,\n );\n\n await this.client.sendToDevice(batch.eventType, contentMap, batch.txnId);\n }\n\n /**\n * Listen to sync state changes and automatically resend any pending events\n * once syncing is resumed\n */\n private onResumedSync = (state: SyncState | null, oldState: SyncState | null): void => {\n if (state === SyncState.Syncing && oldState !== SyncState.Syncing) {\n this.logger.info(`Resuming queue after resumed sync`);\n this.sendQueue();\n }\n };\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,iBAAiB,QAAQ,mBAAmB;AAErD,SAA4BC,WAAW,QAAQ,aAAa;AAQ5D,SAASC,eAAe,QAAQ,gBAAgB;AAChD,SAASC,SAAS,QAAQ,WAAW;AACrC,SAASC,cAAc,QAAQ,YAAY;AAE3C,IAAMC,cAAc,GAAG,EAAE;;AAEzB;AACA;AACA;AACA;AACA,OAAO,MAAMC,oBAAoB,CAAC;EAMvBC,WAAWA,CACNC,MAAoB,EACXC,MAAc,EACjC;IAAA,IAAAC,KAAA;IAAA,KAFUF,MAAoB,GAApBA,MAAoB;IAAA,KACXC,MAAc,GAAdA,MAAc;IAAAE,eAAA,kBAPjB,KAAK;IAAAA,eAAA,kBACL,IAAI;IAAAA,eAAA,uBACuC,IAAI;IAAAA,eAAA,wBACzC,CAAC;IAAAA,eAAA,iCAAAC,iBAAA,CA0CN,aAA2B;MAC1C,IAAIF,KAAI,CAACG,YAAY,KAAK,IAAI,EAAEC,YAAY,CAACJ,KAAI,CAACG,YAAY,CAAC;MAC/DH,KAAI,CAACG,YAAY,GAAG,IAAI;MAExB,IAAIH,KAAI,CAACK,OAAO,IAAI,CAACL,KAAI,CAACM,OAAO,EAAE;MAEnCN,KAAI,CAACD,MAAM,CAACQ,KAAK,CAAC,8CAA8C,CAAC;MAEjEP,KAAI,CAACK,OAAO,GAAG,IAAI;MACnB,IAAIG,SAAsC;MAC1C,IAAI;QACA,OAAOR,KAAI,CAACM,OAAO,EAAE;UACjBE,SAAS,SAASR,KAAI,CAACF,MAAM,CAACW,KAAK,CAACC,sBAAsB,CAAC,CAAC;UAC5D,IAAIF,SAAS,KAAK,IAAI,EAAE;UACxB,MAAMR,KAAI,CAACW,SAAS,CAACH,SAAS,CAAC;UAC/B,MAAMR,KA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C,MAAM,OAAA3B,MAAA,CAAI0B,GAAG,CAACE,QAAQ,cAAA5B,MAAA,CAAW0B,GAAG,CAACG,OAAO,CAAC9D,iBAAiB,CAAC,MACnF,CAAC;QACD+C,MAAI,CAACtC,MAAM,CAACuB,IAAI,gDAAAC,MAAA,CACmCa,KAAK,CAACM,SAAS,aAAAnB,MAAA,CAAUkB,cAAc,CAACG,KAAK,GAC5FG,MACJ,CAAC;MACL;MAEA,MAAMV,MAAI,CAACvC,MAAM,CAACW,KAAK,CAAC4C,mBAAmB,CAACf,OAAO,CAAC;MACpDD,MAAI,CAACZ,SAAS,CAAC,CAAC;IAAC;EACrB;EAiDA;AACJ;AACA;EACkBd,SAASA,CAACyB,KAA2B,EAAiB;IAAA,IAAAkB,MAAA;IAAA,OAAApD,iBAAA;MAChE,IAAMqD,UAAgE,GAAG,IAAI7D,cAAc,CAAC,MAAM,IAAI8D,GAAG,CAAC,CAAC,CAAC;MAC5G,KAAK,IAAMC,IAAI,IAAIrB,KAAK,CAACA,KAAK,EAAE;QAC5BmB,UAAU,CAACG,WAAW,CAACD,IAAI,CAACP,MAAM,CAAC,CAACS,GAAG,CAACF,IAAI,CAACN,QAAQ,EAAEM,IAAI,CAACL,OAAO,CAAC;MACxE;MAEAE,MAAI,CAACvD,MAAM,CAACuB,IAAI,qBAAAC,MAAA,CACQa,KAAK,CAACA,KAAK,CAACI,MAAM,kCAAAjB,MAAA,CAA+Ba,KAAK,CAACvB,EAAE,iBAAAU,MAAA,CAAca,KAAK,CAACQ,KAAK,CAC1G,CAAC;MAED,MAAMU,MAAI,CAACxD,MAAM,CAAC8D,YAAY,CAACxB,KAAK,CAACM,SAAS,EAAEa,UAAU,EAAEnB,KAAK,CAACQ,KAAK,CAAC;IAAC;EAC7E;AAYJ","ignoreList":[]}
1
+ {"version":3,"file":"ToDeviceMessageQueue.js","names":["ToDeviceMessageId","ClientEvent","MatrixScheduler","SyncState","MapWithDefault","MAX_BATCH_SIZE","ToDeviceMessageQueue","constructor","client","logger","_this","_defineProperty","_asyncToGenerator","retryTimeout","clearTimeout","sending","running","debug","headBatch","store","getOldestToDeviceBatch","sendBatch","removeToDeviceBatch","id","retryAttempts","e","retryDelay","RETRY_BACKOFF_RATELIMIT","Math","floor","httpStatus","error","info","concat","setTimeout","sendQueue","state","oldState","Syncing","start","on","Sync","onResumedSync","stop","removeListener","queueBatch","batch","_this2","batches","i","length","batchWithTxnId","eventType","slice","txnId","makeTxnId","push","msgmap","map","msg","userId","deviceId","payload","saveToDeviceBatches","_this3","contentMap","Map","item","getOrCreate","set","sendToDevice"],"sources":["../src/ToDeviceMessageQueue.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ToDeviceMessageId } from \"./@types/event.ts\";\nimport { type Logger } from \"./logger.ts\";\nimport { type MatrixClient, ClientEvent } from \"./client.ts\";\nimport { type MatrixError } from \"./http-api/index.ts\";\nimport {\n type IndexedToDeviceBatch,\n type ToDeviceBatch,\n type ToDeviceBatchWithTxnId,\n type ToDevicePayload,\n} from \"./models/ToDeviceMessage.ts\";\nimport { MatrixScheduler } from \"./scheduler.ts\";\nimport { SyncState } from \"./sync.ts\";\nimport { MapWithDefault } from \"./utils.ts\";\n\nconst MAX_BATCH_SIZE = 20;\n\n/**\n * Maintains a queue of outgoing to-device messages, sending them\n * as soon as the homeserver is reachable.\n */\nexport class ToDeviceMessageQueue {\n private sending = false;\n private running = true;\n private retryTimeout: ReturnType<typeof setTimeout> | null = null;\n private retryAttempts = 0;\n\n public constructor(\n private client: MatrixClient,\n private readonly logger: Logger,\n ) {}\n\n public start(): void {\n this.running = true;\n this.sendQueue();\n this.client.on(ClientEvent.Sync, this.onResumedSync);\n }\n\n public stop(): void {\n this.running = false;\n if (this.retryTimeout !== null) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n this.client.removeListener(ClientEvent.Sync, this.onResumedSync);\n }\n\n public async queueBatch(batch: ToDeviceBatch): Promise<void> {\n const batches: ToDeviceBatchWithTxnId[] = [];\n for (let i = 0; i < batch.batch.length; i += MAX_BATCH_SIZE) {\n const batchWithTxnId = {\n eventType: batch.eventType,\n batch: batch.batch.slice(i, i + MAX_BATCH_SIZE),\n txnId: this.client.makeTxnId(),\n };\n batches.push(batchWithTxnId);\n const msgmap = batchWithTxnId.batch.map(\n (msg) => `${msg.userId}/${msg.deviceId} (msgid ${msg.payload[ToDeviceMessageId]})`,\n );\n this.logger.info(\n `Enqueuing batch of to-device messages. type=${batch.eventType} txnid=${batchWithTxnId.txnId}`,\n msgmap,\n );\n }\n\n await this.client.store.saveToDeviceBatches(batches);\n this.sendQueue();\n }\n\n public sendQueue = async (): Promise<void> => {\n if (this.retryTimeout !== null) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n\n if (this.sending || !this.running) return;\n\n this.logger.debug(\"Attempting to send queued to-device messages\");\n\n this.sending = true;\n let headBatch: IndexedToDeviceBatch | null;\n try {\n while (this.running) {\n headBatch = await this.client.store.getOldestToDeviceBatch();\n if (headBatch === null) break;\n await this.sendBatch(headBatch);\n await this.client.store.removeToDeviceBatch(headBatch.id);\n this.retryAttempts = 0;\n }\n\n // Make sure we're still running after the async tasks: if not, stop.\n if (!this.running) return;\n\n this.logger.debug(\"All queued to-device messages sent\");\n } catch (e) {\n ++this.retryAttempts;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n // eslint-disable-next-line new-cap\n const retryDelay = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null, this.retryAttempts, <MatrixError>e);\n if (retryDelay === -1) {\n // the scheduler function doesn't differentiate between fatal errors and just getting\n // bored and giving up for now\n if (Math.floor((<MatrixError>e).httpStatus! / 100) === 4) {\n this.logger.error(\"Fatal error when sending to-device message - dropping to-device batch!\", e);\n await this.client.store.removeToDeviceBatch(headBatch!.id);\n } else {\n this.logger.info(\"Automatic retry limit reached for to-device messages.\");\n }\n return;\n }\n\n this.logger.info(`Failed to send batch of to-device messages. Will retry in ${retryDelay}ms`, e);\n this.retryTimeout = setTimeout(this.sendQueue, retryDelay);\n } finally {\n this.sending = false;\n }\n };\n\n /**\n * Attempts to send a batch of to-device messages.\n */\n private async sendBatch(batch: IndexedToDeviceBatch): Promise<void> {\n const contentMap: MapWithDefault<string, Map<string, ToDevicePayload>> = new MapWithDefault(() => new Map());\n for (const item of batch.batch) {\n contentMap.getOrCreate(item.userId).set(item.deviceId, item.payload);\n }\n\n this.logger.info(\n `Sending batch of ${batch.batch.length} to-device messages with ID ${batch.id} and txnId ${batch.txnId}`,\n );\n\n await this.client.sendToDevice(batch.eventType, contentMap, batch.txnId);\n }\n\n /**\n * Listen to sync state changes and automatically resend any pending events\n * once syncing is resumed\n */\n private onResumedSync = (state: SyncState | null, oldState: SyncState | null): void => {\n if (state === SyncState.Syncing && oldState !== SyncState.Syncing) {\n this.logger.info(`Resuming queue after resumed sync`);\n this.sendQueue();\n }\n };\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,iBAAiB,QAAQ,mBAAmB;AAErD,SAA4BC,WAAW,QAAQ,aAAa;AAQ5D,SAASC,eAAe,QAAQ,gBAAgB;AAChD,SAASC,SAAS,QAAQ,WAAW;AACrC,SAASC,cAAc,QAAQ,YAAY;AAE3C,IAAMC,cAAc,GAAG,EAAE;;AAEzB;AACA;AACA;AACA;AACA,OAAO,MAAMC,oBAAoB,CAAC;EAMvBC,WAAWA,CACNC,MAAoB,EACXC,MAAc,EACjC;IAAA,IAAAC,KAAA;IAAAC,eAAA,kBARgB,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AAA;MAChE,IAAMqD,UAAgE,GAAG,IAAI7D,cAAc,CAAC,MAAM,IAAI8D,GAAG,CAAC,CAAC,CAAC;MAC5G,KAAK,IAAMC,IAAI,IAAIrB,KAAK,CAACA,KAAK,EAAE;QAC5BmB,UAAU,CAACG,WAAW,CAACD,IAAI,CAACP,MAAM,CAAC,CAACS,GAAG,CAACF,IAAI,CAACN,QAAQ,EAAEM,IAAI,CAACL,OAAO,CAAC;MACxE;MAEAE,MAAI,CAACvD,MAAM,CAACuB,IAAI,qBAAAC,MAAA,CACQa,KAAK,CAACA,KAAK,CAACI,MAAM,kCAAAjB,MAAA,CAA+Ba,KAAK,CAACvB,EAAE,iBAAAU,MAAA,CAAca,KAAK,CAACQ,KAAK,CAC1G,CAAC;MAED,MAAMU,MAAI,CAACxD,MAAM,CAAC8D,YAAY,CAACxB,KAAK,CAACM,SAAS,EAAEa,UAAU,EAAEnB,KAAK,CAACQ,KAAK,CAAC;IAAC;EAC7E;AAYJ","ignoreList":[]}
@@ -460,5 +460,4 @@ _defineProperty(AutoDiscovery, "PROMPT", AutoDiscoveryAction.PROMPT);
460
460
  * The auto discovery was successful.
461
461
  */
462
462
  _defineProperty(AutoDiscovery, "SUCCESS", AutoDiscoveryAction.SUCCESS);
463
- _defineProperty(AutoDiscovery, "fetchFn", void 0);
464
463
  //# sourceMappingURL=autodiscovery.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"autodiscovery.js","names":["logger","Method","timeoutSignal","SUPPORTED_MATRIX_VERSIONS","AutoDiscoveryAction","AutoDiscoveryError","AutoDiscovery","fromDiscoveryConfig","wellknown","_this","_asyncToGenerator","_hsVersions$raw","clientConfig","state","FAIL_ERROR","error","ERROR_INVALID","base_url","PROMPT","FAIL_PROMPT","Promise","resolve","ERROR_INVALID_HS_BASE_URL","hsUrl","sanitizeWellKnownUrl","hsVersions","fetchWellKnownObject","concat","Array","isArray","raw","ERROR_INVALID_HOMESERVER","hsVersionSet","Set","supportedVersionFound","version","has","ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION","SUCCESS","isUrl","failingClientConfig","ERROR_INVALID_IS","ERROR_INVALID_IS_BASE_URL","isResponse","action","ERROR_INVALID_IDENTITY_SERVER","toString","length","Object","keys","forEach","k","notProps","prop","includes","findClientConfig","domain","_this2","Error","domainWithProtocol","reason","IGNORE","getRawClientConfig","_this3","_response$raw","response","url","_parsed","parsed","URL","e","hostname","protocol","port","path","pathname","saferUrl","endsWith","substring","fetch","resource","options","fetchFn","globalThis","setFetchFn","method","Get","signal","status","ERROR_MISSING_WELLKNOWN","err","message","json","name","ERROR_INVALID_JSON","_defineProperty","Invalid","GenericFailure","InvalidHsBaseUrl","InvalidHomeserver","InvalidIsBaseUrl","InvalidIdentityServer","InvalidIs","MissingWellknown","InvalidJson","UnsupportedHomeserverSpecVersion"],"sources":["../src/autodiscovery.ts"],"sourcesContent":["/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 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 IClientWellKnown, type IWellKnownConfig, type IServerVersions } from \"./client.ts\";\nimport { logger } from \"./logger.ts\";\nimport { type MatrixError, Method, timeoutSignal } from \"./http-api/index.ts\";\nimport { SUPPORTED_MATRIX_VERSIONS } from \"./version-support.ts\";\n\n// Dev note: Auto discovery is part of the spec.\n// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery\n\nexport enum AutoDiscoveryAction {\n SUCCESS = \"SUCCESS\",\n IGNORE = \"IGNORE\",\n PROMPT = \"PROMPT\",\n FAIL_PROMPT = \"FAIL_PROMPT\",\n FAIL_ERROR = \"FAIL_ERROR\",\n}\n\nexport enum AutoDiscoveryError {\n Invalid = \"Invalid homeserver discovery response\",\n GenericFailure = \"Failed to get autodiscovery configuration from server\",\n InvalidHsBaseUrl = \"Invalid base_url for m.homeserver\",\n InvalidHomeserver = \"Homeserver URL does not appear to be a valid Matrix homeserver\",\n InvalidIsBaseUrl = \"Invalid base_url for m.identity_server\",\n InvalidIdentityServer = \"Identity server URL does not appear to be a valid identity server\",\n InvalidIs = \"Invalid identity server discovery response\",\n MissingWellknown = \"No .well-known JSON file found\",\n InvalidJson = \"Invalid JSON\",\n UnsupportedHomeserverSpecVersion = \"The homeserver does not meet the version requirements\",\n\n // TODO: Implement when Sydent supports the `/versions` endpoint - https://github.com/matrix-org/sydent/issues/424\n //IdentityServerTooOld = \"The identity server does not meet the minimum version requirements\",\n}\n\ninterface AutoDiscoveryState {\n state: AutoDiscoveryAction;\n error?: IWellKnownConfig[\"error\"] | null;\n}\ninterface WellKnownConfig extends Omit<IWellKnownConfig, \"error\">, AutoDiscoveryState {}\n\nexport interface ClientConfig extends Omit<IClientWellKnown, \"m.homeserver\" | \"m.identity_server\"> {\n \"m.homeserver\": WellKnownConfig;\n \"m.identity_server\": WellKnownConfig;\n}\n\n/**\n * Utilities for automatically discovery resources, such as homeservers\n * for users to log in to.\n */\nexport class AutoDiscovery {\n // Dev note: the constants defined here are related to but not\n // exactly the same as those in the spec. This is to hopefully\n // translate the meaning of the states in the spec, but also\n // support our own if needed.\n\n public static readonly ERROR_INVALID = AutoDiscoveryError.Invalid;\n\n public static readonly ERROR_GENERIC_FAILURE = AutoDiscoveryError.GenericFailure;\n\n public static readonly ERROR_INVALID_HS_BASE_URL = AutoDiscoveryError.InvalidHsBaseUrl;\n\n public static readonly ERROR_INVALID_HOMESERVER = AutoDiscoveryError.InvalidHomeserver;\n\n public static readonly ERROR_INVALID_IS_BASE_URL = AutoDiscoveryError.InvalidIsBaseUrl;\n\n public static readonly ERROR_INVALID_IDENTITY_SERVER = AutoDiscoveryError.InvalidIdentityServer;\n\n public static readonly ERROR_INVALID_IS = AutoDiscoveryError.InvalidIs;\n\n public static readonly ERROR_MISSING_WELLKNOWN = AutoDiscoveryError.MissingWellknown;\n\n public static readonly ERROR_INVALID_JSON = AutoDiscoveryError.InvalidJson;\n\n public static readonly ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION =\n AutoDiscoveryError.UnsupportedHomeserverSpecVersion;\n\n public static readonly ALL_ERRORS = Object.keys(AutoDiscoveryError) as AutoDiscoveryError[];\n\n /**\n * The auto discovery failed. The client is expected to communicate\n * the error to the user and refuse logging in.\n */\n public static readonly FAIL_ERROR = AutoDiscoveryAction.FAIL_ERROR;\n\n /**\n * The auto discovery failed, however the client may still recover\n * from the problem. The client is recommended to that the same\n * action it would for PROMPT while also warning the user about\n * what went wrong. The client may also treat this the same as\n * a FAIL_ERROR state.\n */\n public static readonly FAIL_PROMPT = AutoDiscoveryAction.FAIL_PROMPT;\n\n /**\n * The auto discovery didn't fail but did not find anything of\n * interest. The client is expected to prompt the user for more\n * information, or fail if it prefers.\n */\n public static readonly PROMPT = AutoDiscoveryAction.PROMPT;\n\n /**\n * The auto discovery was successful.\n */\n public static readonly SUCCESS = AutoDiscoveryAction.SUCCESS;\n\n /**\n * Validates and verifies client configuration information for purposes\n * of logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be included, and will be transparently brought into the\n * response object unaltered.\n * @param wellknown - The configuration object itself, as returned\n * by the .well-known auto-discovery endpoint.\n * @returns Promise which resolves to the verified\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when verification fails.\n */\n public static async fromDiscoveryConfig(wellknown?: IClientWellKnown): Promise<ClientConfig> {\n // Step 1 is to get the config, which is provided to us here.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n if (!wellknown?.[\"m.homeserver\"]) {\n logger.error(\"No m.homeserver key in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n\n return Promise.resolve(clientConfig);\n }\n\n if (!wellknown[\"m.homeserver\"][\"base_url\"]) {\n logger.error(\"No m.homeserver base_url in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Make sure the homeserver URL is valid *looking*. We'll make\n // sure it points to a homeserver in Step 3.\n const hsUrl = this.sanitizeWellKnownUrl(wellknown[\"m.homeserver\"][\"base_url\"]);\n if (!hsUrl) {\n logger.error(\"Invalid base_url for m.homeserver\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n return Promise.resolve(clientConfig);\n }\n\n // Step 3: Make sure the homeserver URL points to a homeserver.\n const hsVersions = await this.fetchWellKnownObject<IServerVersions>(`${hsUrl}/_matrix/client/versions`);\n if (!hsVersions || !Array.isArray(hsVersions.raw?.[\"versions\"])) {\n logger.error(\"Invalid /versions response\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 3.1: Non-spec check to ensure the server will actually work for us. We need to check if\n // any of the versions in `SUPPORTED_MATRIX_VERSIONS` are listed in the /versions response.\n const hsVersionSet = new Set(hsVersions.raw![\"versions\"]);\n let supportedVersionFound = false;\n for (const version of SUPPORTED_MATRIX_VERSIONS) {\n if (hsVersionSet.has(version)) {\n supportedVersionFound = true;\n break;\n }\n }\n if (!supportedVersionFound) {\n logger.error(\"Homeserver does not meet version requirements\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 4: Now that the homeserver looks valid, update our client config.\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: hsUrl,\n };\n\n // Step 5: Try to pull out the identity server configuration\n let isUrl: string | boolean = \"\";\n if (wellknown[\"m.identity_server\"]) {\n // We prepare a failing identity server response to save lines later\n // in this branch.\n const failingClientConfig: ClientConfig = {\n \"m.homeserver\": clientConfig[\"m.homeserver\"],\n \"m.identity_server\": {\n state: AutoDiscovery.FAIL_PROMPT,\n error: AutoDiscovery.ERROR_INVALID_IS,\n base_url: null,\n },\n };\n\n // Step 5a: Make sure the URL is valid *looking*. We'll make sure it\n // points to an identity server in Step 5b.\n isUrl = this.sanitizeWellKnownUrl(wellknown[\"m.identity_server\"][\"base_url\"]);\n if (!isUrl) {\n logger.error(\"Invalid base_url for m.identity_server\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;\n return Promise.resolve(failingClientConfig);\n }\n\n // Step 5b: Verify there is an identity server listening on the provided\n // URL.\n const isResponse = await this.fetchWellKnownObject(`${isUrl}/_matrix/identity/v2`);\n if (!isResponse?.raw || isResponse.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"Invalid /v2 response\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;\n\n // Supply the base_url to the caller because they may be ignoring\n // liveliness errors, like this one.\n failingClientConfig[\"m.identity_server\"].base_url = isUrl;\n\n return Promise.resolve(failingClientConfig);\n }\n }\n\n // Step 6: Now that the identity server is valid, or never existed,\n // populate the IS section.\n if (isUrl && isUrl.toString().length > 0) {\n clientConfig[\"m.identity_server\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: isUrl,\n };\n }\n\n // Step 7: Copy any other keys directly into the clientConfig. This is for\n // things like custom configuration of services.\n Object.keys(wellknown).forEach((k: keyof IClientWellKnown) => {\n if (k === \"m.homeserver\" || k === \"m.identity_server\") {\n // Only copy selected parts of the config to avoid overwriting\n // properties computed by the validation logic above.\n const notProps = [\"error\", \"state\", \"base_url\"];\n for (const prop of Object.keys(wellknown[k]!)) {\n if (notProps.includes(prop)) continue;\n type Prop = Exclude<keyof IWellKnownConfig, \"error\" | \"state\" | \"base_url\">;\n // @ts-ignore - ts gets unhappy as we're mixing types here\n clientConfig[k][prop as Prop] = wellknown[k]![prop as Prop];\n }\n } else {\n // Just copy the whole thing over otherwise\n clientConfig[k] = wellknown[k];\n }\n });\n\n // Step 8: Give the config to the caller (finally)\n return Promise.resolve(clientConfig);\n }\n\n /**\n * Attempts to automatically discover client configuration information\n * prior to logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be discovered, and will be transparently included in the\n * response object unaltered.\n * @param domain - The homeserver domain to perform discovery\n * on. For example, \"matrix.org\".\n * @returns Promise which resolves to the discovered\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when discovery fails.\n */\n public static async findClientConfig(domain: string): Promise<ClientConfig> {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n // We use a .well-known lookup for all cases. According to the spec, we\n // can do other discovery mechanisms if we want such as custom lookups\n // however we won't bother with that here (mostly because the spec only\n // supports .well-known right now).\n //\n // By using .well-known, we need to ensure we at least pull out a URL\n // for the homeserver. We don't really need an identity server configuration\n // but will return one anyways (with state PROMPT) to make development\n // easier for clients. If we can't get a homeserver URL, all bets are\n // off on the rest of the config and we'll assume it is invalid too.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n // Step 1: Actually request the .well-known JSON file and make sure it\n // at least has a homeserver definition.\n const domainWithProtocol = domain.includes(\"://\") ? domain : `https://${domain}`;\n const wellknown = await this.fetchWellKnownObject(`${domainWithProtocol}/.well-known/matrix/client`);\n if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"No response or error when parsing .well-known\");\n if (wellknown.reason) logger.error(wellknown.reason);\n if (wellknown.action === AutoDiscoveryAction.IGNORE) {\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n };\n } else {\n // this can only ever be FAIL_PROMPT at this point.\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n }\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Validate and parse the config\n return AutoDiscovery.fromDiscoveryConfig(wellknown.raw!);\n }\n\n /**\n * Gets the raw discovery client configuration for the given domain name.\n * Should only be used if there's no validation to be done on the resulting\n * object, otherwise use findClientConfig().\n * @param domain - The domain to get the client config for.\n * @returns Promise which resolves to the domain's client config. Can\n * be an empty object.\n */\n public static async getRawClientConfig(domain?: string): Promise<IClientWellKnown> {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n const response = await this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`);\n if (!response) return {};\n return response.raw ?? {};\n }\n\n /**\n * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and\n * is suitable for the requirements laid out by .well-known auto discovery.\n * If valid, the URL will also be stripped of any trailing slashes.\n * @param url - The potentially invalid URL to sanitize.\n * @returns The sanitized URL or a falsey value if the URL is invalid.\n * @internal\n */\n private static sanitizeWellKnownUrl(url?: string | null): string | false {\n if (!url) return false;\n\n try {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch (e) {\n logger.error(\"Could not parse url\", e);\n }\n\n if (!parsed?.hostname) return false;\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n\n const port = parsed.port ? `:${parsed.port}` : \"\";\n const path = parsed.pathname ? parsed.pathname : \"\";\n let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`;\n if (saferUrl.endsWith(\"/\")) {\n saferUrl = saferUrl.substring(0, saferUrl.length - 1);\n }\n return saferUrl;\n } catch (e) {\n logger.error(e);\n return false;\n }\n }\n\n private static fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.fetchFn) {\n return this.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n private static fetchFn?: typeof globalThis.fetch;\n\n public static setFetchFn(fetchFn: typeof globalThis.fetch): void {\n AutoDiscovery.fetchFn = fetchFn;\n }\n\n /**\n * Fetches a JSON object from a given URL, as expected by all .well-known\n * related lookups. If the server gives a 404 then the `action` will be\n * IGNORE. If the server returns something that isn't JSON, the `action`\n * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.\n *\n * The returned object will be a result of the call in object form with\n * the following properties:\n * raw: The JSON object returned by the server.\n * action: One of SUCCESS, IGNORE, or FAIL_PROMPT.\n * reason: Relatively human-readable description of what went wrong.\n * error: The actual Error, if one exists.\n * @param url - The URL to fetch a JSON object from.\n * @returns Promise which resolves to the returned state.\n * @internal\n */\n private static async fetchWellKnownObject<T = IWellKnownConfig>(\n url: string,\n ): Promise<IWellKnownConfig<Partial<T>>> {\n let response: Response;\n\n try {\n response = await AutoDiscovery.fetch(url, {\n method: Method.Get,\n signal: timeoutSignal(5000),\n });\n\n if (response.status === 404) {\n return {\n raw: {},\n action: AutoDiscoveryAction.IGNORE,\n reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN,\n };\n }\n\n if (response.status !== 200) {\n return {\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: \"General failure\",\n };\n }\n } catch (err) {\n const error = err as AutoDiscoveryError | string | undefined;\n let reason = \"\";\n if (typeof error === \"object\") {\n reason = (<Error>error)?.message;\n }\n\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: reason || \"General failure\",\n };\n }\n\n try {\n return {\n raw: await response.json(),\n action: AutoDiscoveryAction.SUCCESS,\n };\n } catch (err) {\n const error = err as Error;\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason:\n (error as MatrixError)?.name === \"SyntaxError\"\n ? AutoDiscovery.ERROR_INVALID_JSON\n : AutoDiscovery.ERROR_INVALID,\n };\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,MAAM,QAAQ,aAAa;AACpC,SAA2BC,MAAM,EAAEC,aAAa,QAAQ,qBAAqB;AAC7E,SAASC,yBAAyB,QAAQ,sBAAsB;;AAEhE;AACA;;AAEA,WAAYC,mBAAmB,0BAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAA,OAAnBA,mBAAmB;AAAA;AAQ/B,WAAYC,kBAAkB,0BAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB;EAAlBA,kBAAkB,gGAY1B;EACA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eAAA,CAtDnDzF,aAAa","ignoreList":[]}
1
+ {"version":3,"file":"autodiscovery.js","names":["logger","Method","timeoutSignal","SUPPORTED_MATRIX_VERSIONS","AutoDiscoveryAction","AutoDiscoveryError","AutoDiscovery","fromDiscoveryConfig","wellknown","_this","_asyncToGenerator","_hsVersions$raw","clientConfig","state","FAIL_ERROR","error","ERROR_INVALID","base_url","PROMPT","FAIL_PROMPT","Promise","resolve","ERROR_INVALID_HS_BASE_URL","hsUrl","sanitizeWellKnownUrl","hsVersions","fetchWellKnownObject","concat","Array","isArray","raw","ERROR_INVALID_HOMESERVER","hsVersionSet","Set","supportedVersionFound","version","has","ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION","SUCCESS","isUrl","failingClientConfig","ERROR_INVALID_IS","ERROR_INVALID_IS_BASE_URL","isResponse","action","ERROR_INVALID_IDENTITY_SERVER","toString","length","Object","keys","forEach","k","notProps","prop","includes","findClientConfig","domain","_this2","Error","domainWithProtocol","reason","IGNORE","getRawClientConfig","_this3","_response$raw","response","url","_parsed","parsed","URL","e","hostname","protocol","port","path","pathname","saferUrl","endsWith","substring","fetch","resource","options","fetchFn","globalThis","setFetchFn","method","Get","signal","status","ERROR_MISSING_WELLKNOWN","err","message","json","name","ERROR_INVALID_JSON","_defineProperty","Invalid","GenericFailure","InvalidHsBaseUrl","InvalidHomeserver","InvalidIsBaseUrl","InvalidIdentityServer","InvalidIs","MissingWellknown","InvalidJson","UnsupportedHomeserverSpecVersion"],"sources":["../src/autodiscovery.ts"],"sourcesContent":["/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 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 IClientWellKnown, type IWellKnownConfig, type IServerVersions } from \"./client.ts\";\nimport { logger } from \"./logger.ts\";\nimport { type MatrixError, Method, timeoutSignal } from \"./http-api/index.ts\";\nimport { SUPPORTED_MATRIX_VERSIONS } from \"./version-support.ts\";\n\n// Dev note: Auto discovery is part of the spec.\n// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery\n\nexport enum AutoDiscoveryAction {\n SUCCESS = \"SUCCESS\",\n IGNORE = \"IGNORE\",\n PROMPT = \"PROMPT\",\n FAIL_PROMPT = \"FAIL_PROMPT\",\n FAIL_ERROR = \"FAIL_ERROR\",\n}\n\nexport enum AutoDiscoveryError {\n Invalid = \"Invalid homeserver discovery response\",\n GenericFailure = \"Failed to get autodiscovery configuration from server\",\n InvalidHsBaseUrl = \"Invalid base_url for m.homeserver\",\n InvalidHomeserver = \"Homeserver URL does not appear to be a valid Matrix homeserver\",\n InvalidIsBaseUrl = \"Invalid base_url for m.identity_server\",\n InvalidIdentityServer = \"Identity server URL does not appear to be a valid identity server\",\n InvalidIs = \"Invalid identity server discovery response\",\n MissingWellknown = \"No .well-known JSON file found\",\n InvalidJson = \"Invalid JSON\",\n UnsupportedHomeserverSpecVersion = \"The homeserver does not meet the version requirements\",\n\n // TODO: Implement when Sydent supports the `/versions` endpoint - https://github.com/matrix-org/sydent/issues/424\n //IdentityServerTooOld = \"The identity server does not meet the minimum version requirements\",\n}\n\ninterface AutoDiscoveryState {\n state: AutoDiscoveryAction;\n error?: IWellKnownConfig[\"error\"] | null;\n}\ninterface WellKnownConfig extends Omit<IWellKnownConfig, \"error\">, AutoDiscoveryState {}\n\nexport interface ClientConfig extends Omit<IClientWellKnown, \"m.homeserver\" | \"m.identity_server\"> {\n \"m.homeserver\": WellKnownConfig;\n \"m.identity_server\": WellKnownConfig;\n}\n\n/**\n * Utilities for automatically discovery resources, such as homeservers\n * for users to log in to.\n */\nexport class AutoDiscovery {\n // Dev note: the constants defined here are related to but not\n // exactly the same as those in the spec. This is to hopefully\n // translate the meaning of the states in the spec, but also\n // support our own if needed.\n\n public static readonly ERROR_INVALID = AutoDiscoveryError.Invalid;\n\n public static readonly ERROR_GENERIC_FAILURE = AutoDiscoveryError.GenericFailure;\n\n public static readonly ERROR_INVALID_HS_BASE_URL = AutoDiscoveryError.InvalidHsBaseUrl;\n\n public static readonly ERROR_INVALID_HOMESERVER = AutoDiscoveryError.InvalidHomeserver;\n\n public static readonly ERROR_INVALID_IS_BASE_URL = AutoDiscoveryError.InvalidIsBaseUrl;\n\n public static readonly ERROR_INVALID_IDENTITY_SERVER = AutoDiscoveryError.InvalidIdentityServer;\n\n public static readonly ERROR_INVALID_IS = AutoDiscoveryError.InvalidIs;\n\n public static readonly ERROR_MISSING_WELLKNOWN = AutoDiscoveryError.MissingWellknown;\n\n public static readonly ERROR_INVALID_JSON = AutoDiscoveryError.InvalidJson;\n\n public static readonly ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION =\n AutoDiscoveryError.UnsupportedHomeserverSpecVersion;\n\n public static readonly ALL_ERRORS = Object.keys(AutoDiscoveryError) as AutoDiscoveryError[];\n\n /**\n * The auto discovery failed. The client is expected to communicate\n * the error to the user and refuse logging in.\n */\n public static readonly FAIL_ERROR = AutoDiscoveryAction.FAIL_ERROR;\n\n /**\n * The auto discovery failed, however the client may still recover\n * from the problem. The client is recommended to that the same\n * action it would for PROMPT while also warning the user about\n * what went wrong. The client may also treat this the same as\n * a FAIL_ERROR state.\n */\n public static readonly FAIL_PROMPT = AutoDiscoveryAction.FAIL_PROMPT;\n\n /**\n * The auto discovery didn't fail but did not find anything of\n * interest. The client is expected to prompt the user for more\n * information, or fail if it prefers.\n */\n public static readonly PROMPT = AutoDiscoveryAction.PROMPT;\n\n /**\n * The auto discovery was successful.\n */\n public static readonly SUCCESS = AutoDiscoveryAction.SUCCESS;\n\n /**\n * Validates and verifies client configuration information for purposes\n * of logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be included, and will be transparently brought into the\n * response object unaltered.\n * @param wellknown - The configuration object itself, as returned\n * by the .well-known auto-discovery endpoint.\n * @returns Promise which resolves to the verified\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when verification fails.\n */\n public static async fromDiscoveryConfig(wellknown?: IClientWellKnown): Promise<ClientConfig> {\n // Step 1 is to get the config, which is provided to us here.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n if (!wellknown?.[\"m.homeserver\"]) {\n logger.error(\"No m.homeserver key in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n\n return Promise.resolve(clientConfig);\n }\n\n if (!wellknown[\"m.homeserver\"][\"base_url\"]) {\n logger.error(\"No m.homeserver base_url in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Make sure the homeserver URL is valid *looking*. We'll make\n // sure it points to a homeserver in Step 3.\n const hsUrl = this.sanitizeWellKnownUrl(wellknown[\"m.homeserver\"][\"base_url\"]);\n if (!hsUrl) {\n logger.error(\"Invalid base_url for m.homeserver\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n return Promise.resolve(clientConfig);\n }\n\n // Step 3: Make sure the homeserver URL points to a homeserver.\n const hsVersions = await this.fetchWellKnownObject<IServerVersions>(`${hsUrl}/_matrix/client/versions`);\n if (!hsVersions || !Array.isArray(hsVersions.raw?.[\"versions\"])) {\n logger.error(\"Invalid /versions response\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 3.1: Non-spec check to ensure the server will actually work for us. We need to check if\n // any of the versions in `SUPPORTED_MATRIX_VERSIONS` are listed in the /versions response.\n const hsVersionSet = new Set(hsVersions.raw![\"versions\"]);\n let supportedVersionFound = false;\n for (const version of SUPPORTED_MATRIX_VERSIONS) {\n if (hsVersionSet.has(version)) {\n supportedVersionFound = true;\n break;\n }\n }\n if (!supportedVersionFound) {\n logger.error(\"Homeserver does not meet version requirements\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 4: Now that the homeserver looks valid, update our client config.\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: hsUrl,\n };\n\n // Step 5: Try to pull out the identity server configuration\n let isUrl: string | boolean = \"\";\n if (wellknown[\"m.identity_server\"]) {\n // We prepare a failing identity server response to save lines later\n // in this branch.\n const failingClientConfig: ClientConfig = {\n \"m.homeserver\": clientConfig[\"m.homeserver\"],\n \"m.identity_server\": {\n state: AutoDiscovery.FAIL_PROMPT,\n error: AutoDiscovery.ERROR_INVALID_IS,\n base_url: null,\n },\n };\n\n // Step 5a: Make sure the URL is valid *looking*. We'll make sure it\n // points to an identity server in Step 5b.\n isUrl = this.sanitizeWellKnownUrl(wellknown[\"m.identity_server\"][\"base_url\"]);\n if (!isUrl) {\n logger.error(\"Invalid base_url for m.identity_server\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;\n return Promise.resolve(failingClientConfig);\n }\n\n // Step 5b: Verify there is an identity server listening on the provided\n // URL.\n const isResponse = await this.fetchWellKnownObject(`${isUrl}/_matrix/identity/v2`);\n if (!isResponse?.raw || isResponse.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"Invalid /v2 response\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;\n\n // Supply the base_url to the caller because they may be ignoring\n // liveliness errors, like this one.\n failingClientConfig[\"m.identity_server\"].base_url = isUrl;\n\n return Promise.resolve(failingClientConfig);\n }\n }\n\n // Step 6: Now that the identity server is valid, or never existed,\n // populate the IS section.\n if (isUrl && isUrl.toString().length > 0) {\n clientConfig[\"m.identity_server\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: isUrl,\n };\n }\n\n // Step 7: Copy any other keys directly into the clientConfig. This is for\n // things like custom configuration of services.\n Object.keys(wellknown).forEach((k: keyof IClientWellKnown) => {\n if (k === \"m.homeserver\" || k === \"m.identity_server\") {\n // Only copy selected parts of the config to avoid overwriting\n // properties computed by the validation logic above.\n const notProps = [\"error\", \"state\", \"base_url\"];\n for (const prop of Object.keys(wellknown[k]!)) {\n if (notProps.includes(prop)) continue;\n type Prop = Exclude<keyof IWellKnownConfig, \"error\" | \"state\" | \"base_url\">;\n // @ts-ignore - ts gets unhappy as we're mixing types here\n clientConfig[k][prop as Prop] = wellknown[k]![prop as Prop];\n }\n } else {\n // Just copy the whole thing over otherwise\n clientConfig[k] = wellknown[k];\n }\n });\n\n // Step 8: Give the config to the caller (finally)\n return Promise.resolve(clientConfig);\n }\n\n /**\n * Attempts to automatically discover client configuration information\n * prior to logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be discovered, and will be transparently included in the\n * response object unaltered.\n * @param domain - The homeserver domain to perform discovery\n * on. For example, \"matrix.org\".\n * @returns Promise which resolves to the discovered\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when discovery fails.\n */\n public static async findClientConfig(domain: string): Promise<ClientConfig> {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n // We use a .well-known lookup for all cases. According to the spec, we\n // can do other discovery mechanisms if we want such as custom lookups\n // however we won't bother with that here (mostly because the spec only\n // supports .well-known right now).\n //\n // By using .well-known, we need to ensure we at least pull out a URL\n // for the homeserver. We don't really need an identity server configuration\n // but will return one anyways (with state PROMPT) to make development\n // easier for clients. If we can't get a homeserver URL, all bets are\n // off on the rest of the config and we'll assume it is invalid too.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n // Step 1: Actually request the .well-known JSON file and make sure it\n // at least has a homeserver definition.\n const domainWithProtocol = domain.includes(\"://\") ? domain : `https://${domain}`;\n const wellknown = await this.fetchWellKnownObject(`${domainWithProtocol}/.well-known/matrix/client`);\n if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"No response or error when parsing .well-known\");\n if (wellknown.reason) logger.error(wellknown.reason);\n if (wellknown.action === AutoDiscoveryAction.IGNORE) {\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n };\n } else {\n // this can only ever be FAIL_PROMPT at this point.\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n }\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Validate and parse the config\n return AutoDiscovery.fromDiscoveryConfig(wellknown.raw!);\n }\n\n /**\n * Gets the raw discovery client configuration for the given domain name.\n * Should only be used if there's no validation to be done on the resulting\n * object, otherwise use findClientConfig().\n * @param domain - The domain to get the client config for.\n * @returns Promise which resolves to the domain's client config. Can\n * be an empty object.\n */\n public static async getRawClientConfig(domain?: string): Promise<IClientWellKnown> {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n const response = await this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`);\n if (!response) return {};\n return response.raw ?? {};\n }\n\n /**\n * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and\n * is suitable for the requirements laid out by .well-known auto discovery.\n * If valid, the URL will also be stripped of any trailing slashes.\n * @param url - The potentially invalid URL to sanitize.\n * @returns The sanitized URL or a falsey value if the URL is invalid.\n * @internal\n */\n private static sanitizeWellKnownUrl(url?: string | null): string | false {\n if (!url) return false;\n\n try {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch (e) {\n logger.error(\"Could not parse url\", e);\n }\n\n if (!parsed?.hostname) return false;\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n\n const port = parsed.port ? `:${parsed.port}` : \"\";\n const path = parsed.pathname ? parsed.pathname : \"\";\n let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`;\n if (saferUrl.endsWith(\"/\")) {\n saferUrl = saferUrl.substring(0, saferUrl.length - 1);\n }\n return saferUrl;\n } catch (e) {\n logger.error(e);\n return false;\n }\n }\n\n private static fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.fetchFn) {\n return this.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n private static fetchFn?: typeof globalThis.fetch;\n\n public static setFetchFn(fetchFn: typeof globalThis.fetch): void {\n AutoDiscovery.fetchFn = fetchFn;\n }\n\n /**\n * Fetches a JSON object from a given URL, as expected by all .well-known\n * related lookups. If the server gives a 404 then the `action` will be\n * IGNORE. If the server returns something that isn't JSON, the `action`\n * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.\n *\n * The returned object will be a result of the call in object form with\n * the following properties:\n * raw: The JSON object returned by the server.\n * action: One of SUCCESS, IGNORE, or FAIL_PROMPT.\n * reason: Relatively human-readable description of what went wrong.\n * error: The actual Error, if one exists.\n * @param url - The URL to fetch a JSON object from.\n * @returns Promise which resolves to the returned state.\n * @internal\n */\n private static async fetchWellKnownObject<T = IWellKnownConfig>(\n url: string,\n ): Promise<IWellKnownConfig<Partial<T>>> {\n let response: Response;\n\n try {\n response = await AutoDiscovery.fetch(url, {\n method: Method.Get,\n signal: timeoutSignal(5000),\n });\n\n if (response.status === 404) {\n return {\n raw: {},\n action: AutoDiscoveryAction.IGNORE,\n reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN,\n };\n }\n\n if (response.status !== 200) {\n return {\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: \"General failure\",\n };\n }\n } catch (err) {\n const error = err as AutoDiscoveryError | string | undefined;\n let reason = \"\";\n if (typeof error === \"object\") {\n reason = (<Error>error)?.message;\n }\n\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: reason || \"General failure\",\n };\n }\n\n try {\n return {\n raw: await response.json(),\n action: AutoDiscoveryAction.SUCCESS,\n };\n } catch (err) {\n const error = err as Error;\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason:\n (error as MatrixError)?.name === \"SyntaxError\"\n ? AutoDiscovery.ERROR_INVALID_JSON\n : AutoDiscovery.ERROR_INVALID,\n };\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,MAAM,QAAQ,aAAa;AACpC,SAA2BC,MAAM,EAAEC,aAAa,QAAQ,qBAAqB;AAC7E,SAASC,yBAAyB,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