@monocloud/auth-core 0.1.2 → 0.1.4

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["now","userinfo: MonoCloudUser | undefined","idTokenClaims: Partial<IdTokenClaims>","session: MonoCloudSession","updatedSession: MonoCloudSession","header: JwsHeaderParameters","claims: IdTokenClaims"],"sources":["../src/errors/monocloud-auth-base-error.ts","../src/errors/monocloud-op-error.ts","../src/errors/monocloud-http-error.ts","../src/errors/monocloud-token-error.ts","../src/errors/monocloud-validation-error.ts","../src/client-auth.ts","../src/monocloud-oidc-client.ts"],"sourcesContent":["export class MonoCloudAuthBaseError extends Error {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudOPError extends MonoCloudAuthBaseError {\n error: string;\n\n errorDescription?: string;\n\n constructor(error: string, errorDescription?: string) {\n super(error);\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudHttpError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudTokenError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudValidationError extends MonoCloudAuthBaseError {}\n","import {\n encodeBase64Url,\n randomBytes,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { ClientAuthMethod, Jwk } from './types';\n\nconst algToSubtle = (\n alg?: string\n): HmacImportParams | RsaHashedImportParams | EcKeyImportParams => {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { name: 'HMAC', hash: `SHA-${alg.slice(-3)}` };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n /* v8 ignore next */\n default:\n throw new Error('unsupported JWS algorithm');\n }\n};\n\nconst psAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst rsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst esAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as EcKeyAlgorithm).namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported EcKeyAlgorithm namedCurve');\n }\n};\n\nconst hsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as HmacKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'HS256';\n case 'SHA-384':\n return 'HS384';\n case 'SHA-512':\n return 'HS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported HMAC Algorithm hash');\n }\n};\n\nconst keyToJws = (key: CryptoKey): string => {\n switch (key.algorithm.name) {\n case 'HMAC':\n return hsAlg(key);\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n /* v8 ignore next */\n default:\n throw new Error('unsupported CryptoKey algorithm name');\n }\n};\n\nconst checkRsaKeyAlgorithm = (key: CryptoKey): void => {\n const { algorithm } = key as CryptoKey & { algorithm: RsaHashedKeyAlgorithm };\n\n /* v8 ignore if -- @preserve */\n if (\n typeof algorithm.modulusLength !== 'number' ||\n algorithm.modulusLength < 2048\n ) {\n throw new Error(`Unsupported ${algorithm.name} modulusLength`);\n }\n};\n\nconst ecdsaHashName = (key: CryptoKey): string => {\n const { algorithm } = key as CryptoKey & { algorithm: EcKeyAlgorithm };\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported ECDSA namedCurve');\n }\n};\n\nexport const keyToSubtle = (\n key: CryptoKey\n): AlgorithmIdentifier | RsaPssParams | EcdsaParams => {\n switch (key.algorithm.name) {\n case 'HMAC': {\n return { name: key.algorithm.name };\n }\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n } as EcdsaParams;\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256': // Fall through\n case 'SHA-384': // Fall through\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength:\n parseInt(\n (key.algorithm as RsaHashedKeyAlgorithm).hash.name.slice(-3),\n 10\n ) >> 3,\n } as RsaPssParams;\n /* v8 ignore next */\n default:\n throw new Error('unsupported RSA-PSS hash name');\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n }\n /* v8 ignore next -- @preserve */\n throw new Error('unsupported CryptoKey algorithm name');\n};\n\nconst clientAssertionPayload = (\n issuer: string,\n clientId: string,\n skew: number\n): Record<string, number | string> => {\n const now = Math.floor(Date.now() / 1000) + skew;\n return {\n jti: randomBytes(),\n aud: issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: clientId,\n sub: clientId,\n };\n};\n\nconst jwtAssertionGenerator = async (\n issuer: string,\n clientId: string,\n clientSecret: Jwk,\n body: URLSearchParams,\n skew: number\n): Promise<void> => {\n const key = await crypto.subtle.importKey(\n 'jwk',\n clientSecret as JsonWebKey,\n algToSubtle(clientSecret.alg),\n false,\n ['sign']\n );\n\n const header = { alg: keyToJws(key), kid: clientSecret.kid };\n const payload = clientAssertionPayload(issuer, clientId, skew);\n\n body.set('client_id', clientId);\n body.set(\n 'client_assertion_type',\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n );\n\n const input = `${encodeBase64Url(stringToArrayBuffer(JSON.stringify(header)))}.${encodeBase64Url(stringToArrayBuffer(JSON.stringify(payload)))}`;\n const signature = encodeBase64Url(\n await crypto.subtle.sign(\n keyToSubtle(key),\n key,\n stringToArrayBuffer(input) as BufferSource\n )\n );\n\n body.set('client_assertion', `${input}.${signature}`);\n};\n\nexport const clientAuth = async (\n clientId: string,\n clientSecret?: string | Jwk,\n method?: ClientAuthMethod,\n issuer?: string,\n headers?: Record<string, string>,\n body?: URLSearchParams,\n jwtAssertionSkew?: number\n): Promise<void> => {\n switch (true) {\n case method === 'client_secret_basic' && !!headers: {\n // eslint-disable-next-line no-param-reassign\n headers.authorization = `Basic ${btoa(`${clientId}:${clientSecret ?? ''}`)}`;\n break;\n }\n\n case method === 'client_secret_post' && !!body: {\n body.set('client_id', clientId);\n if (typeof clientSecret === 'string') {\n body.set('client_secret', clientSecret);\n }\n break;\n }\n\n case method === 'client_secret_jwt' &&\n !!issuer &&\n !!body &&\n (typeof clientSecret === 'string' || clientSecret?.kty === 'oct'): {\n const cs =\n typeof clientSecret === 'string'\n ? {\n k: encodeBase64Url(stringToArrayBuffer(clientSecret)),\n kty: 'oct',\n alg: 'HS256',\n }\n : clientSecret;\n\n await jwtAssertionGenerator(\n issuer,\n clientId,\n cs,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n case method === 'private_key_jwt' &&\n typeof clientSecret === 'object' &&\n clientSecret.kty !== 'oct' &&\n !!issuer &&\n !!body: {\n await jwtAssertionGenerator(\n issuer,\n clientId,\n clientSecret,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n default:\n throw new Error('Invalid Client Authentication Method');\n }\n};\n","import {\n decodeBase64Url,\n findToken,\n getPublicSigKeyFromIssuerJwks,\n now,\n parseSpaceSeparated,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { clientAuth, keyToSubtle } from './client-auth';\nimport {\n AccessToken,\n AuthenticateOptions,\n AuthorizationParams,\n ClientAuthMethod,\n EndSessionParameters,\n IdTokenClaims,\n IssuerMetadata,\n Jwk,\n Jwks,\n JWSAlgorithm,\n JwsHeaderParameters,\n MonoCloudClientOptions,\n MonoCloudSession,\n MonoCloudUser,\n ParResponse,\n PushedAuthorizationParams,\n RefetchUserInfoOptions,\n RefreshGrantOptions,\n RefreshSessionOptions,\n Tokens,\n UserinfoResponse,\n} from './types';\nimport { MonoCloudOPError } from './errors/monocloud-op-error';\nimport { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { MonoCloudTokenError } from './errors/monocloud-token-error';\nimport { MonoCloudAuthBaseError } from './errors/monocloud-auth-base-error';\n\nconst JWT_ASSERTION_CLOCK_SKEW = 5;\n\nconst FILTER_ID_TOKEN_CLAIMS = [\n 'iss',\n 'exp',\n 'nbf',\n 'aud',\n 'nonce',\n 'iat',\n 'auth_time',\n 'c_hash',\n 'at_hash',\n 's_hash',\n];\n\nfunction assertMetadataProperty<K extends keyof IssuerMetadata>(\n metadata: IssuerMetadata,\n property: K\n): asserts metadata is IssuerMetadata & Required<Pick<IssuerMetadata, K>> {\n if (metadata[property] === undefined || metadata[property] === null) {\n throw new MonoCloudValidationError(\n `${property as string} endpoint is required but not available in the issuer metadata`\n );\n }\n}\n\nconst innerFetch = async (\n input: string,\n reqInit: RequestInit = {}\n): Promise<Response> => {\n try {\n return await fetch(input, reqInit);\n } catch (e) {\n /* v8 ignore next -- @preserve */\n throw new MonoCloudHttpError(\n (e as any).message ?? 'Unexpected Network Error'\n );\n }\n};\n\nconst deserializeJson = async <T = any>(res: Response): Promise<T> => {\n try {\n return await res.json();\n } catch (e) {\n throw new MonoCloudHttpError(\n /* v8 ignore next -- @preserve */\n `Failed to parse response body as JSON ${(e as any).message ? `: ${(e as any).message}` : ''}`\n );\n }\n};\n\nexport class MonoCloudOidcClient {\n private readonly tenantDomain: string;\n\n private readonly clientId: string;\n\n private readonly clientSecret?: string | Jwk;\n\n private readonly authMethod: ClientAuthMethod;\n\n private readonly idTokenSigningAlgorithm: JWSAlgorithm;\n\n private jwks?: Jwks;\n\n private jwksCacheExpiry = 0;\n\n private jwksCacheDuration = 60;\n\n private metadata?: IssuerMetadata;\n\n private metadataCacheExpiry = 0;\n\n private metadataCacheDuration = 60;\n\n constructor(\n tenantDomain: string,\n clientId: string,\n options?: MonoCloudClientOptions\n ) {\n // eslint-disable-next-line no-param-reassign\n tenantDomain ??= '';\n /* v8 ignore next -- @preserve */\n this.tenantDomain = `${!tenantDomain.startsWith('https://') ? 'https://' : ''}${tenantDomain.endsWith('/') ? tenantDomain.slice(0, -1) : tenantDomain}`;\n this.clientId = clientId;\n this.clientSecret = options?.clientSecret;\n this.authMethod = options?.clientAuthMethod ?? 'client_secret_basic';\n this.idTokenSigningAlgorithm = options?.idTokenSigningAlgorithm ?? 'RS256';\n\n if (options?.jwksCacheDuration) {\n this.jwksCacheDuration = options.jwksCacheDuration;\n }\n\n if (options?.metadataCacheDuration) {\n this.metadataCacheDuration = options.metadataCacheDuration;\n }\n }\n\n /**\n * Generates an authorization URL with specified parameters.\n *\n * If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.\n *\n * @param params Authorization URL parameters\n *\n * @returns Tenant's authorization url.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authorizationUrl(params: AuthorizationParams): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n queryParams.set('redirect_uri', params.redirectUri);\n }\n\n if (params.requestUri) {\n queryParams.set('request_uri', params.requestUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n queryParams.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n queryParams.set('response_type', params.responseType);\n }\n\n if (\n (!params.responseType || params.responseType.length === 0) &&\n !params.requestUri\n ) {\n queryParams.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n queryParams.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n queryParams.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n queryParams.set('request', params.request);\n }\n\n if (params.responseMode) {\n queryParams.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n queryParams.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n queryParams.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n queryParams.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n queryParams.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n queryParams.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n queryParams.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n queryParams.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n queryParams.set('code_challenge', params.codeChallenge);\n queryParams.set(\n 'code_challenge_method',\n params.codeChallengeMethod ?? 'S256'\n );\n }\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'authorization_endpoint');\n\n return `${metadata.authorization_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Fetches the authorization server metadata from the .well-known endpoint.\n * The metadata is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh metadata from the server.\n *\n * @returns The issuer metadata for the tenant, retrieved from the OpenID Connect discovery endpoint.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getMetadata(forceRefresh = false): Promise<IssuerMetadata> {\n if (!forceRefresh && this.metadata && this.metadataCacheExpiry > now()) {\n return this.metadata;\n }\n\n this.metadata = undefined;\n\n const response = await innerFetch(\n `${this.tenantDomain}/.well-known/openid-configuration`\n );\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching metadata. Unexpected status code: ${response.status}`\n );\n }\n\n const metadata = await deserializeJson<IssuerMetadata>(response);\n\n this.metadata = metadata;\n this.metadataCacheExpiry = now() + this.metadataCacheDuration;\n\n return metadata;\n }\n\n /**\n * Fetches the JSON Web Keys used to sign the id token.\n * The JWKS is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.\n *\n * @returns The JSON Web Key Set containing the public keys for token verification.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getJwks(forceRefresh = false): Promise<Jwks> {\n if (!forceRefresh && this.jwks && this.jwksCacheExpiry > now()) {\n return this.jwks;\n }\n\n this.jwks = undefined;\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'jwks_uri');\n\n const response = await innerFetch(metadata.jwks_uri);\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching JWKS. Unexpected status code: ${response.status}`\n );\n }\n const jwks = await deserializeJson<Jwks>(response);\n\n this.jwks = jwks;\n this.jwksCacheExpiry = now() + this.jwksCacheDuration;\n\n return jwks;\n }\n\n /**\n * Performs a pushed authorization request.\n *\n * @param params - Authorization Parameters\n *\n * @returns Response from Pushed Authorization Request (PAR) endpoint\n *\n * @throws {@link MonoCloudOPError} - When the request is invalid.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async pushedAuthorizationRequest(\n params: PushedAuthorizationParams\n ): Promise<ParResponse> {\n const body = new URLSearchParams();\n\n body.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n body.set('redirect_uri', params.redirectUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n body.set('response_type', params.responseType);\n } else {\n body.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n body.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n body.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n body.set('request', params.request);\n }\n\n if (params.responseMode) {\n body.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n body.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n body.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n body.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n body.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n body.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n body.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n body.set('code_challenge', params.codeChallenge);\n body.set('code_challenge_method', params.codeChallengeMethod ?? 'S256');\n }\n\n if (params.state) {\n body.set('state', params.state);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'pushed_authorization_request_endpoint');\n\n const response = await innerFetch(\n metadata.pushed_authorization_request_endpoint,\n {\n body: body.toString(),\n method: 'POST',\n headers,\n }\n );\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'par_request_failed',\n standardBodyError.error_description ??\n 'Pushed Authorization Request Failed'\n );\n }\n\n if (response.status !== 201) {\n throw new MonoCloudHttpError(\n `Error while performing pushed authorization request. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<ParResponse>(response);\n }\n\n /**\n * Fetches userinfo associated with the provided access token.\n *\n * @param accessToken - A valid access token used to retrieve userinfo.\n *\n * @returns The authenticated user's claims.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error (e.g., 'invalid_token') in the 'WWW-Authenticate' header\n * following a 401 Unauthorized response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n * @throws {@link MonoCloudValidationError} - When the access token is invalid.\n *\n */\n async userinfo(accessToken: string): Promise<UserinfoResponse> {\n if (!accessToken.trim().length) {\n throw new MonoCloudValidationError(\n 'Access token is required for fetching userinfo'\n );\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'userinfo_endpoint');\n\n const response = await innerFetch(metadata.userinfo_endpoint, {\n method: 'GET',\n headers: {\n authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (response.status === 401) {\n const authenticateError = response.headers.get('WWW-Authenticate');\n\n if (authenticateError) {\n const errorMatch = /error=\"([^\"]+)\"/.exec(authenticateError);\n const error = errorMatch ? errorMatch[1] : 'userinfo_failed';\n\n const errorDescMatch = /error_description=\"([^\"]+)\"/.exec(\n authenticateError\n );\n\n const errorDescription = errorDescMatch\n ? errorDescMatch[1]\n : 'Userinfo authentication error';\n\n throw new MonoCloudOPError(error, errorDescription);\n }\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching userinfo. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<UserinfoResponse>(response);\n }\n\n /**\n * Generates OpenID end session url for signing out.\n *\n * Note - The `state` is added only when `postLogoutRedirectUri` is present.\n *\n * @param params - Parameters to build end session url\n *\n * @returns Tenant's end session url\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async endSessionUrl(params: EndSessionParameters): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.idToken) {\n queryParams.set('id_token_hint', params.idToken);\n }\n\n if (params.postLogoutRedirectUri) {\n queryParams.set('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'end_session_endpoint');\n\n return `${metadata.end_session_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Exchanges an authorization code for tokens.\n *\n * @param code - The authorization code received from the authorization server.\n * @param redirectUri - The redirect URI used in the initial authorization request.\n * @param codeVerifier - Code verifier for PKCE.\n * @param resource - Space-separated list of resources the access token should be scoped to\n *\n * @returns Tokens obtained by exchanging an authorization code at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async exchangeAuthorizationCode(\n code: string,\n redirectUri: string,\n codeVerifier?: string,\n resource?: string\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'authorization_code');\n body.set('code', code);\n body.set('redirect_uri', redirectUri);\n\n if (codeVerifier) {\n body.set('code_verifier', codeVerifier);\n }\n\n const resources = parseSpaceSeparated(resource) ?? [];\n\n if (resources.length > 0) {\n for (const r of resources) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'code_grant_failed',\n standardBodyError.error_description ?? 'Authorization code grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Exchanges a refresh token for new tokens.\n *\n * @param refreshToken - The refresh token used to request new tokens.\n * @param options - Refresh grant options.\n *\n * @returns Tokens obtained by exchanging a refresh token at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshGrant(\n refreshToken: string,\n options?: RefreshGrantOptions\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'refresh_token');\n body.set('refresh_token', refreshToken);\n\n const scopes = parseSpaceSeparated(options?.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n const resource = parseSpaceSeparated(options?.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'refresh_grant_failed',\n standardBodyError.error_description ?? 'Refresh token grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing refresh token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Generates a session with user and tokens by exchanging authorization code from callback params.\n *\n * @param code - The authorization code received from the callback\n * @param redirectUri - The redirect URI that was used in the authorization request\n * @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.\n * This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.\n * @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.\n * Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.\n * @param options - Options for authenticating a user with authorization code\n *\n * @returns The user's session containing authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,\n * or if 'expires_in' or 'scope' is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authenticate(\n code: string,\n redirectUri: string,\n requestedScopes: string,\n resource?: string,\n options?: AuthenticateOptions\n ): Promise<MonoCloudSession> {\n const tokens = await this.exchangeAuthorizationCode(\n code,\n redirectUri,\n options?.codeVerifier,\n resource\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0,\n options?.idTokenMaxAge,\n options?.idTokenNonce\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const session: MonoCloudSession = {\n user: {\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser,\n idToken: tokens.id_token,\n refreshToken: tokens.refresh_token,\n authorizedScopes: requestedScopes,\n accessTokens: [\n {\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes,\n },\n ],\n };\n\n await options?.onSessionCreating?.(session, idTokenClaims, userinfo);\n\n return session;\n }\n\n /**\n * Refetches user information for an existing session using the userinfo endpoint.\n * Updates the session's user object with the latest user information while preserving existing properties.\n *\n * @param accessToken - Access token used to fetch the userinfo\n * @param session - The current MonoCloudSession\n * @param options - Userinfo refetch options\n *\n * @returns Updated session with the latest userinfo\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain openid scope\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refetchUserInfo(\n accessToken: AccessToken,\n session: MonoCloudSession,\n options?: RefetchUserInfoOptions\n ): Promise<MonoCloudSession> {\n if (!accessToken.scopes?.includes('openid')) {\n throw new MonoCloudValidationError(\n 'Fetching userinfo requires the openid scope'\n );\n }\n\n const userinfo = await this.userinfo(accessToken.accessToken);\n\n // eslint-disable-next-line no-param-reassign\n session.user = { ...session.user, ...userinfo };\n\n await options?.onSessionCreating?.(session, undefined, userinfo);\n\n return session;\n }\n\n /**\n * Refreshes an existing session using the refresh token.\n * This function requests new tokens using the refresh token and optionally updates user information.\n *\n * @param session - The current MonoCloudSession containing the refresh token\n * @param options - Session refresh options\n *\n * @returns User's session containing refreshed authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - If the refresh token is not present in the session,\n * or if 'expires_in' or 'scope' (including the openid scope) is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshSession(\n session: MonoCloudSession,\n options?: RefreshSessionOptions\n ): Promise<MonoCloudSession> {\n if (!session.refreshToken) {\n throw new MonoCloudValidationError(\n 'Session does not contain refresh token'\n );\n }\n\n const tokens = await this.refreshGrant(\n session.refreshToken,\n options?.refreshGrantOptions\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const resource = options?.refreshGrantOptions?.resource;\n let scopes = options?.refreshGrantOptions?.scopes;\n\n if (!resource && !scopes) {\n scopes = session.authorizedScopes;\n }\n\n const accessToken = findToken(session.accessTokens, resource, scopes);\n\n const user =\n Object.keys(idTokenClaims).length === 0 && !userinfo\n ? session.user\n : ({\n ...session.user,\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser);\n\n const newTokens =\n session.accessTokens?.filter(t => t !== accessToken) ?? [];\n\n newTokens.push({\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes: scopes,\n });\n\n const updatedSession: MonoCloudSession = {\n ...session,\n user,\n idToken: tokens.id_token ?? session.idToken,\n refreshToken: tokens.refresh_token ?? session.refreshToken,\n accessTokens: newTokens,\n };\n\n await options?.onSessionCreating?.(updatedSession, idTokenClaims, userinfo);\n\n return updatedSession;\n }\n\n /**\n * Revokes an access token or refresh token, rendering it invalid for future use.\n *\n * @param token - The token string to be revoked\n * @param tokenType - Hint about the token type ('access_token' or 'refresh_token')\n *\n * @returns If token revocation succeeded\n *\n * @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n */\n async revokeToken(token: string, tokenType?: string): Promise<void> {\n if (!token.trim().length) {\n throw new MonoCloudValidationError('Invalid token');\n }\n\n if (\n tokenType &&\n tokenType !== 'access_token' &&\n tokenType !== 'refresh_token'\n ) {\n throw new MonoCloudValidationError(\n 'Only access_token and refresh_token types are supported.'\n );\n }\n\n const body = new URLSearchParams();\n body.set('token', token);\n if (tokenType) {\n body.set('token_type_hint', tokenType);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'revocation_endpoint');\n\n const response = await innerFetch(metadata.revocation_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'revocation_failed',\n standardBodyError.error_description ?? 'Token revocation failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing revocation request. Unexpected status code: ${response.status}`\n );\n }\n }\n\n /**\n * Validates an ID Token.\n *\n * @param idToken - The ID Token JWT string to validate\n * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature\n * @param clockSkew - Number of seconds to adjust the current time to account for clock differences\n * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation\n * @param maxAge - maximum authentication age in seconds\n * @param nonce - nonce value to validate against the token's nonce claim\n *\n * @returns Validated ID Token claims\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n */\n async validateIdToken(\n idToken: string,\n jwks: Jwk[],\n clockSkew: number,\n clockTolerance: number,\n maxAge?: number,\n nonce?: string\n ): Promise<IdTokenClaims> {\n if (typeof idToken !== 'string' || idToken.trim().length === 0) {\n throw new MonoCloudTokenError(\n 'ID Token must be a valid non-empty string'\n );\n }\n\n const {\n 0: protectedHeader,\n 1: payload,\n 2: encodedSignature,\n length,\n } = idToken.split('.');\n\n if (length !== 3) {\n throw new MonoCloudTokenError(\n 'ID Token must have a header, payload and signature'\n );\n }\n\n let header: JwsHeaderParameters;\n try {\n header = JSON.parse(decodeBase64Url(protectedHeader));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Header');\n }\n\n if (\n header === null ||\n typeof header !== 'object' ||\n Array.isArray(header)\n ) {\n throw new MonoCloudTokenError('JWT Header must be a top level object');\n }\n\n if (this.idTokenSigningAlgorithm !== header.alg) {\n throw new MonoCloudTokenError('Invalid signing alg');\n }\n\n if (header.crit !== undefined) {\n throw new MonoCloudTokenError('Unexpected JWT \"crit\" header parameter');\n }\n\n const binary = decodeBase64Url(encodedSignature);\n\n const signature = new Uint8Array(binary.length);\n\n for (let i = 0; i < binary.length; i++) {\n signature[i] = binary.charCodeAt(i);\n }\n\n const key = await getPublicSigKeyFromIssuerJwks(jwks, header);\n\n const input = `${protectedHeader}.${payload}`;\n\n const verified = await crypto.subtle.verify(\n keyToSubtle(key),\n key,\n signature,\n stringToArrayBuffer(input) as BufferSource\n );\n\n if (!verified) {\n throw new MonoCloudTokenError('JWT signature verification failed');\n }\n\n let claims: IdTokenClaims;\n\n try {\n claims = JSON.parse(decodeBase64Url(payload));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Payload');\n }\n\n if (\n claims === null ||\n typeof claims !== 'object' ||\n Array.isArray(claims)\n ) {\n throw new MonoCloudTokenError('JWT Payload must be a top level object');\n }\n\n if ((claims.nonce || nonce) && claims.nonce !== nonce) {\n throw new MonoCloudTokenError('Nonce mismatch');\n }\n\n const current = now() + clockSkew;\n\n /* v8 ignore else -- @preserve */\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim type'\n );\n }\n\n if (claims.exp <= current - clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim value, timestamp is <= now()'\n );\n }\n }\n\n /* v8 ignore else -- @preserve */\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"iat\" (issued at) claim type'\n );\n }\n }\n\n if (\n typeof claims.auth_time === 'number' &&\n typeof maxAge === 'number' &&\n claims.auth_time + maxAge < current\n ) {\n throw new MonoCloudTokenError(\n 'Too much time has elapsed since the last End-User authentication'\n );\n }\n\n if (claims.iss !== this.tenantDomain) {\n throw new MonoCloudTokenError('Invalid Issuer');\n }\n\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim type'\n );\n }\n\n if (claims.nbf > current + clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim value, timestamp is > now()'\n );\n }\n }\n\n const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n\n if (!audience.includes(this.clientId)) {\n throw new MonoCloudTokenError('Invalid audience claim');\n }\n\n return claims;\n }\n\n /**\n * Decodes the payload of a JSON Web Token (JWT) and returns it as an object.\n * **THIS METHOD DOES NOT VERIFY JWT TOKENS**.\n *\n * @param jwt - JWT to decode\n *\n * @returns Decoded payload\n *\n * @throws {@link MonoCloudTokenError} - If decoding fails\n *\n */\n static decodeJwt(jwt: string): IdTokenClaims {\n try {\n const [, payload] = jwt.split('.');\n\n if (!payload?.trim()) {\n throw new MonoCloudTokenError('JWT does not contain payload');\n }\n\n const decoded = decodeBase64Url(payload);\n\n if (!decoded.startsWith('{')) {\n throw new MonoCloudTokenError('Payload is not an object');\n }\n\n return JSON.parse(decoded) as IdTokenClaims;\n } catch (e) {\n if (e instanceof MonoCloudAuthBaseError) {\n throw e;\n }\n\n throw new MonoCloudTokenError(\n 'Could not parse payload. Malformed payload'\n );\n }\n }\n}\n"],"mappings":";;;AAAA,IAAa,yBAAb,cAA4C,MAAM;;;;ACElD,IAAa,mBAAb,cAAsC,u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,OAAO,UAAU,eAC1B,OAAM,IAAI,oBACR,8EACD;;;AAKL,MAAI,OAAO,QAAQ,QACjB;OAAI,OAAO,OAAO,QAAQ,SACxB,OAAM,IAAI,oBACR,gDACD;;AAIL,MACE,OAAO,OAAO,cAAc,YAC5B,OAAO,WAAW,YAClB,OAAO,YAAY,SAAS,QAE5B,OAAM,IAAI,oBACR,mEACD;AAGH,MAAI,OAAO,QAAQ,KAAK,aACtB,OAAM,IAAI,oBAAoB,iBAAiB;AAGjD,MAAI,OAAO,QAAQ,QAAW;AAC5B,OAAI,OAAO,OAAO,QAAQ,SACxB,OAAM,IAAI,oBACR,iDACD;AAGH,OAAI,OAAO,MAAM,UAAU,eACzB,OAAM,IAAI,oBACR,wEACD;;AAML,MAAI,EAFa,MAAM,QAAQ,OAAO,IAAI,GAAG,OAAO,MAAM,CAAC,OAAO,IAAI,EAExD,SAAS,KAAK,SAAS,CACnC,OAAM,IAAI,oBAAoB,yBAAyB;AAGzD,SAAO;;;;;;;;;;;;;CAcT,OAAO,UAAU,KAA4B;AAC3C,MAAI;GACF,MAAM,GAAG,WAAW,IAAI,MAAM,IAAI;AAElC,OAAI,CAAC,SAAS,MAAM,CAClB,OAAM,IAAI,oBAAoB,+BAA+B;GAG/D,MAAM,UAAU,gBAAgB,QAAQ;AAExC,OAAI,CAAC,QAAQ,WAAW,IAAI,CAC1B,OAAM,IAAI,oBAAoB,2BAA2B;AAG3D,UAAO,KAAK,MAAM,QAAQ;WACnB,GAAG;AACV,OAAI,aAAa,uBACf,OAAM;AAGR,SAAM,IAAI,oBACR,6CACD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/errors/monocloud-auth-base-error.ts","../src/errors/monocloud-op-error.ts","../src/errors/monocloud-http-error.ts","../src/errors/monocloud-token-error.ts","../src/errors/monocloud-validation-error.ts","../src/client-auth.ts","../src/monocloud-oidc-client.ts"],"sourcesContent":["export class MonoCloudAuthBaseError extends Error {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudOPError extends MonoCloudAuthBaseError {\n error: string;\n\n errorDescription?: string;\n\n constructor(error: string, errorDescription?: string) {\n super(error);\n this.error = error;\n this.errorDescription = errorDescription;\n }\n}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudHttpError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudTokenError extends MonoCloudAuthBaseError {}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\nexport class MonoCloudValidationError extends MonoCloudAuthBaseError {}\n","import {\n encodeBase64Url,\n randomBytes,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { ClientAuthMethod, Jwk } from './types';\n\nconst algToSubtle = (\n alg?: string\n): HmacImportParams | RsaHashedImportParams | EcKeyImportParams => {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { name: 'HMAC', hash: `SHA-${alg.slice(-3)}` };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n /* v8 ignore next */\n default:\n throw new Error('unsupported JWS algorithm');\n }\n};\n\nconst psAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst rsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n }\n};\n\nconst esAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as EcKeyAlgorithm).namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported EcKeyAlgorithm namedCurve');\n }\n};\n\nconst hsAlg = (key: CryptoKey): string => {\n switch ((key.algorithm as HmacKeyAlgorithm).hash.name) {\n case 'SHA-256':\n return 'HS256';\n case 'SHA-384':\n return 'HS384';\n case 'SHA-512':\n return 'HS512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported HMAC Algorithm hash');\n }\n};\n\nconst keyToJws = (key: CryptoKey): string => {\n switch (key.algorithm.name) {\n case 'HMAC':\n return hsAlg(key);\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n /* v8 ignore next */\n default:\n throw new Error('unsupported CryptoKey algorithm name');\n }\n};\n\nconst checkRsaKeyAlgorithm = (key: CryptoKey): void => {\n const { algorithm } = key as CryptoKey & { algorithm: RsaHashedKeyAlgorithm };\n\n /* v8 ignore if -- @preserve */\n if (\n typeof algorithm.modulusLength !== 'number' ||\n algorithm.modulusLength < 2048\n ) {\n throw new Error(`Unsupported ${algorithm.name} modulusLength`);\n }\n};\n\nconst ecdsaHashName = (key: CryptoKey): string => {\n const { algorithm } = key as CryptoKey & { algorithm: EcKeyAlgorithm };\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n /* v8 ignore next */\n default:\n throw new Error('unsupported ECDSA namedCurve');\n }\n};\n\nexport const keyToSubtle = (\n key: CryptoKey\n): AlgorithmIdentifier | RsaPssParams | EcdsaParams => {\n switch (key.algorithm.name) {\n case 'HMAC': {\n return { name: key.algorithm.name };\n }\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n } as EcdsaParams;\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n case 'SHA-256': // Fall through\n case 'SHA-384': // Fall through\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength:\n parseInt(\n (key.algorithm as RsaHashedKeyAlgorithm).hash.name.slice(-3),\n 10\n ) >> 3,\n } as RsaPssParams;\n /* v8 ignore next */\n default:\n throw new Error('unsupported RSA-PSS hash name');\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n }\n /* v8 ignore next -- @preserve */\n throw new Error('unsupported CryptoKey algorithm name');\n};\n\nconst clientAssertionPayload = (\n issuer: string,\n clientId: string,\n skew: number\n): Record<string, number | string> => {\n const now = Math.floor(Date.now() / 1000) + skew;\n return {\n jti: randomBytes(),\n aud: issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: clientId,\n sub: clientId,\n };\n};\n\nconst jwtAssertionGenerator = async (\n issuer: string,\n clientId: string,\n clientSecret: Jwk,\n body: URLSearchParams,\n skew: number\n): Promise<void> => {\n const key = await crypto.subtle.importKey(\n 'jwk',\n clientSecret as JsonWebKey,\n algToSubtle(clientSecret.alg),\n false,\n ['sign']\n );\n\n const header = { alg: keyToJws(key), kid: clientSecret.kid };\n const payload = clientAssertionPayload(issuer, clientId, skew);\n\n body.set('client_id', clientId);\n body.set(\n 'client_assertion_type',\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n );\n\n const input = `${encodeBase64Url(stringToArrayBuffer(JSON.stringify(header)))}.${encodeBase64Url(stringToArrayBuffer(JSON.stringify(payload)))}`;\n const signature = encodeBase64Url(\n await crypto.subtle.sign(\n keyToSubtle(key),\n key,\n stringToArrayBuffer(input) as BufferSource\n )\n );\n\n body.set('client_assertion', `${input}.${signature}`);\n};\n\nexport const clientAuth = async (\n clientId: string,\n clientSecret?: string | Jwk,\n method?: ClientAuthMethod,\n issuer?: string,\n headers?: Record<string, string>,\n body?: URLSearchParams,\n jwtAssertionSkew?: number\n): Promise<void> => {\n switch (true) {\n case method === 'client_secret_basic' && !!headers: {\n // eslint-disable-next-line no-param-reassign\n headers.authorization = `Basic ${btoa(`${clientId}:${clientSecret ?? ''}`)}`;\n break;\n }\n\n case method === 'client_secret_post' && !!body: {\n body.set('client_id', clientId);\n if (typeof clientSecret === 'string') {\n body.set('client_secret', clientSecret);\n }\n break;\n }\n\n case method === 'client_secret_jwt' &&\n !!issuer &&\n !!body &&\n (typeof clientSecret === 'string' || clientSecret?.kty === 'oct'): {\n const cs =\n typeof clientSecret === 'string'\n ? {\n k: encodeBase64Url(stringToArrayBuffer(clientSecret)),\n kty: 'oct',\n alg: 'HS256',\n }\n : clientSecret;\n\n await jwtAssertionGenerator(\n issuer,\n clientId,\n cs,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n case method === 'private_key_jwt' &&\n typeof clientSecret === 'object' &&\n clientSecret.kty !== 'oct' &&\n !!issuer &&\n !!body: {\n await jwtAssertionGenerator(\n issuer,\n clientId,\n clientSecret,\n body,\n jwtAssertionSkew ?? 0\n );\n break;\n }\n\n default:\n throw new Error('Invalid Client Authentication Method');\n }\n};\n","import {\n decodeBase64Url,\n findToken,\n getPublicSigKeyFromIssuerJwks,\n now,\n parseSpaceSeparated,\n stringToArrayBuffer,\n} from './utils/internal';\nimport { clientAuth, keyToSubtle } from './client-auth';\nimport {\n AccessToken,\n AuthenticateOptions,\n AuthorizationParams,\n ClientAuthMethod,\n EndSessionParameters,\n IdTokenClaims,\n IssuerMetadata,\n Jwk,\n Jwks,\n JWSAlgorithm,\n JwsHeaderParameters,\n MonoCloudClientOptions,\n MonoCloudSession,\n MonoCloudUser,\n ParResponse,\n PushedAuthorizationParams,\n RefetchUserInfoOptions,\n RefreshGrantOptions,\n RefreshSessionOptions,\n Tokens,\n UserinfoResponse,\n} from './types';\nimport { MonoCloudOPError } from './errors/monocloud-op-error';\nimport { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { MonoCloudTokenError } from './errors/monocloud-token-error';\nimport { MonoCloudAuthBaseError } from './errors/monocloud-auth-base-error';\n\nconst JWT_ASSERTION_CLOCK_SKEW = 5;\n\nconst FILTER_ID_TOKEN_CLAIMS = [\n 'iss',\n 'exp',\n 'nbf',\n 'aud',\n 'nonce',\n 'iat',\n 'auth_time',\n 'c_hash',\n 'at_hash',\n 's_hash',\n];\n\nfunction assertMetadataProperty<K extends keyof IssuerMetadata>(\n metadata: IssuerMetadata,\n property: K\n): asserts metadata is IssuerMetadata & Required<Pick<IssuerMetadata, K>> {\n if (metadata[property] === undefined || metadata[property] === null) {\n throw new MonoCloudValidationError(\n `${property as string} endpoint is required but not available in the issuer metadata`\n );\n }\n}\n\nconst innerFetch = async (\n input: string,\n reqInit: RequestInit = {}\n): Promise<Response> => {\n try {\n return await fetch(input, reqInit);\n } catch (e) {\n /* v8 ignore next -- @preserve */\n throw new MonoCloudHttpError(\n (e as any).message ?? 'Unexpected Network Error'\n );\n }\n};\n\nconst deserializeJson = async <T = any>(res: Response): Promise<T> => {\n try {\n return await res.json();\n } catch (e) {\n throw new MonoCloudHttpError(\n /* v8 ignore next -- @preserve */\n `Failed to parse response body as JSON ${(e as any).message ? `: ${(e as any).message}` : ''}`\n );\n }\n};\n\nexport class MonoCloudOidcClient {\n private readonly tenantDomain: string;\n\n private readonly clientId: string;\n\n private readonly clientSecret?: string | Jwk;\n\n private readonly authMethod: ClientAuthMethod;\n\n private readonly idTokenSigningAlgorithm: JWSAlgorithm;\n\n private jwks?: Jwks;\n\n private jwksCacheExpiry = 0;\n\n private jwksCacheDuration = 60;\n\n private metadata?: IssuerMetadata;\n\n private metadataCacheExpiry = 0;\n\n private metadataCacheDuration = 60;\n\n constructor(\n tenantDomain: string,\n clientId: string,\n options?: MonoCloudClientOptions\n ) {\n // eslint-disable-next-line no-param-reassign\n tenantDomain ??= '';\n /* v8 ignore next -- @preserve */\n this.tenantDomain = `${!tenantDomain.startsWith('https://') ? 'https://' : ''}${tenantDomain.endsWith('/') ? tenantDomain.slice(0, -1) : tenantDomain}`;\n this.clientId = clientId;\n this.clientSecret = options?.clientSecret;\n this.authMethod = options?.clientAuthMethod ?? 'client_secret_basic';\n this.idTokenSigningAlgorithm = options?.idTokenSigningAlgorithm ?? 'RS256';\n\n if (options?.jwksCacheDuration) {\n this.jwksCacheDuration = options.jwksCacheDuration;\n }\n\n if (options?.metadataCacheDuration) {\n this.metadataCacheDuration = options.metadataCacheDuration;\n }\n }\n\n /**\n * Generates an authorization URL with specified parameters.\n *\n * If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.\n *\n * @param params Authorization URL parameters\n *\n * @returns Tenant's authorization url.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authorizationUrl(params: AuthorizationParams): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n queryParams.set('redirect_uri', params.redirectUri);\n }\n\n if (params.requestUri) {\n queryParams.set('request_uri', params.requestUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n queryParams.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n queryParams.set('response_type', params.responseType);\n }\n\n if (\n (!params.responseType || params.responseType.length === 0) &&\n !params.requestUri\n ) {\n queryParams.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n queryParams.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n queryParams.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n queryParams.set('request', params.request);\n }\n\n if (params.responseMode) {\n queryParams.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n queryParams.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n queryParams.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n queryParams.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n queryParams.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n queryParams.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n queryParams.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n queryParams.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n queryParams.set('code_challenge', params.codeChallenge);\n queryParams.set(\n 'code_challenge_method',\n params.codeChallengeMethod ?? 'S256'\n );\n }\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'authorization_endpoint');\n\n return `${metadata.authorization_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Fetches the authorization server metadata from the .well-known endpoint.\n * The metadata is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh metadata from the server.\n *\n * @returns The issuer metadata for the tenant, retrieved from the OpenID Connect discovery endpoint.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getMetadata(forceRefresh = false): Promise<IssuerMetadata> {\n if (!forceRefresh && this.metadata && this.metadataCacheExpiry > now()) {\n return this.metadata;\n }\n\n this.metadata = undefined;\n\n const response = await innerFetch(\n `${this.tenantDomain}/.well-known/openid-configuration`\n );\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching metadata. Unexpected status code: ${response.status}`\n );\n }\n\n const metadata = await deserializeJson<IssuerMetadata>(response);\n\n this.metadata = metadata;\n this.metadataCacheExpiry = now() + this.metadataCacheDuration;\n\n return metadata;\n }\n\n /**\n * Fetches the JSON Web Keys used to sign the id token.\n * The JWKS is cached for 1 minute.\n *\n * @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.\n *\n * @returns The JSON Web Key Set containing the public keys for token verification.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async getJwks(forceRefresh = false): Promise<Jwks> {\n if (!forceRefresh && this.jwks && this.jwksCacheExpiry > now()) {\n return this.jwks;\n }\n\n this.jwks = undefined;\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'jwks_uri');\n\n const response = await innerFetch(metadata.jwks_uri);\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching JWKS. Unexpected status code: ${response.status}`\n );\n }\n const jwks = await deserializeJson<Jwks>(response);\n\n this.jwks = jwks;\n this.jwksCacheExpiry = now() + this.jwksCacheDuration;\n\n return jwks;\n }\n\n /**\n * Performs a pushed authorization request.\n *\n * @param params - Authorization Parameters\n *\n * @returns Response from Pushed Authorization Request (PAR) endpoint\n *\n * @throws {@link MonoCloudOPError} - When the request is invalid.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async pushedAuthorizationRequest(\n params: PushedAuthorizationParams\n ): Promise<ParResponse> {\n const body = new URLSearchParams();\n\n body.set('client_id', this.clientId);\n\n if (params.redirectUri) {\n body.set('redirect_uri', params.redirectUri);\n }\n\n const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n if (params.responseType && params.responseType.length > 0) {\n body.set('response_type', params.responseType);\n } else {\n body.set('response_type', 'code');\n }\n\n if (params.authenticatorHint) {\n body.set('authenticator_hint', params.authenticatorHint);\n }\n\n if (params.loginHint) {\n body.set('login_hint', params.loginHint);\n }\n\n if (params.request) {\n body.set('request', params.request);\n }\n\n if (params.responseMode) {\n body.set('response_mode', params.responseMode);\n }\n\n if (params.acrValues && params.acrValues.length > 0) {\n body.set('acr_values', params.acrValues.join(' '));\n }\n\n if (params.nonce) {\n body.set('nonce', params.nonce);\n }\n\n if (params.uiLocales) {\n body.set('ui_locales', params.uiLocales);\n }\n\n if (params.display) {\n body.set('display', params.display);\n }\n\n if (typeof params.maxAge === 'number') {\n body.set('max_age', params.maxAge.toString());\n }\n\n if (params.prompt) {\n body.set('prompt', params.prompt);\n }\n\n const resource = parseSpaceSeparated(params.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n if (params.codeChallenge) {\n body.set('code_challenge', params.codeChallenge);\n body.set('code_challenge_method', params.codeChallengeMethod ?? 'S256');\n }\n\n if (params.state) {\n body.set('state', params.state);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'pushed_authorization_request_endpoint');\n\n const response = await innerFetch(\n metadata.pushed_authorization_request_endpoint,\n {\n body: body.toString(),\n method: 'POST',\n headers,\n }\n );\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'par_request_failed',\n standardBodyError.error_description ??\n 'Pushed Authorization Request Failed'\n );\n }\n\n if (response.status !== 201) {\n throw new MonoCloudHttpError(\n `Error while performing pushed authorization request. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<ParResponse>(response);\n }\n\n /**\n * Fetches userinfo associated with the provided access token.\n *\n * @param accessToken - A valid access token used to retrieve userinfo.\n *\n * @returns The authenticated user's claims.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error (e.g., 'invalid_token') in the 'WWW-Authenticate' header\n * following a 401 Unauthorized response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n * @throws {@link MonoCloudValidationError} - When the access token is invalid.\n *\n */\n async userinfo(accessToken: string): Promise<UserinfoResponse> {\n if (!accessToken.trim().length) {\n throw new MonoCloudValidationError(\n 'Access token is required for fetching userinfo'\n );\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'userinfo_endpoint');\n\n const response = await innerFetch(metadata.userinfo_endpoint, {\n method: 'GET',\n headers: {\n authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (response.status === 401) {\n const authenticateError = response.headers.get('WWW-Authenticate');\n\n if (authenticateError) {\n const errorMatch = /error=\"([^\"]+)\"/.exec(authenticateError);\n const error = errorMatch ? errorMatch[1] : 'userinfo_failed';\n\n const errorDescMatch = /error_description=\"([^\"]+)\"/.exec(\n authenticateError\n );\n\n const errorDescription = errorDescMatch\n ? errorDescMatch[1]\n : 'Userinfo authentication error';\n\n throw new MonoCloudOPError(error, errorDescription);\n }\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while fetching userinfo. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<UserinfoResponse>(response);\n }\n\n /**\n * Generates OpenID end session url for signing out.\n *\n * Note - The `state` is added only when `postLogoutRedirectUri` is present.\n *\n * @param params - Parameters to build end session url\n *\n * @returns Tenant's end session url\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async endSessionUrl(params: EndSessionParameters): Promise<string> {\n const queryParams = new URLSearchParams();\n\n queryParams.set('client_id', this.clientId);\n\n if (params.idToken) {\n queryParams.set('id_token_hint', params.idToken);\n }\n\n if (params.postLogoutRedirectUri) {\n queryParams.set('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\n if (params.state) {\n queryParams.set('state', params.state);\n }\n }\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'end_session_endpoint');\n\n return `${metadata.end_session_endpoint}?${queryParams.toString()}`;\n }\n\n /**\n * Exchanges an authorization code for tokens.\n *\n * @param code - The authorization code received from the authorization server.\n * @param redirectUri - The redirect URI used in the initial authorization request.\n * @param codeVerifier - Code verifier for PKCE.\n * @param resource - Space-separated list of resources the access token should be scoped to\n *\n * @returns Tokens obtained by exchanging an authorization code at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async exchangeAuthorizationCode(\n code: string,\n redirectUri: string,\n codeVerifier?: string,\n resource?: string\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'authorization_code');\n body.set('code', code);\n body.set('redirect_uri', redirectUri);\n\n if (codeVerifier) {\n body.set('code_verifier', codeVerifier);\n }\n\n const resources = parseSpaceSeparated(resource) ?? [];\n\n if (resources.length > 0) {\n for (const r of resources) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'code_grant_failed',\n standardBodyError.error_description ?? 'Authorization code grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Exchanges a refresh token for new tokens.\n *\n * @param refreshToken - The refresh token used to request new tokens.\n * @param options - Refresh grant options.\n *\n * @returns Tokens obtained by exchanging a refresh token at the token endpoint.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshGrant(\n refreshToken: string,\n options?: RefreshGrantOptions\n ): Promise<Tokens> {\n const body = new URLSearchParams();\n\n body.set('grant_type', 'refresh_token');\n body.set('refresh_token', refreshToken);\n\n const scopes = parseSpaceSeparated(options?.scopes) ?? [];\n\n if (scopes.length > 0) {\n body.set('scope', scopes.join(' '));\n }\n\n const resource = parseSpaceSeparated(options?.resource) ?? [];\n\n if (resource.length > 0) {\n for (const r of resource) {\n body.append('resource', r);\n }\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'token_endpoint');\n\n const response = await innerFetch(metadata.token_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'refresh_grant_failed',\n standardBodyError.error_description ?? 'Refresh token grant failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing refresh token grant. Unexpected status code: ${response.status}`\n );\n }\n\n return await deserializeJson<Tokens>(response);\n }\n\n /**\n * Generates a session with user and tokens by exchanging authorization code from callback params.\n *\n * @param code - The authorization code received from the callback\n * @param redirectUri - The redirect URI that was used in the authorization request\n * @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.\n * This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.\n * @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.\n * Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.\n * @param options - Options for authenticating a user with authorization code\n *\n * @returns The user's session containing authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,\n * or if 'expires_in' or 'scope' is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async authenticate(\n code: string,\n redirectUri: string,\n requestedScopes: string,\n resource?: string,\n options?: AuthenticateOptions\n ): Promise<MonoCloudSession> {\n const tokens = await this.exchangeAuthorizationCode(\n code,\n redirectUri,\n options?.codeVerifier,\n resource\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0,\n options?.idTokenMaxAge,\n options?.idTokenNonce\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const session: MonoCloudSession = {\n user: {\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser,\n idToken: tokens.id_token,\n refreshToken: tokens.refresh_token,\n authorizedScopes: requestedScopes,\n accessTokens: [\n {\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes,\n },\n ],\n };\n\n await options?.onSessionCreating?.(session, idTokenClaims, userinfo);\n\n return session;\n }\n\n /**\n * Refetches user information for an existing session using the userinfo endpoint.\n * Updates the session's user object with the latest user information while preserving existing properties.\n *\n * @param accessToken - Access token used to fetch the userinfo\n * @param session - The current MonoCloudSession\n * @param options - Userinfo refetch options\n *\n * @returns Updated session with the latest userinfo\n *\n * @throws {@link MonoCloudValidationError} - When the token scope does not contain openid scope\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refetchUserInfo(\n accessToken: AccessToken,\n session: MonoCloudSession,\n options?: RefetchUserInfoOptions\n ): Promise<MonoCloudSession> {\n if (!accessToken.scopes?.includes('openid')) {\n throw new MonoCloudValidationError(\n 'Fetching userinfo requires the openid scope'\n );\n }\n\n const userinfo = await this.userinfo(accessToken.accessToken);\n\n // eslint-disable-next-line no-param-reassign\n session.user = { ...session.user, ...userinfo };\n\n await options?.onSessionCreating?.(session, undefined, userinfo);\n\n return session;\n }\n\n /**\n * Refreshes an existing session using the refresh token.\n * This function requests new tokens using the refresh token and optionally updates user information.\n *\n * @param session - The current MonoCloudSession containing the refresh token\n * @param options - Session refresh options\n *\n * @returns User's session containing refreshed authentication tokens and user information.\n *\n * @throws {@link MonoCloudValidationError} - If the refresh token is not present in the session,\n * or if 'expires_in' or 'scope' (including the openid scope) is missing from the token response.\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n *\n */\n async refreshSession(\n session: MonoCloudSession,\n options?: RefreshSessionOptions\n ): Promise<MonoCloudSession> {\n if (!session.refreshToken) {\n throw new MonoCloudValidationError(\n 'Session does not contain refresh token'\n );\n }\n\n const tokens = await this.refreshGrant(\n session.refreshToken,\n options?.refreshGrantOptions\n );\n\n const accessTokenExpiration =\n typeof tokens.expires_in === 'number'\n ? now() + tokens.expires_in\n : undefined;\n\n if (!accessTokenExpiration) {\n throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n }\n\n if (!tokens.scope) {\n throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n }\n\n let userinfo: MonoCloudUser | undefined;\n\n if (options?.fetchUserInfo && tokens.scope?.includes('openid')) {\n userinfo = await this.userinfo(tokens.access_token);\n }\n\n let idTokenClaims: Partial<IdTokenClaims> = {};\n\n if (tokens.id_token) {\n if (options?.validateIdToken ?? true) {\n const jwks = options?.jwks ?? (await this.getJwks());\n\n idTokenClaims = await this.validateIdToken(\n tokens.id_token,\n jwks.keys,\n options?.idTokenClockSkew ?? 0,\n options?.idTokenClockTolerance ?? 0\n );\n } else {\n idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n }\n }\n\n (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete idTokenClaims[x];\n });\n\n const resource = options?.refreshGrantOptions?.resource;\n let scopes = options?.refreshGrantOptions?.scopes;\n\n if (!resource && !scopes) {\n scopes = session.authorizedScopes;\n }\n\n const accessToken = findToken(session.accessTokens, resource, scopes);\n\n const user =\n Object.keys(idTokenClaims).length === 0 && !userinfo\n ? session.user\n : ({\n ...session.user,\n ...idTokenClaims,\n ...(userinfo ?? {}),\n } as MonoCloudUser);\n\n const newTokens =\n session.accessTokens?.filter(t => t !== accessToken) ?? [];\n\n newTokens.push({\n scopes: tokens.scope,\n accessToken: tokens.access_token,\n accessTokenExpiration,\n resource,\n requestedScopes: scopes,\n });\n\n const updatedSession: MonoCloudSession = {\n ...session,\n user,\n idToken: tokens.id_token ?? session.idToken,\n refreshToken: tokens.refresh_token ?? session.refreshToken,\n accessTokens: newTokens,\n };\n\n await options?.onSessionCreating?.(updatedSession, idTokenClaims, userinfo);\n\n return updatedSession;\n }\n\n /**\n * Revokes an access token or refresh token, rendering it invalid for future use.\n *\n * @param token - The token string to be revoked\n * @param tokenType - Hint about the token type ('access_token' or 'refresh_token')\n *\n * @returns If token revocation succeeded\n *\n * @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type\n *\n * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n * OAuth 2.0 error response.\n *\n * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n * unexpected status code during the request or a serialization error while processing the response.\n */\n async revokeToken(token: string, tokenType?: string): Promise<void> {\n if (!token.trim().length) {\n throw new MonoCloudValidationError('Invalid token');\n }\n\n if (\n tokenType &&\n tokenType !== 'access_token' &&\n tokenType !== 'refresh_token'\n ) {\n throw new MonoCloudValidationError(\n 'Only access_token and refresh_token types are supported.'\n );\n }\n\n const body = new URLSearchParams();\n body.set('token', token);\n if (tokenType) {\n body.set('token_type_hint', tokenType);\n }\n\n const headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n };\n\n await clientAuth(\n this.clientId,\n this.clientSecret,\n this.authMethod,\n this.tenantDomain,\n headers,\n body,\n JWT_ASSERTION_CLOCK_SKEW\n );\n\n const metadata = await this.getMetadata();\n\n assertMetadataProperty(metadata, 'revocation_endpoint');\n\n const response = await innerFetch(metadata.revocation_endpoint, {\n method: 'POST',\n body: body.toString(),\n headers,\n });\n\n if (response.status === 400) {\n const standardBodyError = await deserializeJson(response);\n\n throw new MonoCloudOPError(\n standardBodyError.error ?? 'revocation_failed',\n standardBodyError.error_description ?? 'Token revocation failed'\n );\n }\n\n if (response.status !== 200) {\n throw new MonoCloudHttpError(\n `Error while performing revocation request. Unexpected status code: ${response.status}`\n );\n }\n }\n\n /**\n * Validates an ID Token.\n *\n * @param idToken - The ID Token JWT string to validate\n * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature\n * @param clockSkew - Number of seconds to adjust the current time to account for clock differences\n * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation\n * @param maxAge - maximum authentication age in seconds\n * @param nonce - nonce value to validate against the token's nonce claim\n *\n * @returns Validated ID Token claims\n *\n * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n *\n */\n async validateIdToken(\n idToken: string,\n jwks: Jwk[],\n clockSkew: number,\n clockTolerance: number,\n maxAge?: number,\n nonce?: string\n ): Promise<IdTokenClaims> {\n if (typeof idToken !== 'string' || idToken.trim().length === 0) {\n throw new MonoCloudTokenError(\n 'ID Token must be a valid non-empty string'\n );\n }\n\n const {\n 0: protectedHeader,\n 1: payload,\n 2: encodedSignature,\n length,\n } = idToken.split('.');\n\n if (length !== 3) {\n throw new MonoCloudTokenError(\n 'ID Token must have a header, payload and signature'\n );\n }\n\n let header: JwsHeaderParameters;\n try {\n header = JSON.parse(decodeBase64Url(protectedHeader));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Header');\n }\n\n if (\n header === null ||\n typeof header !== 'object' ||\n Array.isArray(header)\n ) {\n throw new MonoCloudTokenError('JWT Header must be a top level object');\n }\n\n if (this.idTokenSigningAlgorithm !== header.alg) {\n throw new MonoCloudTokenError('Invalid signing alg');\n }\n\n if (header.crit !== undefined) {\n throw new MonoCloudTokenError('Unexpected JWT \"crit\" header parameter');\n }\n\n const binary = decodeBase64Url(encodedSignature);\n\n const signature = new Uint8Array(binary.length);\n\n for (let i = 0; i < binary.length; i++) {\n signature[i] = binary.charCodeAt(i);\n }\n\n const key = await getPublicSigKeyFromIssuerJwks(jwks, header);\n\n const input = `${protectedHeader}.${payload}`;\n\n const verified = await crypto.subtle.verify(\n keyToSubtle(key),\n key,\n signature,\n stringToArrayBuffer(input) as BufferSource\n );\n\n if (!verified) {\n throw new MonoCloudTokenError('JWT signature verification failed');\n }\n\n let claims: IdTokenClaims;\n\n try {\n claims = JSON.parse(decodeBase64Url(payload));\n } catch {\n throw new MonoCloudTokenError('Failed to parse JWT Payload');\n }\n\n if (\n claims === null ||\n typeof claims !== 'object' ||\n Array.isArray(claims)\n ) {\n throw new MonoCloudTokenError('JWT Payload must be a top level object');\n }\n\n if ((claims.nonce || nonce) && claims.nonce !== nonce) {\n throw new MonoCloudTokenError('Nonce mismatch');\n }\n\n const current = now() + clockSkew;\n\n /* v8 ignore else -- @preserve */\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim type'\n );\n }\n\n if (claims.exp <= current - clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"exp\" (expiration time) claim value, timestamp is <= now()'\n );\n }\n }\n\n /* v8 ignore else -- @preserve */\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"iat\" (issued at) claim type'\n );\n }\n }\n\n if (\n typeof claims.auth_time === 'number' &&\n typeof maxAge === 'number' &&\n claims.auth_time + maxAge < current\n ) {\n throw new MonoCloudTokenError(\n 'Too much time has elapsed since the last End-User authentication'\n );\n }\n\n if (claims.iss !== this.tenantDomain) {\n throw new MonoCloudTokenError('Invalid Issuer');\n }\n\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim type'\n );\n }\n\n if (claims.nbf > current + clockTolerance) {\n throw new MonoCloudTokenError(\n 'Unexpected JWT \"nbf\" (not before) claim value, timestamp is > now()'\n );\n }\n }\n\n const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n\n if (!audience.includes(this.clientId)) {\n throw new MonoCloudTokenError('Invalid audience claim');\n }\n\n return claims;\n }\n\n /**\n * Decodes the payload of a JSON Web Token (JWT) and returns it as an object.\n * **THIS METHOD DOES NOT VERIFY JWT TOKENS**.\n *\n * @param jwt - JWT to decode\n *\n * @returns Decoded payload\n *\n * @throws {@link MonoCloudTokenError} - If decoding fails\n *\n */\n static decodeJwt(jwt: string): IdTokenClaims {\n try {\n const [, payload] = jwt.split('.');\n\n if (!payload?.trim()) {\n throw new MonoCloudTokenError('JWT does not contain payload');\n }\n\n const decoded = decodeBase64Url(payload);\n\n if (!decoded.startsWith('{')) {\n throw new MonoCloudTokenError('Payload is not an object');\n }\n\n return JSON.parse(decoded) as IdTokenClaims;\n } catch (e) {\n if (e instanceof MonoCloudAuthBaseError) {\n throw e;\n }\n\n throw new MonoCloudTokenError(\n 'Could not parse payload. Malformed payload'\n );\n }\n }\n}\n"],"mappings":";;;AAAA,IAAa,yBAAb,cAA4C,MAAM;;;;ACElD,IAAa,mBAAb,cAAsC,uBAAuB;CAK3D,YAAY,OAAe,kBAA2B;AACpD,QAAM,MAAM;AACZ,OAAK,QAAQ;AACb,OAAK,mBAAmB;;;;;;ACR5B,IAAa,qBAAb,cAAwC,uBAAuB;;;;ACA/D,IAAa,sBAAb,cAAyC,uBAAuB;;;;ACAhE,IAAa,2BAAb,cAA8C,uBAAuB;;;;ACKrE,MAAM,eACJ,QACiE;AACjE,SAAQ,KAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAQ,MAAM,OAAO,IAAI,MAAM,GAAG;GAAI;EACvD,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;GAAE,MAAM;GAAW,MAAM,OAAO,IAAI,MAAM,GAAG;GAAI;EAC1D,KAAK;EACL,KAAK;EACL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AI,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,UAAU,gBAAgB,QAAQ;AAExC,OAAI,CAAC,QAAQ,WAAW,IAAI,CAC1B,OAAM,IAAI,oBAAoB,2BAA2B;AAG3D,UAAO,KAAK,MAAM,QAAQ;WACnB,GAAG;AACV,OAAI,aAAa,uBACf,OAAM;AAGR,SAAM,IAAI,oBACR,6CACD"}
@@ -478,4 +478,4 @@ idToken?: Partial<IdTokenClaims>,
478
478
  userInfo?: UserinfoResponse) => Promise<void> | void;
479
479
  //#endregion
480
480
  export { ResponseTypes as A, ParResponse as C, RefreshGrantOptions as D, RefetchUserInfoOptions as E, UserinfoResponse as M, RefreshSessionOptions as O, OnSessionCreating as S, PushedAuthorizationParams as T, Jwks as _, Authenticators as a, MonoCloudSession as b, ClientAuthMethod as c, EndSessionParameters as d, Group as f, Jwk as g, JWSAlgorithm as h, AuthenticateOptions as i, Tokens as j, ResponseModes as k, CodeChallengeMethod as l, IssuerMetadata as m, Address as n, AuthorizationParams as o, IdTokenClaims as p, AuthState as r, CallbackParams as s, AccessToken as t, DisplayOptions as u, JwsHeaderParameters as v, Prompt as w, MonoCloudUser as x, MonoCloudClientOptions as y };
481
- //# sourceMappingURL=types-CnxqWHwA.d.cts.map
481
+ //# sourceMappingURL=types-BAE9nCpJ.d.cts.map
@@ -478,4 +478,4 @@ idToken?: Partial<IdTokenClaims>,
478
478
  userInfo?: UserinfoResponse) => Promise<void> | void;
479
479
  //#endregion
480
480
  export { ResponseTypes as A, ParResponse as C, RefreshGrantOptions as D, RefetchUserInfoOptions as E, UserinfoResponse as M, RefreshSessionOptions as O, OnSessionCreating as S, PushedAuthorizationParams as T, Jwks as _, Authenticators as a, MonoCloudSession as b, ClientAuthMethod as c, EndSessionParameters as d, Group as f, Jwk as g, JWSAlgorithm as h, AuthenticateOptions as i, Tokens as j, ResponseModes as k, CodeChallengeMethod as l, IssuerMetadata as m, Address as n, AuthorizationParams as o, IdTokenClaims as p, AuthState as r, CallbackParams as s, AccessToken as t, DisplayOptions as u, JwsHeaderParameters as v, Prompt as w, MonoCloudUser as x, MonoCloudClientOptions as y };
481
- //# sourceMappingURL=types-DwJl9ZUf.d.mts.map
481
+ //# sourceMappingURL=types-D3lVLgLQ.d.mts.map
@@ -1,11 +1,12 @@
1
- const require_internal = require('../internal-DytuO03E.cjs');
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_utils_internal = require('./internal.cjs');
2
3
 
3
4
  //#region src/utils/index.ts
4
5
  const PBKDF2_ITERATIONS = 31e4;
5
6
  const SALT_LENGTH = 16;
6
7
  const GCM_IV_LENGTH = 12;
7
8
  const deriveEncryptionKey = async (secret, salt) => {
8
- const baseKey = await crypto.subtle.importKey("raw", require_internal.stringToArrayBuffer(secret), "PBKDF2", false, ["deriveKey"]);
9
+ const baseKey = await crypto.subtle.importKey("raw", require_utils_internal.stringToArrayBuffer(secret), "PBKDF2", false, ["deriveKey"]);
9
10
  return crypto.subtle.deriveKey({
10
11
  name: "PBKDF2",
11
12
  salt,
@@ -52,7 +53,7 @@ const parseCallbackParams = (queryOrUrl) => {
52
53
  const encrypt = async (data, secret) => {
53
54
  const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
54
55
  const iv = crypto.getRandomValues(new Uint8Array(GCM_IV_LENGTH));
55
- const plaintextBuffer = require_internal.stringToArrayBuffer(data);
56
+ const plaintextBuffer = require_utils_internal.stringToArrayBuffer(data);
56
57
  const key = await deriveEncryptionKey(secret, salt);
57
58
  const ciphertext = await crypto.subtle.encrypt({
58
59
  name: "AES-GCM",
@@ -62,7 +63,7 @@ const encrypt = async (data, secret) => {
62
63
  resultBuffer.set(salt, 0);
63
64
  resultBuffer.set(iv, salt.byteLength);
64
65
  resultBuffer.set(new Uint8Array(ciphertext), salt.byteLength + iv.byteLength);
65
- return require_internal.arrayBufferToBase64(resultBuffer);
66
+ return require_utils_internal.arrayBufferToBase64(resultBuffer);
66
67
  };
67
68
  /**
68
69
  * Decrypts an encrypted string using a secret with AES-GCM.
@@ -74,13 +75,13 @@ const encrypt = async (data, secret) => {
74
75
  */
75
76
  const decrypt = async (encrypted, secret) => {
76
77
  try {
77
- const ciphertextBuffer = Uint8Array.from(atob(require_internal.fromB64Url(encrypted)), (c) => c.charCodeAt(0));
78
+ const ciphertextBuffer = Uint8Array.from(atob(require_utils_internal.fromB64Url(encrypted)), (c) => c.charCodeAt(0));
78
79
  if (ciphertextBuffer.byteLength <= SALT_LENGTH + GCM_IV_LENGTH) return;
79
80
  const salt = ciphertextBuffer.slice(0, SALT_LENGTH);
80
81
  const iv = ciphertextBuffer.slice(SALT_LENGTH, SALT_LENGTH + GCM_IV_LENGTH);
81
82
  const encryptedPayload = ciphertextBuffer.slice(SALT_LENGTH + GCM_IV_LENGTH);
82
83
  const key = await deriveEncryptionKey(secret, salt);
83
- return require_internal.arrayBufferToString(await crypto.subtle.decrypt({
84
+ return require_utils_internal.arrayBufferToString(await crypto.subtle.decrypt({
84
85
  name: "AES-GCM",
85
86
  iv
86
87
  }, key, encryptedPayload));
@@ -98,7 +99,7 @@ const decrypt = async (encrypted, secret) => {
98
99
  */
99
100
  const encryptSession = (session, secret, ttl) => {
100
101
  let expiresAt;
101
- if (typeof ttl === "number") expiresAt = require_internal.now() + ttl;
102
+ if (typeof ttl === "number") expiresAt = require_utils_internal.now() + ttl;
102
103
  return encrypt(JSON.stringify({
103
104
  session,
104
105
  expiresAt
@@ -125,7 +126,7 @@ const decryptSession = async (encryptedSession, secret) => {
125
126
  }
126
127
  const { session, expiresAt } = payload;
127
128
  if (!session) throw new Error("Invalid session data");
128
- if (typeof expiresAt === "number" && expiresAt < require_internal.now()) throw new Error("Session Expired");
129
+ if (typeof expiresAt === "number" && expiresAt < require_utils_internal.now()) throw new Error("Session Expired");
129
130
  return session;
130
131
  };
131
132
  /**
@@ -139,7 +140,7 @@ const decryptSession = async (encryptedSession, secret) => {
139
140
  */
140
141
  const encryptAuthState = (authState, secret, ttl) => {
141
142
  let expiresAt;
142
- if (typeof ttl === "number") expiresAt = require_internal.now() + ttl;
143
+ if (typeof ttl === "number") expiresAt = require_utils_internal.now() + ttl;
143
144
  return encrypt(JSON.stringify({
144
145
  authState,
145
146
  expiresAt
@@ -167,7 +168,7 @@ const decryptAuthState = async (encryptedAuthState, secret) => {
167
168
  }
168
169
  const { authState, expiresAt } = payload;
169
170
  if (!authState) throw new Error("Invalid auth state");
170
- if (typeof expiresAt === "number" && expiresAt < require_internal.now()) throw new Error("Auth state expired");
171
+ if (typeof expiresAt === "number" && expiresAt < require_utils_internal.now()) throw new Error("Auth state expired");
171
172
  return authState;
172
173
  };
173
174
  /**
@@ -196,22 +197,22 @@ const isUserInGroup = (user, groups, groupsClaim = "groups", matchAll = false) =
196
197
  /**
197
198
  * Generates a random state string.
198
199
  */
199
- const generateState = () => require_internal.randomBytes(32);
200
+ const generateState = () => require_utils_internal.randomBytes(32);
200
201
  /**
201
202
  * Generates a PKCE (Proof Key for Code Exchange) code verifier and code challenge.
202
203
  *
203
204
  */
204
205
  const generatePKCE = async () => {
205
- const codeVerifier = require_internal.randomBytes(32);
206
+ const codeVerifier = require_utils_internal.randomBytes(32);
206
207
  return {
207
208
  codeVerifier,
208
- codeChallenge: require_internal.encodeBase64Url(await crypto.subtle.digest("SHA-256", require_internal.stringToArrayBuffer(codeVerifier)))
209
+ codeChallenge: require_utils_internal.encodeBase64Url(await crypto.subtle.digest("SHA-256", require_utils_internal.stringToArrayBuffer(codeVerifier)))
209
210
  };
210
211
  };
211
212
  /**
212
213
  * Generates a random nonce string.
213
214
  */
214
- const generateNonce = () => require_internal.randomBytes(32);
215
+ const generateNonce = () => require_utils_internal.randomBytes(32);
215
216
  /**
216
217
  * @ignore
217
218
  * Merges multiple arrays of strings, removing duplicates.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["stringToArrayBuffer","arrayBufferToBase64","fromB64Url","arrayBufferToString","now","payload: { session: MonoCloudSession; expiresAt?: number }","payload: { authState: T; expiresAt?: number }","randomBytes","encodeBase64Url"],"sources":["../../src/utils/index.ts"],"sourcesContent":["import type {\n AuthState,\n CallbackParams,\n IdTokenClaims,\n MonoCloudSession,\n MonoCloudUser,\n} from '../types';\nimport {\n arrayBufferToBase64,\n arrayBufferToString,\n encodeBase64Url,\n fromB64Url,\n now,\n randomBytes,\n stringToArrayBuffer,\n} from './internal';\n\nconst PBKDF2_ITERATIONS = 310_000;\nconst SALT_LENGTH = 16;\nconst GCM_IV_LENGTH = 12;\n\nconst deriveEncryptionKey = async (\n secret: string,\n salt: Uint8Array\n): Promise<CryptoKey> => {\n const baseKey = await crypto.subtle.importKey(\n 'raw',\n stringToArrayBuffer(secret) as BufferSource,\n 'PBKDF2',\n false,\n ['deriveKey']\n );\n\n return crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt as BufferSource,\n iterations: PBKDF2_ITERATIONS,\n hash: 'SHA-256',\n },\n baseKey,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt']\n );\n};\n\n/**\n * Parses callback parameters from a URL, a URLSearchParams object, or a query string.\n */\nexport const parseCallbackParams = (\n queryOrUrl: string | URL | URLSearchParams\n): CallbackParams => {\n let params;\n\n if (queryOrUrl instanceof URL) {\n params = queryOrUrl.searchParams;\n } else if (queryOrUrl instanceof URLSearchParams) {\n params = queryOrUrl;\n } else {\n try {\n params = new URL(queryOrUrl).searchParams;\n } catch {\n // eslint-disable-next-line no-param-reassign\n queryOrUrl =\n queryOrUrl.startsWith('?') || queryOrUrl.startsWith('#')\n ? queryOrUrl.substring(1)\n : queryOrUrl;\n params = new URLSearchParams(queryOrUrl);\n }\n }\n\n const expiresIn = params.get('expires_in');\n\n return {\n state: params.get('state') ?? undefined,\n accessToken: params.get('access_token') ?? undefined,\n idToken: params.get('id_token') ?? undefined,\n refreshToken: params.get('refresh_token') ?? undefined,\n sessionState: params.get('session_state') ?? undefined,\n expiresIn: expiresIn ? parseInt(expiresIn, 10) : undefined,\n code: params.get('code') ?? undefined,\n error: params.get('error') ?? undefined,\n errorDescription: params.get('error_description') ?? undefined,\n };\n};\n\n/**\n * Encrypts a given string using a secret with AES-GCM.\n *\n * @param data - The plaintext data to encrypt.\n * @param secret - The secret used to derive the encryption key.\n * @returns Base64-encoded ciphertext.\n */\nexport const encrypt = async (\n data: string,\n secret: string\n): Promise<string> => {\n const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));\n const iv = crypto.getRandomValues(new Uint8Array(GCM_IV_LENGTH));\n const plaintextBuffer = stringToArrayBuffer(data);\n const key = await deriveEncryptionKey(secret, salt);\n\n const ciphertext = await crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv,\n },\n key,\n plaintextBuffer as BufferSource\n );\n\n const resultBuffer = new Uint8Array(\n salt.byteLength + iv.byteLength + ciphertext.byteLength\n );\n resultBuffer.set(salt, 0);\n resultBuffer.set(iv, salt.byteLength);\n resultBuffer.set(new Uint8Array(ciphertext), salt.byteLength + iv.byteLength);\n\n return arrayBufferToBase64(resultBuffer);\n};\n\n/**\n * Decrypts an encrypted string using a secret with AES-GCM.\n *\n * @param encrypted - The ciphertext to decrypt.\n * @param secret - The secret used to derive the decryption key.\n *\n * @returns Decrypted plaintext string or undefined if decryption fails.\n */\nexport const decrypt = async (\n encrypted: string,\n secret: string\n): Promise<string | undefined> => {\n try {\n const ciphertextBuffer = Uint8Array.from(atob(fromB64Url(encrypted)), c =>\n c.charCodeAt(0)\n );\n\n if (ciphertextBuffer.byteLength <= SALT_LENGTH + GCM_IV_LENGTH) {\n return undefined;\n }\n\n const salt = ciphertextBuffer.slice(0, SALT_LENGTH);\n const iv = ciphertextBuffer.slice(SALT_LENGTH, SALT_LENGTH + GCM_IV_LENGTH);\n const encryptedPayload = ciphertextBuffer.slice(\n SALT_LENGTH + GCM_IV_LENGTH\n );\n const key = await deriveEncryptionKey(secret, salt);\n const decryptedBuffer = await crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv,\n },\n key,\n encryptedPayload\n );\n return arrayBufferToString(decryptedBuffer);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Encrypts a MonoCloud session object with a secret and optional time-to-live (TTL).\n *\n * @param session - The session object to encrypt.\n * @param secret - The secret used for encryption.\n * @param ttl - Optional time-to-live in seconds, after which the session expires.\n * @returns Encrypted session string.\n */\nexport const encryptSession = (\n session: MonoCloudSession,\n secret: string,\n ttl?: number\n): Promise<string> => {\n let expiresAt;\n\n if (typeof ttl === 'number') {\n expiresAt = now() + ttl;\n }\n return encrypt(JSON.stringify({ session, expiresAt }), secret);\n};\n\n/**\n * Decrypts an encrypted MonoCloud session.\n *\n * @param encryptedSession - The encrypted session string to decrypt.\n * @param secret - The secret used for decryption.\n *\n * @returns Session object on success.\n *\n * @throws If decryption fails or the session has expired\n */\nexport const decryptSession = async (\n encryptedSession: string,\n secret: string\n): Promise<MonoCloudSession> => {\n const decryptedText = await decrypt(encryptedSession, secret);\n\n if (!decryptedText) {\n throw new Error('Invalid session data');\n }\n\n let payload: { session: MonoCloudSession; expiresAt?: number };\n try {\n payload = JSON.parse(decryptedText);\n } catch {\n throw new Error('Invalid session data');\n }\n\n const { session, expiresAt } = payload;\n\n if (!session) {\n throw new Error('Invalid session data');\n }\n\n if (typeof expiresAt === 'number' && expiresAt < now()) {\n throw new Error('Session Expired');\n }\n\n return session;\n};\n\n/**\n * Encrypts an AuthState object with a secret and optional time-to-live (TTL).\n *\n * @param authState - A type that extends the AuthState interface.\n * @param secret - The secret used for encryption.\n * @param ttl - Optional time-to-live in seconds, after which the auth state expires.\n *\n * @returns Encrypted auth state string.\n */\nexport const encryptAuthState = <T extends AuthState>(\n authState: T,\n secret: string,\n ttl?: number\n): Promise<string> => {\n let expiresAt;\n\n if (typeof ttl === 'number') {\n expiresAt = now() + ttl;\n }\n\n return encrypt(JSON.stringify({ authState, expiresAt }), secret);\n};\n\n/**\n * Decrypts an encrypted AuthState.\n *\n * @param encryptedAuthState - The encrypted auth state string to decrypt.\n * @param secret - The secret used for decryption.\n *\n * @returns State object on success\n *\n * @throws If decryption fails or the auth state has expired\n *\n */\nexport const decryptAuthState = async <T extends AuthState>(\n encryptedAuthState: string,\n secret: string\n): Promise<T> => {\n const decryptedText = await decrypt(encryptedAuthState, secret);\n\n if (!decryptedText) {\n throw new Error('Invalid auth state');\n }\n\n let payload: { authState: T; expiresAt?: number };\n try {\n payload = JSON.parse(decryptedText);\n } catch {\n throw new Error('Invalid auth state');\n }\n\n const { authState, expiresAt } = payload;\n\n if (!authState) {\n throw new Error('Invalid auth state');\n }\n\n if (typeof expiresAt === 'number' && expiresAt < now()) {\n throw new Error('Auth state expired');\n }\n\n return authState;\n};\n\n/**\n * Checks if a user is a member of a specified group or groups.\n *\n * @param user - The user.\n * @param groups - An array of group names or IDs to check membership against.\n * @param groupsClaim - The claim in the user object that contains groups.\n * @param matchAll - If `true`, requires the user to be in all specified groups; if `false`, checks if the user is in at least one of the groups.\n *\n * @returns `true` if the user is in the specified groups, `false` otherwise.\n */\nexport const isUserInGroup = (\n user: MonoCloudUser | IdTokenClaims,\n groups: string[],\n groupsClaim = 'groups',\n matchAll = false\n): boolean => {\n const userGroups = (user[groupsClaim] ?? []) as (\n | string\n | { id: string; name: string }\n )[];\n\n if (!Array.isArray(groups) || groups.length === 0) {\n return true;\n }\n\n if (!Array.isArray(userGroups) || userGroups.length === 0) {\n return false;\n }\n\n let matched = false;\n\n for (const expectedGroup of groups) {\n const userInGroup = userGroups.some(\n g =>\n (typeof g === 'string' && g === expectedGroup) ||\n (typeof g === 'object' &&\n (g.id === expectedGroup || g.name === expectedGroup))\n );\n\n if (!matchAll && userInGroup) {\n return userInGroup;\n }\n\n if (matchAll && !userInGroup) {\n return false;\n }\n\n matched = userInGroup;\n }\n\n return matched;\n};\n\n/**\n * Generates a random state string.\n */\nexport const generateState = (): string => randomBytes(32);\n\n/**\n * Generates a PKCE (Proof Key for Code Exchange) code verifier and code challenge.\n *\n */\nexport const generatePKCE = async (): Promise<{\n codeVerifier: string;\n codeChallenge: string;\n}> => {\n const codeVerifier = randomBytes(32);\n return {\n codeVerifier,\n codeChallenge: encodeBase64Url(\n await crypto.subtle.digest(\n 'SHA-256',\n stringToArrayBuffer(codeVerifier) as BufferSource\n )\n ),\n };\n};\n\n/**\n * Generates a random nonce string.\n */\nexport const generateNonce = (): string => randomBytes(32);\n\n/**\n * @ignore\n * Merges multiple arrays of strings, removing duplicates.\n *\n * @param args - List of arrays to merge\n *\n * @returns A new array containing unique strings from both input arrays, or `undefined` if both inputs are `undefined`.\n */\nexport const mergeArrays = (\n ...args: (string[] | undefined)[]\n): string[] | undefined => {\n const arrays = args.filter(x => Array.isArray(x));\n return arrays.length > 0\n ? Array.from(new Set(arrays.reduce((acc, x) => [...acc, ...x], [])))\n : undefined;\n};\n"],"mappings":";;;AAiBA,MAAM,oBAAoB;AAC1B,MAAM,cAAc;AACpB,MAAM,gBAAgB;AAEtB,MAAM,sBAAsB,OAC1B,QACA,SACuB;CACvB,MAAM,UAAU,MAAM,OAAO,OAAO,UAClC,OACAA,qCAAoB,OAAO,EAC3B,UACA,OACA,CAAC,YAAY,CACd;AAED,QAAO,OAAO,OAAO,UACnB;EACE,MAAM;EACA;EACN,YAAY;EACZ,MAAM;EACP,EACD,SACA;EAAE,MAAM;EAAW,QAAQ;EAAK,EAChC,OACA,CAAC,WAAW,UAAU,CACvB;;;;;AAMH,MAAa,uBACX,eACmB;CACnB,IAAI;AAEJ,KAAI,sBAAsB,IACxB,UAAS,WAAW;UACX,sBAAsB,gBAC/B,UAAS;KAET,KAAI;AACF,WAAS,IAAI,IAAI,WAAW,CAA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AK,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,GAClE"}
1
+ {"version":3,"file":"index.cjs","names":["stringToArrayBuffer","arrayBufferToBase64","fromB64Url","arrayBufferToString","now","randomBytes","encodeBase64Url"],"sources":["../../src/utils/index.ts"],"sourcesContent":["import type {\n AuthState,\n CallbackParams,\n IdTokenClaims,\n MonoCloudSession,\n MonoCloudUser,\n} from '../types';\nimport {\n arrayBufferToBase64,\n arrayBufferToString,\n encodeBase64Url,\n fromB64Url,\n now,\n randomBytes,\n stringToArrayBuffer,\n} from './internal';\n\nconst PBKDF2_ITERATIONS = 310_000;\nconst SALT_LENGTH = 16;\nconst GCM_IV_LENGTH = 12;\n\nconst deriveEncryptionKey = async (\n secret: string,\n salt: Uint8Array\n): Promise<CryptoKey> => {\n const baseKey = await crypto.subtle.importKey(\n 'raw',\n stringToArrayBuffer(secret) as BufferSource,\n 'PBKDF2',\n false,\n ['deriveKey']\n );\n\n return crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt as BufferSource,\n iterations: PBKDF2_ITERATIONS,\n hash: 'SHA-256',\n },\n baseKey,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt']\n );\n};\n\n/**\n * Parses callback parameters from a URL, a URLSearchParams object, or a query string.\n */\nexport const parseCallbackParams = (\n queryOrUrl: string | URL | URLSearchParams\n): CallbackParams => {\n let params;\n\n if (queryOrUrl instanceof URL) {\n params = queryOrUrl.searchParams;\n } else if (queryOrUrl instanceof URLSearchParams) {\n params = queryOrUrl;\n } else {\n try {\n params = new URL(queryOrUrl).searchParams;\n } catch {\n // eslint-disable-next-line no-param-reassign\n queryOrUrl =\n queryOrUrl.startsWith('?') || queryOrUrl.startsWith('#')\n ? queryOrUrl.substring(1)\n : queryOrUrl;\n params = new URLSearchParams(queryOrUrl);\n }\n }\n\n const expiresIn = params.get('expires_in');\n\n return {\n state: params.get('state') ?? undefined,\n accessToken: params.get('access_token') ?? undefined,\n idToken: params.get('id_token') ?? undefined,\n refreshToken: params.get('refresh_token') ?? undefined,\n sessionState: params.get('session_state') ?? undefined,\n expiresIn: expiresIn ? parseInt(expiresIn, 10) : undefined,\n code: params.get('code') ?? undefined,\n error: params.get('error') ?? undefined,\n errorDescription: params.get('error_description') ?? undefined,\n };\n};\n\n/**\n * Encrypts a given string using a secret with AES-GCM.\n *\n * @param data - The plaintext data to encrypt.\n * @param secret - The secret used to derive the encryption key.\n * @returns Base64-encoded ciphertext.\n */\nexport const encrypt = async (\n data: string,\n secret: string\n): Promise<string> => {\n const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));\n const iv = crypto.getRandomValues(new Uint8Array(GCM_IV_LENGTH));\n const plaintextBuffer = stringToArrayBuffer(data);\n const key = await deriveEncryptionKey(secret, salt);\n\n const ciphertext = await crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv,\n },\n key,\n plaintextBuffer as BufferSource\n );\n\n const resultBuffer = new Uint8Array(\n salt.byteLength + iv.byteLength + ciphertext.byteLength\n );\n resultBuffer.set(salt, 0);\n resultBuffer.set(iv, salt.byteLength);\n resultBuffer.set(new Uint8Array(ciphertext), salt.byteLength + iv.byteLength);\n\n return arrayBufferToBase64(resultBuffer);\n};\n\n/**\n * Decrypts an encrypted string using a secret with AES-GCM.\n *\n * @param encrypted - The ciphertext to decrypt.\n * @param secret - The secret used to derive the decryption key.\n *\n * @returns Decrypted plaintext string or undefined if decryption fails.\n */\nexport const decrypt = async (\n encrypted: string,\n secret: string\n): Promise<string | undefined> => {\n try {\n const ciphertextBuffer = Uint8Array.from(atob(fromB64Url(encrypted)), c =>\n c.charCodeAt(0)\n );\n\n if (ciphertextBuffer.byteLength <= SALT_LENGTH + GCM_IV_LENGTH) {\n return undefined;\n }\n\n const salt = ciphertextBuffer.slice(0, SALT_LENGTH);\n const iv = ciphertextBuffer.slice(SALT_LENGTH, SALT_LENGTH + GCM_IV_LENGTH);\n const encryptedPayload = ciphertextBuffer.slice(\n SALT_LENGTH + GCM_IV_LENGTH\n );\n const key = await deriveEncryptionKey(secret, salt);\n const decryptedBuffer = await crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv,\n },\n key,\n encryptedPayload\n );\n return arrayBufferToString(decryptedBuffer);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Encrypts a MonoCloud session object with a secret and optional time-to-live (TTL).\n *\n * @param session - The session object to encrypt.\n * @param secret - The secret used for encryption.\n * @param ttl - Optional time-to-live in seconds, after which the session expires.\n * @returns Encrypted session string.\n */\nexport const encryptSession = (\n session: MonoCloudSession,\n secret: string,\n ttl?: number\n): Promise<string> => {\n let expiresAt;\n\n if (typeof ttl === 'number') {\n expiresAt = now() + ttl;\n }\n return encrypt(JSON.stringify({ session, expiresAt }), secret);\n};\n\n/**\n * Decrypts an encrypted MonoCloud session.\n *\n * @param encryptedSession - The encrypted session string to decrypt.\n * @param secret - The secret used for decryption.\n *\n * @returns Session object on success.\n *\n * @throws If decryption fails or the session has expired\n */\nexport const decryptSession = async (\n encryptedSession: string,\n secret: string\n): Promise<MonoCloudSession> => {\n const decryptedText = await decrypt(encryptedSession, secret);\n\n if (!decryptedText) {\n throw new Error('Invalid session data');\n }\n\n let payload: { session: MonoCloudSession; expiresAt?: number };\n try {\n payload = JSON.parse(decryptedText);\n } catch {\n throw new Error('Invalid session data');\n }\n\n const { session, expiresAt } = payload;\n\n if (!session) {\n throw new Error('Invalid session data');\n }\n\n if (typeof expiresAt === 'number' && expiresAt < now()) {\n throw new Error('Session Expired');\n }\n\n return session;\n};\n\n/**\n * Encrypts an AuthState object with a secret and optional time-to-live (TTL).\n *\n * @param authState - A type that extends the AuthState interface.\n * @param secret - The secret used for encryption.\n * @param ttl - Optional time-to-live in seconds, after which the auth state expires.\n *\n * @returns Encrypted auth state string.\n */\nexport const encryptAuthState = <T extends AuthState>(\n authState: T,\n secret: string,\n ttl?: number\n): Promise<string> => {\n let expiresAt;\n\n if (typeof ttl === 'number') {\n expiresAt = now() + ttl;\n }\n\n return encrypt(JSON.stringify({ authState, expiresAt }), secret);\n};\n\n/**\n * Decrypts an encrypted AuthState.\n *\n * @param encryptedAuthState - The encrypted auth state string to decrypt.\n * @param secret - The secret used for decryption.\n *\n * @returns State object on success\n *\n * @throws If decryption fails or the auth state has expired\n *\n */\nexport const decryptAuthState = async <T extends AuthState>(\n encryptedAuthState: string,\n secret: string\n): Promise<T> => {\n const decryptedText = await decrypt(encryptedAuthState, secret);\n\n if (!decryptedText) {\n throw new Error('Invalid auth state');\n }\n\n let payload: { authState: T; expiresAt?: number };\n try {\n payload = JSON.parse(decryptedText);\n } catch {\n throw new Error('Invalid auth state');\n }\n\n const { authState, expiresAt } = payload;\n\n if (!authState) {\n throw new Error('Invalid auth state');\n }\n\n if (typeof expiresAt === 'number' && expiresAt < now()) {\n throw new Error('Auth state expired');\n }\n\n return authState;\n};\n\n/**\n * Checks if a user is a member of a specified group or groups.\n *\n * @param user - The user.\n * @param groups - An array of group names or IDs to check membership against.\n * @param groupsClaim - The claim in the user object that contains groups.\n * @param matchAll - If `true`, requires the user to be in all specified groups; if `false`, checks if the user is in at least one of the groups.\n *\n * @returns `true` if the user is in the specified groups, `false` otherwise.\n */\nexport const isUserInGroup = (\n user: MonoCloudUser | IdTokenClaims,\n groups: string[],\n groupsClaim = 'groups',\n matchAll = false\n): boolean => {\n const userGroups = (user[groupsClaim] ?? []) as (\n | string\n | { id: string; name: string }\n )[];\n\n if (!Array.isArray(groups) || groups.length === 0) {\n return true;\n }\n\n if (!Array.isArray(userGroups) || userGroups.length === 0) {\n return false;\n }\n\n let matched = false;\n\n for (const expectedGroup of groups) {\n const userInGroup = userGroups.some(\n g =>\n (typeof g === 'string' && g === expectedGroup) ||\n (typeof g === 'object' &&\n (g.id === expectedGroup || g.name === expectedGroup))\n );\n\n if (!matchAll && userInGroup) {\n return userInGroup;\n }\n\n if (matchAll && !userInGroup) {\n return false;\n }\n\n matched = userInGroup;\n }\n\n return matched;\n};\n\n/**\n * Generates a random state string.\n */\nexport const generateState = (): string => randomBytes(32);\n\n/**\n * Generates a PKCE (Proof Key for Code Exchange) code verifier and code challenge.\n *\n */\nexport const generatePKCE = async (): Promise<{\n codeVerifier: string;\n codeChallenge: string;\n}> => {\n const codeVerifier = randomBytes(32);\n return {\n codeVerifier,\n codeChallenge: encodeBase64Url(\n await crypto.subtle.digest(\n 'SHA-256',\n stringToArrayBuffer(codeVerifier) as BufferSource\n )\n ),\n };\n};\n\n/**\n * Generates a random nonce string.\n */\nexport const generateNonce = (): string => randomBytes(32);\n\n/**\n * @ignore\n * Merges multiple arrays of strings, removing duplicates.\n *\n * @param args - List of arrays to merge\n *\n * @returns A new array containing unique strings from both input arrays, or `undefined` if both inputs are `undefined`.\n */\nexport const mergeArrays = (\n ...args: (string[] | undefined)[]\n): string[] | undefined => {\n const arrays = args.filter(x => Array.isArray(x));\n return arrays.length > 0\n ? Array.from(new Set(arrays.reduce((acc, x) => [...acc, ...x], [])))\n : undefined;\n};\n"],"mappings":";;;;AAiBA,MAAM,oBAAoB;AAC1B,MAAM,cAAc;AACpB,MAAM,gBAAgB;AAEtB,MAAM,sBAAsB,OAC1B,QACA,SACuB;CACvB,MAAM,UAAU,MAAM,OAAO,OAAO,UAClC,OACAA,2CAAoB,OAAO,EAC3B,UACA,OACA,CAAC,YAAY,CACd;AAED,QAAO,OAAO,OAAO,UACnB;EACE,MAAM;EACA;EACN,YAAY;EACZ,MAAM;EACP,EACD,SACA;EAAE,MAAM;EAAW,QAAQ;EAAK,EAChC,OACA,CAAC,WAAW,UAAU,CACvB;;;;;AAMH,MAAa,uBACX,eACmB;CACnB,IAAI;AAEJ,KAAI,sBAAsB,IACxB,UAAS,WAAW;UACX,sBAAsB,gBAC/B,UAAS;KAET,KAAI;AACF,WAAS,IAAI,IAAI,WAAW,CAAC;SACvB;AAEN,eACE,WAAW,WAAW,IAAI,IAAI,WAAW,WAAW,IAAI,GACpD,WAAW,UAAU,EAAE,GACvB;AACN,WAAS,IAAI,gBAAgB,WAA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ams, x as MonoCloudUser } from "../types-CnxqWHwA.cjs";
1
+ import { b as MonoCloudSession, p as IdTokenClaims, r as AuthState, s as CallbackParams, x as MonoCloudUser } from "../types-BAE9nCpJ.cjs";
2
2
 
3
3
  //#region src/utils/index.d.ts
4
-
5
4
  /**
6
5
  * Parses callback parameters from a URL, a URLSearchParams object, or a query string.
7
6
  */
@@ -1,7 +1,6 @@
1
- import { b as MonoCloudSession, p as IdTokenClaims, r as AuthState, s as CallbackParams, x as MonoCloudUser } from "../types-DwJl9ZUf.mjs";
1
+ import { b as MonoCloudSession, p as IdTokenClaims, r as AuthState, s as CallbackParams, x as MonoCloudUser } from "../types-D3lVLgLQ.mjs";
2
2
 
3
3
  //#region src/utils/index.d.ts
4
-
5
4
  /**
6
5
  * Parses callback parameters from a URL, a URLSearchParams object, or a query string.
7
6
  */
@@ -1,4 +1,4 @@
1
- import { h as now, i as encodeBase64Url, n as arrayBufferToString, s as fromB64Url, t as arrayBufferToBase64, v as randomBytes, x as stringToArrayBuffer } from "../internal-DXHuqjJJ.mjs";
1
+ import { arrayBufferToBase64, arrayBufferToString, encodeBase64Url, fromB64Url, now, randomBytes, stringToArrayBuffer } from "./internal.mjs";
2
2
 
3
3
  //#region src/utils/index.ts
4
4
  const PBKDF2_ITERATIONS = 31e4;