matrix-js-sdk 41.9.0 → 42.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/@types/auth.d.ts +0 -5
  3. package/lib/@types/auth.d.ts.map +1 -1
  4. package/lib/@types/auth.js +0 -6
  5. package/lib/@types/auth.js.map +1 -1
  6. package/lib/@types/type-guards.d.ts +43 -0
  7. package/lib/@types/type-guards.d.ts.map +1 -0
  8. package/lib/@types/type-guards.js +104 -0
  9. package/lib/@types/type-guards.js.map +1 -0
  10. package/lib/NamespacedValue.d.ts.map +1 -1
  11. package/lib/ReEmitter.d.ts.map +1 -1
  12. package/lib/ToDeviceMessageQueue.d.ts.map +1 -1
  13. package/lib/autodiscovery.d.ts.map +1 -1
  14. package/lib/capabilityPoller.d.ts.map +1 -1
  15. package/lib/client.d.ts +4 -7
  16. package/lib/client.d.ts.map +1 -1
  17. package/lib/client.js +10 -22
  18. package/lib/client.js.map +1 -1
  19. package/lib/common-crypto/CryptoBackend.d.ts.map +1 -1
  20. package/lib/content-helpers.d.ts.map +1 -1
  21. package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts.map +1 -1
  22. package/lib/crypto/store/indexeddb-crypto-store.d.ts.map +1 -1
  23. package/lib/crypto/store/localStorage-crypto-store.d.ts.map +1 -1
  24. package/lib/crypto/store/memory-crypto-store.d.ts.map +1 -1
  25. package/lib/crypto-api/index.d.ts +1 -1
  26. package/lib/crypto-api/index.d.ts.map +1 -1
  27. package/lib/crypto-api/index.js.map +1 -1
  28. package/lib/crypto-api/verification.d.ts +23 -5
  29. package/lib/crypto-api/verification.d.ts.map +1 -1
  30. package/lib/crypto-api/verification.js.map +1 -1
  31. package/lib/embedded.d.ts.map +1 -1
  32. package/lib/errors.d.ts.map +1 -1
  33. package/lib/extensible_events_v1/ExtensibleEvent.d.ts.map +1 -1
  34. package/lib/extensible_events_v1/InvalidEventError.d.ts.map +1 -1
  35. package/lib/extensible_events_v1/MessageEvent.d.ts.map +1 -1
  36. package/lib/extensible_events_v1/PollEndEvent.d.ts.map +1 -1
  37. package/lib/extensible_events_v1/PollResponseEvent.d.ts.map +1 -1
  38. package/lib/extensible_events_v1/PollStartEvent.d.ts.map +1 -1
  39. package/lib/filter-component.d.ts.map +1 -1
  40. package/lib/filter.d.ts.map +1 -1
  41. package/lib/http-api/errors.d.ts.map +1 -1
  42. package/lib/http-api/fetch.d.ts +1 -1
  43. package/lib/http-api/fetch.d.ts.map +1 -1
  44. package/lib/http-api/fetch.js.map +1 -1
  45. package/lib/http-api/index.d.ts +1 -7
  46. package/lib/http-api/index.d.ts.map +1 -1
  47. package/lib/http-api/index.js +0 -15
  48. package/lib/http-api/index.js.map +1 -1
  49. package/lib/http-api/interface.d.ts +0 -9
  50. package/lib/http-api/interface.d.ts.map +1 -1
  51. package/lib/http-api/interface.js +0 -2
  52. package/lib/http-api/interface.js.map +1 -1
  53. package/lib/http-api/refresh.d.ts.map +1 -1
  54. package/lib/index.d.ts.map +1 -1
  55. package/lib/interactive-auth.d.ts.map +1 -1
  56. package/lib/logger.d.ts.map +1 -1
  57. package/lib/matrix.d.ts +1 -1
  58. package/lib/matrix.d.ts.map +1 -1
  59. package/lib/matrix.js +1 -1
  60. package/lib/matrix.js.map +1 -1
  61. package/lib/matrixrtc/CallMembership.d.ts.map +1 -1
  62. package/lib/matrixrtc/LivekitTransport.d.ts.map +1 -1
  63. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  64. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts.map +1 -1
  65. package/lib/matrixrtc/MembershipManager.d.ts.map +1 -1
  66. package/lib/matrixrtc/MembershipManagerActionScheduler.d.ts.map +1 -1
  67. package/lib/matrixrtc/RTCEncryptionManager.d.ts.map +1 -1
  68. package/lib/matrixrtc/ToDeviceKeyTransport.d.ts.map +1 -1
  69. package/lib/matrixrtc/membershipData/common.d.ts.map +1 -1
  70. package/lib/matrixrtc/membershipData/rtc.d.ts.map +1 -1
  71. package/lib/matrixrtc/membershipData/session.d.ts.map +1 -1
  72. package/lib/matrixrtc/types.d.ts.map +1 -1
  73. package/lib/matrixrtc/utils.d.ts.map +1 -1
  74. package/lib/models/MSC3089Branch.d.ts.map +1 -1
  75. package/lib/models/MSC3089TreeSpace.d.ts.map +1 -1
  76. package/lib/models/beacon.d.ts.map +1 -1
  77. package/lib/models/device.d.ts.map +1 -1
  78. package/lib/models/event-context.d.ts.map +1 -1
  79. package/lib/models/event-timeline-set.d.ts.map +1 -1
  80. package/lib/models/event-timeline.d.ts.map +1 -1
  81. package/lib/models/event.d.ts.map +1 -1
  82. package/lib/models/invites-ignorer.d.ts.map +1 -1
  83. package/lib/models/poll.d.ts.map +1 -1
  84. package/lib/models/read-receipt.d.ts.map +1 -1
  85. package/lib/models/related-relations.d.ts.map +1 -1
  86. package/lib/models/relations-container.d.ts.map +1 -1
  87. package/lib/models/relations.d.ts.map +1 -1
  88. package/lib/models/room-member.d.ts.map +1 -1
  89. package/lib/models/room-receipts.d.ts.map +1 -1
  90. package/lib/models/room-retention.d.ts.map +1 -1
  91. package/lib/models/room-state.d.ts.map +1 -1
  92. package/lib/models/room-sticky-events.d.ts.map +1 -1
  93. package/lib/models/room-summary.d.ts.map +1 -1
  94. package/lib/models/room.d.ts.map +1 -1
  95. package/lib/models/search-result.d.ts.map +1 -1
  96. package/lib/models/thread.d.ts.map +1 -1
  97. package/lib/models/typed-event-emitter.d.ts.map +1 -1
  98. package/lib/models/user.d.ts.map +1 -1
  99. package/lib/oauth/authorize.d.ts +133 -0
  100. package/lib/oauth/authorize.d.ts.map +1 -0
  101. package/lib/oauth/authorize.js +193 -0
  102. package/lib/oauth/authorize.js.map +1 -0
  103. package/lib/oauth/discover.d.ts +58 -0
  104. package/lib/oauth/discover.d.ts.map +1 -0
  105. package/lib/oauth/discover.js +35 -0
  106. package/lib/oauth/discover.js.map +1 -0
  107. package/lib/oauth/error.d.ts +19 -0
  108. package/lib/oauth/error.d.ts.map +1 -0
  109. package/lib/oauth/error.js +36 -0
  110. package/lib/oauth/error.js.map +1 -0
  111. package/lib/oauth/index.d.ts +87 -0
  112. package/lib/oauth/index.d.ts.map +1 -0
  113. package/lib/oauth/index.js +234 -0
  114. package/lib/oauth/index.js.map +1 -0
  115. package/lib/oauth/register.d.ts +136 -0
  116. package/lib/oauth/register.d.ts.map +1 -0
  117. package/lib/oauth/register.js +73 -0
  118. package/lib/oauth/register.js.map +1 -0
  119. package/lib/oauth/tokenRefresher.d.ts +21 -0
  120. package/lib/oauth/tokenRefresher.d.ts.map +1 -0
  121. package/lib/oauth/tokenRefresher.js +68 -0
  122. package/lib/oauth/tokenRefresher.js.map +1 -0
  123. package/lib/pushprocessor.d.ts.map +1 -1
  124. package/lib/receipt-accumulator.d.ts.map +1 -1
  125. package/lib/rendezvous/MSC4108SignInWithQR.d.ts +7 -7
  126. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  127. package/lib/rendezvous/MSC4108SignInWithQR.js +11 -11
  128. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  129. package/lib/rendezvous/RendezvousError.d.ts.map +1 -1
  130. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts.map +1 -1
  131. package/lib/rendezvous/index.d.ts.map +1 -1
  132. package/lib/rendezvous/index.js.map +1 -1
  133. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +1 -1
  134. package/lib/retentionPolicy.d.ts.map +1 -1
  135. package/lib/room-hierarchy.d.ts.map +1 -1
  136. package/lib/rust-crypto/CrossSigningIdentity.d.ts.map +1 -1
  137. package/lib/rust-crypto/DehydratedDeviceManager.d.ts.map +1 -1
  138. package/lib/rust-crypto/DehydratedDeviceManager.js +11 -13
  139. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  140. package/lib/rust-crypto/KeyClaimManager.d.ts.map +1 -1
  141. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +1 -1
  142. package/lib/rust-crypto/OutgoingRequestsManager.d.ts.map +1 -1
  143. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts.map +1 -1
  144. package/lib/rust-crypto/RoomEncryptor.d.ts.map +1 -1
  145. package/lib/rust-crypto/backup.d.ts.map +1 -1
  146. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  147. package/lib/rust-crypto/verification.d.ts.map +1 -1
  148. package/lib/scheduler.d.ts.map +1 -1
  149. package/lib/secret-storage.d.ts.map +1 -1
  150. package/lib/serverCapabilities.d.ts.map +1 -1
  151. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  152. package/lib/sliding-sync.d.ts.map +1 -1
  153. package/lib/store/indexeddb-local-backend.d.ts.map +1 -1
  154. package/lib/store/indexeddb-remote-backend.d.ts.map +1 -1
  155. package/lib/store/indexeddb-store-worker.d.ts.map +1 -1
  156. package/lib/store/indexeddb.d.ts.map +1 -1
  157. package/lib/store/memory.d.ts.map +1 -1
  158. package/lib/store/stub.d.ts.map +1 -1
  159. package/lib/sync-accumulator.d.ts.map +1 -1
  160. package/lib/sync.d.ts.map +1 -1
  161. package/lib/testing.d.ts +2 -10
  162. package/lib/testing.d.ts.map +1 -1
  163. package/lib/testing.js +4 -19
  164. package/lib/testing.js.map +1 -1
  165. package/lib/timeline-window.d.ts.map +1 -1
  166. package/lib/utils.d.ts.map +1 -1
  167. package/lib/webrtc/call.d.ts.map +1 -1
  168. package/lib/webrtc/callEventHandler.d.ts.map +1 -1
  169. package/lib/webrtc/callFeed.d.ts.map +1 -1
  170. package/lib/webrtc/groupCall.d.ts.map +1 -1
  171. package/lib/webrtc/groupCallEventHandler.d.ts.map +1 -1
  172. package/lib/webrtc/mediaHandler.d.ts.map +1 -1
  173. package/lib/webrtc/stats/callFeedStatsReporter.d.ts.map +1 -1
  174. package/lib/webrtc/stats/callStatsReportGatherer.d.ts.map +1 -1
  175. package/lib/webrtc/stats/connectionStatsBuilder.d.ts.map +1 -1
  176. package/lib/webrtc/stats/connectionStatsReportBuilder.d.ts.map +1 -1
  177. package/lib/webrtc/stats/groupCallStats.d.ts.map +1 -1
  178. package/lib/webrtc/stats/media/mediaSsrcHandler.d.ts.map +1 -1
  179. package/lib/webrtc/stats/media/mediaTrackHandler.d.ts.map +1 -1
  180. package/lib/webrtc/stats/media/mediaTrackStats.d.ts.map +1 -1
  181. package/lib/webrtc/stats/media/mediaTrackStatsHandler.d.ts.map +1 -1
  182. package/lib/webrtc/stats/statsReportEmitter.d.ts.map +1 -1
  183. package/lib/webrtc/stats/summaryStatsReportGatherer.d.ts.map +1 -1
  184. package/lib/webrtc/stats/trackStatsBuilder.d.ts.map +1 -1
  185. package/lib/webrtc/stats/transportStatsBuilder.d.ts.map +1 -1
  186. package/lib/webrtc/stats/valueFormatter.d.ts.map +1 -1
  187. package/package.json +7 -9
  188. package/src/@types/auth.ts +0 -6
  189. package/src/@types/type-guards.ts +126 -0
  190. package/src/client.ts +13 -29
  191. package/src/crypto-api/index.ts +1 -1
  192. package/src/crypto-api/verification.ts +23 -5
  193. package/src/http-api/fetch.ts +1 -1
  194. package/src/http-api/index.ts +1 -23
  195. package/src/http-api/interface.ts +0 -11
  196. package/src/matrix.ts +1 -1
  197. package/src/oauth/authorize.ts +274 -0
  198. package/src/oauth/discover.ts +102 -0
  199. package/src/{oidc → oauth}/error.ts +8 -7
  200. package/src/oauth/index.ts +297 -0
  201. package/src/oauth/register.ts +166 -0
  202. package/src/oauth/tokenRefresher.ts +77 -0
  203. package/src/rendezvous/MSC4108SignInWithQR.ts +11 -12
  204. package/src/rendezvous/index.ts +2 -2
  205. package/src/rust-crypto/DehydratedDeviceManager.ts +14 -13
  206. package/src/testing.ts +3 -22
  207. package/lib/oidc/authorize.d.ts +0 -157
  208. package/lib/oidc/authorize.d.ts.map +0 -1
  209. package/lib/oidc/authorize.js +0 -365
  210. package/lib/oidc/authorize.js.map +0 -1
  211. package/lib/oidc/discovery.d.ts +0 -22
  212. package/lib/oidc/discovery.d.ts.map +0 -1
  213. package/lib/oidc/discovery.js +0 -65
  214. package/lib/oidc/discovery.js.map +0 -1
  215. package/lib/oidc/error.d.ts +0 -18
  216. package/lib/oidc/error.d.ts.map +0 -1
  217. package/lib/oidc/error.js +0 -35
  218. package/lib/oidc/error.js.map +0 -1
  219. package/lib/oidc/index.d.ts +0 -16
  220. package/lib/oidc/index.d.ts.map +0 -1
  221. package/lib/oidc/index.js +0 -30
  222. package/lib/oidc/index.js.map +0 -1
  223. package/lib/oidc/register.d.ts +0 -70
  224. package/lib/oidc/register.d.ts.map +0 -1
  225. package/lib/oidc/register.js +0 -134
  226. package/lib/oidc/register.js.map +0 -1
  227. package/lib/oidc/tokenRefresher.d.ts +0 -91
  228. package/lib/oidc/tokenRefresher.d.ts.map +0 -1
  229. package/lib/oidc/tokenRefresher.js +0 -173
  230. package/lib/oidc/tokenRefresher.js.map +0 -1
  231. package/lib/oidc/validate.d.ts +0 -78
  232. package/lib/oidc/validate.d.ts.map +0 -1
  233. package/lib/oidc/validate.js +0 -181
  234. package/lib/oidc/validate.js.map +0 -1
  235. package/src/oidc/authorize.ts +0 -431
  236. package/src/oidc/discovery.ts +0 -67
  237. package/src/oidc/index.ts +0 -33
  238. package/src/oidc/register.ts +0 -168
  239. package/src/oidc/tokenRefresher.ts +0 -184
  240. package/src/oidc/validate.ts +0 -265
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.
3
+ * Not intended to be displayed directly to the user.
4
+ */
5
+ export declare enum OAuth2Error {
6
+ General = "Something went wrong with OAuth2 discovery",
7
+ OpSupport = "Configured OAuth2 OP does not support required functions",
8
+ DynamicRegistrationNotSupported = "Dynamic registration not supported",
9
+ DynamicRegistrationFailed = "Dynamic registration failed",
10
+ DynamicRegistrationInvalid = "Dynamic registration invalid response",
11
+ CodeExchangeFailed = "Failed to exchange code for token",
12
+ InvalidBearerTokenResponse = "Invalid bearer token response",
13
+ InvalidDeviceAuthorizationResponse = "Invalid device authorization response",
14
+ MissingOrInvalidStoredState = "State required to finish logging in is not found in storage.",
15
+ RefreshTokenFailed = "Failed to refresh token",
16
+ RevokeTokenFailed = "Failed to revoke token",
17
+ DeviceAuthorizationGrantFailed = "Failed to perform device authorization grant"
18
+ }
19
+ //# sourceMappingURL=error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../src/oauth/error.ts"],"names":[],"mappings":"AAgBA;;;GAGG;AACH,oBAAY,WAAW;IACnB,OAAO,+CAA+C;IACtD,SAAS,6DAA6D;IACtE,+BAA+B,uCAAuC;IACtE,yBAAyB,gCAAgC;IACzD,0BAA0B,0CAA0C;IACpE,kBAAkB,sCAAsC;IACxD,0BAA0B,kCAAkC;IAC5D,kCAAkC,0CAA0C;IAC5E,2BAA2B,iEAAiE;IAC5F,kBAAkB,4BAA4B;IAC9C,iBAAiB,2BAA2B;IAC5C,8BAA8B,iDAAiD;CAClF"}
@@ -0,0 +1,36 @@
1
+ /*
2
+ Copyright 2023 The Matrix.org Foundation C.I.C.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.
19
+ * Not intended to be displayed directly to the user.
20
+ */
21
+ export let OAuth2Error = /*#__PURE__*/function (OAuth2Error) {
22
+ OAuth2Error["General"] = "Something went wrong with OAuth2 discovery";
23
+ OAuth2Error["OpSupport"] = "Configured OAuth2 OP does not support required functions";
24
+ OAuth2Error["DynamicRegistrationNotSupported"] = "Dynamic registration not supported";
25
+ OAuth2Error["DynamicRegistrationFailed"] = "Dynamic registration failed";
26
+ OAuth2Error["DynamicRegistrationInvalid"] = "Dynamic registration invalid response";
27
+ OAuth2Error["CodeExchangeFailed"] = "Failed to exchange code for token";
28
+ OAuth2Error["InvalidBearerTokenResponse"] = "Invalid bearer token response";
29
+ OAuth2Error["InvalidDeviceAuthorizationResponse"] = "Invalid device authorization response";
30
+ OAuth2Error["MissingOrInvalidStoredState"] = "State required to finish logging in is not found in storage.";
31
+ OAuth2Error["RefreshTokenFailed"] = "Failed to refresh token";
32
+ OAuth2Error["RevokeTokenFailed"] = "Failed to revoke token";
33
+ OAuth2Error["DeviceAuthorizationGrantFailed"] = "Failed to perform device authorization grant";
34
+ return OAuth2Error;
35
+ }({});
36
+ //# sourceMappingURL=error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.js","names":[],"sources":["../../src/oauth/error.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.\n * Not intended to be displayed directly to the user.\n */\nexport enum OAuth2Error {\n General = \"Something went wrong with OAuth2 discovery\",\n OpSupport = \"Configured OAuth2 OP does not support required functions\",\n DynamicRegistrationNotSupported = \"Dynamic registration not supported\",\n DynamicRegistrationFailed = \"Dynamic registration failed\",\n DynamicRegistrationInvalid = \"Dynamic registration invalid response\",\n CodeExchangeFailed = \"Failed to exchange code for token\",\n InvalidBearerTokenResponse = \"Invalid bearer token response\",\n InvalidDeviceAuthorizationResponse = \"Invalid device authorization response\",\n MissingOrInvalidStoredState = \"State required to finish logging in is not found in storage.\",\n RefreshTokenFailed = \"Failed to refresh token\",\n RevokeTokenFailed = \"Failed to revoke token\",\n DeviceAuthorizationGrantFailed = \"Failed to perform device authorization grant\",\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAY,WAAW,0BAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAX,WAAW;EAAA,OAAX,WAAW;AAAA","ignoreList":[]}
@@ -0,0 +1,87 @@
1
+ import { type BearerTokenResponse, type DeviceAccessTokenError, type DeviceAccessTokenResponse, type DeviceAuthorizationResponse } from "./authorize.ts";
2
+ import type { ValidatedAuthMetadata } from "./discover.ts";
3
+ import { type OAuthRegistrationRequest } from "./register.ts";
4
+ export * from "./authorize.ts";
5
+ export * from "./error.ts";
6
+ export * from "./register.ts";
7
+ export * from "./tokenRefresher.ts";
8
+ export * from "./discover.ts";
9
+ /**
10
+ * Type representing the persistent context needed for typical OAuth flows
11
+ */
12
+ type Context = {
13
+ /** The OAuth client ID */
14
+ clientId: string;
15
+ /** The desired device ID */
16
+ deviceId?: string;
17
+ /** The seed used to generate the challenge code */
18
+ codeVerifier?: string;
19
+ /** The URI to redirect the user to with credentials after auth */
20
+ redirectUri: string;
21
+ };
22
+ export declare class OAuth2 {
23
+ readonly metadata: ValidatedAuthMetadata;
24
+ /**
25
+ * Attempts dynamic registration against the configured registration endpoint.
26
+ * Will ignore any URIs that do not use client_uri as a common base as per the spec.
27
+ * @param authMetadata - Auth config from {@link MatrixClient.getAuthMetadata}
28
+ * @param clientMetadata - The metadata for the client which to register,
29
+ * grant_types & response_types & token_endpoint_auth_method will be sanely calculated if omitted.
30
+ * @returns Promise<string> resolved with registered clientId
31
+ * @throws when registration is not supported, on failed request or invalid response
32
+ */
33
+ static registerClient(authMetadata: ValidatedAuthMetadata, clientMetadata: OAuthRegistrationRequest): Promise<string>;
34
+ readonly context: Required<Context>;
35
+ constructor(metadata: ValidatedAuthMetadata, context: Context);
36
+ /**
37
+ * Generate a URL to attempt authorization with the OP
38
+ * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-flow
39
+ * @param state - A unique opaque identifier, like a transaction ID,
40
+ * that will allow the client to maintain state between the authorization request and the callback.
41
+ * The app should use this to key the storage for where the rest of the auth context is saved.
42
+ * @param responseMode - The manner in which the IdP should send the secrets back to the app. Defaults to `fragment` for privacy.
43
+ * @param prompt - Optional prompt parameter to pass to the IdP to signal intent, e.g. `create` for User registration.
44
+ * @param scope - The OAuth2 scope to request, will be generated based on the device ID if omitted.
45
+ * @returns a Promise with the url as a string
46
+ */
47
+ generateAuthorizationCodeGrantUrl(state: string, responseMode?: "fragment" | "query", prompt?: string, scope?: string): Promise<string>;
48
+ /**
49
+ * Attempt to exchange authorization code for bearer token.
50
+ *
51
+ * Takes the authorization code returned by the OAuth2 Provider via the authorization URL, and makes a
52
+ * request to the Token Endpoint, to obtain the access token, refresh token, etc.
53
+ *
54
+ * @param code - authorization code as returned by IdP during authorization
55
+ * @returns a validated bearer token response
56
+ * @throws An `Error` with `message` set to an entry in {@link OAuth2Error},
57
+ * when the request fails, or the returned token response is invalid.
58
+ */
59
+ completeAuthorizationCodeGrant(code: string): Promise<BearerTokenResponse>;
60
+ /**
61
+ * Refresh the access token using the given refresh token and the refresh token grant
62
+ * @param refreshToken - the token to use to refresh the access token
63
+ */
64
+ performRefreshTokenGrant(refreshToken: string): Promise<BearerTokenResponse>;
65
+ /**
66
+ * Revokes the given token
67
+ * @param token - the token to remove
68
+ * @param type - the type of token, acts as a hint to the IdP
69
+ */
70
+ revokeToken(token: string, type?: "access_token" | "refresh_token"): Promise<void>;
71
+ /**
72
+ * Begin OAuth2 device authorization flow.
73
+ * @param scope - the scope to request for authorization.
74
+ * @returns a promise that resolves to a device access token response,
75
+ * or an error response if the user denies authorization or the device code expires.
76
+ */
77
+ startDeviceAuthorizationGrant(scope?: string): Promise<DeviceAuthorizationResponse>;
78
+ /**
79
+ * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.
80
+ * @param session - The session returned from a previous call to {@link OAuth2.startDeviceAuthorizationGrant}.
81
+ * @returns a promise that resolves to a device access token response,
82
+ * or an error response if the user denies authorization or the device code expires.
83
+ */
84
+ waitForDeviceAuthorizationGrant(session: DeviceAuthorizationResponse): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError>;
85
+ private fetch;
86
+ }
87
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAgBA,OAAO,EACH,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,KAAK,yBAAyB,EAC9B,KAAK,2BAA2B,EAMnC,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EAEH,KAAK,wBAAwB,EAGhC,MAAM,eAAe,CAAC;AASvB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AACpC,cAAc,eAAe,CAAC;AAE9B;;GAEG;AACH,KAAK,OAAO,GAAG;IACX,0BAA0B;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,4BAA4B;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kEAAkE;IAClE,WAAW,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,qBAAa,MAAM;aA0EK,QAAQ,EAAE,qBAAqB;IAzEnD;;;;;;;;OAQG;IACH,OAAoB,cAAc,CAC9B,YAAY,EAAE,qBAAqB,EACnC,cAAc,EAAE,wBAAwB,GACzC,OAAO,CAAC,MAAM,CAAC,CAwDjB;IAED,SAAgB,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;IAE3C,YACoB,QAAQ,EAAE,qBAAqB,EAC/C,OAAO,EAAE,OAAO,EAQnB;IAED;;;;;;;;;;OAUG;IACU,iCAAiC,CAC1C,KAAK,EAAE,MAAM,EACb,YAAY,GAAE,UAAU,GAAG,OAAoB,EAC/C,MAAM,CAAC,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC,CAkBjB;IAED;;;;;;;;;;OAUG;IACU,8BAA8B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAatF;IAED;;;OAGG;IACU,wBAAwB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAWxF;IAED;;;;OAIG;IACU,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,cAAc,GAAG,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAY9F;IAED;;;;;OAKG;IACU,6BAA6B,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAM/F;IAED;;;;;OAKG;IACU,+BAA+B,CACxC,OAAO,EAAE,2BAA2B,GACrC,OAAO,CAAC,yBAAyB,GAAG,sBAAsB,CAAC,CAM7D;YAEa,KAAK;CAqBtB"}
@@ -0,0 +1,234 @@
1
+ import _objectSpread from "@babel/runtime/helpers/objectSpread2";
2
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
3
+ /*
4
+ Copyright 2023 The Matrix.org Foundation C.I.C.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing, software
13
+ distributed under the License is distributed on an "AS IS" BASIS,
14
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ See the License for the specific language governing permissions and
16
+ limitations under the License.
17
+ */
18
+
19
+ import { generateScope, normalizeBearerTokenResponseTokenType, startDeviceAuthorization, validateBearerTokenResponse, waitForDeviceAuthorization } from "./authorize.js";
20
+ import { OAuthGrantType, urlHasCommonBase, validateRegistrationResponse } from "./register.js";
21
+ import { encodeUnpaddedBase64Url } from "../base64.js";
22
+ import { sha256 } from "../digest.js";
23
+ import { HTTPError, Method } from "../http-api";
24
+ import { logger } from "../logger.js";
25
+ import { OAuth2Error } from "./error.js";
26
+ import { secureRandomString } from "../randomstring.js";
27
+ export * from "./authorize.js";
28
+ export * from "./error.js";
29
+ export * from "./register.js";
30
+ export * from "./tokenRefresher.js";
31
+ export * from "./discover.js";
32
+
33
+ /**
34
+ * Type representing the persistent context needed for typical OAuth flows
35
+ */
36
+
37
+ export class OAuth2 {
38
+ /**
39
+ * Attempts dynamic registration against the configured registration endpoint.
40
+ * Will ignore any URIs that do not use client_uri as a common base as per the spec.
41
+ * @param authMetadata - Auth config from {@link MatrixClient.getAuthMetadata}
42
+ * @param clientMetadata - The metadata for the client which to register,
43
+ * grant_types & response_types & token_endpoint_auth_method will be sanely calculated if omitted.
44
+ * @returns Promise<string> resolved with registered clientId
45
+ * @throws when registration is not supported, on failed request or invalid response
46
+ */
47
+ static async registerClient(authMetadata, clientMetadata) {
48
+ const defaultGrantTypes = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];
49
+ // ask for device authorization grant if supported
50
+ if (authMetadata.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
51
+ defaultGrantTypes.push(OAuthGrantType.DeviceAuthorization);
52
+ }
53
+ const grantTypes = clientMetadata.grant_types ?? defaultGrantTypes;
54
+ if (grantTypes.some(scope => !authMetadata.grant_types_supported.includes(scope))) {
55
+ throw new Error(OAuth2Error.DynamicRegistrationNotSupported);
56
+ }
57
+ const commonBase = new URL(clientMetadata.client_uri);
58
+ const request = _objectSpread(_objectSpread({
59
+ // Apply some defaults
60
+ response_types: ["code"],
61
+ token_endpoint_auth_method: "none"
62
+ }, clientMetadata), {}, {
63
+ grant_types: grantTypes,
64
+ logo_uri: urlHasCommonBase(commonBase, clientMetadata.logo_uri) ? clientMetadata.logo_uri : undefined,
65
+ policy_uri: urlHasCommonBase(commonBase, clientMetadata.policy_uri) ? clientMetadata.policy_uri : undefined,
66
+ tos_uri: urlHasCommonBase(commonBase, clientMetadata.tos_uri) ? clientMetadata.tos_uri : undefined
67
+ });
68
+ try {
69
+ const response = await fetch(authMetadata.registration_endpoint, {
70
+ method: Method.Post,
71
+ headers: {
72
+ "Accept": "application/json",
73
+ "Content-Type": "application/json"
74
+ },
75
+ body: JSON.stringify(request)
76
+ });
77
+ if (response.status >= 400) {
78
+ throw new Error(OAuth2Error.DynamicRegistrationFailed);
79
+ }
80
+ const registrationResponse = await response.json();
81
+ if (validateRegistrationResponse(registrationResponse)) {
82
+ return registrationResponse.client_id;
83
+ }
84
+ throw new Error(OAuth2Error.DynamicRegistrationInvalid);
85
+ } catch (error) {
86
+ if (Object.values(OAuth2Error).includes(error.message)) {
87
+ throw error;
88
+ } else {
89
+ logger.error("Dynamic registration request failed", error);
90
+ throw new Error(OAuth2Error.DynamicRegistrationFailed);
91
+ }
92
+ }
93
+ }
94
+ constructor(metadata, context) {
95
+ _defineProperty(this, "context", void 0);
96
+ this.metadata = metadata;
97
+ this.context = {
98
+ clientId: context.clientId,
99
+ redirectUri: context.redirectUri,
100
+ deviceId: context.deviceId ?? secureRandomString(10),
101
+ codeVerifier: context.codeVerifier ?? secureRandomString(96)
102
+ };
103
+ }
104
+
105
+ /**
106
+ * Generate a URL to attempt authorization with the OP
107
+ * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-flow
108
+ * @param state - A unique opaque identifier, like a transaction ID,
109
+ * that will allow the client to maintain state between the authorization request and the callback.
110
+ * The app should use this to key the storage for where the rest of the auth context is saved.
111
+ * @param responseMode - The manner in which the IdP should send the secrets back to the app. Defaults to `fragment` for privacy.
112
+ * @param prompt - Optional prompt parameter to pass to the IdP to signal intent, e.g. `create` for User registration.
113
+ * @param scope - The OAuth2 scope to request, will be generated based on the device ID if omitted.
114
+ * @returns a Promise with the url as a string
115
+ */
116
+ async generateAuthorizationCodeGrantUrl(state, responseMode = "fragment", prompt, scope) {
117
+ const challenge = encodeUnpaddedBase64Url(await sha256(this.context.codeVerifier));
118
+ const url = new URL(this.metadata.authorization_endpoint);
119
+ url.searchParams.set("response_type", "code");
120
+ url.searchParams.set("response_mode", responseMode);
121
+ url.searchParams.set("client_id", this.context.clientId);
122
+ url.searchParams.set("redirect_uri", this.context.redirectUri);
123
+ url.searchParams.set("scope", scope ?? generateScope(this.context.deviceId));
124
+ url.searchParams.set("state", state);
125
+ url.searchParams.set("code_challenge_method", "S256");
126
+ url.searchParams.set("code_challenge", challenge);
127
+ if (prompt) {
128
+ url.searchParams.set("prompt", prompt);
129
+ }
130
+ return url.toString();
131
+ }
132
+
133
+ /**
134
+ * Attempt to exchange authorization code for bearer token.
135
+ *
136
+ * Takes the authorization code returned by the OAuth2 Provider via the authorization URL, and makes a
137
+ * request to the Token Endpoint, to obtain the access token, refresh token, etc.
138
+ *
139
+ * @param code - authorization code as returned by IdP during authorization
140
+ * @returns a validated bearer token response
141
+ * @throws An `Error` with `message` set to an entry in {@link OAuth2Error},
142
+ * when the request fails, or the returned token response is invalid.
143
+ */
144
+ async completeAuthorizationCodeGrant(code) {
145
+ const params = new URLSearchParams();
146
+ params.append("grant_type", "authorization_code");
147
+ params.append("client_id", this.context.clientId);
148
+ params.append("code_verifier", this.context.codeVerifier);
149
+ params.append("redirect_uri", this.context.redirectUri);
150
+ params.append("code", code);
151
+ const tokenResponse = await this.fetch("token", params, OAuth2Error.CodeExchangeFailed);
152
+
153
+ // throws when response is invalid
154
+ validateBearerTokenResponse(tokenResponse);
155
+ return normalizeBearerTokenResponseTokenType(tokenResponse);
156
+ }
157
+
158
+ /**
159
+ * Refresh the access token using the given refresh token and the refresh token grant
160
+ * @param refreshToken - the token to use to refresh the access token
161
+ */
162
+ async performRefreshTokenGrant(refreshToken) {
163
+ const params = new URLSearchParams();
164
+ params.append("grant_type", "refresh_token");
165
+ params.append("client_id", this.context.clientId);
166
+ params.append("refresh_token", refreshToken);
167
+ const tokenResponse = await this.fetch("token", params, OAuth2Error.RefreshTokenFailed);
168
+
169
+ // throws when response is invalid
170
+ validateBearerTokenResponse(tokenResponse);
171
+ return normalizeBearerTokenResponseTokenType(tokenResponse);
172
+ }
173
+
174
+ /**
175
+ * Revokes the given token
176
+ * @param token - the token to remove
177
+ * @param type - the type of token, acts as a hint to the IdP
178
+ */
179
+ async revokeToken(token, type) {
180
+ const params = new URLSearchParams();
181
+ params.append("token", token);
182
+ params.append("client_id", this.context.clientId);
183
+ if (type) {
184
+ params.append("token_type_hint", type);
185
+ }
186
+ await this.fetch("revocation", params, OAuth2Error.RevokeTokenFailed);
187
+ const headers = new Headers();
188
+ headers.set("Content-Type", "application/x-www-form-urlencoded");
189
+ }
190
+
191
+ /**
192
+ * Begin OAuth2 device authorization flow.
193
+ * @param scope - the scope to request for authorization.
194
+ * @returns a promise that resolves to a device access token response,
195
+ * or an error response if the user denies authorization or the device code expires.
196
+ */
197
+ async startDeviceAuthorizationGrant(scope) {
198
+ return startDeviceAuthorization({
199
+ scope: scope ?? generateScope(this.context.deviceId),
200
+ metadata: this.metadata,
201
+ clientId: this.context.clientId
202
+ });
203
+ }
204
+
205
+ /**
206
+ * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.
207
+ * @param session - The session returned from a previous call to {@link OAuth2.startDeviceAuthorizationGrant}.
208
+ * @returns a promise that resolves to a device access token response,
209
+ * or an error response if the user denies authorization or the device code expires.
210
+ */
211
+ async waitForDeviceAuthorizationGrant(session) {
212
+ return waitForDeviceAuthorization({
213
+ session,
214
+ metadata: this.metadata,
215
+ clientId: this.context.clientId
216
+ });
217
+ }
218
+ async fetch(target, params, error) {
219
+ const url = this.metadata[`${target}_endpoint`];
220
+ const res = await fetch(url, {
221
+ method: Method.Post,
222
+ headers: {
223
+ "Content-Type": "application/x-www-form-urlencoded",
224
+ "Accept": "application/json"
225
+ },
226
+ body: params
227
+ });
228
+ if (res.status >= 400) {
229
+ throw new HTTPError(error, res.status, res.headers);
230
+ }
231
+ return await res.json();
232
+ }
233
+ }
234
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/oauth/index.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n type BearerTokenResponse,\n type DeviceAccessTokenError,\n type DeviceAccessTokenResponse,\n type DeviceAuthorizationResponse,\n generateScope,\n normalizeBearerTokenResponseTokenType,\n startDeviceAuthorization,\n validateBearerTokenResponse,\n waitForDeviceAuthorization,\n} from \"./authorize.ts\";\nimport type { ValidatedAuthMetadata } from \"./discover.ts\";\nimport {\n OAuthGrantType,\n type OAuthRegistrationRequest,\n urlHasCommonBase,\n validateRegistrationResponse,\n} from \"./register.ts\";\nimport { encodeUnpaddedBase64Url } from \"../base64.ts\";\nimport { sha256 } from \"../digest.ts\";\nimport { HTTPError, Method } from \"../http-api\";\nimport { logger } from \"../logger.ts\";\nimport { OAuth2Error } from \"./error.ts\";\nimport { secureRandomString } from \"../randomstring.ts\";\nimport { type NonEmptyArray } from \"../@types/common.ts\";\n\nexport * from \"./authorize.ts\";\nexport * from \"./error.ts\";\nexport * from \"./register.ts\";\nexport * from \"./tokenRefresher.ts\";\nexport * from \"./discover.ts\";\n\n/**\n * Type representing the persistent context needed for typical OAuth flows\n */\ntype Context = {\n /** The OAuth client ID */\n clientId: string;\n /** The desired device ID */\n deviceId?: string;\n /** The seed used to generate the challenge code */\n codeVerifier?: string;\n /** The URI to redirect the user to with credentials after auth */\n redirectUri: string;\n};\n\nexport class OAuth2 {\n /**\n * Attempts dynamic registration against the configured registration endpoint.\n * Will ignore any URIs that do not use client_uri as a common base as per the spec.\n * @param authMetadata - Auth config from {@link MatrixClient.getAuthMetadata}\n * @param clientMetadata - The metadata for the client which to register,\n * grant_types & response_types & token_endpoint_auth_method will be sanely calculated if omitted.\n * @returns Promise<string> resolved with registered clientId\n * @throws when registration is not supported, on failed request or invalid response\n */\n public static async registerClient(\n authMetadata: ValidatedAuthMetadata,\n clientMetadata: OAuthRegistrationRequest,\n ): Promise<string> {\n const defaultGrantTypes: NonEmptyArray<string> = [\n OAuthGrantType.AuthorizationCode,\n OAuthGrantType.RefreshToken,\n ];\n // ask for device authorization grant if supported\n if (authMetadata.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {\n defaultGrantTypes.push(OAuthGrantType.DeviceAuthorization);\n }\n\n const grantTypes = clientMetadata.grant_types ?? defaultGrantTypes;\n if (grantTypes.some((scope) => !authMetadata.grant_types_supported.includes(scope))) {\n throw new Error(OAuth2Error.DynamicRegistrationNotSupported);\n }\n\n const commonBase = new URL(clientMetadata.client_uri);\n\n const request: OAuthRegistrationRequest = {\n // Apply some defaults\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\",\n ...clientMetadata,\n grant_types: grantTypes,\n logo_uri: urlHasCommonBase(commonBase, clientMetadata.logo_uri) ? clientMetadata.logo_uri : undefined,\n policy_uri: urlHasCommonBase(commonBase, clientMetadata.policy_uri) ? clientMetadata.policy_uri : undefined,\n tos_uri: urlHasCommonBase(commonBase, clientMetadata.tos_uri) ? clientMetadata.tos_uri : undefined,\n };\n\n try {\n const response = await fetch(authMetadata.registration_endpoint, {\n method: Method.Post,\n headers: {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request),\n });\n\n if (response.status >= 400) {\n throw new Error(OAuth2Error.DynamicRegistrationFailed);\n }\n\n const registrationResponse = await response.json();\n if (validateRegistrationResponse(registrationResponse)) {\n return registrationResponse.client_id;\n }\n\n throw new Error(OAuth2Error.DynamicRegistrationInvalid);\n } catch (error) {\n if (Object.values(OAuth2Error).includes((error as Error).message as OAuth2Error)) {\n throw error;\n } else {\n logger.error(\"Dynamic registration request failed\", error);\n throw new Error(OAuth2Error.DynamicRegistrationFailed);\n }\n }\n }\n\n public readonly context: Required<Context>;\n\n public constructor(\n public readonly metadata: ValidatedAuthMetadata,\n context: Context,\n ) {\n this.context = {\n clientId: context.clientId,\n redirectUri: context.redirectUri,\n deviceId: context.deviceId ?? secureRandomString(10),\n codeVerifier: context.codeVerifier ?? secureRandomString(96),\n };\n }\n\n /**\n * Generate a URL to attempt authorization with the OP\n * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-flow\n * @param state - A unique opaque identifier, like a transaction ID,\n * that will allow the client to maintain state between the authorization request and the callback.\n * The app should use this to key the storage for where the rest of the auth context is saved.\n * @param responseMode - The manner in which the IdP should send the secrets back to the app. Defaults to `fragment` for privacy.\n * @param prompt - Optional prompt parameter to pass to the IdP to signal intent, e.g. `create` for User registration.\n * @param scope - The OAuth2 scope to request, will be generated based on the device ID if omitted.\n * @returns a Promise with the url as a string\n */\n public async generateAuthorizationCodeGrantUrl(\n state: string,\n responseMode: \"fragment\" | \"query\" = \"fragment\",\n prompt?: string,\n scope?: string,\n ): Promise<string> {\n const challenge = encodeUnpaddedBase64Url(await sha256(this.context.codeVerifier));\n\n const url = new URL(this.metadata.authorization_endpoint);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"response_mode\", responseMode);\n url.searchParams.set(\"client_id\", this.context.clientId);\n url.searchParams.set(\"redirect_uri\", this.context.redirectUri);\n url.searchParams.set(\"scope\", scope ?? generateScope(this.context.deviceId));\n url.searchParams.set(\"state\", state);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"code_challenge\", challenge);\n\n if (prompt) {\n url.searchParams.set(\"prompt\", prompt);\n }\n\n return url.toString();\n }\n\n /**\n * Attempt to exchange authorization code for bearer token.\n *\n * Takes the authorization code returned by the OAuth2 Provider via the authorization URL, and makes a\n * request to the Token Endpoint, to obtain the access token, refresh token, etc.\n *\n * @param code - authorization code as returned by IdP during authorization\n * @returns a validated bearer token response\n * @throws An `Error` with `message` set to an entry in {@link OAuth2Error},\n * when the request fails, or the returned token response is invalid.\n */\n public async completeAuthorizationCodeGrant(code: string): Promise<BearerTokenResponse> {\n const params = new URLSearchParams();\n params.append(\"grant_type\", \"authorization_code\");\n params.append(\"client_id\", this.context.clientId);\n params.append(\"code_verifier\", this.context.codeVerifier);\n params.append(\"redirect_uri\", this.context.redirectUri);\n params.append(\"code\", code);\n\n const tokenResponse = await this.fetch(\"token\", params, OAuth2Error.CodeExchangeFailed);\n\n // throws when response is invalid\n validateBearerTokenResponse(tokenResponse);\n return normalizeBearerTokenResponseTokenType(tokenResponse);\n }\n\n /**\n * Refresh the access token using the given refresh token and the refresh token grant\n * @param refreshToken - the token to use to refresh the access token\n */\n public async performRefreshTokenGrant(refreshToken: string): Promise<BearerTokenResponse> {\n const params = new URLSearchParams();\n params.append(\"grant_type\", \"refresh_token\");\n params.append(\"client_id\", this.context.clientId);\n params.append(\"refresh_token\", refreshToken);\n\n const tokenResponse = await this.fetch(\"token\", params, OAuth2Error.RefreshTokenFailed);\n\n // throws when response is invalid\n validateBearerTokenResponse(tokenResponse);\n return normalizeBearerTokenResponseTokenType(tokenResponse);\n }\n\n /**\n * Revokes the given token\n * @param token - the token to remove\n * @param type - the type of token, acts as a hint to the IdP\n */\n public async revokeToken(token: string, type?: \"access_token\" | \"refresh_token\"): Promise<void> {\n const params = new URLSearchParams();\n params.append(\"token\", token);\n params.append(\"client_id\", this.context.clientId);\n if (type) {\n params.append(\"token_type_hint\", type);\n }\n\n await this.fetch(\"revocation\", params, OAuth2Error.RevokeTokenFailed);\n\n const headers = new Headers();\n headers.set(\"Content-Type\", \"application/x-www-form-urlencoded\");\n }\n\n /**\n * Begin OAuth2 device authorization flow.\n * @param scope - the scope to request for authorization.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\n public async startDeviceAuthorizationGrant(scope?: string): Promise<DeviceAuthorizationResponse> {\n return startDeviceAuthorization({\n scope: scope ?? generateScope(this.context.deviceId),\n metadata: this.metadata,\n clientId: this.context.clientId,\n });\n }\n\n /**\n * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.\n * @param session - The session returned from a previous call to {@link OAuth2.startDeviceAuthorizationGrant}.\n * @returns a promise that resolves to a device access token response,\n * or an error response if the user denies authorization or the device code expires.\n */\n public async waitForDeviceAuthorizationGrant(\n session: DeviceAuthorizationResponse,\n ): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> {\n return waitForDeviceAuthorization({\n session,\n metadata: this.metadata,\n clientId: this.context.clientId,\n });\n }\n\n private async fetch(\n target: \"token\" | \"registration\" | \"revocation\",\n params: URLSearchParams,\n error: OAuth2Error,\n ): Promise<unknown> {\n const url = this.metadata[`${target}_endpoint`];\n const res = await fetch(url, {\n method: Method.Post,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"application/json\",\n },\n body: params,\n });\n\n if (res.status >= 400) {\n throw new HTTPError(error, res.status, res.headers);\n }\n\n return await res.json();\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAKI,aAAa,EACb,qCAAqC,EACrC,wBAAwB,EACxB,2BAA2B,EAC3B,0BAA0B,QACvB,gBAAgB;AAEvB,SAC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AC,GAAG,MAAM,WAAW,CAAC;IAC/C,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;MACzB,MAAM,EAAE,MAAM,CAAC,IAAI;MACnB,OAAO,EAAE;QACL,cAAc,EAAE,mCAAmC;QACnD,QAAQ,EAAE;MACd,CAAC;MACD,IAAI,EAAE;IACV,CAAC,CAAC;IAEF,IAAI,GAAG,CAAC,MAAM,IAAI,GAAG,EAAE;MACnB,MAAM,IAAI,SAAS,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC;IACvD;IAEA,OAAO,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC;EAC3B;AACJ","ignoreList":[]}
@@ -0,0 +1,136 @@
1
+ import { type NonEmptyArray } from "../@types/common.ts";
2
+ type LocalizableKeys = "client_name" | "client_uri" | "policy_uri" | "tos_uri" | "logo_uri";
3
+ /**
4
+ * Request body for dynamic registration as defined by https://spec.matrix.org/v1.18/client-server-api/#client-registration
5
+ */
6
+ export type OAuthRegistrationRequest = {
7
+ /**
8
+ * Kind of the application.
9
+ *
10
+ * The homeserver MUST support the web and native values to be able to perform redirect URI validation.
11
+ *
12
+ * Defaults to web if omitted.
13
+ */
14
+ application_type?: "web" | "native";
15
+ /**
16
+ * Human-readable name of the client to be presented to the user.
17
+ *
18
+ * This field can be localized by specifying `client_name#$lang`.
19
+ */
20
+ client_name?: string;
21
+ /**
22
+ * A URL to a valid web page that SHOULD give the user more information about the client.
23
+ *
24
+ * This URL MUST use the https scheme and SHOULD NOT require authentication to access.
25
+ * It MUST NOT use a user or password in the authority component of the URI.
26
+ *
27
+ * The server MAY reject client registrations if this field is invalid or missing.
28
+ *
29
+ * This URI is a common base for all the other URIs in the metadata:
30
+ * those MUST be either on the same host or on a subdomain of the host of the client_uri.
31
+ * The port number, path and query components MAY be different.
32
+ *
33
+ * For example, if the client_uri is https://example.com/,
34
+ * then one of the redirect_uris can be https://example.com/callback or https://app.example.com/callback,
35
+ * but not https://app.com/callback.
36
+ *
37
+ * This field can be localized by specifying `client_uri#$lang`.
38
+ */
39
+ client_uri: string;
40
+ /**
41
+ * Array of the OAuth 2.0 grant types that the client may use.
42
+ *
43
+ * This MUST include:
44
+ *
45
+ * the authorization_code value to use the authorization code grant,
46
+ * the refresh_token value to use the refresh token grant.
47
+ */
48
+ grant_types?: NonEmptyArray<string>;
49
+ /**
50
+ * URL that references a logo for the client.
51
+ *
52
+ * This URL MUST use the https scheme.
53
+ *
54
+ * This field can be localized by specifying `logo_uri#$lang`.
55
+ */
56
+ logo_uri?: string;
57
+ /**
58
+ * URL that points to a human-readable policy document for the client.
59
+ *
60
+ * This URL MUST use the https scheme and SHOULD NOT require authentication to access.
61
+ * It MUST NOT use a user or password in the authority component of the URI.
62
+ *
63
+ * This field can be localized by specifying `policy_uri#$lang`.
64
+ */
65
+ policy_uri?: string;
66
+ /**
67
+ * Array of redirection URIs for use in redirect-based flows.
68
+ *
69
+ * At least one URI is required to use the authorization code grant.
70
+ */
71
+ redirect_uris?: NonEmptyArray<string>;
72
+ /**
73
+ * Array of the OAuth 2.0 response types that the client may use.
74
+ *
75
+ * This MUST include the code value to use the authorization code grant.
76
+ */
77
+ response_types?: NonEmptyArray<string>;
78
+ /**
79
+ * String indicator of the requested authentication method for the token endpoint.
80
+ */
81
+ token_endpoint_auth_method?: string;
82
+ /**
83
+ * URL that points to a human-readable terms of service document for the client.
84
+ *
85
+ * This URL MUST use the https scheme and SHOULD NOT require authentication to access.
86
+ * It MUST NOT use a user or password in the authority component of the URI.
87
+ *
88
+ * This field can be localized by specifying `tos_uri#$lang`.
89
+ */
90
+ tos_uri?: string;
91
+ } & {
92
+ [K in `${LocalizableKeys}#${string}`]?: string;
93
+ };
94
+ /**
95
+ * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
96
+ */
97
+ export declare enum OAuthGrantType {
98
+ /**
99
+ * As per RFC 6749 section 4.1, the authorization code grant lets the client obtain an access token through a browser redirect.
100
+ *
101
+ * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-grant
102
+ */
103
+ AuthorizationCode = "authorization_code",
104
+ /**
105
+ * As per RFC 6749 section 6, the refresh token grant lets the client exchange a refresh token for an access token.
106
+ *
107
+ * https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
108
+ */
109
+ RefreshToken = "refresh_token",
110
+ /**
111
+ * As per RFC 8628, the device authorization grant lets clients on devices with limited input capabilities obtain
112
+ * an access token by having the user complete authorization on a separate device with a web browser.
113
+ *
114
+ * See https://spec.matrix.org/v1.18/client-server-api/#device-authorization-grant
115
+ */
116
+ DeviceAuthorization = "urn:ietf:params:oauth:grant-type:device_code"
117
+ }
118
+ /**
119
+ * Check that URIs have a common base,
120
+ * as per https://spec.matrix.org/v1.18/client-server-api/#redirect-uri-validation
121
+ */
122
+ export declare function urlHasCommonBase(base: URL, urlStr?: string): boolean;
123
+ /**
124
+ * Response from dynamic registration
125
+ */
126
+ type RegistrationResponse = {
127
+ client_id: string;
128
+ };
129
+ /**
130
+ * Validate the given response matches the format expected for a {@link RegistrationResponse}
131
+ * @param response - the response to validate
132
+ * @throws if the response does not match the expected format
133
+ */
134
+ export declare function validateRegistrationResponse(response: unknown): response is RegistrationResponse;
135
+ export {};
136
+ //# sourceMappingURL=register.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../src/oauth/register.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,KAAK,eAAe,GAAG,aAAa,GAAG,YAAY,GAAG,YAAY,GAAG,SAAS,GAAG,UAAU,CAAC;AAE5F;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACnC;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,KAAK,GAAG,QAAQ,CAAC;IACpC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;;;;;;OAiBG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACpC;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACtC;;;;OAIG;IACH,cAAc,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACvC;;OAEG;IACH,0BAA0B,CAAC,EAAE,MAAM,CAAC;IACpC;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG;KAEC,CAAC,IAAI,GAAG,eAAe,IAAI,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM;CACjD,CAAC;AAEF;;GAEG;AACH,oBAAY,cAAc;IACtB;;;;OAIG;IACH,iBAAiB,uBAAuB;IACxC;;;;OAIG;IACH,YAAY,kBAAkB;IAC9B;;;;;OAKG;IACH,mBAAmB,iDAAiD;CACvE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAMpE;AAED;;GAEG;AACH,KAAK,oBAAoB,GAAG;IACxB,SAAS,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,oBAAoB,CAEhG"}
@@ -0,0 +1,73 @@
1
+ /*
2
+ Copyright 2023-2026 The Matrix.org Foundation C.I.C.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { hasRequiredStringProperty, isRecord } from "../@types/type-guards.js";
18
+
19
+ /**
20
+ * Request body for dynamic registration as defined by https://spec.matrix.org/v1.18/client-server-api/#client-registration
21
+ */
22
+
23
+ /**
24
+ * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
25
+ */
26
+ export let OAuthGrantType = /*#__PURE__*/function (OAuthGrantType) {
27
+ /**
28
+ * As per RFC 6749 section 4.1, the authorization code grant lets the client obtain an access token through a browser redirect.
29
+ *
30
+ * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-grant
31
+ */
32
+ OAuthGrantType["AuthorizationCode"] = "authorization_code";
33
+ /**
34
+ * As per RFC 6749 section 6, the refresh token grant lets the client exchange a refresh token for an access token.
35
+ *
36
+ * https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
37
+ */
38
+ OAuthGrantType["RefreshToken"] = "refresh_token";
39
+ /**
40
+ * As per RFC 8628, the device authorization grant lets clients on devices with limited input capabilities obtain
41
+ * an access token by having the user complete authorization on a separate device with a web browser.
42
+ *
43
+ * See https://spec.matrix.org/v1.18/client-server-api/#device-authorization-grant
44
+ */
45
+ OAuthGrantType["DeviceAuthorization"] = "urn:ietf:params:oauth:grant-type:device_code";
46
+ return OAuthGrantType;
47
+ }({});
48
+
49
+ /**
50
+ * Check that URIs have a common base,
51
+ * as per https://spec.matrix.org/v1.18/client-server-api/#redirect-uri-validation
52
+ */
53
+ export function urlHasCommonBase(base, urlStr) {
54
+ if (!urlStr) return false;
55
+ const url = new URL(urlStr);
56
+ if (url.protocol !== base.protocol) return false;
57
+ if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;
58
+ return true;
59
+ }
60
+
61
+ /**
62
+ * Response from dynamic registration
63
+ */
64
+
65
+ /**
66
+ * Validate the given response matches the format expected for a {@link RegistrationResponse}
67
+ * @param response - the response to validate
68
+ * @throws if the response does not match the expected format
69
+ */
70
+ export function validateRegistrationResponse(response) {
71
+ return isRecord(response) && hasRequiredStringProperty(response, "client_id");
72
+ }
73
+ //# sourceMappingURL=register.js.map