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
@@ -36,11 +36,11 @@ interface DehydratedDeviceResp {
36
36
  };
37
37
  }
38
38
  /**
39
- * The response body of `POST /_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device/events`.
39
+ * The response body of `GET /_matrix/client/unstable/org.matrix.msc3814.v1/dehydrated_device/{device_id}/events`.
40
40
  */
41
41
  interface DehydratedDeviceEventsResp {
42
42
  events: IToDeviceEvent[];
43
- next_batch: string;
43
+ next_batch?: string;
44
44
  }
45
45
 
46
46
  /**
@@ -267,28 +267,29 @@ export class DehydratedDeviceManager extends TypedEventEmitter<DehydratedDevices
267
267
  const path = encodeUri("/dehydrated_device/$device_id/events", {
268
268
  $device_id: dehydratedDeviceResp.device_id,
269
269
  });
270
- // eslint-disable-next-line no-constant-condition
271
- while (true) {
270
+
271
+ do {
272
272
  const eventResp: DehydratedDeviceEventsResp = await this.http.authedRequest<DehydratedDeviceEventsResp>(
273
- Method.Post,
273
+ Method.Get,
274
274
  path,
275
+ nextBatch ? { from: nextBatch } : undefined,
275
276
  undefined,
276
- nextBatch ? { next_batch: nextBatch } : {},
277
277
  {
278
278
  prefix: UnstablePrefix,
279
279
  },
280
280
  );
281
281
 
282
- if (eventResp.events.length === 0) {
283
- break;
284
- }
285
282
  toDeviceCount += eventResp.events.length;
286
283
  nextBatch = eventResp.next_batch;
287
- const roomKeyInfos = await rehydratedDevice.receiveEvents(JSON.stringify(eventResp.events));
288
- roomKeyCount += roomKeyInfos.length;
289
284
 
290
- this.emit(CryptoEvent.RehydrationProgress, roomKeyCount, toDeviceCount);
291
- }
285
+ if (eventResp.events.length > 0) {
286
+ const roomKeyInfos = await rehydratedDevice.receiveEvents(JSON.stringify(eventResp.events));
287
+ roomKeyCount += roomKeyInfos.length;
288
+
289
+ this.emit(CryptoEvent.RehydrationProgress, roomKeyCount, toDeviceCount);
290
+ }
291
+ } while (nextBatch !== undefined);
292
+
292
293
  this.logger.info(`dehydration: received ${roomKeyCount} room keys from ${toDeviceCount} to-device events`);
293
294
  this.emit(CryptoEvent.RehydrationCompleted);
294
295
 
package/src/testing.ts CHANGED
@@ -27,7 +27,7 @@ import { type RoomMember } from "./models/room-member.ts";
27
27
  import { EventType } from "./@types/event.ts";
28
28
  import { type DecryptionFailureCode } from "./crypto-api/index.ts";
29
29
  import { DecryptionError, type EventDecryptionResult } from "./common-crypto/CryptoBackend.ts";
30
- import { OAuthGrantType, type OidcClientConfig, type ValidatedAuthMetadata } from "./oidc/index.ts";
30
+ import { OAuthGrantType, type ValidatedAuthMetadata } from "./oauth/index.ts";
31
31
 
32
32
  /**
33
33
  * Create a {@link MatrixEvent}.
@@ -195,26 +195,7 @@ export async function decryptExistingEvent(
195
195
  * @returns OidcClientConfig
196
196
  * @experimental
197
197
  */
198
- export const makeDelegatedAuthConfig = (
199
- issuer = "https://auth.org/",
200
- additionalGrantTypes: string[] = [],
201
- ): OidcClientConfig => {
202
- const metadata = mockOpenIdConfiguration(issuer, additionalGrantTypes);
203
-
204
- return {
205
- ...metadata,
206
- signingKeys: null,
207
- };
208
- };
209
-
210
- /**
211
- * Useful for mocking <issuer>/.well-known/openid-configuration
212
- * @param issuer used as the base for all other urls
213
- * @param additionalGrantTypes to add to the default grant types
214
- * @returns ValidatedAuthMetadata
215
- * @experimental
216
- */
217
- export const mockOpenIdConfiguration = (
198
+ export const makeDelegatedAuthMetadata = (
218
199
  issuer = "https://auth.org/",
219
200
  additionalGrantTypes: string[] = [],
220
201
  ): ValidatedAuthMetadata => ({
@@ -224,8 +205,8 @@ export const mockOpenIdConfiguration = (
224
205
  authorization_endpoint: issuer + "auth",
225
206
  registration_endpoint: issuer + "registration",
226
207
  device_authorization_endpoint: issuer + "device",
227
- jwks_uri: issuer + "jwks",
228
208
  response_types_supported: ["code"],
229
209
  grant_types_supported: [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken, ...additionalGrantTypes],
230
210
  code_challenge_methods_supported: ["S256"],
211
+ response_modes_supported: ["query", "fragment"],
231
212
  });
@@ -1,157 +0,0 @@
1
- import { type IdTokenClaims, type SigninRequestCreateArgs } from "oidc-client-ts";
2
- import { type BearerTokenResponse, type ValidatedAuthMetadata } from "./validate.ts";
3
- export type { BearerTokenResponse };
4
- /**
5
- * Authorization parameters which are used in the authentication request of an OIDC auth code flow.
6
- *
7
- * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.
8
- */
9
- export type AuthorizationParams = {
10
- state: string;
11
- scope: string;
12
- redirectUri: string;
13
- codeVerifier: string;
14
- nonce: string;
15
- };
16
- /**
17
- * @experimental
18
- * Generate the scope used in authorization request with OIDC OP
19
- * @returns scope
20
- */
21
- export declare const generateScope: (deviceId?: string) => string;
22
- /**
23
- * Generate authorization params to pass to {@link generateAuthorizationUrl}.
24
- *
25
- * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.
26
- *
27
- * @param redirectUri - absolute url for OP to redirect to after authorization
28
- * @returns AuthorizationParams
29
- */
30
- export declare const generateAuthorizationParams: ({ redirectUri }: {
31
- redirectUri: string;
32
- }) => AuthorizationParams;
33
- /**
34
- * @deprecated use generateOidcAuthorizationUrl
35
- * Generate a URL to attempt authorization with the OP
36
- * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
37
- * @param authorizationUrl - endpoint to attempt authorization with the OP
38
- * @param clientId - id of this client as registered with the OP
39
- * @param authorizationParams - params to be used in the url
40
- * @returns a Promise with the url as a string
41
- */
42
- export declare const generateAuthorizationUrl: (authorizationUrl: string, clientId: string, { scope, redirectUri, state, nonce, codeVerifier }: AuthorizationParams) => Promise<string>;
43
- /**
44
- * @experimental
45
- * Generate a URL to attempt authorization with the OP
46
- * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
47
- * @param metadata - validated metadata from OP discovery
48
- * @param clientId - this client's id as registered with the OP
49
- * @param homeserverUrl - used to establish the session on return from the OP
50
- * @param identityServerUrl - used to establish the session on return from the OP
51
- * @param nonce - state
52
- * @param prompt - indicates to the OP which flow the user should see - eg login or registration
53
- * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter
54
- * @param urlState - value to append to the opaque state identifier to uniquely identify the callback
55
- * @param loginHint - value to send as the `login_hint` to the OP, giving a hint about the login identifier the user might use to log in.
56
- * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.
57
- * @param responseMode - value to send as the `response_mode` to the OP, selecting how auth is passed back during redirect.
58
- * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.
59
- * @returns a Promise with the url as a string
60
- */
61
- export declare const generateOidcAuthorizationUrl: ({ metadata, redirectUri, clientId, homeserverUrl, identityServerUrl, nonce, prompt, urlState, loginHint, responseMode, }: {
62
- clientId: string;
63
- metadata: ValidatedAuthMetadata;
64
- homeserverUrl: string;
65
- identityServerUrl?: string;
66
- redirectUri: string;
67
- nonce: string;
68
- prompt?: string;
69
- urlState?: string;
70
- loginHint?: string;
71
- responseMode?: SigninRequestCreateArgs["response_mode"];
72
- }) => Promise<string>;
73
- /**
74
- * @experimental
75
- * Attempt to exchange authorization code for bearer token.
76
- *
77
- * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a
78
- * request to the Token Endpoint, to obtain the access token, refresh token, etc.
79
- *
80
- * @param code - authorization code as returned by OP during authorization
81
- * @param state - authorization state param as returned by OP during authorization
82
- * @param responseMode - the response mode used for authentication
83
- * @returns valid bearer token response
84
- * @throws An `Error` with `message` set to an entry in {@link OidcError},
85
- * when the request fails, or the returned token response is invalid.
86
- */
87
- export declare const completeAuthorizationCodeGrant: (code: string, state: string, responseMode?: SigninRequestCreateArgs["response_mode"]) => Promise<{
88
- oidcClientSettings: {
89
- clientId: string;
90
- issuer: string;
91
- };
92
- tokenResponse: BearerTokenResponse;
93
- homeserverUrl: string;
94
- idTokenClaims: IdTokenClaims;
95
- identityServerUrl?: string;
96
- }>;
97
- /**
98
- * Response from the OIDC token endpoint when exchanging a token for grant_type device_code.
99
- */
100
- export interface DeviceAccessTokenResponse {
101
- id_token?: string;
102
- access_token: string;
103
- token_type: string;
104
- refresh_token?: string;
105
- scope?: string;
106
- expires_in?: number;
107
- session_state?: string;
108
- }
109
- /**
110
- * Error from the OIDC token endpoint when exchanging a token for grant_type device_code.
111
- */
112
- export interface DeviceAccessTokenError {
113
- error: string;
114
- error_description?: string;
115
- error_uri?: string;
116
- session_state?: string;
117
- }
118
- /**
119
- * Response from the OIDC device authorization endpoint.
120
- */
121
- export interface DeviceAuthorizationResponse {
122
- device_code: string;
123
- user_code: string;
124
- verification_uri: string;
125
- verification_uri_complete?: string;
126
- expires_in: number;
127
- interval?: number;
128
- }
129
- /**
130
- * Begin OIDC device authorization flow.
131
- * @param options - The device authorization parameters.
132
- * @param options.clientId - the client ID returned from client registration.
133
- * @param options.scope - the scope to request for authorization.
134
- * @param options.metadata - the validated OIDC metadata for the Identity Provider.
135
- * @returns a promise that resolves to a device access token response,
136
- * or an error response if the user denies authorization or the device code expires.
137
- */
138
- export declare const startDeviceAuthorization: ({ clientId, scope, metadata, }: {
139
- clientId: string;
140
- scope: string;
141
- metadata: ValidatedAuthMetadata;
142
- }) => Promise<DeviceAuthorizationResponse>;
143
- /**
144
- * Polls the OIDC token endpoint until we get a device access token response, or encounter an unrecoverable error.
145
- * @param options - The device authorization parameters.
146
- * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.
147
- * @param options.metadata - The validated OIDC metadata for the Identity Provider.
148
- * @param options.clientId - The client ID returned from client registration.
149
- * @returns a promise that resolves to a device access token response,
150
- * or an error response if the user denies authorization or the device code expires.
151
- */
152
- export declare const waitForDeviceAuthorization: ({ session, metadata, clientId, }: {
153
- session: DeviceAuthorizationResponse;
154
- metadata: ValidatedAuthMetadata;
155
- clientId: string;
156
- }) => Promise<DeviceAccessTokenResponse | DeviceAccessTokenError>;
157
- //# sourceMappingURL=authorize.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../src/oidc/authorize.ts"],"names":[],"mappings":"AAgBA,OAAO,EACH,KAAK,aAAa,EAGlB,KAAK,uBAAuB,EAI/B,MAAM,gBAAgB,CAAC;AAKxB,OAAO,EACH,KAAK,mBAAmB,EAGxB,KAAK,qBAAqB,EAG7B,MAAM,eAAe,CAAC;AAQvB,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC;;;;GAIG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CA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org Foundation C.I.C.
4
-
5
- Licensed under the Apache License, Version 2.0 (the "License");
6
- you may not use this file except in compliance with the License.
7
- You may obtain a copy of the License at
8
-
9
- http://www.apache.org/licenses/LICENSE-2.0
10
-
11
- Unless required by applicable law or agreed to in writing, software
12
- distributed under the License is distributed on an "AS IS" BASIS,
13
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- See the License for the specific language governing permissions and
15
- limitations under the License.
16
- */
17
-
18
- import { Log, OidcClient, SigninResponse, SigninState, WebStorageStateStore } from "oidc-client-ts";
19
- import { logger } from "../logger.js";
20
- import { secureRandomString } from "../randomstring.js";
21
- import { OidcError } from "./error.js";
22
- import { validateBearerTokenResponse, validateIdToken, validateStoredUserState } from "./validate.js";
23
- import { sha256 } from "../digest.js";
24
- import { encodeUnpaddedBase64Url } from "../base64.js";
25
- import { OAuthGrantType } from "./register.js";
26
- import { sleep } from "../utils.js";
27
- import { Method } from "../http-api/index.js";
28
-
29
- // reexport for backwards compatibility
30
-
31
- /**
32
- * Authorization parameters which are used in the authentication request of an OIDC auth code flow.
33
- *
34
- * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.
35
- */
36
-
37
- /**
38
- * @experimental
39
- * Generate the scope used in authorization request with OIDC OP
40
- * @returns scope
41
- */
42
- export const generateScope = deviceId => {
43
- const safeDeviceId = deviceId ?? secureRandomString(10);
44
- return `openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${safeDeviceId}`;
45
- };
46
-
47
- // https://www.rfc-editor.org/rfc/rfc7636
48
- const generateCodeChallenge = async codeVerifier => {
49
- if (!globalThis.crypto.subtle) {
50
- // @TODO(kerrya) should this be allowed? configurable?
51
- logger.warn("A secure context is required to generate code challenge. Using plain text code challenge");
52
- return codeVerifier;
53
- }
54
- const hashBuffer = await sha256(codeVerifier);
55
- return encodeUnpaddedBase64Url(hashBuffer);
56
- };
57
-
58
- /**
59
- * Generate authorization params to pass to {@link generateAuthorizationUrl}.
60
- *
61
- * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.
62
- *
63
- * @param redirectUri - absolute url for OP to redirect to after authorization
64
- * @returns AuthorizationParams
65
- */
66
- export const generateAuthorizationParams = ({
67
- redirectUri
68
- }) => ({
69
- scope: generateScope(),
70
- redirectUri,
71
- state: secureRandomString(8),
72
- nonce: secureRandomString(8),
73
- codeVerifier: secureRandomString(64) // https://tools.ietf.org/html/rfc7636#section-4.1 length needs to be 43-128 characters
74
- });
75
-
76
- /**
77
- * @deprecated use generateOidcAuthorizationUrl
78
- * Generate a URL to attempt authorization with the OP
79
- * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
80
- * @param authorizationUrl - endpoint to attempt authorization with the OP
81
- * @param clientId - id of this client as registered with the OP
82
- * @param authorizationParams - params to be used in the url
83
- * @returns a Promise with the url as a string
84
- */
85
- export const generateAuthorizationUrl = async (authorizationUrl, clientId, {
86
- scope,
87
- redirectUri,
88
- state,
89
- nonce,
90
- codeVerifier
91
- }) => {
92
- const url = new URL(authorizationUrl);
93
- url.searchParams.append("response_mode", "query");
94
- url.searchParams.append("response_type", "code");
95
- url.searchParams.append("redirect_uri", redirectUri);
96
- url.searchParams.append("client_id", clientId);
97
- url.searchParams.append("state", state);
98
- url.searchParams.append("scope", scope);
99
- url.searchParams.append("nonce", nonce);
100
- url.searchParams.append("code_challenge_method", "S256");
101
- url.searchParams.append("code_challenge", await generateCodeChallenge(codeVerifier));
102
- return url.toString();
103
- };
104
-
105
- /**
106
- * @experimental
107
- * Generate a URL to attempt authorization with the OP
108
- * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
109
- * @param metadata - validated metadata from OP discovery
110
- * @param clientId - this client's id as registered with the OP
111
- * @param homeserverUrl - used to establish the session on return from the OP
112
- * @param identityServerUrl - used to establish the session on return from the OP
113
- * @param nonce - state
114
- * @param prompt - indicates to the OP which flow the user should see - eg login or registration
115
- * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter
116
- * @param urlState - value to append to the opaque state identifier to uniquely identify the callback
117
- * @param loginHint - value to send as the `login_hint` to the OP, giving a hint about the login identifier the user might use to log in.
118
- * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.
119
- * @param responseMode - value to send as the `response_mode` to the OP, selecting how auth is passed back during redirect.
120
- * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.
121
- * @returns a Promise with the url as a string
122
- */
123
- export const generateOidcAuthorizationUrl = async ({
124
- metadata,
125
- redirectUri,
126
- clientId,
127
- homeserverUrl,
128
- identityServerUrl,
129
- nonce,
130
- prompt,
131
- urlState,
132
- loginHint,
133
- responseMode = "query"
134
- }) => {
135
- const scope = generateScope();
136
- const oidcClient = new OidcClient(_objectSpread(_objectSpread({}, metadata), {}, {
137
- client_id: clientId,
138
- redirect_uri: redirectUri,
139
- authority: metadata.issuer,
140
- response_mode: responseMode,
141
- response_type: "code",
142
- scope,
143
- stateStore: new WebStorageStateStore({
144
- prefix: "mx_oidc_",
145
- store: window.sessionStorage
146
- })
147
- }));
148
- const userState = {
149
- homeserverUrl,
150
- nonce,
151
- identityServerUrl
152
- };
153
- const request = await oidcClient.createSigninRequest({
154
- state: userState,
155
- nonce,
156
- prompt,
157
- url_state: urlState,
158
- login_hint: loginHint
159
- });
160
- return request.url;
161
- };
162
-
163
- /**
164
- * Normalize token_type to use capital case to make consuming the token response easier
165
- * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: "bearer"
166
- * Later, when used in auth headers it is case sensitive and must be Bearer
167
- * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4
168
- *
169
- * @param response - validated token response
170
- * @returns response with token_type set to 'Bearer'
171
- */
172
- const normalizeBearerTokenResponseTokenType = response => ({
173
- id_token: response.id_token,
174
- scope: response.scope,
175
- expires_at: response.expires_at,
176
- refresh_token: response.refresh_token,
177
- access_token: response.access_token,
178
- token_type: "Bearer"
179
- });
180
-
181
- /**
182
- * @experimental
183
- * Attempt to exchange authorization code for bearer token.
184
- *
185
- * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a
186
- * request to the Token Endpoint, to obtain the access token, refresh token, etc.
187
- *
188
- * @param code - authorization code as returned by OP during authorization
189
- * @param state - authorization state param as returned by OP during authorization
190
- * @param responseMode - the response mode used for authentication
191
- * @returns valid bearer token response
192
- * @throws An `Error` with `message` set to an entry in {@link OidcError},
193
- * when the request fails, or the returned token response is invalid.
194
- */
195
- export const completeAuthorizationCodeGrant = async (code, state, responseMode = "query") => {
196
- /**
197
- * Element Web strips and changes the url on starting the app
198
- * Use the code and state from query params to rebuild a url
199
- * so that oidc-client can parse it
200
- */
201
- const reconstructedUrl = new URL(window.location.origin);
202
- const params = new URLSearchParams({
203
- code,
204
- state
205
- });
206
- if (responseMode === "query") {
207
- reconstructedUrl.search = params.toString();
208
- } else {
209
- reconstructedUrl.hash = `#${params.toString()}`;
210
- }
211
-
212
- // set oidc-client to use our logger
213
- Log.setLogger(logger);
214
- try {
215
- const response = new SigninResponse(params);
216
- const stateStore = new WebStorageStateStore({
217
- prefix: "mx_oidc_",
218
- store: window.sessionStorage
219
- });
220
-
221
- // retrieve the state we put in storage at the start of oidc auth flow
222
- const stateString = await stateStore.get(response.state);
223
- if (!stateString) {
224
- throw new Error(OidcError.MissingOrInvalidStoredState);
225
- }
226
-
227
- // hydrate the sign in state and create a client
228
- // the stored sign in state includes oidc configuration we set at the start of the oidc login flow
229
- const signInState = await SigninState.fromStorageString(stateString);
230
- const client = new OidcClient(_objectSpread(_objectSpread({}, signInState), {}, {
231
- stateStore
232
- }));
233
-
234
- // validate the code and state, and attempt to swap the code for tokens
235
- const signinResponse = await client.processSigninResponse(reconstructedUrl.href);
236
-
237
- // extra values we stored at the start of the login flow
238
- // used to complete login in the client
239
- const userState = signinResponse.userState;
240
- validateStoredUserState(userState);
241
-
242
- // throws when response is invalid
243
- validateBearerTokenResponse(signinResponse);
244
- if (signinResponse.id_token) {
245
- // The token is not yet in the Matrix spec so consider it optional
246
- // throws when token is invalid
247
- validateIdToken(signinResponse.id_token, client.settings.authority, client.settings.client_id, userState.nonce);
248
- }
249
- const normalizedTokenResponse = normalizeBearerTokenResponseTokenType(signinResponse);
250
- return {
251
- oidcClientSettings: {
252
- clientId: client.settings.client_id,
253
- issuer: client.settings.authority
254
- },
255
- tokenResponse: normalizedTokenResponse,
256
- homeserverUrl: userState.homeserverUrl,
257
- identityServerUrl: userState.identityServerUrl,
258
- idTokenClaims: signinResponse.profile
259
- };
260
- } catch (error) {
261
- logger.error("Oidc login failed", error);
262
- const errorType = error.message;
263
-
264
- // rethrow errors that we recognise
265
- if (Object.values(OidcError).includes(errorType)) {
266
- throw error;
267
- }
268
- throw new Error(OidcError.CodeExchangeFailed);
269
- }
270
- };
271
-
272
- /**
273
- * Response from the OIDC token endpoint when exchanging a token for grant_type device_code.
274
- */
275
-
276
- /**
277
- * Error from the OIDC token endpoint when exchanging a token for grant_type device_code.
278
- */
279
-
280
- /**
281
- * Response from the OIDC device authorization endpoint.
282
- */
283
-
284
- /**
285
- * Begin OIDC device authorization flow.
286
- * @param options - The device authorization parameters.
287
- * @param options.clientId - the client ID returned from client registration.
288
- * @param options.scope - the scope to request for authorization.
289
- * @param options.metadata - the validated OIDC metadata for the Identity Provider.
290
- * @returns a promise that resolves to a device access token response,
291
- * or an error response if the user denies authorization or the device code expires.
292
- */
293
- export const startDeviceAuthorization = async ({
294
- clientId,
295
- scope,
296
- metadata
297
- }) => {
298
- const body = new URLSearchParams({
299
- client_id: clientId,
300
- scope: scope
301
- }).toString();
302
- const url = metadata.device_authorization_endpoint;
303
- if (!url) {
304
- throw new Error("No device_authorization_endpoint given");
305
- }
306
- const response = await fetch(url, {
307
- method: Method.Post,
308
- headers: {
309
- "Content-Type": "application/x-www-form-urlencoded"
310
- },
311
- body
312
- });
313
- return await response.json();
314
- };
315
-
316
- /**
317
- * Polls the OIDC token endpoint until we get a device access token response, or encounter an unrecoverable error.
318
- * @param options - The device authorization parameters.
319
- * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.
320
- * @param options.metadata - The validated OIDC metadata for the Identity Provider.
321
- * @param options.clientId - The client ID returned from client registration.
322
- * @returns a promise that resolves to a device access token response,
323
- * or an error response if the user denies authorization or the device code expires.
324
- */
325
- export const waitForDeviceAuthorization = async ({
326
- session,
327
- metadata,
328
- clientId
329
- }) => {
330
- let interval = (session.interval ?? 5) * 1000; // poll interval
331
- const expiration = Date.now() + session.expires_in * 1000;
332
- do {
333
- const body = new URLSearchParams({
334
- device_code: session.device_code,
335
- grant_type: OAuthGrantType.DeviceAuthorization,
336
- client_id: clientId
337
- }).toString();
338
- const response = await fetch(metadata.token_endpoint, {
339
- method: Method.Post,
340
- headers: {
341
- "Content-Type": "application/x-www-form-urlencoded"
342
- },
343
- body
344
- });
345
- if (response.ok) {
346
- return await response.json();
347
- }
348
- const errorResponse = await response.json();
349
- switch (errorResponse.error) {
350
- case "authorization_pending":
351
- break;
352
- case "slow_down":
353
- interval += 5000;
354
- break;
355
- case "access_denied":
356
- case "expired_token":
357
- return errorResponse;
358
- }
359
- await sleep(interval);
360
- } while (Date.now() < expiration);
361
- return {
362
- error: "expired"
363
- };
364
- };
365
- //# sourceMappingURL=authorize.js.map