matrix-js-sdk 42.0.0 → 42.1.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 (226) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/lib/@types/PushRules.d.ts.map +1 -1
  3. package/lib/@types/PushRules.js +0 -5
  4. package/lib/@types/PushRules.js.map +1 -1
  5. package/lib/@types/auth.d.ts.map +1 -1
  6. package/lib/@types/auth.js +0 -5
  7. package/lib/@types/auth.js.map +1 -1
  8. package/lib/@types/crypto.d.ts.map +1 -1
  9. package/lib/@types/crypto.js.map +1 -1
  10. package/lib/@types/event.d.ts +3 -1
  11. package/lib/@types/event.d.ts.map +1 -1
  12. package/lib/@types/event.js +1 -0
  13. package/lib/@types/event.js.map +1 -1
  14. package/lib/@types/extensible_events.js.map +1 -1
  15. package/lib/@types/matrix-sdk-crypto-wasm.d.js.map +1 -1
  16. package/lib/@types/media.js.map +1 -1
  17. package/lib/@types/partials.d.ts.map +1 -1
  18. package/lib/@types/partials.js.map +1 -1
  19. package/lib/@types/requests.d.ts.map +1 -1
  20. package/lib/@types/requests.js +0 -5
  21. package/lib/@types/requests.js.map +1 -1
  22. package/lib/@types/search.d.ts.map +1 -1
  23. package/lib/@types/search.js +0 -3
  24. package/lib/@types/search.js.map +1 -1
  25. package/lib/@types/spaces.d.ts.map +1 -1
  26. package/lib/@types/spaces.js.map +1 -1
  27. package/lib/@types/synapse.d.ts.map +1 -1
  28. package/lib/@types/synapse.js.map +1 -1
  29. package/lib/@types/threepids.js.map +1 -1
  30. package/lib/ToDeviceMessageQueue.d.ts.map +1 -1
  31. package/lib/ToDeviceMessageQueue.js +0 -2
  32. package/lib/ToDeviceMessageQueue.js.map +1 -1
  33. package/lib/browser-index.d.ts.map +1 -1
  34. package/lib/browser-index.js +3 -1
  35. package/lib/browser-index.js.map +1 -1
  36. package/lib/client.d.ts +5 -8
  37. package/lib/client.d.ts.map +1 -1
  38. package/lib/client.js +5 -46
  39. package/lib/client.js.map +1 -1
  40. package/lib/common-crypto/key-passphrase.d.ts.map +1 -1
  41. package/lib/common-crypto/key-passphrase.js +0 -3
  42. package/lib/common-crypto/key-passphrase.js.map +1 -1
  43. package/lib/crypto/store/base.d.ts.map +1 -1
  44. package/lib/crypto/store/base.js +0 -9
  45. package/lib/crypto/store/base.js.map +1 -1
  46. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  47. package/lib/crypto/store/localStorage-crypto-store.d.ts.map +1 -1
  48. package/lib/crypto/store/localStorage-crypto-store.js +0 -2
  49. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  50. package/lib/crypto-api/keybackup.d.ts +13 -6
  51. package/lib/crypto-api/keybackup.d.ts.map +1 -1
  52. package/lib/crypto-api/keybackup.js.map +1 -1
  53. package/lib/embedded.d.ts.map +1 -1
  54. package/lib/embedded.js +0 -5
  55. package/lib/embedded.js.map +1 -1
  56. package/lib/feature.d.ts.map +1 -1
  57. package/lib/feature.js +0 -3
  58. package/lib/feature.js.map +1 -1
  59. package/lib/filter-component.d.ts.map +1 -1
  60. package/lib/filter-component.js +2 -5
  61. package/lib/filter-component.js.map +1 -1
  62. package/lib/filter.d.ts.map +1 -1
  63. package/lib/filter.js +0 -4
  64. package/lib/filter.js.map +1 -1
  65. package/lib/http-api/interface.d.ts.map +1 -1
  66. package/lib/http-api/interface.js.map +1 -1
  67. package/lib/http-api/refresh.d.ts.map +1 -1
  68. package/lib/http-api/refresh.js +0 -3
  69. package/lib/http-api/refresh.js.map +1 -1
  70. package/lib/interactive-auth.d.ts.map +1 -1
  71. package/lib/interactive-auth.js +5 -6
  72. package/lib/interactive-auth.js.map +1 -1
  73. package/lib/logger.d.ts.map +1 -1
  74. package/lib/logger.js +0 -2
  75. package/lib/logger.js.map +1 -1
  76. package/lib/matrixrtc/CallMembership.d.ts +3 -3
  77. package/lib/matrixrtc/CallMembership.js +5 -5
  78. package/lib/matrixrtc/CallMembership.js.map +1 -1
  79. package/lib/matrixrtc/MatrixRTCSession.d.ts +18 -1
  80. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  81. package/lib/matrixrtc/MatrixRTCSession.js +56 -4
  82. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  83. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts +14 -1
  84. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts.map +1 -1
  85. package/lib/matrixrtc/MatrixRTCSessionManager.js +20 -1
  86. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  87. package/lib/matrixrtc/MembershipManager.d.ts.map +1 -1
  88. package/lib/matrixrtc/MembershipManager.js +9 -6
  89. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  90. package/lib/matrixrtc/index.d.ts +1 -1
  91. package/lib/matrixrtc/index.d.ts.map +1 -1
  92. package/lib/matrixrtc/index.js +1 -1
  93. package/lib/matrixrtc/index.js.map +1 -1
  94. package/lib/matrixrtc/membershipData/rtc.d.ts +6 -3
  95. package/lib/matrixrtc/membershipData/rtc.d.ts.map +1 -1
  96. package/lib/matrixrtc/membershipData/rtc.js +7 -4
  97. package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
  98. package/lib/matrixrtc/types.d.ts +19 -6
  99. package/lib/matrixrtc/types.d.ts.map +1 -1
  100. package/lib/matrixrtc/types.js +11 -1
  101. package/lib/matrixrtc/types.js.map +1 -1
  102. package/lib/models/event.d.ts.map +1 -1
  103. package/lib/models/event.js +0 -6
  104. package/lib/models/event.js.map +1 -1
  105. package/lib/models/room-state.d.ts.map +1 -1
  106. package/lib/models/room-state.js.map +1 -1
  107. package/lib/models/room.d.ts.map +1 -1
  108. package/lib/models/room.js +6 -6
  109. package/lib/models/room.js.map +1 -1
  110. package/lib/models/thread.d.ts +2 -2
  111. package/lib/models/thread.d.ts.map +1 -1
  112. package/lib/models/thread.js.map +1 -1
  113. package/lib/realtime-callbacks.js +0 -1
  114. package/lib/realtime-callbacks.js.map +1 -1
  115. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +1 -1
  116. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +0 -1
  117. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  118. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +1 -1
  119. package/lib/rust-crypto/OutgoingRequestProcessor.js +0 -2
  120. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  121. package/lib/rust-crypto/backup.d.ts +21 -1
  122. package/lib/rust-crypto/backup.d.ts.map +1 -1
  123. package/lib/rust-crypto/backup.js +62 -21
  124. package/lib/rust-crypto/backup.js.map +1 -1
  125. package/lib/rust-crypto/device-converter.d.ts.map +1 -1
  126. package/lib/rust-crypto/device-converter.js +1 -0
  127. package/lib/rust-crypto/device-converter.js.map +1 -1
  128. package/lib/rust-crypto/index.d.ts +7 -0
  129. package/lib/rust-crypto/index.d.ts.map +1 -1
  130. package/lib/rust-crypto/index.js +3 -3
  131. package/lib/rust-crypto/index.js.map +1 -1
  132. package/lib/rust-crypto/libolm_migration.d.ts.map +1 -1
  133. package/lib/rust-crypto/libolm_migration.js +0 -2
  134. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  135. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  136. package/lib/rust-crypto/rust-crypto.js +0 -3
  137. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  138. package/lib/scheduler.d.ts.map +1 -1
  139. package/lib/scheduler.js +0 -3
  140. package/lib/scheduler.js.map +1 -1
  141. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  142. package/lib/sliding-sync-sdk.js +6 -0
  143. package/lib/sliding-sync-sdk.js.map +1 -1
  144. package/lib/sliding-sync.d.ts.map +1 -1
  145. package/lib/sliding-sync.js +3 -0
  146. package/lib/sliding-sync.js.map +1 -1
  147. package/lib/store/indexeddb.d.ts.map +1 -1
  148. package/lib/store/indexeddb.js +0 -2
  149. package/lib/store/indexeddb.js.map +1 -1
  150. package/lib/store/memory.d.ts.map +1 -1
  151. package/lib/store/memory.js +7 -9
  152. package/lib/store/memory.js.map +1 -1
  153. package/lib/sync-accumulator.d.ts.map +1 -1
  154. package/lib/sync-accumulator.js +1 -5
  155. package/lib/sync-accumulator.js.map +1 -1
  156. package/lib/sync.d.ts.map +1 -1
  157. package/lib/sync.js +1 -1
  158. package/lib/sync.js.map +1 -1
  159. package/lib/timeline-window.d.ts.map +1 -1
  160. package/lib/timeline-window.js +0 -1
  161. package/lib/timeline-window.js.map +1 -1
  162. package/lib/utils/internal/deriveKeys.d.ts.map +1 -1
  163. package/lib/utils/internal/deriveKeys.js +0 -1
  164. package/lib/utils/internal/deriveKeys.js.map +1 -1
  165. package/lib/webrtc/callEventTypes.d.ts.map +1 -1
  166. package/lib/webrtc/callEventTypes.js +0 -5
  167. package/lib/webrtc/callEventTypes.js.map +1 -1
  168. package/package.json +5 -5
  169. package/src/@types/PushRules.ts +0 -5
  170. package/src/@types/auth.ts +0 -6
  171. package/src/@types/crypto.ts +2 -6
  172. package/src/@types/event.ts +3 -0
  173. package/src/@types/extensible_events.ts +4 -4
  174. package/src/@types/matrix-sdk-crypto-wasm.d.ts +0 -1
  175. package/src/@types/media.ts +1 -1
  176. package/src/@types/partials.ts +0 -2
  177. package/src/@types/requests.ts +0 -5
  178. package/src/@types/search.ts +0 -2
  179. package/src/@types/spaces.ts +0 -2
  180. package/src/@types/synapse.ts +0 -2
  181. package/src/@types/threepids.ts +2 -2
  182. package/src/ToDeviceMessageQueue.ts +0 -2
  183. package/src/browser-index.ts +3 -3
  184. package/src/client.ts +18 -61
  185. package/src/common-crypto/key-passphrase.ts +0 -1
  186. package/src/crypto/store/base.ts +1 -8
  187. package/src/crypto/store/indexeddb-crypto-store-backend.ts +1 -1
  188. package/src/crypto/store/localStorage-crypto-store.ts +0 -1
  189. package/src/crypto-api/keybackup.ts +14 -7
  190. package/src/embedded.ts +0 -5
  191. package/src/feature.ts +0 -3
  192. package/src/filter-component.ts +1 -2
  193. package/src/filter.ts +0 -3
  194. package/src/http-api/interface.ts +0 -1
  195. package/src/http-api/refresh.ts +0 -1
  196. package/src/interactive-auth.ts +4 -4
  197. package/src/logger.ts +0 -2
  198. package/src/matrixrtc/CallMembership.ts +5 -5
  199. package/src/matrixrtc/MatrixRTCSession.ts +70 -3
  200. package/src/matrixrtc/MatrixRTCSessionManager.ts +21 -2
  201. package/src/matrixrtc/MembershipManager.ts +8 -5
  202. package/src/matrixrtc/index.ts +1 -1
  203. package/src/matrixrtc/membershipData/rtc.ts +18 -7
  204. package/src/matrixrtc/types.ts +24 -7
  205. package/src/models/event.ts +0 -3
  206. package/src/models/room-state.ts +0 -3
  207. package/src/models/room.ts +6 -6
  208. package/src/models/thread.ts +2 -2
  209. package/src/realtime-callbacks.ts +0 -1
  210. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +0 -1
  211. package/src/rust-crypto/OutgoingRequestProcessor.ts +0 -1
  212. package/src/rust-crypto/backup.ts +66 -28
  213. package/src/rust-crypto/device-converter.ts +1 -0
  214. package/src/rust-crypto/index.ts +11 -0
  215. package/src/rust-crypto/libolm_migration.ts +0 -2
  216. package/src/rust-crypto/rust-crypto.ts +0 -3
  217. package/src/scheduler.ts +0 -3
  218. package/src/sliding-sync-sdk.ts +3 -0
  219. package/src/sliding-sync.ts +2 -0
  220. package/src/store/indexeddb.ts +0 -2
  221. package/src/store/memory.ts +7 -9
  222. package/src/sync-accumulator.ts +1 -3
  223. package/src/sync.ts +1 -3
  224. package/src/timeline-window.ts +0 -1
  225. package/src/utils/internal/deriveKeys.ts +0 -1
  226. package/src/webrtc/callEventTypes.ts +0 -5
@@ -1 +1 @@
1
- {"version":3,"file":"interface.js","names":[],"sources":["../../src/http-api/interface.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type MatrixError } from \"./errors.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { type QueryDict } from \"../utils.ts\";\n\nexport type Body = Record<string, any> | BodyInit;\n\n/**\n * Unencrypted access and (optional) refresh token\n */\nexport type AccessTokens = {\n /**\n * The new access token to use for authenticated requests\n */\n accessToken: string;\n /**\n * The new refresh token to use for refreshing tokens, optional\n */\n refreshToken?: string;\n /**\n * Approximate date when the access token will expire, optional\n */\n expiry?: Date;\n};\n\n/**\n * Function that performs token refresh using the given refreshToken.\n * Returns a promise that resolves to the refreshed access and (optional) refresh tokens.\n *\n * Can be passed to HttpApi instance as {@link IHttpOpts.tokenRefreshFunction} during client creation {@link ICreateClientOpts}\n */\nexport type TokenRefreshFunction = (refreshToken: string) => Promise<AccessTokens>;\n\n/** Options object for `FetchHttpApi` and {@link MatrixHttpApi}. */\nexport interface IHttpOpts {\n fetchFn?: typeof globalThis.fetch;\n\n baseUrl: string;\n idBaseUrl?: string;\n prefix: string;\n extraParams?: QueryDict;\n\n accessToken?: string;\n /**\n * Used in conjunction with tokenRefreshFunction to attempt token refresh\n */\n refreshToken?: string;\n /**\n * Function to attempt token refresh when a possibly expired token is encountered\n * Optional, only called when a refreshToken is present\n */\n tokenRefreshFunction?: TokenRefreshFunction;\n\n /**\n * Whether to use the HTTP Authorization header over the `access_token` query parameter\n * @deprecated as of v1.11 in https://spec.matrix.org/v1.17/client-server-api/#using-access-tokens\n */\n useAuthorizationHeader?: boolean; // defaults to true\n\n /** For historical reasons, must be set to `true`. Will eventually be removed. */\n onlyData?: boolean;\n\n localTimeoutMs?: number;\n\n /** Optional logger instance. If provided, requests and responses will be logged. */\n logger?: Logger;\n}\n\n/** Options object for `FetchHttpApi.requestOtherUrl`. */\nexport interface BaseRequestOpts extends Pick<RequestInit, \"priority\"> {\n /**\n * map of additional request headers\n */\n headers?: Record<string, string>;\n abortSignal?: AbortSignal;\n /**\n * The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n keepAlive?: boolean; // defaults to false\n\n /**\n * By default, we will:\n *\n * * If the `body` is an object, JSON-encode it and set `Content-Type: application/json` in the\n * request headers (unless overridden by {@link headers}).\n *\n * * Set `Accept: application/json` in the request headers (again, unless overridden by {@link headers}).\n *\n * * Parse the response as JSON and return the parsed response.\n *\n * Setting this to `false` inhibits all three behaviors, and the response is instead parsed as a UTF-8 string. It\n * defaults to `true`, unless {@link rawResponseBody} is set.\n *\n * @deprecated Instead of setting this to `false`, set {@link rawResponseBody} to `true`.\n */\n json?: boolean;\n\n /**\n * Setting this to `true` does two things:\n *\n * * Inhibits the automatic addition of `Accept: application/json` in the request headers.\n *\n * * Causes the raw response to be returned as a {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob|Blob}\n * instead of parsing it as JSON.\n */\n rawResponseBody?: boolean;\n}\n\nexport interface IRequestOpts extends BaseRequestOpts {\n /**\n * The alternative base url to use.\n * If not specified, uses this.opts.baseUrl\n */\n baseUrl?: string;\n /**\n * The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n */\n prefix?: string;\n\n // Set to true to prevent the request function from emitting a Session.logged_out event.\n // This is intended for use on endpoints where M_UNKNOWN_TOKEN is a valid/notable error response,\n // such as with token refreshes.\n inhibitLogoutEmit?: boolean;\n}\n\nexport enum HttpApiEvent {\n SessionLoggedOut = \"Session.logged_out\",\n NoConsent = \"no_consent\",\n}\n\nexport type HttpApiEventHandlerMap = {\n /**\n * Fires whenever the login session the JS SDK is using is no\n * longer valid and the user must log in again.\n * NB. This only fires when action is required from the user, not\n * when then login session can be renewed by using a refresh token.\n * @example\n * ```\n * matrixClient.on(\"Session.logged_out\", function(errorObj){\n * // show the login screen\n * });\n * ```\n */\n [HttpApiEvent.SessionLoggedOut]: (err: MatrixError) => void;\n /**\n * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response\n * to a HTTP request.\n * @example\n * ```\n * matrixClient.on(\"no_consent\", function(message, contentUri) {\n * console.info(message + ' Go to ' + contentUri);\n * });\n * ```\n */\n [HttpApiEvent.NoConsent]: (message: string, consentUri: string) => void;\n};\n\nexport interface UploadProgress {\n loaded: number;\n total: number;\n}\n\nexport interface UploadOpts {\n /**\n * Name to give the file on the server. Defaults to <tt>file.name</tt>.\n */\n name?: string;\n /**\n * Content-type for the upload. Defaults to\n * <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.\n */\n type?: string;\n /**\n * if false will not send the filename,\n * e.g for encrypted file uploads where filename leaks are undesirable.\n * Defaults to true.\n */\n includeFilename?: boolean;\n /**\n * Optional. Called when a chunk of\n * data has been uploaded, with an object containing the fields `loaded`\n * (number of bytes transferred) and `total` (total size, if known).\n */\n progressHandler?(progress: UploadProgress): void;\n abortController?: AbortController;\n}\n\nexport interface Upload {\n loaded: number;\n total: number;\n promise: Promise<UploadResponse>;\n abortController: AbortController;\n}\n\nexport interface UploadResponse {\n // eslint-disable-next-line camelcase\n content_uri: string;\n}\n\nexport type FileType = XMLHttpRequestBodyInit;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;;AAGA;;AAmCA;;AA4DA,WAAY,YAAY,0BAAZ,YAAY;EAAZ,YAAY;EAAZ,YAAY;EAAA,OAAZ,YAAY;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"interface.js","names":[],"sources":["../../src/http-api/interface.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type MatrixError } from \"./errors.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { type QueryDict } from \"../utils.ts\";\n\nexport type Body = Record<string, any> | BodyInit;\n\n/**\n * Unencrypted access and (optional) refresh token\n */\nexport type AccessTokens = {\n /**\n * The new access token to use for authenticated requests\n */\n accessToken: string;\n /**\n * The new refresh token to use for refreshing tokens, optional\n */\n refreshToken?: string;\n /**\n * Approximate date when the access token will expire, optional\n */\n expiry?: Date;\n};\n\n/**\n * Function that performs token refresh using the given refreshToken.\n * Returns a promise that resolves to the refreshed access and (optional) refresh tokens.\n *\n * Can be passed to HttpApi instance as {@link IHttpOpts.tokenRefreshFunction} during client creation {@link ICreateClientOpts}\n */\nexport type TokenRefreshFunction = (refreshToken: string) => Promise<AccessTokens>;\n\n/** Options object for `FetchHttpApi` and {@link MatrixHttpApi}. */\nexport interface IHttpOpts {\n fetchFn?: typeof globalThis.fetch;\n\n baseUrl: string;\n idBaseUrl?: string;\n prefix: string;\n extraParams?: QueryDict;\n\n accessToken?: string;\n /**\n * Used in conjunction with tokenRefreshFunction to attempt token refresh\n */\n refreshToken?: string;\n /**\n * Function to attempt token refresh when a possibly expired token is encountered\n * Optional, only called when a refreshToken is present\n */\n tokenRefreshFunction?: TokenRefreshFunction;\n\n /**\n * Whether to use the HTTP Authorization header over the `access_token` query parameter\n * @deprecated as of v1.11 in https://spec.matrix.org/v1.17/client-server-api/#using-access-tokens\n */\n useAuthorizationHeader?: boolean; // defaults to true\n\n /** For historical reasons, must be set to `true`. Will eventually be removed. */\n onlyData?: boolean;\n\n localTimeoutMs?: number;\n\n /** Optional logger instance. If provided, requests and responses will be logged. */\n logger?: Logger;\n}\n\n/** Options object for `FetchHttpApi.requestOtherUrl`. */\nexport interface BaseRequestOpts extends Pick<RequestInit, \"priority\"> {\n /**\n * map of additional request headers\n */\n headers?: Record<string, string>;\n abortSignal?: AbortSignal;\n /**\n * The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n keepAlive?: boolean; // defaults to false\n\n /**\n * By default, we will:\n *\n * * If the `body` is an object, JSON-encode it and set `Content-Type: application/json` in the\n * request headers (unless overridden by {@link headers}).\n *\n * * Set `Accept: application/json` in the request headers (again, unless overridden by {@link headers}).\n *\n * * Parse the response as JSON and return the parsed response.\n *\n * Setting this to `false` inhibits all three behaviors, and the response is instead parsed as a UTF-8 string. It\n * defaults to `true`, unless {@link rawResponseBody} is set.\n *\n * @deprecated Instead of setting this to `false`, set {@link rawResponseBody} to `true`.\n */\n json?: boolean;\n\n /**\n * Setting this to `true` does two things:\n *\n * * Inhibits the automatic addition of `Accept: application/json` in the request headers.\n *\n * * Causes the raw response to be returned as a {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob|Blob}\n * instead of parsing it as JSON.\n */\n rawResponseBody?: boolean;\n}\n\nexport interface IRequestOpts extends BaseRequestOpts {\n /**\n * The alternative base url to use.\n * If not specified, uses this.opts.baseUrl\n */\n baseUrl?: string;\n /**\n * The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n */\n prefix?: string;\n\n // Set to true to prevent the request function from emitting a Session.logged_out event.\n // This is intended for use on endpoints where M_UNKNOWN_TOKEN is a valid/notable error response,\n // such as with token refreshes.\n inhibitLogoutEmit?: boolean;\n}\n\nexport enum HttpApiEvent {\n SessionLoggedOut = \"Session.logged_out\",\n NoConsent = \"no_consent\",\n}\n\nexport type HttpApiEventHandlerMap = {\n /**\n * Fires whenever the login session the JS SDK is using is no\n * longer valid and the user must log in again.\n * NB. This only fires when action is required from the user, not\n * when then login session can be renewed by using a refresh token.\n * @example\n * ```\n * matrixClient.on(\"Session.logged_out\", function(errorObj){\n * // show the login screen\n * });\n * ```\n */\n [HttpApiEvent.SessionLoggedOut]: (err: MatrixError) => void;\n /**\n * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response\n * to a HTTP request.\n * @example\n * ```\n * matrixClient.on(\"no_consent\", function(message, contentUri) {\n * console.info(message + ' Go to ' + contentUri);\n * });\n * ```\n */\n [HttpApiEvent.NoConsent]: (message: string, consentUri: string) => void;\n};\n\nexport interface UploadProgress {\n loaded: number;\n total: number;\n}\n\nexport interface UploadOpts {\n /**\n * Name to give the file on the server. Defaults to <tt>file.name</tt>.\n */\n name?: string;\n /**\n * Content-type for the upload. Defaults to\n * <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.\n */\n type?: string;\n /**\n * if false will not send the filename,\n * e.g for encrypted file uploads where filename leaks are undesirable.\n * Defaults to true.\n */\n includeFilename?: boolean;\n /**\n * Optional. Called when a chunk of\n * data has been uploaded, with an object containing the fields `loaded`\n * (number of bytes transferred) and `total` (total size, if known).\n */\n progressHandler?(progress: UploadProgress): void;\n abortController?: AbortController;\n}\n\nexport interface Upload {\n loaded: number;\n total: number;\n promise: Promise<UploadResponse>;\n abortController: AbortController;\n}\n\nexport interface UploadResponse {\n content_uri: string;\n}\n\nexport type FileType = XMLHttpRequestBodyInit;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;;AAGA;;AAmCA;;AA4DA,WAAY,YAAY,0BAAZ,YAAY;EAAZ,YAAY;EAAZ,YAAY;EAAA,OAAZ,YAAY;AAAA","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.d.ts","sourceRoot":"","sources":["../../src/http-api/refresh.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAGhD;;GAEG;AAEH,0BAAkB,mBAAmB;IACjC,OAAO,YAAY;IACn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O,CAAC,QAAQ,CAAC,IAAI;IAAxC,YAAoC,IAAI,EAAE,IAAI,EAAI;IAElD;;;OAGG;IACH,OAAO,CAAC,mBAAmB,CAAC,CAA+B;IAE3D,OAAO,CAAC,wBAAwB,CAAC,CAAO;IAExC;;;;OAIG;IACU,iBAAiB,IAAI,OAAO,CAAC,QAAQ,CAAC,CASlD;YAEa,eAAe;IAa7B;;;;;;OAMG;IACU,kBAAkB,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAEjG;YAEa,mBAAmB;IA6BjC;;;;OAIG;YACW,cAAc;CAgC/B"}
@@ -83,9 +83,6 @@ export class TokenRefresher {
83
83
  async handleUnknownToken(snapshot, attempt) {
84
84
  return this._handleUnknownToken(snapshot, attempt);
85
85
  }
86
-
87
- /* eslint-disable @typescript-eslint/naming-convention */
88
-
89
86
  async _handleUnknownToken(snapshot, attempt) {
90
87
  if (snapshot?.expiry) {
91
88
  // If our token is unknown, but it should not have expired yet, then we should not refresh
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.js","names":[],"sources":["../../src/http-api/refresh.ts"],"sourcesContent":["/*\nCopyright 2025 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 { MatrixError, TokenRefreshLogoutError } from \"./errors.ts\";\nimport { type IHttpOpts } from \"./interface.ts\";\nimport { sleep } from \"../utils.ts\";\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nexport const enum TokenRefreshOutcome {\n Success = \"success\",\n Failure = \"failure\",\n Logout = \"logout\",\n}\n\ninterface Snapshot {\n accessToken: string;\n refreshToken?: string;\n expiry?: Date;\n}\n\n// If the token expires in less than this time amount of time, we will eagerly refresh it before making the intended request.\nconst REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS = 500;\n// If we get an unknown token error and the token expires in less than this time amount of time, we will refresh it before making the intended request.\n// Otherwise, we will error as the token should not have expired yet and we need to avoid retrying indefinitely.\nconst REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1000;\n\ntype Opts = Pick<IHttpOpts, \"tokenRefreshFunction\" | \"logger\" | \"refreshToken\" | \"accessToken\">;\n\n/**\n * This class is responsible for managing the access token and refresh token for authenticated requests.\n * It will automatically refresh the access token when it is about to expire, and will handle unknown token errors.\n */\nexport class TokenRefresher {\n public constructor(private readonly opts: Opts) {}\n\n /**\n * Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.\n * @private\n */\n private tokenRefreshPromise?: Promise<TokenRefreshOutcome>;\n\n private latestTokenRefreshExpiry?: Date;\n\n /**\n * This function is called before every request to ensure that the access token is valid.\n * @returns a snapshot containing the access token and other properties which must be passed to the handleUnknownToken\n * handler if an M_UNKNOWN_TOKEN error is encountered.\n */\n public async prepareForRequest(): Promise<Snapshot> {\n // Ensure our token is refreshed before we build the headers/params\n await this.refreshIfNeeded();\n\n return {\n accessToken: this.opts.accessToken!,\n refreshToken: this.opts.refreshToken,\n expiry: this.latestTokenRefreshExpiry,\n };\n }\n\n private async refreshIfNeeded(): Promise<unknown> {\n if (this.tokenRefreshPromise) {\n return this.tokenRefreshPromise;\n }\n // If we don't know the token expiry, we can't eagerly refresh\n if (!this.latestTokenRefreshExpiry) return;\n\n const expiresIn = this.latestTokenRefreshExpiry.getTime() - Date.now();\n if (expiresIn <= REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS) {\n await this._handleUnknownToken();\n }\n }\n\n /**\n * This function is called when an M_UNKNOWN_TOKEN error is encountered.\n * It will attempt to refresh the access token if it is unknown, and will return a TokenRefreshOutcome.\n * @param snapshot - the snapshot returned by prepareForRequest\n * @param attempt - the number of attempts made for this request so far\n * @returns a TokenRefreshOutcome indicating the result of the refresh attempt\n */\n public async handleUnknownToken(snapshot: Snapshot, attempt: number): Promise<TokenRefreshOutcome> {\n return this._handleUnknownToken(snapshot, attempt);\n }\n\n /* eslint-disable @typescript-eslint/naming-convention */\n private async _handleUnknownToken(): Promise<TokenRefreshOutcome>;\n private async _handleUnknownToken(snapshot: Snapshot, attempt: number): Promise<TokenRefreshOutcome>;\n private async _handleUnknownToken(snapshot?: Snapshot, attempt?: number): Promise<TokenRefreshOutcome> {\n if (snapshot?.expiry) {\n // If our token is unknown, but it should not have expired yet, then we should not refresh\n const expiresIn = snapshot.expiry.getTime() - Date.now();\n // If it still has plenty of time left on the clock, we assume something else must be wrong and\n // do not refresh. Otherwise if it's expired, or will soon, we try refreshing.\n if (expiresIn >= REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS) {\n return TokenRefreshOutcome.Logout;\n }\n }\n\n if (!snapshot || snapshot?.accessToken === this.opts.accessToken) {\n // If we have a snapshot, but the access token is the same as the current one then a refresh\n // did not happen behind us but one may be ongoing anyway\n this.tokenRefreshPromise ??= this.doTokenRefresh(attempt);\n\n try {\n return await this.tokenRefreshPromise;\n } finally {\n this.tokenRefreshPromise = undefined;\n }\n }\n\n // We may end up here if the token was refreshed in the background due to another request\n return TokenRefreshOutcome.Success;\n }\n\n /**\n * Attempt to refresh access tokens.\n * On success, sets new access and refresh tokens in opts.\n * @returns Promise that resolves to a boolean - true when token was refreshed successfully\n */\n private async doTokenRefresh(attempt?: number): Promise<TokenRefreshOutcome> {\n if (!this.opts.refreshToken || !this.opts.tokenRefreshFunction) {\n this.opts.logger?.error(\"Unable to refresh token - no refresh token or refresh function\");\n return TokenRefreshOutcome.Logout;\n }\n\n if (attempt && attempt > 1) {\n // Exponential backoff to ensure we don't trash the server, up to 2^5 seconds\n await sleep(1000 * Math.min(32, 2 ** attempt));\n }\n\n try {\n this.opts.logger?.debug(\"Attempting to refresh token\");\n const { accessToken, refreshToken, expiry } = await this.opts.tokenRefreshFunction(this.opts.refreshToken);\n this.opts.accessToken = accessToken;\n this.opts.refreshToken = refreshToken;\n this.latestTokenRefreshExpiry = expiry;\n this.opts.logger?.debug(\"... token refresh complete, new token expiry:\", expiry);\n\n // successfully got new tokens\n return TokenRefreshOutcome.Success;\n } catch (error) {\n // If we get a TokenError or MatrixError, we should log out, otherwise assume transient\n if (error instanceof TokenRefreshLogoutError || error instanceof MatrixError) {\n this.opts.logger?.error(\"Failed to refresh token\", error);\n return TokenRefreshOutcome.Logout;\n }\n\n this.opts.logger?.warn(\"Failed to refresh token\", error);\n return TokenRefreshOutcome.Failure;\n }\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,WAAW,EAAE,uBAAuB,QAAQ,aAAa;AAElE,SAAS,KAAK,QAAQ,aAAa;;AAEnC;AACA;AACA;;AAEA,WAAkB,mBAAmB,0BAAnB,mBAAmB;EAAnB,mBAAmB;EAAnB,mBAAmB;EAAnB,mBAAmB;EAAA,OAAnB,mBAAmB;AAAA;AAYrC;AACA,MAAM,kCAAkC,GAAG,GAAG;AAC9C;AACA;AACA,MAAM,2CAA2C,GAAG,EAAE,GAAG,IAAI;AAI7D;AACA;AACA;AACA;AACA,OAAO,MAAM,cAAc,CAAC;EACjB,WAAW,CAAkB,IAAU,EAAE;IAEhD;AACJ;AACA;AACA;IAHI;IAAA;IAAA,KAFoC,IAAU,GAAV,IAAU;EAAG;EAUjD;AACJ;AACA;AACA;AACA;EACI,MAAa,iBAAiB,GAAsB;IAChD;IACA,MAAM,IAAI,CAAC,eAAe,CAAC,CAAC;IAE5B,OAAO;MACH,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,WAAY;MACnC,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,YAAY;MACpC,MAAM,EA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{"version":3,"file":"refresh.js","names":[],"sources":["../../src/http-api/refresh.ts"],"sourcesContent":["/*\nCopyright 2025 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 { MatrixError, TokenRefreshLogoutError } from \"./errors.ts\";\nimport { type IHttpOpts } from \"./interface.ts\";\nimport { sleep } from \"../utils.ts\";\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nexport const enum TokenRefreshOutcome {\n Success = \"success\",\n Failure = \"failure\",\n Logout = \"logout\",\n}\n\ninterface Snapshot {\n accessToken: string;\n refreshToken?: string;\n expiry?: Date;\n}\n\n// If the token expires in less than this time amount of time, we will eagerly refresh it before making the intended request.\nconst REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS = 500;\n// If we get an unknown token error and the token expires in less than this time amount of time, we will refresh it before making the intended request.\n// Otherwise, we will error as the token should not have expired yet and we need to avoid retrying indefinitely.\nconst REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1000;\n\ntype Opts = Pick<IHttpOpts, \"tokenRefreshFunction\" | \"logger\" | \"refreshToken\" | \"accessToken\">;\n\n/**\n * This class is responsible for managing the access token and refresh token for authenticated requests.\n * It will automatically refresh the access token when it is about to expire, and will handle unknown token errors.\n */\nexport class TokenRefresher {\n public constructor(private readonly opts: Opts) {}\n\n /**\n * Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.\n * @private\n */\n private tokenRefreshPromise?: Promise<TokenRefreshOutcome>;\n\n private latestTokenRefreshExpiry?: Date;\n\n /**\n * This function is called before every request to ensure that the access token is valid.\n * @returns a snapshot containing the access token and other properties which must be passed to the handleUnknownToken\n * handler if an M_UNKNOWN_TOKEN error is encountered.\n */\n public async prepareForRequest(): Promise<Snapshot> {\n // Ensure our token is refreshed before we build the headers/params\n await this.refreshIfNeeded();\n\n return {\n accessToken: this.opts.accessToken!,\n refreshToken: this.opts.refreshToken,\n expiry: this.latestTokenRefreshExpiry,\n };\n }\n\n private async refreshIfNeeded(): Promise<unknown> {\n if (this.tokenRefreshPromise) {\n return this.tokenRefreshPromise;\n }\n // If we don't know the token expiry, we can't eagerly refresh\n if (!this.latestTokenRefreshExpiry) return;\n\n const expiresIn = this.latestTokenRefreshExpiry.getTime() - Date.now();\n if (expiresIn <= REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS) {\n await this._handleUnknownToken();\n }\n }\n\n /**\n * This function is called when an M_UNKNOWN_TOKEN error is encountered.\n * It will attempt to refresh the access token if it is unknown, and will return a TokenRefreshOutcome.\n * @param snapshot - the snapshot returned by prepareForRequest\n * @param attempt - the number of attempts made for this request so far\n * @returns a TokenRefreshOutcome indicating the result of the refresh attempt\n */\n public async handleUnknownToken(snapshot: Snapshot, attempt: number): Promise<TokenRefreshOutcome> {\n return this._handleUnknownToken(snapshot, attempt);\n }\n\n private async _handleUnknownToken(): Promise<TokenRefreshOutcome>;\n private async _handleUnknownToken(snapshot: Snapshot, attempt: number): Promise<TokenRefreshOutcome>;\n private async _handleUnknownToken(snapshot?: Snapshot, attempt?: number): Promise<TokenRefreshOutcome> {\n if (snapshot?.expiry) {\n // If our token is unknown, but it should not have expired yet, then we should not refresh\n const expiresIn = snapshot.expiry.getTime() - Date.now();\n // If it still has plenty of time left on the clock, we assume something else must be wrong and\n // do not refresh. Otherwise if it's expired, or will soon, we try refreshing.\n if (expiresIn >= REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS) {\n return TokenRefreshOutcome.Logout;\n }\n }\n\n if (!snapshot || snapshot?.accessToken === this.opts.accessToken) {\n // If we have a snapshot, but the access token is the same as the current one then a refresh\n // did not happen behind us but one may be ongoing anyway\n this.tokenRefreshPromise ??= this.doTokenRefresh(attempt);\n\n try {\n return await this.tokenRefreshPromise;\n } finally {\n this.tokenRefreshPromise = undefined;\n }\n }\n\n // We may end up here if the token was refreshed in the background due to another request\n return TokenRefreshOutcome.Success;\n }\n\n /**\n * Attempt to refresh access tokens.\n * On success, sets new access and refresh tokens in opts.\n * @returns Promise that resolves to a boolean - true when token was refreshed successfully\n */\n private async doTokenRefresh(attempt?: number): Promise<TokenRefreshOutcome> {\n if (!this.opts.refreshToken || !this.opts.tokenRefreshFunction) {\n this.opts.logger?.error(\"Unable to refresh token - no refresh token or refresh function\");\n return TokenRefreshOutcome.Logout;\n }\n\n if (attempt && attempt > 1) {\n // Exponential backoff to ensure we don't trash the server, up to 2^5 seconds\n await sleep(1000 * Math.min(32, 2 ** attempt));\n }\n\n try {\n this.opts.logger?.debug(\"Attempting to refresh token\");\n const { accessToken, refreshToken, expiry } = await this.opts.tokenRefreshFunction(this.opts.refreshToken);\n this.opts.accessToken = accessToken;\n this.opts.refreshToken = refreshToken;\n this.latestTokenRefreshExpiry = expiry;\n this.opts.logger?.debug(\"... token refresh complete, new token expiry:\", expiry);\n\n // successfully got new tokens\n return TokenRefreshOutcome.Success;\n } catch (error) {\n // If we get a TokenError or MatrixError, we should log out, otherwise assume transient\n if (error instanceof TokenRefreshLogoutError || error instanceof MatrixError) {\n this.opts.logger?.error(\"Failed to refresh token\", error);\n return TokenRefreshOutcome.Logout;\n }\n\n this.opts.logger?.warn(\"Failed to refresh token\", error);\n return TokenRefreshOutcome.Failure;\n }\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,WAAW,EAAE,uBAAuB,QAAQ,aAAa;AAElE,SAAS,KAAK,QAAQ,aAAa;;AAEnC;AACA;AACA;;AAEA,WAAkB,mBAAmB,0BAAnB,mBAAmB;EAAnB,mBAAmB;E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70
70
 
71
71
  export class NoAuthFlowFoundError extends Error {
72
- constructor(m,
73
- // eslint-disable-next-line @typescript-eslint/naming-convention, camelcase
74
- required_stages, flows) {
72
+ constructor(m, required_stages, flows) {
75
73
  super(m);
76
74
  _defineProperty(this, "name", "NoAuthFlowFoundError");
77
75
  this.required_stages = required_stages;
@@ -282,12 +280,13 @@ export class InteractiveAuth {
282
280
  // if we're currently trying a request, wait for it to finish
283
281
  // as otherwise we can get multiple 200 responses which can mean
284
282
  // things like multiple logins for register requests.
285
- // (but discard any exceptions as we only care when its done,
286
- // not whether it worked or not)
287
283
  while (this.submitPromise) {
288
284
  try {
289
285
  await this.submitPromise;
290
- } catch {}
286
+ } catch {
287
+ // discard any exceptions as we only care when its done,
288
+ // not whether it worked or not
289
+ }
291
290
  }
292
291
 
293
292
  // use the sessionid from the last request, if one is present.
@@ -1 +1 @@
1
- {"version":3,"file":"interactive-auth.js","names":[],"sources":["../src/interactive-auth.ts"],"sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations 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 { logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { MatrixError } from \"./http-api/index.ts\";\nimport { type UserIdentifier } from \"./@types/auth.ts\";\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\nexport interface UIAFlow {\n stages: Array<AuthType | string>;\n}\n\nexport interface IInputs {\n // An email address. If supplied, a flow using email verification will be chosen.\n emailAddress?: string;\n // An ISO two letter country code. Gives the country that opts.phoneNumber should be resolved relative to.\n phoneCountry?: string;\n // A phone number. If supplied, a flow using phone number validation will be chosen.\n phoneNumber?: string;\n registrationToken?: string;\n}\n\nexport interface IStageStatus {\n emailSid?: string;\n errcode?: string;\n error?: string;\n}\n\n/**\n * Data returned in the body of a 401 response from a UIA endpoint.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#user-interactive-api-in-the-rest-api\n */\nexport interface IAuthData {\n /**\n * This is a session identifier that the client must pass back to the home server,\n * if one is provided, in subsequent attempts to authenticate in the same API call.\n */\n session?: string;\n /**\n * A list of the stages the client has completed successfully\n */\n completed?: string[];\n /**\n * A list of the login flows supported by the server for this API.\n */\n flows?: UIAFlow[];\n /**\n * Contains any information that the client will need to know in order to use a given type of authentication.\n * For each login type presented, that type may be present as a key in this dictionary.\n * For example, the public part of an OAuth client ID could be given here.\n */\n params?: Record<string, Record<string, any>>;\n}\n\nexport enum AuthType {\n Password = \"m.login.password\",\n Recaptcha = \"m.login.recaptcha\",\n Terms = \"m.login.terms\",\n Email = \"m.login.email.identity\",\n Msisdn = \"m.login.msisdn\",\n Sso = \"m.login.sso\",\n SsoUnstable = \"org.matrix.login.sso\",\n Dummy = \"m.login.dummy\",\n RegistrationToken = \"m.login.registration_token\",\n // For backwards compatability with servers that have not yet updated to\n // use the stable \"m.login.registration_token\" type.\n // The authentication flow is the same in both cases.\n UnstableRegistrationToken = \"org.matrix.msc3231.login.registration_token\",\n /**\n * m.oauth stage introduced by MSC4312:\n * https://spec.matrix.org/v1.17/client-server-api/#oauth-authentication\n */\n OAuth = \"m.oauth\",\n}\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#password-based\n */\ntype PasswordDict = {\n type: AuthType.Password;\n identifier: UserIdentifier;\n password: string;\n session: string;\n};\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#google-recaptcha\n */\ntype RecaptchaDict = {\n type: AuthType.Recaptcha;\n response: string;\n session: string;\n};\n\ninterface ThreepidCreds {\n sid: string;\n client_secret: string;\n id_server: string;\n id_access_token: string;\n}\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#email-based-identity--homeserver\n */\ntype EmailIdentityDict = {\n type: AuthType.Email;\n threepid_creds: ThreepidCreds;\n session: string;\n};\n\n/**\n * The parameters which are submitted as the `auth` dict in a UIA request\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#authentication-types\n */\nexport type AuthDict =\n | PasswordDict\n | RecaptchaDict\n | EmailIdentityDict\n | { type: Exclude<string, AuthType>; [key: string]: any }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n | {};\n\nexport class NoAuthFlowFoundError extends Error {\n public name = \"NoAuthFlowFoundError\";\n\n public constructor(\n m: string,\n // eslint-disable-next-line @typescript-eslint/naming-convention, camelcase\n public readonly required_stages: string[],\n public readonly flows: UIAFlow[],\n ) {\n super(m);\n }\n}\n\n/**\n * The type of an application callback to perform the user-interactive bit of UIA.\n *\n * It is called with a single parameter, `makeRequest`, which is a function which takes the UIA parameters and\n * makes the HTTP request. The `authData` parameter in `makeRequest` can be set to null to omit the `auth` field\n * from the UIA request.\n *\n * The generic parameter `T` is the type of the response of the endpoint, once it is eventually successful.\n */\nexport type UIAuthCallback<T> = (makeRequest: (authData: AuthDict | null) => Promise<T>) => Promise<T>;\n\ninterface IOpts<T> {\n /**\n * A matrix client to use for the auth process\n */\n matrixClient: MatrixClient;\n /**\n * Error response from the last request. If null, a request will be made with no auth before starting.\n */\n authData?: IAuthData;\n /**\n * Inputs provided by the user and used by different stages of the auto process.\n * The inputs provided will affect what flow is chosen.\n */\n inputs?: IInputs;\n /**\n * If resuming an existing interactive auth session, the sessionId of that session.\n */\n sessionId?: string;\n /**\n * If resuming an existing interactive auth session, the client secret for that session\n */\n clientSecret?: string;\n /**\n * If returning from having completed m.login.email.identity auth, the sid for the email verification session.\n */\n emailSid?: string;\n\n /**\n * If specified, will prefer flows which entirely consist of listed stages.\n * These should normally be of type AuthTypes but can be string when supporting custom auth stages.\n *\n * This can be used to avoid needing the fallback mechanism.\n */\n supportedStages?: Array<AuthType | string>;\n\n /**\n * Called with the new auth dict to submit the request.\n * Also passes a second deprecated arg which is a flag set to true if this request is a background request.\n * The busyChanged callback should be used instead of the background flag.\n * Should return a promise which resolves to the successful response or rejects with a MatrixError.\n */\n doRequest(this: void, auth: AuthDict | null, background: boolean): Promise<T>;\n /**\n * Called when the status of the UI auth changes,\n * ie. when the state of an auth stage changes of when the auth flow moves to a new stage.\n * The arguments are: the login type (eg m.login.password); and an object which is either an error or an\n * informational object specific to the login type.\n * If the 'errcode' key is defined, the object is an error, and has keys:\n * errcode: string, the textual error code, eg. M_UNKNOWN\n * error: string, human readable string describing the error\n *\n * The login type specific objects are as follows:\n * m.login.email.identity:\n * * emailSid: string, the sid of the active email auth session\n */\n stateUpdated(this: void, nextStage: AuthType | string, status: IStageStatus): void;\n\n /**\n * A function that takes the email address (string), clientSecret (string), attempt number (int) and\n * sessionId (string) and calls the relevant requestToken function and returns the promise returned by that\n * function.\n * If the resulting promise rejects, the rejection will propagate through to the attemptAuth promise.\n */\n requestEmailToken(\n this: void,\n email: string,\n secret: string,\n attempt: number,\n session: string,\n ): Promise<{ sid: string }>;\n /**\n * Called whenever the interactive auth logic becomes busy submitting information provided by the user or finishes.\n * After this has been called with true the UI should indicate that a request is in progress\n * until it is called again with false.\n */\n busyChanged?(this: void, busy: boolean): void;\n startAuthStage?(this: void, nextStage: string): Promise<void>; // LEGACY\n}\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n * <p>Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n * <p>Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @param opts - options object\n * @typeParam T - the return type of the request when it is successful\n */\nexport class InteractiveAuth<T> {\n private readonly matrixClient: MatrixClient;\n private readonly inputs: IInputs;\n private readonly clientSecret: string;\n private readonly requestCallback: IOpts<T>[\"doRequest\"];\n private readonly busyChangedCallback?: IOpts<T>[\"busyChanged\"];\n private readonly stateUpdatedCallback: IOpts<T>[\"stateUpdated\"];\n private readonly requestEmailTokenCallback: IOpts<T>[\"requestEmailToken\"];\n private readonly supportedStages?: Set<string>;\n\n // The current latest data or error received from the server during the user interactive auth flow.\n private data: IAuthData & MatrixError[\"data\"];\n private emailSid?: string;\n private requestingEmailToken = false;\n private attemptAuthDeferred: PromiseWithResolvers<T> | null = null;\n private chosenFlow: UIAFlow | null = null;\n private currentStage: string | null = null;\n\n private emailAttempt = 1;\n\n // if we are currently trying to submit an auth dict (which includes polling)\n // the promise the will resolve/reject when it completes\n private submitPromise: Promise<void> | null = null;\n\n public constructor(opts: IOpts<T>) {\n this.matrixClient = opts.matrixClient;\n this.data = opts.authData || { flows: [] };\n this.requestCallback = opts.doRequest;\n this.busyChangedCallback = opts.busyChanged;\n // startAuthStage included for backwards compat\n this.stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;\n this.requestEmailTokenCallback = opts.requestEmailToken;\n this.inputs = opts.inputs || {};\n\n if (opts.sessionId) this.data.session = opts.sessionId;\n this.clientSecret = opts.clientSecret || this.matrixClient.generateClientSecret();\n this.emailSid = opts.emailSid;\n if (opts.supportedStages !== undefined) this.supportedStages = new Set(opts.supportedStages);\n }\n\n /**\n * begin the authentication process.\n *\n * @returns which resolves to the response on success,\n * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if\n * no suitable authentication flow can be found\n */\n public async attemptAuth(): Promise<T> {\n // This promise will be quite long-lived and will resolve when the\n // request is authenticated and completes successfully.\n this.attemptAuthDeferred = Promise.withResolvers();\n // pluck the promise out now, as doRequest may clear before we return\n const promise = this.attemptAuthDeferred.promise;\n\n // if we have no flows, try a request to acquire the flows\n if (!(this.data as IAuthData)?.flows?.length) {\n this.busyChangedCallback?.(true);\n // use the existing sessionId, if one is present.\n const auth = (this.data as IAuthData).session ? { session: (this.data as IAuthData).session } : null;\n this.doRequest(auth).finally(() => {\n this.busyChangedCallback?.(false);\n });\n } else {\n this.startNextAuthStage();\n }\n\n return promise;\n }\n\n /**\n * Poll to check if the auth session or current stage has been\n * completed out-of-band. If so, the attemptAuth promise will\n * be resolved.\n */\n public async poll(): Promise<void> {\n if (!(this.data as IAuthData).session) return;\n // likewise don't poll if there is no auth session in progress\n if (!this.attemptAuthDeferred) return;\n // if we currently have a request in flight, there's no point making\n // another just to check what the status is\n if (this.submitPromise) return;\n\n let authDict: AuthDict = {};\n if (this.currentStage == EMAIL_STAGE_TYPE) {\n // The email can be validated out-of-band, but we need to provide the\n // creds so the HS can go & check it.\n if (this.emailSid) {\n const creds: Record<string, string> = {\n sid: this.emailSid,\n client_secret: this.clientSecret,\n };\n const isUrl = this.matrixClient.getIdentityServerUrl();\n if (isUrl) {\n creds.id_server = new URL(isUrl).host;\n }\n authDict = {\n type: EMAIL_STAGE_TYPE,\n threepid_creds: creds,\n };\n }\n }\n\n this.submitAuthDict(authDict, true);\n }\n\n /**\n * get the auth session ID\n *\n * @returns session id\n */\n public getSessionId(): string | undefined {\n return (this.data as IAuthData)?.session;\n }\n\n /**\n * get the client secret used for validation sessions\n * with the identity server.\n *\n * @returns client secret\n */\n public getClientSecret(): string {\n return this.clientSecret;\n }\n\n /**\n * get the server params for a given stage\n *\n * @param loginType - login type for the stage\n * @returns any parameters from the server for this stage\n */\n public getStageParams(loginType: string): Record<string, any> | undefined {\n return (this.data as IAuthData)?.params?.[loginType];\n }\n\n public getChosenFlow(): UIAFlow | null {\n return this.chosenFlow;\n }\n\n /**\n * submit a new auth dict and fire off the request. This will either\n * make attemptAuth resolve/reject, or cause the startAuthStage callback\n * to be called for a new stage.\n *\n * @param authData - new auth dict to send to the server. Should\n * include a `type` property denoting the login type, as well as any\n * other params for that stage.\n * @param background - If true, this request failing will not result\n * in the attemptAuth promise being rejected. This can be set to true\n * for requests that just poll to see if auth has been completed elsewhere.\n */\n public async submitAuthDict(authData: AuthDict, background = false): Promise<void> {\n if (!this.attemptAuthDeferred) {\n throw new Error(\"submitAuthDict() called before attemptAuth()\");\n }\n\n if (!background) {\n this.busyChangedCallback?.(true);\n }\n\n // if we're currently trying a request, wait for it to finish\n // as otherwise we can get multiple 200 responses which can mean\n // things like multiple logins for register requests.\n // (but discard any exceptions as we only care when its done,\n // not whether it worked or not)\n while (this.submitPromise) {\n try {\n await this.submitPromise;\n } catch {}\n }\n\n // use the sessionid from the last request, if one is present.\n let auth: AuthDict;\n if ((this.data as IAuthData)?.session) {\n auth = Object.assign(\n {\n session: (this.data as IAuthData).session,\n },\n authData,\n );\n } else {\n auth = authData;\n }\n\n try {\n // NB. the 'background' flag is deprecated by the busyChanged\n // callback and is here for backwards compat\n this.submitPromise = this.doRequest(auth, background);\n await this.submitPromise;\n } finally {\n this.submitPromise = null;\n if (!background) {\n this.busyChangedCallback?.(false);\n }\n }\n }\n\n /**\n * Gets the sid for the email validation session\n * Specific to m.login.email.identity\n *\n * @returns The sid of the email auth session\n */\n public getEmailSid(): string | undefined {\n return this.emailSid;\n }\n\n /**\n * Sets the sid for the email validation session\n * This must be set in order to successfully poll for completion\n * of the email validation.\n * Specific to m.login.email.identity\n *\n * @param sid - The sid for the email validation session\n */\n public setEmailSid(sid: string): void {\n this.emailSid = sid;\n }\n\n /**\n * Requests a new email token and sets the email sid for the validation session\n */\n public requestEmailToken = async (): Promise<void> => {\n if (!this.requestingEmailToken) {\n logger.trace(\"Requesting email token. Attempt: \" + this.emailAttempt);\n // If we've picked a flow with email auth, we send the email\n // now because we want the request to fail as soon as possible\n // if the email address is not valid (ie. already taken or not\n // registered, depending on what the operation is).\n this.requestingEmailToken = true;\n try {\n const requestTokenResult = await this.requestEmailTokenCallback(\n this.inputs.emailAddress!,\n this.clientSecret,\n this.emailAttempt++,\n (this.data as IAuthData).session!,\n );\n this.emailSid = requestTokenResult.sid;\n logger.trace(\"Email token request succeeded\");\n } finally {\n this.requestingEmailToken = false;\n }\n } else {\n logger.warn(\"Could not request email token: Already requesting\");\n }\n };\n\n /**\n * Fire off a request, and either resolve the promise, or call\n * startAuthStage.\n *\n * @internal\n * @param auth - new auth dict, including session id\n * @param background - If true, this request is a background poll, so it\n * failing will not result in the attemptAuth promise being rejected.\n * This can be set to true for requests that just poll to see if auth has\n * been completed elsewhere.\n */\n private async doRequest(auth: AuthDict | null, background = false): Promise<void> {\n try {\n const result = await this.requestCallback(auth, background);\n this.attemptAuthDeferred!.resolve(result);\n this.attemptAuthDeferred = null;\n } catch (error) {\n const matrixError = error instanceof MatrixError ? error : null;\n\n // sometimes UI auth errors don't come with flows\n const errorFlows = matrixError?.data?.flows ?? null;\n const haveFlows = (this.data as IAuthData)?.flows || Boolean(errorFlows);\n if (!matrixError || matrixError.httpStatus !== 401 || !matrixError.data || !haveFlows) {\n // doesn't look like an interactive-auth failure.\n if (!background) {\n this.attemptAuthDeferred?.reject(error);\n } else {\n // We ignore all failures here (even non-UI auth related ones)\n // since we don't want to suddenly fail if the internet connection\n // had a blip whilst we were polling\n logger.log(\"Background poll request failed doing UI auth: ignoring\", error);\n }\n }\n if (matrixError && !matrixError.data) {\n matrixError.data = {};\n }\n // if the error didn't come with flows, completed flows or session ID,\n // copy over the ones we have. Synapse sometimes sends responses without\n // any UI auth data (eg. when polling for email validation, if the email\n // has not yet been validated). This appears to be a Synapse bug, which\n // we workaround here.\n if (matrixError && !matrixError.data.flows && !matrixError.data.completed && !matrixError.data.session) {\n matrixError.data.flows = (this.data as IAuthData).flows;\n matrixError.data.completed = (this.data as IAuthData).completed;\n matrixError.data.session = (this.data as IAuthData).session;\n }\n if (matrixError) {\n this.data = matrixError.data;\n }\n try {\n this.startNextAuthStage();\n } catch (e) {\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n return;\n }\n\n if (!this.emailSid && this.chosenFlow?.stages.includes(AuthType.Email)) {\n try {\n await this.requestEmailToken();\n // NB. promise is not resolved here - at some point, doRequest\n // will be called again and if the user has jumped through all\n // the hoops correctly, auth will be complete and the request\n // will succeed.\n // Also, we should expose the fact that this request has compledted\n // so clients can know that the email has actually been sent.\n } catch (e) {\n // we failed to request an email token, so fail the request.\n // This could be due to the email already beeing registered\n // (or not being registered, depending on what we're trying\n // to do) or it could be a network failure. Either way, pass\n // the failure up as the user can't complete auth if we can't\n // send the email, for whatever reason.\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n }\n }\n }\n }\n\n /**\n * Pick the next stage and call the callback\n *\n * @internal\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private startNextAuthStage(): void {\n const nextStage = this.chooseStage();\n if (!nextStage) {\n throw new Error(\"No incomplete flows from the server\");\n }\n this.currentStage = nextStage;\n\n if (nextStage === AuthType.Dummy) {\n this.submitAuthDict({\n type: \"m.login.dummy\",\n });\n return;\n }\n\n if (this.data?.errcode || this.data?.error) {\n this.stateUpdatedCallback(nextStage, {\n errcode: this.data?.errcode || \"\",\n error: this.data?.error || \"\",\n });\n return;\n }\n\n this.stateUpdatedCallback(nextStage, nextStage === EMAIL_STAGE_TYPE ? { emailSid: this.emailSid } : {});\n }\n\n /**\n * Pick the next auth stage\n *\n * @internal\n * @returns login type\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseStage(): AuthType | string | undefined {\n if (this.chosenFlow === null) {\n this.chosenFlow = this.chooseFlow();\n }\n logger.log(\"Active flow => %s\", JSON.stringify(this.chosenFlow));\n const nextStage = this.firstUncompletedStage(this.chosenFlow);\n logger.log(\"Next stage: %s\", nextStage);\n return nextStage;\n }\n\n // Returns a low number for flows we consider best. Counts increase for longer flows and even more so\n // for flows which contain stages not listed in `supportedStages`.\n private scoreFlow(flow: UIAFlow): number {\n let score = flow.stages.length;\n if (this.supportedStages !== undefined) {\n // Add 10 points to the score for each unsupported stage in the flow.\n score += flow.stages.filter((stage) => !this.supportedStages!.has(stage)).length * 10;\n }\n return score;\n }\n\n /**\n * Pick one of the flows from the returned list\n * If a flow using all of the inputs is found, it will\n * be returned, otherwise, null will be returned.\n *\n * Only flows using all given inputs are chosen because it\n * is likely to be surprising if the user provides a\n * credential and it is not used. For example, for registration,\n * this could result in the email not being used which would leave\n * the account with no means to reset a password.\n *\n * @internal\n * @returns flow\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseFlow(): UIAFlow {\n const flows = (this.data as IAuthData)?.flows || [];\n\n // we've been given an email or we've already done an email part\n const haveEmail = Boolean(this.inputs.emailAddress) || Boolean(this.emailSid);\n const haveMsisdn = Boolean(this.inputs.phoneCountry) && Boolean(this.inputs.phoneNumber);\n\n // Flows are not represented in a significant order, so we can choose any we support best\n // Sort flows based on how many unsupported stages they contain ascending\n flows.sort((a, b) => this.scoreFlow(a) - this.scoreFlow(b));\n\n for (const flow of flows) {\n let flowHasEmail = false;\n let flowHasMsisdn = false;\n for (const stage of flow.stages) {\n if (stage === EMAIL_STAGE_TYPE) {\n flowHasEmail = true;\n } else if (stage == MSISDN_STAGE_TYPE) {\n flowHasMsisdn = true;\n }\n }\n\n if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {\n return flow;\n }\n }\n\n const requiredStages: string[] = [];\n if (haveEmail) requiredStages.push(EMAIL_STAGE_TYPE);\n if (haveMsisdn) requiredStages.push(MSISDN_STAGE_TYPE);\n // Throw an error with a fairly generic description, but with more\n // information such that the app can give a better one if so desired.\n throw new NoAuthFlowFoundError(\"No appropriate authentication flow found\", requiredStages, flows);\n }\n\n /**\n * Get the first uncompleted stage in the given flow\n *\n * @internal\n * @returns login type\n */\n private firstUncompletedStage(flow: UIAFlow): AuthType | string | undefined {\n const completed = (this.data as IAuthData)?.completed || [];\n return flow.stages.find((stageType) => !completed.includes(stageType));\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,M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AK,IAAI,iBAAiB,EAAE;UACnC,aAAa,GAAG,IAAI;QACxB;MACJ;MAEA,IAAI,YAAY,IAAI,SAAS,IAAI,aAAa,IAAI,UAAU,EAAE;QAC1D,OAAO,IAAI;MACf;IACJ;IAEA,MAAM,cAAwB,GAAG,EAAE;IACnC,IAAI,SAAS,EAAE,cAAc,CAAC,IAAI,CAAC,gBAAgB,CAAC;IACpD,IAAI,UAAU,EAAE,cAAc,CAAC,IAAI,CAAC,iBAAiB,CAAC;IACtD;IACA;IACA,MAAM,IAAI,oBAAoB,CAAC,0CAA0C,EAAE,cAAc,EAAE,KAAK,CAAC;EACrG;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACY,qBAAqB,CAAC,IAAa,EAAiC;IACxE,MAAM,SAAS,GAAI,IAAI,CAAC,IAAI,EAAgB,SAAS,IAAI,EAAE;IAC3D,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAE,SAAS,IAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;EAC1E;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"interactive-auth.js","names":[],"sources":["../src/interactive-auth.ts"],"sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations 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 { logger } from \"./logger.ts\";\nimport { type MatrixClient } from \"./client.ts\";\nimport { MatrixError } from \"./http-api/index.ts\";\nimport { type UserIdentifier } from \"./@types/auth.ts\";\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\nexport interface UIAFlow {\n stages: Array<AuthType | string>;\n}\n\nexport interface IInputs {\n // An email address. If supplied, a flow using email verification will be chosen.\n emailAddress?: string;\n // An ISO two letter country code. Gives the country that opts.phoneNumber should be resolved relative to.\n phoneCountry?: string;\n // A phone number. If supplied, a flow using phone number validation will be chosen.\n phoneNumber?: string;\n registrationToken?: string;\n}\n\nexport interface IStageStatus {\n emailSid?: string;\n errcode?: string;\n error?: string;\n}\n\n/**\n * Data returned in the body of a 401 response from a UIA endpoint.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#user-interactive-api-in-the-rest-api\n */\nexport interface IAuthData {\n /**\n * This is a session identifier that the client must pass back to the home server,\n * if one is provided, in subsequent attempts to authenticate in the same API call.\n */\n session?: string;\n /**\n * A list of the stages the client has completed successfully\n */\n completed?: string[];\n /**\n * A list of the login flows supported by the server for this API.\n */\n flows?: UIAFlow[];\n /**\n * Contains any information that the client will need to know in order to use a given type of authentication.\n * For each login type presented, that type may be present as a key in this dictionary.\n * For example, the public part of an OAuth client ID could be given here.\n */\n params?: Record<string, Record<string, any>>;\n}\n\nexport enum AuthType {\n Password = \"m.login.password\",\n Recaptcha = \"m.login.recaptcha\",\n Terms = \"m.login.terms\",\n Email = \"m.login.email.identity\",\n Msisdn = \"m.login.msisdn\",\n Sso = \"m.login.sso\",\n SsoUnstable = \"org.matrix.login.sso\",\n Dummy = \"m.login.dummy\",\n RegistrationToken = \"m.login.registration_token\",\n // For backwards compatability with servers that have not yet updated to\n // use the stable \"m.login.registration_token\" type.\n // The authentication flow is the same in both cases.\n UnstableRegistrationToken = \"org.matrix.msc3231.login.registration_token\",\n /**\n * m.oauth stage introduced by MSC4312:\n * https://spec.matrix.org/v1.17/client-server-api/#oauth-authentication\n */\n OAuth = \"m.oauth\",\n}\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#password-based\n */\ntype PasswordDict = {\n type: AuthType.Password;\n identifier: UserIdentifier;\n password: string;\n session: string;\n};\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#google-recaptcha\n */\ntype RecaptchaDict = {\n type: AuthType.Recaptcha;\n response: string;\n session: string;\n};\n\ninterface ThreepidCreds {\n sid: string;\n client_secret: string;\n id_server: string;\n id_access_token: string;\n}\n\n/**\n * https://spec.matrix.org/v1.7/client-server-api/#email-based-identity--homeserver\n */\ntype EmailIdentityDict = {\n type: AuthType.Email;\n threepid_creds: ThreepidCreds;\n session: string;\n};\n\n/**\n * The parameters which are submitted as the `auth` dict in a UIA request\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#authentication-types\n */\nexport type AuthDict =\n | PasswordDict\n | RecaptchaDict\n | EmailIdentityDict\n | { type: Exclude<string, AuthType>; [key: string]: any }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n | {};\n\nexport class NoAuthFlowFoundError extends Error {\n public name = \"NoAuthFlowFoundError\";\n\n public constructor(\n m: string,\n public readonly required_stages: string[],\n public readonly flows: UIAFlow[],\n ) {\n super(m);\n }\n}\n\n/**\n * The type of an application callback to perform the user-interactive bit of UIA.\n *\n * It is called with a single parameter, `makeRequest`, which is a function which takes the UIA parameters and\n * makes the HTTP request. The `authData` parameter in `makeRequest` can be set to null to omit the `auth` field\n * from the UIA request.\n *\n * The generic parameter `T` is the type of the response of the endpoint, once it is eventually successful.\n */\nexport type UIAuthCallback<T> = (makeRequest: (authData: AuthDict | null) => Promise<T>) => Promise<T>;\n\ninterface IOpts<T> {\n /**\n * A matrix client to use for the auth process\n */\n matrixClient: MatrixClient;\n /**\n * Error response from the last request. If null, a request will be made with no auth before starting.\n */\n authData?: IAuthData;\n /**\n * Inputs provided by the user and used by different stages of the auto process.\n * The inputs provided will affect what flow is chosen.\n */\n inputs?: IInputs;\n /**\n * If resuming an existing interactive auth session, the sessionId of that session.\n */\n sessionId?: string;\n /**\n * If resuming an existing interactive auth session, the client secret for that session\n */\n clientSecret?: string;\n /**\n * If returning from having completed m.login.email.identity auth, the sid for the email verification session.\n */\n emailSid?: string;\n\n /**\n * If specified, will prefer flows which entirely consist of listed stages.\n * These should normally be of type AuthTypes but can be string when supporting custom auth stages.\n *\n * This can be used to avoid needing the fallback mechanism.\n */\n supportedStages?: Array<AuthType | string>;\n\n /**\n * Called with the new auth dict to submit the request.\n * Also passes a second deprecated arg which is a flag set to true if this request is a background request.\n * The busyChanged callback should be used instead of the background flag.\n * Should return a promise which resolves to the successful response or rejects with a MatrixError.\n */\n doRequest(this: void, auth: AuthDict | null, background: boolean): Promise<T>;\n /**\n * Called when the status of the UI auth changes,\n * ie. when the state of an auth stage changes of when the auth flow moves to a new stage.\n * The arguments are: the login type (eg m.login.password); and an object which is either an error or an\n * informational object specific to the login type.\n * If the 'errcode' key is defined, the object is an error, and has keys:\n * errcode: string, the textual error code, eg. M_UNKNOWN\n * error: string, human readable string describing the error\n *\n * The login type specific objects are as follows:\n * m.login.email.identity:\n * * emailSid: string, the sid of the active email auth session\n */\n stateUpdated(this: void, nextStage: AuthType | string, status: IStageStatus): void;\n\n /**\n * A function that takes the email address (string), clientSecret (string), attempt number (int) and\n * sessionId (string) and calls the relevant requestToken function and returns the promise returned by that\n * function.\n * If the resulting promise rejects, the rejection will propagate through to the attemptAuth promise.\n */\n requestEmailToken(\n this: void,\n email: string,\n secret: string,\n attempt: number,\n session: string,\n ): Promise<{ sid: string }>;\n /**\n * Called whenever the interactive auth logic becomes busy submitting information provided by the user or finishes.\n * After this has been called with true the UI should indicate that a request is in progress\n * until it is called again with false.\n */\n busyChanged?(this: void, busy: boolean): void;\n startAuthStage?(this: void, nextStage: string): Promise<void>; // LEGACY\n}\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n * <p>Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n * <p>Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @param opts - options object\n * @typeParam T - the return type of the request when it is successful\n */\nexport class InteractiveAuth<T> {\n private readonly matrixClient: MatrixClient;\n private readonly inputs: IInputs;\n private readonly clientSecret: string;\n private readonly requestCallback: IOpts<T>[\"doRequest\"];\n private readonly busyChangedCallback?: IOpts<T>[\"busyChanged\"];\n private readonly stateUpdatedCallback: IOpts<T>[\"stateUpdated\"];\n private readonly requestEmailTokenCallback: IOpts<T>[\"requestEmailToken\"];\n private readonly supportedStages?: Set<string>;\n\n // The current latest data or error received from the server during the user interactive auth flow.\n private data: IAuthData & MatrixError[\"data\"];\n private emailSid?: string;\n private requestingEmailToken = false;\n private attemptAuthDeferred: PromiseWithResolvers<T> | null = null;\n private chosenFlow: UIAFlow | null = null;\n private currentStage: string | null = null;\n\n private emailAttempt = 1;\n\n // if we are currently trying to submit an auth dict (which includes polling)\n // the promise the will resolve/reject when it completes\n private submitPromise: Promise<void> | null = null;\n\n public constructor(opts: IOpts<T>) {\n this.matrixClient = opts.matrixClient;\n this.data = opts.authData || { flows: [] };\n this.requestCallback = opts.doRequest;\n this.busyChangedCallback = opts.busyChanged;\n // startAuthStage included for backwards compat\n this.stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;\n this.requestEmailTokenCallback = opts.requestEmailToken;\n this.inputs = opts.inputs || {};\n\n if (opts.sessionId) this.data.session = opts.sessionId;\n this.clientSecret = opts.clientSecret || this.matrixClient.generateClientSecret();\n this.emailSid = opts.emailSid;\n if (opts.supportedStages !== undefined) this.supportedStages = new Set(opts.supportedStages);\n }\n\n /**\n * begin the authentication process.\n *\n * @returns which resolves to the response on success,\n * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if\n * no suitable authentication flow can be found\n */\n public async attemptAuth(): Promise<T> {\n // This promise will be quite long-lived and will resolve when the\n // request is authenticated and completes successfully.\n this.attemptAuthDeferred = Promise.withResolvers();\n // pluck the promise out now, as doRequest may clear before we return\n const promise = this.attemptAuthDeferred.promise;\n\n // if we have no flows, try a request to acquire the flows\n if (!(this.data as IAuthData)?.flows?.length) {\n this.busyChangedCallback?.(true);\n // use the existing sessionId, if one is present.\n const auth = (this.data as IAuthData).session ? { session: (this.data as IAuthData).session } : null;\n this.doRequest(auth).finally(() => {\n this.busyChangedCallback?.(false);\n });\n } else {\n this.startNextAuthStage();\n }\n\n return promise;\n }\n\n /**\n * Poll to check if the auth session or current stage has been\n * completed out-of-band. If so, the attemptAuth promise will\n * be resolved.\n */\n public async poll(): Promise<void> {\n if (!(this.data as IAuthData).session) return;\n // likewise don't poll if there is no auth session in progress\n if (!this.attemptAuthDeferred) return;\n // if we currently have a request in flight, there's no point making\n // another just to check what the status is\n if (this.submitPromise) return;\n\n let authDict: AuthDict = {};\n if (this.currentStage == EMAIL_STAGE_TYPE) {\n // The email can be validated out-of-band, but we need to provide the\n // creds so the HS can go & check it.\n if (this.emailSid) {\n const creds: Record<string, string> = {\n sid: this.emailSid,\n client_secret: this.clientSecret,\n };\n const isUrl = this.matrixClient.getIdentityServerUrl();\n if (isUrl) {\n creds.id_server = new URL(isUrl).host;\n }\n authDict = {\n type: EMAIL_STAGE_TYPE,\n threepid_creds: creds,\n };\n }\n }\n\n this.submitAuthDict(authDict, true);\n }\n\n /**\n * get the auth session ID\n *\n * @returns session id\n */\n public getSessionId(): string | undefined {\n return (this.data as IAuthData)?.session;\n }\n\n /**\n * get the client secret used for validation sessions\n * with the identity server.\n *\n * @returns client secret\n */\n public getClientSecret(): string {\n return this.clientSecret;\n }\n\n /**\n * get the server params for a given stage\n *\n * @param loginType - login type for the stage\n * @returns any parameters from the server for this stage\n */\n public getStageParams(loginType: string): Record<string, any> | undefined {\n return (this.data as IAuthData)?.params?.[loginType];\n }\n\n public getChosenFlow(): UIAFlow | null {\n return this.chosenFlow;\n }\n\n /**\n * submit a new auth dict and fire off the request. This will either\n * make attemptAuth resolve/reject, or cause the startAuthStage callback\n * to be called for a new stage.\n *\n * @param authData - new auth dict to send to the server. Should\n * include a `type` property denoting the login type, as well as any\n * other params for that stage.\n * @param background - If true, this request failing will not result\n * in the attemptAuth promise being rejected. This can be set to true\n * for requests that just poll to see if auth has been completed elsewhere.\n */\n public async submitAuthDict(authData: AuthDict, background = false): Promise<void> {\n if (!this.attemptAuthDeferred) {\n throw new Error(\"submitAuthDict() called before attemptAuth()\");\n }\n\n if (!background) {\n this.busyChangedCallback?.(true);\n }\n\n // if we're currently trying a request, wait for it to finish\n // as otherwise we can get multiple 200 responses which can mean\n // things like multiple logins for register requests.\n while (this.submitPromise) {\n try {\n await this.submitPromise;\n } catch {\n // discard any exceptions as we only care when its done,\n // not whether it worked or not\n }\n }\n\n // use the sessionid from the last request, if one is present.\n let auth: AuthDict;\n if ((this.data as IAuthData)?.session) {\n auth = Object.assign(\n {\n session: (this.data as IAuthData).session,\n },\n authData,\n );\n } else {\n auth = authData;\n }\n\n try {\n // NB. the 'background' flag is deprecated by the busyChanged\n // callback and is here for backwards compat\n this.submitPromise = this.doRequest(auth, background);\n await this.submitPromise;\n } finally {\n this.submitPromise = null;\n if (!background) {\n this.busyChangedCallback?.(false);\n }\n }\n }\n\n /**\n * Gets the sid for the email validation session\n * Specific to m.login.email.identity\n *\n * @returns The sid of the email auth session\n */\n public getEmailSid(): string | undefined {\n return this.emailSid;\n }\n\n /**\n * Sets the sid for the email validation session\n * This must be set in order to successfully poll for completion\n * of the email validation.\n * Specific to m.login.email.identity\n *\n * @param sid - The sid for the email validation session\n */\n public setEmailSid(sid: string): void {\n this.emailSid = sid;\n }\n\n /**\n * Requests a new email token and sets the email sid for the validation session\n */\n public requestEmailToken = async (): Promise<void> => {\n if (!this.requestingEmailToken) {\n logger.trace(\"Requesting email token. Attempt: \" + this.emailAttempt);\n // If we've picked a flow with email auth, we send the email\n // now because we want the request to fail as soon as possible\n // if the email address is not valid (ie. already taken or not\n // registered, depending on what the operation is).\n this.requestingEmailToken = true;\n try {\n const requestTokenResult = await this.requestEmailTokenCallback(\n this.inputs.emailAddress!,\n this.clientSecret,\n this.emailAttempt++,\n (this.data as IAuthData).session!,\n );\n this.emailSid = requestTokenResult.sid;\n logger.trace(\"Email token request succeeded\");\n } finally {\n this.requestingEmailToken = false;\n }\n } else {\n logger.warn(\"Could not request email token: Already requesting\");\n }\n };\n\n /**\n * Fire off a request, and either resolve the promise, or call\n * startAuthStage.\n *\n * @internal\n * @param auth - new auth dict, including session id\n * @param background - If true, this request is a background poll, so it\n * failing will not result in the attemptAuth promise being rejected.\n * This can be set to true for requests that just poll to see if auth has\n * been completed elsewhere.\n */\n private async doRequest(auth: AuthDict | null, background = false): Promise<void> {\n try {\n const result = await this.requestCallback(auth, background);\n this.attemptAuthDeferred!.resolve(result);\n this.attemptAuthDeferred = null;\n } catch (error) {\n const matrixError = error instanceof MatrixError ? error : null;\n\n // sometimes UI auth errors don't come with flows\n const errorFlows = matrixError?.data?.flows ?? null;\n const haveFlows = (this.data as IAuthData)?.flows || Boolean(errorFlows);\n if (!matrixError || matrixError.httpStatus !== 401 || !matrixError.data || !haveFlows) {\n // doesn't look like an interactive-auth failure.\n if (!background) {\n this.attemptAuthDeferred?.reject(error);\n } else {\n // We ignore all failures here (even non-UI auth related ones)\n // since we don't want to suddenly fail if the internet connection\n // had a blip whilst we were polling\n logger.log(\"Background poll request failed doing UI auth: ignoring\", error);\n }\n }\n if (matrixError && !matrixError.data) {\n matrixError.data = {};\n }\n // if the error didn't come with flows, completed flows or session ID,\n // copy over the ones we have. Synapse sometimes sends responses without\n // any UI auth data (eg. when polling for email validation, if the email\n // has not yet been validated). This appears to be a Synapse bug, which\n // we workaround here.\n if (matrixError && !matrixError.data.flows && !matrixError.data.completed && !matrixError.data.session) {\n matrixError.data.flows = (this.data as IAuthData).flows;\n matrixError.data.completed = (this.data as IAuthData).completed;\n matrixError.data.session = (this.data as IAuthData).session;\n }\n if (matrixError) {\n this.data = matrixError.data;\n }\n try {\n this.startNextAuthStage();\n } catch (e) {\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n return;\n }\n\n if (!this.emailSid && this.chosenFlow?.stages.includes(AuthType.Email)) {\n try {\n await this.requestEmailToken();\n // NB. promise is not resolved here - at some point, doRequest\n // will be called again and if the user has jumped through all\n // the hoops correctly, auth will be complete and the request\n // will succeed.\n // Also, we should expose the fact that this request has compledted\n // so clients can know that the email has actually been sent.\n } catch (e) {\n // we failed to request an email token, so fail the request.\n // This could be due to the email already beeing registered\n // (or not being registered, depending on what we're trying\n // to do) or it could be a network failure. Either way, pass\n // the failure up as the user can't complete auth if we can't\n // send the email, for whatever reason.\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n }\n }\n }\n }\n\n /**\n * Pick the next stage and call the callback\n *\n * @internal\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private startNextAuthStage(): void {\n const nextStage = this.chooseStage();\n if (!nextStage) {\n throw new Error(\"No incomplete flows from the server\");\n }\n this.currentStage = nextStage;\n\n if (nextStage === AuthType.Dummy) {\n this.submitAuthDict({\n type: \"m.login.dummy\",\n });\n return;\n }\n\n if (this.data?.errcode || this.data?.error) {\n this.stateUpdatedCallback(nextStage, {\n errcode: this.data?.errcode || \"\",\n error: this.data?.error || \"\",\n });\n return;\n }\n\n this.stateUpdatedCallback(nextStage, nextStage === EMAIL_STAGE_TYPE ? { emailSid: this.emailSid } : {});\n }\n\n /**\n * Pick the next auth stage\n *\n * @internal\n * @returns login type\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseStage(): AuthType | string | undefined {\n if (this.chosenFlow === null) {\n this.chosenFlow = this.chooseFlow();\n }\n logger.log(\"Active flow => %s\", JSON.stringify(this.chosenFlow));\n const nextStage = this.firstUncompletedStage(this.chosenFlow);\n logger.log(\"Next stage: %s\", nextStage);\n return nextStage;\n }\n\n // Returns a low number for flows we consider best. Counts increase for longer flows and even more so\n // for flows which contain stages not listed in `supportedStages`.\n private scoreFlow(flow: UIAFlow): number {\n let score = flow.stages.length;\n if (this.supportedStages !== undefined) {\n // Add 10 points to the score for each unsupported stage in the flow.\n score += flow.stages.filter((stage) => !this.supportedStages!.has(stage)).length * 10;\n }\n return score;\n }\n\n /**\n * Pick one of the flows from the returned list\n * If a flow using all of the inputs is found, it will\n * be returned, otherwise, null will be returned.\n *\n * Only flows using all given inputs are chosen because it\n * is likely to be surprising if the user provides a\n * credential and it is not used. For example, for registration,\n * this could result in the email not being used which would leave\n * the account with no means to reset a password.\n *\n * @internal\n * @returns flow\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseFlow(): UIAFlow {\n const flows = (this.data as IAuthData)?.flows || [];\n\n // we've been given an email or we've already done an email part\n const haveEmail = Boolean(this.inputs.emailAddress) || Boolean(this.emailSid);\n const haveMsisdn = Boolean(this.inputs.phoneCountry) && Boolean(this.inputs.phoneNumber);\n\n // Flows are not represented in a significant order, so we can choose any we support best\n // Sort flows based on how many unsupported stages they contain ascending\n flows.sort((a, b) => this.scoreFlow(a) - this.scoreFlow(b));\n\n for (const flow of flows) {\n let flowHasEmail = false;\n let flowHasMsisdn = false;\n for (const stage of flow.stages) {\n if (stage === EMAIL_STAGE_TYPE) {\n flowHasEmail = true;\n } else if (stage == MSISDN_STAGE_TYPE) {\n flowHasMsisdn = true;\n }\n }\n\n if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {\n return flow;\n }\n }\n\n const requiredStages: string[] = [];\n if (haveEmail) requiredStages.push(EMAIL_STAGE_TYPE);\n if (haveMsisdn) requiredStages.push(MSISDN_STAGE_TYPE);\n // Throw an error with a fairly generic description, but with more\n // information such that the app can give a better one if so desired.\n throw new NoAuthFlowFoundError(\"No appropriate authentication flow found\", requiredStages, flows);\n }\n\n /**\n * Get the first uncompleted stage in the given flow\n *\n * @internal\n * @returns login type\n */\n private firstUncompletedStage(flow: UIAFlow): AuthType | string | undefined {\n const completed = (this.data as IAuthData)?.completed || [];\n return flow.stages.find((stageType) => !completed.includes(stageType));\n }\n}\n"],"mappings":";AAAA;AACA;AACA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,EAAE,GAAG,IAAI,CAEhC;IAEM,KAAK,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAEhC;IAEM,IAAI,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAE/B;IAEM,IAAI,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAE/B;IAEM,KAAK,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAEhC;IAEM,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,WAAW,CAE9C;IAED,OAAO,CAAC,eAAe;CAiB1B"}
package/lib/logger.js CHANGED
@@ -39,11 +39,9 @@ const DEFAULT_NAMESPACE = "matrix";
39
39
  // when logging so we always get the current value of console methods.
40
40
  loglevel.methodFactory = function (methodName, logLevel, loggerName) {
41
41
  return function (...args) {
42
- /* eslint-disable @typescript-eslint/no-invalid-this */
43
42
  if (this.prefix) {
44
43
  args.unshift(this.prefix);
45
44
  }
46
- /* eslint-enable @typescript-eslint/no-invalid-this */
47
45
  const supportedByConsole = methodName === "error" || methodName === "warn" || methodName === "trace" || methodName === "info" || methodName === "debug";
48
46
  /* eslint-disable no-console */
49
47
  if (supportedByConsole) {
package/lib/logger.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","names":[],"sources":["../src/logger.ts"],"sourcesContent":["/*\nCopyright 2018 André Jaenisch\nCopyright 2019-2025 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 loglevel from \"loglevel\";\n\n/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */\ninterface LoggerWithLogMethod extends Logger {\n /**\n * Output debug message to the logger.\n *\n * @param msg - Data to log.\n *\n * @deprecated prefer {@link Logger.debug}.\n */\n log(...msg: any[]): void;\n}\n\n/** Logger interface used within the js-sdk codebase */\nexport interface Logger extends BaseLogger {\n /**\n * Create a child logger.\n *\n * This child will use the `methodFactory` of the parent, so any log extensions applied to the parent\n * at the time of calling `getChild` will be applied to the child as well.\n * It will NOT apply changes to the parent's `methodFactory` after the child was created.\n * Those changes need to be applied to the child manually.\n *\n * @param namespace - name to add to the current logger to generate the child. Some implementations of `Logger`\n * use this as a prefix; others use a different mechanism.\n */\n getChild(namespace: string): Logger;\n}\n\n/** The basic interface for a logger which doesn't support children */\nexport interface BaseLogger {\n /**\n * Output trace message to the logger, with stack trace.\n *\n * @param msg - Data to log.\n */\n trace(this: void, ...msg: any[]): void;\n\n /**\n * Output debug message to the logger.\n *\n * @param msg - Data to log.\n */\n debug(this: void, ...msg: any[]): void;\n\n /**\n * Output info message to the logger.\n *\n * @param msg - Data to log.\n */\n info(this: void, ...msg: any[]): void;\n\n /**\n * Output warn message to the logger.\n *\n * @param msg - Data to log.\n */\n warn(this: void, ...msg: any[]): void;\n\n /**\n * Output error message to the logger.\n *\n * @param msg - Data to log.\n */\n error(this: void, ...msg: any[]): void;\n}\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nconst DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nloglevel.methodFactory = function (methodName, logLevel, loggerName) {\n return function (this: PrefixedLogger, ...args): void {\n /* eslint-disable @typescript-eslint/no-invalid-this */\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n /* eslint-enable @typescript-eslint/no-invalid-this */\n const supportedByConsole =\n methodName === \"error\" ||\n methodName === \"warn\" ||\n methodName === \"trace\" ||\n methodName === \"info\" ||\n methodName === \"debug\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Implementation of {@link Logger} based on `loglevel`.\n */\ninterface PrefixedLogger extends loglevel.Logger, LoggerWithLogMethod {\n prefix?: string;\n}\n\n/**\n * Internal utility function: gets a {@link Logger} based on `loglevel`.\n *\n * Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.\n *\n * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.\n */\nfunction getPrefixedLogger(prefix?: string): PrefixedLogger {\n const loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? \"\" : `-${prefix}`);\n const prefixLogger = loglevel.getLogger(loggerName) as PrefixedLogger;\n\n if (prefixLogger.getChild === undefined) {\n // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.\n prefixLogger.prefix = prefix;\n prefixLogger.getChild = (childPrefix): Logger => {\n // create the new child logger\n const childLogger = getPrefixedLogger((prefix ?? \"\") + childPrefix);\n // Assign the methodFactory from the parent logger.\n // This is useful if we add extensions to the parent logger that modifies\n // its methodFactory. (An example extension is: storing each log to a rageshake db)\n childLogger.methodFactory = prefixLogger.methodFactory;\n // Rebuild the child logger with the new methodFactory.\n childLogger.rebuild();\n return childLogger;\n };\n prefixLogger.setLevel(loglevel.levels.DEBUG, false);\n }\n\n return prefixLogger;\n}\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n *\n * @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger\n * associated with `MatrixClient`.\n */\nexport const logger = getPrefixedLogger() as LoggerWithLogMethod;\n\n/**\n * A \"span\" for grouping related log lines together.\n *\n * The current implementation just adds the name at the start of each log line.\n *\n * This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,\n * it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,\n * no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course\n * of an application's life and just drop references to them when the job is done.\n */\nexport class LogSpan implements BaseLogger {\n private readonly name;\n\n public constructor(\n private readonly parent: BaseLogger,\n name: string,\n ) {\n this.name = name + \":\";\n }\n\n public trace(...msg: any[]): void {\n this.parent.trace(this.name, ...msg);\n }\n\n public debug(...msg: any[]): void {\n this.parent.debug(this.name, ...msg);\n }\n\n public info(...msg: any[]): void {\n this.parent.info(this.name, ...msg);\n }\n\n public warn(...msg: any[]): void {\n this.parent.warn(this.name, ...msg);\n }\n\n public error(...msg: any[]): void {\n this.parent.error(this.name, ...msg);\n }\n}\n\n/**\n * A simplification of the `Debugger` type exposed by the `debug` library. We reimplement the bits we need here\n * to avoid a dependency on `debug`.\n */\ninterface Debugger {\n (formatter: any, ...args: any[]): void;\n extend: (namespace: string, delimiter?: string) => Debugger;\n}\n\n/**\n * A `Logger` instance, suitable for use in {@link ICreateClientOpts.logger}, which will write to the `debug` library.\n *\n * @example\n * ```js\n * import debug from \"debug\";\n *\n * const client = createClient({\n * baseUrl: homeserverUrl,\n * userId: userId,\n * accessToken: \"akjgkrgjs\",\n * deviceId: \"xzcvb\",\n * logger: new DebugLogger(debug(`matrix-js-sdk:${userId}`)),\n * });\n * ```\n */\nexport class DebugLogger implements Logger {\n public constructor(private debugInstance: Debugger) {}\n\n public trace(...msg: any[]): void {\n this.debugWithPrefix(\"[TRACE]\", ...msg);\n }\n\n public debug(...msg: any[]): void {\n this.debugWithPrefix(\"[DEBUG]\", ...msg);\n }\n\n public info(...msg: any[]): void {\n this.debugWithPrefix(\"[INFO]\", ...msg);\n }\n\n public warn(...msg: any[]): void {\n this.debugWithPrefix(\"[WARN]\", ...msg);\n }\n\n public error(...msg: any[]): void {\n this.debugWithPrefix(\"[ERROR]\", ...msg);\n }\n\n public getChild(namespace: string): DebugLogger {\n return new DebugLogger(this.debugInstance.extend(namespace));\n }\n\n private debugWithPrefix(prefix: string, ...msg: any[]): void {\n let formatter: string;\n\n // Convert the first argument to a string, so that we can safely add a prefix. This is much the same logic that\n // `debug()` uses.\n if (msg.length === 0) {\n formatter = \"\";\n } else if (msg[0] instanceof Error) {\n const err = msg.shift();\n formatter = err.stack || err.message;\n } else if (typeof msg[0] == \"string\") {\n formatter = msg.shift();\n } else {\n formatter = \"%O\";\n }\n this.debugInstance(prefix + \" \" + formatter, ...msg);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAO,QAAQ,MAAM,UAAU;;AAE/B;;AAYA;;AAgBA;;AAsCA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,iBAAiB,GAAG,QAAQ;;AAElC;AACA;AACA;AACA;AACA;AACA,QAAQ,CAAC,aAAa,GAAG,UAAU,UAAU,EAAE,QAAQ,EAAE,UAAU,EAAE;EACjE,OAAO,UAAgC,GAAG,IAAI,EAAQ;IAClD;IACA,IAAI,IAAI,CAAC,MAAM,EAAE;MACb,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IAC7B;IACA;IACA,MAAM,kBAAkB,GACpB,UAAU,KAAK,OAAO,IACtB,UAAU,KAAK,MAAM,IACrB,UAAU,KAAK,OAAO,IACtB,UAAU,KAAK,MAAM,IACrB,UAAU,KAAK,OAAO;IAC1B;IACA,IAAI,kBAAkB,EAAE;MACpB,OAAO,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,IAAI,CAAC;IACvC,CAAC,MAAM;MACH,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;IAC/B;IACA;EACJ,CAAC;AACL,CAAC;;AAED;AACA;AACA;;AAKA;AACA;AACA;AACA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AM,CAAC,SAAS,CAAC,CAAC;EAChE;EAEQ,eAAe,CAAC,MAAc,EAAE,GAAG,GAAU,EAAQ;IACzD,IAAI,SAAiB;;IAErB;IACA;IACA,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;MAClB,SAAS,GAAG,EAAE;IAClB,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,YAAY,KAAK,EAAE;MAChC,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;MACvB,SAAS,GAAG,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,OAAO;IACxC,CAAC,MAAM,IAAI,OAAO,GAAG,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE;MAClC,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC,MAAM;MACH,SAAS,GAAG,IAAI;IACpB;IACA,IAAI,CAAC,aAAa,CAAC,MAAM,GAAG,GAAG,GAAG,SAAS,EAAE,GAAG,GAAG,CAAC;EACxD;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"logger.js","names":[],"sources":["../src/logger.ts"],"sourcesContent":["/*\nCopyright 2018 André Jaenisch\nCopyright 2019-2025 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 loglevel from \"loglevel\";\n\n/** Backwards-compatibility hack to expose `log` to applications that might still be relying on it. */\ninterface LoggerWithLogMethod extends Logger {\n /**\n * Output debug message to the logger.\n *\n * @param msg - Data to log.\n *\n * @deprecated prefer {@link Logger.debug}.\n */\n log(...msg: any[]): void;\n}\n\n/** Logger interface used within the js-sdk codebase */\nexport interface Logger extends BaseLogger {\n /**\n * Create a child logger.\n *\n * This child will use the `methodFactory` of the parent, so any log extensions applied to the parent\n * at the time of calling `getChild` will be applied to the child as well.\n * It will NOT apply changes to the parent's `methodFactory` after the child was created.\n * Those changes need to be applied to the child manually.\n *\n * @param namespace - name to add to the current logger to generate the child. Some implementations of `Logger`\n * use this as a prefix; others use a different mechanism.\n */\n getChild(namespace: string): Logger;\n}\n\n/** The basic interface for a logger which doesn't support children */\nexport interface BaseLogger {\n /**\n * Output trace message to the logger, with stack trace.\n *\n * @param msg - Data to log.\n */\n trace(this: void, ...msg: any[]): void;\n\n /**\n * Output debug message to the logger.\n *\n * @param msg - Data to log.\n */\n debug(this: void, ...msg: any[]): void;\n\n /**\n * Output info message to the logger.\n *\n * @param msg - Data to log.\n */\n info(this: void, ...msg: any[]): void;\n\n /**\n * Output warn message to the logger.\n *\n * @param msg - Data to log.\n */\n warn(this: void, ...msg: any[]): void;\n\n /**\n * Output error message to the logger.\n *\n * @param msg - Data to log.\n */\n error(this: void, ...msg: any[]): void;\n}\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nconst DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nloglevel.methodFactory = function (methodName, logLevel, loggerName) {\n return function (this: PrefixedLogger, ...args): void {\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n const supportedByConsole =\n methodName === \"error\" ||\n methodName === \"warn\" ||\n methodName === \"trace\" ||\n methodName === \"info\" ||\n methodName === \"debug\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Implementation of {@link Logger} based on `loglevel`.\n */\ninterface PrefixedLogger extends loglevel.Logger, LoggerWithLogMethod {\n prefix?: string;\n}\n\n/**\n * Internal utility function: gets a {@link Logger} based on `loglevel`.\n *\n * Child loggers produced by {@link Logger.getChild} add the name of the child logger as a prefix on each log line.\n *\n * @param prefix Prefix to add to each logged line. If undefined, no prefix will be added.\n */\nfunction getPrefixedLogger(prefix?: string): PrefixedLogger {\n const loggerName = DEFAULT_NAMESPACE + (prefix === undefined ? \"\" : `-${prefix}`);\n const prefixLogger = loglevel.getLogger(loggerName) as PrefixedLogger;\n\n if (prefixLogger.getChild === undefined) {\n // This is a new loglevel Logger which has not been turned into a PrefixedLogger yet.\n prefixLogger.prefix = prefix;\n prefixLogger.getChild = (childPrefix): Logger => {\n // create the new child logger\n const childLogger = getPrefixedLogger((prefix ?? \"\") + childPrefix);\n // Assign the methodFactory from the parent logger.\n // This is useful if we add extensions to the parent logger that modifies\n // its methodFactory. (An example extension is: storing each log to a rageshake db)\n childLogger.methodFactory = prefixLogger.methodFactory;\n // Rebuild the child logger with the new methodFactory.\n childLogger.rebuild();\n return childLogger;\n };\n prefixLogger.setLevel(loglevel.levels.DEBUG, false);\n }\n\n return prefixLogger;\n}\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n *\n * @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger\n * associated with `MatrixClient`.\n */\nexport const logger = getPrefixedLogger() as LoggerWithLogMethod;\n\n/**\n * A \"span\" for grouping related log lines together.\n *\n * The current implementation just adds the name at the start of each log line.\n *\n * This offers a lighter-weight alternative to 'child' loggers returned by {@link Logger#getChild}. In particular,\n * it's not possible to apply individual filters to the LogSpan such as setting the verbosity level. On the other hand,\n * no reference to the LogSpan is retained in the logging framework, so it is safe to make lots of them over the course\n * of an application's life and just drop references to them when the job is done.\n */\nexport class LogSpan implements BaseLogger {\n private readonly name;\n\n public constructor(\n private readonly parent: BaseLogger,\n name: string,\n ) {\n this.name = name + \":\";\n }\n\n public trace(...msg: any[]): void {\n this.parent.trace(this.name, ...msg);\n }\n\n public debug(...msg: any[]): void {\n this.parent.debug(this.name, ...msg);\n }\n\n public info(...msg: any[]): void {\n this.parent.info(this.name, ...msg);\n }\n\n public warn(...msg: any[]): void {\n this.parent.warn(this.name, ...msg);\n }\n\n public error(...msg: any[]): void {\n this.parent.error(this.name, ...msg);\n }\n}\n\n/**\n * A simplification of the `Debugger` type exposed by the `debug` library. We reimplement the bits we need here\n * to avoid a dependency on `debug`.\n */\ninterface Debugger {\n (formatter: any, ...args: any[]): void;\n extend: (namespace: string, delimiter?: string) => Debugger;\n}\n\n/**\n * A `Logger` instance, suitable for use in {@link ICreateClientOpts.logger}, which will write to the `debug` library.\n *\n * @example\n * ```js\n * import debug from \"debug\";\n *\n * const client = createClient({\n * baseUrl: homeserverUrl,\n * userId: userId,\n * accessToken: \"akjgkrgjs\",\n * deviceId: \"xzcvb\",\n * logger: new DebugLogger(debug(`matrix-js-sdk:${userId}`)),\n * });\n * ```\n */\nexport class DebugLogger implements Logger {\n public constructor(private debugInstance: Debugger) {}\n\n public trace(...msg: any[]): void {\n this.debugWithPrefix(\"[TRACE]\", ...msg);\n }\n\n public debug(...msg: any[]): void {\n this.debugWithPrefix(\"[DEBUG]\", ...msg);\n }\n\n public info(...msg: any[]): void {\n this.debugWithPrefix(\"[INFO]\", ...msg);\n }\n\n public warn(...msg: any[]): void {\n this.debugWithPrefix(\"[WARN]\", ...msg);\n }\n\n public error(...msg: any[]): void {\n this.debugWithPrefix(\"[ERROR]\", ...msg);\n }\n\n public getChild(namespace: string): DebugLogger {\n return new DebugLogger(this.debugInstance.extend(namespace));\n }\n\n private debugWithPrefix(prefix: string, ...msg: any[]): void {\n let formatter: string;\n\n // Convert the first argument to a string, so that we can safely add a prefix. This is much the same logic that\n // `debug()` uses.\n if (msg.length === 0) {\n formatter = \"\";\n } else if (msg[0] instanceof Error) {\n const err = msg.shift();\n formatter = err.stack || err.message;\n } else if (typeof msg[0] == \"string\") {\n formatter = msg.shift();\n } else {\n formatter = \"%O\";\n }\n this.debugInstance(prefix + \" \" + formatter, ...msg);\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAO,QAAQ,MAAM,UAAU;;AAE/B;;AAYA;;AAgBA;;AAsCA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,iBAAiB,GAAG,QAAQ;;AAElC;AACA;AACA;AACA;AACA;AACA,QAAQ,CAAC,aAAa,GAAG,UAAU,UAAU,EAAE,QAAQ,EAAE,UAAU,EAAE;EACjE,OAAO,UAAgC,GAAG,IAAI,EAAQ;IAClD,IAAI,IAAI,CAAC,MAAM,EAAE;MACb,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IAC7B;IACA,MAAM,kBAAkB,GACpB,UAAU,KAAK,OAAO,IACtB,UAAU,KAAK,MAAM,IACrB,UAAU,KAAK,OAAO,IACtB,UAAU,KAAK,MAAM,IACrB,UAAU,KAAK,OAAO;IAC1B;IACA,IAAI,kBAAkB,EAAE;MACpB,OAAO,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,IAAI,CAAC;IACvC,CAAC,MAAM;MACH,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;IAC/B;IACA;EACJ,CAAC;AACL,CAAC;;AAED;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,iBAAiB,CAAC,MAAe,EAAkB;EACxD,MAAM,UAAU,GAAG,iBAAiB,IAAI,MAAM,KAAK,SAAS,GAAG,EAAE,GAAG,IAAI,MAAM,EAAE,CAAC;EACjF,MAAM,YAAY,GAAG,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAmB;EAErE,IAAI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C,CAAC,YAAY,KAAK,EAAE;MAChC,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;MACvB,SAAS,GAAG,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,OAAO;IACxC,CAAC,MAAM,IAAI,OAAO,GAAG,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE;MAClC,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC,MAAM;MACH,SAAS,GAAG,IAAI;IACpB;IACA,IAAI,CAAC,aAAa,CAAC,MAAM,GAAG,GAAG,GAAG,SAAS,EAAE,GAAG,GAAG,CAAC;EACxD;AACJ","ignoreList":[]}
@@ -130,7 +130,7 @@ export declare class CallMembership {
130
130
  * ## RTC Membership
131
131
  * Gets the primary transport to use for this RTC membership (m.rtc.member).
132
132
  * This will return the primary transport that is used by this call membership to publish their media.
133
- * Directly relates to the `rtc_transports` field.
133
+ * Directly relates to the `transports.published` field.
134
134
  *
135
135
  * ## Legacy session membership
136
136
  * In case of a legacy session membership (m.call.member) this will return the selected transport where
@@ -138,14 +138,14 @@ export declare class CallMembership {
138
138
  * If the `focus_selection` is `oldest_membership` this will return the transport of the oldest membership
139
139
  * in the room (based on the `created_ts` field of the session membership).
140
140
  * If the `focus_selection` is `multi_sfu` it will return the first transport of the `foci_preferred` list.
141
- * (`multi_sfu` is equivalent to how `m.rtc.member` `rtc_transports` work).
141
+ * (`multi_sfu` is equivalent to how `m.rtc.member` `transports.published` work).
142
142
  * @param oldestMembership For backwards compatibility with session membership (legacy). Unused in case of RTC membership.
143
143
  * Always required to make the consumer not care if it deals with RTC or session memberships.
144
144
  * @returns The transport this membership uses to publish media or undefined if no transport is available.
145
145
  */
146
146
  getTransport(oldestMembership: CallMembership): Transport | undefined;
147
147
  /**
148
- * The value of the `rtc_transports` field for RTC memberships (m.rtc.member).
148
+ * The value of the `transports.published` field for RTC memberships (m.rtc.member).
149
149
  * Or the value of the `foci_preferred` field for legacy session memberships (m.call.member).
150
150
  */
151
151
  get transports(): Transport[];
@@ -402,7 +402,7 @@ export class CallMembership {
402
402
  * ## RTC Membership
403
403
  * Gets the primary transport to use for this RTC membership (m.rtc.member).
404
404
  * This will return the primary transport that is used by this call membership to publish their media.
405
- * Directly relates to the `rtc_transports` field.
405
+ * Directly relates to the `transports.published` field.
406
406
  *
407
407
  * ## Legacy session membership
408
408
  * In case of a legacy session membership (m.call.member) this will return the selected transport where
@@ -410,7 +410,7 @@ export class CallMembership {
410
410
  * If the `focus_selection` is `oldest_membership` this will return the transport of the oldest membership
411
411
  * in the room (based on the `created_ts` field of the session membership).
412
412
  * If the `focus_selection` is `multi_sfu` it will return the first transport of the `foci_preferred` list.
413
- * (`multi_sfu` is equivalent to how `m.rtc.member` `rtc_transports` work).
413
+ * (`multi_sfu` is equivalent to how `m.rtc.member` `transports.published` work).
414
414
  * @param oldestMembership For backwards compatibility with session membership (legacy). Unused in case of RTC membership.
415
415
  * Always required to make the consumer not care if it deals with RTC or session memberships.
416
416
  * @returns The transport this membership uses to publish media or undefined if no transport is available.
@@ -422,7 +422,7 @@ export class CallMembership {
422
422
  } = this.membershipData;
423
423
  switch (kind) {
424
424
  case MembershipKind.RTC:
425
- return data.rtc_transports[0];
425
+ return data.transports.published[0];
426
426
  case MembershipKind.Session:
427
427
  switch (data.focus_active.focus_selection) {
428
428
  case "oldest_membership":
@@ -442,7 +442,7 @@ export class CallMembership {
442
442
  }
443
443
 
444
444
  /**
445
- * The value of the `rtc_transports` field for RTC memberships (m.rtc.member).
445
+ * The value of the `transports.published` field for RTC memberships (m.rtc.member).
446
446
  * Or the value of the `foci_preferred` field for legacy session memberships (m.call.member).
447
447
  */
448
448
  get transports() {
@@ -452,7 +452,7 @@ export class CallMembership {
452
452
  } = this.membershipData;
453
453
  switch (kind) {
454
454
  case MembershipKind.RTC:
455
- return data.rtc_transports;
455
+ return data.transports.published;
456
456
  case MembershipKind.Session:
457
457
  default:
458
458
  return data.foci_preferred;