@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/README.md +19 -3
- package/dist/index.cjs +101 -65
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +72 -35
- package/dist/index.mjs +75 -40
- package/dist/index.mjs.map +1 -1
- package/dist/types-hokU85Zr.d.mts +1243 -0
- package/dist/utils/index.cjs +19 -19
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.mts +5 -7
- package/dist/utils/index.mjs +5 -6
- package/dist/utils/index.mjs.map +1 -1
- package/dist/utils/internal.cjs +365 -23
- package/dist/utils/internal.cjs.map +1 -0
- package/dist/utils/internal.d.mts +5 -6
- package/dist/utils/internal.mjs +342 -2
- package/dist/utils/internal.mjs.map +1 -0
- package/package.json +4 -4
- package/dist/index.d.cts +0 -274
- package/dist/internal-DXHuqjJJ.mjs +0 -343
- package/dist/internal-DXHuqjJJ.mjs.map +0 -1
- package/dist/internal-DytuO03E.cjs +0 -475
- package/dist/internal-DytuO03E.cjs.map +0 -1
- package/dist/types-CnxqWHwA.d.cts +0 -481
- package/dist/types-DwJl9ZUf.d.mts +0 -481
- package/dist/utils/index.d.cts +0 -106
- package/dist/utils/internal.d.cts +0 -209
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["now","randomBytes","encodeBase64Url","stringToArrayBuffer","parseSpaceSeparated","now","userinfo: MonoCloudUser | undefined","idTokenClaims: Partial<IdTokenClaims>","session: MonoCloudSession","findToken","updatedSession: MonoCloudSession","header: JwsHeaderParameters","decodeBase64Url","getPublicSigKeyFromIssuerJwks","stringToArrayBuffer","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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,OAAO,QAAQ,SACxB,OAAM,IAAI,oBACR,iDACD;AAGH,OAAI,OAAO,MAAM,UAAU,eACzB,OAAM,IAAI,oBACR,wEACD;;AAML,MAAI,EAFa,MAAM,QAAQ,OAAO,IAAI,GAAG,OAAO,MAAM,CAAC,OAAO,IAAI,EAExD,SAAS,KAAK,SAAS,CACnC,OAAM,IAAI,oBAAoB,yBAAyB;AAGzD,SAAO;;;;;;;;;;;;;CAcT,OAAO,UAAU,KAA4B;AAC3C,MAAI;GACF,MAAM,GAAG,WAAW,IAAI,MAAM,IAAI;AAElC,OAAI,CAAC,SAAS,MAAM,CAClB,OAAM,IAAI,oBAAoB,+BAA+B;GAG/D,MAAM,UAAUO,iCAAgB,QAAQ;AAExC,OAAI,CAAC,QAAQ,WAAW,IAAI,CAC1B,OAAM,IAAI,oBAAoB,2BAA2B;AAG3D,UAAO,KAAK,MAAM,QAAQ;WACnB,GAAG;AACV,OAAI,aAAa,uBACf,OAAM;AAGR,SAAM,IAAI,oBACR,6CACD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["randomBytes","encodeBase64Url","stringToArrayBuffer","parseSpaceSeparated","now","findToken","decodeBase64Url","getPublicSigKeyFromIssuerJwks","stringToArrayBuffer"],"sources":["../src/errors/monocloud-auth-base-error.ts","../src/errors/monocloud-op-error.ts","../src/errors/monocloud-http-error.ts","../src/errors/monocloud-token-error.ts","../src/errors/monocloud-validation-error.ts","../src/client-auth.ts","../src/monocloud-oidc-client.ts"],"sourcesContent":["/**\n * Base class for all MonoCloud authentication errors.\n *\n * All errors thrown by the MonoCloud SDK extend this class, allowing applications to safely detect and handle MonoCloud-specific failures using `instanceof`.\n *\n * @category Error Classes\n */\nexport class MonoCloudAuthBaseError extends Error {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * OAuth error returned by the authorization server during an authentication or token request.\n *\n * These errors correspond to standard OAuth / OpenID Connect error responses such as `invalid_request`, `access_denied`, or `invalid_grant`.\n *\n * @category Error Classes\n */\nexport class MonoCloudOPError extends MonoCloudAuthBaseError {\n /** OAuth error code returned by the authorization server. */\n error: string;\n\n /** Human-readable description of the error. */\n errorDescription?: string;\n\n constructor(error: string, errorDescription?: string) {\n super(error);\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when a request to the MonoCloud authorization server fails.\n *\n * This error typically indicates a network failure, an unexpected HTTP response, or an unsuccessful response returned by the authorization server.\n *\n * @category Error Classes\n */\nexport class MonoCloudHttpError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when a token operation fails.\n *\n * @category Error Classes\n */\nexport class MonoCloudTokenError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when validation fails.\n *\n * @category Error Classes\n */\nexport class MonoCloudValidationError extends MonoCloudAuthBaseError {}\n","import {\n encodeBase64Url,\n randomBytes,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { ClientAuthMethod, Jwk } from './types';\n\nconst algToSubtle = (\n alg?: string\n): HmacImportParams | RsaHashedImportParams | EcKeyImportParams => {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { name: 'HMAC', hash: `SHA-${alg.slice(-3)}` };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n /* v8 ignore next */\n default:\n throw new Error('unsupported JWS algorithm');\n }\n};\n\nconst psAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst rsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst esAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as EcKeyAlgorithm).namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported EcKeyAlgorithm namedCurve');\n }\n};\n\nconst hsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as HmacKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'HS256';\n case 'SHA-384':\n return 'HS384';\n case 'SHA-512':\n return 'HS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported HMAC Algorithm hash');\n }\n};\n\nconst keyToJws = (key: CryptoKey): string => {\n switch (key.algorithm.name) {\n case 'HMAC':\n return hsAlg(key);\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n /* v8 ignore next */\n default:\n throw new Error('unsupported CryptoKey algorithm name');\n }\n};\n\nconst checkRsaKeyAlgorithm = (key: CryptoKey): void => {\n const { algorithm } = key as CryptoKey & { algorithm: RsaHashedKeyAlgorithm };\n\n /* v8 ignore if -- @preserve */\n if (\n typeof algorithm.modulusLength !== 'number' ||\n algorithm.modulusLength < 2048\n ) {\n throw new Error(`Unsupported ${algorithm.name} modulusLength`);\n }\n};\n\nconst ecdsaHashName = (key: CryptoKey): string => {\n const { algorithm } = key as CryptoKey & { algorithm: EcKeyAlgorithm };\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported ECDSA namedCurve');\n }\n};\n\nexport const keyToSubtle = (\n key: CryptoKey\n): AlgorithmIdentifier | RsaPssParams | EcdsaParams => {\n switch (key.algorithm.name) {\n case 'HMAC': {\n return { name: key.algorithm.name };\n }\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n } as EcdsaParams;\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256': // Fall through\n case 'SHA-384': // Fall through\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength:\n parseInt(\n (key.algorithm as RsaHashedKeyAlgorithm).hash.name.slice(-3),\n 10\n ) >> 3,\n } as RsaPssParams;\n /* v8 ignore next */\n default:\n throw new Error('unsupported RSA-PSS hash name');\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n }\n /* v8 ignore next -- @preserve */\n throw new Error('unsupported CryptoKey algorithm name');\n};\n\nconst clientAssertionPayload = (\n issuer: string,\n clientId: string,\n skew: number\n): Record<string, number | string> => {\n const now = Math.floor(Date.now() / 1000) + skew;\n return {\n jti: randomBytes(),\n aud: issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: clientId,\n sub: clientId,\n };\n};\n\nconst jwtAssertionGenerator = async (\n issuer: string,\n clientId: string,\n clientSecret: Jwk,\n body: URLSearchParams,\n skew: number\n): Promise<void> => {\n const key = await crypto.subtle.importKey(\n 'jwk',\n clientSecret as JsonWebKey,\n algToSubtle(clientSecret.alg),\n false,\n ['sign']\n );\n\n const header = { alg: keyToJws(key), kid: clientSecret.kid };\n const payload = clientAssertionPayload(issuer, clientId, skew);\n\n body.set('client_id', clientId);\n body.set(\n 'client_assertion_type',\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n );\n\n const input = `${encodeBase64Url(stringToArrayBuffer(JSON.stringify(header)))}.${encodeBase64Url(stringToArrayBuffer(JSON.stringify(payload)))}`;\n const signature = encodeBase64Url(\n await crypto.subtle.sign(\n keyToSubtle(key),\n key,\n stringToArrayBuffer(input) as BufferSource\n )\n );\n\n body.set('client_assertion', `${input}.${signature}`);\n};\n\nexport const clientAuth = async (\n clientId: string,\n clientSecret?: string | Jwk,\n method?: ClientAuthMethod,\n issuer?: string,\n headers?: Record<string, string>,\n body?: URLSearchParams,\n jwtAssertionSkew?: number\n): Promise<void> => {\n switch (true) {\n case method === 'client_secret_basic' && !!headers: {\n // eslint-disable-next-line no-param-reassign\n headers.authorization = `Basic ${btoa(`${clientId}:${clientSecret ?? ''}`)}`;\n break;\n }\n\n case method === 'client_secret_post' && !!body: {\n body.set('client_id', clientId);\n if (typeof clientSecret === 'string') {\n body.set('client_secret', clientSecret);\n }\n break;\n }\n\n case method === 'client_secret_jwt' &&\n !!issuer &&\n !!body &&\n (typeof clientSecret === 'string' || clientSecret?.kty === 'oct'): {\n const cs =\n typeof clientSecret === 'string'\n ? {\n k: encodeBase64Url(stringToArrayBuffer(clientSecret)),\n kty: 'oct',\n alg: 'HS256',\n }\n : clientSecret;\n\n await jwtAssertionGenerator(\n issuer,\n clientId,\n cs,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n case method === 'private_key_jwt' &&\n typeof clientSecret === 'object' &&\n clientSecret.kty !== 'oct' &&\n !!issuer &&\n !!body: {\n await jwtAssertionGenerator(\n issuer,\n clientId,\n clientSecret,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n default:\n throw new Error('Invalid Client Authentication Method');\n }\n};\n","import {\n decodeBase64Url,\n findToken,\n getPublicSigKeyFromIssuerJwks,\n now,\n parseSpaceSeparated,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { clientAuth, keyToSubtle } from './client-auth';\nimport {\n AccessToken,\n AuthenticateOptions,\n AuthorizationParams,\n ClientAuthMethod,\n EndSessionParameters,\n IdTokenClaims,\n IssuerMetadata,\n Jwk,\n Jwks,\n SecurityAlgorithms,\n JwsHeaderParameters,\n MonoCloudClientOptions,\n MonoCloudSession,\n MonoCloudUser,\n ParResponse,\n PushedAuthorizationParams,\n RefetchUserInfoOptions,\n RefreshGrantOptions,\n RefreshSessionOptions,\n Tokens,\n UserinfoResponse,\n} from './types';\nimport { MonoCloudOPError } from './errors/monocloud-op-error';\nimport { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { MonoCloudTokenError } from './errors/monocloud-token-error';\nimport { MonoCloudAuthBaseError } from './errors/monocloud-auth-base-error';\n\nconst JWT_ASSERTION_CLOCK_SKEW = 5;\n\nconst FILTER_ID_TOKEN_CLAIMS = [\n 'iss',\n 'exp',\n 'nbf',\n 'aud',\n 'nonce',\n 'iat',\n 'auth_time',\n 'c_hash',\n 'at_hash',\n 's_hash',\n];\n\nfunction assertMetadataProperty<K extends keyof IssuerMetadata>(\n metadata: IssuerMetadata,\n property: K\n): asserts metadata is IssuerMetadata & Required<Pick<IssuerMetadata, K>> {\n if (metadata[property] === undefined || metadata[property] === null) {\n throw new MonoCloudValidationError(\n `${property as string} endpoint is required but not available in the issuer metadata`\n );\n }\n}\n\nconst innerFetch = async (\n input: string,\n reqInit: RequestInit = {}\n): Promise<Response> => {\n try {\n return await fetch(input, reqInit);\n } catch (e) {\n /* v8 ignore next -- @preserve */\n throw new MonoCloudHttpError(\n (e as any).message ?? 'Unexpected Network Error'\n );\n }\n};\n\nconst deserializeJson = async <T = any>(res: Response): Promise<T> => {\n try {\n return await res.json();\n } catch (e) {\n throw new MonoCloudHttpError(\n /* v8 ignore next -- @preserve */\n `Failed to parse response body as JSON ${(e as any).message ? `: ${(e as any).message}` : ''}`\n );\n }\n};\n\n/**\n * @category Classes\n */\nexport class MonoCloudOidcClient {\n private readonly tenantDomain: string;\n\n private readonly clientId: string;\n\n private readonly clientSecret?: string | Jwk;\n\n private readonly authMethod: ClientAuthMethod;\n\n private readonly idTokenSigningAlgorithm: SecurityAlgorithms;\n\n private jwks?: Jwks;\n\n private jwksCacheExpiry = 0;\n\n private jwksCacheDuration = 300;\n\n private metadata?: IssuerMetadata;\n\n private metadataCacheExpiry = 0;\n\n private metadataCacheDuration = 300;\n\n constructor(\n tenantDomain: string,\n clientId: string,\n options?: MonoCloudClientOptions\n ) {\n // eslint-disable-next-line no-param-reassign\n tenantDomain ??= '';\n /* v8 ignore next -- @preserve */\n this.tenantDomain = `${!tenantDomain.startsWith('https://') ? 'https://' : ''}${tenantDomain.endsWith('/') ? tenantDomain.slice(0, -1) : tenantDomain}`;\n this.clientId = clientId;\n this.clientSecret = options?.clientSecret;\n this.authMethod = options?.clientAuthMethod ?? 'client_secret_basic';\n this.idTokenSigningAlgorithm = options?.idTokenSigningAlgorithm ?? 'RS256';\n\n if (options?.jwksCacheDuration) {\n this.jwksCacheDuration = options.jwksCacheDuration;\n }\n\n if (options?.metadataCacheDuration) {\n this.metadataCacheDuration = options.metadataCacheDuration;\n }\n }\n\n /**\n * Generates an authorization URL with specified parameters.\n *\n * If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.\n *\n * @param params - Authorization URL parameters.\n *\n * @returns Tenant's authorization URL.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authorizationUrl(params: AuthorizationParams): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n queryParams.set('redirect_uri', params.redirectUri);\n }\n\n if (params.requestUri) {\n queryParams.set('request_uri', params.requestUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n queryParams.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n queryParams.set('response_type', params.responseType);\n }\n\n if (\n (!params.responseType || params.responseType.length === 0) &&\n !params.requestUri\n ) {\n queryParams.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n queryParams.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n queryParams.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n queryParams.set('request', params.request);\n }\n\n if (params.responseMode) {\n queryParams.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n queryParams.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n queryParams.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n queryParams.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n queryParams.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n queryParams.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n queryParams.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n queryParams.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n queryParams.set('code_challenge', params.codeChallenge);\n queryParams.set(\n 'code_challenge_method',\n params.codeChallengeMethod ?? 'S256'\n );\n }\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'authorization_endpoint');\n\n return `${metadata.authorization_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Fetches the authorization server metadata from the .well-known endpoint.\n * The metadata is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh metadata from the server.\n *\n * @returns The issuer metadata for the tenant, retrieved from the OpenID Connect discovery endpoint.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getMetadata(forceRefresh = false): Promise<IssuerMetadata> {\n if (!forceRefresh && this.metadata && this.metadataCacheExpiry > now()) {\n return this.metadata;\n }\n\n this.metadata = undefined;\n\n const response = await innerFetch(\n `${this.tenantDomain}/.well-known/openid-configuration`\n );\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching metadata. Unexpected status code: ${response.status}`\n );\n }\n\n const metadata = await deserializeJson<IssuerMetadata>(response);\n\n this.metadata = metadata;\n this.metadataCacheExpiry = now() + this.metadataCacheDuration;\n\n return metadata;\n }\n\n /**\n * Fetches the JSON Web Keys used to sign the ID token.\n * The JWKS is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.\n *\n * @returns The JSON Web Key Set containing the public keys for token verification.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getJwks(forceRefresh = false): Promise<Jwks> {\n if (!forceRefresh && this.jwks && this.jwksCacheExpiry > now()) {\n return this.jwks;\n }\n\n this.jwks = undefined;\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'jwks_uri');\n\n const response = await innerFetch(metadata.jwks_uri);\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching JWKS. Unexpected status code: ${response.status}`\n );\n }\n const jwks = await deserializeJson<Jwks>(response);\n\n this.jwks = jwks;\n this.jwksCacheExpiry = now() + this.jwksCacheDuration;\n\n return jwks;\n }\n\n /**\n * Performs a pushed authorization request.\n *\n * @param params - Authorization Parameters.\n *\n * @returns Response from Pushed Authorization Request (PAR) endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the request is invalid.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async pushedAuthorizationRequest(\n params: PushedAuthorizationParams\n ): Promise<ParResponse> {\n const body = new URLSearchParams();\n\n body.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n body.set('redirect_uri', params.redirectUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n body.set('response_type', params.responseType);\n } else {\n body.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n body.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n body.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n body.set('request', params.request);\n }\n\n if (params.responseMode) {\n body.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n body.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n body.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n body.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n body.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n body.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n body.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n body.set('code_challenge', params.codeChallenge);\n body.set('code_challenge_method', params.codeChallengeMethod ?? 'S256');\n }\n\n if (params.state) {\n body.set('state', params.state);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'pushed_authorization_request_endpoint');\n\n const response = await innerFetch(\n metadata.pushed_authorization_request_endpoint,\n {\n body: body.toString(),\n method: 'POST',\n headers,\n }\n );\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'par_request_failed',\n standardBodyError.error_description ??\n 'Pushed Authorization Request Failed'\n );\n }\n\n if (response.status !== 201) {\n throw new MonoCloudHttpError(\n `Error while performing pushed authorization request. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<ParResponse>(response);\n }\n\n /**\n * Fetches userinfo associated with the provided access token.\n *\n * @param accessToken - A valid access token used to retrieve userinfo.\n *\n * @returns The authenticated user's claims.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error (e.g., 'invalid_token') in the 'WWW-Authenticate' header\n * following a 401 Unauthorized response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n * @throws {@link MonoCloudValidationError} - When the access token is invalid.\n *\n */\n async userinfo(accessToken: string): Promise<UserinfoResponse> {\n if (!accessToken.trim().length) {\n throw new MonoCloudValidationError(\n 'Access token is required for fetching userinfo'\n );\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'userinfo_endpoint');\n\n const response = await innerFetch(metadata.userinfo_endpoint, {\n method: 'GET',\n headers: {\n authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (response.status === 401) {\n const authenticateError = response.headers.get('WWW-Authenticate');\n\n if (authenticateError) {\n const errorMatch = /error=\"([^\"]+)\"/.exec(authenticateError);\n const error = errorMatch ? errorMatch[1] : 'userinfo_failed';\n\n const errorDescMatch = /error_description=\"([^\"]+)\"/.exec(\n authenticateError\n );\n\n const errorDescription = errorDescMatch\n ? errorDescMatch[1]\n : 'Userinfo authentication error';\n\n throw new MonoCloudOPError(error, errorDescription);\n }\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching userinfo. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<UserinfoResponse>(response);\n }\n\n /**\n * Generates OpenID end session URL for signing out.\n *\n * Note - The `state` is added only when `postLogoutRedirectUri` is present.\n *\n * @param params - Parameters to build end session URL.\n *\n * @returns Tenant's end session URL.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async endSessionUrl(params: EndSessionParameters): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.idToken) {\n queryParams.set('id_token_hint', params.idToken);\n }\n\n if (params.postLogoutRedirectUri) {\n queryParams.set('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'end_session_endpoint');\n\n return `${metadata.end_session_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Exchanges an authorization code for tokens.\n *\n * @param code - The authorization code received from the authorization server.\n * @param redirectUri - The redirect URI used in the initial authorization request.\n * @param codeVerifier - Code verifier for PKCE.\n * @param resource - Space-separated list of resources the access token should be scoped to.\n *\n * @returns Tokens obtained by exchanging an authorization code at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async exchangeAuthorizationCode(\n code: string,\n redirectUri: string,\n codeVerifier?: string,\n resource?: string\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'authorization_code');\n body.set('code', code);\n body.set('redirect_uri', redirectUri);\n\n if (codeVerifier) {\n body.set('code_verifier', codeVerifier);\n }\n\n const resources = parseSpaceSeparated(resource) ?? [];\n\n if (resources.length > 0) {\n for (const r of resources) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'code_grant_failed',\n standardBodyError.error_description ?? 'Authorization code grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Exchanges a refresh token for new tokens.\n *\n * @param refreshToken - The refresh token used to request new tokens.\n * @param options - Refresh grant options.\n *\n * @returns Tokens obtained by exchanging a refresh token at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshGrant(\n refreshToken: string,\n options?: RefreshGrantOptions\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'refresh_token');\n body.set('refresh_token', refreshToken);\n\n const scopes = parseSpaceSeparated(options?.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n const resource = parseSpaceSeparated(options?.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'refresh_grant_failed',\n standardBodyError.error_description ?? 'Refresh token grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing refresh token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Generates a session with user and tokens by exchanging authorization code from callback params.\n *\n * @param code - The authorization code received from the callback.\n * @param redirectUri - The redirect URI that was used in the authorization request.\n * @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.\n * This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.\n * @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.\n * Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.\n * @param options - Options for authenticating a user with authorization code.\n *\n * @returns The user's session containing authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,\n * or if 'expires_in' or 'scope' is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized.\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authenticate(\n code: string,\n redirectUri: string,\n requestedScopes: string,\n resource?: string,\n options?: AuthenticateOptions\n ): Promise<MonoCloudSession> {\n const tokens = await this.exchangeAuthorizationCode(\n code,\n redirectUri,\n options?.codeVerifier,\n resource\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0,\n options?.idTokenMaxAge,\n options?.idTokenNonce\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const session: MonoCloudSession = {\n user: {\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser,\n idToken: tokens.id_token,\n refreshToken: tokens.refresh_token,\n authorizedScopes: requestedScopes,\n accessTokens: [\n {\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes,\n },\n ],\n };\n\n await options?.onSessionCreating?.(session, idTokenClaims, userinfo);\n\n return session;\n }\n\n /**\n * Refetches user information for an existing session using the userinfo endpoint.\n * Updates the session's user object with the latest user information while preserving existing properties.\n *\n * @param accessToken - Access token used to fetch the userinfo.\n * @param session - The current MonoCloudSession.\n * @param options - Userinfo refetch options.\n *\n * @returns Updated session with the latest userinfo.\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain openid scope\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refetchUserInfo(\n accessToken: AccessToken,\n session: MonoCloudSession,\n options?: RefetchUserInfoOptions\n ): Promise<MonoCloudSession> {\n if (!accessToken.scopes?.includes('openid')) {\n throw new MonoCloudValidationError(\n 'Fetching userinfo requires the openid scope'\n );\n }\n\n const userinfo = await this.userinfo(accessToken.accessToken);\n\n // eslint-disable-next-line no-param-reassign\n session.user = { ...session.user, ...userinfo };\n\n await options?.onSessionCreating?.(session, undefined, userinfo);\n\n return session;\n }\n\n /**\n * Refreshes an existing session using the refresh token.\n * This function requests new tokens using the refresh token and optionally updates user information.\n *\n * @param session - The current MonoCloudSession containing the refresh token.\n * @param options - Session refresh options.\n *\n * @returns User's session containing refreshed authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - If the refresh token is not present in the session,\n * or if 'expires_in' or 'scope' (including the openid scope) is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshSession(\n session: MonoCloudSession,\n options?: RefreshSessionOptions\n ): Promise<MonoCloudSession> {\n if (!session.refreshToken) {\n throw new MonoCloudValidationError(\n 'Session does not contain refresh token'\n );\n }\n\n const tokens = await this.refreshGrant(\n session.refreshToken,\n options?.refreshGrantOptions\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const resource = options?.refreshGrantOptions?.resource;\n let scopes = options?.refreshGrantOptions?.scopes;\n\n if (!resource && !scopes) {\n scopes = session.authorizedScopes;\n }\n\n const accessToken = findToken(session.accessTokens, resource, scopes);\n\n const user =\n Object.keys(idTokenClaims).length === 0 && !userinfo\n ? session.user\n : ({\n ...session.user,\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser);\n\n const newTokens =\n session.accessTokens?.filter(t => t !== accessToken) ?? [];\n\n newTokens.push({\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes: scopes,\n });\n\n const updatedSession: MonoCloudSession = {\n ...session,\n user,\n idToken: tokens.id_token ?? session.idToken,\n refreshToken: tokens.refresh_token ?? session.refreshToken,\n accessTokens: newTokens,\n };\n\n await options?.onSessionCreating?.(updatedSession, idTokenClaims, userinfo);\n\n return updatedSession;\n }\n\n /**\n * Revokes an access token or refresh token, rendering it invalid for future use.\n *\n * @param token - The token string to be revoked.\n * @param tokenType - Hint about the token type ('access_token' or 'refresh_token').\n *\n * @returns If token revocation succeeded.\n *\n * @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n */\n async revokeToken(token: string, tokenType?: string): Promise<void> {\n if (!token.trim().length) {\n throw new MonoCloudValidationError('Invalid token');\n }\n\n if (\n tokenType &&\n tokenType !== 'access_token' &&\n tokenType !== 'refresh_token'\n ) {\n throw new MonoCloudValidationError(\n 'Only access_token and refresh_token types are supported.'\n );\n }\n\n const body = new URLSearchParams();\n body.set('token', token);\n if (tokenType) {\n body.set('token_type_hint', tokenType);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'revocation_endpoint');\n\n const response = await innerFetch(metadata.revocation_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'revocation_failed',\n standardBodyError.error_description ?? 'Token revocation failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing revocation request. Unexpected status code: ${response.status}`\n );\n }\n }\n\n /**\n * Validates an ID Token.\n *\n * @param idToken - The ID Token JWT string to validate.\n * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature.\n * @param clockSkew - Number of seconds to adjust the current time to account for clock differences.\n * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation.\n * @param maxAge - Maximum authentication age in seconds.\n * @param nonce - Nonce value to validate against the token's nonce claim.\n *\n * @returns Validated ID Token claims.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n */\n async validateIdToken(\n idToken: string,\n jwks: Jwk[],\n clockSkew: number,\n clockTolerance: number,\n maxAge?: number,\n nonce?: string\n ): Promise<IdTokenClaims> {\n if (typeof idToken !== 'string' || idToken.trim().length === 0) {\n throw new MonoCloudTokenError(\n 'ID Token must be a valid non-empty string'\n );\n }\n\n const {\n 0: protectedHeader,\n 1: payload,\n 2: encodedSignature,\n length,\n } = idToken.split('.');\n\n if (length !== 3) {\n throw new MonoCloudTokenError(\n 'ID Token must have a header, payload and signature'\n );\n }\n\n let header: JwsHeaderParameters;\n try {\n header = JSON.parse(decodeBase64Url(protectedHeader));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Header');\n }\n\n if (\n header === null ||\n typeof header !== 'object' ||\n Array.isArray(header)\n ) {\n throw new MonoCloudTokenError('JWT Header must be a top level object');\n }\n\n if (this.idTokenSigningAlgorithm !== header.alg) {\n throw new MonoCloudTokenError('Invalid signing alg');\n }\n\n if (header.crit !== undefined) {\n throw new MonoCloudTokenError('Unexpected JWT \"crit\" header parameter');\n }\n\n const binary = decodeBase64Url(encodedSignature);\n\n const signature = new Uint8Array(binary.length);\n\n for (let i = 0; i < binary.length; i++) {\n signature[i] = binary.charCodeAt(i);\n }\n\n const key = await getPublicSigKeyFromIssuerJwks(jwks, header);\n\n const input = `${protectedHeader}.${payload}`;\n\n const verified = await crypto.subtle.verify(\n keyToSubtle(key),\n key,\n signature,\n stringToArrayBuffer(input) as BufferSource\n );\n\n if (!verified) {\n throw new MonoCloudTokenError('JWT signature verification failed');\n }\n\n let claims: IdTokenClaims;\n\n try {\n claims = JSON.parse(decodeBase64Url(payload));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Payload');\n }\n\n if (\n claims === null ||\n typeof claims !== 'object' ||\n Array.isArray(claims)\n ) {\n throw new MonoCloudTokenError('JWT Payload must be a top level object');\n }\n\n if ((claims.nonce || nonce) && claims.nonce !== nonce) {\n throw new MonoCloudTokenError('Nonce mismatch');\n }\n\n const current = now() + clockSkew;\n\n /* v8 ignore else -- @preserve */\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim type'\n );\n }\n\n if (claims.exp <= current - clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim value, timestamp is <= now()'\n );\n }\n }\n\n /* v8 ignore else -- @preserve */\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"iat\" (issued at) claim type'\n );\n }\n }\n\n if (\n typeof claims.auth_time === 'number' &&\n typeof maxAge === 'number' &&\n claims.auth_time + maxAge < current\n ) {\n throw new MonoCloudTokenError(\n 'Too much time has elapsed since the last End-User authentication'\n );\n }\n\n if (claims.iss !== this.tenantDomain) {\n throw new MonoCloudTokenError('Invalid Issuer');\n }\n\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim type'\n );\n }\n\n if (claims.nbf > current + clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim value, timestamp is > now()'\n );\n }\n }\n\n const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n\n if (!audience.includes(this.clientId)) {\n throw new MonoCloudTokenError('Invalid audience claim');\n }\n\n return claims;\n }\n\n /**\n * Decodes the payload of a JSON Web Token (JWT) and returns it as an object.\n *\n * >Note: THIS METHOD DOES NOT VERIFY JWT TOKENS.\n *\n * @param jwt - JWT to decode.\n *\n * @returns Decoded payload.\n *\n * @throws {@link MonoCloudTokenError} - If decoding fails\n *\n */\n static decodeJwt(jwt: string): IdTokenClaims {\n try {\n const [, payload] = jwt.split('.');\n\n if (!payload?.trim()) {\n throw new MonoCloudTokenError('JWT does not contain payload');\n }\n\n const decoded = decodeBase64Url(payload);\n\n if (!decoded.startsWith('{')) {\n throw new MonoCloudTokenError('Payload is not an object');\n }\n\n return JSON.parse(decoded) as IdTokenClaims;\n } catch (e) {\n if (e instanceof MonoCloudAuthBaseError) {\n throw e;\n }\n\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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M,IAAI,oBACR,gDACD;;AAIL,MACE,OAAO,OAAO,cAAc,YAC5B,OAAO,WAAW,YAClB,OAAO,YAAY,SAAS,QAE5B,OAAM,IAAI,oBACR,mEACD;AAGH,MAAI,OAAO,QAAQ,KAAK,aACtB,OAAM,IAAI,oBAAoB,iBAAiB;AAGjD,MAAI,OAAO,QAAQ,QAAW;AAC5B,OAAI,OAAO,OAAO,QAAQ,SACxB,OAAM,IAAI,oBACR,iDACD;AAGH,OAAI,OAAO,MAAM,UAAU,eACzB,OAAM,IAAI,oBACR,wEACD;;AAML,MAAI,EAFa,MAAM,QAAQ,OAAO,IAAI,GAAG,OAAO,MAAM,CAAC,OAAO,IAAI,EAExD,SAAS,KAAK,SAAS,CACnC,OAAM,IAAI,oBAAoB,yBAAyB;AAGzD,SAAO;;;;;;;;;;;;;;CAeT,OAAO,UAAU,KAA4B;AAC3C,MAAI;GACF,MAAM,GAAG,WAAW,IAAI,MAAM,IAAI;AAElC,OAAI,CAAC,SAAS,MAAM,CAClB,OAAM,IAAI,oBAAoB,+BAA+B;GAG/D,MAAM,UAAUE,uCAAgB,QAAQ;AAExC,OAAI,CAAC,QAAQ,WAAW,IAAI,CAC1B,OAAM,IAAI,oBAAoB,2BAA2B;AAG3D,UAAO,KAAK,MAAM,QAAQ;WACnB,GAAG;AACV,OAAI,aAAa,uBACf,OAAM;AAGR,SAAM,IAAI,oBACR,6CACD"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,25 +1,61 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as SecurityAlgorithms, C as Prompt, D as RefreshSessionOptions, E as RefreshGrantOptions, M as UserinfoResponse, O as ResponseModes, S as ParResponse, T as RefetchUserInfoOptions, _ as JwsHeaderParameters, a as Authenticators, b as MonoCloudUser, c as ClientAuthMethod, d as EndSessionParameters, f as Group, g as Jwks, h as Jwk, i as AuthenticateOptions, j as Tokens, k as ResponseTypes, l as CodeChallengeMethod, m as IssuerMetadata, n as Address, o as AuthorizationParams, p as IdTokenClaims, r as AuthState, s as CallbackParams, t as AccessToken, u as DisplayOptions, v as MonoCloudClientOptions, w as PushedAuthorizationParams, x as OnSessionCreating, y as MonoCloudSession } from "./types-hokU85Zr.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/errors/monocloud-auth-base-error.d.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
|
declare class MonoCloudAuthBaseError extends Error {}
|
|
5
12
|
//#endregion
|
|
6
13
|
//#region src/errors/monocloud-op-error.d.ts
|
|
14
|
+
/**
|
|
15
|
+
* OAuth error returned by the authorization server during an authentication or token request.
|
|
16
|
+
*
|
|
17
|
+
* These errors correspond to standard OAuth / OpenID Connect error responses such as `invalid_request`, `access_denied`, or `invalid_grant`.
|
|
18
|
+
*
|
|
19
|
+
* @category Error Classes
|
|
20
|
+
*/
|
|
7
21
|
declare class MonoCloudOPError extends MonoCloudAuthBaseError {
|
|
22
|
+
/** OAuth error code returned by the authorization server. */
|
|
8
23
|
error: string;
|
|
24
|
+
/** Human-readable description of the error. */
|
|
9
25
|
errorDescription?: string;
|
|
10
26
|
constructor(error: string, errorDescription?: string);
|
|
11
27
|
}
|
|
12
28
|
//#endregion
|
|
13
29
|
//#region src/errors/monocloud-http-error.d.ts
|
|
30
|
+
/**
|
|
31
|
+
* Error thrown when a request to the MonoCloud authorization server fails.
|
|
32
|
+
*
|
|
33
|
+
* This error typically indicates a network failure, an unexpected HTTP response, or an unsuccessful response returned by the authorization server.
|
|
34
|
+
*
|
|
35
|
+
* @category Error Classes
|
|
36
|
+
*/
|
|
14
37
|
declare class MonoCloudHttpError extends MonoCloudAuthBaseError {}
|
|
15
38
|
//#endregion
|
|
16
39
|
//#region src/errors/monocloud-token-error.d.ts
|
|
40
|
+
/**
|
|
41
|
+
* Error thrown when a token operation fails.
|
|
42
|
+
*
|
|
43
|
+
* @category Error Classes
|
|
44
|
+
*/
|
|
17
45
|
declare class MonoCloudTokenError extends MonoCloudAuthBaseError {}
|
|
18
46
|
//#endregion
|
|
19
47
|
//#region src/errors/monocloud-validation-error.d.ts
|
|
48
|
+
/**
|
|
49
|
+
* Error thrown when validation fails.
|
|
50
|
+
*
|
|
51
|
+
* @category Error Classes
|
|
52
|
+
*/
|
|
20
53
|
declare class MonoCloudValidationError extends MonoCloudAuthBaseError {}
|
|
21
54
|
//#endregion
|
|
22
55
|
//#region src/monocloud-oidc-client.d.ts
|
|
56
|
+
/**
|
|
57
|
+
* @category Classes
|
|
58
|
+
*/
|
|
23
59
|
declare class MonoCloudOidcClient {
|
|
24
60
|
private readonly tenantDomain;
|
|
25
61
|
private readonly clientId;
|
|
@@ -38,9 +74,9 @@ declare class MonoCloudOidcClient {
|
|
|
38
74
|
*
|
|
39
75
|
* If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.
|
|
40
76
|
*
|
|
41
|
-
* @param params Authorization URL parameters
|
|
77
|
+
* @param params - Authorization URL parameters.
|
|
42
78
|
*
|
|
43
|
-
* @returns Tenant's authorization
|
|
79
|
+
* @returns Tenant's authorization URL.
|
|
44
80
|
*
|
|
45
81
|
* @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
|
|
46
82
|
* unexpected status code during the request or a serialization error while processing the response.
|
|
@@ -61,7 +97,7 @@ declare class MonoCloudOidcClient {
|
|
|
61
97
|
*/
|
|
62
98
|
getMetadata(forceRefresh?: boolean): Promise<IssuerMetadata>;
|
|
63
99
|
/**
|
|
64
|
-
* Fetches the JSON Web Keys used to sign the
|
|
100
|
+
* Fetches the JSON Web Keys used to sign the ID token.
|
|
65
101
|
* The JWKS is cached for 1 minute.
|
|
66
102
|
*
|
|
67
103
|
* @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.
|
|
@@ -76,9 +112,9 @@ declare class MonoCloudOidcClient {
|
|
|
76
112
|
/**
|
|
77
113
|
* Performs a pushed authorization request.
|
|
78
114
|
*
|
|
79
|
-
* @param params - Authorization Parameters
|
|
115
|
+
* @param params - Authorization Parameters.
|
|
80
116
|
*
|
|
81
|
-
* @returns Response from Pushed Authorization Request (PAR) endpoint
|
|
117
|
+
* @returns Response from Pushed Authorization Request (PAR) endpoint.
|
|
82
118
|
*
|
|
83
119
|
* @throws {@link MonoCloudOPError} - When the request is invalid.
|
|
84
120
|
*
|
|
@@ -106,13 +142,13 @@ declare class MonoCloudOidcClient {
|
|
|
106
142
|
*/
|
|
107
143
|
userinfo(accessToken: string): Promise<UserinfoResponse>;
|
|
108
144
|
/**
|
|
109
|
-
* Generates OpenID end session
|
|
145
|
+
* Generates OpenID end session URL for signing out.
|
|
110
146
|
*
|
|
111
147
|
* Note - The `state` is added only when `postLogoutRedirectUri` is present.
|
|
112
148
|
*
|
|
113
|
-
* @param params - Parameters to build end session
|
|
149
|
+
* @param params - Parameters to build end session URL.
|
|
114
150
|
*
|
|
115
|
-
* @returns Tenant's end session
|
|
151
|
+
* @returns Tenant's end session URL.
|
|
116
152
|
*
|
|
117
153
|
* @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
|
|
118
154
|
* unexpected status code during the request or a serialization error while processing the response.
|
|
@@ -125,7 +161,7 @@ declare class MonoCloudOidcClient {
|
|
|
125
161
|
* @param code - The authorization code received from the authorization server.
|
|
126
162
|
* @param redirectUri - The redirect URI used in the initial authorization request.
|
|
127
163
|
* @param codeVerifier - Code verifier for PKCE.
|
|
128
|
-
* @param resource - Space-separated list of resources the access token should be scoped to
|
|
164
|
+
* @param resource - Space-separated list of resources the access token should be scoped to.
|
|
129
165
|
*
|
|
130
166
|
* @returns Tokens obtained by exchanging an authorization code at the token endpoint.
|
|
131
167
|
*
|
|
@@ -156,23 +192,23 @@ declare class MonoCloudOidcClient {
|
|
|
156
192
|
/**
|
|
157
193
|
* Generates a session with user and tokens by exchanging authorization code from callback params.
|
|
158
194
|
*
|
|
159
|
-
* @param code - The authorization code received from the callback
|
|
160
|
-
* @param redirectUri - The redirect URI that was used in the authorization request
|
|
195
|
+
* @param code - The authorization code received from the callback.
|
|
196
|
+
* @param redirectUri - The redirect URI that was used in the authorization request.
|
|
161
197
|
* @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.
|
|
162
198
|
* This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.
|
|
163
199
|
* @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.
|
|
164
200
|
* Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.
|
|
165
|
-
* @param options - Options for authenticating a user with authorization code
|
|
201
|
+
* @param options - Options for authenticating a user with authorization code.
|
|
166
202
|
*
|
|
167
203
|
* @returns The user's session containing authentication tokens and user information.
|
|
168
204
|
*
|
|
169
205
|
* @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,
|
|
170
206
|
* or if 'expires_in' or 'scope' is missing from the token response.
|
|
171
207
|
*
|
|
172
|
-
* @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized
|
|
208
|
+
* @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized.
|
|
173
209
|
* OAuth 2.0 error response.
|
|
174
210
|
*
|
|
175
|
-
* @throws {@link MonoCloudTokenError} - If ID Token validation fails
|
|
211
|
+
* @throws {@link MonoCloudTokenError} - If ID Token validation fails.
|
|
176
212
|
*
|
|
177
213
|
* @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or
|
|
178
214
|
* unexpected status code during the request or a serialization error while processing the response.
|
|
@@ -183,11 +219,11 @@ declare class MonoCloudOidcClient {
|
|
|
183
219
|
* Refetches user information for an existing session using the userinfo endpoint.
|
|
184
220
|
* Updates the session's user object with the latest user information while preserving existing properties.
|
|
185
221
|
*
|
|
186
|
-
* @param accessToken - Access token used to fetch the userinfo
|
|
187
|
-
* @param session - The current MonoCloudSession
|
|
188
|
-
* @param options - Userinfo refetch options
|
|
222
|
+
* @param accessToken - Access token used to fetch the userinfo.
|
|
223
|
+
* @param session - The current MonoCloudSession.
|
|
224
|
+
* @param options - Userinfo refetch options.
|
|
189
225
|
*
|
|
190
|
-
* @returns Updated session with the latest userinfo
|
|
226
|
+
* @returns Updated session with the latest userinfo.
|
|
191
227
|
*
|
|
192
228
|
* @throws {@link MonoCloudValidationError} - When the token scope does not contain openid scope
|
|
193
229
|
*
|
|
@@ -205,8 +241,8 @@ declare class MonoCloudOidcClient {
|
|
|
205
241
|
* Refreshes an existing session using the refresh token.
|
|
206
242
|
* This function requests new tokens using the refresh token and optionally updates user information.
|
|
207
243
|
*
|
|
208
|
-
* @param session - The current MonoCloudSession containing the refresh token
|
|
209
|
-
* @param options - Session refresh options
|
|
244
|
+
* @param session - The current MonoCloudSession containing the refresh token.
|
|
245
|
+
* @param options - Session refresh options.
|
|
210
246
|
*
|
|
211
247
|
* @returns User's session containing refreshed authentication tokens and user information.
|
|
212
248
|
*
|
|
@@ -226,10 +262,10 @@ declare class MonoCloudOidcClient {
|
|
|
226
262
|
/**
|
|
227
263
|
* Revokes an access token or refresh token, rendering it invalid for future use.
|
|
228
264
|
*
|
|
229
|
-
* @param token - The token string to be revoked
|
|
230
|
-
* @param tokenType - Hint about the token type ('access_token' or 'refresh_token')
|
|
265
|
+
* @param token - The token string to be revoked.
|
|
266
|
+
* @param tokenType - Hint about the token type ('access_token' or 'refresh_token').
|
|
231
267
|
*
|
|
232
|
-
* @returns If token revocation succeeded
|
|
268
|
+
* @returns If token revocation succeeded.
|
|
233
269
|
*
|
|
234
270
|
* @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type
|
|
235
271
|
*
|
|
@@ -243,14 +279,14 @@ declare class MonoCloudOidcClient {
|
|
|
243
279
|
/**
|
|
244
280
|
* Validates an ID Token.
|
|
245
281
|
*
|
|
246
|
-
* @param idToken - The ID Token JWT string to validate
|
|
247
|
-
* @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature
|
|
248
|
-
* @param clockSkew - Number of seconds to adjust the current time to account for clock differences
|
|
249
|
-
* @param clockTolerance - Additional time tolerance in seconds for time-based claim validation
|
|
250
|
-
* @param maxAge -
|
|
251
|
-
* @param nonce -
|
|
282
|
+
* @param idToken - The ID Token JWT string to validate.
|
|
283
|
+
* @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature.
|
|
284
|
+
* @param clockSkew - Number of seconds to adjust the current time to account for clock differences.
|
|
285
|
+
* @param clockTolerance - Additional time tolerance in seconds for time-based claim validation.
|
|
286
|
+
* @param maxAge - Maximum authentication age in seconds.
|
|
287
|
+
* @param nonce - Nonce value to validate against the token's nonce claim.
|
|
252
288
|
*
|
|
253
|
-
* @returns Validated ID Token claims
|
|
289
|
+
* @returns Validated ID Token claims.
|
|
254
290
|
*
|
|
255
291
|
* @throws {@link MonoCloudTokenError} - If ID Token validation fails
|
|
256
292
|
*
|
|
@@ -258,11 +294,12 @@ declare class MonoCloudOidcClient {
|
|
|
258
294
|
validateIdToken(idToken: string, jwks: Jwk[], clockSkew: number, clockTolerance: number, maxAge?: number, nonce?: string): Promise<IdTokenClaims>;
|
|
259
295
|
/**
|
|
260
296
|
* Decodes the payload of a JSON Web Token (JWT) and returns it as an object.
|
|
261
|
-
* **THIS METHOD DOES NOT VERIFY JWT TOKENS**.
|
|
262
297
|
*
|
|
263
|
-
*
|
|
298
|
+
* >Note: THIS METHOD DOES NOT VERIFY JWT TOKENS.
|
|
299
|
+
*
|
|
300
|
+
* @param jwt - JWT to decode.
|
|
264
301
|
*
|
|
265
|
-
* @returns Decoded payload
|
|
302
|
+
* @returns Decoded payload.
|
|
266
303
|
*
|
|
267
304
|
* @throws {@link MonoCloudTokenError} - If decoding fails
|
|
268
305
|
*
|
|
@@ -270,5 +307,5 @@ declare class MonoCloudOidcClient {
|
|
|
270
307
|
static decodeJwt(jwt: string): IdTokenClaims;
|
|
271
308
|
}
|
|
272
309
|
//#endregion
|
|
273
|
-
export { type AccessToken, type Address, type AuthState, type AuthenticateOptions, type Authenticators, type AuthorizationParams, type CallbackParams, type ClientAuthMethod, type CodeChallengeMethod, type DisplayOptions, type EndSessionParameters, type Group, type IdTokenClaims, type IssuerMetadata, type
|
|
310
|
+
export { type AccessToken, type Address, type AuthState, type AuthenticateOptions, type Authenticators, type AuthorizationParams, type CallbackParams, type ClientAuthMethod, type CodeChallengeMethod, type DisplayOptions, type EndSessionParameters, type Group, type IdTokenClaims, type IssuerMetadata, type Jwk, type Jwks, type JwsHeaderParameters, MonoCloudAuthBaseError, type MonoCloudClientOptions, MonoCloudHttpError, MonoCloudOPError, MonoCloudOidcClient, type MonoCloudSession, MonoCloudTokenError, type MonoCloudUser, MonoCloudValidationError, type OnSessionCreating, type ParResponse, type Prompt, type PushedAuthorizationParams, type RefetchUserInfoOptions, type RefreshGrantOptions, type RefreshSessionOptions, type ResponseModes, type ResponseTypes, type SecurityAlgorithms, type Tokens, type UserinfoResponse };
|
|
274
311
|
//# sourceMappingURL=index.d.mts.map
|