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
@@ -1,431 +0,0 @@
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 IdTokenClaims,
19
- Log,
20
- OidcClient,
21
- type SigninRequestCreateArgs,
22
- SigninResponse,
23
- SigninState,
24
- WebStorageStateStore,
25
- } from "oidc-client-ts";
26
-
27
- import { logger } from "../logger.ts";
28
- import { secureRandomString } from "../randomstring.ts";
29
- import { OidcError } from "./error.ts";
30
- import {
31
- type BearerTokenResponse,
32
- type UserState,
33
- validateBearerTokenResponse,
34
- type ValidatedAuthMetadata,
35
- validateIdToken,
36
- validateStoredUserState,
37
- } from "./validate.ts";
38
- import { sha256 } from "../digest.ts";
39
- import { encodeUnpaddedBase64Url } from "../base64.ts";
40
- import { OAuthGrantType } from "./register.ts";
41
- import { sleep } from "../utils.ts";
42
- import { Method } from "../http-api/index.ts";
43
-
44
- // reexport for backwards compatibility
45
- export type { BearerTokenResponse };
46
-
47
- /**
48
- * Authorization parameters which are used in the authentication request of an OIDC auth code flow.
49
- *
50
- * See https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters.
51
- */
52
- export type AuthorizationParams = {
53
- state: string;
54
- scope: string;
55
- redirectUri: string;
56
- codeVerifier: string;
57
- nonce: string;
58
- };
59
-
60
- /**
61
- * @experimental
62
- * Generate the scope used in authorization request with OIDC OP
63
- * @returns scope
64
- */
65
- export const generateScope = (deviceId?: string): string => {
66
- const safeDeviceId = deviceId ?? secureRandomString(10);
67
- return `openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${safeDeviceId}`;
68
- };
69
-
70
- // https://www.rfc-editor.org/rfc/rfc7636
71
- const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
72
- if (!globalThis.crypto.subtle) {
73
- // @TODO(kerrya) should this be allowed? configurable?
74
- logger.warn("A secure context is required to generate code challenge. Using plain text code challenge");
75
- return codeVerifier;
76
- }
77
-
78
- const hashBuffer = await sha256(codeVerifier);
79
- return encodeUnpaddedBase64Url(hashBuffer);
80
- };
81
-
82
- /**
83
- * Generate authorization params to pass to {@link generateAuthorizationUrl}.
84
- *
85
- * Used as part of an authorization code OIDC flow: see https://openid.net/specs/openid-connect-basic-1_0.html#CodeFlow.
86
- *
87
- * @param redirectUri - absolute url for OP to redirect to after authorization
88
- * @returns AuthorizationParams
89
- */
90
- export const generateAuthorizationParams = ({ redirectUri }: { redirectUri: string }): AuthorizationParams => ({
91
- scope: generateScope(),
92
- redirectUri,
93
- state: secureRandomString(8),
94
- nonce: secureRandomString(8),
95
- codeVerifier: secureRandomString(64), // https://tools.ietf.org/html/rfc7636#section-4.1 length needs to be 43-128 characters
96
- });
97
-
98
- /**
99
- * @deprecated use generateOidcAuthorizationUrl
100
- * Generate a URL to attempt authorization with the OP
101
- * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
102
- * @param authorizationUrl - endpoint to attempt authorization with the OP
103
- * @param clientId - id of this client as registered with the OP
104
- * @param authorizationParams - params to be used in the url
105
- * @returns a Promise with the url as a string
106
- */
107
- export const generateAuthorizationUrl = async (
108
- authorizationUrl: string,
109
- clientId: string,
110
- { scope, redirectUri, state, nonce, codeVerifier }: AuthorizationParams,
111
- ): Promise<string> => {
112
- const url = new URL(authorizationUrl);
113
- url.searchParams.append("response_mode", "query");
114
- url.searchParams.append("response_type", "code");
115
- url.searchParams.append("redirect_uri", redirectUri);
116
- url.searchParams.append("client_id", clientId);
117
- url.searchParams.append("state", state);
118
- url.searchParams.append("scope", scope);
119
- url.searchParams.append("nonce", nonce);
120
-
121
- url.searchParams.append("code_challenge_method", "S256");
122
- url.searchParams.append("code_challenge", await generateCodeChallenge(codeVerifier));
123
-
124
- return url.toString();
125
- };
126
-
127
- /**
128
- * @experimental
129
- * Generate a URL to attempt authorization with the OP
130
- * See https://openid.net/specs/openid-connect-basic-1_0.html#CodeRequest
131
- * @param metadata - validated metadata from OP discovery
132
- * @param clientId - this client's id as registered with the OP
133
- * @param homeserverUrl - used to establish the session on return from the OP
134
- * @param identityServerUrl - used to establish the session on return from the OP
135
- * @param nonce - state
136
- * @param prompt - indicates to the OP which flow the user should see - eg login or registration
137
- * See https://openid.net/specs/openid-connect-prompt-create-1_0.html#name-prompt-parameter
138
- * @param urlState - value to append to the opaque state identifier to uniquely identify the callback
139
- * @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.
140
- * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.
141
- * @param responseMode - value to send as the `response_mode` to the OP, selecting how auth is passed back during redirect.
142
- * See {@link https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest OIDC core 3.1.2.1}.
143
- * @returns a Promise with the url as a string
144
- */
145
- export const generateOidcAuthorizationUrl = async ({
146
- metadata,
147
- redirectUri,
148
- clientId,
149
- homeserverUrl,
150
- identityServerUrl,
151
- nonce,
152
- prompt,
153
- urlState,
154
- loginHint,
155
- responseMode = "query",
156
- }: {
157
- clientId: string;
158
- metadata: ValidatedAuthMetadata;
159
- homeserverUrl: string;
160
- identityServerUrl?: string;
161
- redirectUri: string;
162
- nonce: string;
163
- prompt?: string;
164
- urlState?: string;
165
- loginHint?: string;
166
- responseMode?: SigninRequestCreateArgs["response_mode"];
167
- }): Promise<string> => {
168
- const scope = generateScope();
169
- const oidcClient = new OidcClient({
170
- ...metadata,
171
- client_id: clientId,
172
- redirect_uri: redirectUri,
173
- authority: metadata.issuer,
174
- response_mode: responseMode,
175
- response_type: "code",
176
- scope,
177
- stateStore: new WebStorageStateStore({ prefix: "mx_oidc_", store: window.sessionStorage }),
178
- });
179
- const userState: UserState = { homeserverUrl, nonce, identityServerUrl };
180
- const request = await oidcClient.createSigninRequest({
181
- state: userState,
182
- nonce,
183
- prompt,
184
- url_state: urlState,
185
- login_hint: loginHint,
186
- });
187
-
188
- return request.url;
189
- };
190
-
191
- /**
192
- * Normalize token_type to use capital case to make consuming the token response easier
193
- * token_type is case insensitive, and it is spec-compliant for OPs to return token_type: "bearer"
194
- * Later, when used in auth headers it is case sensitive and must be Bearer
195
- * See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4
196
- *
197
- * @param response - validated token response
198
- * @returns response with token_type set to 'Bearer'
199
- */
200
- const normalizeBearerTokenResponseTokenType = (response: SigninResponse): BearerTokenResponse =>
201
- ({
202
- id_token: response.id_token,
203
- scope: response.scope,
204
- expires_at: response.expires_at,
205
- refresh_token: response.refresh_token,
206
- access_token: response.access_token,
207
- token_type: "Bearer",
208
- }) as BearerTokenResponse;
209
-
210
- /**
211
- * @experimental
212
- * Attempt to exchange authorization code for bearer token.
213
- *
214
- * Takes the authorization code returned by the OpenID Provider via the authorization URL, and makes a
215
- * request to the Token Endpoint, to obtain the access token, refresh token, etc.
216
- *
217
- * @param code - authorization code as returned by OP during authorization
218
- * @param state - authorization state param as returned by OP during authorization
219
- * @param responseMode - the response mode used for authentication
220
- * @returns valid bearer token response
221
- * @throws An `Error` with `message` set to an entry in {@link OidcError},
222
- * when the request fails, or the returned token response is invalid.
223
- */
224
- export const completeAuthorizationCodeGrant = async (
225
- code: string,
226
- state: string,
227
- responseMode: SigninRequestCreateArgs["response_mode"] = "query",
228
- ): Promise<{
229
- oidcClientSettings: { clientId: string; issuer: string };
230
- tokenResponse: BearerTokenResponse;
231
- homeserverUrl: string;
232
- idTokenClaims: IdTokenClaims;
233
- identityServerUrl?: string;
234
- }> => {
235
- /**
236
- * Element Web strips and changes the url on starting the app
237
- * Use the code and state from query params to rebuild a url
238
- * so that oidc-client can parse it
239
- */
240
- const reconstructedUrl = new URL(window.location.origin);
241
-
242
- const params = new URLSearchParams({ code, state });
243
- if (responseMode === "query") {
244
- reconstructedUrl.search = params.toString();
245
- } else {
246
- reconstructedUrl.hash = `#${params.toString()}`;
247
- }
248
-
249
- // set oidc-client to use our logger
250
- Log.setLogger(logger);
251
- try {
252
- const response = new SigninResponse(params);
253
-
254
- const stateStore = new WebStorageStateStore({ prefix: "mx_oidc_", store: window.sessionStorage });
255
-
256
- // retrieve the state we put in storage at the start of oidc auth flow
257
- const stateString = await stateStore.get(response.state!);
258
- if (!stateString) {
259
- throw new Error(OidcError.MissingOrInvalidStoredState);
260
- }
261
-
262
- // hydrate the sign in state and create a client
263
- // the stored sign in state includes oidc configuration we set at the start of the oidc login flow
264
- const signInState = await SigninState.fromStorageString(stateString);
265
- const client = new OidcClient({ ...signInState, stateStore });
266
-
267
- // validate the code and state, and attempt to swap the code for tokens
268
- const signinResponse = await client.processSigninResponse(reconstructedUrl.href);
269
-
270
- // extra values we stored at the start of the login flow
271
- // used to complete login in the client
272
- const userState = signinResponse.userState;
273
- validateStoredUserState(userState);
274
-
275
- // throws when response is invalid
276
- validateBearerTokenResponse(signinResponse);
277
- if (signinResponse.id_token) {
278
- // The token is not yet in the Matrix spec so consider it optional
279
- // throws when token is invalid
280
- validateIdToken(
281
- signinResponse.id_token,
282
- client.settings.authority,
283
- client.settings.client_id,
284
- userState.nonce,
285
- );
286
- }
287
- const normalizedTokenResponse = normalizeBearerTokenResponseTokenType(signinResponse);
288
-
289
- return {
290
- oidcClientSettings: {
291
- clientId: client.settings.client_id,
292
- issuer: client.settings.authority,
293
- },
294
- tokenResponse: normalizedTokenResponse,
295
- homeserverUrl: userState.homeserverUrl,
296
- identityServerUrl: userState.identityServerUrl,
297
- idTokenClaims: signinResponse.profile,
298
- };
299
- } catch (error) {
300
- logger.error("Oidc login failed", error);
301
- const errorType = (error as Error).message;
302
-
303
- // rethrow errors that we recognise
304
- if (Object.values(OidcError).includes(errorType as any)) {
305
- throw error;
306
- }
307
- throw new Error(OidcError.CodeExchangeFailed);
308
- }
309
- };
310
-
311
- /**
312
- * Response from the OIDC token endpoint when exchanging a token for grant_type device_code.
313
- */
314
- export interface DeviceAccessTokenResponse {
315
- id_token?: string;
316
- access_token: string;
317
- token_type: string;
318
- refresh_token?: string;
319
- scope?: string;
320
- expires_in?: number;
321
- session_state?: string;
322
- }
323
-
324
- /**
325
- * Error from the OIDC token endpoint when exchanging a token for grant_type device_code.
326
- */
327
- export interface DeviceAccessTokenError {
328
- error: string;
329
- error_description?: string;
330
- error_uri?: string;
331
- session_state?: string;
332
- }
333
-
334
- /**
335
- * Response from the OIDC device authorization endpoint.
336
- */
337
- export interface DeviceAuthorizationResponse {
338
- device_code: string;
339
- user_code: string;
340
- verification_uri: string;
341
- verification_uri_complete?: string;
342
- expires_in: number;
343
- interval?: number;
344
- }
345
-
346
- /**
347
- * Begin OIDC device authorization flow.
348
- * @param options - The device authorization parameters.
349
- * @param options.clientId - the client ID returned from client registration.
350
- * @param options.scope - the scope to request for authorization.
351
- * @param options.metadata - the validated OIDC metadata for the Identity Provider.
352
- * @returns a promise that resolves to a device access token response,
353
- * or an error response if the user denies authorization or the device code expires.
354
- */
355
- export const startDeviceAuthorization = async ({
356
- clientId,
357
- scope,
358
- metadata,
359
- }: {
360
- clientId: string;
361
- scope: string;
362
- metadata: ValidatedAuthMetadata;
363
- }): Promise<DeviceAuthorizationResponse> => {
364
- const body = new URLSearchParams({ client_id: clientId, scope: scope }).toString();
365
-
366
- const url = metadata.device_authorization_endpoint;
367
- if (!url) {
368
- throw new Error("No device_authorization_endpoint given");
369
- }
370
-
371
- const response = await fetch(url, {
372
- method: Method.Post,
373
- headers: {
374
- "Content-Type": "application/x-www-form-urlencoded",
375
- },
376
- body,
377
- });
378
-
379
- return (await response.json()) as DeviceAuthorizationResponse;
380
- };
381
-
382
- /**
383
- * Polls the OIDC token endpoint until we get a device access token response, or encounter an unrecoverable error.
384
- * @param options - The device authorization parameters.
385
- * @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.
386
- * @param options.metadata - The validated OIDC metadata for the Identity Provider.
387
- * @param options.clientId - The client ID returned from client registration.
388
- * @returns a promise that resolves to a device access token response,
389
- * or an error response if the user denies authorization or the device code expires.
390
- */
391
- export const waitForDeviceAuthorization = async ({
392
- session,
393
- metadata,
394
- clientId,
395
- }: {
396
- session: DeviceAuthorizationResponse;
397
- metadata: ValidatedAuthMetadata;
398
- clientId: string;
399
- }): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError> => {
400
- let interval = (session.interval ?? 5) * 1000; // poll interval
401
- const expiration = Date.now() + session.expires_in * 1000;
402
- do {
403
- const body = new URLSearchParams({
404
- device_code: session.device_code,
405
- grant_type: OAuthGrantType.DeviceAuthorization,
406
- client_id: clientId,
407
- }).toString();
408
- const response = await fetch(metadata.token_endpoint, {
409
- method: Method.Post,
410
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
411
- body,
412
- });
413
-
414
- if (response.ok) {
415
- return (await response.json()) as DeviceAccessTokenResponse;
416
- }
417
- const errorResponse = (await response.json()) as DeviceAccessTokenError;
418
- switch (errorResponse.error) {
419
- case "authorization_pending":
420
- break;
421
- case "slow_down":
422
- interval += 5000;
423
- break;
424
- case "access_denied":
425
- case "expired_token":
426
- return errorResponse;
427
- }
428
- await sleep(interval);
429
- } while (Date.now() < expiration);
430
- return { error: "expired" };
431
- };
@@ -1,67 +0,0 @@
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 { MetadataService, OidcClientSettingsStore } from "oidc-client-ts";
18
-
19
- import { validateAuthMetadata } from "./validate.ts";
20
- import { Method, timeoutSignal } from "../http-api/index.ts";
21
- import { type OidcClientConfig } from "./index.ts";
22
-
23
- /**
24
- * @experimental
25
- * Discover and validate delegated auth configuration
26
- * - delegated auth issuer openid-configuration is reachable
27
- * - delegated auth issuer openid-configuration is configured correctly for us
28
- * Fetches https://oidc-issuer.example.com/.well-known/openid-configuration and other files linked therein.
29
- * When successful, validated metadata is returned
30
- * @param issuer - the OIDC issuer as returned by the /auth_issuer API
31
- * @returns validated authentication metadata and optionally signing keys
32
- * @throws when delegated auth config is invalid or unreachable
33
- * @deprecated in favour of {@link MatrixClient#getAuthMetadata}
34
- */
35
- export const discoverAndValidateOIDCIssuerWellKnown = async (issuer: string): Promise<OidcClientConfig> => {
36
- const issuerOpenIdConfigUrl = new URL(".well-known/openid-configuration", issuer);
37
- const issuerWellKnownResponse = await fetch(issuerOpenIdConfigUrl, {
38
- method: Method.Get,
39
- signal: timeoutSignal(5000),
40
- });
41
- const issuerWellKnown = await issuerWellKnownResponse.json();
42
- return validateAuthMetadataAndKeys(issuerWellKnown);
43
- };
44
-
45
- /**
46
- * @experimental
47
- * Validate the authentication metadata and fetch the signing keys from the jwks_uri in the metadata
48
- * @param authMetadata - the authentication metadata to validate
49
- * @returns validated authentication metadata and signing keys
50
- */
51
- export const validateAuthMetadataAndKeys = async (authMetadata: unknown): Promise<OidcClientConfig> => {
52
- const validatedIssuerConfig = validateAuthMetadata(authMetadata);
53
-
54
- // create a temporary settings store, so we can use metadata service for discovery
55
- const settings = new OidcClientSettingsStore({
56
- authority: validatedIssuerConfig.issuer,
57
- metadata: validatedIssuerConfig,
58
- redirect_uri: "", // Not known yet, this is here to make the type checker happy
59
- client_id: "", // Not known yet, this is here to make the type checker happy
60
- });
61
- const metadataService = new MetadataService(settings);
62
-
63
- return {
64
- ...validatedIssuerConfig,
65
- signingKeys: validatedIssuerConfig.jwks_uri ? await metadataService.getSigningKeys() : null,
66
- };
67
- };
package/src/oidc/index.ts DELETED
@@ -1,33 +0,0 @@
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 { SigningKey } from "oidc-client-ts";
18
- import { type ValidatedAuthMetadata } from "./validate.ts";
19
-
20
- export * from "./authorize.ts";
21
- export * from "./discovery.ts";
22
- export * from "./error.ts";
23
- export * from "./register.ts";
24
- export * from "./tokenRefresher.ts";
25
- export * from "./validate.ts";
26
-
27
- /**
28
- * Validated config for native OIDC authentication, as returned by {@link discoverAndValidateOIDCIssuerWellKnown}.
29
- * Contains metadata and signing keys from the issuer's well-known (https://oidc-issuer.example.com/.well-known/openid-configuration).
30
- */
31
- export interface OidcClientConfig extends ValidatedAuthMetadata {
32
- signingKeys: SigningKey[] | null;
33
- }