@monocloud/auth-core 0.1.3 → 0.1.5

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.mjs CHANGED
@@ -1,10 +1,24 @@
1
- import { g as parseSpaceSeparated, h as now, i as encodeBase64Url, o as findToken, r as decodeBase64Url, u as getPublicSigKeyFromIssuerJwks, v as randomBytes, x as stringToArrayBuffer } from "./internal-DXHuqjJJ.mjs";
1
+ import { decodeBase64Url, encodeBase64Url, findToken, getPublicSigKeyFromIssuerJwks, now, parseSpaceSeparated, randomBytes, stringToArrayBuffer } from "./utils/internal.mjs";
2
2
 
3
3
  //#region src/errors/monocloud-auth-base-error.ts
4
+ /**
5
+ * Base class for all MonoCloud authentication errors.
6
+ *
7
+ * All errors thrown by the MonoCloud SDK extend this class, allowing applications to safely detect and handle MonoCloud-specific failures using `instanceof`.
8
+ *
9
+ * @category Error Classes
10
+ */
4
11
  var MonoCloudAuthBaseError = class extends Error {};
5
12
 
6
13
  //#endregion
7
14
  //#region src/errors/monocloud-op-error.ts
15
+ /**
16
+ * OAuth error returned by the authorization server during an authentication or token request.
17
+ *
18
+ * These errors correspond to standard OAuth / OpenID Connect error responses such as `invalid_request`, `access_denied`, or `invalid_grant`.
19
+ *
20
+ * @category Error Classes
21
+ */
8
22
  var MonoCloudOPError = class extends MonoCloudAuthBaseError {
9
23
  constructor(error, errorDescription) {
10
24
  super(error);
@@ -15,14 +29,31 @@ var MonoCloudOPError = class extends MonoCloudAuthBaseError {
15
29
 
16
30
  //#endregion
17
31
  //#region src/errors/monocloud-http-error.ts
32
+ /**
33
+ * Error thrown when a request to the MonoCloud authorization server fails.
34
+ *
35
+ * This error typically indicates a network failure, an unexpected HTTP response, or an unsuccessful response returned by the authorization server.
36
+ *
37
+ * @category Error Classes
38
+ */
18
39
  var MonoCloudHttpError = class extends MonoCloudAuthBaseError {};
19
40
 
20
41
  //#endregion
21
42
  //#region src/errors/monocloud-token-error.ts
43
+ /**
44
+ * Error thrown when a token operation fails.
45
+ *
46
+ * @category Error Classes
47
+ */
22
48
  var MonoCloudTokenError = class extends MonoCloudAuthBaseError {};
23
49
 
24
50
  //#endregion
25
51
  //#region src/errors/monocloud-validation-error.ts
52
+ /**
53
+ * Error thrown when validation fails.
54
+ *
55
+ * @category Error Classes
56
+ */
26
57
  var MonoCloudValidationError = class extends MonoCloudAuthBaseError {};
27
58
 
28
59
  //#endregion
@@ -140,13 +171,13 @@ const keyToSubtle = (key) => {
140
171
  throw new Error("unsupported CryptoKey algorithm name");
141
172
  };
142
173
  const clientAssertionPayload = (issuer, clientId, skew) => {
143
- const now$1 = Math.floor(Date.now() / 1e3) + skew;
174
+ const now = Math.floor(Date.now() / 1e3) + skew;
144
175
  return {
145
176
  jti: randomBytes(),
146
177
  aud: issuer,
147
- exp: now$1 + 60,
148
- iat: now$1,
149
- nbf: now$1,
178
+ exp: now + 60,
179
+ iat: now,
180
+ nbf: now,
150
181
  iss: clientId,
151
182
  sub: clientId
152
183
  };
@@ -223,12 +254,15 @@ const deserializeJson = async (res) => {
223
254
  );
224
255
  }
225
256
  };
257
+ /**
258
+ * @category Classes
259
+ */
226
260
  var MonoCloudOidcClient = class MonoCloudOidcClient {
227
261
  constructor(tenantDomain, clientId, options) {
228
262
  this.jwksCacheExpiry = 0;
229
- this.jwksCacheDuration = 60;
263
+ this.jwksCacheDuration = 300;
230
264
  this.metadataCacheExpiry = 0;
231
- this.metadataCacheDuration = 60;
265
+ this.metadataCacheDuration = 300;
232
266
  tenantDomain ??= "";
233
267
  /* v8 ignore next -- @preserve */
234
268
  this.tenantDomain = `${!tenantDomain.startsWith("https://") ? "https://" : ""}${tenantDomain.endsWith("/") ? tenantDomain.slice(0, -1) : tenantDomain}`;
@@ -244,9 +278,9 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
244
278
  *
245
279
  * If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.
246
280
  *
247
- * @param params Authorization URL parameters
281
+ * @param params - Authorization URL parameters.
248
282
  *
249
- * @returns Tenant's authorization url.
283
+ * @returns Tenant's authorization URL.
250
284
  *
251
285
  * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
252
286
  * unexpected status code during the request or a serialization error while processing the response.
@@ -305,7 +339,7 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
305
339
  return metadata;
306
340
  }
307
341
  /**
308
- * Fetches the JSON Web Keys used to sign the id token.
342
+ * Fetches the JSON Web Keys used to sign the ID token.
309
343
  * The JWKS is cached for 1 minute.
310
344
  *
311
345
  * @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.
@@ -331,9 +365,9 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
331
365
  /**
332
366
  * Performs a pushed authorization request.
333
367
  *
334
- * @param params - Authorization Parameters
368
+ * @param params - Authorization Parameters.
335
369
  *
336
- * @returns Response from Pushed Authorization Request (PAR) endpoint
370
+ * @returns Response from Pushed Authorization Request (PAR) endpoint.
337
371
  *
338
372
  * @throws {@link MonoCloudOPError} - When the request is invalid.
339
373
  *
@@ -423,13 +457,13 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
423
457
  return await deserializeJson(response);
424
458
  }
425
459
  /**
426
- * Generates OpenID end session url for signing out.
460
+ * Generates OpenID end session URL for signing out.
427
461
  *
428
462
  * Note - The `state` is added only when `postLogoutRedirectUri` is present.
429
463
  *
430
- * @param params - Parameters to build end session url
464
+ * @param params - Parameters to build end session URL.
431
465
  *
432
- * @returns Tenant's end session url
466
+ * @returns Tenant's end session URL.
433
467
  *
434
468
  * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
435
469
  * unexpected status code during the request or a serialization error while processing the response.
@@ -453,7 +487,7 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
453
487
  * @param code - The authorization code received from the authorization server.
454
488
  * @param redirectUri - The redirect URI used in the initial authorization request.
455
489
  * @param codeVerifier - Code verifier for PKCE.
456
- * @param resource - Space-separated list of resources the access token should be scoped to
490
+ * @param resource - Space-separated list of resources the access token should be scoped to.
457
491
  *
458
492
  * @returns Tokens obtained by exchanging an authorization code at the token endpoint.
459
493
  *
@@ -536,23 +570,23 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
536
570
  /**
537
571
  * Generates a session with user and tokens by exchanging authorization code from callback params.
538
572
  *
539
- * @param code - The authorization code received from the callback
540
- * @param redirectUri - The redirect URI that was used in the authorization request
573
+ * @param code - The authorization code received from the callback.
574
+ * @param redirectUri - The redirect URI that was used in the authorization request.
541
575
  * @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.
542
576
  * This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.
543
577
  * @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.
544
578
  * Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.
545
- * @param options - Options for authenticating a user with authorization code
579
+ * @param options - Options for authenticating a user with authorization code.
546
580
  *
547
581
  * @returns The user's session containing authentication tokens and user information.
548
582
  *
549
583
  * @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,
550
584
  * or if 'expires_in' or 'scope' is missing from the token response.
551
585
  *
552
- * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized
586
+ * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized.
553
587
  * OAuth 2.0 error response.
554
588
  *
555
- * @throws {@link MonoCloudTokenError} - If ID Token validation fails
589
+ * @throws {@link MonoCloudTokenError} - If ID Token validation fails.
556
590
  *
557
591
  * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
558
592
  * unexpected status code during the request or a serialization error while processing the response.
@@ -596,11 +630,11 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
596
630
  * Refetches user information for an existing session using the userinfo endpoint.
597
631
  * Updates the session's user object with the latest user information while preserving existing properties.
598
632
  *
599
- * @param accessToken - Access token used to fetch the userinfo
600
- * @param session - The current MonoCloudSession
601
- * @param options - Userinfo refetch options
633
+ * @param accessToken - Access token used to fetch the userinfo.
634
+ * @param session - The current MonoCloudSession.
635
+ * @param options - Userinfo refetch options.
602
636
  *
603
- * @returns Updated session with the latest userinfo
637
+ * @returns Updated session with the latest userinfo.
604
638
  *
605
639
  * @throws {@link MonoCloudValidationError} - When the token scope does not contain openid scope
606
640
  *
@@ -627,8 +661,8 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
627
661
  * Refreshes an existing session using the refresh token.
628
662
  * This function requests new tokens using the refresh token and optionally updates user information.
629
663
  *
630
- * @param session - The current MonoCloudSession containing the refresh token
631
- * @param options - Session refresh options
664
+ * @param session - The current MonoCloudSession containing the refresh token.
665
+ * @param options - Session refresh options.
632
666
  *
633
667
  * @returns User's session containing refreshed authentication tokens and user information.
634
668
  *
@@ -690,10 +724,10 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
690
724
  /**
691
725
  * Revokes an access token or refresh token, rendering it invalid for future use.
692
726
  *
693
- * @param token - The token string to be revoked
694
- * @param tokenType - Hint about the token type ('access_token' or 'refresh_token')
727
+ * @param token - The token string to be revoked.
728
+ * @param tokenType - Hint about the token type ('access_token' or 'refresh_token').
695
729
  *
696
- * @returns If token revocation succeeded
730
+ * @returns If token revocation succeeded.
697
731
  *
698
732
  * @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type
699
733
  *
@@ -727,14 +761,14 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
727
761
  /**
728
762
  * Validates an ID Token.
729
763
  *
730
- * @param idToken - The ID Token JWT string to validate
731
- * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature
732
- * @param clockSkew - Number of seconds to adjust the current time to account for clock differences
733
- * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation
734
- * @param maxAge - maximum authentication age in seconds
735
- * @param nonce - nonce value to validate against the token's nonce claim
764
+ * @param idToken - The ID Token JWT string to validate.
765
+ * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature.
766
+ * @param clockSkew - Number of seconds to adjust the current time to account for clock differences.
767
+ * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation.
768
+ * @param maxAge - Maximum authentication age in seconds.
769
+ * @param nonce - Nonce value to validate against the token's nonce claim.
736
770
  *
737
- * @returns Validated ID Token claims
771
+ * @returns Validated ID Token claims.
738
772
  *
739
773
  * @throws {@link MonoCloudTokenError} - If ID Token validation fails
740
774
  *
@@ -787,11 +821,12 @@ var MonoCloudOidcClient = class MonoCloudOidcClient {
787
821
  }
788
822
  /**
789
823
  * Decodes the payload of a JSON Web Token (JWT) and returns it as an object.
790
- * **THIS METHOD DOES NOT VERIFY JWT TOKENS**.
791
824
  *
792
- * @param jwt - JWT to decode
825
+ * >Note: THIS METHOD DOES NOT VERIFY JWT TOKENS.
826
+ *
827
+ * @param jwt - JWT to decode.
793
828
  *
794
- * @returns Decoded payload
829
+ * @returns Decoded payload.
795
830
  *
796
831
  * @throws {@link MonoCloudTokenError} - If decoding fails
797
832
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["now","userinfo: MonoCloudUser | undefined","idTokenClaims: Partial<IdTokenClaims>","session: MonoCloudSession","updatedSession: MonoCloudSession","header: JwsHeaderParameters","claims: IdTokenClaims"],"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,OAAK,QAAQ;AACb,OAAK,mBAAmB;;;;;;ACR5B,IAAa,qBAAb,cAAwC,uBAAuB;;;;ACA/D,IAAa,sBAAb,cAAyC,uBAAuB;;;;ACAhE,IAAa,2BAAb,cAA8C,uBAAuB;;;;ACKrE,MAAM,eACJ,QACiE;AACjE,SAAQ,KAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAQ,MAAM,OAAO,IAAI,MAAM,GAAG;GAAI;EACvD,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAW,MAAM,OAAO,IAAI,MAAM,GAAG;GAAI;EAC1D,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAqB,MAAM,OAAO,IAAI,MAAM,GAAG;GAAI;EACpE,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAS,YAAY,KAAK,IAAI,MAAM,GAAG;GAAI;EAC5D,KAAK,QACH,QAAO;GAAE,MAAM;GAAS,YAAY;GAAS;EAE/C,QACE,OAAM,IAAI,MAAM,4BAA4B;;;AAIlD,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AI,oBAAoB,+BAA+B;GAG/D,MAAM,UAAU,gBAAgB,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.mjs","names":[],"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\n throw new MonoCloudTokenError(\n 'Could not parse payload. Malformed payload'\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAOA,IAAa,yBAAb,cAA4C,MAAM;;;;;;;;;;;ACElD,IAAa,mBAAb,cAAsC,uBAAuB;CAO3D,YAAY,OAAe,kBAA2B;AACpD,QAAM,MAAM;AACZ,OAAK,QAAQ;AACb,OAAK,mBAAmB;;;;;;;;;;;;;ACV5B,IAAa,qBAAb,cAAwC,uBAAuB;;;;;;;;;ACF/D,IAAa,sBAAb,cAAyC,uBAAuB;;;;;;;;;ACAhE,IAAa,2BAAb,cAA8C,uBAAuB;;;;ACArE,MAAM,eACJ,QACiE;AACjE,SAAQ,KAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAQ,MAAM,OAAO,IAAI,MAAM,GAAG;GAAI;EACvD,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAW,MAAM,OAAO,IAAI,MAAM,GAAG;GAAI;EAC1D,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAqB,MAAM,OAAO,IAAI,MAAM,GAAG;GAAI;EACpE,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAS,YAAY,KAAK,IAAI,MAAM,GAAG;GAAI;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