@monocloud/auth-core 0.1.4 → 0.1.6

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.
package/dist/index.cjs CHANGED
@@ -2,10 +2,24 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_utils_internal = require('./utils/internal.cjs');
3
3
 
4
4
  //#region src/errors/monocloud-auth-base-error.ts
5
+ /**
6
+ * Base class for all MonoCloud authentication errors.
7
+ *
8
+ * All errors thrown by the MonoCloud SDK extend this class, allowing applications to safely detect and handle MonoCloud-specific failures using `instanceof`.
9
+ *
10
+ * @category Error Classes
11
+ */
5
12
  var MonoCloudAuthBaseError = class extends Error {};
6
13
 
7
14
  //#endregion
8
15
  //#region src/errors/monocloud-op-error.ts
16
+ /**
17
+ * OAuth error returned by the authorization server during an authentication or token request.
18
+ *
19
+ * These errors correspond to standard OAuth / OpenID Connect error responses such as `invalid_request`, `access_denied`, or `invalid_grant`.
20
+ *
21
+ * @category Error Classes
22
+ */
9
23
  var MonoCloudOPError = class extends MonoCloudAuthBaseError {
10
24
  constructor(error, errorDescription) {
11
25
  super(error);
@@ -16,14 +30,31 @@ var MonoCloudOPError = class extends MonoCloudAuthBaseError {
16
30
 
17
31
  //#endregion
18
32
  //#region src/errors/monocloud-http-error.ts
33
+ /**
34
+ * Error thrown when a request to the MonoCloud authorization server fails.
35
+ *
36
+ * This error typically indicates a network failure, an unexpected HTTP response, or an unsuccessful response returned by the authorization server.
37
+ *
38
+ * @category Error Classes
39
+ */
19
40
  var MonoCloudHttpError = class extends MonoCloudAuthBaseError {};
20
41
 
21
42
  //#endregion
22
43
  //#region src/errors/monocloud-token-error.ts
44
+ /**
45
+ * Error thrown when a token operation fails.
46
+ *
47
+ * @category Error Classes
48
+ */
23
49
  var MonoCloudTokenError = class extends MonoCloudAuthBaseError {};
24
50
 
25
51
  //#endregion
26
52
  //#region src/errors/monocloud-validation-error.ts
53
+ /**
54
+ * Error thrown when validation fails.
55
+ *
56
+ * @category Error Classes
57
+ */
27
58
  var MonoCloudValidationError = class extends MonoCloudAuthBaseError {};
28
59
 
29
60
  //#endregion
@@ -224,12 +255,15 @@ const deserializeJson = async (res) => {
224
255
  );
225
256
  }
226
257
  };
258
+ /**
259
+ * @category Classes
260
+ */
227
261
  var MonoCloudOidcClient = class MonoCloudOidcClient {
228
262
  constructor(tenantDomain, clientId, options) {
229
263
  this.jwksCacheExpiry = 0;
230
- this.jwksCacheDuration = 60;
264
+ this.jwksCacheDuration = 300;
231
265
  this.metadataCacheExpiry = 0;
232
- this.metadataCacheDuration = 60;
266
+ this.metadataCacheDuration = 300;
233
267
  tenantDomain ??= "";
234
268
  /* v8 ignore next -- @preserve */
235
269
  this.tenantDomain = `${!tenantDomain.startsWith("https://") ? "https://" : ""}${tenantDomain.endsWith("/") ? tenantDomain.slice(0, -1) : tenantDomain}`;
@@ -245,9 +279,9 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
245
279
  *
246
280
  * If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.
247
281
  *
248
- * @param params Authorization URL parameters
282
+ * @param params - Authorization URL parameters.
249
283
  *
250
- * @returns Tenant's authorization url.
284
+ * @returns Tenant's authorization URL.
251
285
  *
252
286
  * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
253
287
  * unexpected status code during the request or a serialization error while processing the response.
@@ -306,7 +340,7 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
306
340
  return metadata;
307
341
  }
308
342
  /**
309
- * Fetches the JSON Web Keys used to sign the id token.
343
+ * Fetches the JSON Web Keys used to sign the ID token.
310
344
  * The JWKS is cached for 1 minute.
311
345
  *
312
346
  * @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.
@@ -332,9 +366,9 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
332
366
  /**
333
367
  * Performs a pushed authorization request.
334
368
  *
335
- * @param params - Authorization Parameters
369
+ * @param params - Authorization Parameters.
336
370
  *
337
- * @returns Response from Pushed Authorization Request (PAR) endpoint
371
+ * @returns Response from Pushed Authorization Request (PAR) endpoint.
338
372
  *
339
373
  * @throws {@link MonoCloudOPError} - When the request is invalid.
340
374
  *
@@ -424,13 +458,13 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
424
458
  return await deserializeJson(response);
425
459
  }
426
460
  /**
427
- * Generates OpenID end session url for signing out.
461
+ * Generates OpenID end session URL for signing out.
428
462
  *
429
463
  * Note - The `state` is added only when `postLogoutRedirectUri` is present.
430
464
  *
431
- * @param params - Parameters to build end session url
465
+ * @param params - Parameters to build end session URL.
432
466
  *
433
- * @returns Tenant's end session url
467
+ * @returns Tenant's end session URL.
434
468
  *
435
469
  * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
436
470
  * unexpected status code during the request or a serialization error while processing the response.
@@ -454,7 +488,7 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
454
488
  * @param code - The authorization code received from the authorization server.
455
489
  * @param redirectUri - The redirect URI used in the initial authorization request.
456
490
  * @param codeVerifier - Code verifier for PKCE.
457
- * @param resource - Space-separated list of resources the access token should be scoped to
491
+ * @param resource - Space-separated list of resources the access token should be scoped to.
458
492
  *
459
493
  * @returns Tokens obtained by exchanging an authorization code at the token endpoint.
460
494
  *
@@ -537,23 +571,23 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
537
571
  /**
538
572
  * Generates a session with user and tokens by exchanging authorization code from callback params.
539
573
  *
540
- * @param code - The authorization code received from the callback
541
- * @param redirectUri - The redirect URI that was used in the authorization request
574
+ * @param code - The authorization code received from the callback.
575
+ * @param redirectUri - The redirect URI that was used in the authorization request.
542
576
  * @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.
543
577
  * This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.
544
578
  * @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.
545
579
  * Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.
546
- * @param options - Options for authenticating a user with authorization code
580
+ * @param options - Options for authenticating a user with authorization code.
547
581
  *
548
582
  * @returns The user's session containing authentication tokens and user information.
549
583
  *
550
584
  * @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,
551
585
  * or if 'expires_in' or 'scope' is missing from the token response.
552
586
  *
553
- * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized
587
+ * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized.
554
588
  * OAuth 2.0 error response.
555
589
  *
556
- * @throws {@link MonoCloudTokenError} - If ID Token validation fails
590
+ * @throws {@link MonoCloudTokenError} - If ID Token validation fails.
557
591
  *
558
592
  * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
559
593
  * unexpected status code during the request or a serialization error while processing the response.
@@ -597,11 +631,11 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
597
631
  * Refetches user information for an existing session using the userinfo endpoint.
598
632
  * Updates the session's user object with the latest user information while preserving existing properties.
599
633
  *
600
- * @param accessToken - Access token used to fetch the userinfo
601
- * @param session - The current MonoCloudSession
602
- * @param options - Userinfo refetch options
634
+ * @param accessToken - Access token used to fetch the userinfo.
635
+ * @param session - The current MonoCloudSession.
636
+ * @param options - Userinfo refetch options.
603
637
  *
604
- * @returns Updated session with the latest userinfo
638
+ * @returns Updated session with the latest userinfo.
605
639
  *
606
640
  * @throws {@link MonoCloudValidationError} - When the token scope does not contain openid scope
607
641
  *
@@ -628,8 +662,8 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
628
662
  * Refreshes an existing session using the refresh token.
629
663
  * This function requests new tokens using the refresh token and optionally updates user information.
630
664
  *
631
- * @param session - The current MonoCloudSession containing the refresh token
632
- * @param options - Session refresh options
665
+ * @param session - The current MonoCloudSession containing the refresh token.
666
+ * @param options - Session refresh options.
633
667
  *
634
668
  * @returns User's session containing refreshed authentication tokens and user information.
635
669
  *
@@ -691,10 +725,10 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
691
725
  /**
692
726
  * Revokes an access token or refresh token, rendering it invalid for future use.
693
727
  *
694
- * @param token - The token string to be revoked
695
- * @param tokenType - Hint about the token type ('access_token' or 'refresh_token')
728
+ * @param token - The token string to be revoked.
729
+ * @param tokenType - Hint about the token type ('access_token' or 'refresh_token').
696
730
  *
697
- * @returns If token revocation succeeded
731
+ * @returns If token revocation succeeded.
698
732
  *
699
733
  * @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type
700
734
  *
@@ -728,14 +762,14 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
728
762
  /**
729
763
  * Validates an ID Token.
730
764
  *
731
- * @param idToken - The ID Token JWT string to validate
732
- * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature
733
- * @param clockSkew - Number of seconds to adjust the current time to account for clock differences
734
- * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation
735
- * @param maxAge - maximum authentication age in seconds
736
- * @param nonce - nonce value to validate against the token's nonce claim
765
+ * @param idToken - The ID Token JWT string to validate.
766
+ * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature.
767
+ * @param clockSkew - Number of seconds to adjust the current time to account for clock differences.
768
+ * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation.
769
+ * @param maxAge - Maximum authentication age in seconds.
770
+ * @param nonce - Nonce value to validate against the token's nonce claim.
737
771
  *
738
- * @returns Validated ID Token claims
772
+ * @returns Validated ID Token claims.
739
773
  *
740
774
  * @throws {@link MonoCloudTokenError} - If ID Token validation fails
741
775
  *
@@ -788,11 +822,12 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
788
822
  }
789
823
  /**
790
824
  * Decodes the payload of a JSON Web Token (JWT) and returns it as an object.
791
- * **THIS METHOD DOES NOT VERIFY JWT TOKENS**.
792
825
  *
793
- * @param jwt - JWT to decode
826
+ * >Note: THIS METHOD DOES NOT VERIFY JWT TOKENS.
827
+ *
828
+ * @param jwt - JWT to decode.
794
829
  *
795
- * @returns Decoded payload
830
+ * @returns Decoded payload.
796
831
  *
797
832
  * @throws {@link MonoCloudTokenError} - If decoding fails
798
833
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["randomBytes","encodeBase64Url","stringToArrayBuffer","parseSpaceSeparated","now","findToken","decodeBase64Url","getPublicSigKeyFromIssuerJwks","stringToArrayBuffer"],"sources":["../src/errors/monocloud-auth-base-error.ts","../src/errors/monocloud-op-error.ts","../src/errors/monocloud-http-error.ts","../src/errors/monocloud-token-error.ts","../src/errors/monocloud-validation-error.ts","../src/client-auth.ts","../src/monocloud-oidc-client.ts"],"sourcesContent":["export class MonoCloudAuthBaseError extends Error {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudOPError extends MonoCloudAuthBaseError {\n error: string;\n\n errorDescription?: string;\n\n constructor(error: string, errorDescription?: string) {\n super(error);\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudHttpError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudTokenError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudValidationError extends MonoCloudAuthBaseError {}\n","import {\n encodeBase64Url,\n randomBytes,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { ClientAuthMethod, Jwk } from './types';\n\nconst algToSubtle = (\n alg?: string\n): HmacImportParams | RsaHashedImportParams | EcKeyImportParams => {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { name: 'HMAC', hash: `SHA-${alg.slice(-3)}` };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n /* v8 ignore next */\n default:\n throw new Error('unsupported JWS algorithm');\n }\n};\n\nconst psAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst rsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst esAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as EcKeyAlgorithm).namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported EcKeyAlgorithm namedCurve');\n }\n};\n\nconst hsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as HmacKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'HS256';\n case 'SHA-384':\n return 'HS384';\n case 'SHA-512':\n return 'HS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported HMAC Algorithm hash');\n }\n};\n\nconst keyToJws = (key: CryptoKey): string => {\n switch (key.algorithm.name) {\n case 'HMAC':\n return hsAlg(key);\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n /* v8 ignore next */\n default:\n throw new Error('unsupported CryptoKey algorithm name');\n }\n};\n\nconst checkRsaKeyAlgorithm = (key: CryptoKey): void => {\n const { algorithm } = key as CryptoKey & { algorithm: RsaHashedKeyAlgorithm };\n\n /* v8 ignore if -- @preserve */\n if (\n typeof algorithm.modulusLength !== 'number' ||\n algorithm.modulusLength < 2048\n ) {\n throw new Error(`Unsupported ${algorithm.name} modulusLength`);\n }\n};\n\nconst ecdsaHashName = (key: CryptoKey): string => {\n const { algorithm } = key as CryptoKey & { algorithm: EcKeyAlgorithm };\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported ECDSA namedCurve');\n }\n};\n\nexport const keyToSubtle = (\n key: CryptoKey\n): AlgorithmIdentifier | RsaPssParams | EcdsaParams => {\n switch (key.algorithm.name) {\n case 'HMAC': {\n return { name: key.algorithm.name };\n }\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n } as EcdsaParams;\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256': // Fall through\n case 'SHA-384': // Fall through\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength:\n parseInt(\n (key.algorithm as RsaHashedKeyAlgorithm).hash.name.slice(-3),\n 10\n ) >> 3,\n } as RsaPssParams;\n /* v8 ignore next */\n default:\n throw new Error('unsupported RSA-PSS hash name');\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n }\n /* v8 ignore next -- @preserve */\n throw new Error('unsupported CryptoKey algorithm name');\n};\n\nconst clientAssertionPayload = (\n issuer: string,\n clientId: string,\n skew: number\n): Record<string, number | string> => {\n const now = Math.floor(Date.now() / 1000) + skew;\n return {\n jti: randomBytes(),\n aud: issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: clientId,\n sub: clientId,\n };\n};\n\nconst jwtAssertionGenerator = async (\n issuer: string,\n clientId: string,\n clientSecret: Jwk,\n body: URLSearchParams,\n skew: number\n): Promise<void> => {\n const key = await crypto.subtle.importKey(\n 'jwk',\n clientSecret as JsonWebKey,\n algToSubtle(clientSecret.alg),\n false,\n ['sign']\n );\n\n const header = { alg: keyToJws(key), kid: clientSecret.kid };\n const payload = clientAssertionPayload(issuer, clientId, skew);\n\n body.set('client_id', clientId);\n body.set(\n 'client_assertion_type',\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n );\n\n const input = `${encodeBase64Url(stringToArrayBuffer(JSON.stringify(header)))}.${encodeBase64Url(stringToArrayBuffer(JSON.stringify(payload)))}`;\n const signature = encodeBase64Url(\n await crypto.subtle.sign(\n keyToSubtle(key),\n key,\n stringToArrayBuffer(input) as BufferSource\n )\n );\n\n body.set('client_assertion', `${input}.${signature}`);\n};\n\nexport const clientAuth = async (\n clientId: string,\n clientSecret?: string | Jwk,\n method?: ClientAuthMethod,\n issuer?: string,\n headers?: Record<string, string>,\n body?: URLSearchParams,\n jwtAssertionSkew?: number\n): Promise<void> => {\n switch (true) {\n case method === 'client_secret_basic' && !!headers: {\n // eslint-disable-next-line no-param-reassign\n headers.authorization = `Basic ${btoa(`${clientId}:${clientSecret ?? ''}`)}`;\n break;\n }\n\n case method === 'client_secret_post' && !!body: {\n body.set('client_id', clientId);\n if (typeof clientSecret === 'string') {\n body.set('client_secret', clientSecret);\n }\n break;\n }\n\n case method === 'client_secret_jwt' &&\n !!issuer &&\n !!body &&\n (typeof clientSecret === 'string' || clientSecret?.kty === 'oct'): {\n const cs =\n typeof clientSecret === 'string'\n ? {\n k: encodeBase64Url(stringToArrayBuffer(clientSecret)),\n kty: 'oct',\n alg: 'HS256',\n }\n : clientSecret;\n\n await jwtAssertionGenerator(\n issuer,\n clientId,\n cs,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n case method === 'private_key_jwt' &&\n typeof clientSecret === 'object' &&\n clientSecret.kty !== 'oct' &&\n !!issuer &&\n !!body: {\n await jwtAssertionGenerator(\n issuer,\n clientId,\n clientSecret,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n default:\n throw new Error('Invalid Client Authentication Method');\n }\n};\n","import {\n decodeBase64Url,\n findToken,\n getPublicSigKeyFromIssuerJwks,\n now,\n parseSpaceSeparated,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { clientAuth, keyToSubtle } from './client-auth';\nimport {\n AccessToken,\n AuthenticateOptions,\n AuthorizationParams,\n ClientAuthMethod,\n EndSessionParameters,\n IdTokenClaims,\n IssuerMetadata,\n Jwk,\n Jwks,\n JWSAlgorithm,\n JwsHeaderParameters,\n MonoCloudClientOptions,\n MonoCloudSession,\n MonoCloudUser,\n ParResponse,\n PushedAuthorizationParams,\n RefetchUserInfoOptions,\n RefreshGrantOptions,\n RefreshSessionOptions,\n Tokens,\n UserinfoResponse,\n} from './types';\nimport { MonoCloudOPError } from './errors/monocloud-op-error';\nimport { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { MonoCloudTokenError } from './errors/monocloud-token-error';\nimport { MonoCloudAuthBaseError } from './errors/monocloud-auth-base-error';\n\nconst JWT_ASSERTION_CLOCK_SKEW = 5;\n\nconst FILTER_ID_TOKEN_CLAIMS = [\n 'iss',\n 'exp',\n 'nbf',\n 'aud',\n 'nonce',\n 'iat',\n 'auth_time',\n 'c_hash',\n 'at_hash',\n 's_hash',\n];\n\nfunction assertMetadataProperty<K extends keyof IssuerMetadata>(\n metadata: IssuerMetadata,\n property: K\n): asserts metadata is IssuerMetadata & Required<Pick<IssuerMetadata, K>> {\n if (metadata[property] === undefined || metadata[property] === null) {\n throw new MonoCloudValidationError(\n `${property as string} endpoint is required but not available in the issuer metadata`\n );\n }\n}\n\nconst innerFetch = async (\n input: string,\n reqInit: RequestInit = {}\n): Promise<Response> => {\n try {\n return await fetch(input, reqInit);\n } catch (e) {\n /* v8 ignore next -- @preserve */\n throw new MonoCloudHttpError(\n (e as any).message ?? 'Unexpected Network Error'\n );\n }\n};\n\nconst deserializeJson = async <T = any>(res: Response): Promise<T> => {\n try {\n return await res.json();\n } catch (e) {\n throw new MonoCloudHttpError(\n /* v8 ignore next -- @preserve */\n `Failed to parse response body as JSON ${(e as any).message ? `: ${(e as any).message}` : ''}`\n );\n }\n};\n\nexport class MonoCloudOidcClient {\n private readonly tenantDomain: string;\n\n private readonly clientId: string;\n\n private readonly clientSecret?: string | Jwk;\n\n private readonly authMethod: ClientAuthMethod;\n\n private readonly idTokenSigningAlgorithm: JWSAlgorithm;\n\n private jwks?: Jwks;\n\n private jwksCacheExpiry = 0;\n\n private jwksCacheDuration = 60;\n\n private metadata?: IssuerMetadata;\n\n private metadataCacheExpiry = 0;\n\n private metadataCacheDuration = 60;\n\n constructor(\n tenantDomain: string,\n clientId: string,\n options?: MonoCloudClientOptions\n ) {\n // eslint-disable-next-line no-param-reassign\n tenantDomain ??= '';\n /* v8 ignore next -- @preserve */\n this.tenantDomain = `${!tenantDomain.startsWith('https://') ? 'https://' : ''}${tenantDomain.endsWith('/') ? tenantDomain.slice(0, -1) : tenantDomain}`;\n this.clientId = clientId;\n this.clientSecret = options?.clientSecret;\n this.authMethod = options?.clientAuthMethod ?? 'client_secret_basic';\n this.idTokenSigningAlgorithm = options?.idTokenSigningAlgorithm ?? 'RS256';\n\n if (options?.jwksCacheDuration) {\n this.jwksCacheDuration = options.jwksCacheDuration;\n }\n\n if (options?.metadataCacheDuration) {\n this.metadataCacheDuration = options.metadataCacheDuration;\n }\n }\n\n /**\n * Generates an authorization URL with specified parameters.\n *\n * If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.\n *\n * @param params Authorization URL parameters\n *\n * @returns Tenant's authorization url.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authorizationUrl(params: AuthorizationParams): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n queryParams.set('redirect_uri', params.redirectUri);\n }\n\n if (params.requestUri) {\n queryParams.set('request_uri', params.requestUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n queryParams.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n queryParams.set('response_type', params.responseType);\n }\n\n if (\n (!params.responseType || params.responseType.length === 0) &&\n !params.requestUri\n ) {\n queryParams.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n queryParams.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n queryParams.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n queryParams.set('request', params.request);\n }\n\n if (params.responseMode) {\n queryParams.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n queryParams.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n queryParams.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n queryParams.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n queryParams.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n queryParams.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n queryParams.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n queryParams.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n queryParams.set('code_challenge', params.codeChallenge);\n queryParams.set(\n 'code_challenge_method',\n params.codeChallengeMethod ?? 'S256'\n );\n }\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'authorization_endpoint');\n\n return `${metadata.authorization_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Fetches the authorization server metadata from the .well-known endpoint.\n * The metadata is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh metadata from the server.\n *\n * @returns The issuer metadata for the tenant, retrieved from the OpenID Connect discovery endpoint.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getMetadata(forceRefresh = false): Promise<IssuerMetadata> {\n if (!forceRefresh && this.metadata && this.metadataCacheExpiry > now()) {\n return this.metadata;\n }\n\n this.metadata = undefined;\n\n const response = await innerFetch(\n `${this.tenantDomain}/.well-known/openid-configuration`\n );\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching metadata. Unexpected status code: ${response.status}`\n );\n }\n\n const metadata = await deserializeJson<IssuerMetadata>(response);\n\n this.metadata = metadata;\n this.metadataCacheExpiry = now() + this.metadataCacheDuration;\n\n return metadata;\n }\n\n /**\n * Fetches the JSON Web Keys used to sign the id token.\n * The JWKS is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.\n *\n * @returns The JSON Web Key Set containing the public keys for token verification.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getJwks(forceRefresh = false): Promise<Jwks> {\n if (!forceRefresh && this.jwks && this.jwksCacheExpiry > now()) {\n return this.jwks;\n }\n\n this.jwks = undefined;\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'jwks_uri');\n\n const response = await innerFetch(metadata.jwks_uri);\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching JWKS. Unexpected status code: ${response.status}`\n );\n }\n const jwks = await deserializeJson<Jwks>(response);\n\n this.jwks = jwks;\n this.jwksCacheExpiry = now() + this.jwksCacheDuration;\n\n return jwks;\n }\n\n /**\n * Performs a pushed authorization request.\n *\n * @param params - Authorization Parameters\n *\n * @returns Response from Pushed Authorization Request (PAR) endpoint\n *\n * @throws {@link MonoCloudOPError} - When the request is invalid.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async pushedAuthorizationRequest(\n params: PushedAuthorizationParams\n ): Promise<ParResponse> {\n const body = new URLSearchParams();\n\n body.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n body.set('redirect_uri', params.redirectUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n body.set('response_type', params.responseType);\n } else {\n body.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n body.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n body.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n body.set('request', params.request);\n }\n\n if (params.responseMode) {\n body.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n body.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n body.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n body.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n body.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n body.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n body.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n body.set('code_challenge', params.codeChallenge);\n body.set('code_challenge_method', params.codeChallengeMethod ?? 'S256');\n }\n\n if (params.state) {\n body.set('state', params.state);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'pushed_authorization_request_endpoint');\n\n const response = await innerFetch(\n metadata.pushed_authorization_request_endpoint,\n {\n body: body.toString(),\n method: 'POST',\n headers,\n }\n );\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'par_request_failed',\n standardBodyError.error_description ??\n 'Pushed Authorization Request Failed'\n );\n }\n\n if (response.status !== 201) {\n throw new MonoCloudHttpError(\n `Error while performing pushed authorization request. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<ParResponse>(response);\n }\n\n /**\n * Fetches userinfo associated with the provided access token.\n *\n * @param accessToken - A valid access token used to retrieve userinfo.\n *\n * @returns The authenticated user's claims.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error (e.g., 'invalid_token') in the 'WWW-Authenticate' header\n * following a 401 Unauthorized response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n * @throws {@link MonoCloudValidationError} - When the access token is invalid.\n *\n */\n async userinfo(accessToken: string): Promise<UserinfoResponse> {\n if (!accessToken.trim().length) {\n throw new MonoCloudValidationError(\n 'Access token is required for fetching userinfo'\n );\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'userinfo_endpoint');\n\n const response = await innerFetch(metadata.userinfo_endpoint, {\n method: 'GET',\n headers: {\n authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (response.status === 401) {\n const authenticateError = response.headers.get('WWW-Authenticate');\n\n if (authenticateError) {\n const errorMatch = /error=\"([^\"]+)\"/.exec(authenticateError);\n const error = errorMatch ? errorMatch[1] : 'userinfo_failed';\n\n const errorDescMatch = /error_description=\"([^\"]+)\"/.exec(\n authenticateError\n );\n\n const errorDescription = errorDescMatch\n ? errorDescMatch[1]\n : 'Userinfo authentication error';\n\n throw new MonoCloudOPError(error, errorDescription);\n }\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching userinfo. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<UserinfoResponse>(response);\n }\n\n /**\n * Generates OpenID end session url for signing out.\n *\n * Note - The `state` is added only when `postLogoutRedirectUri` is present.\n *\n * @param params - Parameters to build end session url\n *\n * @returns Tenant's end session url\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async endSessionUrl(params: EndSessionParameters): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.idToken) {\n queryParams.set('id_token_hint', params.idToken);\n }\n\n if (params.postLogoutRedirectUri) {\n queryParams.set('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'end_session_endpoint');\n\n return `${metadata.end_session_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Exchanges an authorization code for tokens.\n *\n * @param code - The authorization code received from the authorization server.\n * @param redirectUri - The redirect URI used in the initial authorization request.\n * @param codeVerifier - Code verifier for PKCE.\n * @param resource - Space-separated list of resources the access token should be scoped to\n *\n * @returns Tokens obtained by exchanging an authorization code at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async exchangeAuthorizationCode(\n code: string,\n redirectUri: string,\n codeVerifier?: string,\n resource?: string\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'authorization_code');\n body.set('code', code);\n body.set('redirect_uri', redirectUri);\n\n if (codeVerifier) {\n body.set('code_verifier', codeVerifier);\n }\n\n const resources = parseSpaceSeparated(resource) ?? [];\n\n if (resources.length > 0) {\n for (const r of resources) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'code_grant_failed',\n standardBodyError.error_description ?? 'Authorization code grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Exchanges a refresh token for new tokens.\n *\n * @param refreshToken - The refresh token used to request new tokens.\n * @param options - Refresh grant options.\n *\n * @returns Tokens obtained by exchanging a refresh token at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshGrant(\n refreshToken: string,\n options?: RefreshGrantOptions\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'refresh_token');\n body.set('refresh_token', refreshToken);\n\n const scopes = parseSpaceSeparated(options?.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n const resource = parseSpaceSeparated(options?.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'refresh_grant_failed',\n standardBodyError.error_description ?? 'Refresh token grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing refresh token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Generates a session with user and tokens by exchanging authorization code from callback params.\n *\n * @param code - The authorization code received from the callback\n * @param redirectUri - The redirect URI that was used in the authorization request\n * @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.\n * This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.\n * @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.\n * Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.\n * @param options - Options for authenticating a user with authorization code\n *\n * @returns The user's session containing authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,\n * or if 'expires_in' or 'scope' is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authenticate(\n code: string,\n redirectUri: string,\n requestedScopes: string,\n resource?: string,\n options?: AuthenticateOptions\n ): Promise<MonoCloudSession> {\n const tokens = await this.exchangeAuthorizationCode(\n code,\n redirectUri,\n options?.codeVerifier,\n resource\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0,\n options?.idTokenMaxAge,\n options?.idTokenNonce\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const session: MonoCloudSession = {\n user: {\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser,\n idToken: tokens.id_token,\n refreshToken: tokens.refresh_token,\n authorizedScopes: requestedScopes,\n accessTokens: [\n {\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes,\n },\n ],\n };\n\n await options?.onSessionCreating?.(session, idTokenClaims, userinfo);\n\n return session;\n }\n\n /**\n * Refetches user information for an existing session using the userinfo endpoint.\n * Updates the session's user object with the latest user information while preserving existing properties.\n *\n * @param accessToken - Access token used to fetch the userinfo\n * @param session - The current MonoCloudSession\n * @param options - Userinfo refetch options\n *\n * @returns Updated session with the latest userinfo\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain openid scope\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refetchUserInfo(\n accessToken: AccessToken,\n session: MonoCloudSession,\n options?: RefetchUserInfoOptions\n ): Promise<MonoCloudSession> {\n if (!accessToken.scopes?.includes('openid')) {\n throw new MonoCloudValidationError(\n 'Fetching userinfo requires the openid scope'\n );\n }\n\n const userinfo = await this.userinfo(accessToken.accessToken);\n\n // eslint-disable-next-line no-param-reassign\n session.user = { ...session.user, ...userinfo };\n\n await options?.onSessionCreating?.(session, undefined, userinfo);\n\n return session;\n }\n\n /**\n * Refreshes an existing session using the refresh token.\n * This function requests new tokens using the refresh token and optionally updates user information.\n *\n * @param session - The current MonoCloudSession containing the refresh token\n * @param options - Session refresh options\n *\n * @returns User's session containing refreshed authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - If the refresh token is not present in the session,\n * or if 'expires_in' or 'scope' (including the openid scope) is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshSession(\n session: MonoCloudSession,\n options?: RefreshSessionOptions\n ): Promise<MonoCloudSession> {\n if (!session.refreshToken) {\n throw new MonoCloudValidationError(\n 'Session does not contain refresh token'\n );\n }\n\n const tokens = await this.refreshGrant(\n session.refreshToken,\n options?.refreshGrantOptions\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const resource = options?.refreshGrantOptions?.resource;\n let scopes = options?.refreshGrantOptions?.scopes;\n\n if (!resource && !scopes) {\n scopes = session.authorizedScopes;\n }\n\n const accessToken = findToken(session.accessTokens, resource, scopes);\n\n const user =\n Object.keys(idTokenClaims).length === 0 && !userinfo\n ? session.user\n : ({\n ...session.user,\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser);\n\n const newTokens =\n session.accessTokens?.filter(t => t !== accessToken) ?? [];\n\n newTokens.push({\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes: scopes,\n });\n\n const updatedSession: MonoCloudSession = {\n ...session,\n user,\n idToken: tokens.id_token ?? session.idToken,\n refreshToken: tokens.refresh_token ?? session.refreshToken,\n accessTokens: newTokens,\n };\n\n await options?.onSessionCreating?.(updatedSession, idTokenClaims, userinfo);\n\n return updatedSession;\n }\n\n /**\n * Revokes an access token or refresh token, rendering it invalid for future use.\n *\n * @param token - The token string to be revoked\n * @param tokenType - Hint about the token type ('access_token' or 'refresh_token')\n *\n * @returns If token revocation succeeded\n *\n * @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n */\n async revokeToken(token: string, tokenType?: string): Promise<void> {\n if (!token.trim().length) {\n throw new MonoCloudValidationError('Invalid token');\n }\n\n if (\n tokenType &&\n tokenType !== 'access_token' &&\n tokenType !== 'refresh_token'\n ) {\n throw new MonoCloudValidationError(\n 'Only access_token and refresh_token types are supported.'\n );\n }\n\n const body = new URLSearchParams();\n body.set('token', token);\n if (tokenType) {\n body.set('token_type_hint', tokenType);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'revocation_endpoint');\n\n const response = await innerFetch(metadata.revocation_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'revocation_failed',\n standardBodyError.error_description ?? 'Token revocation failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing revocation request. Unexpected status code: ${response.status}`\n );\n }\n }\n\n /**\n * Validates an ID Token.\n *\n * @param idToken - The ID Token JWT string to validate\n * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature\n * @param clockSkew - Number of seconds to adjust the current time to account for clock differences\n * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation\n * @param maxAge - maximum authentication age in seconds\n * @param nonce - nonce value to validate against the token's nonce claim\n *\n * @returns Validated ID Token claims\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n */\n async validateIdToken(\n idToken: string,\n jwks: Jwk[],\n clockSkew: number,\n clockTolerance: number,\n maxAge?: number,\n nonce?: string\n ): Promise<IdTokenClaims> {\n if (typeof idToken !== 'string' || idToken.trim().length === 0) {\n throw new MonoCloudTokenError(\n 'ID Token must be a valid non-empty string'\n );\n }\n\n const {\n 0: protectedHeader,\n 1: payload,\n 2: encodedSignature,\n length,\n } = idToken.split('.');\n\n if (length !== 3) {\n throw new MonoCloudTokenError(\n 'ID Token must have a header, payload and signature'\n );\n }\n\n let header: JwsHeaderParameters;\n try {\n header = JSON.parse(decodeBase64Url(protectedHeader));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Header');\n }\n\n if (\n header === null ||\n typeof header !== 'object' ||\n Array.isArray(header)\n ) {\n throw new MonoCloudTokenError('JWT Header must be a top level object');\n }\n\n if (this.idTokenSigningAlgorithm !== header.alg) {\n throw new MonoCloudTokenError('Invalid signing alg');\n }\n\n if (header.crit !== undefined) {\n throw new MonoCloudTokenError('Unexpected JWT \"crit\" header parameter');\n }\n\n const binary = decodeBase64Url(encodedSignature);\n\n const signature = new Uint8Array(binary.length);\n\n for (let i = 0; i < binary.length; i++) {\n signature[i] = binary.charCodeAt(i);\n }\n\n const key = await getPublicSigKeyFromIssuerJwks(jwks, header);\n\n const input = `${protectedHeader}.${payload}`;\n\n const verified = await crypto.subtle.verify(\n keyToSubtle(key),\n key,\n signature,\n stringToArrayBuffer(input) as BufferSource\n );\n\n if (!verified) {\n throw new MonoCloudTokenError('JWT signature verification failed');\n }\n\n let claims: IdTokenClaims;\n\n try {\n claims = JSON.parse(decodeBase64Url(payload));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Payload');\n }\n\n if (\n claims === null ||\n typeof claims !== 'object' ||\n Array.isArray(claims)\n ) {\n throw new MonoCloudTokenError('JWT Payload must be a top level object');\n }\n\n if ((claims.nonce || nonce) && claims.nonce !== nonce) {\n throw new MonoCloudTokenError('Nonce mismatch');\n }\n\n const current = now() + clockSkew;\n\n /* v8 ignore else -- @preserve */\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim type'\n );\n }\n\n if (claims.exp <= current - clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim value, timestamp is <= now()'\n );\n }\n }\n\n /* v8 ignore else -- @preserve */\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"iat\" (issued at) claim type'\n );\n }\n }\n\n if (\n typeof claims.auth_time === 'number' &&\n typeof maxAge === 'number' &&\n claims.auth_time + maxAge < current\n ) {\n throw new MonoCloudTokenError(\n 'Too much time has elapsed since the last End-User authentication'\n );\n }\n\n if (claims.iss !== this.tenantDomain) {\n throw new MonoCloudTokenError('Invalid Issuer');\n }\n\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim type'\n );\n }\n\n if (claims.nbf > current + clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim value, timestamp is > now()'\n );\n }\n }\n\n const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n\n if (!audience.includes(this.clientId)) {\n throw new MonoCloudTokenError('Invalid audience claim');\n }\n\n return claims;\n }\n\n /**\n * Decodes the payload of a JSON Web Token (JWT) and returns it as an object.\n * **THIS METHOD DOES NOT VERIFY JWT TOKENS**.\n *\n * @param jwt - JWT to decode\n *\n * @returns Decoded payload\n *\n * @throws {@link MonoCloudTokenError} - If decoding fails\n *\n */\n static decodeJwt(jwt: string): IdTokenClaims {\n try {\n const [, payload] = jwt.split('.');\n\n if (!payload?.trim()) {\n throw new MonoCloudTokenError('JWT does not contain payload');\n }\n\n const decoded = decodeBase64Url(payload);\n\n if (!decoded.startsWith('{')) {\n throw new MonoCloudTokenError('Payload is not an object');\n }\n\n return JSON.parse(decoded) as IdTokenClaims;\n } catch (e) {\n if (e instanceof MonoCloudAuthBaseError) {\n throw e;\n }\n\n throw new MonoCloudTokenError(\n 'Could not parse payload. Malformed payload'\n );\n }\n }\n}\n"],"mappings":";;;;AAAA,IAAa,yBAAb,cAA4C,MAAM;;;;ACElD,IAAa,mBAAb,cAAsC,uBAAuB;CAK3D,YAAY,OAAe,kBAA2B;AACpD,QAAM,MAAM;AACZ,O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oBACR,8EACD;;;AAKL,MAAI,OAAO,QAAQ,QACjB;OAAI,OAAO,OAAO,QAAQ,SACxB,OAAM,IAAI,oBACR,gDACD;;AAIL,MACE,OAAO,OAAO,cAAc,YAC5B,OAAO,WAAW,YAClB,OAAO,YAAY,SAAS,QAE5B,OAAM,IAAI,oBACR,mEACD;AAGH,MAAI,OAAO,QAAQ,KAAK,aACtB,OAAM,IAAI,oBAAoB,iBAAiB;AAGjD,MAAI,OAAO,QAAQ,QAAW;AAC5B,OAAI,OAAO,OAAO,QAAQ,SACxB,OAAM,IAAI,oBACR,iDACD;AAGH,OAAI,OAAO,MAAM,UAAU,eACzB,OAAM,IAAI,oBACR,wEACD;;AAML,MAAI,EAFa,MAAM,QAAQ,OAAO,IAAI,GAAG,OAAO,MAAM,CAAC,OAAO,IAAI,EAExD,SAAS,KAAK,SAAS,CACnC,OAAM,IAAI,oBAAoB,yBAAyB;AAGzD,SAAO;;;;;;;;;;;;;CAcT,OAAO,UAAU,KAA4B;AAC3C,MAAI;GACF,MAAM,GAAG,WAAW,IAAI,MAAM,IAAI;AAElC,OAAI,CAAC,SAAS,MAAM,CAClB,OAAM,IAAI,oBAAoB,+BAA+B;GAG/D,MAAM,UAAUE,uCAAgB,QAAQ;AAExC,OAAI,CAAC,QAAQ,WAAW,IAAI,CAC1B,OAAM,IAAI,oBAAoB,2BAA2B;AAG3D,UAAO,KAAK,MAAM,QAAQ;WACnB,GAAG;AACV,OAAI,aAAa,uBACf,OAAM;AAGR,SAAM,IAAI,oBACR,6CACD"}
1
+ {"version":3,"file":"index.cjs","names":["randomBytes","encodeBase64Url","stringToArrayBuffer","parseSpaceSeparated","now","findToken","decodeBase64Url","getPublicSigKeyFromIssuerJwks","stringToArrayBuffer"],"sources":["../src/errors/monocloud-auth-base-error.ts","../src/errors/monocloud-op-error.ts","../src/errors/monocloud-http-error.ts","../src/errors/monocloud-token-error.ts","../src/errors/monocloud-validation-error.ts","../src/client-auth.ts","../src/monocloud-oidc-client.ts"],"sourcesContent":["/**\n * Base class for all MonoCloud authentication errors.\n *\n * All errors thrown by the MonoCloud SDK extend this class, allowing applications to safely detect and handle MonoCloud-specific failures using `instanceof`.\n *\n * @category Error Classes\n */\nexport class MonoCloudAuthBaseError extends Error {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * OAuth error returned by the authorization server during an authentication or token request.\n *\n * These errors correspond to standard OAuth / OpenID Connect error responses such as `invalid_request`, `access_denied`, or `invalid_grant`.\n *\n * @category Error Classes\n */\nexport class MonoCloudOPError extends MonoCloudAuthBaseError {\n /** OAuth error code returned by the authorization server. */\n error: string;\n\n /** Human-readable description of the error. */\n errorDescription?: string;\n\n constructor(error: string, errorDescription?: string) {\n super(error);\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when a request to the MonoCloud authorization server fails.\n *\n * This error typically indicates a network failure, an unexpected HTTP response, or an unsuccessful response returned by the authorization server.\n *\n * @category Error Classes\n */\nexport class MonoCloudHttpError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when a token operation fails.\n *\n * @category Error Classes\n */\nexport class MonoCloudTokenError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when validation fails.\n *\n * @category Error Classes\n */\nexport class MonoCloudValidationError extends MonoCloudAuthBaseError {}\n","import {\n encodeBase64Url,\n randomBytes,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { ClientAuthMethod, Jwk } from './types';\n\nconst algToSubtle = (\n alg?: string\n): HmacImportParams | RsaHashedImportParams | EcKeyImportParams => {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { name: 'HMAC', hash: `SHA-${alg.slice(-3)}` };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n /* v8 ignore next */\n default:\n throw new Error('unsupported JWS algorithm');\n }\n};\n\nconst psAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst rsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst esAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as EcKeyAlgorithm).namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported EcKeyAlgorithm namedCurve');\n }\n};\n\nconst hsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as HmacKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'HS256';\n case 'SHA-384':\n return 'HS384';\n case 'SHA-512':\n return 'HS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported HMAC Algorithm hash');\n }\n};\n\nconst keyToJws = (key: CryptoKey): string => {\n switch (key.algorithm.name) {\n case 'HMAC':\n return hsAlg(key);\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n /* v8 ignore next */\n default:\n throw new Error('unsupported CryptoKey algorithm name');\n }\n};\n\nconst checkRsaKeyAlgorithm = (key: CryptoKey): void => {\n const { algorithm } = key as CryptoKey & { algorithm: RsaHashedKeyAlgorithm };\n\n /* v8 ignore if -- @preserve */\n if (\n typeof algorithm.modulusLength !== 'number' ||\n algorithm.modulusLength < 2048\n ) {\n throw new Error(`Unsupported ${algorithm.name} modulusLength`);\n }\n};\n\nconst ecdsaHashName = (key: CryptoKey): string => {\n const { algorithm } = key as CryptoKey & { algorithm: EcKeyAlgorithm };\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported ECDSA namedCurve');\n }\n};\n\nexport const keyToSubtle = (\n key: CryptoKey\n): AlgorithmIdentifier | RsaPssParams | EcdsaParams => {\n switch (key.algorithm.name) {\n case 'HMAC': {\n return { name: key.algorithm.name };\n }\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n } as EcdsaParams;\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256': // Fall through\n case 'SHA-384': // Fall through\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength:\n parseInt(\n (key.algorithm as RsaHashedKeyAlgorithm).hash.name.slice(-3),\n 10\n ) >> 3,\n } as RsaPssParams;\n /* v8 ignore next */\n default:\n throw new Error('unsupported RSA-PSS hash name');\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n }\n /* v8 ignore next -- @preserve */\n throw new Error('unsupported CryptoKey algorithm name');\n};\n\nconst clientAssertionPayload = (\n issuer: string,\n clientId: string,\n skew: number\n): Record<string, number | string> => {\n const now = Math.floor(Date.now() / 1000) + skew;\n return {\n jti: randomBytes(),\n aud: issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: clientId,\n sub: clientId,\n };\n};\n\nconst jwtAssertionGenerator = async (\n issuer: string,\n clientId: string,\n clientSecret: Jwk,\n body: URLSearchParams,\n skew: number\n): Promise<void> => {\n const key = await crypto.subtle.importKey(\n 'jwk',\n clientSecret as JsonWebKey,\n algToSubtle(clientSecret.alg),\n false,\n ['sign']\n );\n\n const header = { alg: keyToJws(key), kid: clientSecret.kid };\n const payload = clientAssertionPayload(issuer, clientId, skew);\n\n body.set('client_id', clientId);\n body.set(\n 'client_assertion_type',\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n );\n\n const input = `${encodeBase64Url(stringToArrayBuffer(JSON.stringify(header)))}.${encodeBase64Url(stringToArrayBuffer(JSON.stringify(payload)))}`;\n const signature = encodeBase64Url(\n await crypto.subtle.sign(\n keyToSubtle(key),\n key,\n stringToArrayBuffer(input) as BufferSource\n )\n );\n\n body.set('client_assertion', `${input}.${signature}`);\n};\n\nexport const clientAuth = async (\n clientId: string,\n clientSecret?: string | Jwk,\n method?: ClientAuthMethod,\n issuer?: string,\n headers?: Record<string, string>,\n body?: URLSearchParams,\n jwtAssertionSkew?: number\n): Promise<void> => {\n switch (true) {\n case method === 'client_secret_basic' && !!headers: {\n // eslint-disable-next-line no-param-reassign\n headers.authorization = `Basic ${btoa(`${clientId}:${clientSecret ?? ''}`)}`;\n break;\n }\n\n case method === 'client_secret_post' && !!body: {\n body.set('client_id', clientId);\n if (typeof clientSecret === 'string') {\n body.set('client_secret', clientSecret);\n }\n break;\n }\n\n case method === 'client_secret_jwt' &&\n !!issuer &&\n !!body &&\n (typeof clientSecret === 'string' || clientSecret?.kty === 'oct'): {\n const cs =\n typeof clientSecret === 'string'\n ? {\n k: encodeBase64Url(stringToArrayBuffer(clientSecret)),\n kty: 'oct',\n alg: 'HS256',\n }\n : clientSecret;\n\n await jwtAssertionGenerator(\n issuer,\n clientId,\n cs,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n case method === 'private_key_jwt' &&\n typeof clientSecret === 'object' &&\n clientSecret.kty !== 'oct' &&\n !!issuer &&\n !!body: {\n await jwtAssertionGenerator(\n issuer,\n clientId,\n clientSecret,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n default:\n throw new Error('Invalid Client Authentication Method');\n }\n};\n","import {\n decodeBase64Url,\n findToken,\n getPublicSigKeyFromIssuerJwks,\n now,\n parseSpaceSeparated,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { clientAuth, keyToSubtle } from './client-auth';\nimport {\n AccessToken,\n AuthenticateOptions,\n AuthorizationParams,\n ClientAuthMethod,\n EndSessionParameters,\n IdTokenClaims,\n IssuerMetadata,\n Jwk,\n Jwks,\n SecurityAlgorithms,\n JwsHeaderParameters,\n MonoCloudClientOptions,\n MonoCloudSession,\n MonoCloudUser,\n ParResponse,\n PushedAuthorizationParams,\n RefetchUserInfoOptions,\n RefreshGrantOptions,\n RefreshSessionOptions,\n Tokens,\n UserinfoResponse,\n} from './types';\nimport { MonoCloudOPError } from './errors/monocloud-op-error';\nimport { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { MonoCloudTokenError } from './errors/monocloud-token-error';\nimport { MonoCloudAuthBaseError } from './errors/monocloud-auth-base-error';\n\nconst JWT_ASSERTION_CLOCK_SKEW = 5;\n\nconst FILTER_ID_TOKEN_CLAIMS = [\n 'iss',\n 'exp',\n 'nbf',\n 'aud',\n 'nonce',\n 'iat',\n 'auth_time',\n 'c_hash',\n 'at_hash',\n 's_hash',\n];\n\nfunction assertMetadataProperty<K extends keyof IssuerMetadata>(\n metadata: IssuerMetadata,\n property: K\n): asserts metadata is IssuerMetadata & Required<Pick<IssuerMetadata, K>> {\n if (metadata[property] === undefined || metadata[property] === null) {\n throw new MonoCloudValidationError(\n `${property as string} endpoint is required but not available in the issuer metadata`\n );\n }\n}\n\nconst innerFetch = async (\n input: string,\n reqInit: RequestInit = {}\n): Promise<Response> => {\n try {\n return await fetch(input, reqInit);\n } catch (e) {\n /* v8 ignore next -- @preserve */\n throw new MonoCloudHttpError(\n (e as any).message ?? 'Unexpected Network Error'\n );\n }\n};\n\nconst deserializeJson = async <T = any>(res: Response): Promise<T> => {\n try {\n return await res.json();\n } catch (e) {\n throw new MonoCloudHttpError(\n /* v8 ignore next -- @preserve */\n `Failed to parse response body as JSON ${(e as any).message ? `: ${(e as any).message}` : ''}`\n );\n }\n};\n\n/**\n * @category Classes\n */\nexport class MonoCloudOidcClient {\n private readonly tenantDomain: string;\n\n private readonly clientId: string;\n\n private readonly clientSecret?: string | Jwk;\n\n private readonly authMethod: ClientAuthMethod;\n\n private readonly idTokenSigningAlgorithm: SecurityAlgorithms;\n\n private jwks?: Jwks;\n\n private jwksCacheExpiry = 0;\n\n private jwksCacheDuration = 300;\n\n private metadata?: IssuerMetadata;\n\n private metadataCacheExpiry = 0;\n\n private metadataCacheDuration = 300;\n\n constructor(\n tenantDomain: string,\n clientId: string,\n options?: MonoCloudClientOptions\n ) {\n // eslint-disable-next-line no-param-reassign\n tenantDomain ??= '';\n /* v8 ignore next -- @preserve */\n this.tenantDomain = `${!tenantDomain.startsWith('https://') ? 'https://' : ''}${tenantDomain.endsWith('/') ? tenantDomain.slice(0, -1) : tenantDomain}`;\n this.clientId = clientId;\n this.clientSecret = options?.clientSecret;\n this.authMethod = options?.clientAuthMethod ?? 'client_secret_basic';\n this.idTokenSigningAlgorithm = options?.idTokenSigningAlgorithm ?? 'RS256';\n\n if (options?.jwksCacheDuration) {\n this.jwksCacheDuration = options.jwksCacheDuration;\n }\n\n if (options?.metadataCacheDuration) {\n this.metadataCacheDuration = options.metadataCacheDuration;\n }\n }\n\n /**\n * Generates an authorization URL with specified parameters.\n *\n * If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.\n *\n * @param params - Authorization URL parameters.\n *\n * @returns Tenant's authorization URL.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authorizationUrl(params: AuthorizationParams): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n queryParams.set('redirect_uri', params.redirectUri);\n }\n\n if (params.requestUri) {\n queryParams.set('request_uri', params.requestUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n queryParams.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n queryParams.set('response_type', params.responseType);\n }\n\n if (\n (!params.responseType || params.responseType.length === 0) &&\n !params.requestUri\n ) {\n queryParams.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n queryParams.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n queryParams.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n queryParams.set('request', params.request);\n }\n\n if (params.responseMode) {\n queryParams.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n queryParams.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n queryParams.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n queryParams.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n queryParams.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n queryParams.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n queryParams.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n queryParams.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n queryParams.set('code_challenge', params.codeChallenge);\n queryParams.set(\n 'code_challenge_method',\n params.codeChallengeMethod ?? 'S256'\n );\n }\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'authorization_endpoint');\n\n return `${metadata.authorization_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Fetches the authorization server metadata from the .well-known endpoint.\n * The metadata is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh metadata from the server.\n *\n * @returns The issuer metadata for the tenant, retrieved from the OpenID Connect discovery endpoint.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getMetadata(forceRefresh = false): Promise<IssuerMetadata> {\n if (!forceRefresh && this.metadata && this.metadataCacheExpiry > now()) {\n return this.metadata;\n }\n\n this.metadata = undefined;\n\n const response = await innerFetch(\n `${this.tenantDomain}/.well-known/openid-configuration`\n );\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching metadata. Unexpected status code: ${response.status}`\n );\n }\n\n const metadata = await deserializeJson<IssuerMetadata>(response);\n\n this.metadata = metadata;\n this.metadataCacheExpiry = now() + this.metadataCacheDuration;\n\n return metadata;\n }\n\n /**\n * Fetches the JSON Web Keys used to sign the ID token.\n * The JWKS is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.\n *\n * @returns The JSON Web Key Set containing the public keys for token verification.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getJwks(forceRefresh = false): Promise<Jwks> {\n if (!forceRefresh && this.jwks && this.jwksCacheExpiry > now()) {\n return this.jwks;\n }\n\n this.jwks = undefined;\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'jwks_uri');\n\n const response = await innerFetch(metadata.jwks_uri);\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching JWKS. Unexpected status code: ${response.status}`\n );\n }\n const jwks = await deserializeJson<Jwks>(response);\n\n this.jwks = jwks;\n this.jwksCacheExpiry = now() + this.jwksCacheDuration;\n\n return jwks;\n }\n\n /**\n * Performs a pushed authorization request.\n *\n * @param params - Authorization Parameters.\n *\n * @returns Response from Pushed Authorization Request (PAR) endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the request is invalid.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async pushedAuthorizationRequest(\n params: PushedAuthorizationParams\n ): Promise<ParResponse> {\n const body = new URLSearchParams();\n\n body.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n body.set('redirect_uri', params.redirectUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n body.set('response_type', params.responseType);\n } else {\n body.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n body.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n body.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n body.set('request', params.request);\n }\n\n if (params.responseMode) {\n body.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n body.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n body.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n body.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n body.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n body.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n body.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n body.set('code_challenge', params.codeChallenge);\n body.set('code_challenge_method', params.codeChallengeMethod ?? 'S256');\n }\n\n if (params.state) {\n body.set('state', params.state);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'pushed_authorization_request_endpoint');\n\n const response = await innerFetch(\n metadata.pushed_authorization_request_endpoint,\n {\n body: body.toString(),\n method: 'POST',\n headers,\n }\n );\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'par_request_failed',\n standardBodyError.error_description ??\n 'Pushed Authorization Request Failed'\n );\n }\n\n if (response.status !== 201) {\n throw new MonoCloudHttpError(\n `Error while performing pushed authorization request. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<ParResponse>(response);\n }\n\n /**\n * Fetches userinfo associated with the provided access token.\n *\n * @param accessToken - A valid access token used to retrieve userinfo.\n *\n * @returns The authenticated user's claims.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error (e.g., 'invalid_token') in the 'WWW-Authenticate' header\n * following a 401 Unauthorized response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n * @throws {@link MonoCloudValidationError} - When the access token is invalid.\n *\n */\n async userinfo(accessToken: string): Promise<UserinfoResponse> {\n if (!accessToken.trim().length) {\n throw new MonoCloudValidationError(\n 'Access token is required for fetching userinfo'\n );\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'userinfo_endpoint');\n\n const response = await innerFetch(metadata.userinfo_endpoint, {\n method: 'GET',\n headers: {\n authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (response.status === 401) {\n const authenticateError = response.headers.get('WWW-Authenticate');\n\n if (authenticateError) {\n const errorMatch = /error=\"([^\"]+)\"/.exec(authenticateError);\n const error = errorMatch ? errorMatch[1] : 'userinfo_failed';\n\n const errorDescMatch = /error_description=\"([^\"]+)\"/.exec(\n authenticateError\n );\n\n const errorDescription = errorDescMatch\n ? errorDescMatch[1]\n : 'Userinfo authentication error';\n\n throw new MonoCloudOPError(error, errorDescription);\n }\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching userinfo. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<UserinfoResponse>(response);\n }\n\n /**\n * Generates OpenID end session URL for signing out.\n *\n * Note - The `state` is added only when `postLogoutRedirectUri` is present.\n *\n * @param params - Parameters to build end session URL.\n *\n * @returns Tenant's end session URL.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async endSessionUrl(params: EndSessionParameters): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.idToken) {\n queryParams.set('id_token_hint', params.idToken);\n }\n\n if (params.postLogoutRedirectUri) {\n queryParams.set('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'end_session_endpoint');\n\n return `${metadata.end_session_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Exchanges an authorization code for tokens.\n *\n * @param code - The authorization code received from the authorization server.\n * @param redirectUri - The redirect URI used in the initial authorization request.\n * @param codeVerifier - Code verifier for PKCE.\n * @param resource - Space-separated list of resources the access token should be scoped to.\n *\n * @returns Tokens obtained by exchanging an authorization code at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async exchangeAuthorizationCode(\n code: string,\n redirectUri: string,\n codeVerifier?: string,\n resource?: string\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'authorization_code');\n body.set('code', code);\n body.set('redirect_uri', redirectUri);\n\n if (codeVerifier) {\n body.set('code_verifier', codeVerifier);\n }\n\n const resources = parseSpaceSeparated(resource) ?? [];\n\n if (resources.length > 0) {\n for (const r of resources) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'code_grant_failed',\n standardBodyError.error_description ?? 'Authorization code grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Exchanges a refresh token for new tokens.\n *\n * @param refreshToken - The refresh token used to request new tokens.\n * @param options - Refresh grant options.\n *\n * @returns Tokens obtained by exchanging a refresh token at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshGrant(\n refreshToken: string,\n options?: RefreshGrantOptions\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'refresh_token');\n body.set('refresh_token', refreshToken);\n\n const scopes = parseSpaceSeparated(options?.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n const resource = parseSpaceSeparated(options?.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'refresh_grant_failed',\n standardBodyError.error_description ?? 'Refresh token grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing refresh token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Generates a session with user and tokens by exchanging authorization code from callback params.\n *\n * @param code - The authorization code received from the callback.\n * @param redirectUri - The redirect URI that was used in the authorization request.\n * @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.\n * This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.\n * @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.\n * Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.\n * @param options - Options for authenticating a user with authorization code.\n *\n * @returns The user's session containing authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,\n * or if 'expires_in' or 'scope' is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized.\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authenticate(\n code: string,\n redirectUri: string,\n requestedScopes: string,\n resource?: string,\n options?: AuthenticateOptions\n ): Promise<MonoCloudSession> {\n const tokens = await this.exchangeAuthorizationCode(\n code,\n redirectUri,\n options?.codeVerifier,\n resource\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0,\n options?.idTokenMaxAge,\n options?.idTokenNonce\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const session: MonoCloudSession = {\n user: {\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser,\n idToken: tokens.id_token,\n refreshToken: tokens.refresh_token,\n authorizedScopes: requestedScopes,\n accessTokens: [\n {\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes,\n },\n ],\n };\n\n await options?.onSessionCreating?.(session, idTokenClaims, userinfo);\n\n return session;\n }\n\n /**\n * Refetches user information for an existing session using the userinfo endpoint.\n * Updates the session's user object with the latest user information while preserving existing properties.\n *\n * @param accessToken - Access token used to fetch the userinfo.\n * @param session - The current MonoCloudSession.\n * @param options - Userinfo refetch options.\n *\n * @returns Updated session with the latest userinfo.\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain openid scope\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refetchUserInfo(\n accessToken: AccessToken,\n session: MonoCloudSession,\n options?: RefetchUserInfoOptions\n ): Promise<MonoCloudSession> {\n if (!accessToken.scopes?.includes('openid')) {\n throw new MonoCloudValidationError(\n 'Fetching userinfo requires the openid scope'\n );\n }\n\n const userinfo = await this.userinfo(accessToken.accessToken);\n\n // eslint-disable-next-line no-param-reassign\n session.user = { ...session.user, ...userinfo };\n\n await options?.onSessionCreating?.(session, undefined, userinfo);\n\n return session;\n }\n\n /**\n * Refreshes an existing session using the refresh token.\n * This function requests new tokens using the refresh token and optionally updates user information.\n *\n * @param session - The current MonoCloudSession containing the refresh token.\n * @param options - Session refresh options.\n *\n * @returns User's session containing refreshed authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - If the refresh token is not present in the session,\n * or if 'expires_in' or 'scope' (including the openid scope) is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshSession(\n session: MonoCloudSession,\n options?: RefreshSessionOptions\n ): Promise<MonoCloudSession> {\n if (!session.refreshToken) {\n throw new MonoCloudValidationError(\n 'Session does not contain refresh token'\n );\n }\n\n const tokens = await this.refreshGrant(\n session.refreshToken,\n options?.refreshGrantOptions\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const resource = options?.refreshGrantOptions?.resource;\n let scopes = options?.refreshGrantOptions?.scopes;\n\n if (!resource && !scopes) {\n scopes = session.authorizedScopes;\n }\n\n const accessToken = findToken(session.accessTokens, resource, scopes);\n\n const user =\n Object.keys(idTokenClaims).length === 0 && !userinfo\n ? session.user\n : ({\n ...session.user,\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser);\n\n const newTokens =\n session.accessTokens?.filter(t => t !== accessToken) ?? [];\n\n newTokens.push({\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes: scopes,\n });\n\n const updatedSession: MonoCloudSession = {\n ...session,\n user,\n idToken: tokens.id_token ?? session.idToken,\n refreshToken: tokens.refresh_token ?? session.refreshToken,\n accessTokens: newTokens,\n };\n\n await options?.onSessionCreating?.(updatedSession, idTokenClaims, userinfo);\n\n return updatedSession;\n }\n\n /**\n * Revokes an access token or refresh token, rendering it invalid for future use.\n *\n * @param token - The token string to be revoked.\n * @param tokenType - Hint about the token type ('access_token' or 'refresh_token').\n *\n * @returns If token revocation succeeded.\n *\n * @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n */\n async revokeToken(token: string, tokenType?: string): Promise<void> {\n if (!token.trim().length) {\n throw new MonoCloudValidationError('Invalid token');\n }\n\n if (\n tokenType &&\n tokenType !== 'access_token' &&\n tokenType !== 'refresh_token'\n ) {\n throw new MonoCloudValidationError(\n 'Only access_token and refresh_token types are supported.'\n );\n }\n\n const body = new URLSearchParams();\n body.set('token', token);\n if (tokenType) {\n body.set('token_type_hint', tokenType);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'revocation_endpoint');\n\n const response = await innerFetch(metadata.revocation_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'revocation_failed',\n standardBodyError.error_description ?? 'Token revocation failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing revocation request. Unexpected status code: ${response.status}`\n );\n }\n }\n\n /**\n * Validates an ID Token.\n *\n * @param idToken - The ID Token JWT string to validate.\n * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature.\n * @param clockSkew - Number of seconds to adjust the current time to account for clock differences.\n * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation.\n * @param maxAge - Maximum authentication age in seconds.\n * @param nonce - Nonce value to validate against the token's nonce claim.\n *\n * @returns Validated ID Token claims.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n */\n async validateIdToken(\n idToken: string,\n jwks: Jwk[],\n clockSkew: number,\n clockTolerance: number,\n maxAge?: number,\n nonce?: string\n ): Promise<IdTokenClaims> {\n if (typeof idToken !== 'string' || idToken.trim().length === 0) {\n throw new MonoCloudTokenError(\n 'ID Token must be a valid non-empty string'\n );\n }\n\n const {\n 0: protectedHeader,\n 1: payload,\n 2: encodedSignature,\n length,\n } = idToken.split('.');\n\n if (length !== 3) {\n throw new MonoCloudTokenError(\n 'ID Token must have a header, payload and signature'\n );\n }\n\n let header: JwsHeaderParameters;\n try {\n header = JSON.parse(decodeBase64Url(protectedHeader));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Header');\n }\n\n if (\n header === null ||\n typeof header !== 'object' ||\n Array.isArray(header)\n ) {\n throw new MonoCloudTokenError('JWT Header must be a top level object');\n }\n\n if (this.idTokenSigningAlgorithm !== header.alg) {\n throw new MonoCloudTokenError('Invalid signing alg');\n }\n\n if (header.crit !== undefined) {\n throw new MonoCloudTokenError('Unexpected JWT \"crit\" header parameter');\n }\n\n const binary = decodeBase64Url(encodedSignature);\n\n const signature = new Uint8Array(binary.length);\n\n for (let i = 0; i < binary.length; i++) {\n signature[i] = binary.charCodeAt(i);\n }\n\n const key = await getPublicSigKeyFromIssuerJwks(jwks, header);\n\n const input = `${protectedHeader}.${payload}`;\n\n const verified = await crypto.subtle.verify(\n keyToSubtle(key),\n key,\n signature,\n stringToArrayBuffer(input) as BufferSource\n );\n\n if (!verified) {\n throw new MonoCloudTokenError('JWT signature verification failed');\n }\n\n let claims: IdTokenClaims;\n\n try {\n claims = JSON.parse(decodeBase64Url(payload));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Payload');\n }\n\n if (\n claims === null ||\n typeof claims !== 'object' ||\n Array.isArray(claims)\n ) {\n throw new MonoCloudTokenError('JWT Payload must be a top level object');\n }\n\n if ((claims.nonce || nonce) && claims.nonce !== nonce) {\n throw new MonoCloudTokenError('Nonce mismatch');\n }\n\n const current = now() + clockSkew;\n\n /* v8 ignore else -- @preserve */\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim type'\n );\n }\n\n if (claims.exp <= current - clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim value, timestamp is <= now()'\n );\n }\n }\n\n /* v8 ignore else -- @preserve */\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"iat\" (issued at) claim type'\n );\n }\n }\n\n if (\n typeof claims.auth_time === 'number' &&\n typeof maxAge === 'number' &&\n claims.auth_time + maxAge < current\n ) {\n throw new MonoCloudTokenError(\n 'Too much time has elapsed since the last End-User authentication'\n );\n }\n\n if (claims.iss !== this.tenantDomain) {\n throw new MonoCloudTokenError('Invalid Issuer');\n }\n\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim type'\n );\n }\n\n if (claims.nbf > current + clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim value, timestamp is > now()'\n );\n }\n }\n\n const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n\n if (!audience.includes(this.clientId)) {\n throw new MonoCloudTokenError('Invalid audience claim');\n }\n\n return claims;\n }\n\n /**\n * Decodes the payload of a JSON Web Token (JWT) and returns it as an object.\n *\n * >Note: THIS METHOD DOES NOT VERIFY JWT TOKENS.\n *\n * @param jwt - JWT to decode.\n *\n * @returns Decoded payload.\n *\n * @throws {@link MonoCloudTokenError} - If decoding fails\n *\n */\n static decodeJwt(jwt: string): IdTokenClaims {\n try {\n const [, payload] = jwt.split('.');\n\n if (!payload?.trim()) {\n throw new MonoCloudTokenError('JWT does not contain payload');\n }\n\n const decoded = decodeBase64Url(payload);\n\n if (!decoded.startsWith('{')) {\n throw new MonoCloudTokenError('Payload is not an object');\n }\n\n return JSON.parse(decoded) as IdTokenClaims;\n } catch (e) {\n if (e instanceof MonoCloudAuthBaseError) {\n throw e;\n }\n\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