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,168 +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 OidcClientConfig } from "./index.ts";
18
- import { OidcError } from "./error.ts";
19
- import { Method } from "../http-api/index.ts";
20
- import { logger } from "../logger.ts";
21
- import { type NonEmptyArray } from "../@types/common.ts";
22
-
23
- /**
24
- * Client metadata passed to registration endpoint
25
- */
26
- export type OidcRegistrationClientMetadata = {
27
- clientName: OidcRegistrationRequestBody["client_name"];
28
- clientUri: OidcRegistrationRequestBody["client_uri"];
29
- logoUri?: OidcRegistrationRequestBody["logo_uri"];
30
- applicationType: OidcRegistrationRequestBody["application_type"];
31
- redirectUris: OidcRegistrationRequestBody["redirect_uris"];
32
- contacts: OidcRegistrationRequestBody["contacts"];
33
- tosUri: OidcRegistrationRequestBody["tos_uri"];
34
- policyUri: OidcRegistrationRequestBody["policy_uri"];
35
- };
36
-
37
- /**
38
- * Request body for dynamic registration as defined by https://github.com/matrix-org/matrix-spec-proposals/pull/2966
39
- */
40
- interface OidcRegistrationRequestBody {
41
- client_name?: string;
42
- client_uri: string;
43
- logo_uri?: string;
44
- contacts?: string[];
45
- tos_uri?: string;
46
- policy_uri?: string;
47
- redirect_uris?: NonEmptyArray<string>;
48
- response_types?: NonEmptyArray<string>;
49
- grant_types?: NonEmptyArray<string>;
50
- id_token_signed_response_alg?: string;
51
- token_endpoint_auth_method: string;
52
- application_type: "web" | "native";
53
- }
54
-
55
- /**
56
- * The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
57
- */
58
- export enum OAuthGrantType {
59
- /**
60
- * See https://spec.matrix.org/v1.17/client-server-api/#authorization-code-grant
61
- */
62
- AuthorizationCode = "authorization_code",
63
- /**
64
- * https://spec.matrix.org/v1.17/client-server-api/#refresh-token-grant
65
- */
66
- RefreshToken = "refresh_token",
67
- /**
68
- * The OAuth 2.0 Device Authorization Grant type identifier as per
69
- * https://www.rfc-editor.org/rfc/rfc8628.html#section-7.2 from
70
- * [MSC4341](https://github.com/matrix-org/matrix-spec-proposals/pull/4341).
71
- *
72
- * @experimental Note that this is UNSTABLE and may have breaking changes without notice.
73
- */
74
- DeviceAuthorization = "urn:ietf:params:oauth:grant-type:device_code",
75
- }
76
-
77
- /**
78
- * The name "scope" is a misnomer here as it is actually a "grant type".
79
- *
80
- * @deprecated use `OAuthGrantType.DeviceAuthorization` instead
81
- */
82
- export const DEVICE_CODE_SCOPE: string = OAuthGrantType.DeviceAuthorization;
83
-
84
- // Check that URIs have a common base, as per the MSC2966 definition
85
- const urlHasCommonBase = (base: URL, urlStr?: string): boolean => {
86
- if (!urlStr) return false;
87
- const url = new URL(urlStr);
88
- if (url.protocol !== base.protocol) return false;
89
- if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;
90
- return true;
91
- };
92
-
93
- /**
94
- * Attempts dynamic registration against the configured registration endpoint.
95
- * Will ignore any URIs that do not use client_uri as a common base as per the spec.
96
- * @param delegatedAuthConfig - Auth config from {@link discoverAndValidateOIDCIssuerWellKnown}
97
- * @param clientMetadata - The metadata for the client which to register
98
- * @returns Promise<string> resolved with registered clientId
99
- * @throws when registration is not supported, on failed request or invalid response
100
- */
101
- export const registerOidcClient = async (
102
- delegatedAuthConfig: OidcClientConfig,
103
- clientMetadata: OidcRegistrationClientMetadata,
104
- ): Promise<string> => {
105
- if (!delegatedAuthConfig.registration_endpoint) {
106
- throw new Error(OidcError.DynamicRegistrationNotSupported);
107
- }
108
-
109
- const grantTypes: NonEmptyArray<string> = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];
110
- if (grantTypes.some((scope) => !delegatedAuthConfig.grant_types_supported.includes(scope))) {
111
- throw new Error(OidcError.DynamicRegistrationNotSupported);
112
- }
113
-
114
- // ask for device authorization grant if supported
115
- if (delegatedAuthConfig.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
116
- grantTypes.push(OAuthGrantType.DeviceAuthorization);
117
- }
118
-
119
- const commonBase = new URL(clientMetadata.clientUri);
120
-
121
- // https://openid.net/specs/openid-connect-registration-1_0.html
122
- const metadata: OidcRegistrationRequestBody = {
123
- client_name: clientMetadata.clientName,
124
- client_uri: clientMetadata.clientUri,
125
- response_types: ["code"],
126
- grant_types: grantTypes,
127
- redirect_uris: clientMetadata.redirectUris,
128
- id_token_signed_response_alg: "RS256",
129
- token_endpoint_auth_method: "none",
130
- application_type: clientMetadata.applicationType,
131
- contacts: clientMetadata.contacts,
132
- logo_uri: urlHasCommonBase(commonBase, clientMetadata.logoUri) ? clientMetadata.logoUri : undefined,
133
- policy_uri: urlHasCommonBase(commonBase, clientMetadata.policyUri) ? clientMetadata.policyUri : undefined,
134
- tos_uri: urlHasCommonBase(commonBase, clientMetadata.tosUri) ? clientMetadata.tosUri : undefined,
135
- };
136
-
137
- const headers = {
138
- "Accept": "application/json",
139
- "Content-Type": "application/json",
140
- };
141
-
142
- try {
143
- const response = await fetch(delegatedAuthConfig.registration_endpoint, {
144
- method: Method.Post,
145
- headers,
146
- body: JSON.stringify(metadata),
147
- });
148
-
149
- if (response.status >= 400) {
150
- throw new Error(OidcError.DynamicRegistrationFailed);
151
- }
152
-
153
- const body = await response.json();
154
- const clientId = body["client_id"];
155
- if (!clientId || typeof clientId !== "string") {
156
- throw new Error(OidcError.DynamicRegistrationInvalid);
157
- }
158
-
159
- return clientId;
160
- } catch (error) {
161
- if (Object.values(OidcError).includes((error as Error).message as OidcError)) {
162
- throw error;
163
- } else {
164
- logger.error("Dynamic registration request failed", error);
165
- throw new Error(OidcError.DynamicRegistrationFailed);
166
- }
167
- }
168
- };
@@ -1,184 +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 IdTokenClaims, OidcClient, WebStorageStateStore, ErrorResponse } from "oidc-client-ts";
18
-
19
- import { type AccessTokens, TokenRefreshLogoutError } from "../http-api/index.ts";
20
- import { generateScope } from "./authorize.ts";
21
- import { discoverAndValidateOIDCIssuerWellKnown } from "./discovery.ts";
22
- import { logger } from "../logger.ts";
23
-
24
- /**
25
- * @experimental
26
- * Class responsible for refreshing OIDC access tokens
27
- *
28
- * Client implementations will likely want to override {@link persistTokens} to persist tokens after successful refresh
29
- *
30
- */
31
- export class OidcTokenRefresher {
32
- /**
33
- * This is now just a resolved promise and will be removed in a future version.
34
- * Initialisation is done lazily at token refresh time.
35
- * @deprecated Consumers no longer need to wait for this promise.
36
- */
37
- public readonly oidcClientReady!: Promise<void>;
38
-
39
- // If there is a initialisation attempt in progress, we keep track of it here.
40
- private initPromise?: Promise<void>;
41
-
42
- private oidcClient!: OidcClient;
43
- private inflightRefreshRequest?: Promise<AccessTokens>;
44
-
45
- public constructor(
46
- /**
47
- * The OIDC issuer as returned by the /auth_issuer API
48
- */
49
- private issuer: string,
50
- /**
51
- * id of this client as registered with the OP
52
- */
53
- private clientId: string,
54
- /**
55
- * redirectUri as registered with OP
56
- */
57
- private redirectUri: string,
58
- /**
59
- * Device ID of current session
60
- */
61
- protected deviceId: string,
62
- /**
63
- * idTokenClaims as returned from authorization grant
64
- * used to validate tokens
65
- */
66
- private readonly idTokenClaims: IdTokenClaims,
67
- ) {
68
- this.oidcClientReady = Promise.resolve();
69
- }
70
-
71
- /**
72
- * Ensures that the client is initialised.
73
- * @returns Promise that resolves when initialisation is complete
74
- * @throws if initialisation fails
75
- */
76
- private async ensureInit(): Promise<void> {
77
- if (!this.oidcClient) {
78
- if (this.initPromise) {
79
- return this.initPromise;
80
- }
81
-
82
- this.initPromise = this.initialiseOidcClient(this.issuer, this.clientId, this.deviceId, this.redirectUri);
83
- try {
84
- await this.initPromise;
85
- } finally {
86
- this.initPromise = undefined;
87
- }
88
- }
89
- }
90
-
91
- private async initialiseOidcClient(
92
- issuer: string,
93
- clientId: string,
94
- deviceId: string,
95
- redirectUri: string,
96
- ): Promise<void> {
97
- try {
98
- const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);
99
-
100
- const scope = generateScope(deviceId);
101
-
102
- this.oidcClient = new OidcClient({
103
- metadata: config,
104
- signingKeys: config.signingKeys ?? undefined,
105
- client_id: clientId,
106
- scope,
107
- redirect_uri: redirectUri,
108
- authority: config.issuer,
109
- stateStore: new WebStorageStateStore({ prefix: "mx_oidc_", store: window.sessionStorage }),
110
- });
111
- } catch (error) {
112
- logger.error("Failed to initialise OIDC client.", error);
113
- throw new Error("Failed to initialise OIDC client.");
114
- }
115
- }
116
-
117
- /**
118
- * Attempt token refresh using given refresh token
119
- * @param refreshToken - refresh token to use in request with token issuer
120
- * @returns tokens - Promise that resolves with new access and refresh tokens
121
- * @throws when token refresh fails
122
- */
123
- public async doRefreshAccessToken(refreshToken: string): Promise<AccessTokens> {
124
- await this.ensureInit();
125
-
126
- if (!this.inflightRefreshRequest) {
127
- this.inflightRefreshRequest = this.getNewTokens(refreshToken);
128
- }
129
- try {
130
- const tokens = await this.inflightRefreshRequest;
131
- return tokens;
132
- } catch (e) {
133
- // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError
134
- if (e instanceof ErrorResponse) {
135
- throw new TokenRefreshLogoutError(e);
136
- }
137
- throw e;
138
- } finally {
139
- this.inflightRefreshRequest = undefined;
140
- }
141
- }
142
-
143
- /**
144
- * Persist the new tokens, called after tokens are successfully refreshed.
145
- *
146
- * This function is intended to be overriden by the consumer when persistence is necessary.
147
- *
148
- * @param tokens.accessToken - new access token
149
- * @param tokens.refreshToken - OPTIONAL new refresh token
150
- */
151
- protected async persistTokens(tokens: { accessToken: string; refreshToken?: string }): Promise<void> {
152
- // NOOP
153
- }
154
-
155
- private async getNewTokens(refreshToken: string): Promise<AccessTokens> {
156
- if (!this.oidcClient) {
157
- throw new Error("Cannot get new token before OIDC client is initialised.");
158
- }
159
-
160
- const refreshTokenState = {
161
- refresh_token: refreshToken,
162
- session_state: "test",
163
- data: undefined,
164
- profile: this.idTokenClaims,
165
- };
166
-
167
- const requestStart = Date.now();
168
- const response = await this.oidcClient.useRefreshToken({
169
- state: refreshTokenState,
170
- timeoutInSeconds: 300,
171
- });
172
-
173
- const tokens = {
174
- accessToken: response.access_token,
175
- refreshToken: response.refresh_token,
176
- // We use the request start time to calculate the expiry time as we don't know when the server received our request
177
- expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined,
178
- } satisfies AccessTokens;
179
-
180
- await this.persistTokens(tokens);
181
-
182
- return tokens;
183
- }
184
- }
@@ -1,265 +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 { jwtDecode } from "jwt-decode";
18
- import { type IdTokenClaims, type OidcMetadata, type SigninResponse } from "oidc-client-ts";
19
-
20
- import { logger } from "../logger.ts";
21
- import { OidcError } from "./error.ts";
22
- import { OAuthGrantType } from "./index.ts";
23
-
24
- /**
25
- * Metadata from OAuth 2.0 client authentication API as per
26
- * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata
27
- * With validated properties required in type
28
- */
29
- export type ValidatedAuthMetadata = Partial<OidcMetadata> &
30
- Pick<
31
- // These values are from [RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)
32
- // so we can reuse the OidcMetadata definitions from oidc-client-ts
33
- OidcMetadata,
34
- | "issuer"
35
- | "authorization_endpoint"
36
- | "token_endpoint"
37
- | "revocation_endpoint"
38
- | "response_types_supported"
39
- | "grant_types_supported"
40
- | "code_challenge_methods_supported"
41
- > & {
42
- // These values aren't part of RFC8414 so we add them here
43
- // Account management fields from stable MSC4191:
44
- account_management_uri?: string;
45
- account_management_actions_supported?: string[];
46
- // Value from [Initiating User Registration via OpenID Connect](https://openid.net/specs/openid-connect-prompt-create-1_0.html):
47
- prompt_values_supported?: string[];
48
- // Experimental MSC4341 value from [RFC8628](https://datatracker.ietf.org/doc/html/rfc8628#section-4):
49
- device_authorization_endpoint?: string;
50
- };
51
-
52
- const isRecord = (value: unknown): value is Record<string, unknown> =>
53
- !!value && typeof value === "object" && !Array.isArray(value);
54
- const requiredStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {
55
- if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {
56
- logger.error(`Missing or invalid property: ${key}`);
57
- return false;
58
- }
59
- return true;
60
- };
61
- const optionalStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {
62
- if (!!wellKnown[key] && typeof wellKnown[key] !== "string") {
63
- logger.error(`Invalid property: ${key}`);
64
- return false;
65
- }
66
- return true;
67
- };
68
- const optionalStringArrayProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {
69
- if (
70
- !!wellKnown[key] &&
71
- (!Array.isArray(wellKnown[key]) || !(<unknown[]>wellKnown[key]).every((v) => typeof v === "string"))
72
- ) {
73
- logger.error(`Invalid property: ${key}`);
74
- return false;
75
- }
76
- return true;
77
- };
78
- const requiredArrayValue = (wellKnown: Record<string, unknown>, key: string, value: any): boolean => {
79
- const array = wellKnown[key];
80
- if (!array || !Array.isArray(array) || !array.includes(value)) {
81
- logger.error(`Invalid property: ${key}. ${value} is required.`);
82
- return false;
83
- }
84
- return true;
85
- };
86
-
87
- /**
88
- * Validates OAuth 2.0 auth metadata as defined by
89
- * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata
90
- * is compatible with Element's OAuth/OIDC flow
91
- * @param authMetadata - json object
92
- * @returns valid issuer config
93
- * @throws Error - when issuer config is not found or is invalid
94
- */
95
- export const validateAuthMetadata = (authMetadata: unknown): ValidatedAuthMetadata => {
96
- if (!isRecord(authMetadata)) {
97
- logger.error("Issuer configuration not found or malformed");
98
- throw new Error(OidcError.OpSupport);
99
- }
100
-
101
- const isInvalid = [
102
- requiredStringProperty(authMetadata, "issuer"),
103
- requiredStringProperty(authMetadata, "authorization_endpoint"),
104
- requiredStringProperty(authMetadata, "token_endpoint"),
105
- requiredStringProperty(authMetadata, "revocation_endpoint"),
106
- optionalStringProperty(authMetadata, "registration_endpoint"),
107
- optionalStringProperty(authMetadata, "account_management_uri"),
108
- optionalStringProperty(authMetadata, "device_authorization_endpoint"),
109
- optionalStringArrayProperty(authMetadata, "account_management_actions_supported"),
110
- requiredArrayValue(authMetadata, "response_types_supported", "code"),
111
- requiredArrayValue(authMetadata, "grant_types_supported", OAuthGrantType.AuthorizationCode),
112
- requiredArrayValue(authMetadata, "code_challenge_methods_supported", "S256"),
113
- optionalStringArrayProperty(authMetadata, "prompt_values_supported"),
114
- ].some((isValid) => !isValid);
115
-
116
- if (!isInvalid) {
117
- return authMetadata as ValidatedAuthMetadata;
118
- }
119
-
120
- logger.error("Issuer configuration not valid");
121
- throw new Error(OidcError.OpSupport);
122
- };
123
-
124
- export const decodeIdToken = (token: string): IdTokenClaims => {
125
- try {
126
- return jwtDecode<IdTokenClaims>(token);
127
- } catch (error) {
128
- logger.error("Could not decode id_token", error);
129
- throw error;
130
- }
131
- };
132
-
133
- /**
134
- * Validate idToken
135
- * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
136
- * @param idToken - id token from token endpoint
137
- * @param issuer - issuer for the OP as found during discovery
138
- * @param clientId - this client's id as registered with the OP
139
- * @param nonce - nonce used in the authentication request
140
- * @throws when id token is invalid
141
- */
142
- export const validateIdToken = (
143
- idToken: string | undefined,
144
- issuer: string,
145
- clientId: string,
146
- nonce: string | undefined,
147
- ): void => {
148
- try {
149
- if (!idToken) {
150
- throw new Error("No ID token");
151
- }
152
- const claims = decodeIdToken(idToken);
153
-
154
- // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.
155
- if (claims.iss !== issuer) {
156
- throw new Error("Invalid issuer");
157
- }
158
- /**
159
- * The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience.
160
- * The aud (audience) Claim MAY contain an array with more than one element.
161
- * The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.
162
- * EW: Don't accept tokens with other untrusted audiences
163
- * */
164
- const sanitisedAuds = typeof claims.aud === "string" ? [claims.aud] : claims.aud;
165
- if (!sanitisedAuds.includes(clientId)) {
166
- throw new Error("Invalid audience");
167
- }
168
-
169
- /**
170
- * If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked
171
- * to verify that it is the same value as the one that was sent in the Authentication Request.
172
- */
173
- if (nonce !== undefined && claims.nonce !== nonce) {
174
- throw new Error("Invalid nonce");
175
- }
176
-
177
- /**
178
- * The current time MUST be before the time represented by the exp Claim.
179
- * exp is an epoch timestamp in seconds
180
- * */
181
- if (!claims.exp || Date.now() > claims.exp * 1000) {
182
- throw new Error("Invalid expiry");
183
- }
184
- } catch (error) {
185
- logger.error("Invalid ID token", error);
186
- throw new Error(OidcError.InvalidIdToken);
187
- }
188
- };
189
-
190
- /**
191
- * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)
192
- * so that we can access it on return from the OP and complete login
193
- */
194
- export type UserState = {
195
- /**
196
- * Remember which server we were trying to login to
197
- */
198
- homeserverUrl: string;
199
- identityServerUrl?: string;
200
- /**
201
- * Used to validate id token
202
- */
203
- nonce: string;
204
- };
205
- /**
206
- * Validate stored user state exists and is valid
207
- * @param userState - userState returned by oidcClient.processSigninResponse
208
- * @throws when userState is invalid
209
- */
210
- export function validateStoredUserState(userState: unknown): asserts userState is UserState {
211
- if (!isRecord(userState)) {
212
- logger.error("Stored user state not found");
213
- throw new Error(OidcError.MissingOrInvalidStoredState);
214
- }
215
- const isInvalid = [
216
- requiredStringProperty(userState, "homeserverUrl"),
217
- requiredStringProperty(userState, "nonce"),
218
- optionalStringProperty(userState, "identityServerUrl"),
219
- ].some((isValid) => !isValid);
220
-
221
- if (isInvalid) {
222
- throw new Error(OidcError.MissingOrInvalidStoredState);
223
- }
224
- }
225
-
226
- /**
227
- * The expected response type from the token endpoint during authorization code flow
228
- * Normalized to always use capitalized 'Bearer' for token_type
229
- *
230
- * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,
231
- * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.
232
- */
233
- export type BearerTokenResponse = {
234
- token_type: "Bearer";
235
- access_token: string;
236
- scope: string;
237
- refresh_token?: string;
238
- expires_in?: number;
239
- // from oidc-client-ts
240
- expires_at?: number;
241
- id_token: string;
242
- };
243
-
244
- /**
245
- * Make required properties required in type
246
- */
247
- type ValidSignInResponse = SigninResponse &
248
- BearerTokenResponse & {
249
- token_type: "Bearer" | "bearer";
250
- };
251
-
252
- const isValidBearerTokenResponse = (response: unknown): response is ValidSignInResponse =>
253
- isRecord(response) &&
254
- requiredStringProperty(response, "token_type") &&
255
- // token_type is case insensitive, some OPs return `token_type: "bearer"`
256
- (response["token_type"] as string).toLowerCase() === "bearer" &&
257
- requiredStringProperty(response, "access_token") &&
258
- requiredStringProperty(response, "refresh_token") &&
259
- (!("expires_in" in response) || typeof response["expires_in"] === "number");
260
-
261
- export function validateBearerTokenResponse(response: unknown): asserts response is ValidSignInResponse {
262
- if (!isValidBearerTokenResponse(response)) {
263
- throw new Error(OidcError.InvalidBearerTokenResponse);
264
- }
265
- }