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,173 +0,0 @@
1
- import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
- /*
3
- Copyright 2023 The Matrix.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 { OidcClient, WebStorageStateStore, ErrorResponse } from "oidc-client-ts";
19
- import { TokenRefreshLogoutError } from "../http-api/index.js";
20
- import { generateScope } from "./authorize.js";
21
- import { discoverAndValidateOIDCIssuerWellKnown } from "./discovery.js";
22
- import { logger } from "../logger.js";
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
- constructor(
33
- /**
34
- * The OIDC issuer as returned by the /auth_issuer API
35
- */
36
- issuer,
37
- /**
38
- * id of this client as registered with the OP
39
- */
40
- clientId,
41
- /**
42
- * redirectUri as registered with OP
43
- */
44
- redirectUri,
45
- /**
46
- * Device ID of current session
47
- */
48
- deviceId,
49
- /**
50
- * idTokenClaims as returned from authorization grant
51
- * used to validate tokens
52
- */
53
- idTokenClaims) {
54
- /**
55
- * This is now just a resolved promise and will be removed in a future version.
56
- * Initialisation is done lazily at token refresh time.
57
- * @deprecated Consumers no longer need to wait for this promise.
58
- */
59
- _defineProperty(this, "oidcClientReady", void 0);
60
- // If there is a initialisation attempt in progress, we keep track of it here.
61
- _defineProperty(this, "initPromise", void 0);
62
- _defineProperty(this, "oidcClient", void 0);
63
- _defineProperty(this, "inflightRefreshRequest", void 0);
64
- this.issuer = issuer;
65
- this.clientId = clientId;
66
- this.redirectUri = redirectUri;
67
- this.deviceId = deviceId;
68
- this.idTokenClaims = idTokenClaims;
69
- this.oidcClientReady = Promise.resolve();
70
- }
71
-
72
- /**
73
- * Ensures that the client is initialised.
74
- * @returns Promise that resolves when initialisation is complete
75
- * @throws if initialisation fails
76
- */
77
- async ensureInit() {
78
- if (!this.oidcClient) {
79
- if (this.initPromise) {
80
- return this.initPromise;
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
- async initialiseOidcClient(issuer, clientId, deviceId, redirectUri) {
91
- try {
92
- const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);
93
- const scope = generateScope(deviceId);
94
- this.oidcClient = new OidcClient({
95
- metadata: config,
96
- signingKeys: config.signingKeys ?? undefined,
97
- client_id: clientId,
98
- scope,
99
- redirect_uri: redirectUri,
100
- authority: config.issuer,
101
- stateStore: new WebStorageStateStore({
102
- prefix: "mx_oidc_",
103
- store: window.sessionStorage
104
- })
105
- });
106
- } catch (error) {
107
- logger.error("Failed to initialise OIDC client.", error);
108
- throw new Error("Failed to initialise OIDC client.");
109
- }
110
- }
111
-
112
- /**
113
- * Attempt token refresh using given refresh token
114
- * @param refreshToken - refresh token to use in request with token issuer
115
- * @returns tokens - Promise that resolves with new access and refresh tokens
116
- * @throws when token refresh fails
117
- */
118
- async doRefreshAccessToken(refreshToken) {
119
- await this.ensureInit();
120
- if (!this.inflightRefreshRequest) {
121
- this.inflightRefreshRequest = this.getNewTokens(refreshToken);
122
- }
123
- try {
124
- const tokens = await this.inflightRefreshRequest;
125
- return tokens;
126
- } catch (e) {
127
- // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError
128
- if (e instanceof ErrorResponse) {
129
- throw new TokenRefreshLogoutError(e);
130
- }
131
- throw e;
132
- } finally {
133
- this.inflightRefreshRequest = undefined;
134
- }
135
- }
136
-
137
- /**
138
- * Persist the new tokens, called after tokens are successfully refreshed.
139
- *
140
- * This function is intended to be overriden by the consumer when persistence is necessary.
141
- *
142
- * @param tokens.accessToken - new access token
143
- * @param tokens.refreshToken - OPTIONAL new refresh token
144
- */
145
- async persistTokens(tokens) {
146
- // NOOP
147
- }
148
- async getNewTokens(refreshToken) {
149
- if (!this.oidcClient) {
150
- throw new Error("Cannot get new token before OIDC client is initialised.");
151
- }
152
- const refreshTokenState = {
153
- refresh_token: refreshToken,
154
- session_state: "test",
155
- data: undefined,
156
- profile: this.idTokenClaims
157
- };
158
- const requestStart = Date.now();
159
- const response = await this.oidcClient.useRefreshToken({
160
- state: refreshTokenState,
161
- timeoutInSeconds: 300
162
- });
163
- const tokens = {
164
- accessToken: response.access_token,
165
- refreshToken: response.refresh_token,
166
- // We use the request start time to calculate the expiry time as we don't know when the server received our request
167
- expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined
168
- };
169
- await this.persistTokens(tokens);
170
- return tokens;
171
- }
172
- }
173
- //# sourceMappingURL=tokenRefresher.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tokenRefresher.js","names":[],"sources":["../../src/oidc/tokenRefresher.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type IdTokenClaims, OidcClient, WebStorageStateStore, ErrorResponse } from \"oidc-client-ts\";\n\nimport { type AccessTokens, TokenRefreshLogoutError } from \"../http-api/index.ts\";\nimport { generateScope } from \"./authorize.ts\";\nimport { discoverAndValidateOIDCIssuerWellKnown } from \"./discovery.ts\";\nimport { logger } from \"../logger.ts\";\n\n/**\n * @experimental\n * Class responsible for refreshing OIDC access tokens\n *\n * Client implementations will likely want to override {@link persistTokens} to persist tokens after successful refresh\n *\n */\nexport class OidcTokenRefresher {\n /**\n * This is now just a resolved promise and will be removed in a future version.\n * Initialisation is done lazily at token refresh time.\n * @deprecated Consumers no longer need to wait for this promise.\n */\n public readonly oidcClientReady!: Promise<void>;\n\n // If there is a initialisation attempt in progress, we keep track of it here.\n private initPromise?: Promise<void>;\n\n private oidcClient!: OidcClient;\n private inflightRefreshRequest?: Promise<AccessTokens>;\n\n public constructor(\n /**\n * The OIDC issuer as returned by the /auth_issuer API\n */\n private issuer: string,\n /**\n * id of this client as registered with the OP\n */\n private clientId: string,\n /**\n * redirectUri as registered with OP\n */\n private redirectUri: string,\n /**\n * Device ID of current session\n */\n protected deviceId: string,\n /**\n * idTokenClaims as returned from authorization grant\n * used to validate tokens\n */\n private readonly idTokenClaims: IdTokenClaims,\n ) {\n this.oidcClientReady = Promise.resolve();\n }\n\n /**\n * Ensures that the client is initialised.\n * @returns Promise that resolves when initialisation is complete\n * @throws if initialisation fails\n */\n private async ensureInit(): Promise<void> {\n if (!this.oidcClient) {\n if (this.initPromise) {\n return this.initPromise;\n }\n\n this.initPromise = this.initialiseOidcClient(this.issuer, this.clientId, this.deviceId, this.redirectUri);\n try {\n await this.initPromise;\n } finally {\n this.initPromise = undefined;\n }\n }\n }\n\n private async initialiseOidcClient(\n issuer: string,\n clientId: string,\n deviceId: string,\n redirectUri: string,\n ): Promise<void> {\n try {\n const config = await discoverAndValidateOIDCIssuerWellKnown(issuer);\n\n const scope = generateScope(deviceId);\n\n this.oidcClient = new OidcClient({\n metadata: config,\n signingKeys: config.signingKeys ?? undefined,\n client_id: clientId,\n scope,\n redirect_uri: redirectUri,\n authority: config.issuer,\n stateStore: new WebStorageStateStore({ prefix: \"mx_oidc_\", store: window.sessionStorage }),\n });\n } catch (error) {\n logger.error(\"Failed to initialise OIDC client.\", error);\n throw new Error(\"Failed to initialise OIDC client.\");\n }\n }\n\n /**\n * Attempt token refresh using given refresh token\n * @param refreshToken - refresh token to use in request with token issuer\n * @returns tokens - Promise that resolves with new access and refresh tokens\n * @throws when token refresh fails\n */\n public async doRefreshAccessToken(refreshToken: string): Promise<AccessTokens> {\n await this.ensureInit();\n\n if (!this.inflightRefreshRequest) {\n this.inflightRefreshRequest = this.getNewTokens(refreshToken);\n }\n try {\n const tokens = await this.inflightRefreshRequest;\n return tokens;\n } catch (e) {\n // If we encounter an OIDC error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError\n if (e instanceof ErrorResponse) {\n throw new TokenRefreshLogoutError(e);\n }\n throw e;\n } finally {\n this.inflightRefreshRequest = undefined;\n }\n }\n\n /**\n * Persist the new tokens, called after tokens are successfully refreshed.\n *\n * This function is intended to be overriden by the consumer when persistence is necessary.\n *\n * @param tokens.accessToken - new access token\n * @param tokens.refreshToken - OPTIONAL new refresh token\n */\n protected async persistTokens(tokens: { accessToken: string; refreshToken?: string }): Promise<void> {\n // NOOP\n }\n\n private async getNewTokens(refreshToken: string): Promise<AccessTokens> {\n if (!this.oidcClient) {\n throw new Error(\"Cannot get new token before OIDC client is initialised.\");\n }\n\n const refreshTokenState = {\n refresh_token: refreshToken,\n session_state: \"test\",\n data: undefined,\n profile: this.idTokenClaims,\n };\n\n const requestStart = Date.now();\n const response = await this.oidcClient.useRefreshToken({\n state: refreshTokenState,\n timeoutInSeconds: 300,\n });\n\n const tokens = {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n // We use the request start time to calculate the expiry time as we don't know when the server received our request\n expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined,\n } satisfies AccessTokens;\n\n await this.persistTokens(tokens);\n\n return tokens;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA6B,UAAU,EAAE,oBAAoB,EAAE,aAAa,QAAQ,gBAAgB;AAEpG,SAA4B,uBAAuB,QAAQ,sBAAsB;AACjF,SAAS,aAAa,QAAQ,gBAAgB;AAC9C,SAAS,sCAAsC,QAAQ,gBAAgB;AACvE,SAAS,MAAM,QAAQ,cAAc;;AAErC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM,kBAAkB,CAAC;EAcrB,WAAW;EACd;AACR;AACA;EACgB,MAAc;EACtB;AACR;AACA;EACgB,QAAgB;EACxB;AACR;AACA;EACgB,WAAmB;EAC3B;AACR;AACA;EACkB,QAAgB;EAC1B;AACR;AACA;AACA;EACyB,aAA4B,E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xB,gBAAgB,EAAE;IACtB,CAAC,CAAC;IAEF,MAAM,MAAM,GAAG;MACX,WAAW,EAAE,QAAQ,CAAC,YAAY;MAClC,YAAY,EAAE,QAAQ,CAAC,aAAa;MACpC;MACA,MAAM,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI,IAAI,CAAC,YAAY,GAAG,QAAQ,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG;IACxF,CAAwB;IAExB,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;IAEhC,OAAO,MAAM;EACjB;AACJ","ignoreList":[]}
@@ -1,78 +0,0 @@
1
- import { type IdTokenClaims, type OidcMetadata, type SigninResponse } from "oidc-client-ts";
2
- /**
3
- * Metadata from OAuth 2.0 client authentication API as per
4
- * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata
5
- * With validated properties required in type
6
- */
7
- export type ValidatedAuthMetadata = Partial<OidcMetadata> & Pick<OidcMetadata, "issuer" | "authorization_endpoint" | "token_endpoint" | "revocation_endpoint" | "response_types_supported" | "grant_types_supported" | "code_challenge_methods_supported"> & {
8
- account_management_uri?: string;
9
- account_management_actions_supported?: string[];
10
- prompt_values_supported?: string[];
11
- device_authorization_endpoint?: string;
12
- };
13
- /**
14
- * Validates OAuth 2.0 auth metadata as defined by
15
- * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata
16
- * is compatible with Element's OAuth/OIDC flow
17
- * @param authMetadata - json object
18
- * @returns valid issuer config
19
- * @throws Error - when issuer config is not found or is invalid
20
- */
21
- export declare const validateAuthMetadata: (authMetadata: unknown) => ValidatedAuthMetadata;
22
- export declare const decodeIdToken: (token: string) => IdTokenClaims;
23
- /**
24
- * Validate idToken
25
- * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
26
- * @param idToken - id token from token endpoint
27
- * @param issuer - issuer for the OP as found during discovery
28
- * @param clientId - this client's id as registered with the OP
29
- * @param nonce - nonce used in the authentication request
30
- * @throws when id token is invalid
31
- */
32
- export declare const validateIdToken: (idToken: string | undefined, issuer: string, clientId: string, nonce: string | undefined) => void;
33
- /**
34
- * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)
35
- * so that we can access it on return from the OP and complete login
36
- */
37
- export type UserState = {
38
- /**
39
- * Remember which server we were trying to login to
40
- */
41
- homeserverUrl: string;
42
- identityServerUrl?: string;
43
- /**
44
- * Used to validate id token
45
- */
46
- nonce: string;
47
- };
48
- /**
49
- * Validate stored user state exists and is valid
50
- * @param userState - userState returned by oidcClient.processSigninResponse
51
- * @throws when userState is invalid
52
- */
53
- export declare function validateStoredUserState(userState: unknown): asserts userState is UserState;
54
- /**
55
- * The expected response type from the token endpoint during authorization code flow
56
- * Normalized to always use capitalized 'Bearer' for token_type
57
- *
58
- * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,
59
- * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.
60
- */
61
- export type BearerTokenResponse = {
62
- token_type: "Bearer";
63
- access_token: string;
64
- scope: string;
65
- refresh_token?: string;
66
- expires_in?: number;
67
- expires_at?: number;
68
- id_token: string;
69
- };
70
- /**
71
- * Make required properties required in type
72
- */
73
- type ValidSignInResponse = SigninResponse & BearerTokenResponse & {
74
- token_type: "Bearer" | "bearer";
75
- };
76
- export declare function validateBearerTokenResponse(response: unknown): asserts response is ValidSignInResponse;
77
- export {};
78
- //# sourceMappingURL=validate.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../../src/oidc/validate.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,YAAY,EAAE,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAM5F;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG,OAAO,CAAC,YAAY,CAAC,GACrD,IAAI,CAGA,YAAY,EACV,QAAQ,GACR,wBAAwB,GACxB,gBAAgB,GAChB,qBAAqB,GAC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C,CAAC;AAWN,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,IAAI,mBAAmB,CAItG"}
@@ -1,181 +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 { logger } from "../logger.js";
19
- import { OidcError } from "./error.js";
20
- import { OAuthGrantType } from "./index.js";
21
-
22
- /**
23
- * Metadata from OAuth 2.0 client authentication API as per
24
- * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata
25
- * With validated properties required in type
26
- */
27
-
28
- const isRecord = value => !!value && typeof value === "object" && !Array.isArray(value);
29
- const requiredStringProperty = (wellKnown, key) => {
30
- if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {
31
- logger.error(`Missing or invalid property: ${key}`);
32
- return false;
33
- }
34
- return true;
35
- };
36
- const optionalStringProperty = (wellKnown, key) => {
37
- if (!!wellKnown[key] && typeof wellKnown[key] !== "string") {
38
- logger.error(`Invalid property: ${key}`);
39
- return false;
40
- }
41
- return true;
42
- };
43
- const optionalStringArrayProperty = (wellKnown, key) => {
44
- if (!!wellKnown[key] && (!Array.isArray(wellKnown[key]) || !wellKnown[key].every(v => typeof v === "string"))) {
45
- logger.error(`Invalid property: ${key}`);
46
- return false;
47
- }
48
- return true;
49
- };
50
- const requiredArrayValue = (wellKnown, key, value) => {
51
- const array = wellKnown[key];
52
- if (!array || !Array.isArray(array) || !array.includes(value)) {
53
- logger.error(`Invalid property: ${key}. ${value} is required.`);
54
- return false;
55
- }
56
- return true;
57
- };
58
-
59
- /**
60
- * Validates OAuth 2.0 auth metadata as defined by
61
- * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata
62
- * is compatible with Element's OAuth/OIDC flow
63
- * @param authMetadata - json object
64
- * @returns valid issuer config
65
- * @throws Error - when issuer config is not found or is invalid
66
- */
67
- export const validateAuthMetadata = authMetadata => {
68
- if (!isRecord(authMetadata)) {
69
- logger.error("Issuer configuration not found or malformed");
70
- throw new Error(OidcError.OpSupport);
71
- }
72
- const isInvalid = [requiredStringProperty(authMetadata, "issuer"), requiredStringProperty(authMetadata, "authorization_endpoint"), requiredStringProperty(authMetadata, "token_endpoint"), requiredStringProperty(authMetadata, "revocation_endpoint"), optionalStringProperty(authMetadata, "registration_endpoint"), optionalStringProperty(authMetadata, "account_management_uri"), optionalStringProperty(authMetadata, "device_authorization_endpoint"), optionalStringArrayProperty(authMetadata, "account_management_actions_supported"), requiredArrayValue(authMetadata, "response_types_supported", "code"), requiredArrayValue(authMetadata, "grant_types_supported", OAuthGrantType.AuthorizationCode), requiredArrayValue(authMetadata, "code_challenge_methods_supported", "S256"), optionalStringArrayProperty(authMetadata, "prompt_values_supported")].some(isValid => !isValid);
73
- if (!isInvalid) {
74
- return authMetadata;
75
- }
76
- logger.error("Issuer configuration not valid");
77
- throw new Error(OidcError.OpSupport);
78
- };
79
- export const decodeIdToken = token => {
80
- try {
81
- return jwtDecode(token);
82
- } catch (error) {
83
- logger.error("Could not decode id_token", error);
84
- throw error;
85
- }
86
- };
87
-
88
- /**
89
- * Validate idToken
90
- * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
91
- * @param idToken - id token from token endpoint
92
- * @param issuer - issuer for the OP as found during discovery
93
- * @param clientId - this client's id as registered with the OP
94
- * @param nonce - nonce used in the authentication request
95
- * @throws when id token is invalid
96
- */
97
- export const validateIdToken = (idToken, issuer, clientId, nonce) => {
98
- try {
99
- if (!idToken) {
100
- throw new Error("No ID token");
101
- }
102
- const claims = decodeIdToken(idToken);
103
-
104
- // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.
105
- if (claims.iss !== issuer) {
106
- throw new Error("Invalid issuer");
107
- }
108
- /**
109
- * 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.
110
- * The aud (audience) Claim MAY contain an array with more than one element.
111
- * 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.
112
- * EW: Don't accept tokens with other untrusted audiences
113
- * */
114
- const sanitisedAuds = typeof claims.aud === "string" ? [claims.aud] : claims.aud;
115
- if (!sanitisedAuds.includes(clientId)) {
116
- throw new Error("Invalid audience");
117
- }
118
-
119
- /**
120
- * If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked
121
- * to verify that it is the same value as the one that was sent in the Authentication Request.
122
- */
123
- if (nonce !== undefined && claims.nonce !== nonce) {
124
- throw new Error("Invalid nonce");
125
- }
126
-
127
- /**
128
- * The current time MUST be before the time represented by the exp Claim.
129
- * exp is an epoch timestamp in seconds
130
- * */
131
- if (!claims.exp || Date.now() > claims.exp * 1000) {
132
- throw new Error("Invalid expiry");
133
- }
134
- } catch (error) {
135
- logger.error("Invalid ID token", error);
136
- throw new Error(OidcError.InvalidIdToken);
137
- }
138
- };
139
-
140
- /**
141
- * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)
142
- * so that we can access it on return from the OP and complete login
143
- */
144
-
145
- /**
146
- * Validate stored user state exists and is valid
147
- * @param userState - userState returned by oidcClient.processSigninResponse
148
- * @throws when userState is invalid
149
- */
150
- export function validateStoredUserState(userState) {
151
- if (!isRecord(userState)) {
152
- logger.error("Stored user state not found");
153
- throw new Error(OidcError.MissingOrInvalidStoredState);
154
- }
155
- const isInvalid = [requiredStringProperty(userState, "homeserverUrl"), requiredStringProperty(userState, "nonce"), optionalStringProperty(userState, "identityServerUrl")].some(isValid => !isValid);
156
- if (isInvalid) {
157
- throw new Error(OidcError.MissingOrInvalidStoredState);
158
- }
159
- }
160
-
161
- /**
162
- * The expected response type from the token endpoint during authorization code flow
163
- * Normalized to always use capitalized 'Bearer' for token_type
164
- *
165
- * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,
166
- * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.
167
- */
168
-
169
- /**
170
- * Make required properties required in type
171
- */
172
-
173
- const isValidBearerTokenResponse = response => isRecord(response) && requiredStringProperty(response, "token_type") &&
174
- // token_type is case insensitive, some OPs return `token_type: "bearer"`
175
- response["token_type"].toLowerCase() === "bearer" && requiredStringProperty(response, "access_token") && requiredStringProperty(response, "refresh_token") && (!("expires_in" in response) || typeof response["expires_in"] === "number");
176
- export function validateBearerTokenResponse(response) {
177
- if (!isValidBearerTokenResponse(response)) {
178
- throw new Error(OidcError.InvalidBearerTokenResponse);
179
- }
180
- }
181
- //# sourceMappingURL=validate.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"validate.js","names":[],"sources":["../../src/oidc/validate.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { jwtDecode } from \"jwt-decode\";\nimport { type IdTokenClaims, type OidcMetadata, type SigninResponse } from \"oidc-client-ts\";\n\nimport { logger } from \"../logger.ts\";\nimport { OidcError } from \"./error.ts\";\nimport { OAuthGrantType } from \"./index.ts\";\n\n/**\n * Metadata from OAuth 2.0 client authentication API as per\n * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata\n * With validated properties required in type\n */\nexport type ValidatedAuthMetadata = Partial<OidcMetadata> &\n Pick<\n // These values are from [RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)\n // so we can reuse the OidcMetadata definitions from oidc-client-ts\n OidcMetadata,\n | \"issuer\"\n | \"authorization_endpoint\"\n | \"token_endpoint\"\n | \"revocation_endpoint\"\n | \"response_types_supported\"\n | \"grant_types_supported\"\n | \"code_challenge_methods_supported\"\n > & {\n // These values aren't part of RFC8414 so we add them here\n // Account management fields from stable MSC4191:\n account_management_uri?: string;\n account_management_actions_supported?: string[];\n // Value from [Initiating User Registration via OpenID Connect](https://openid.net/specs/openid-connect-prompt-create-1_0.html):\n prompt_values_supported?: string[];\n // Experimental MSC4341 value from [RFC8628](https://datatracker.ietf.org/doc/html/rfc8628#section-4):\n device_authorization_endpoint?: string;\n };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\nconst requiredStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!wellKnown[key] || !optionalStringProperty(wellKnown, key)) {\n logger.error(`Missing or invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (!!wellKnown[key] && typeof wellKnown[key] !== \"string\") {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst optionalStringArrayProperty = (wellKnown: Record<string, unknown>, key: string): boolean => {\n if (\n !!wellKnown[key] &&\n (!Array.isArray(wellKnown[key]) || !(<unknown[]>wellKnown[key]).every((v) => typeof v === \"string\"))\n ) {\n logger.error(`Invalid property: ${key}`);\n return false;\n }\n return true;\n};\nconst requiredArrayValue = (wellKnown: Record<string, unknown>, key: string, value: any): boolean => {\n const array = wellKnown[key];\n if (!array || !Array.isArray(array) || !array.includes(value)) {\n logger.error(`Invalid property: ${key}. ${value} is required.`);\n return false;\n }\n return true;\n};\n\n/**\n * Validates OAuth 2.0 auth metadata as defined by\n * https://spec.matrix.org/v1.17/client-server-api/#get_matrixclientv1auth_metadata\n * is compatible with Element's OAuth/OIDC flow\n * @param authMetadata - json object\n * @returns valid issuer config\n * @throws Error - when issuer config is not found or is invalid\n */\nexport const validateAuthMetadata = (authMetadata: unknown): ValidatedAuthMetadata => {\n if (!isRecord(authMetadata)) {\n logger.error(\"Issuer configuration not found or malformed\");\n throw new Error(OidcError.OpSupport);\n }\n\n const isInvalid = [\n requiredStringProperty(authMetadata, \"issuer\"),\n requiredStringProperty(authMetadata, \"authorization_endpoint\"),\n requiredStringProperty(authMetadata, \"token_endpoint\"),\n requiredStringProperty(authMetadata, \"revocation_endpoint\"),\n optionalStringProperty(authMetadata, \"registration_endpoint\"),\n optionalStringProperty(authMetadata, \"account_management_uri\"),\n optionalStringProperty(authMetadata, \"device_authorization_endpoint\"),\n optionalStringArrayProperty(authMetadata, \"account_management_actions_supported\"),\n requiredArrayValue(authMetadata, \"response_types_supported\", \"code\"),\n requiredArrayValue(authMetadata, \"grant_types_supported\", OAuthGrantType.AuthorizationCode),\n requiredArrayValue(authMetadata, \"code_challenge_methods_supported\", \"S256\"),\n optionalStringArrayProperty(authMetadata, \"prompt_values_supported\"),\n ].some((isValid) => !isValid);\n\n if (!isInvalid) {\n return authMetadata as ValidatedAuthMetadata;\n }\n\n logger.error(\"Issuer configuration not valid\");\n throw new Error(OidcError.OpSupport);\n};\n\nexport const decodeIdToken = (token: string): IdTokenClaims => {\n try {\n return jwtDecode<IdTokenClaims>(token);\n } catch (error) {\n logger.error(\"Could not decode id_token\", error);\n throw error;\n }\n};\n\n/**\n * Validate idToken\n * https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation\n * @param idToken - id token from token endpoint\n * @param issuer - issuer for the OP as found during discovery\n * @param clientId - this client's id as registered with the OP\n * @param nonce - nonce used in the authentication request\n * @throws when id token is invalid\n */\nexport const validateIdToken = (\n idToken: string | undefined,\n issuer: string,\n clientId: string,\n nonce: string | undefined,\n): void => {\n try {\n if (!idToken) {\n throw new Error(\"No ID token\");\n }\n const claims = decodeIdToken(idToken);\n\n // The Issuer Identifier for the OpenID Provider MUST exactly match the value of the iss (issuer) Claim.\n if (claims.iss !== issuer) {\n throw new Error(\"Invalid issuer\");\n }\n /**\n * 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.\n * The aud (audience) Claim MAY contain an array with more than one element.\n * 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.\n * EW: Don't accept tokens with other untrusted audiences\n * */\n const sanitisedAuds = typeof claims.aud === \"string\" ? [claims.aud] : claims.aud;\n if (!sanitisedAuds.includes(clientId)) {\n throw new Error(\"Invalid audience\");\n }\n\n /**\n * If a nonce value was sent in the Authentication Request, a nonce Claim MUST be present and its value checked\n * to verify that it is the same value as the one that was sent in the Authentication Request.\n */\n if (nonce !== undefined && claims.nonce !== nonce) {\n throw new Error(\"Invalid nonce\");\n }\n\n /**\n * The current time MUST be before the time represented by the exp Claim.\n * exp is an epoch timestamp in seconds\n * */\n if (!claims.exp || Date.now() > claims.exp * 1000) {\n throw new Error(\"Invalid expiry\");\n }\n } catch (error) {\n logger.error(\"Invalid ID token\", error);\n throw new Error(OidcError.InvalidIdToken);\n }\n};\n\n/**\n * State we ask OidcClient to store when starting oidc authorization flow (in `generateOidcAuthorizationUrl`)\n * so that we can access it on return from the OP and complete login\n */\nexport type UserState = {\n /**\n * Remember which server we were trying to login to\n */\n homeserverUrl: string;\n identityServerUrl?: string;\n /**\n * Used to validate id token\n */\n nonce: string;\n};\n/**\n * Validate stored user state exists and is valid\n * @param userState - userState returned by oidcClient.processSigninResponse\n * @throws when userState is invalid\n */\nexport function validateStoredUserState(userState: unknown): asserts userState is UserState {\n if (!isRecord(userState)) {\n logger.error(\"Stored user state not found\");\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n const isInvalid = [\n requiredStringProperty(userState, \"homeserverUrl\"),\n requiredStringProperty(userState, \"nonce\"),\n optionalStringProperty(userState, \"identityServerUrl\"),\n ].some((isValid) => !isValid);\n\n if (isInvalid) {\n throw new Error(OidcError.MissingOrInvalidStoredState);\n }\n}\n\n/**\n * The expected response type from the token endpoint during authorization code flow\n * Normalized to always use capitalized 'Bearer' for token_type\n *\n * See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4,\n * https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK.\n */\nexport type BearerTokenResponse = {\n token_type: \"Bearer\";\n access_token: string;\n scope: string;\n refresh_token?: string;\n expires_in?: number;\n // from oidc-client-ts\n expires_at?: number;\n id_token: string;\n};\n\n/**\n * Make required properties required in type\n */\ntype ValidSignInResponse = SigninResponse &\n BearerTokenResponse & {\n token_type: \"Bearer\" | \"bearer\";\n };\n\nconst isValidBearerTokenResponse = (response: unknown): response is ValidSignInResponse =>\n isRecord(response) &&\n requiredStringProperty(response, \"token_type\") &&\n // token_type is case insensitive, some OPs return `token_type: \"bearer\"`\n (response[\"token_type\"] as string).toLowerCase() === \"bearer\" &&\n requiredStringProperty(response, \"access_token\") &&\n requiredStringProperty(response, \"refresh_token\") &&\n (!(\"expires_in\" in response) || typeof response[\"expires_in\"] === \"number\");\n\nexport function validateBearerTokenResponse(response: unknown): asserts response is ValidSignInResponse {\n if (!isValidBearerTokenResponse(response)) {\n throw new Error(OidcError.InvalidBearerTokenResponse);\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,SAAS,QAAQ,YAAY;AAGtC,SAAS,MAAM,QAAQ,cAAc;AACrC,SAAS,SAAS,QAAQ,YAAY;AACtC,SAAS,cAAc,QAAQ,YAAY;;AAE3C;AACA;AACA;AACA;AACA;;AAwBA,MAAM,QAAQ,GAAI,KAAc,IAC5B,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,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