matrix-js-sdk 41.5.0 → 41.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/lib/ReEmitter.js +1 -1
  3. package/lib/ReEmitter.js.map +1 -1
  4. package/lib/ToDeviceMessageQueue.js +2 -2
  5. package/lib/ToDeviceMessageQueue.js.map +1 -1
  6. package/lib/autodiscovery.js +0 -1
  7. package/lib/autodiscovery.js.map +1 -1
  8. package/lib/client.js +112 -165
  9. package/lib/client.js.map +1 -1
  10. package/lib/common-crypto/CryptoBackend.js +0 -2
  11. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  12. package/lib/content-helpers.js +3 -5
  13. package/lib/content-helpers.js.map +1 -1
  14. package/lib/content-repo.js +7 -1
  15. package/lib/content-repo.js.map +1 -1
  16. package/lib/crypto/store/indexeddb-crypto-store-backend.js +9 -11
  17. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  18. package/lib/crypto/store/indexeddb-crypto-store.js +0 -2
  19. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  20. package/lib/crypto/store/localStorage-crypto-store.js +11 -9
  21. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  22. package/lib/crypto/store/memory-crypto-store.js +11 -9
  23. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  24. package/lib/crypto-api/index.js +58 -58
  25. package/lib/crypto-api/index.js.map +1 -1
  26. package/lib/embedded.js +29 -45
  27. package/lib/embedded.js.map +1 -1
  28. package/lib/extensible_events_v1/MessageEvent.js +15 -15
  29. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  30. package/lib/extensible_events_v1/PollEndEvent.js +8 -8
  31. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  32. package/lib/extensible_events_v1/PollResponseEvent.js +0 -1
  33. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  34. package/lib/extensible_events_v1/PollStartEvent.js +28 -28
  35. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  36. package/lib/feature.js +5 -1
  37. package/lib/feature.js.map +1 -1
  38. package/lib/filter-component.js +4 -1
  39. package/lib/filter-component.js.map +1 -1
  40. package/lib/filter.js +1 -3
  41. package/lib/filter.js.map +1 -1
  42. package/lib/http-api/errors.js +20 -16
  43. package/lib/http-api/errors.js.map +1 -1
  44. package/lib/http-api/fetch.js +4 -6
  45. package/lib/http-api/fetch.js.map +1 -1
  46. package/lib/http-api/refresh.js +10 -12
  47. package/lib/http-api/refresh.js.map +1 -1
  48. package/lib/interactive-auth.js +1 -11
  49. package/lib/interactive-auth.js.map +1 -1
  50. package/lib/logger.js +0 -2
  51. package/lib/logger.js.map +1 -1
  52. package/lib/matrixrtc/CallMembership.js +43 -57
  53. package/lib/matrixrtc/CallMembership.js.map +1 -1
  54. package/lib/matrixrtc/MatrixRTCSession.js +19 -24
  55. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  56. package/lib/matrixrtc/MatrixRTCSessionManager.js +2 -3
  57. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  58. package/lib/matrixrtc/MembershipManager.js +23 -30
  59. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  60. package/lib/matrixrtc/MembershipManagerActionScheduler.js +1 -2
  61. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  62. package/lib/matrixrtc/RTCEncryptionManager.js +8 -11
  63. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  64. package/lib/matrixrtc/ToDeviceKeyTransport.js +4 -4
  65. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  66. package/lib/matrixrtc/utils.js +7 -1
  67. package/lib/matrixrtc/utils.js.map +1 -1
  68. package/lib/models/MSC3089TreeSpace.js +5 -7
  69. package/lib/models/MSC3089TreeSpace.js.map +1 -1
  70. package/lib/models/beacon.js +5 -11
  71. package/lib/models/beacon.js.map +1 -1
  72. package/lib/models/device.js +0 -7
  73. package/lib/models/device.js.map +1 -1
  74. package/lib/models/event-context.js +1 -2
  75. package/lib/models/event-context.js.map +1 -1
  76. package/lib/models/event-timeline-set.js +16 -26
  77. package/lib/models/event-timeline-set.js.map +1 -1
  78. package/lib/models/event-timeline.js +8 -15
  79. package/lib/models/event-timeline.js.map +1 -1
  80. package/lib/models/event.js +20 -37
  81. package/lib/models/event.js.map +1 -1
  82. package/lib/models/invites-ignorer.js +8 -12
  83. package/lib/models/invites-ignorer.js.map +1 -1
  84. package/lib/models/poll.js +7 -13
  85. package/lib/models/poll.js.map +1 -1
  86. package/lib/models/read-receipt.js +8 -4
  87. package/lib/models/read-receipt.js.map +1 -1
  88. package/lib/models/related-relations.js +0 -2
  89. package/lib/models/related-relations.js.map +1 -1
  90. package/lib/models/relations-container.js +4 -6
  91. package/lib/models/relations-container.js.map +1 -1
  92. package/lib/models/relations.js +7 -10
  93. package/lib/models/relations.js.map +1 -1
  94. package/lib/models/room-member.js +2 -24
  95. package/lib/models/room-member.js.map +1 -1
  96. package/lib/models/room-receipts.js +25 -22
  97. package/lib/models/room-receipts.js.map +1 -1
  98. package/lib/models/room-state.js +2 -2
  99. package/lib/models/room-state.js.map +1 -1
  100. package/lib/models/room-sticky-events.js +20 -5
  101. package/lib/models/room-sticky-events.js.map +1 -1
  102. package/lib/models/room.js +82 -105
  103. package/lib/models/room.js.map +1 -1
  104. package/lib/models/thread.js +12 -57
  105. package/lib/models/thread.js.map +1 -1
  106. package/lib/models/user.js +1 -20
  107. package/lib/models/user.js.map +1 -1
  108. package/lib/oidc/authorize.js +23 -32
  109. package/lib/oidc/authorize.js.map +1 -1
  110. package/lib/oidc/tokenRefresher.js +8 -11
  111. package/lib/oidc/tokenRefresher.js.map +1 -1
  112. package/lib/pushprocessor.js +8 -5
  113. package/lib/pushprocessor.js.map +1 -1
  114. package/lib/receipt-accumulator.js +12 -3
  115. package/lib/receipt-accumulator.js.map +1 -1
  116. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  117. package/lib/rendezvous/MSC4108SignInWithQR.js +10 -23
  118. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  119. package/lib/rendezvous/channels/MSC4108SecureChannel.js +5 -10
  120. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  121. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +5 -15
  122. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  123. package/lib/room-hierarchy.js +7 -12
  124. package/lib/room-hierarchy.js.map +1 -1
  125. package/lib/rust-crypto/DehydratedDeviceManager.js +2 -3
  126. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  127. package/lib/rust-crypto/KeyClaimManager.js +1 -2
  128. package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
  129. package/lib/rust-crypto/OutgoingRequestProcessor.js +11 -4
  130. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  131. package/lib/rust-crypto/OutgoingRequestsManager.js +12 -12
  132. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  133. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +3 -5
  134. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  135. package/lib/rust-crypto/RoomEncryptor.js +6 -6
  136. package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
  137. package/lib/rust-crypto/backup.js +22 -16
  138. package/lib/rust-crypto/backup.js.map +1 -1
  139. package/lib/rust-crypto/device-converter.js +13 -4
  140. package/lib/rust-crypto/device-converter.js.map +1 -1
  141. package/lib/rust-crypto/index.js +1 -3
  142. package/lib/rust-crypto/index.js.map +1 -1
  143. package/lib/rust-crypto/libolm_migration.js +13 -15
  144. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  145. package/lib/rust-crypto/rust-crypto.js +52 -59
  146. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  147. package/lib/rust-crypto/verification.js +10 -10
  148. package/lib/rust-crypto/verification.js.map +1 -1
  149. package/lib/scheduler.js +2 -2
  150. package/lib/scheduler.js.map +1 -1
  151. package/lib/secret-storage.js +16 -10
  152. package/lib/secret-storage.js.map +1 -1
  153. package/lib/serverCapabilities.js +2 -5
  154. package/lib/serverCapabilities.js.map +1 -1
  155. package/lib/sliding-sync-sdk.js +4 -9
  156. package/lib/sliding-sync-sdk.js.map +1 -1
  157. package/lib/sliding-sync.js +4 -9
  158. package/lib/sliding-sync.js.map +1 -1
  159. package/lib/store/indexeddb-local-backend.js +13 -8
  160. package/lib/store/indexeddb-local-backend.js.map +1 -1
  161. package/lib/store/indexeddb-remote-backend.js +6 -7
  162. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  163. package/lib/store/indexeddb-store-worker.js +1 -2
  164. package/lib/store/indexeddb-store-worker.js.map +1 -1
  165. package/lib/store/indexeddb.js +4 -2
  166. package/lib/store/indexeddb.js.map +1 -1
  167. package/lib/store/memory.js +0 -4
  168. package/lib/store/memory.js.map +1 -1
  169. package/lib/sync-accumulator.js +2 -4
  170. package/lib/sync-accumulator.js.map +1 -1
  171. package/lib/sync.js +36 -43
  172. package/lib/sync.js.map +1 -1
  173. package/lib/timeline-window.js +2 -6
  174. package/lib/timeline-window.js.map +1 -1
  175. package/lib/utils/decryptAESSecretStorageItem.js +5 -1
  176. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  177. package/lib/utils/encryptAESSecretStorageItem.js +5 -1
  178. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  179. package/lib/utils.js +35 -20
  180. package/lib/utils.js.map +1 -1
  181. package/lib/webrtc/call.js +13 -45
  182. package/lib/webrtc/call.js.map +1 -1
  183. package/lib/webrtc/callEventHandler.js +0 -5
  184. package/lib/webrtc/callEventHandler.js.map +1 -1
  185. package/lib/webrtc/callFeed.js +0 -15
  186. package/lib/webrtc/callFeed.js.map +1 -1
  187. package/lib/webrtc/groupCall.js +82 -89
  188. package/lib/webrtc/groupCall.js.map +1 -1
  189. package/lib/webrtc/groupCallEventHandler.js +6 -7
  190. package/lib/webrtc/groupCallEventHandler.js.map +1 -1
  191. package/lib/webrtc/mediaHandler.js +8 -15
  192. package/lib/webrtc/mediaHandler.js.map +1 -1
  193. package/lib/webrtc/stats/callStatsReportGatherer.js +2 -5
  194. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  195. package/lib/webrtc/stats/connectionStatsReportBuilder.js +5 -1
  196. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  197. package/lib/webrtc/stats/groupCallStats.js +3 -4
  198. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  199. package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
  200. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  201. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +1 -1
  202. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  203. package/package.json +3 -3
  204. package/src/rendezvous/MSC4108SignInWithQR.ts +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","names":["checkObjectHasKeys","deepCopy","encodeParams","Method","ConnectionError","MatrixError","TokenRefreshError","HttpApiEvent","anySignal","parseErrorResponse","timeoutSignal","TokenRefresher","TokenRefreshOutcome","FetchHttpApi","constructor","eventEmitter","opts","_opts$useAuthorizatio","_defineProperty","AbortController","onlyData","Error","useAuthorizationHeader","tokenRefresher","abort","abortController","fetch","resource","options","fetchFn","globalThis","setIdBaseUrl","url","idBaseUrl","idServerRequest","method","path","params","prefix","accessToken","queryParams","undefined","body","Get","fullUri","getUrl","json","headers","Authorization","concat","requestOtherUrl","authedRequest","arguments","length","paramOpts","doAuthedRequest","attempt","_arguments","_this","_asyncToGenerator","abortSignal","requestSnapshot","prepareForRequest","access_token","response","request","error","errcode","outcome","handleUnknownToken","Success","Failure","inhibitLogoutEmit","emit","SessionLoggedOut","NoConsent","message","data","consent_uri","baseUrl","_arguments2","_this2","_this2$opts$logger","_opts$localTimeoutMs","_opts$keepAlive","_body$constructor","rawResponseBody","urlForLogs","sanitizeUrlForLogs","logger","debug","Object","assign","jsonResponse","timeout","localTimeoutMs","keepAlive","signals","signal","push","name","JSON","stringify","cleanup","cacheMode","res","start","Date","now","_this2$opts$logger2","mode","redirect","referrer","referrerPolicy","cache","credentials","keepalive","priority","status","e","_this2$opts$logger3","ok","text","blob","asUrl","URL","sanitizedQs","URLSearchParams","key","searchParams","keys","append","sanitizedQsString","toString","sanitizedQsUrlPiece","origin","pathname","_unused","baseUrlWithFallback","baseUrlWithoutTrailingSlash","endsWith","slice","extraParams","mergedParams","_objectSpread"],"sources":["../../src/http-api/fetch.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\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nimport { checkObjectHasKeys, deepCopy, encodeParams } from \"../utils.ts\";\nimport { type TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { Method } from \"./method.ts\";\nimport { ConnectionError, MatrixError, TokenRefreshError } from \"./errors.ts\";\nimport {\n type BaseRequestOpts,\n HttpApiEvent,\n type HttpApiEventHandlerMap,\n type IHttpOpts,\n type IRequestOpts,\n type Body,\n} from \"./interface.ts\";\nimport { anySignal, parseErrorResponse, timeoutSignal } from \"./utils.ts\";\nimport { type QueryDict } from \"../utils.ts\";\nimport { TokenRefresher, TokenRefreshOutcome } from \"./refresh.ts\";\n\nexport class FetchHttpApi<O extends IHttpOpts> {\n private abortController = new AbortController();\n private readonly tokenRefresher: TokenRefresher;\n\n public constructor(\n private eventEmitter: TypedEventEmitter<HttpApiEvent, HttpApiEventHandlerMap>,\n public readonly opts: O,\n ) {\n checkObjectHasKeys(opts, [\"baseUrl\", \"prefix\"]);\n if (!opts.onlyData) {\n throw new Error(\"Constructing FetchHttpApi without `onlyData=true` is no longer supported.\");\n }\n opts.useAuthorizationHeader = opts.useAuthorizationHeader ?? true;\n\n this.tokenRefresher = new TokenRefresher(opts);\n }\n\n public abort(): void {\n this.abortController.abort();\n this.abortController = new AbortController();\n }\n\n public fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.opts.fetchFn) {\n return this.opts.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n /**\n * Sets the base URL for the identity server\n * @param url - The new base url\n */\n public setIdBaseUrl(url?: string): void {\n this.opts.idBaseUrl = url;\n }\n\n public idServerRequest<T extends object = Record<string, unknown>>(\n method: Method,\n path: string,\n params: Record<string, string | string[]> | undefined,\n prefix: string,\n accessToken?: string,\n ): Promise<T> {\n if (!this.opts.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n let queryParams: QueryDict | undefined = undefined;\n let body: Record<string, string | string[]> | undefined = undefined;\n if (method === Method.Get) {\n queryParams = params;\n } else {\n body = params;\n }\n\n const fullUri = this.getUrl(path, queryParams, prefix, this.opts.idBaseUrl);\n\n const opts: IRequestOpts = {\n json: true,\n headers: {},\n };\n if (accessToken) {\n opts.headers!.Authorization = `Bearer ${accessToken}`;\n }\n\n return this.requestOtherUrl(method, fullUri, body, opts);\n }\n\n /**\n * Perform an authorised request to the homeserver.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param paramOpts - additional options.\n * When `paramOpts.doNotAttemptTokenRefresh` is true, token refresh will not be attempted\n * when an expired token is encountered. Used to only attempt token refresh once.\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public authedRequest<T>(\n method: Method,\n path: string,\n queryParams: QueryDict = {},\n body?: Body,\n paramOpts: IRequestOpts = {},\n ): Promise<T> {\n return this.doAuthedRequest<T>(1, method, path, queryParams, body, paramOpts);\n }\n\n // Wrapper around public method authedRequest to allow for tracking retry attempt counts\n private async doAuthedRequest<T>(\n attempt: number,\n method: Method,\n path: string,\n queryParams: QueryDict,\n body?: Body,\n paramOpts: IRequestOpts = {},\n ): Promise<T> {\n // avoid mutating paramOpts so they can be used on retry\n const opts = deepCopy(paramOpts);\n // we have to manually copy the abortSignal over as it is not a plain object\n opts.abortSignal = paramOpts.abortSignal;\n\n // Take a snapshot of the current token state before we start the request so we can reference it if we error\n const requestSnapshot = await this.tokenRefresher.prepareForRequest();\n if (requestSnapshot.accessToken) {\n if (this.opts.useAuthorizationHeader) {\n if (!opts.headers) {\n opts.headers = {};\n }\n if (!opts.headers.Authorization) {\n opts.headers.Authorization = `Bearer ${requestSnapshot.accessToken}`;\n }\n if (queryParams.access_token) {\n delete queryParams.access_token;\n }\n } else if (!queryParams.access_token) {\n queryParams.access_token = requestSnapshot.accessToken;\n }\n }\n\n try {\n const response = await this.request<T>(method, path, queryParams, body, opts);\n return response;\n } catch (error) {\n if (!(error instanceof MatrixError)) {\n throw error;\n }\n\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n const outcome = await this.tokenRefresher.handleUnknownToken(requestSnapshot, attempt);\n if (outcome === TokenRefreshOutcome.Success) {\n // if we got a new token retry the request\n return this.doAuthedRequest(attempt + 1, method, path, queryParams, body, paramOpts);\n }\n if (outcome === TokenRefreshOutcome.Failure) {\n throw new TokenRefreshError(error);\n }\n\n if (!opts?.inhibitLogoutEmit) {\n this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, error);\n }\n } else if (error.errcode == \"M_CONSENT_NOT_GIVEN\") {\n this.eventEmitter.emit(HttpApiEvent.NoConsent, error.message, error.data.consent_uri);\n }\n\n throw error;\n }\n }\n\n /**\n * Perform a request to the homeserver without any credentials.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public request<T>(\n method: Method,\n path: string,\n queryParams?: QueryDict,\n body?: Body,\n opts?: IRequestOpts,\n ): Promise<T> {\n const fullUri = this.getUrl(path, queryParams, opts?.prefix, opts?.baseUrl);\n return this.requestOtherUrl<T>(method, fullUri, body, opts);\n }\n\n /**\n * Perform a request to an arbitrary URL.\n * @param method - The HTTP method e.g. \"GET\".\n * @param url - The HTTP URL object.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public async requestOtherUrl<T>(\n method: Method,\n url: URL | string,\n body?: Body,\n opts: BaseRequestOpts = {},\n ): Promise<T> {\n if (opts.json !== undefined && opts.rawResponseBody !== undefined) {\n throw new Error(\"Invalid call to `FetchHttpApi` sets both `opts.json` and `opts.rawResponseBody`\");\n }\n\n const urlForLogs = this.sanitizeUrlForLogs(url);\n\n this.opts.logger?.debug(`FetchHttpApi: --> ${method} ${urlForLogs}`);\n\n const headers = Object.assign({}, opts.headers || {});\n\n const jsonResponse = !opts.rawResponseBody && opts.json !== false;\n if (jsonResponse) {\n if (!headers[\"Accept\"]) {\n headers[\"Accept\"] = \"application/json\";\n }\n }\n\n const timeout = opts.localTimeoutMs ?? this.opts.localTimeoutMs;\n const keepAlive = opts.keepAlive ?? false;\n const signals = [this.abortController.signal];\n if (timeout !== undefined) {\n signals.push(timeoutSignal(timeout));\n }\n if (opts.abortSignal) {\n signals.push(opts.abortSignal);\n }\n\n // If the body is an object, encode it as JSON and set the `Content-Type` header,\n // unless that has been explicitly inhibited by setting `opts.json: false`.\n // We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref\n let data: BodyInit;\n if (opts.json !== false && body?.constructor?.name === Object.name) {\n data = JSON.stringify(body);\n if (!headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n } else {\n data = body as BodyInit;\n }\n\n const { signal, cleanup } = anySignal(signals);\n\n // Set cache mode based on presence of Authorization header.\n // Browsers/proxies do not cache responses to requests with Authorization headers.\n // So specifying \"no-cache\" is redundant, and actually prevents caching\n // of preflight requests in CORS scenarios. As such, we only set \"no-cache\"\n // when there is no Authorization header.\n const cacheMode = \"Authorization\" in headers ? undefined : \"no-cache\";\n\n let res: Response;\n const start = Date.now();\n try {\n res = await this.fetch(url, {\n signal,\n method,\n body: data,\n headers,\n mode: \"cors\",\n redirect: \"follow\",\n referrer: \"\",\n referrerPolicy: \"no-referrer\",\n cache: cacheMode,\n credentials: \"omit\", // we send credentials via headers\n keepalive: keepAlive,\n priority: opts.priority,\n });\n\n this.opts.logger?.debug(\n `FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${res.status}]`,\n );\n } catch (e) {\n this.opts.logger?.debug(`FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${e}]`);\n if ((<Error>e).name === \"AbortError\") {\n throw e;\n }\n throw new ConnectionError(\"fetch failed\", <Error>e);\n } finally {\n cleanup();\n }\n\n if (!res.ok) {\n throw parseErrorResponse(res, await res.text());\n }\n\n if (opts.rawResponseBody) {\n return (await res.blob()) as T;\n } else if (jsonResponse) {\n return await res.json();\n } else {\n return (await res.text()) as T;\n }\n }\n\n private sanitizeUrlForLogs(url: URL | string): string {\n try {\n let asUrl: URL;\n if (typeof url === \"string\") {\n asUrl = new URL(url);\n } else {\n asUrl = url;\n }\n // Remove the values of any URL params that could contain potential secrets\n const sanitizedQs = new URLSearchParams();\n for (const key of asUrl.searchParams.keys()) {\n sanitizedQs.append(key, \"xxx\");\n }\n const sanitizedQsString = sanitizedQs.toString();\n const sanitizedQsUrlPiece = sanitizedQsString ? `?${sanitizedQsString}` : \"\";\n\n return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;\n } catch {\n // defensive coding for malformed url\n return \"??\";\n }\n }\n /**\n * Form and return a homeserver request URL based on the given path params and prefix.\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g. \"/createRoom\".\n * @param queryParams - A dict of query params (these will NOT be urlencoded).\n * @param prefix - The full prefix to use e.g. \"/_matrix/client/v2_alpha\", defaulting to this.opts.prefix.\n * @param baseUrl - The baseUrl to use e.g. \"https://matrix.org\", defaulting to this.opts.baseUrl.\n * @returns URL\n */\n public getUrl(path: string, queryParams?: QueryDict, prefix?: string, baseUrl?: string): URL {\n const baseUrlWithFallback = baseUrl ?? this.opts.baseUrl;\n const baseUrlWithoutTrailingSlash = baseUrlWithFallback.endsWith(\"/\")\n ? baseUrlWithFallback.slice(0, -1)\n : baseUrlWithFallback;\n const url = new URL(baseUrlWithoutTrailingSlash + (prefix ?? this.opts.prefix) + path);\n // If there are any params, encode and append them to the URL.\n if (this.opts.extraParams || queryParams) {\n const mergedParams = { ...this.opts.extraParams, ...queryParams };\n encodeParams(mergedParams, url.searchParams);\n }\n\n return url;\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,SAASA,kBAAkB,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,aAAa;AAExE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,eAAe,EAAEC,WAAW,EAAEC,iBAAiB,QAAQ,aAAa;AAC7E,SAEIC,YAAY,QAKT,gBAAgB;AACvB,SAASC,SAAS,EAAEC,kBAAkB,EAAEC,aAAa,QAAQ,YAAY;AAEzE,SAASC,cAAc,EAAEC,m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I,IAAI,CAAC/D,IAAI,CAAC+D,OAAO;IACxD,IAAM4D,2BAA2B,GAAGD,mBAAmB,CAACE,QAAQ,CAAC,GAAG,CAAC,GAC/DF,mBAAmB,CAACG,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAChCH,mBAAmB;IACzB,IAAM1G,GAAG,GAAG,IAAI6F,GAAG,CAACc,2BAA2B,IAAIrG,MAAM,aAANA,MAAM,cAANA,MAAM,GAAI,IAAI,CAACtB,IAAI,CAACsB,MAAM,CAAC,GAAGF,IAAI,CAAC;IACtF;IACA,IAAI,IAAI,CAACpB,IAAI,CAAC8H,WAAW,IAAItG,WAAW,EAAE;MACtC,IAAMuG,YAAY,GAAAC,aAAA,CAAAA,aAAA,KAAQ,IAAI,CAAChI,IAAI,CAAC8H,WAAW,GAAKtG,WAAW,CAAE;MACjEtC,YAAY,CAAC6I,YAAY,EAAE/G,GAAG,CAACiG,YAAY,CAAC;IAChD;IAEA,OAAOjG,GAAG;EACd;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"fetch.js","names":["checkObjectHasKeys","deepCopy","encodeParams","Method","ConnectionError","MatrixError","TokenRefreshError","HttpApiEvent","anySignal","parseErrorResponse","timeoutSignal","TokenRefresher","TokenRefreshOutcome","FetchHttpApi","constructor","eventEmitter","opts","_opts$useAuthorizatio","_defineProperty","AbortController","onlyData","Error","useAuthorizationHeader","tokenRefresher","abort","abortController","fetch","resource","options","fetchFn","globalThis","setIdBaseUrl","url","idBaseUrl","idServerRequest","method","path","params","prefix","accessToken","queryParams","undefined","body","Get","fullUri","getUrl","json","headers","Authorization","concat","requestOtherUrl","authedRequest","arguments","length","paramOpts","doAuthedRequest","attempt","_arguments","_this","_asyncToGenerator","abortSignal","requestSnapshot","prepareForRequest","access_token","response","request","error","errcode","outcome","handleUnknownToken","Success","Failure","inhibitLogoutEmit","emit","SessionLoggedOut","NoConsent","message","data","consent_uri","baseUrl","_arguments2","_this2","_this2$opts$logger","_opts$localTimeoutMs","_opts$keepAlive","_body$constructor","rawResponseBody","urlForLogs","sanitizeUrlForLogs","logger","debug","Object","assign","jsonResponse","timeout","localTimeoutMs","keepAlive","signals","signal","push","name","JSON","stringify","_anySignal","cleanup","cacheMode","res","start","Date","now","_this2$opts$logger2","mode","redirect","referrer","referrerPolicy","cache","credentials","keepalive","priority","status","e","_this2$opts$logger3","ok","text","blob","asUrl","URL","sanitizedQs","URLSearchParams","key","searchParams","keys","append","sanitizedQsString","toString","sanitizedQsUrlPiece","origin","pathname","_unused","baseUrlWithFallback","baseUrlWithoutTrailingSlash","endsWith","slice","extraParams","mergedParams","_objectSpread"],"sources":["../../src/http-api/fetch.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\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nimport { checkObjectHasKeys, deepCopy, encodeParams } from \"../utils.ts\";\nimport { type TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\nimport { Method } from \"./method.ts\";\nimport { ConnectionError, MatrixError, TokenRefreshError } from \"./errors.ts\";\nimport {\n type BaseRequestOpts,\n HttpApiEvent,\n type HttpApiEventHandlerMap,\n type IHttpOpts,\n type IRequestOpts,\n type Body,\n} from \"./interface.ts\";\nimport { anySignal, parseErrorResponse, timeoutSignal } from \"./utils.ts\";\nimport { type QueryDict } from \"../utils.ts\";\nimport { TokenRefresher, TokenRefreshOutcome } from \"./refresh.ts\";\n\nexport class FetchHttpApi<O extends IHttpOpts> {\n private abortController = new AbortController();\n private readonly tokenRefresher: TokenRefresher;\n\n public constructor(\n private eventEmitter: TypedEventEmitter<HttpApiEvent, HttpApiEventHandlerMap>,\n public readonly opts: O,\n ) {\n checkObjectHasKeys(opts, [\"baseUrl\", \"prefix\"]);\n if (!opts.onlyData) {\n throw new Error(\"Constructing FetchHttpApi without `onlyData=true` is no longer supported.\");\n }\n opts.useAuthorizationHeader = opts.useAuthorizationHeader ?? true;\n\n this.tokenRefresher = new TokenRefresher(opts);\n }\n\n public abort(): void {\n this.abortController.abort();\n this.abortController = new AbortController();\n }\n\n public fetch(resource: URL | string, options?: RequestInit): ReturnType<typeof globalThis.fetch> {\n if (this.opts.fetchFn) {\n return this.opts.fetchFn(resource, options);\n }\n return globalThis.fetch(resource, options);\n }\n\n /**\n * Sets the base URL for the identity server\n * @param url - The new base url\n */\n public setIdBaseUrl(url?: string): void {\n this.opts.idBaseUrl = url;\n }\n\n public idServerRequest<T extends object = Record<string, unknown>>(\n method: Method,\n path: string,\n params: Record<string, string | string[]> | undefined,\n prefix: string,\n accessToken?: string,\n ): Promise<T> {\n if (!this.opts.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n let queryParams: QueryDict | undefined = undefined;\n let body: Record<string, string | string[]> | undefined = undefined;\n if (method === Method.Get) {\n queryParams = params;\n } else {\n body = params;\n }\n\n const fullUri = this.getUrl(path, queryParams, prefix, this.opts.idBaseUrl);\n\n const opts: IRequestOpts = {\n json: true,\n headers: {},\n };\n if (accessToken) {\n opts.headers!.Authorization = `Bearer ${accessToken}`;\n }\n\n return this.requestOtherUrl(method, fullUri, body, opts);\n }\n\n /**\n * Perform an authorised request to the homeserver.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param paramOpts - additional options.\n * When `paramOpts.doNotAttemptTokenRefresh` is true, token refresh will not be attempted\n * when an expired token is encountered. Used to only attempt token refresh once.\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public authedRequest<T>(\n method: Method,\n path: string,\n queryParams: QueryDict = {},\n body?: Body,\n paramOpts: IRequestOpts = {},\n ): Promise<T> {\n return this.doAuthedRequest<T>(1, method, path, queryParams, body, paramOpts);\n }\n\n // Wrapper around public method authedRequest to allow for tracking retry attempt counts\n private async doAuthedRequest<T>(\n attempt: number,\n method: Method,\n path: string,\n queryParams: QueryDict,\n body?: Body,\n paramOpts: IRequestOpts = {},\n ): Promise<T> {\n // avoid mutating paramOpts so they can be used on retry\n const opts = deepCopy(paramOpts);\n // we have to manually copy the abortSignal over as it is not a plain object\n opts.abortSignal = paramOpts.abortSignal;\n\n // Take a snapshot of the current token state before we start the request so we can reference it if we error\n const requestSnapshot = await this.tokenRefresher.prepareForRequest();\n if (requestSnapshot.accessToken) {\n if (this.opts.useAuthorizationHeader) {\n if (!opts.headers) {\n opts.headers = {};\n }\n if (!opts.headers.Authorization) {\n opts.headers.Authorization = `Bearer ${requestSnapshot.accessToken}`;\n }\n if (queryParams.access_token) {\n delete queryParams.access_token;\n }\n } else if (!queryParams.access_token) {\n queryParams.access_token = requestSnapshot.accessToken;\n }\n }\n\n try {\n const response = await this.request<T>(method, path, queryParams, body, opts);\n return response;\n } catch (error) {\n if (!(error instanceof MatrixError)) {\n throw error;\n }\n\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n const outcome = await this.tokenRefresher.handleUnknownToken(requestSnapshot, attempt);\n if (outcome === TokenRefreshOutcome.Success) {\n // if we got a new token retry the request\n return this.doAuthedRequest(attempt + 1, method, path, queryParams, body, paramOpts);\n }\n if (outcome === TokenRefreshOutcome.Failure) {\n throw new TokenRefreshError(error);\n }\n\n if (!opts?.inhibitLogoutEmit) {\n this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, error);\n }\n } else if (error.errcode == \"M_CONSENT_NOT_GIVEN\") {\n this.eventEmitter.emit(HttpApiEvent.NoConsent, error.message, error.data.consent_uri);\n }\n\n throw error;\n }\n }\n\n /**\n * Perform a request to the homeserver without any credentials.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public request<T>(\n method: Method,\n path: string,\n queryParams?: QueryDict,\n body?: Body,\n opts?: IRequestOpts,\n ): Promise<T> {\n const fullUri = this.getUrl(path, queryParams, opts?.prefix, opts?.baseUrl);\n return this.requestOtherUrl<T>(method, fullUri, body, opts);\n }\n\n /**\n * Perform a request to an arbitrary URL.\n * @param method - The HTTP method e.g. \"GET\".\n * @param url - The HTTP URL object.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns The parsed response.\n * @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.\n */\n public async requestOtherUrl<T>(\n method: Method,\n url: URL | string,\n body?: Body,\n opts: BaseRequestOpts = {},\n ): Promise<T> {\n if (opts.json !== undefined && opts.rawResponseBody !== undefined) {\n throw new Error(\"Invalid call to `FetchHttpApi` sets both `opts.json` and `opts.rawResponseBody`\");\n }\n\n const urlForLogs = this.sanitizeUrlForLogs(url);\n\n this.opts.logger?.debug(`FetchHttpApi: --> ${method} ${urlForLogs}`);\n\n const headers = Object.assign({}, opts.headers || {});\n\n const jsonResponse = !opts.rawResponseBody && opts.json !== false;\n if (jsonResponse) {\n if (!headers[\"Accept\"]) {\n headers[\"Accept\"] = \"application/json\";\n }\n }\n\n const timeout = opts.localTimeoutMs ?? this.opts.localTimeoutMs;\n const keepAlive = opts.keepAlive ?? false;\n const signals = [this.abortController.signal];\n if (timeout !== undefined) {\n signals.push(timeoutSignal(timeout));\n }\n if (opts.abortSignal) {\n signals.push(opts.abortSignal);\n }\n\n // If the body is an object, encode it as JSON and set the `Content-Type` header,\n // unless that has been explicitly inhibited by setting `opts.json: false`.\n // We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref\n let data: BodyInit;\n if (opts.json !== false && body?.constructor?.name === Object.name) {\n data = JSON.stringify(body);\n if (!headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n } else {\n data = body as BodyInit;\n }\n\n const { signal, cleanup } = anySignal(signals);\n\n // Set cache mode based on presence of Authorization header.\n // Browsers/proxies do not cache responses to requests with Authorization headers.\n // So specifying \"no-cache\" is redundant, and actually prevents caching\n // of preflight requests in CORS scenarios. As such, we only set \"no-cache\"\n // when there is no Authorization header.\n const cacheMode = \"Authorization\" in headers ? undefined : \"no-cache\";\n\n let res: Response;\n const start = Date.now();\n try {\n res = await this.fetch(url, {\n signal,\n method,\n body: data,\n headers,\n mode: \"cors\",\n redirect: \"follow\",\n referrer: \"\",\n referrerPolicy: \"no-referrer\",\n cache: cacheMode,\n credentials: \"omit\", // we send credentials via headers\n keepalive: keepAlive,\n priority: opts.priority,\n });\n\n this.opts.logger?.debug(\n `FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${res.status}]`,\n );\n } catch (e) {\n this.opts.logger?.debug(`FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${e}]`);\n if ((<Error>e).name === \"AbortError\") {\n throw e;\n }\n throw new ConnectionError(\"fetch failed\", <Error>e);\n } finally {\n cleanup();\n }\n\n if (!res.ok) {\n throw parseErrorResponse(res, await res.text());\n }\n\n if (opts.rawResponseBody) {\n return (await res.blob()) as T;\n } else if (jsonResponse) {\n return await res.json();\n } else {\n return (await res.text()) as T;\n }\n }\n\n private sanitizeUrlForLogs(url: URL | string): string {\n try {\n let asUrl: URL;\n if (typeof url === \"string\") {\n asUrl = new URL(url);\n } else {\n asUrl = url;\n }\n // Remove the values of any URL params that could contain potential secrets\n const sanitizedQs = new URLSearchParams();\n for (const key of asUrl.searchParams.keys()) {\n sanitizedQs.append(key, \"xxx\");\n }\n const sanitizedQsString = sanitizedQs.toString();\n const sanitizedQsUrlPiece = sanitizedQsString ? `?${sanitizedQsString}` : \"\";\n\n return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;\n } catch {\n // defensive coding for malformed url\n return \"??\";\n }\n }\n /**\n * Form and return a homeserver request URL based on the given path params and prefix.\n * @param path - The HTTP path <b>after</b> the supplied prefix e.g. \"/createRoom\".\n * @param queryParams - A dict of query params (these will NOT be urlencoded).\n * @param prefix - The full prefix to use e.g. \"/_matrix/client/v2_alpha\", defaulting to this.opts.prefix.\n * @param baseUrl - The baseUrl to use e.g. \"https://matrix.org\", defaulting to this.opts.baseUrl.\n * @returns URL\n */\n public getUrl(path: string, queryParams?: QueryDict, prefix?: string, baseUrl?: string): URL {\n const baseUrlWithFallback = baseUrl ?? this.opts.baseUrl;\n const baseUrlWithoutTrailingSlash = baseUrlWithFallback.endsWith(\"/\")\n ? baseUrlWithFallback.slice(0, -1)\n : baseUrlWithFallback;\n const url = new URL(baseUrlWithoutTrailingSlash + (prefix ?? this.opts.prefix) + path);\n // If there are any params, encode and append them to the URL.\n if (this.opts.extraParams || queryParams) {\n const mergedParams = { ...this.opts.extraParams, ...queryParams };\n encodeParams(mergedParams, url.searchParams);\n }\n\n return url;\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,SAASA,kBAAkB,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,aAAa;AAExE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,eAAe,EAAEC,WAAW,EAAEC,iBAAiB,QAAQ,aAAa;AAC7E,SAEIC,YAAY,QAKT,gBAAgB;AACvB,SAASC,SAAS,EAAEC,kBAAkB,EAAEC,aAAa,QAAQ,YAAY;AAEzE,SAASC,cAAc,EAA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mB,GAAG5D,OAAO,aAAPA,OAAO,cAAPA,OAAO,GAAI,IAAI,CAAC/D,IAAI,CAAC+D,OAAO;IACxD,IAAM6D,2BAA2B,GAAGD,mBAAmB,CAACE,QAAQ,CAAC,GAAG,CAAC,GAC/DF,mBAAmB,CAACG,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAChCH,mBAAmB;IACzB,IAAM3G,GAAG,GAAG,IAAI8F,GAAG,CAACc,2BAA2B,IAAItG,MAAM,aAANA,MAAM,cAANA,MAAM,GAAI,IAAI,CAACtB,IAAI,CAACsB,MAAM,CAAC,GAAGF,IAAI,CAAC;IACtF;IACA,IAAI,IAAI,CAACpB,IAAI,CAAC+H,WAAW,IAAIvG,WAAW,EAAE;MACtC,IAAMwG,YAAY,GAAAC,aAAA,CAAAA,aAAA,KAAQ,IAAI,CAACjI,IAAI,CAAC+H,WAAW,GAAKvG,WAAW,CAAE;MACjEtC,YAAY,CAAC8I,YAAY,EAAEhH,GAAG,CAACkG,YAAY,CAAC;IAChD;IAEA,OAAOlG,GAAG;EACd;AACJ","ignoreList":[]}
@@ -1,5 +1,4 @@
1
1
  import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
2
- import _defineProperty from "@babel/runtime/helpers/defineProperty";
3
2
  /*
4
3
  Copyright 2025 The Matrix.org Foundation C.I.C.
5
4
 
@@ -41,13 +40,13 @@ var REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1000;
41
40
  export class TokenRefresher {
42
41
  constructor(opts) {
43
42
  this.opts = opts;
44
- /**
45
- * Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.
46
- * @private
47
- */
48
- _defineProperty(this, "tokenRefreshPromise", void 0);
49
- _defineProperty(this, "latestTokenRefreshExpiry", void 0);
50
43
  }
44
+
45
+ /**
46
+ * Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.
47
+ * @private
48
+ */
49
+
51
50
  /**
52
51
  * This function is called before every request to ensure that the access token is valid.
53
52
  * @returns a snapshot containing the access token and other properties which must be passed to the handleUnknownToken
@@ -145,11 +144,10 @@ export class TokenRefresher {
145
144
  try {
146
145
  var _this5$opts$logger2, _this5$opts$logger3;
147
146
  (_this5$opts$logger2 = _this5.opts.logger) === null || _this5$opts$logger2 === void 0 || _this5$opts$logger2.debug("Attempting to refresh token");
148
- var {
149
- accessToken,
150
- refreshToken,
151
- expiry
152
- } = yield _this5.opts.tokenRefreshFunction(_this5.opts.refreshToken);
147
+ var _yield$_this5$opts$to = yield _this5.opts.tokenRefreshFunction(_this5.opts.refreshToken),
148
+ accessToken = _yield$_this5$opts$to.accessToken,
149
+ refreshToken = _yield$_this5$opts$to.refreshToken,
150
+ expiry = _yield$_this5$opts$to.expiry;
153
151
  _this5.opts.accessToken = accessToken;
154
152
  _this5.opts.refreshToken = refreshToken;
155
153
  _this5.latestTokenRefreshExpiry = expiry;
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.js","names":["MatrixError","TokenRefreshLogoutError","sleep","TokenRefreshOutcome","REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS","REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS","TokenRefresher","constructor","opts","_defineProperty","prepareForRequest","_this","_asyncToGenerator","refreshIfNeeded","accessToken","refreshToken","expiry","latestTokenRefreshExpiry","_this2","tokenRefreshPromise","expiresIn","getTime","Date","now","_handleUnknownToken","handleUnknownToken","snapshot","attempt","_this3","_this4","Logout","_this4$tokenRefreshPr","doTokenRefresh","undefined","Success","_this5","tokenRefreshFunction","_this5$opts$logger","logger","error","Math","min","_this5$opts$logger2","_this5$opts$logger3","debug","_this5$opts$logger5","_this5$opts$logger4","warn","Failure"],"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,SAASA,WAAW,EAAEC,uBAAuB,QAAQ,aAAa;AAElE,SAASC,KAAK,QAAQ,aAAa;;AAEnC;AACA;AACA;;AAEA,WAAkBC,mBAAmB,0BAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAA,OAAnBA,mBAAmB;AAAA;AAYrC;AACA,IAAMC,kCAAkC,GAAG,GAAG;AAC9C;AACA;AACA,IAAMC,2CAA2C,GAAG,EAAE,GAAG,IAAI;AAI7D;AACA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C,mBAAmB,CAAC6C,OAAO;MACtC;IAAC;EACL;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"refresh.js","names":["MatrixError","TokenRefreshLogoutError","sleep","TokenRefreshOutcome","REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS","REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS","TokenRefresher","constructor","opts","prepareForRequest","_this","_asyncToGenerator","refreshIfNeeded","accessToken","refreshToken","expiry","latestTokenRefreshExpiry","_this2","tokenRefreshPromise","expiresIn","getTime","Date","now","_handleUnknownToken","handleUnknownToken","snapshot","attempt","_this3","_this4","Logout","_this4$tokenRefreshPr","doTokenRefresh","undefined","Success","_this5","tokenRefreshFunction","_this5$opts$logger","logger","error","Math","min","_this5$opts$logger2","_this5$opts$logger3","debug","_yield$_this5$opts$to","_this5$opts$logger5","_this5$opts$logger4","warn","Failure"],"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,SAASA,WAAW,EAAEC,uBAAuB,QAAQ,aAAa;AAElE,SAASC,KAAK,QAAQ,aAAa;;AAEnC;AACA;AACA;;AAEA,WAAkBC,mBAAmB,0BAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAA,OAAnBA,mBAAmB;AAAA;AAYrC;AACA,IAAMC,kCAAkC,GAAG,GAAG;AAC9C;AACA;AACA,IAAMC,2CAA2C,GAAG,EAAE,GAAG,IAAI;AAI7D;AACA;AACA;AACA;AACA,OAAO,MAAMC,cAAc,CAAC;EACjBC,WAAWA,CAAkBC,IAAU,EAAE;IAAA,KAAZA,IAAU,GAAVA,IAAU;EAAG;;EAEjD;AACJ;AACA;AACA;;EAKI;AACJ;AACA;AACA;AACA;EACiBC,iBAAiBA,CAAA,EAAsB;IAAA,IAAAC,KAAA;IAAA,OAAAC,iBAAA;MAChD;MACA,MAAMD,KAAI,CAACE,eAAe,CAAC,CAAC;MAE5B,OAAO;QACHC,WAAW,EAAEH,KAAI,CAACF,IAAI,CAACK,WAAY;QACnCC,YAAY,EAAEJ,KAAI,CAACF,IAAI,CAACM,YAAY;QACpCC,MAAM,EAAEL,KAAI,CAACM;MACjB,CAAC;IAAC;EACN;EAEcJ,eAAeA,CAAA,EAAqB;IAAA,IAAAK,MAAA;IA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W,GAAGA,WAAW;QACnCqB,MAAI,CAAC1B,IAAI,CAACM,YAAY,GAAGA,YAAY;QACrCoB,MAAI,CAAClB,wBAAwB,GAAGD,MAAM;QACtC,CAAA2B,mBAAA,GAAAR,MAAI,CAAC1B,IAAI,CAAC6B,MAAM,cAAAK,mBAAA,eAAhBA,mBAAA,CAAkBC,KAAK,CAAC,+CAA+C,EAAE5B,MAAM,CAAC;;QAEhF;QACA,OAAOZ,mBAAmB,CAAC8B,OAAO;MACtC,CAAC,CAAC,OAAOK,KAAK,EAAE;QAAA,IAAAO,mBAAA;QACZ;QACA,IAAIP,KAAK,YAAYrC,uBAAuB,IAAIqC,KAAK,YAAYtC,WAAW,EAAE;UAAA,IAAA8C,mBAAA;UAC1E,CAAAA,mBAAA,GAAAZ,MAAI,CAAC1B,IAAI,CAAC6B,MAAM,cAAAS,mBAAA,eAAhBA,mBAAA,CAAkBR,KAAK,CAAC,yBAAyB,EAAEA,KAAK,CAAC;UACzD,OAAOnC,mBAAmB,CAAC0B,MAAM;QACrC;QAEA,CAAAgB,mBAAA,GAAAX,MAAI,CAAC1B,IAAI,CAAC6B,MAAM,cAAAQ,mBAAA,eAAhBA,mBAAA,CAAkBE,IAAI,CAAC,yBAAyB,EAAET,KAAK,CAAC;QACxD,OAAOnC,mBAAmB,CAAC6C,OAAO;MACtC;IAAC;EACL;AACJ","ignoreList":[]}
@@ -74,9 +74,9 @@ export class NoAuthFlowFoundError extends Error {
74
74
  // eslint-disable-next-line @typescript-eslint/naming-convention, camelcase
75
75
  required_stages, flows) {
76
76
  super(m);
77
+ _defineProperty(this, "name", "NoAuthFlowFoundError");
77
78
  this.required_stages = required_stages;
78
79
  this.flows = flows;
79
- _defineProperty(this, "name", "NoAuthFlowFoundError");
80
80
  }
81
81
  }
82
82
 
@@ -108,17 +108,7 @@ export class NoAuthFlowFoundError extends Error {
108
108
  export class InteractiveAuth {
109
109
  constructor(opts) {
110
110
  var _this = this;
111
- _defineProperty(this, "matrixClient", void 0);
112
- _defineProperty(this, "inputs", void 0);
113
- _defineProperty(this, "clientSecret", void 0);
114
- _defineProperty(this, "requestCallback", void 0);
115
- _defineProperty(this, "busyChangedCallback", void 0);
116
- _defineProperty(this, "stateUpdatedCallback", void 0);
117
- _defineProperty(this, "requestEmailTokenCallback", void 0);
118
- _defineProperty(this, "supportedStages", void 0);
119
111
  // The current latest data or error received from the server during the user interactive auth flow.
120
- _defineProperty(this, "data", void 0);
121
- _defineProperty(this, "emailSid", void 0);
122
112
  _defineProperty(this, "requestingEmailToken", false);
123
113
  _defineProperty(this, "attemptAuthDeferred", null);
124
114
  _defineProperty(this, "chosenFlow", null);
@@ -1 +1 @@
1
- {"version":3,"file":"interactive-auth.js","names":["logger","MatrixError","EMAIL_STAGE_TYPE","MSISDN_STAGE_TYPE","AuthType","NoAuthFlowFoundError","Error","constructor","m","required_stages","flows","_defineProperty","InteractiveAuth","opts","_this","_asyncToGenerator","requestingEmailToken","trace","emailAttempt","requestTokenResult","requestEmailTokenCallback","inputs","emailAddress","clientSecret","data","session","emailSid","sid","warn","matrixClient","authData","requestCallback","doRequest","busyChangedCallback","busyChanged","stateUpdatedCallback","stateUpdated","startAuthStage","requestEmailToken","sessionId","generateClientSecret","supportedStages","undefined","Set","attemptAuth","_this2","_this2$data","attemptAuthDeferred","Promise","withResolvers","promise","length","_this2$busyChangedCal","call","auth","finally","_this2$busyChangedCal2","startNextAuthStage","poll","_this3","submitPromise","authDict","currentStage","creds","client_secret","isUrl","getIdentityServerUrl","id_server","URL","host","type","threepid_creds","submitAuthDict","getSessionId","_this$data","getClientSecret","getStageParams","loginType","_this$data2","params","getChosenFlow","chosenFlow","_arguments","arguments","_this4","_this4$data","background","_this4$busyChangedCal","_unused","Object","assign","_this4$busyChangedCal2","getEmailSid","setEmailSid","_arguments2","_this5","result","resolve","error","_matrixError$data$flo","_matrixError$data","_this5$data","_this5$chosenFlow","matrixError","errorFlows","haveFlows","Boolean","httpStatus","_this5$attemptAuthDef","reject","log","completed","e","stages","includes","Email","_this$data3","_this$data4","nextStage","chooseStage","Dummy","errcode","_this$data5","_this$data6","chooseFlow","JSON","stringify","firstUncompletedStage","scoreFlow","flow","score","filter","stage","has","_this$data7","haveEmail","haveMsisdn","phoneCountry","phoneNumber","sort","a","b","flowHasEmail","flowHasMsisdn","requiredStages","push","_this$data8","find","stageType"],"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(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(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(email: string, secret: string, attempt: number, session: string): 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?(busy: boolean): void;\n startAuthStage?(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,SAASA,MAAM,QAAQ,aAAa;AAEpC,SAASC,WAAW,QAAQ,qBAAqB;AAGjD,IAAMC,gBAAgB,GAAG,wBAAwB;AACjD,IAAMC,iBAAiB,GAAG,gBAAgB;;AAsB1C;AACA;AACA;AACA;AACA;;AAuBA,WAAYC,QAAQ,0BAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAUhB;EACA;EACA;EAZQA,QAAQ;EAchB;AACJ;AACA;AACA;EAjBYA,QAAQ;EAAA,OAARA,QA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,IAAIsI,UAAU,EAAEQ,cAAc,CAACC,IAAI,CAAC9I,iBAAiB,CAAC;IACtD;IACA;IACA,MAAM,IAAIE,oBAAoB,CAAC,0CAA0C,EAAE2I,cAAc,EAAEtI,KAAK,CAAC;EACrG;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACYqH,qBAAqBA,CAACE,IAAa,EAAiC;IAAA,IAAAiB,WAAA;IACxE,IAAMnC,SAAS,GAAG,EAAAmC,WAAA,GAAC,IAAI,CAAC1H,IAAI,cAAA0H,WAAA,uBAAVA,WAAA,CAA0BnC,SAAS,KAAI,EAAE;IAC3D,OAAOkB,IAAI,CAAChB,MAAM,CAACkC,IAAI,CAAEC,SAAS,IAAK,CAACrC,SAAS,CAACG,QAAQ,CAACkC,SAAS,CAAC,CAAC;EAC1E;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"interactive-auth.js","names":["logger","MatrixError","EMAIL_STAGE_TYPE","MSISDN_STAGE_TYPE","AuthType","NoAuthFlowFoundError","Error","constructor","m","required_stages","flows","_defineProperty","InteractiveAuth","opts","_this","_asyncToGenerator","requestingEmailToken","trace","emailAttempt","requestTokenResult","requestEmailTokenCallback","inputs","emailAddress","clientSecret","data","session","emailSid","sid","warn","matrixClient","authData","requestCallback","doRequest","busyChangedCallback","busyChanged","stateUpdatedCallback","stateUpdated","startAuthStage","requestEmailToken","sessionId","generateClientSecret","supportedStages","undefined","Set","attemptAuth","_this2","_this2$data","attemptAuthDeferred","Promise","withResolvers","promise","length","_this2$busyChangedCal","call","auth","finally","_this2$busyChangedCal2","startNextAuthStage","poll","_this3","submitPromise","authDict","currentStage","creds","client_secret","isUrl","getIdentityServerUrl","id_server","URL","host","type","threepid_creds","submitAuthDict","getSessionId","_this$data","getClientSecret","getStageParams","loginType","_this$data2","params","getChosenFlow","chosenFlow","_arguments","arguments","_this4","_this4$data","background","_this4$busyChangedCal","_unused","Object","assign","_this4$busyChangedCal2","getEmailSid","setEmailSid","_arguments2","_this5","result","resolve","error","_matrixError$data$flo","_matrixError$data","_this5$data","_this5$chosenFlow","matrixError","errorFlows","haveFlows","Boolean","httpStatus","_this5$attemptAuthDef","reject","log","completed","e","stages","includes","Email","_this$data3","_this$data4","nextStage","chooseStage","Dummy","errcode","_this$data5","_this$data6","chooseFlow","JSON","stringify","firstUncompletedStage","scoreFlow","flow","score","filter","stage","has","_this$data7","haveEmail","haveMsisdn","phoneCountry","phoneNumber","sort","a","b","flowHasEmail","flowHasMsisdn","requiredStages","push","_this$data8","find","stageType"],"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(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(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(email: string, secret: string, attempt: number, session: string): 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?(busy: boolean): void;\n startAuthStage?(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,SAASA,MAAM,QAAQ,aAAa;AAEpC,SAASC,WAAW,QAAQ,qBAAqB;AAGjD,IAAMC,gBAAgB,GAAG,wBAAwB;AACjD,IAAMC,iBAAiB,GAAG,gBAAgB;;AAsB1C;AACA;AACA;AACA;AACA;;AAuBA,WAAYC,QAAQ,0BAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAAQ;EAARA,QAA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C,IAAI,CAAC9I,iBAAiB,CAAC;IACtD;IACA;IACA,MAAM,IAAIE,oBAAoB,CAAC,0CAA0C,EAAE2I,cAAc,EAAEtI,KAAK,CAAC;EACrG;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACYqH,qBAAqBA,CAACE,IAAa,EAAiC;IAAA,IAAAiB,WAAA;IACxE,IAAMnC,SAAS,GAAG,EAAAmC,WAAA,GAAC,IAAI,CAAC1H,IAAI,cAAA0H,WAAA,uBAAVA,WAAA,CAA0BnC,SAAS,KAAI,EAAE;IAC3D,OAAOkB,IAAI,CAAChB,MAAM,CAACkC,IAAI,CAAEC,SAAS,IAAK,CAACrC,SAAS,CAACG,QAAQ,CAACkC,SAAS,CAAC,CAAC;EAC1E;AACJ","ignoreList":[]}
package/lib/logger.js CHANGED
@@ -1,4 +1,3 @@
1
- import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
1
  /*
3
2
  Copyright 2018 André Jaenisch
4
3
  Copyright 2019-2025 The Matrix.org Foundation C.I.C.
@@ -113,7 +112,6 @@ export var logger = getPrefixedLogger();
113
112
  export class LogSpan {
114
113
  constructor(parent, name) {
115
114
  this.parent = parent;
116
- _defineProperty(this, "name", void 0);
117
115
  this.name = name + ":";
118
116
  }
119
117
  trace() {
package/lib/logger.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","names":["loglevel","DEFAULT_NAMESPACE","methodFactory","methodName","logLevel","loggerName","_len","arguments","length","args","Array","_key","prefix","unshift","supportedByConsole","console","log","getPrefixedLogger","undefined","concat","prefixLogger","getLogger","getChild","childPrefix","childLogger","rebuild","setLevel","levels","DEBUG","logger","LogSpan","constructor","parent","name","_defineProperty","trace","_len2","msg","_key2","debug","_len3","_key3","info","_len4","_key4","warn","_len5","_key5","error","_len6","_key6","DebugLogger","debugInstance","_len7","_key7","debugWithPrefix","_len8","_key8","_len9","_key9","_len0","_key0","_len1","_key1","namespace","extend","formatter","_len10","_key10","Error","err","shift","stack","message"],"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,OAAOA,QAAQ,MAAM,UAAU;;AAE/B;;AAYA;;AAgBA;;AAsCA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,iBAAiB,GAAG,QAAQ;;AAElC;AACA;AACA;AACA;AACA;AACAD,QAAQ,CAACE,aAAa,GAAG,UAAUC,UAAU,EAAEC,QAAQ,EAAEC,UAAU,EAAE;EACjE,OAAO,YAA+C;IAAA,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAAZC,IAAI,OAAAC,KAAA,CAAAJ,IAAA,GA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AAA;MAAH1B,GAAG,CAAA0B,KAAA,IAAAxD,SAAA,CAAAwD,KAAA;IAAA;IACf,IAAI,CAACR,eAAe,CAAC,SAAS,EAAE,GAAGlB,GAAG,CAAC;EAC3C;EAEOf,QAAQA,CAAC0C,SAAiB,EAAe;IAC5C,OAAO,IAAIb,WAAW,CAAC,IAAI,CAACC,aAAa,CAACa,MAAM,CAACD,SAAS,CAAC,CAAC;EAChE;EAEQT,eAAeA,CAAC3C,MAAc,EAAuB;IACzD,IAAIsD,SAAiB;;IAErB;IACA;IAAA,SAAAC,MAAA,GAAA5D,SAAA,CAAAC,MAAA,EAJuC6B,GAAG,OAAA3B,KAAA,CAAAyD,MAAA,OAAAA,MAAA,WAAAC,MAAA,MAAAA,MAAA,GAAAD,MAAA,EAAAC,MAAA;MAAH/B,GAAG,CAAA+B,MAAA,QAAA7D,SAAA,CAAA6D,MAAA;IAAA;IAK1C,IAAI/B,GAAG,CAAC7B,MAAM,KAAK,CAAC,EAAE;MAClB0D,SAAS,GAAG,EAAE;IAClB,CAAC,MAAM,IAAI7B,GAAG,CAAC,CAAC,CAAC,YAAYgC,KAAK,EAAE;MAChC,IAAMC,GAAG,GAAGjC,GAAG,CAACkC,KAAK,CAAC,CAAC;MACvBL,SAAS,GAAGI,GAAG,CAACE,KAAK,IAAIF,GAAG,CAACG,OAAO;IACxC,CAAC,MAAM,IAAI,OAAOpC,GAAG,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE;MAClC6B,SAAS,GAAG7B,GAAG,CAACkC,KAAK,CAAC,CAAC;IAC3B,CAAC,MAAM;MACHL,SAAS,GAAG,IAAI;IACpB;IACA,IAAI,CAACd,aAAa,CAACxC,MAAM,GAAG,GAAG,GAAGsD,SAAS,EAAE,GAAG7B,GAAG,CAAC;EACxD;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"logger.js","names":["loglevel","DEFAULT_NAMESPACE","methodFactory","methodName","logLevel","loggerName","_len","arguments","length","args","Array","_key","prefix","unshift","supportedByConsole","console","log","getPrefixedLogger","undefined","concat","prefixLogger","getLogger","getChild","childPrefix","childLogger","rebuild","setLevel","levels","DEBUG","logger","LogSpan","constructor","parent","name","trace","_len2","msg","_key2","debug","_len3","_key3","info","_len4","_key4","warn","_len5","_key5","error","_len6","_key6","DebugLogger","debugInstance","_len7","_key7","debugWithPrefix","_len8","_key8","_len9","_key9","_len0","_key0","_len1","_key1","namespace","extend","formatter","_len10","_key10","Error","err","shift","stack","message"],"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,OAAOA,QAAQ,MAAM,UAAU;;AAE/B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