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,297 @@
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
+ import {
18
+ type BearerTokenResponse,
19
+ type DeviceAccessTokenError,
20
+ type DeviceAccessTokenResponse,
21
+ type DeviceAuthorizationResponse,
22
+ generateScope,
23
+ normalizeBearerTokenResponseTokenType,
24
+ startDeviceAuthorization,
25
+ validateBearerTokenResponse,
26
+ waitForDeviceAuthorization,
27
+ } from "./authorize.ts";
28
+ import type { ValidatedAuthMetadata } from "./discover.ts";
29
+ import {
30
+ OAuthGrantType,
31
+ type OAuthRegistrationRequest,
32
+ urlHasCommonBase,
33
+ validateRegistrationResponse,
34
+ } from "./register.ts";
35
+ import { encodeUnpaddedBase64Url } from "../base64.ts";
36
+ import { sha256 } from "../digest.ts";
37
+ import { HTTPError, Method } from "../http-api";
38
+ import { logger } from "../logger.ts";
39
+ import { OAuth2Error } from "./error.ts";
40
+ import { secureRandomString } from "../randomstring.ts";
41
+ import { type NonEmptyArray } from "../@types/common.ts";
42
+
43
+ export * from "./authorize.ts";
44
+ export * from "./error.ts";
45
+ export * from "./register.ts";
46
+ export * from "./tokenRefresher.ts";
47
+ export * from "./discover.ts";
48
+
49
+ /**
50
+ * Type representing the persistent context needed for typical OAuth flows
51
+ */
52
+ type Context = {
53
+ /** The OAuth client ID */
54
+ clientId: string;
55
+ /** The desired device ID */
56
+ deviceId?: string;
57
+ /** The seed used to generate the challenge code */
58
+ codeVerifier?: string;
59
+ /** The URI to redirect the user to with credentials after auth */
60
+ redirectUri: string;
61
+ };
62
+
63
+ export class OAuth2 {
64
+ /**
65
+ * Attempts dynamic registration against the configured registration endpoint.
66
+ * Will ignore any URIs that do not use client_uri as a common base as per the spec.
67
+ * @param authMetadata - Auth config from {@link MatrixClient.getAuthMetadata}
68
+ * @param clientMetadata - The metadata for the client which to register,
69
+ * grant_types & response_types & token_endpoint_auth_method will be sanely calculated if omitted.
70
+ * @returns Promise<string> resolved with registered clientId
71
+ * @throws when registration is not supported, on failed request or invalid response
72
+ */
73
+ public static async registerClient(
74
+ authMetadata: ValidatedAuthMetadata,
75
+ clientMetadata: OAuthRegistrationRequest,
76
+ ): Promise<string> {
77
+ const defaultGrantTypes: NonEmptyArray<string> = [
78
+ OAuthGrantType.AuthorizationCode,
79
+ OAuthGrantType.RefreshToken,
80
+ ];
81
+ // ask for device authorization grant if supported
82
+ if (authMetadata.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
83
+ defaultGrantTypes.push(OAuthGrantType.DeviceAuthorization);
84
+ }
85
+
86
+ const grantTypes = clientMetadata.grant_types ?? defaultGrantTypes;
87
+ if (grantTypes.some((scope) => !authMetadata.grant_types_supported.includes(scope))) {
88
+ throw new Error(OAuth2Error.DynamicRegistrationNotSupported);
89
+ }
90
+
91
+ const commonBase = new URL(clientMetadata.client_uri);
92
+
93
+ const request: OAuthRegistrationRequest = {
94
+ // Apply some defaults
95
+ response_types: ["code"],
96
+ token_endpoint_auth_method: "none",
97
+ ...clientMetadata,
98
+ grant_types: grantTypes,
99
+ logo_uri: urlHasCommonBase(commonBase, clientMetadata.logo_uri) ? clientMetadata.logo_uri : undefined,
100
+ policy_uri: urlHasCommonBase(commonBase, clientMetadata.policy_uri) ? clientMetadata.policy_uri : undefined,
101
+ tos_uri: urlHasCommonBase(commonBase, clientMetadata.tos_uri) ? clientMetadata.tos_uri : undefined,
102
+ };
103
+
104
+ try {
105
+ const response = await fetch(authMetadata.registration_endpoint, {
106
+ method: Method.Post,
107
+ headers: {
108
+ "Accept": "application/json",
109
+ "Content-Type": "application/json",
110
+ },
111
+ body: JSON.stringify(request),
112
+ });
113
+
114
+ if (response.status >= 400) {
115
+ throw new Error(OAuth2Error.DynamicRegistrationFailed);
116
+ }
117
+
118
+ const registrationResponse = await response.json();
119
+ if (validateRegistrationResponse(registrationResponse)) {
120
+ return registrationResponse.client_id;
121
+ }
122
+
123
+ throw new Error(OAuth2Error.DynamicRegistrationInvalid);
124
+ } catch (error) {
125
+ if (Object.values(OAuth2Error).includes((error as Error).message as OAuth2Error)) {
126
+ throw error;
127
+ } else {
128
+ logger.error("Dynamic registration request failed", error);
129
+ throw new Error(OAuth2Error.DynamicRegistrationFailed);
130
+ }
131
+ }
132
+ }
133
+
134
+ public readonly context: Required<Context>;
135
+
136
+ public constructor(
137
+ public readonly metadata: ValidatedAuthMetadata,
138
+ context: Context,
139
+ ) {
140
+ this.context = {
141
+ clientId: context.clientId,
142
+ redirectUri: context.redirectUri,
143
+ deviceId: context.deviceId ?? secureRandomString(10),
144
+ codeVerifier: context.codeVerifier ?? secureRandomString(96),
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Generate a URL to attempt authorization with the OP
150
+ * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-flow
151
+ * @param state - A unique opaque identifier, like a transaction ID,
152
+ * that will allow the client to maintain state between the authorization request and the callback.
153
+ * The app should use this to key the storage for where the rest of the auth context is saved.
154
+ * @param responseMode - The manner in which the IdP should send the secrets back to the app. Defaults to `fragment` for privacy.
155
+ * @param prompt - Optional prompt parameter to pass to the IdP to signal intent, e.g. `create` for User registration.
156
+ * @param scope - The OAuth2 scope to request, will be generated based on the device ID if omitted.
157
+ * @returns a Promise with the url as a string
158
+ */
159
+ public async generateAuthorizationCodeGrantUrl(
160
+ state: string,
161
+ responseMode: "fragment" | "query" = "fragment",
162
+ prompt?: string,
163
+ scope?: string,
164
+ ): Promise<string> {
165
+ const challenge = encodeUnpaddedBase64Url(await sha256(this.context.codeVerifier));
166
+
167
+ const url = new URL(this.metadata.authorization_endpoint);
168
+ url.searchParams.set("response_type", "code");
169
+ url.searchParams.set("response_mode", responseMode);
170
+ url.searchParams.set("client_id", this.context.clientId);
171
+ url.searchParams.set("redirect_uri", this.context.redirectUri);
172
+ url.searchParams.set("scope", scope ?? generateScope(this.context.deviceId));
173
+ url.searchParams.set("state", state);
174
+ url.searchParams.set("code_challenge_method", "S256");
175
+ url.searchParams.set("code_challenge", challenge);
176
+
177
+ if (prompt) {
178
+ url.searchParams.set("prompt", prompt);
179
+ }
180
+
181
+ return url.toString();
182
+ }
183
+
184
+ /**
185
+ * Attempt to exchange authorization code for bearer token.
186
+ *
187
+ * Takes the authorization code returned by the OAuth2 Provider via the authorization URL, and makes a
188
+ * request to the Token Endpoint, to obtain the access token, refresh token, etc.
189
+ *
190
+ * @param code - authorization code as returned by IdP during authorization
191
+ * @returns a validated bearer token response
192
+ * @throws An `Error` with `message` set to an entry in {@link OAuth2Error},
193
+ * when the request fails, or the returned token response is invalid.
194
+ */
195
+ public async completeAuthorizationCodeGrant(code: string): Promise<BearerTokenResponse> {
196
+ const params = new URLSearchParams();
197
+ params.append("grant_type", "authorization_code");
198
+ params.append("client_id", this.context.clientId);
199
+ params.append("code_verifier", this.context.codeVerifier);
200
+ params.append("redirect_uri", this.context.redirectUri);
201
+ params.append("code", code);
202
+
203
+ const tokenResponse = await this.fetch("token", params, OAuth2Error.CodeExchangeFailed);
204
+
205
+ // throws when response is invalid
206
+ validateBearerTokenResponse(tokenResponse);
207
+ return normalizeBearerTokenResponseTokenType(tokenResponse);
208
+ }
209
+
210
+ /**
211
+ * Refresh the access token using the given refresh token and the refresh token grant
212
+ * @param refreshToken - the token to use to refresh the access token
213
+ */
214
+ public async performRefreshTokenGrant(refreshToken: string): Promise<BearerTokenResponse> {
215
+ const params = new URLSearchParams();
216
+ params.append("grant_type", "refresh_token");
217
+ params.append("client_id", this.context.clientId);
218
+ params.append("refresh_token", refreshToken);
219
+
220
+ const tokenResponse = await this.fetch("token", params, OAuth2Error.RefreshTokenFailed);
221
+
222
+ // throws when response is invalid
223
+ validateBearerTokenResponse(tokenResponse);
224
+ return normalizeBearerTokenResponseTokenType(tokenResponse);
225
+ }
226
+
227
+ /**
228
+ * Revokes the given token
229
+ * @param token - the token to remove
230
+ * @param type - the type of token, acts as a hint to the IdP
231
+ */
232
+ public async revokeToken(token: string, type?: "access_token" | "refresh_token"): Promise<void> {
233
+ const params = new URLSearchParams();
234
+ params.append("token", token);
235
+ params.append("client_id", this.context.clientId);
236
+ if (type) {
237
+ params.append("token_type_hint", type);
238
+ }
239
+
240
+ await this.fetch("revocation", params, OAuth2Error.RevokeTokenFailed);
241
+
242
+ const headers = new Headers();
243
+ headers.set("Content-Type", "application/x-www-form-urlencoded");
244
+ }
245
+
246
+ /**
247
+ * Begin OAuth2 device authorization flow.
248
+ * @param scope - the scope to request for authorization.
249
+ * @returns a promise that resolves to a device access token response,
250
+ * or an error response if the user denies authorization or the device code expires.
251
+ */
252
+ public async startDeviceAuthorizationGrant(scope?: string): Promise<DeviceAuthorizationResponse> {
253
+ return startDeviceAuthorization({
254
+ scope: scope ?? generateScope(this.context.deviceId),
255
+ metadata: this.metadata,
256
+ clientId: this.context.clientId,
257
+ });
258
+ }
259
+
260
+ /**
261
+ * Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.
262
+ * @param session - The session returned from a previous call to {@link OAuth2.startDeviceAuthorizationGrant}.
263
+ * @returns a promise that resolves to a device access token response,
264
+ * or an error response if the user denies authorization or the device code expires.
265
+ */
266
+ public async waitForDeviceAuthorizationGrant(
267
+ session: DeviceAuthorizationResponse,
268
+ ): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> {
269
+ return waitForDeviceAuthorization({
270
+ session,
271
+ metadata: this.metadata,
272
+ clientId: this.context.clientId,
273
+ });
274
+ }
275
+
276
+ private async fetch(
277
+ target: "token" | "registration" | "revocation",
278
+ params: URLSearchParams,
279
+ error: OAuth2Error,
280
+ ): Promise<unknown> {
281
+ const url = this.metadata[`${target}_endpoint`];
282
+ const res = await fetch(url, {
283
+ method: Method.Post,
284
+ headers: {
285
+ "Content-Type": "application/x-www-form-urlencoded",
286
+ "Accept": "application/json",
287
+ },
288
+ body: params,
289
+ });
290
+
291
+ if (res.status >= 400) {
292
+ throw new HTTPError(error, res.status, res.headers);
293
+ }
294
+
295
+ return await res.json();
296
+ }
297
+ }
@@ -0,0 +1,166 @@
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 { type NonEmptyArray } from "../@types/common.ts";
18
+ import { hasRequiredStringProperty, isRecord } from "../@types/type-guards.ts";
19
+
20
+ type LocalizableKeys = "client_name" | "client_uri" | "policy_uri" | "tos_uri" | "logo_uri";
21
+
22
+ /**
23
+ * Request body for dynamic registration as defined by https://spec.matrix.org/v1.18/client-server-api/#client-registration
24
+ */
25
+ export type OAuthRegistrationRequest = {
26
+ /**
27
+ * Kind of the application.
28
+ *
29
+ * The homeserver MUST support the web and native values to be able to perform redirect URI validation.
30
+ *
31
+ * Defaults to web if omitted.
32
+ */
33
+ application_type?: "web" | "native";
34
+ /**
35
+ * Human-readable name of the client to be presented to the user.
36
+ *
37
+ * This field can be localized by specifying `client_name#$lang`.
38
+ */
39
+ client_name?: string;
40
+ /**
41
+ * A URL to a valid web page that SHOULD give the user more information about the client.
42
+ *
43
+ * This URL MUST use the https scheme and SHOULD NOT require authentication to access.
44
+ * It MUST NOT use a user or password in the authority component of the URI.
45
+ *
46
+ * The server MAY reject client registrations if this field is invalid or missing.
47
+ *
48
+ * This URI is a common base for all the other URIs in the metadata:
49
+ * those MUST be either on the same host or on a subdomain of the host of the client_uri.
50
+ * The port number, path and query components MAY be different.
51
+ *
52
+ * For example, if the client_uri is https://example.com/,
53
+ * then one of the redirect_uris can be https://example.com/callback or https://app.example.com/callback,
54
+ * but not https://app.com/callback.
55
+ *
56
+ * This field can be localized by specifying `client_uri#$lang`.
57
+ */
58
+ client_uri: string;
59
+ /**
60
+ * Array of the OAuth 2.0 grant types that the client may use.
61
+ *
62
+ * This MUST include:
63
+ *
64
+ * the authorization_code value to use the authorization code grant,
65
+ * the refresh_token value to use the refresh token grant.
66
+ */
67
+ grant_types?: NonEmptyArray<string>;
68
+ /**
69
+ * URL that references a logo for the client.
70
+ *
71
+ * This URL MUST use the https scheme.
72
+ *
73
+ * This field can be localized by specifying `logo_uri#$lang`.
74
+ */
75
+ logo_uri?: string;
76
+ /**
77
+ * URL that points to a human-readable policy document for the client.
78
+ *
79
+ * This URL MUST use the https scheme and SHOULD NOT require authentication to access.
80
+ * It MUST NOT use a user or password in the authority component of the URI.
81
+ *
82
+ * This field can be localized by specifying `policy_uri#$lang`.
83
+ */
84
+ policy_uri?: string;
85
+ /**
86
+ * Array of redirection URIs for use in redirect-based flows.
87
+ *
88
+ * At least one URI is required to use the authorization code grant.
89
+ */
90
+ redirect_uris?: NonEmptyArray<string>;
91
+ /**
92
+ * Array of the OAuth 2.0 response types that the client may use.
93
+ *
94
+ * This MUST include the code value to use the authorization code grant.
95
+ */
96
+ response_types?: NonEmptyArray<string>;
97
+ /**
98
+ * String indicator of the requested authentication method for the token endpoint.
99
+ */
100
+ token_endpoint_auth_method?: string;
101
+ /**
102
+ * URL that points to a human-readable terms of service document for the client.
103
+ *
104
+ * This URL MUST use the https scheme and SHOULD NOT require authentication to access.
105
+ * It MUST NOT use a user or password in the authority component of the URI.
106
+ *
107
+ * This field can be localized by specifying `tos_uri#$lang`.
108
+ */
109
+ tos_uri?: string;
110
+ } & {
111
+ // --- Dynamic Localized Fields (e.g., client_name#es-ES) ---
112
+ [K in `${LocalizableKeys}#${string}`]?: string;
113
+ };
114
+
115
+ /**
116
+ * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
117
+ */
118
+ export enum OAuthGrantType {
119
+ /**
120
+ * As per RFC 6749 section 4.1, the authorization code grant lets the client obtain an access token through a browser redirect.
121
+ *
122
+ * See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-grant
123
+ */
124
+ AuthorizationCode = "authorization_code",
125
+ /**
126
+ * As per RFC 6749 section 6, the refresh token grant lets the client exchange a refresh token for an access token.
127
+ *
128
+ * https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
129
+ */
130
+ RefreshToken = "refresh_token",
131
+ /**
132
+ * As per RFC 8628, the device authorization grant lets clients on devices with limited input capabilities obtain
133
+ * an access token by having the user complete authorization on a separate device with a web browser.
134
+ *
135
+ * See https://spec.matrix.org/v1.18/client-server-api/#device-authorization-grant
136
+ */
137
+ DeviceAuthorization = "urn:ietf:params:oauth:grant-type:device_code",
138
+ }
139
+
140
+ /**
141
+ * Check that URIs have a common base,
142
+ * as per https://spec.matrix.org/v1.18/client-server-api/#redirect-uri-validation
143
+ */
144
+ export function urlHasCommonBase(base: URL, urlStr?: string): boolean {
145
+ if (!urlStr) return false;
146
+ const url = new URL(urlStr);
147
+ if (url.protocol !== base.protocol) return false;
148
+ if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;
149
+ return true;
150
+ }
151
+
152
+ /**
153
+ * Response from dynamic registration
154
+ */
155
+ type RegistrationResponse = {
156
+ client_id: string;
157
+ };
158
+
159
+ /**
160
+ * Validate the given response matches the format expected for a {@link RegistrationResponse}
161
+ * @param response - the response to validate
162
+ * @throws if the response does not match the expected format
163
+ */
164
+ export function validateRegistrationResponse(response: unknown): response is RegistrationResponse {
165
+ return isRecord(response) && hasRequiredStringProperty(response, "client_id");
166
+ }
@@ -0,0 +1,77 @@
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
+ import { type AccessTokens, HTTPError, type TokenRefreshFunction, TokenRefreshLogoutError } from "../http-api/index.ts";
18
+ import { type OAuth2 } from "./index.ts";
19
+
20
+ /**
21
+ * Class responsible for refreshing OAuth2 access tokens
22
+ */
23
+ export class TokenRefresher {
24
+ private inflightRefreshRequest?: Promise<AccessTokens>;
25
+
26
+ public constructor(
27
+ private readonly auth: OAuth2,
28
+ private readonly onRefresh: (tokens: AccessTokens) => Promise<void>,
29
+ ) {}
30
+
31
+ /**
32
+ * Attempt token refresh using given refresh token
33
+ * @param refreshToken - refresh token to use in request with token issuer
34
+ * @returns tokens - Promise that resolves with new access and refresh tokens
35
+ * @throws when token refresh fails
36
+ */
37
+ public tokenRefreshFunction: TokenRefreshFunction = async (refreshToken: string): Promise<AccessTokens> => {
38
+ if (!this.inflightRefreshRequest) {
39
+ this.inflightRefreshRequest = this.getNewTokens(refreshToken);
40
+ }
41
+
42
+ try {
43
+ const tokens = await this.inflightRefreshRequest;
44
+ return tokens;
45
+ } catch (e) {
46
+ // If we encounter a 40x error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError
47
+ if (e instanceof HTTPError && this.shouldLogoutOnError(e)) {
48
+ throw new TokenRefreshLogoutError(e);
49
+ }
50
+ throw e;
51
+ } finally {
52
+ this.inflightRefreshRequest = undefined;
53
+ }
54
+ };
55
+
56
+ private shouldLogoutOnError(error: HTTPError): boolean {
57
+ // As per https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
58
+ return typeof error.httpStatus === "number" && error.httpStatus < 500 && error.httpStatus >= 400;
59
+ }
60
+
61
+ private async getNewTokens(refreshToken: string): Promise<AccessTokens> {
62
+ const requestStart = Date.now();
63
+
64
+ const response = await this.auth.performRefreshTokenGrant(refreshToken);
65
+
66
+ const tokens = {
67
+ accessToken: response.access_token,
68
+ refreshToken: response.refresh_token,
69
+ // We use the request start time to calculate the expiry time as we don't know when the server received our request
70
+ expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined,
71
+ } satisfies AccessTokens;
72
+
73
+ await this.onRefresh(tokens);
74
+
75
+ return tokens;
76
+ }
77
+ }
@@ -35,8 +35,7 @@ import {
35
35
  startDeviceAuthorization,
36
36
  type ValidatedAuthMetadata,
37
37
  waitForDeviceAuthorization,
38
- type OidcClientConfig,
39
- } from "../oidc/index.ts";
38
+ } from "../oauth/index.ts";
40
39
  import { type CryptoApi } from "../crypto-api/index.ts";
41
40
 
42
41
  /**
@@ -113,7 +112,7 @@ interface SecretsPayload extends MSC4108Payload, Awaited<ReturnType<NonNullable<
113
112
 
114
113
  /**
115
114
  * Prototype of the unstable [MSC4108](https://github.com/matrix-org/matrix-spec-proposals/pull/4108)
116
- * sign in with QR + OIDC flow.
115
+ * sign in with QR + OAuth2 flow.
117
116
  * @experimental Note that this is UNSTABLE and may have breaking changes without notice.
118
117
  */
119
118
  export class MSC4108SignInWithQR {
@@ -182,7 +181,7 @@ export class MSC4108SignInWithQR {
182
181
  }
183
182
 
184
183
  /**
185
- * The first step in the OIDC QR login process.
184
+ * The first step in the OAuth2 QR login process.
186
185
  * To be called after the QR code has been rendered or scanned.
187
186
  * The scanning device has to discover the homeserver details, if they scanned the code then they already have it.
188
187
  * If the new device is the one rendering the QR code then it has to wait be sent the homeserver details via the rendezvous channel.
@@ -198,14 +197,14 @@ export class MSC4108SignInWithQR {
198
197
  // MSC4108-Flow: ExistingScanned - take homeserver from QR code which should already be set
199
198
  } else {
200
199
  // MSC4108-Flow: NewScanned -send protocols message
201
- let oidcClientConfig: OidcClientConfig | undefined;
200
+ let authMetadata: ValidatedAuthMetadata | undefined;
202
201
  try {
203
- oidcClientConfig = await this.client!.getAuthMetadata();
202
+ authMetadata = await this.client!.getAuthMetadata();
204
203
  } catch (e) {
205
- logger.error("Failed to discover OIDC metadata", e);
204
+ logger.error("Failed to discover OAuth2 metadata", e);
206
205
  }
207
206
 
208
- if (oidcClientConfig?.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
207
+ if (authMetadata?.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
209
208
  await this.send<ProtocolsPayload>({
210
209
  type: PayloadType.Protocols,
211
210
  protocols: ["device_authorization_grant"],
@@ -250,9 +249,9 @@ export class MSC4108SignInWithQR {
250
249
  }
251
250
 
252
251
  /**
253
- * The second & third step in the OIDC QR login process.
252
+ * The second & third step in the OAuth2 QR login process.
254
253
  * To be called after `negotiateProtocols` for the existing device.
255
- * To be called after OIDC negotiation for the new device.
254
+ * To be called after OAuth2 negotiation for the new device.
256
255
  *
257
256
  * @param input - Required for the new device to start the device authorization grant, not required for the existing device reciprocating the login
258
257
  */
@@ -362,7 +361,7 @@ export class MSC4108SignInWithQR {
362
361
  }
363
362
 
364
363
  /**
365
- * The fourth step in the OIDC QR login process.
364
+ * The fourth step in the OAuth2 QR login process.
366
365
  * The reciprocating device must perform step 5 for this method to resolve.
367
366
  * To be called after {@link deviceAuthorizationGrant} only on the new device.
368
367
  */
@@ -426,7 +425,7 @@ export class MSC4108SignInWithQR {
426
425
  }
427
426
 
428
427
  /**
429
- * The fifth (and final) step in the OIDC QR login process.
428
+ * The fifth (and final) step in the OAuth2 QR login process.
430
429
  * To be called after the new device has completed authentication.
431
430
  */
432
431
  public async shareSecrets(): Promise<{ secrets?: Omit<SecretsPayload, "type"> }> {
@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import { type MatrixClient, OAuthGrantType, type OidcClientConfig } from "../matrix.ts";
17
+ import { type MatrixClient, OAuthGrantType, type ValidatedAuthMetadata } from "../matrix.ts";
18
18
  import { MSC4108FailureReason, type RendezvousFailureListener } from "./RendezvousFailureReason.ts";
19
19
  import { MSC4108SignInWithQR } from "./MSC4108SignInWithQR.ts";
20
20
  import { MSC4108RendezvousSession } from "./transports/MSC4108RendezvousSession.ts";
@@ -39,7 +39,7 @@ export * from "./channels/index.ts";
39
39
  * @returns true if the homeserver that the client is connected to supports a variant of sign-in with QR that we can use, false otherwise.
40
40
  */
41
41
  export async function isSignInWithQRAvailable(client: MatrixClient): Promise<boolean> {
42
- let metadata: OidcClientConfig;
42
+ let metadata: ValidatedAuthMetadata;
43
43
  try {
44
44
  metadata = await client.getAuthMetadata();
45
45
  } catch (e) {