@hyper.authio/client 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constants.ts","../src/errors.ts","../src/options.ts","../src/http.ts","../src/discovery.ts","../src/keys.ts","../src/client-authentication.ts","../src/encryption.ts","../src/token-validation.ts","../src/authorization.ts","../src/client.ts","../src/admin.ts","../src/resource-access.ts","../src/webhooks.ts"],"names":["importPKCS8","importJWK","errors","algorithmOf","decodeProtectedHeader","toBase64Url","token","withoutUndefined","textOf","parseJson","seconds"],"mappings":";;;AAGO,IAAM,gBAAA,GAAmB;AAAA,EAC9B,OAAA,EAAS,KAAA;AAAA,EACT,KAAA,EAAO,KAAA;AAAA,EACP,MAAA,EAAQ,KAAA;AAAA,EACR,QAAA,EAAU,KAAA;AAAA,EACV,UAAA,EAAY,KAAA;AAAA,EACZ,QAAA,EAAU,KAAA;AAAA,EACV,SAAA,EAAW,KAAA;AAAA,EACX,QAAA,EAAU,WAAA;AAAA,EACV,SAAA,EAAW,KAAA;AAAA,EACX,eAAA,EAAiB,KAAA;AAAA,EACjB,KAAA,EAAO,OAAA;AAAA,EACP,SAAA,EAAW,KAAA;AAAA,EACX,0BAAA,EAA4B,KAAA;AAAA,EAC5B,qBAAA,EAAuB,KAAA;AAAA,EACvB,gBAAA,EAAkB,KAAA;AAAA,EAClB,KAAA,EAAO,OAAA;AAAA,EACP,eAAA,EAAiB,SAAA;AAAA,EACjB,MAAA,EAAQ,QAAA;AAAA,EACR,cAAA,EAAgB,QAAA;AAAA,EAChB,iBAAA,EAAmB,WAAA;AAAA,EACnB,SAAA,EAAW,YAAA;AAAA,EACX,KAAA,EAAO,KAAA;AAAA,EACP,YAAA,EAAc,eAAA;AAAA,EACd,QAAA,EAAU,WAAA;AAAA,EACV,IAAA,EAAM,MAAA;AAAA,EACN,SAAA,EAAW,YAAA;AAAA,EAC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O,MAAA,GAAS,KAAK,MAAM,CAAA;AAE1D,EAAA,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAC,CAAA;AACrB,EAAA,OAAA,CAAQ,GAAA,CAAI,IAAA,EAAM,MAAA,CAAO,MAAM,CAAA;AAE/B,EAAA,MAAM,MAAM,MAAM,MAAA,CAAO,OAAO,SAAA,CAAU,KAAA,EAAO,QAAQ,MAAA,CAAO,MAAM,GAAG,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,SAAA,IAAa,KAAA,EAAO,CAAC,MAAM,CAAC,CAAA;AAE3H,EAAA,OAAO,IAAI,WAAW,MAAM,MAAA,CAAO,OAAO,IAAA,CAAK,MAAA,EAAQ,GAAA,EAAK,OAAO,CAAC,CAAA;AACtE;AAEA,SAAS,kBAAA,CAAmB,MAAkB,KAAA,EAA4B;AACxE,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,KAAA,CAAM,MAAA,EAAQ,OAAO,KAAA;AAEzC,EAAA,IAAI,UAAA,GAAa,CAAA;AAEjB,EAAA,KAAA,IAAS,KAAA,GAAQ,CAAA,EAAG,KAAA,GAAQ,IAAA,CAAK,MAAA,EAAQ,KAAA,EAAA,EAAS,UAAA,IAAc,IAAA,CAAK,KAAK,CAAA,GAAK,KAAA,CAAM,KAAK,CAAA;AAE1F,EAAA,OAAO,UAAA,KAAe,CAAA;AACxB","file":"index.js","sourcesContent":["/**\n * Claim names Authio writes into its tokens.\n */\nexport const AuthioClaimTypes = {\n Subject: \"sub\",\n JwtId: \"jti\",\n Issuer: \"iss\",\n Audience: \"aud\",\n Expiration: \"exp\",\n IssuedAt: \"iat\",\n NotBefore: \"nbf\",\n AuthTime: \"auth_time\",\n TokenType: \"typ\",\n AuthorizedParty: \"azp\",\n Scope: \"scope\",\n SessionId: \"sid\",\n AuthenticationContextClass: \"acr\",\n AuthenticationMethods: \"amr\",\n IdentityProvider: \"idp\",\n Nonce: \"nonce\",\n AccessTokenHash: \"at_hash\",\n Events: \"events\",\n OrganizationId: \"org_id\",\n OrganizationAlias: \"org_alias\",\n AccountId: \"account_id\",\n Actor: \"act\",\n DelegationId: \"delegation_id\",\n ClientId: \"client_id\",\n Name: \"name\",\n GivenName: \"given_name\",\n FamilyName: \"family_name\",\n UniqueName: \"unique_name\",\n PreferredUsername: \"preferred_username\",\n UpdatedAt: \"updated_at\",\n Email: \"email\",\n EmailVerified: \"email_verified\",\n PhoneNumber: \"phone_number\",\n PhoneNumberVerified: \"phone_number_verified\",\n ConsumerName: \"consumer_name\",\n CredentialId: \"credential_id\",\n CredentialType: \"credential_type\",\n CredentialName: \"credential_name\",\n CredentialRealm: \"credential_realm\",\n CredentialClient: \"credential_client\",\n ActorType: \"actor_type\",\n OwnerUserId: \"owner_user_id\",\n OwnerUsername: \"owner_username\",\n UserResourceAccess: \"user_resource_access\",\n RealmResourceAccess: \"realm_resource_access\",\n ClientResourceAccess: \"client_resource_access\",\n PlanResourceAccess: \"plan_resource_access\",\n ConsumerResourceAccess: \"consumer_resource_access\",\n SecretResourceAccess: \"secret_resource_access\",\n SystemResourceAccess: \"system_resource_access\",\n} as const;\n\n/**\n * Where a role in a `*_resource_access` claim was granted.\n *\n * - `user`: to the person, directly or through one of their groups.\n * - `realm`: to everyone who signs in to the realm.\n * - `client`: to everyone who signs in through the client.\n * - `plan`: by the plan of an Authio platform account (platform users only).\n * - `consumer`: to a machine consumer of the client.\n * - `secret`: to an account credential (API key, client secret, personal access token).\n * - `system`: to an Authio platform user (the console).\n */\nexport type AuthioResourceAccessSource = \"user\" | \"realm\" | \"client\" | \"plan\" | \"consumer\" | \"secret\" | \"system\";\n\n/**\n * The seven `*_resource_access` claim names, mapped to their source.\n */\nexport const AuthioResourceAccessClaims: Readonly<Record<string, AuthioResourceAccessSource>> = Object.freeze({\n [AuthioClaimTypes.UserResourceAccess]: \"user\",\n [AuthioClaimTypes.RealmResourceAccess]: \"realm\",\n [AuthioClaimTypes.ClientResourceAccess]: \"client\",\n [AuthioClaimTypes.PlanResourceAccess]: \"plan\",\n [AuthioClaimTypes.ConsumerResourceAccess]: \"consumer\",\n [AuthioClaimTypes.SecretResourceAccess]: \"secret\",\n [AuthioClaimTypes.SystemResourceAccess]: \"system\",\n});\n\n/**\n * Scopes Authio defines.\n */\nexport const AuthioScopes = {\n OpenId: \"openid\",\n Profile: \"profile\",\n Email: \"email\",\n Phone: \"phone\",\n Roles: \"roles\",\n OfflineAccess: \"offline_access\",\n} as const;\n\n/**\n * Grant types Authio's token endpoint accepts.\n */\nexport const AuthioGrantTypes = {\n AuthorizationCode: \"authorization_code\",\n RefreshToken: \"refresh_token\",\n ClientCredentials: \"client_credentials\",\n Password: \"password\",\n DeviceCode: \"urn:ietf:params:oauth:grant-type:device_code\",\n TokenExchange: \"urn:ietf:params:oauth:grant-type:token-exchange\",\n PersonalAccessToken: \"personal_access_token\",\n} as const;\n\n/**\n * Token type identifiers.\n */\nexport const AuthioTokenTypes = {\n AccessTokenUrn: \"urn:ietf:params:oauth:token-type:access_token\",\n ConnectionAccessTokenUrn: \"urn:authio:params:oauth:token-type:connection-access-token\",\n AccessToken: \"access_token\",\n RefreshToken: \"refresh_token\",\n} as const;\n\n/**\n * OAuth error codes Authio answers with.\n */\nexport const AuthioOAuthErrors = {\n InvalidRequest: \"invalid_request\",\n InvalidClient: \"invalid_client\",\n InvalidGrant: \"invalid_grant\",\n UnauthorizedClient: \"unauthorized_client\",\n UnsupportedGrantType: \"unsupported_grant_type\",\n InvalidScope: \"invalid_scope\",\n InvalidTarget: \"invalid_target\",\n AccessDenied: \"access_denied\",\n InvalidToken: \"invalid_token\",\n AuthorizationPending: \"authorization_pending\",\n SlowDown: \"slow_down\",\n ExpiredToken: \"expired_token\",\n ConnectionRequired: \"connection_required\",\n ConnectionSelectionRequired: \"connection_selection_required\",\n ConnectionPolicyViolation: \"connection_policy_violation\",\n ServerError: \"server_error\",\n TemporarilyUnavailable: \"temporarily_unavailable\",\n LoginRequired: \"login_required\",\n InteractionRequired: \"interaction_required\",\n ConsentRequired: \"consent_required\",\n AccountSelectionRequired: \"account_selection_required\",\n InsufficientScope: \"insufficient_scope\",\n InsufficientUserAuthentication: \"insufficient_user_authentication\",\n} as const;\n\n/**\n * Webhook event types.\n */\nexport const AuthioWebhookEventTypes = {\n UserCreated: \"user_created\",\n UserUpdated: \"user_updated\",\n UserDeleted: \"user_deleted\",\n LoginSucceeded: \"login_succeeded\",\n LoginFailed: \"login_failed\",\n UserLockedOut: \"user_locked_out\",\n TokenRevoked: \"token_revoked\",\n KeysRotated: \"keys_rotated\",\n TokenReuseDetected: \"token_reuse_detected\",\n AdminResourceCreated: \"admin_resource_created\",\n AdminResourceUpdated: \"admin_resource_updated\",\n AdminResourceDeleted: \"admin_resource_deleted\",\n UserSuspended: \"user_suspended\",\n UserSuspensionEnded: \"user_suspension_ended\",\n AttackDetected: \"attack_detected\",\n CredentialCompromised: \"credential_compromised\",\n Ping: \"ping\",\n} as const;\n\n/**\n * Headers Authio sends with a webhook delivery.\n */\nexport const AuthioWebhookHeaders = {\n Signature: \"X-Authio-Signature\",\n Event: \"X-Authio-Event\",\n EventId: \"X-Authio-Event-Id\",\n} as const;\n\n/**\n * Who called an API, read from the access token (see `conformance/callers.json`).\n *\n * - `user`: a person signed in (the token carries `auth_time`).\n * - `client`: a client authenticated as itself.\n * - `consumer`: a machine consumer of a client (`credential_type` `client_consumer`).\n * - `account_credential`: a credential of an Authio account (`credential_type` `account_secret`).\n */\nexport type AuthioCallerKind = \"user\" | \"client\" | \"consumer\" | \"account_credential\";\n\n/**\n * How a machine caller proved who it is.\n */\nexport type AuthioCredentialForm = \"client_secret\" | \"personal_access_token\" | \"api_key\" | \"consumer_api_key\";\n\n/**\n * The caller kinds.\n */\nexport const AuthioCallerKinds = [\"user\", \"client\", \"consumer\", \"account_credential\"] as const satisfies readonly AuthioCallerKind[];\n\n/**\n * The values of `prompt` Authio honours.\n */\nexport const AuthioPrompts = [\"none\", \"login\", \"select_account\", \"consent\"] as const;\n\n/**\n * A value of `prompt`.\n */\nexport type AuthioPrompt = (typeof AuthioPrompts)[number];\n\n/**\n * Asymmetric signing algorithms Authio issues tokens with and accepts in client assertions.\n */\nexport const AuthioAsymmetricAlgorithms = [\n \"RS256\",\n \"RS384\",\n \"RS512\",\n \"PS256\",\n \"PS384\",\n \"PS512\",\n \"ES256\",\n \"ES384\",\n \"ES512\",\n] as const;\n\n/**\n * Symmetric algorithms Authio may sign a client's tokens with. A client verifies them with its own client secret\n * (OpenID Connect Core §10.1), and only when `idTokenSignedResponseAlg` names one.\n */\nexport const AuthioHmacAlgorithms = [\"HS256\", \"HS384\", \"HS512\"] as const;\n\n/**\n * The shortest client secret, in bytes of its UTF-8 form, each HS* algorithm is verified with: the size of the hash\n * output (RFC 7518 §3.2). Authio refuses a shorter secret for the algorithm, and so do the SDKs.\n */\nexport const AuthioHmacMinimumSecretBytes = Object.freeze({ HS256: 32, HS384: 48, HS512: 64 }) as Readonly<Record<(typeof AuthioHmacAlgorithms)[number], number>>;\n\n/**\n * Defaults shared by every Authio SDK.\n */\nexport const AuthioDefaults = {\n DiscoveryPath: \"/.well-known/openid-configuration\",\n ProtectedResourceMetadataPath: \"/.well-known/oauth-protected-resource\",\n RedactedValue: \"[redacted]\",\n PlatformRealm: \"authio\",\n PlatformClientId: \"authio\",\n ApiKeyPrefix: \"ak_\",\n ClientSecretPrefix: \"cs_\",\n PersonalAccessTokenPrefix: \"pat_\",\n /** The `client_id` an account credential's client secret is exchanged with: `cred_` and the credential id (format N). */\n CredentialClientIdPrefix: \"cred_\",\n ApiKeyHeader: \"x-api-key\",\n RequestIdHeader: \"X-Request-Id\",\n /** The header `typ` of a back-channel logout token. */\n LogoutTokenType: \"logout+jwt\",\n /** The event a back-channel logout token carries. */\n BackchannelLogoutEvent: \"http://schemas.openid.net/event/backchannel-logout\",\n /** Seconds. */\n ClockSkew: 30,\n /** Seconds. */\n ClientAssertionLifetime: 120,\n /** Seconds. */\n MaxClientAssertionLifetime: 3600,\n /** Seconds. */\n DeviceInterval: 5,\n /** Seconds. */\n DeviceSlowDownIncrement: 5,\n /** Seconds a token without `expires_in` is assumed to live. */\n AssumedTokenLifetime: 300,\n /** Seconds. */\n DiscoveryCacheDuration: 3600,\n /** Seconds. */\n HttpTimeout: 30,\n /** Seconds. */\n TokenRefreshSkew: 60,\n /** Seconds. */\n WebhookTolerance: 300,\n /** Smallest RSA key Authio verifies a client assertion from, in bits. */\n MinimumRsaKeySize: 2048,\n CredentialHeaders: [\"authorization\", \"proxy-authorization\", \"x-api-key\", \"cookie\", \"set-cookie\"],\n} as const;\n","/**\n * Base class of every error the Authio SDKs throw on purpose.\n */\nexport class AuthioError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/**\n * An OAuth error Authio answered with, or an answer the SDK could not read.\n *\n * `error` is the OAuth error code; `http_{status}` when the body carried none, and `invalid_response` when a success\n * body could not be read.\n */\nexport class AuthioProtocolError extends AuthioError {\n /** The OAuth error code. */\n readonly error: string;\n /** The OAuth error description. */\n readonly errorDescription: string | undefined;\n /** Authio's own error code (`error_code`), more specific than `error`. */\n readonly errorCode: string | undefined;\n /** The HTTP status, when the error came from a response. */\n readonly status: number | undefined;\n\n constructor(error: string, errorDescription?: string, errorCode?: string, status?: number, options?: { cause?: unknown }) {\n super(errorDescription ? `${error}: ${errorDescription}` : error, options);\n this.error = error;\n this.errorDescription = errorDescription;\n this.errorCode = errorCode;\n this.status = status;\n }\n}\n\n/**\n * The discovery document could not be read, or names another issuer.\n */\nexport class AuthioDiscoveryError extends AuthioError {}\n\n/**\n * The SDK was configured in a way it cannot work with.\n */\nexport class AuthioConfigurationError extends AuthioError {}\n\n/**\n * Why a token was refused, with the outcome names of `conformance/tokens.json`.\n */\nexport type AuthioTokenFailure =\n | \"not_access_token\"\n | \"not_id_token\"\n | \"invalid_audience\"\n | \"invalid_issuer\"\n | \"expired\"\n | \"not_yet_valid\"\n | \"invalid_signature\"\n | \"invalid_algorithm\"\n | \"reference_token\"\n | \"malformed\"\n | \"decryption_failed\"\n | \"legacy_algorithm\"\n | \"invalid_nonce\"\n | \"invalid_at_hash\"\n | \"authentication_too_old\"\n | \"invalid_logout_token\"\n | \"signing_keys_unavailable\";\n\n/**\n * A token (ID token, logout token, signed UserInfo, encrypted token) did not pass validation.\n */\nexport class AuthioTokenValidationError extends AuthioError {\n /** Why, as a stable code. */\n readonly reason: AuthioTokenFailure;\n\n constructor(reason: AuthioTokenFailure, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.reason = reason;\n }\n}\n\n/**\n * Why an authorization callback was refused before any code was exchanged.\n */\nexport type AuthioCallbackFailure = \"state_mismatch\" | \"issuer_mismatch\" | \"missing_issuer\" | \"missing_code\";\n\n/**\n * The authorization callback does not belong to the request this client made: `state` differs, the `iss` parameter\n * (RFC 9207) names another issuer or is missing where Authio sends it, or there is no code.\n */\nexport class AuthioCallbackError extends AuthioError {\n /** Why, as a stable code. */\n readonly reason: AuthioCallbackFailure;\n\n constructor(reason: AuthioCallbackFailure, message: string) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * One message of an Admin API error, optionally tied to a field of the request.\n */\nexport interface AuthioAdminNotification {\n readonly message: string;\n readonly field?: string;\n readonly code?: string;\n}\n\n/**\n * The Admin API refused a request. `errorCode` is the envelope's top-level `errorCode`; the HTTP status is read from\n * the response, never from the envelope's numeric `statusCode`.\n */\nexport class AuthioAdminError extends AuthioError {\n /** The HTTP status. */\n readonly status: number;\n /** Authio's error code, such as `ValidationFailed` or `RealmNotFound`. */\n readonly errorCode: string | undefined;\n /** The messages, with the field each one is about. */\n readonly notifications: readonly AuthioAdminNotification[];\n /** The request id, from the envelope or the `X-Request-Id` header. */\n readonly requestId: string | undefined;\n /** Seconds to wait before retrying, from `Retry-After` (`429` and `503`). */\n readonly retryAfterSeconds: number | undefined;\n\n constructor(details: {\n status: number;\n errorCode?: string;\n notifications?: readonly AuthioAdminNotification[];\n requestId?: string;\n retryAfterSeconds?: number;\n cause?: unknown;\n }) {\n const notifications = details.notifications ?? [];\n const summary = notifications.map((notification) => notification.message).filter(Boolean).join(\" \");\n\n super(\n `The Authio Admin API answered HTTP ${details.status}${details.errorCode ? ` (${details.errorCode})` : \"\"}${summary ? `: ${summary}` : \".\"}`,\n { cause: details.cause },\n );\n this.status = details.status;\n this.errorCode = details.errorCode;\n this.notifications = Object.freeze([...notifications]);\n this.requestId = details.requestId;\n this.retryAfterSeconds = details.retryAfterSeconds;\n }\n}\n","import { AuthioDefaults } from \"./constants.js\";\nimport { AuthioConfigurationError } from \"./errors.js\";\n\n/**\n * Time as the SDK sees it. Replace it in tests to control expiry, caching and device polling.\n */\nexport interface AuthioClock {\n /** Milliseconds since the epoch. */\n now(): number;\n /** Waits `ms` milliseconds; rejects when the signal aborts. */\n sleep(ms: number, signal?: AbortSignal): Promise<void>;\n}\n\n/**\n * The real clock.\n */\nexport const systemClock: AuthioClock = {\n now: () => Date.now(),\n sleep: (ms, signal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n }),\n};\n\n/**\n * Where Authio is and how to reach it. Shared by the client and the API verifier.\n */\nexport interface AuthioConnectionOptions {\n /**\n * The realm's issuer, such as `https://auth.example.com/realms/acme`. When absent it is composed from\n * `authority` and `realm`.\n */\n issuer?: string;\n /** Authio's base URL, such as `https://auth.example.com`. */\n authority?: string;\n /** The realm name. */\n realm?: string;\n /**\n * Refuses an `http` issuer or authority unless it is loopback. Defaults to `true`; turn it off only in\n * development.\n */\n requireHttps?: boolean;\n /** Seconds the discovery document is kept. Defaults to 3600. */\n discoveryCacheDuration?: number;\n /** Seconds every HTTP call may take. Defaults to 30. */\n httpTimeout?: number;\n /** The `fetch` every call goes through. Defaults to the global one. */\n fetch?: typeof fetch;\n /** The clock. Defaults to the system clock. */\n clock?: AuthioClock;\n}\n\n/**\n * How the client authenticates to the token, introspection, revocation and device endpoints: the client's\n * `token_endpoint_auth_method` in Authio, which Authio matches exactly.\n */\nexport type AuthioTokenEndpointAuthMethod = \"client_secret_basic\" | \"client_secret_post\" | \"private_key_jwt\" | \"none\";\n\n/**\n * The values of `tokenEndpointAuthMethod`.\n */\nexport const AuthioTokenEndpointAuthMethods = [\n \"client_secret_basic\",\n \"client_secret_post\",\n \"private_key_jwt\",\n \"none\",\n] as const satisfies readonly AuthioTokenEndpointAuthMethod[];\n\n/**\n * The connection settings, resolved once.\n */\nexport interface AuthioConnection {\n readonly issuer: string;\n readonly discoveryUrl: string;\n readonly requireHttps: boolean;\n readonly discoveryCacheDurationMs: number;\n readonly httpTimeoutMs: number;\n readonly fetch: typeof fetch;\n readonly clock: AuthioClock;\n}\n\n/**\n * Resolves and validates the connection settings.\n *\n * @throws AuthioConfigurationError when the issuer cannot be composed or is not HTTPS.\n */\nexport function resolveConnection(options: AuthioConnectionOptions): AuthioConnection {\n const requireHttps = options.requireHttps ?? true;\n const issuer = resolveIssuer(options);\n\n for (const [name, value] of [\n [\"authority\", options.authority],\n [\"issuer\", issuer],\n ] as const) {\n if (value && !isAllowedUrl(value, requireHttps))\n throw new AuthioConfigurationError(\n `The Authio ${name} '${value}' must be an absolute HTTPS URL (http is allowed only for loopback, or with requireHttps: false).`,\n );\n }\n\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n\n if (typeof fetchImplementation !== \"function\")\n throw new AuthioConfigurationError(\"No fetch implementation is available: pass options.fetch.\");\n\n return {\n issuer,\n discoveryUrl: issuer + AuthioDefaults.DiscoveryPath,\n requireHttps,\n discoveryCacheDurationMs: seconds(options.discoveryCacheDuration, AuthioDefaults.DiscoveryCacheDuration, \"discoveryCacheDuration\"),\n httpTimeoutMs: seconds(options.httpTimeout, AuthioDefaults.HttpTimeout, \"httpTimeout\"),\n fetch: fetchImplementation,\n clock: options.clock ?? systemClock,\n };\n}\n\n/**\n * The issuer: `issuer` when set, else `{authority}/realms/{realm}`.\n *\n * @throws AuthioConfigurationError when neither is configured.\n */\nexport function resolveIssuer(options: Pick<AuthioConnectionOptions, \"issuer\" | \"authority\" | \"realm\">): string {\n const issuer = options.issuer?.trim();\n\n if (issuer) return trimTrailingSlashes(issuer);\n\n const authority = options.authority?.trim();\n const realm = options.realm?.trim();\n\n if (!authority || !realm)\n throw new AuthioConfigurationError(\n \"The Authio issuer is not set, and authority and realm are not both set to compose it.\",\n );\n\n return `${trimTrailingSlashes(authority)}/realms/${escapeDataString(realm)}`;\n}\n\n/**\n * Whether a URL may be used to reach Authio: HTTPS, or HTTP on loopback (or anywhere when HTTPS is not required).\n */\nexport function isAllowedUrl(value: string, requireHttps: boolean): boolean {\n let url: URL;\n\n try {\n url = new URL(value);\n } catch {\n return false;\n }\n\n if (url.protocol === \"https:\") return true;\n\n return url.protocol === \"http:\" && (!requireHttps || isLoopback(url.hostname));\n}\n\n/**\n * Percent-encodes everything but RFC 3986 unreserved characters, as .NET's `Uri.EscapeDataString` does.\n */\nexport function escapeDataString(value: string): string {\n return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);\n}\n\n/**\n * Converts optional seconds to milliseconds, refusing negative or non-finite values.\n *\n * @internal\n */\nexport function seconds(value: number | undefined, fallback: number, name: string): number {\n const resolved = value ?? fallback;\n\n if (!Number.isFinite(resolved) || resolved < 0)\n throw new AuthioConfigurationError(`The Authio option ${name} must be a non-negative number of seconds.`);\n\n return resolved * 1000;\n}\n\nfunction trimTrailingSlashes(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction isLoopback(hostname: string): boolean {\n const host = hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n\n return host === \"localhost\" || host === \"::1\" || /^127(\\.\\d{1,3}){3}$/.test(host);\n}\n","import { AuthioDefaults } from \"./constants.js\";\nimport { AuthioProtocolError } from \"./errors.js\";\nimport type { AuthioConnection } from \"./options.js\";\n\n/**\n * The OAuth error body Authio answers with.\n */\nexport interface AuthioErrorResponse {\n error?: string;\n error_description?: string;\n error_code?: string;\n connect_uri?: string;\n connection_provider?: string;\n connections?: { id: string; label?: string; external_login?: string }[];\n [member: string]: unknown;\n}\n\n/**\n * Sends a request through the configured `fetch`, bounded by the HTTP timeout and the caller's signal.\n *\n * @internal\n */\nexport function send(connection: AuthioConnection, url: string, init: RequestInit, signal?: AbortSignal): Promise<Response> {\n const timeout = AbortSignal.timeout(connection.httpTimeoutMs);\n\n return connection.fetch(url, { ...init, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });\n}\n\n/**\n * Builds an `application/x-www-form-urlencoded` body, skipping empty values.\n *\n * @internal\n */\nexport function formBody(parameters: Record<string, string | undefined | null>): URLSearchParams {\n const form = new URLSearchParams();\n\n for (const [name, value] of Object.entries(parameters)) {\n if (value !== undefined && value !== null && value !== \"\") form.append(name, value);\n }\n\n return form;\n}\n\n/**\n * Joins scopes into one space-separated value, splitting values that already hold several and dropping duplicates.\n *\n * @returns `undefined` when there is no scope.\n */\nexport function toScopeString(scopes: Iterable<string> | string | undefined | null): string | undefined {\n if (scopes === undefined || scopes === null) return undefined;\n\n const values = typeof scopes === \"string\" ? [scopes] : [...scopes];\n const distinct = [...new Set(values.flatMap((scope) => (scope ?? \"\").split(\" \").filter(Boolean)))];\n\n return distinct.length === 0 ? undefined : distinct.join(\" \");\n}\n\n/**\n * Reads a JSON success body, or throws the OAuth error the response carries.\n *\n * @internal\n */\nexport async function readProtocolJson<T>(response: Response): Promise<T> {\n const body = await response.text();\n\n if (!response.ok) throw toProtocolError(body, response.status);\n\n return parseProtocolJson<T>(body, response.status);\n}\n\n/**\n * Throws the OAuth error a failed response carries.\n *\n * @internal\n */\nexport async function ensureProtocolSuccess(response: Response): Promise<void> {\n if (response.ok) return;\n\n throw toProtocolError(await response.text(), response.status);\n}\n\n/**\n * Parses a success body.\n *\n * @internal\n */\nexport function parseProtocolJson<T>(body: string, status: number): T {\n try {\n const value = JSON.parse(body) as unknown;\n\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new SyntaxError(\"The body is not a JSON object.\");\n\n return value as T;\n } catch (error) {\n throw new AuthioProtocolError(\n \"invalid_response\",\n `Authio answered with a body that could not be read: ${(error as Error).message}`,\n undefined,\n status,\n { cause: error },\n );\n }\n}\n\n/**\n * Reads the OAuth error of a body, when it has one.\n *\n * @internal\n */\nexport function toErrorResponse(body: string | undefined): AuthioErrorResponse | undefined {\n if (!body?.trim()) return undefined;\n\n try {\n const value = JSON.parse(body) as AuthioErrorResponse;\n\n return value && typeof value === \"object\" && typeof value.error === \"string\" && value.error ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The error a failed response stands for.\n *\n * @internal\n */\nexport function toProtocolError(body: string | undefined, status: number): AuthioProtocolError {\n const error = toErrorResponse(body);\n\n return error\n ? new AuthioProtocolError(error.error!, error.error_description, error.error_code, status)\n : new AuthioProtocolError(`http_${status}`, `Authio answered HTTP ${status} without an OAuth error.`, undefined, status);\n}\n\n/**\n * Makes `console.log` and `util.inspect` print `[redacted]` in place of the named members, without changing what\n * `JSON.stringify` or a spread sees.\n *\n * @internal\n */\nexport function redact<T extends object>(value: T, secrets: readonly string[]): T {\n Object.defineProperty(value, Symbol.for(\"nodejs.util.inspect.custom\"), {\n enumerable: false,\n value(this: Record<string, unknown>) {\n const copy: Record<string, unknown> = {};\n\n for (const [name, member] of Object.entries(this))\n copy[name] = secrets.includes(name) && member !== undefined && member !== null ? AuthioDefaults.RedactedValue : member;\n\n return copy;\n },\n });\n\n return value;\n}\n","import { AuthioDiscoveryError } from \"./errors.js\";\nimport { send } from \"./http.js\";\nimport { resolveConnection, type AuthioConnection, type AuthioConnectionOptions } from \"./options.js\";\n\n/**\n * The realm's OpenID Connect discovery document. Members not listed are kept as sent.\n */\nexport interface AuthioDiscoveryDocument {\n issuer: string;\n authorization_endpoint?: string;\n token_endpoint?: string;\n userinfo_endpoint?: string;\n jwks_uri?: string;\n introspection_endpoint?: string;\n revocation_endpoint?: string;\n end_session_endpoint?: string;\n device_authorization_endpoint?: string;\n pushed_authorization_request_endpoint?: string;\n scopes_supported?: string[];\n response_types_supported?: string[];\n response_modes_supported?: string[];\n grant_types_supported?: string[];\n subject_types_supported?: string[];\n id_token_signing_alg_values_supported?: string[];\n userinfo_signing_alg_values_supported?: string[];\n token_endpoint_auth_methods_supported?: string[];\n token_endpoint_auth_signing_alg_values_supported?: string[];\n introspection_endpoint_auth_methods_supported?: string[];\n revocation_endpoint_auth_methods_supported?: string[];\n code_challenge_methods_supported?: string[];\n claims_supported?: string[];\n prompt_values_supported?: string[];\n authorization_response_iss_parameter_supported?: boolean;\n frontchannel_logout_supported?: boolean;\n frontchannel_logout_session_supported?: boolean;\n [member: string]: unknown;\n}\n\n/**\n * Reads and caches the discovery document.\n */\nexport interface AuthioDiscoveryClient {\n /** The connection settings the client was built with. */\n readonly connection: AuthioConnection;\n /**\n * The document, read at most once per cache period (concurrent callers share one read).\n *\n * @throws AuthioDiscoveryError when it cannot be read or names another issuer.\n */\n get(signal?: AbortSignal): Promise<AuthioDiscoveryDocument>;\n /** Drops the cached document, so the next `get` reads it again. */\n invalidate(): void;\n}\n\n/**\n * Creates a discovery client. It needs no client credentials, so an API that only validates tokens can use it.\n */\nexport function createAuthioDiscoveryClient(options: AuthioConnectionOptions | AuthioConnection): AuthioDiscoveryClient {\n const connection = isConnection(options) ? options : resolveConnection(options);\n let cached: { document: AuthioDiscoveryDocument; fetchedAt: number } | undefined;\n let pending: Promise<AuthioDiscoveryDocument> | undefined;\n\n const fresh = () =>\n cached && connection.clock.now() - cached.fetchedAt < connection.discoveryCacheDurationMs ? cached.document : undefined;\n\n return {\n connection,\n async get(signal) {\n const current = fresh();\n\n if (current) return current;\n\n pending ??= fetchDocument(connection, signal)\n .then((document) => {\n cached = { document, fetchedAt: connection.clock.now() };\n return document;\n })\n .finally(() => {\n pending = undefined;\n });\n\n return pending;\n },\n invalidate() {\n cached = undefined;\n },\n };\n}\n\n/**\n * The endpoint the document names, or an error saying which one is missing.\n *\n * @internal\n */\nexport function requireEndpoint(document: AuthioDiscoveryDocument, member: keyof AuthioDiscoveryDocument & string): string {\n const value = document[member];\n\n if (typeof value !== \"string\" || !value)\n throw new AuthioDiscoveryError(`The Authio discovery document has no ${member}.`);\n\n return value;\n}\n\nasync function fetchDocument(connection: AuthioConnection, signal?: AbortSignal): Promise<AuthioDiscoveryDocument> {\n const url = connection.discoveryUrl;\n let body: string;\n\n try {\n const response = await send(connection, url, { method: \"GET\", headers: { accept: \"application/json\" } }, signal);\n\n body = await response.text();\n\n if (!response.ok) throw new AuthioDiscoveryError(`Authio answered HTTP ${response.status} for the discovery document at ${url}.`);\n } catch (error) {\n if (error instanceof AuthioDiscoveryError) throw error;\n if (signal?.aborted) throw error;\n\n const timedOut = (error as Error)?.name === \"TimeoutError\";\n\n throw new AuthioDiscoveryError(\n timedOut\n ? `Reading the Authio discovery document at ${url} timed out.`\n : `The Authio discovery document at ${url} could not be read.`,\n { cause: error },\n );\n }\n\n let document: AuthioDiscoveryDocument;\n\n try {\n document = JSON.parse(body) as AuthioDiscoveryDocument;\n } catch (error) {\n throw new AuthioDiscoveryError(`The Authio discovery document at ${url} is not valid JSON.`, { cause: error });\n }\n\n if (!document || typeof document !== \"object\" || typeof document.issuer !== \"string\" || !document.issuer.trim())\n throw new AuthioDiscoveryError(`The Authio discovery document at ${url} has no issuer.`);\n\n if (document.issuer.replace(/\\/+$/, \"\") !== connection.issuer)\n throw new AuthioDiscoveryError(\n `The Authio discovery document names the issuer '${document.issuer}', not the configured '${connection.issuer}'.`,\n );\n\n return document;\n}\n\nfunction isConnection(value: AuthioConnectionOptions | AuthioConnection): value is AuthioConnection {\n return typeof (value as AuthioConnection).discoveryUrl === \"string\" && typeof (value as AuthioConnection).httpTimeoutMs === \"number\";\n}\n","import { importJWK, importPKCS8, type CryptoKey, type JWK } from \"jose\";\nimport { AuthioAsymmetricAlgorithms, AuthioDefaults } from \"./constants.js\";\nimport { AuthioConfigurationError } from \"./errors.js\";\n\n/**\n * A private key as the SDK accepts it: PEM text (PKCS#8, PKCS#1 RSA or SEC1 EC; PKCS#1 and SEC1 need Node), a JWK\n * (object or JSON text), or a `CryptoKey`.\n */\nexport type AuthioPrivateKeyInput = string | JWK | CryptoKey;\n\n/**\n * A key ready to sign with, and the algorithm it signs with.\n */\nexport interface AuthioSigningKey {\n readonly key: CryptoKey | Uint8Array;\n readonly algorithm: string;\n readonly keyId: string | undefined;\n}\n\nconst curveAlgorithms: Record<string, string> = { \"P-256\": \"ES256\", \"P-384\": \"ES384\", \"P-521\": \"ES512\" };\n\n/**\n * Imports a signing key and settles its algorithm: the configured one when it suits the key, else RS256 for RSA and\n * the curve's ES algorithm for EC.\n *\n * @param input The key.\n * @param algorithm The configured algorithm, if any.\n * @param keyId The `kid` to send.\n * @param source The setting the key came from, named in errors.\n * @throws AuthioConfigurationError when the key cannot be read, is too weak, or does not suit the algorithm.\n */\nexport async function importSigningKey(\n input: AuthioPrivateKeyInput,\n algorithm: string | undefined,\n keyId: string | undefined,\n source: string,\n): Promise<AuthioSigningKey> {\n if (typeof input === \"string\") {\n const text = input.trim();\n\n if (text.startsWith(\"{\")) return importSigningKey(parseJwk(text, source), algorithm, keyId, source);\n\n return importPem(text, algorithm, keyId, source);\n }\n\n if (isCryptoKey(input)) {\n const shape = describeCryptoKey(input, source);\n\n return { key: input, algorithm: settleAlgorithm(shape, algorithm, source), keyId };\n }\n\n return importFromJwk(input, algorithm, keyId ?? (typeof input.kid === \"string\" ? input.kid : undefined), source);\n}\n\n/**\n * The algorithms a client assertion may be signed with.\n */\nexport const AuthioClientAssertionAlgorithms = AuthioAsymmetricAlgorithms;\n\ninterface KeyShape {\n readonly type: \"RSA\" | \"EC\";\n readonly curve?: string;\n readonly fixedAlgorithm?: string;\n}\n\nasync function importPem(pem: string, algorithm: string | undefined, keyId: string | undefined, source: string): Promise<AuthioSigningKey> {\n const nodeCrypto = await loadNodeCrypto();\n\n if (nodeCrypto) {\n let keyObject: import(\"node:crypto\").KeyObject;\n\n try {\n keyObject = nodeCrypto.createPrivateKey({ key: pem, format: \"pem\" });\n } catch (error) {\n throw new AuthioConfigurationError(`${source} could not be read as an RSA or EC private key.`, { cause: error });\n }\n\n const jwk = keyObject.export({ format: \"jwk\" }) as JWK;\n\n return importFromJwk(jwk, algorithm, keyId, source);\n }\n\n if (!pem.includes(\"-----BEGIN PRIVATE KEY-----\"))\n throw new AuthioConfigurationError(\n `${source} must be a PKCS#8 PEM (\"BEGIN PRIVATE KEY\") or a JWK outside Node; PKCS#1 and SEC1 keys need Node.`,\n );\n\n const chosen = algorithm?.trim() || \"RS256\";\n\n try {\n return { key: await importPKCS8(pem, chosen), algorithm: chosen, keyId };\n } catch (error) {\n throw new AuthioConfigurationError(`${source} could not be imported for ${chosen}.`, { cause: error });\n }\n}\n\nasync function importFromJwk(jwk: JWK, algorithm: string | undefined, keyId: string | undefined, source: string): Promise<AuthioSigningKey> {\n if (!jwk.d) throw new AuthioConfigurationError(`${source} is a public key; Authio needs the private key to sign.`);\n\n const shape = describeJwk(jwk, source);\n const chosen = settleAlgorithm(shape, algorithm ?? (typeof jwk.alg === \"string\" ? jwk.alg : undefined), source);\n\n try {\n const key = await importJWK({ ...jwk, alg: chosen }, chosen);\n\n return { key, algorithm: chosen, keyId };\n } catch (error) {\n throw new AuthioConfigurationError(`${source} could not be imported for ${chosen}.`, { cause: error });\n }\n}\n\nfunction describeJwk(jwk: JWK, source: string): KeyShape {\n if (jwk.kty === \"RSA\") {\n const bits = base64UrlLength(jwk.n ?? \"\") * 8;\n\n if (bits < AuthioDefaults.MinimumRsaKeySize)\n throw new AuthioConfigurationError(`${source} is a ${bits}-bit RSA key; use at least ${AuthioDefaults.MinimumRsaKeySize} bits.`);\n\n return { type: \"RSA\" };\n }\n\n if (jwk.kty === \"EC\") {\n if (!jwk.crv || !curveAlgorithms[jwk.crv])\n throw new AuthioConfigurationError(`${source} is an EC key on a curve Authio does not accept; use P-256, P-384 or P-521.`);\n\n return { type: \"EC\", curve: jwk.crv };\n }\n\n throw new AuthioConfigurationError(`${source} could not be read as an RSA or EC private key.`);\n}\n\nfunction describeCryptoKey(key: CryptoKey, source: string): KeyShape {\n const algorithm = key.algorithm as { name: string; namedCurve?: string; modulusLength?: number; hash?: { name: string } };\n\n if (algorithm.name === \"ECDSA\" && algorithm.namedCurve && curveAlgorithms[algorithm.namedCurve])\n return { type: \"EC\", curve: algorithm.namedCurve };\n\n if (algorithm.name === \"RSASSA-PKCS1-v1_5\" || algorithm.name === \"RSA-PSS\") {\n if ((algorithm.modulusLength ?? 0) < AuthioDefaults.MinimumRsaKeySize)\n throw new AuthioConfigurationError(\n `${source} is a ${algorithm.modulusLength}-bit RSA key; use at least ${AuthioDefaults.MinimumRsaKeySize} bits.`,\n );\n\n const size = algorithm.hash?.name.replace(\"SHA-\", \"\") ?? \"256\";\n\n return { type: \"RSA\", fixedAlgorithm: `${algorithm.name === \"RSA-PSS\" ? \"PS\" : \"RS\"}${size}` };\n }\n\n throw new AuthioConfigurationError(`${source} is a CryptoKey Authio cannot sign assertions with; use an RSA or EC signing key.`);\n}\n\nfunction settleAlgorithm(shape: KeyShape, configured: string | undefined, source: string): string {\n const suited =\n shape.fixedAlgorithm !== undefined\n ? [shape.fixedAlgorithm]\n : shape.type === \"EC\"\n ? [curveAlgorithms[shape.curve!]!]\n : AuthioAsymmetricAlgorithms.filter((name) => name.startsWith(\"RS\") || name.startsWith(\"PS\"));\n\n const chosen = configured?.trim() || suited[0]!;\n\n if (!suited.includes(chosen))\n throw new AuthioConfigurationError(\n `The signing algorithm '${chosen}' does not suit the key in ${source}; use one of: ${suited.join(\", \")}.`,\n );\n\n return chosen;\n}\n\nfunction parseJwk(text: string, source: string): JWK {\n try {\n const parsed = JSON.parse(text) as JWK & { keys?: JWK[] };\n\n if (Array.isArray(parsed.keys)) {\n if (parsed.keys.length !== 1) throw new Error(\"A JWK Set must hold exactly one key.\");\n return parsed.keys[0]!;\n }\n\n return parsed;\n } catch (error) {\n throw new AuthioConfigurationError(`${source} is not a valid JWK.`, { cause: error });\n }\n}\n\nfunction base64UrlLength(value: string): number {\n const clean = value.replace(/=+$/, \"\");\n return Math.floor((clean.length * 3) / 4);\n}\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n return typeof value === \"object\" && value !== null && \"algorithm\" in value && \"type\" in value && \"usages\" in value;\n}\n\nlet nodeCryptoModule: Promise<typeof import(\"node:crypto\") | undefined> | undefined;\n\n/**\n * Node's crypto module, or `undefined` outside Node.\n *\n * @internal\n */\nexport function loadNodeCrypto(): Promise<typeof import(\"node:crypto\") | undefined> {\n nodeCryptoModule ??= (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node\n ? import(\"node:crypto\").catch(() => undefined)\n : Promise.resolve(undefined);\n\n return nodeCryptoModule;\n}\n\n","import { SignJWT } from \"jose\";\nimport { AuthioDefaults } from \"./constants.js\";\nimport { AuthioConfigurationError } from \"./errors.js\";\nimport { importSigningKey, loadNodeCrypto, type AuthioPrivateKeyInput, type AuthioSigningKey } from \"./keys.js\";\nimport { escapeDataString, seconds, AuthioTokenEndpointAuthMethods, type AuthioConnection, type AuthioTokenEndpointAuthMethod } from \"./options.js\";\n\n/**\n * The client secret, or a function returning the current one, called for every request so a rotated secret is used\n * without a restart.\n */\nexport type AuthioSecretSource = string | (() => string | Promise<string>);\n\n/**\n * How the client proves who it is.\n */\nexport interface AuthioClientCredentialsSettings {\n /** The client id. */\n clientId: string;\n /**\n * The client secret, for `client_secret_basic` and `client_secret_post`; or a function returning the current one,\n * called for every request.\n */\n clientSecret?: AuthioSecretSource;\n /**\n * How the client authenticates, as registered in Authio (which matches it exactly). Defaults to\n * `client_secret_basic` with a `clientSecret`, `private_key_jwt` with only a private key, and `none` with neither.\n */\n tokenEndpointAuthMethod?: AuthioTokenEndpointAuthMethod;\n /** The private key for `private_key_jwt`. */\n clientPrivateKey?: AuthioPrivateKeyInput;\n /** A PEM file holding the private key for `private_key_jwt` (Node only); re-read when it changes. */\n clientPrivateKeyPath?: string;\n /** The `kid` of the key, as registered in Authio. */\n clientKeyId?: string;\n /** The assertion's signing algorithm. Defaults to RS256 for RSA keys and the curve's ES algorithm for EC keys. */\n clientSigningAlgorithm?: string;\n /** Seconds a client assertion lives. Defaults to 120, at most 3600. */\n clientAssertionLifetime?: number;\n}\n\n/**\n * Adds the client's credentials to a request to a protocol endpoint.\n *\n * @internal\n */\nexport interface AuthioClientAuthenticator {\n readonly clientId: string;\n readonly method: AuthioTokenEndpointAuthMethod;\n apply(form: URLSearchParams, headers: Headers): Promise<void>;\n}\n\n/**\n * Builds the HTTP Basic value for a client id and secret, escaping both first as RFC 6749 §2.3.1 asks.\n */\nexport function toBasicAuthorization(clientId: string, clientSecret: string): string {\n const bytes = new TextEncoder().encode(`${escapeDataString(clientId)}:${escapeDataString(clientSecret)}`);\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return `Basic ${btoa(binary)}`;\n}\n\n/**\n * Validates the credential settings and returns the authenticator.\n *\n * @throws AuthioConfigurationError when a setting the method needs is missing.\n * @internal\n */\nexport function createClientAuthenticator(settings: AuthioClientCredentialsSettings, connection: AuthioConnection): AuthioClientAuthenticator {\n const clientId = settings.clientId?.trim();\n\n if (!clientId) throw new AuthioConfigurationError(\"The Authio clientId is required.\");\n\n const hasKey = settings.clientPrivateKey !== undefined || !!settings.clientPrivateKeyPath;\n const method: AuthioTokenEndpointAuthMethod =\n settings.tokenEndpointAuthMethod ?? (settings.clientSecret ? \"client_secret_basic\" : hasKey ? \"private_key_jwt\" : \"none\");\n\n if (!(AuthioTokenEndpointAuthMethods as readonly string[]).includes(method))\n throw new AuthioConfigurationError(`The Authio tokenEndpointAuthMethod '${String(method)}' is not one of ${AuthioTokenEndpointAuthMethods.join(\", \")}.`);\n\n if ((method === \"client_secret_basic\" || method === \"client_secret_post\") && !settings.clientSecret)\n throw new AuthioConfigurationError(`The Authio clientSecret is required with ${method}.`);\n\n if (method === \"private_key_jwt\" && !hasKey)\n throw new AuthioConfigurationError(\"private_key_jwt needs clientPrivateKey or clientPrivateKeyPath.\");\n\n const lifetimeMs = seconds(settings.clientAssertionLifetime, AuthioDefaults.ClientAssertionLifetime, \"clientAssertionLifetime\");\n\n if (lifetimeMs <= 0 || lifetimeMs > AuthioDefaults.MaxClientAssertionLifetime * 1000)\n throw new AuthioConfigurationError(\n `The Authio clientAssertionLifetime must be more than 0 and at most ${AuthioDefaults.MaxClientAssertionLifetime} seconds.`,\n );\n\n const loadKey = method === \"private_key_jwt\" ? createKeyLoader(settings) : undefined;\n const secret = async () => {\n const value = typeof settings.clientSecret === \"function\" ? await settings.clientSecret() : settings.clientSecret;\n\n if (typeof value !== \"string\" || !value) throw new AuthioConfigurationError(\"The Authio clientSecret function returned no secret.\");\n\n return value;\n };\n\n return {\n clientId,\n method,\n async apply(form, headers) {\n switch (method) {\n case \"client_secret_basic\":\n headers.set(\"authorization\", toBasicAuthorization(clientId, await secret()));\n return;\n case \"client_secret_post\":\n form.set(\"client_id\", clientId);\n form.set(\"client_secret\", await secret());\n return;\n case \"private_key_jwt\":\n form.set(\"client_id\", clientId);\n form.set(\"client_assertion_type\", \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\");\n form.set(\"client_assertion\", await buildAssertion(clientId, connection, lifetimeMs, await loadKey!()));\n return;\n default:\n form.set(\"client_id\", clientId);\n }\n },\n };\n}\n\n/**\n * Signs a client assertion: `iss` = `sub` = the client id, `aud` = the issuer, `iat` = `nbf` = now,\n * `exp` = now + lifetime, a 128-bit random `jti`.\n *\n * @internal\n */\nexport async function buildAssertion(clientId: string, connection: AuthioConnection, lifetimeMs: number, signing: AuthioSigningKey): Promise<string> {\n const now = Math.floor(connection.clock.now() / 1000);\n const jti = [...crypto.getRandomValues(new Uint8Array(16))].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n return new SignJWT({ jti })\n .setProtectedHeader({ alg: signing.algorithm, typ: \"JWT\", ...(signing.keyId ? { kid: signing.keyId } : {}) })\n .setIssuer(clientId)\n .setSubject(clientId)\n .setAudience(connection.issuer)\n .setIssuedAt(now)\n .setNotBefore(now)\n .setExpirationTime(now + Math.floor(lifetimeMs / 1000))\n .sign(signing.key);\n}\n\nfunction createKeyLoader(settings: AuthioClientCredentialsSettings): () => Promise<AuthioSigningKey> {\n if (settings.clientPrivateKey !== undefined) {\n let loaded: Promise<AuthioSigningKey> | undefined;\n\n return () => {\n loaded ??= importSigningKey(settings.clientPrivateKey!, settings.clientSigningAlgorithm, settings.clientKeyId, \"clientPrivateKey\");\n loaded.catch(() => {\n loaded = undefined;\n });\n return loaded;\n };\n }\n\n const path = settings.clientPrivateKeyPath!;\n let current: { written: number; key: Promise<AuthioSigningKey> } | undefined;\n\n return async () => {\n const nodeCrypto = await loadNodeCrypto();\n\n if (!nodeCrypto) throw new AuthioConfigurationError(\"clientPrivateKeyPath needs Node; pass clientPrivateKey instead.\");\n\n const { readFile, stat } = await import(\"node:fs/promises\");\n let written: number;\n\n try {\n written = (await stat(path)).mtimeMs;\n } catch (error) {\n throw new AuthioConfigurationError(`clientPrivateKeyPath '${path}' could not be read.`, { cause: error });\n }\n\n if (!current || current.written !== written) {\n const key = readFile(path, \"utf8\").then((pem) =>\n importSigningKey(pem, settings.clientSigningAlgorithm, settings.clientKeyId, `clientPrivateKeyPath '${path}'`),\n );\n\n current = { written, key };\n key.catch(() => {\n if (current?.key === key) current = undefined;\n });\n }\n\n return current.key;\n };\n}\n","import { compactDecrypt, decodeProtectedHeader, errors, importJWK, importPKCS8, type CryptoKey, type JWK } from \"jose\";\nimport { AuthioConfigurationError, AuthioTokenValidationError } from \"./errors.js\";\nimport { loadNodeCrypto } from \"./keys.js\";\n\n/**\n * The client's own encryption key, the pair Authio encrypts the client's tokens and UserInfo to: the private JWK\n * Authio hands over when it generates the pair (object or JSON text), or a PEM private key (PKCS#8 or PKCS#1 RSA).\n */\nexport type AuthioEncryptionKey = string | JWK;\n\n/**\n * Where the encryption key comes from: the key itself, or a function returning it (read again on every new\n * algorithm, so a rotated key is picked up).\n */\nexport type AuthioEncryptionKeySource = AuthioEncryptionKey | (() => AuthioEncryptionKey | Promise<AuthioEncryptionKey>);\n\n/**\n * Opens a compact JWE and returns its plaintext; a token that is not a JWE comes back unchanged.\n *\n * @throws AuthioTokenValidationError with `legacy_algorithm` for RSA1_5 and `decryption_failed` when the key cannot\n * open it.\n */\nexport type AuthioTokenDecrypter = (token: string) => Promise<string>;\n\n/**\n * The key management algorithms Authio encrypts with, and this SDK decrypts.\n */\nexport const AuthioKeyManagementAlgorithms = [\"RSA-OAEP\", \"RSA-OAEP-256\"] as const;\n\n/**\n * Key management algorithms Authio may still use for clients registered long ago. Node and WebCrypto cannot decrypt\n * RSA1_5 (PKCS#1 v1.5), so this SDK refuses it even with `allowLegacyEncryptionAlgorithms`.\n */\nexport const AuthioLegacyKeyManagementAlgorithms = [\"RSA1_5\"] as const;\n\n/**\n * The content encryption algorithms Authio encrypts with to a client's own key, the default `encryptionMethods`.\n */\nexport const AuthioContentEncryptionAlgorithms = [\"A128CBC-HS256\", \"A192CBC-HS384\", \"A256CBC-HS512\"] as const;\n\n/**\n * Every content encryption algorithm `encryptionMethods` may list: the CBC-HS ones and AES-GCM.\n */\nexport const AuthioSupportedContentEncryptionAlgorithms = [...AuthioContentEncryptionAlgorithms, \"A128GCM\", \"A192GCM\", \"A256GCM\"] as const;\n\n/**\n * Options of the decrypter.\n */\nexport interface AuthioTokenDecrypterOptions {\n /** The setting the key came from, named in errors. Defaults to `clientEncryptionKey`. */\n setting?: string;\n /**\n * Accepted for parity with the other Authio SDKs. RSA1_5 stays refused here, with an error saying so, because\n * neither Node nor WebCrypto can decrypt PKCS#1 v1.5.\n */\n allowLegacyEncryptionAlgorithms?: boolean;\n /**\n * The key management algorithms (`alg`) accepted, as registered for the client in Authio. Defaults to RSA-OAEP and\n * RSA-OAEP-256. RSA1_5 cannot be listed: neither Node nor WebCrypto can decrypt it.\n */\n encryptionAlgorithms?: readonly string[];\n /** The content encryption algorithms (`enc`) accepted. Defaults to A128CBC-HS256, A192CBC-HS384 and A256CBC-HS512. */\n encryptionMethods?: readonly string[];\n}\n\nconst rsaAlgorithmIdentifier = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00];\n\n/**\n * Whether a value is a compact JWE (five segments).\n */\nexport function isAuthioTokenEncrypted(token: unknown): token is string {\n return typeof token === \"string\" && token.split(\".\").length === 5;\n}\n\n/**\n * Creates a decrypter for the client's own encryption key. Keys are imported once per algorithm.\n *\n * @param key The key, a function returning it, or `undefined` when none is configured: an encrypted token then throws.\n * @param options The setting name for errors, and the legacy algorithm switch. A string is taken as the setting name.\n */\nexport function createAuthioTokenDecrypter(\n key: AuthioEncryptionKeySource | undefined,\n options: AuthioTokenDecrypterOptions | string = {},\n): AuthioTokenDecrypter {\n const settings: AuthioTokenDecrypterOptions = typeof options === \"string\" ? { setting: options } : options;\n const setting = settings.setting ?? \"clientEncryptionKey\";\n const keyManagementAlgorithms = resolveAllowlist(settings.encryptionAlgorithms, AuthioKeyManagementAlgorithms, AuthioKeyManagementAlgorithms, \"encryptionAlgorithms\");\n const contentEncryptionAlgorithms = resolveAllowlist(\n settings.encryptionMethods,\n AuthioContentEncryptionAlgorithms,\n AuthioSupportedContentEncryptionAlgorithms,\n \"encryptionMethods\",\n );\n const imported = new Map<string, Promise<CryptoKey | Uint8Array>>();\n\n const importFor = (algorithm: string) => {\n let pending = imported.get(algorithm);\n\n if (!pending) {\n pending = Promise.resolve(typeof key === \"function\" ? key() : key!).then((value) => importDecryptionKey(value, algorithm, setting));\n imported.set(algorithm, pending);\n pending.catch(() => imported.delete(algorithm));\n }\n\n return pending;\n };\n\n return async (token) => {\n if (!isAuthioTokenEncrypted(token)) return token;\n\n const algorithm = algorithmOf(token);\n\n if ((AuthioLegacyKeyManagementAlgorithms as readonly string[]).includes(algorithm))\n throw new AuthioTokenValidationError(\n \"legacy_algorithm\",\n settings.allowLegacyEncryptionAlgorithms\n ? \"The token is encrypted with RSA1_5 (PKCS#1 v1.5), which Node and WebCrypto cannot decrypt even with allowLegacyEncryptionAlgorithms; register RSA-OAEP-256 as the client's encryption algorithm in Authio.\"\n : \"The token is encrypted with the legacy RSA1_5 algorithm, which is refused; register RSA-OAEP-256 as the client's encryption algorithm in Authio.\",\n );\n\n if (!keyManagementAlgorithms.includes(algorithm))\n throw new AuthioTokenValidationError(\n \"decryption_failed\",\n `The token is encrypted with '${algorithm}', and encryptionAlgorithms accepts ${keyManagementAlgorithms.join(\" or \")}.`,\n );\n\n const method = contentMethodOf(token);\n\n if (!contentEncryptionAlgorithms.includes(method))\n throw new AuthioTokenValidationError(\n \"decryption_failed\",\n `The token's content is encrypted with '${method}', and encryptionMethods accepts ${contentEncryptionAlgorithms.join(\" or \")}.`,\n );\n\n if (key === undefined || key === null || key === \"\")\n throw new AuthioTokenValidationError(\n \"decryption_failed\",\n `Authio encrypted this token to the client's own key; set ${setting} to the private key Authio showed when it generated the pair.`,\n );\n\n try {\n const { plaintext } = await compactDecrypt(token, (header) => importFor(header.alg), {\n keyManagementAlgorithms: [...keyManagementAlgorithms],\n contentEncryptionAlgorithms: [...contentEncryptionAlgorithms],\n });\n\n return new TextDecoder().decode(plaintext);\n } catch (error) {\n if (error instanceof AuthioConfigurationError) throw error;\n if (error instanceof errors.JOSEError)\n throw new AuthioTokenValidationError(\"decryption_failed\", `The token could not be decrypted with ${setting}: ${error.message}`, { cause: error });\n throw error;\n }\n };\n}\n\n/**\n * Reads the client's encryption key from a PEM or JWK file (Node only), again whenever the file changes.\n *\n * @internal\n */\nexport function encryptionKeyFromFile(path: string, setting = \"clientEncryptionKeyPath\"): () => Promise<AuthioEncryptionKey> {\n let current: { written: number; key: Promise<string> } | undefined;\n\n return async () => {\n const nodeCrypto = await loadNodeCrypto();\n\n if (!nodeCrypto) throw new AuthioConfigurationError(`${setting} needs Node; pass clientEncryptionKey instead.`);\n\n const { readFile, stat } = await import(\"node:fs/promises\");\n let written: number;\n\n try {\n written = (await stat(path)).mtimeMs;\n } catch (error) {\n throw new AuthioConfigurationError(`${setting} '${path}' could not be read.`, { cause: error });\n }\n\n if (!current || current.written !== written) current = { written, key: readFile(path, \"utf8\") };\n\n return current.key;\n };\n}\n\nfunction algorithmOf(token: string): string {\n try {\n return String(decodeProtectedHeader(token).alg ?? \"\");\n } catch (error) {\n throw new AuthioTokenValidationError(\"decryption_failed\", \"The encrypted token's header could not be read.\", { cause: error });\n }\n}\n\nfunction contentMethodOf(token: string): string {\n try {\n return String(decodeProtectedHeader(token).enc ?? \"\");\n } catch (error) {\n throw new AuthioTokenValidationError(\"decryption_failed\", \"The encrypted token's header could not be read.\", { cause: error });\n }\n}\n\nfunction resolveAllowlist(configured: readonly string[] | undefined, defaults: readonly string[], supported: readonly string[], setting: string): readonly string[] {\n if (configured === undefined || configured.length === 0) return defaults;\n\n for (const value of configured) {\n if ((AuthioLegacyKeyManagementAlgorithms as readonly string[]).includes(value))\n throw new AuthioConfigurationError(\n `${setting} cannot hold ${value}: Node and WebCrypto cannot decrypt PKCS#1 v1.5; register RSA-OAEP-256 as the client's encryption algorithm in Authio.`,\n );\n\n if (!supported.includes(value)) throw new AuthioConfigurationError(`${setting} holds '${value}'; it accepts ${supported.join(\", \")}.`);\n }\n\n return [...new Set(configured)];\n}\n\nasync function importDecryptionKey(key: AuthioEncryptionKey, algorithm: string, setting: string): Promise<CryptoKey | Uint8Array> {\n try {\n if (typeof key !== \"string\") return await importPrivateJwk(key, algorithm, setting);\n\n const text = key.trim();\n\n return text.startsWith(\"{\")\n ? await importPrivateJwk(JSON.parse(text) as JWK, algorithm, setting)\n : await importPKCS8(toPkcs8(text), algorithm);\n } catch (error) {\n if (error instanceof AuthioConfigurationError) throw error;\n throw new AuthioConfigurationError(`${setting} is neither a private JWK nor a PEM private key.`, { cause: error });\n }\n}\n\nfunction importPrivateJwk(jwk: JWK, algorithm: string, setting: string): Promise<CryptoKey | Uint8Array> {\n if (!jwk.d) throw new AuthioConfigurationError(`${setting} is a JWK without its private parameters; only the private key decrypts.`);\n\n return importJWK({ ...jwk, alg: algorithm, use: \"enc\", key_ops: undefined }, algorithm);\n}\n\nfunction toPkcs8(pem: string): string {\n const normalized = pem.replace(/\\\\n/g, \"\\n\").trim();\n\n if (!normalized.includes(\"BEGIN RSA PRIVATE KEY\")) return normalized;\n\n const pkcs1 = fromBase64(normalized.replace(/-----[^-]+-----|\\s/g, \"\"));\n const body = [0x02, 0x01, 0x00, ...rsaAlgorithmIdentifier, 0x04, ...derLength(pkcs1.length), ...pkcs1];\n const der = Uint8Array.from([0x30, ...derLength(body.length), ...body]);\n const lines = toBase64(der).match(/.{1,64}/g) ?? [];\n\n return `-----BEGIN PRIVATE KEY-----\\n${lines.join(\"\\n\")}\\n-----END PRIVATE KEY-----`;\n}\n\nfunction derLength(length: number): number[] {\n if (length < 0x80) return [length];\n\n const bytes: number[] = [];\n\n for (let rest = length; rest > 0; rest >>= 8) bytes.unshift(rest & 0xff);\n\n return [0x80 | bytes.length, ...bytes];\n}\n\nfunction fromBase64(text: string): Uint8Array {\n return Uint8Array.from(atob(text), (character) => character.charCodeAt(0));\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n}\n","import { createRemoteJWKSet, customFetch, decodeProtectedHeader, errors, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from \"jose\";\nimport { AuthioAsymmetricAlgorithms, AuthioClaimTypes, AuthioDefaults, AuthioHmacAlgorithms, AuthioHmacMinimumSecretBytes } from \"./constants.js\";\nimport type { AuthioDiscoveryClient } from \"./discovery.js\";\nimport { AuthioConfigurationError, AuthioError, AuthioTokenValidationError } from \"./errors.js\";\nimport { isAuthioTokenEncrypted, type AuthioTokenDecrypter } from \"./encryption.js\";\nimport type { AuthioConnection } from \"./options.js\";\n\n/**\n * The claims of a validated ID token. Authio writes `typ` = `ID`, `sid`, `auth_time`, `acr`, `amr`, `nonce` and\n * `at_hash`, besides the profile claims of the granted scopes.\n */\nexport interface AuthioIdTokenClaims extends JWTPayload {\n sub: string;\n sid?: string;\n nonce?: string;\n auth_time?: number;\n acr?: string;\n amr?: string[];\n at_hash?: string;\n [claim: string]: unknown;\n}\n\n/**\n * A validated back-channel logout token: end the sessions of `subject`, or the one session `sessionId` names.\n */\nexport interface AuthioLogoutToken {\n /** `sub`, when the token names the person. */\n readonly subject: string | undefined;\n /** `sid`, when the token names one session. */\n readonly sessionId: string | undefined;\n /** `jti`. */\n readonly tokenId: string | undefined;\n /** Every claim. */\n readonly claims: Readonly<JWTPayload>;\n}\n\n/**\n * The realm's signing keys, read from the discovery document's `jwks_uri` and cached; an unknown `kid` makes it read\n * them again (at most once every 30 seconds).\n *\n * @internal\n */\nexport type AuthioSigningKeys = (signal?: AbortSignal) => Promise<JWTVerifyGetKey>;\n\n/**\n * What a JWT is checked against.\n *\n * @internal\n */\nexport interface AuthioJwtExpectations {\n readonly issuer: string;\n /** The accepted audiences; `aud` is not checked when absent. */\n readonly audiences?: readonly string[];\n readonly algorithms?: readonly string[];\n /** Seconds. */\n readonly clockSkew?: number;\n /** Milliseconds since the epoch. */\n readonly now: number;\n readonly requiredClaims?: readonly string[];\n}\n\n/**\n * Creates the cached reader of the realm's signing keys.\n *\n * @internal\n */\nexport function createAuthioSigningKeys(connection: AuthioConnection, discovery: AuthioDiscoveryClient): AuthioSigningKeys {\n let keys: { uri: string; set: JWTVerifyGetKey } | undefined;\n\n return async (signal) => {\n const document = await discovery.get(signal);\n const uri = document.jwks_uri;\n\n if (!uri) throw new AuthioError(\"The Authio discovery document has no jwks_uri.\");\n\n if (!keys || keys.uri !== uri)\n keys = { uri, set: createRemoteJWKSet(new URL(uri), { [customFetch]: connection.fetch, timeoutDuration: connection.httpTimeoutMs }) };\n\n return keys.set;\n };\n}\n\n/**\n * Verifies a signed JWT: signature by a realm key with an accepted algorithm, `iss`, `aud`, `exp` (required) and\n * `nbf` with the clock skew.\n *\n * @throws AuthioTokenValidationError naming why the token was refused.\n * @internal\n */\nexport async function verifyAuthioJwt(token: string, keys: JWTVerifyGetKey, expected: AuthioJwtExpectations): Promise<{ payload: JWTPayload; header: Record<string, unknown> }> {\n if (!looksLikeJws(token))\n throw new AuthioTokenValidationError(\"reference_token\", \"The token is not a JWT; only introspection can resolve it ('introspectionOnly').\");\n\n try {\n const { payload, protectedHeader } = await jwtVerify(token, keys, {\n issuer: expected.issuer,\n audience: expected.audiences ? [...expected.audiences] : undefined,\n algorithms: [...(expected.algorithms && expected.algorithms.length > 0 ? expected.algorithms : AuthioAsymmetricAlgorithms)],\n clockTolerance: expected.clockSkew ?? AuthioDefaults.ClockSkew,\n requiredClaims: [...new Set([\"exp\", ...(expected.requiredClaims ?? [])])],\n currentDate: new Date(expected.now),\n });\n\n return { payload, header: protectedHeader as Record<string, unknown> };\n } catch (error) {\n if (error instanceof AuthioConfigurationError) throw error;\n\n throw toTokenValidationError(error, expected.audiences ?? [], token);\n }\n}\n\n/**\n * Wraps the realm's keys so an HS256, HS384 or HS512 signature is verified with the client secret instead (OpenID\n * Connect Core §10.1: the octets of its UTF-8 form). Only reached for an algorithm the allowlist accepts, so an HS*\n * token is verified with the secret only when `idTokenSignedResponseAlg` names that algorithm.\n *\n * @internal\n */\nexport function withClientSecret(keys: JWTVerifyGetKey, secret: (() => Promise<string>) | undefined): JWTVerifyGetKey {\n if (!secret) return keys;\n\n return async (header, token) => {\n const algorithm = String(header.alg);\n\n if (!(AuthioHmacAlgorithms as readonly string[]).includes(algorithm)) return keys(header, token);\n\n const bytes = new TextEncoder().encode(await secret());\n\n requireHmacSecretLength(algorithm, bytes.length);\n\n return bytes;\n };\n}\n\n/**\n * Refuses a client secret shorter than the HS* algorithm's hash output (RFC 7518 §3.2).\n *\n * @throws AuthioConfigurationError naming the algorithm and both lengths.\n * @internal\n */\nexport function requireHmacSecretLength(algorithm: string, length: number): void {\n const minimum = AuthioHmacMinimumSecretBytes[algorithm as keyof typeof AuthioHmacMinimumSecretBytes];\n\n if (minimum !== undefined && length < minimum)\n throw new AuthioConfigurationError(\n `The Authio clientSecret has ${length} bytes, and ${algorithm} needs at least ${minimum} (RFC 7518 §3.2): Authio refuses a shorter secret for it.`,\n );\n}\n\n/**\n * The algorithms a token is accepted with: the one configured, else the asymmetric ones the discovery document\n * announces for it, else every asymmetric one. HS* is never accepted unless configured.\n *\n * @internal\n */\nexport function acceptedSigningAlgorithms(configured: string | undefined, announced: unknown): readonly string[] {\n if (configured) return [configured];\n\n const asymmetric = (Array.isArray(announced) ? announced : []).filter(\n (algorithm): algorithm is string => typeof algorithm === \"string\" && (AuthioAsymmetricAlgorithms as readonly string[]).includes(algorithm),\n );\n\n return asymmetric.length > 0 ? asymmetric : AuthioAsymmetricAlgorithms;\n}\n\n/**\n * Turns a `jose` failure into the refusal it stands for, worded as ASP.NET Core's bearer handler words it.\n *\n * @internal\n */\nexport function toTokenValidationError(error: unknown, audiences: readonly string[], token: string): AuthioTokenValidationError {\n if (error instanceof AuthioTokenValidationError) return error;\n\n const refuse = (reason: ConstructorParameters<typeof AuthioTokenValidationError>[0], message: string) =>\n new AuthioTokenValidationError(reason, message, { cause: error });\n\n if (error instanceof errors.JWTExpired) {\n const exp = error.payload.exp;\n\n return refuse(\"expired\", typeof exp === \"number\" ? `The token expired at '${new Date(exp * 1000).toISOString()}'` : \"The token has expired\");\n }\n\n if (error instanceof errors.JWTClaimValidationFailed) {\n switch (error.claim) {\n case \"aud\":\n return refuse(\"invalid_audience\", describeAudience([error.payload.aud ?? []].flat(), audiences));\n case \"iss\":\n return refuse(\"invalid_issuer\", `The issuer '${error.payload.iss ?? \"\"}' is invalid`);\n case \"nbf\":\n return refuse(\n \"not_yet_valid\",\n typeof error.payload.nbf === \"number\" ? `The token is not valid before '${new Date(error.payload.nbf * 1000).toISOString()}'` : \"The token is not valid yet\",\n );\n case \"exp\":\n return refuse(\"expired\", \"The token has no expiration\");\n default:\n return refuse(\"malformed\", `The token's ${error.claim} claim is invalid`);\n }\n }\n\n if (error instanceof errors.JWSSignatureVerificationFailed) return refuse(\"invalid_signature\", \"The signature is invalid\");\n if (error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JWKSMultipleMatchingKeys)\n return refuse(\"invalid_signature\", \"The signature key was not found\");\n if (error instanceof errors.JOSEAlgNotAllowed) return refuse(\"invalid_algorithm\", `The algorithm '${algorithmOf(token)}' is not available`);\n if (error instanceof errors.JWKSTimeout || error instanceof errors.JWKSInvalid)\n return refuse(\"signing_keys_unavailable\", \"Authio could not be reached to read its signing keys.\");\n if (error instanceof errors.JWTInvalid || error instanceof errors.JWSInvalid) return refuse(\"malformed\", \"The token is malformed\");\n if (error instanceof errors.JOSEError) return refuse(\"malformed\", error.message);\n\n return refuse(\"signing_keys_unavailable\", \"Authio could not be reached to read its signing keys.\");\n}\n\n/**\n * The `at_hash` / `c_hash` of a value for a signing algorithm: the left half of its SHA-256, SHA-384 or SHA-512\n * digest, base64url-encoded (OpenID Connect Core §3.1.3.6).\n */\nexport async function computeAuthioTokenHash(value: string, algorithm: string): Promise<string> {\n const size = /(\\d{3})$/.exec(algorithm)?.[1];\n const hash = size === \"384\" ? \"SHA-384\" : size === \"512\" ? \"SHA-512\" : \"SHA-256\";\n const digest = new Uint8Array(await crypto.subtle.digest(hash, new TextEncoder().encode(value)));\n\n return toBase64Url(digest.subarray(0, digest.length / 2));\n}\n\n/**\n * Validates an ID token: decrypted first when it is a JWE, then signature, `iss`, `aud` = the client, `exp` with the\n * skew, payload `typ` = `ID`, `azp` when there are several audiences, `nonce`, `at_hash` and `auth_time` against\n * `maxAge`.\n *\n * @internal\n */\nexport async function validateAuthioIdToken(\n token: string,\n context: { keys: JWTVerifyGetKey; decrypt: AuthioTokenDecrypter; issuer: string; clientId: string; algorithms?: readonly string[]; clockSkew?: number; now: number },\n expectations: { nonce?: string; accessToken?: string; maxAge?: number } = {},\n): Promise<AuthioIdTokenClaims> {\n const signed = isAuthioTokenEncrypted(token) ? await context.decrypt(token) : token;\n const { payload, header } = await verifyAuthioJwt(signed, context.keys, {\n issuer: context.issuer,\n audiences: [context.clientId],\n algorithms: context.algorithms,\n clockSkew: context.clockSkew,\n now: context.now,\n requiredClaims: [\"sub\", \"iat\"],\n });\n const type = typeof payload.typ === \"string\" ? payload.typ : undefined;\n\n if (type !== undefined && type.toLowerCase() !== \"id\")\n throw new AuthioTokenValidationError(\"not_id_token\", `Only ID tokens are accepted; this token's typ is '${type}'.`);\n\n const audiences = [payload.aud ?? []].flat();\n\n if (audiences.length > 1 && payload.azp !== context.clientId)\n throw new AuthioTokenValidationError(\"invalid_audience\", `The ID token has several audiences and its azp is not '${context.clientId}'.`);\n\n if (expectations.nonce !== undefined && payload[AuthioClaimTypes.Nonce] !== expectations.nonce)\n throw new AuthioTokenValidationError(\n \"invalid_nonce\",\n payload[AuthioClaimTypes.Nonce] === undefined ? \"The ID token carries no nonce, although one was sent.\" : \"The ID token's nonce is not the one sent.\",\n );\n\n const atHash = payload[AuthioClaimTypes.AccessTokenHash];\n\n if (expectations.accessToken !== undefined && typeof atHash === \"string\") {\n const expected = await computeAuthioTokenHash(expectations.accessToken, String(header.alg ?? \"\"));\n\n if (expected !== atHash) throw new AuthioTokenValidationError(\"invalid_at_hash\", \"The ID token's at_hash does not match the access token.\");\n }\n\n if (expectations.maxAge !== undefined) {\n const authTime = payload[AuthioClaimTypes.AuthTime];\n const skew = context.clockSkew ?? AuthioDefaults.ClockSkew;\n\n if (typeof authTime !== \"number\")\n throw new AuthioTokenValidationError(\"authentication_too_old\", \"max_age was requested, and the ID token carries no auth_time.\");\n\n if ((authTime + expectations.maxAge + skew) * 1000 < context.now)\n throw new AuthioTokenValidationError(\n \"authentication_too_old\",\n `The person signed in at '${new Date(authTime * 1000).toISOString()}', more than ${expectations.maxAge} seconds ago.`,\n );\n }\n\n return payload as AuthioIdTokenClaims;\n}\n\n/**\n * Validates a back-channel logout token (OpenID Connect Back-Channel Logout 1.0 §2.6): header `typ` =\n * `logout+jwt`, signature, `iss`, `aud` = the client, `exp`, the back-channel event, no `nonce`, and `sub` or `sid`.\n *\n * @internal\n */\nexport async function validateAuthioLogoutToken(\n token: string,\n context: { keys: JWTVerifyGetKey; decrypt: AuthioTokenDecrypter; issuer: string; clientId: string; algorithms?: readonly string[]; clockSkew?: number; now: number },\n): Promise<AuthioLogoutToken> {\n const signed = isAuthioTokenEncrypted(token) ? await context.decrypt(token) : token;\n const invalid = (message: string) => new AuthioTokenValidationError(\"invalid_logout_token\", message);\n let headerType: string | undefined;\n\n try {\n const header = decodeProtectedHeader(signed);\n\n headerType = typeof header.typ === \"string\" ? header.typ.toLowerCase() : undefined;\n } catch (error) {\n throw new AuthioTokenValidationError(\"malformed\", \"The logout token is malformed\", { cause: error });\n }\n\n const { payload } = await verifyAuthioJwt(signed, context.keys, {\n issuer: context.issuer,\n audiences: [context.clientId],\n algorithms: context.algorithms,\n clockSkew: context.clockSkew,\n now: context.now,\n requiredClaims: [\"iat\"],\n });\n\n if (headerType !== AuthioDefaults.LogoutTokenType && headerType !== `application/${AuthioDefaults.LogoutTokenType}`)\n throw invalid(`The token's header typ is '${headerType ?? \"\"}', not '${AuthioDefaults.LogoutTokenType}'.`);\n\n const events = payload[AuthioClaimTypes.Events];\n\n if (!events || typeof events !== \"object\" || Array.isArray(events) || typeof (events as Record<string, unknown>)[AuthioDefaults.BackchannelLogoutEvent] !== \"object\")\n throw invalid(\"The token carries no back-channel logout event.\");\n\n if (payload[AuthioClaimTypes.Nonce] !== undefined) throw invalid(\"A logout token must not carry a nonce.\");\n\n const subject = typeof payload.sub === \"string\" && payload.sub ? payload.sub : undefined;\n const sessionId = typeof payload.sid === \"string\" && payload.sid ? payload.sid : undefined;\n\n if (!subject && !sessionId) throw invalid(\"The logout token names neither a subject nor a session.\");\n\n return Object.freeze({ subject, sessionId, tokenId: typeof payload.jti === \"string\" ? payload.jti : undefined, claims: Object.freeze({ ...payload }) });\n}\n\nfunction describeAudience(tokenAudiences: readonly string[], audiences: readonly string[]): string {\n const known = tokenAudiences.length === 0 ? \"\" : ` ${tokenAudiences.map((audience) => `'${audience}'`).join(\" and \")}`;\n const accepted = audiences.map((audience) => `'${audience}'`).join(\" or \");\n\n return audiences.length === 1\n ? `The token is not addressed to this API: its audience${known} is not ${accepted}. Request the token for that resource (RFC 8707).`\n : `The token is not addressed to this API: its audience${known} is not ${accepted}. Request the token for one of those resources (RFC 8707).`;\n}\n\nfunction looksLikeJws(token: string): boolean {\n const parts = token.split(\".\");\n\n return parts.length === 3 && parts[0]!.length > 0;\n}\n\nfunction algorithmOf(token: string): string {\n try {\n return String(decodeProtectedHeader(token).alg ?? \"\");\n } catch {\n return \"\";\n }\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n","import type { AuthioPrompt } from \"./constants.js\";\nimport { AuthioCallbackError, AuthioConfigurationError } from \"./errors.js\";\nimport { toScopeString } from \"./http.js\";\n\n/**\n * The PKCE method (RFC 7636). `S256` is the default; `plain` only when asked for, for a client that cannot hash.\n */\nexport type AuthioCodeChallengeMethod = \"S256\" | \"plain\";\n\n/**\n * What the client checks on an authorization round trip, as the client is registered in Authio: `pkce` sends a code\n * challenge and redeems the code with its verifier, `state` binds the callback to the request, `nonce` binds the ID\n * token to it. `none` is the same as an empty list. Nothing is checked unless listed.\n */\nexport type AuthioCheck = \"pkce\" | \"state\" | \"nonce\" | \"none\";\n\n/**\n * How Authio answers the authorization request: `query` (a redirect) or `web_message` (posted to the opener window).\n */\nexport type AuthioResponseMode = \"query\" | \"web_message\";\n\n/**\n * The checks every Authio library accepts.\n */\nexport const AuthioChecks = [\"pkce\", \"state\", \"nonce\", \"none\"] as const satisfies readonly AuthioCheck[];\n\n/**\n * A PKCE pair: send `codeChallenge` with the authorization request and `codeVerifier` with the code exchange.\n */\nexport interface AuthioPkcePair {\n readonly codeVerifier: string;\n readonly codeChallenge: string;\n readonly codeChallengeMethod: AuthioCodeChallengeMethod;\n}\n\n/**\n * What an authorization request asks Authio for. Every member is optional; `redirectUri` falls back to the client's.\n */\nexport interface AuthioAuthorizationRequest {\n /** Where Authio sends the person back. Defaults to the client's `redirectUri`. */\n redirectUri?: string;\n /** Defaults to `openid`. */\n scopes?: Iterable<string> | string;\n /** The resource server the access token is for (RFC 8707). */\n resource?: string;\n /** The organization (its handle) the sign-in is for. Authoritative: the person cannot switch to another one. */\n organization?: string;\n /** `none` (silent), `login`, `select_account`, `consent`; several are joined with spaces. */\n prompt?: AuthioPrompt | readonly AuthioPrompt[];\n /** Seconds the person's sign-in may be old; Authio asks again past it, and the ID token's `auth_time` is checked. */\n maxAge?: number;\n /** Authentication context classes asked for: `1` one factor, `2` several, `3` one of them phishing-resistant. */\n acrValues?: string | readonly string[];\n /** Pre-fills the identifier on the sign-in screen. */\n loginHint?: string;\n /** A previously issued ID token, naming the person whose session is renewed. */\n idTokenHint?: string;\n /** Languages of the hosted screens, most preferred first. */\n uiLocales?: string | readonly string[];\n /** `page` (default) or `popup`, the layout of the hosted screens. */\n display?: \"page\" | \"popup\";\n /** `query` or `web_message` (the answer posted to the opener window). Defaults to the client's `responseMode`. */\n responseMode?: AuthioResponseMode;\n /** Shorthand for `display: \"popup\"` with `responseMode: \"web_message\"`. */\n popup?: boolean;\n /** The alias of the identity provider to go straight to, skipping Authio's sign-in screen. */\n idpHint?: string;\n /** The checks of this request. Defaults to the client's `checks`. */\n checks?: readonly AuthioCheck[];\n /** The PKCE method, when `checks` holds `pkce`. Defaults to the client's `codeChallengeMethod`, else `S256`. */\n codeChallengeMethod?: AuthioCodeChallengeMethod;\n /** A `state` of your own for the `state` check (a random one otherwise); without the check it is sent unchecked. */\n state?: string;\n /** A `nonce` of your own for the `nonce` check (a random one otherwise); without the check it is sent unchecked. */\n nonce?: string;\n /** Further parameters, sent as given. */\n extraParameters?: Record<string, string | undefined>;\n}\n\n/**\n * What the application keeps between the authorization request and the callback (in its session, a cookie, …), to\n * check the callback and redeem the code.\n */\nexport interface AuthioAuthorizationTransaction {\n /** The checks the request was made with; the callback checks exactly these. */\n readonly checks: readonly Exclude<AuthioCheck, \"none\">[];\n /** With the `state` check. */\n readonly state?: string;\n /** With the `nonce` check. */\n readonly nonce?: string;\n /** With the `pkce` check. */\n readonly codeVerifier?: string;\n /** With the `pkce` check. */\n readonly codeChallengeMethod?: AuthioCodeChallengeMethod;\n readonly redirectUri: string;\n readonly resource?: string;\n readonly maxAge?: number;\n}\n\n/**\n * An authorization URL and the transaction to keep until the callback.\n */\nexport interface AuthioAuthorizationUrl {\n readonly url: string;\n readonly transaction: AuthioAuthorizationTransaction;\n}\n\n/**\n * A `WWW-Authenticate` bearer challenge, as an API answers it (RFC 6750, RFC 9470, RFC 9728).\n */\nexport interface AuthioBearerChallenge {\n readonly error: string | undefined;\n readonly errorDescription: string | undefined;\n /** `insufficient_scope`: the scopes required. */\n readonly scope: string | undefined;\n /** `insufficient_user_authentication`: the context classes to ask for. */\n readonly acrValues: string | undefined;\n /** `insufficient_user_authentication`: how old the sign-in may be, in seconds. */\n readonly maxAge: number | undefined;\n /** RFC 9728: where the API's protected resource metadata is. */\n readonly resourceMetadata: string | undefined;\n}\n\n/**\n * Creates a PKCE pair: a 256-bit random verifier and its S256 (or plain) challenge.\n */\nexport async function createAuthioPkce(method: AuthioCodeChallengeMethod = \"S256\"): Promise<AuthioPkcePair> {\n if (method !== \"S256\" && method !== \"plain\") throw new TypeError(`The PKCE method '${String(method)}' is not S256 or plain.`);\n\n const codeVerifier = randomValue(32);\n const codeChallenge =\n method === \"plain\" ? codeVerifier : toBase64Url(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(codeVerifier))));\n\n return { codeVerifier, codeChallenge, codeChallengeMethod: method };\n}\n\n/**\n * A random, URL-safe value of `bytes` random bytes, for `state` and `nonce`.\n */\nexport function randomValue(bytes = 32): string {\n return toBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\n/**\n * The checks of a list, without duplicates and without `none`.\n *\n * @throws AuthioConfigurationError naming a value that is not a check.\n * @internal\n */\nexport function resolveChecks(checks: readonly AuthioCheck[] | undefined, setting = \"checks\"): readonly Exclude<AuthioCheck, \"none\">[] {\n const resolved: Exclude<AuthioCheck, \"none\">[] = [];\n\n for (const check of checks ?? []) {\n if (!(AuthioChecks as readonly string[]).includes(check))\n throw new AuthioConfigurationError(`The Authio ${setting} value '${String(check)}' is not one of ${AuthioChecks.join(\", \")}.`);\n\n if (check !== \"none\" && !resolved.includes(check)) resolved.push(check);\n }\n\n return Object.freeze(resolved);\n}\n\n/**\n * Builds the authorization URL and its transaction. Only the listed checks generate their parameter.\n *\n * @internal\n */\nexport async function buildAuthorizationUrl(\n endpoint: string,\n clientId: string,\n request: AuthioAuthorizationRequest & { redirectUri: string },\n): Promise<AuthioAuthorizationUrl> {\n const checks = resolveChecks(request.checks);\n const pkce = checks.includes(\"pkce\") ? await createAuthioPkce(request.codeChallengeMethod ?? \"S256\") : undefined;\n const state = checks.includes(\"state\") ? request.state?.trim() || randomValue() : undefined;\n const nonce = checks.includes(\"nonce\") ? request.nonce?.trim() || randomValue() : undefined;\n\n if (request.maxAge !== undefined && (!Number.isInteger(request.maxAge) || request.maxAge < 0))\n throw new RangeError(\"maxAge must be a non-negative whole number of seconds.\");\n\n const display = request.popup ? \"popup\" : request.display;\n const responseMode = request.popup ? \"web_message\" : request.responseMode;\n\n if (responseMode !== undefined && responseMode !== \"query\" && responseMode !== \"web_message\")\n throw new AuthioConfigurationError(`The Authio responseMode '${String(responseMode)}' is not query or web_message.`);\n\n const url = new URL(endpoint);\n const parameters: Record<string, string | undefined> = {\n ...request.extraParameters,\n response_type: \"code\",\n client_id: clientId,\n redirect_uri: request.redirectUri,\n scope: toScopeString(request.scopes) ?? \"openid\",\n state: state ?? request.state?.trim(),\n nonce: nonce ?? request.nonce?.trim(),\n code_challenge: pkce?.codeChallenge,\n code_challenge_method: pkce?.codeChallengeMethod,\n resource: request.resource,\n organization: request.organization,\n prompt: joined(request.prompt),\n max_age: request.maxAge?.toString(),\n acr_values: joined(request.acrValues),\n login_hint: request.loginHint,\n id_token_hint: request.idTokenHint,\n ui_locales: joined(request.uiLocales),\n display,\n response_mode: responseMode,\n idp_hint: request.idpHint,\n };\n\n for (const [name, value] of Object.entries(parameters)) if (value !== undefined && value !== \"\") url.searchParams.set(name, value);\n\n return {\n url: url.toString(),\n transaction: Object.freeze({\n checks,\n ...(state ? { state } : {}),\n ...(nonce ? { nonce } : {}),\n ...(pkce ? { codeVerifier: pkce.codeVerifier, codeChallengeMethod: pkce.codeChallengeMethod } : {}),\n redirectUri: request.redirectUri,\n ...(request.resource ? { resource: request.resource } : {}),\n ...(request.maxAge !== undefined ? { maxAge: request.maxAge } : {}),\n }),\n };\n}\n\n/**\n * Reads the parameters of an authorization callback: a full URL, its query, a `URLSearchParams`, or an object (a\n * `web_message` answer, or a parsed query).\n *\n * @internal\n */\nexport function readCallbackParameters(callback: string | URL | URLSearchParams | Readonly<Record<string, unknown>>): Record<string, string> {\n if (callback instanceof URLSearchParams) return Object.fromEntries(callback);\n if (callback instanceof URL) return Object.fromEntries(callback.searchParams);\n\n if (typeof callback === \"string\") {\n const text = callback.trim();\n const query = /^[a-z][a-z0-9+.-]*:/i.test(text) ? new URL(text).search : text.slice(text.indexOf(\"?\") + 1);\n\n return Object.fromEntries(new URLSearchParams(query));\n }\n\n const parameters: Record<string, string> = {};\n\n for (const [name, value] of Object.entries(callback ?? {})) {\n const first = Array.isArray(value) ? value[0] : value;\n\n if (typeof first === \"string\") parameters[name] = first;\n }\n\n return parameters;\n}\n\n/**\n * A front-channel logout request (OpenID Connect Front-Channel Logout 1.0): Authio loads the client's\n * `frontchannel_logout_uri` in an iframe, with `iss` and `sid` when the client requires the session.\n */\nexport interface AuthioFrontChannelLogout {\n /** `sid`: the Authio session that ended, when Authio sent it. */\n readonly sessionId: string | undefined;\n /** `iss`, when Authio sent it; always this client's issuer. */\n readonly issuer: string | undefined;\n}\n\n/**\n * Reads a front-channel logout request: `iss` and `sid` come together, and `iss` must be the issuer.\n *\n * @throws AuthioCallbackError with `issuer_mismatch` for another issuer, `missing_issuer` for a `sid` without `iss`.\n */\nexport function readAuthioFrontChannelLogout(\n request: string | URL | URLSearchParams | Readonly<Record<string, unknown>>,\n issuer: string,\n): AuthioFrontChannelLogout {\n const parameters = readCallbackParameters(request);\n const sessionId = parameters.sid?.trim() || undefined;\n const sentIssuer = parameters.iss?.trim() || undefined;\n\n if (sentIssuer !== undefined && sentIssuer.replace(/\\/+$/, \"\") !== issuer.replace(/\\/+$/, \"\"))\n throw new AuthioCallbackError(\"issuer_mismatch\", `The front-channel logout comes from the issuer '${sentIssuer}', not '${issuer}'.`);\n\n if (sessionId !== undefined && sentIssuer === undefined)\n throw new AuthioCallbackError(\"missing_issuer\", \"The front-channel logout names a sid without its iss.\");\n\n return Object.freeze({ sessionId, issuer: sentIssuer });\n}\n\n/**\n * Parses a `WWW-Authenticate` bearer challenge, or `undefined` when the header holds none.\n */\nexport function parseAuthioBearerChallenge(header: string | null | undefined): AuthioBearerChallenge | undefined {\n if (!header || !/^\\s*bearer(\\s|$)/i.test(header)) return undefined;\n\n const values: Record<string, string> = {};\n\n for (const match of header.matchAll(/([a-zA-Z_]+)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"|([a-zA-Z_]+)\\s*=\\s*([^,\\s]+)/g)) {\n const name = (match[1] ?? match[3] ?? \"\").toLowerCase();\n\n values[name] ??= (match[2] ?? match[4] ?? \"\").replace(/\\\\(.)/g, \"$1\");\n }\n\n const maxAge = values.max_age !== undefined && /^\\d+$/.test(values.max_age) ? Number(values.max_age) : undefined;\n\n return {\n error: values.error,\n errorDescription: values.error_description,\n scope: values.scope,\n acrValues: values.acr_values,\n maxAge,\n resourceMetadata: values.resource_metadata,\n };\n}\n\nfunction joined(value: string | readonly string[] | undefined): string | undefined {\n if (value === undefined) return undefined;\n\n const text = (typeof value === \"string\" ? [value] : [...value]).map((item) => item.trim()).filter(Boolean).join(\" \");\n\n return text || undefined;\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n","import type { JWTPayload, JWTVerifyGetKey } from \"jose\";\nimport {\n buildAuthorizationUrl,\n parseAuthioBearerChallenge,\n readAuthioFrontChannelLogout,\n readCallbackParameters,\n resolveChecks,\n type AuthioAuthorizationRequest,\n type AuthioAuthorizationTransaction,\n type AuthioAuthorizationUrl,\n type AuthioBearerChallenge,\n type AuthioCheck,\n type AuthioCodeChallengeMethod,\n type AuthioFrontChannelLogout,\n type AuthioResponseMode,\n} from \"./authorization.js\";\nimport { createClientAuthenticator, type AuthioClientAuthenticator, type AuthioClientCredentialsSettings } from \"./client-authentication.js\";\nimport { AuthioAsymmetricAlgorithms, AuthioDefaults, AuthioGrantTypes, AuthioHmacAlgorithms, AuthioOAuthErrors, AuthioTokenTypes } from \"./constants.js\";\nimport { createAuthioDiscoveryClient, requireEndpoint, type AuthioDiscoveryClient, type AuthioDiscoveryDocument } from \"./discovery.js\";\nimport {\n createAuthioTokenDecrypter,\n encryptionKeyFromFile,\n isAuthioTokenEncrypted,\n type AuthioEncryptionKeySource,\n type AuthioTokenDecrypter,\n} from \"./encryption.js\";\nimport { AuthioCallbackError, AuthioConfigurationError, AuthioProtocolError } from \"./errors.js\";\nimport {\n acceptedSigningAlgorithms,\n createAuthioSigningKeys,\n validateAuthioIdToken,\n validateAuthioLogoutToken,\n verifyAuthioJwt,\n requireHmacSecretLength,\n withClientSecret,\n type AuthioIdTokenClaims,\n type AuthioLogoutToken,\n} from \"./token-validation.js\";\nimport {\n ensureProtocolSuccess,\n formBody,\n parseProtocolJson,\n readProtocolJson,\n redact,\n send,\n toErrorResponse,\n toProtocolError,\n toScopeString,\n} from \"./http.js\";\nimport type {\n AuthioClientCredentialsToken,\n AuthioConnectionChoice,\n AuthioConnectionExchangeResult,\n AuthioDeviceAuthorization,\n AuthioDevicePollOutcome,\n AuthioIntrospectionResult,\n AuthioTokenResponse,\n AuthioUserInfo,\n} from \"./models.js\";\nimport { resolveConnection, seconds, type AuthioConnection, type AuthioConnectionOptions } from \"./options.js\";\n\n/**\n * Everything the Authio client needs: where Authio is, and the client's credentials.\n */\nexport interface AuthioClientOptions extends AuthioConnectionOptions, AuthioClientCredentialsSettings {\n /**\n * Seconds before expiry a cached token is renewed (capped at half its lifetime). Defaults to 60.\n */\n tokenRefreshSkew?: number;\n /**\n * What the authorization round trip checks, as the client is registered in Authio: `pkce`, `state`, `nonce`, or\n * `none`. Only the listed checks are made; omitted, none is (a client that requires PKCE needs `[\"pkce\"]`).\n */\n checks?: readonly AuthioCheck[];\n /** The PKCE method, when `checks` holds `pkce`: one of the client's allowed methods. Defaults to `S256`. */\n codeChallengeMethod?: AuthioCodeChallengeMethod;\n /** The `response_mode` sent with every authorization request: `query` or `web_message`. Omitted, none is sent. */\n responseMode?: AuthioResponseMode;\n /**\n * The algorithm the client's ID tokens are signed with, as registered in Authio, which signs the client's logout\n * tokens with it too. HS256, HS384 and HS512 are verified with `clientSecret` (OpenID Connect Core\n * §10.1). Omitted, the asymmetric algorithms the discovery document announces are accepted (RS*, PS*, ES*).\n */\n idTokenSignedResponseAlg?: string;\n /** The algorithm a signed UserInfo answer is signed with. Defaults to `idTokenSignedResponseAlg`. */\n userinfoSignedResponseAlg?: string;\n /**\n * The algorithm the client's access tokens are signed with (Authio's second signing setting), for\n * `readAccessTokenClaims`. HS* is verified with `clientSecret`. Omitted, the asymmetric algorithms the discovery\n * document announces are accepted, and never HS*.\n */\n accessTokenSignedResponseAlg?: string;\n /**\n * The private half of the client's own encryption key, to read ID tokens, UserInfo and logout tokens Authio\n * encrypts to the client; or a function returning it. Without it, nothing is decrypted.\n */\n clientEncryptionKey?: AuthioEncryptionKeySource;\n /** A PEM or JWK file holding `clientEncryptionKey` (Node only), read on first use. */\n clientEncryptionKeyPath?: string;\n /**\n * The key management algorithms (`alg`) decrypted, as registered for the client. Defaults to RSA-OAEP and\n * RSA-OAEP-256; RSA1_5 cannot be listed, because Node and WebCrypto cannot decrypt it.\n */\n encryptionAlgorithms?: readonly string[];\n /** The content encryption algorithms (`enc`) decrypted. Defaults to A128CBC-HS256, A192CBC-HS384, A256CBC-HS512. */\n encryptionMethods?: readonly string[];\n /**\n * Accepted for parity with the other Authio SDKs; RSA1_5 stays refused here, because Node and WebCrypto cannot\n * decrypt it. Defaults to `false`.\n */\n allowLegacyEncryptionAlgorithms?: boolean;\n /** Where Authio sends the person back after signing in, unless a request names another. */\n redirectUri?: string;\n /** Where Authio sends the person after signing out, unless a request names another. */\n postLogoutRedirectUri?: string;\n /** Seconds of clock skew tolerated on ID tokens, logout tokens and signed UserInfo. Defaults to 30. */\n clockSkew?: number;\n}\n\n/**\n * What a completed sign-in yields.\n */\nexport interface AuthioAuthorizationResult {\n /** The token endpoint's answer: access token, refresh token, ID token. */\n readonly tokens: AuthioTokenResponse;\n /** The validated ID token's claims, when Authio issued one (the `openid` scope). */\n readonly idToken: AuthioIdTokenClaims | undefined;\n}\n\n/**\n * What the end-session URL carries (OpenID Connect RP-Initiated Logout).\n */\nexport interface AuthioEndSessionRequest {\n /** The ID token of the session to end. */\n idTokenHint?: string;\n /** Where to send the person afterwards; must be registered. Defaults to the client's `postLogoutRedirectUri`. */\n postLogoutRedirectUri?: string;\n /** Echoed back to `postLogoutRedirectUri`. */\n state?: string;\n /** The language of the signed-out screen. */\n uiLocales?: string | readonly string[];\n /** Sends the client id unless `false`, so Authio knows the client without an ID token. */\n includeClientId?: boolean;\n}\n\n/**\n * Per-call options.\n */\nexport interface AuthioCallOptions {\n /** Aborts the call. */\n signal?: AbortSignal;\n}\n\n/**\n * The token endpoint's grants.\n */\nexport interface AuthioTokenClient {\n /** `client_credentials`, optionally for a resource (RFC 8707). */\n clientCredentials(options?: { scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions): Promise<AuthioTokenResponse>;\n /** Redeems an authorization code. */\n authorizationCode(\n options: { code: string; redirectUri: string; codeVerifier?: string; resource?: string } & AuthioCallOptions,\n ): Promise<AuthioTokenResponse>;\n /**\n * Refreshes; the answer carries the rotated refresh token, which must be stored. `scopes` may only narrow the\n * granted ones; `resource` (RFC 8707) asks for an access token addressed to that resource server.\n */\n refresh(options: { refreshToken: string; scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions): Promise<AuthioTokenResponse>;\n /** Exchanges a user's access token for one addressed to another resource (RFC 8693, on-behalf-of). */\n exchange(\n options: { subjectToken: string; scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions,\n ): Promise<AuthioTokenResponse>;\n /**\n * Exchanges a user's access token for the token of one of their connected accounts. OAuth refusals come back as\n * a result, never thrown.\n */\n exchangeForConnection(\n options: { subjectToken: string; provider: string; connectionId?: string } & AuthioCallOptions,\n ): Promise<AuthioConnectionExchangeResult>;\n /** Starts the device flow (RFC 8628). */\n deviceAuthorization(options?: { scopes?: Iterable<string> | string } & AuthioCallOptions): Promise<AuthioDeviceAuthorization>;\n /**\n * Polls until the person approves: waits `interval` (default 5 s) before each poll, adds 5 s on `slow_down`, throws\n * on `access_denied` and `expired_token`, and throws `expired_token` when `expires_in` elapses locally.\n */\n pollDevice(\n authorization: AuthioDeviceAuthorization | { device_code: string; interval?: number; expires_in?: number },\n options?: AuthioCallOptions,\n ): Promise<AuthioTokenResponse>;\n /** The resource owner password grant, where the client allows it. */\n password(options: { username: string; password: string; scopes?: Iterable<string> | string } & AuthioCallOptions): Promise<AuthioTokenResponse>;\n /**\n * The `personal_access_token` grant: a `pat_` value presented as `client_secret`, with the consumer's client id for\n * a consumer's token or none for an account's token. The client's own credentials are not sent.\n */\n personalAccessToken(\n options: { token: string; clientId?: string; scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions,\n ): Promise<AuthioTokenResponse>;\n}\n\n/**\n * Client-credentials tokens, cached per scopes and resource.\n */\nexport interface AuthioClientCredentialsCache {\n /**\n * A token for the scopes and resource, renewed `tokenRefreshSkew` before expiry (at most half its lifetime);\n * concurrent callers for one key share one request.\n */\n getToken(options?: { scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions): Promise<AuthioClientCredentialsToken>;\n /** Drops the cached token; with `accessToken`, only when the cache still holds that token. */\n invalidate(options?: { scopes?: Iterable<string> | string; resource?: string; accessToken?: string }): void;\n}\n\n/**\n * The Authio client.\n */\nexport interface AuthioClient {\n /** The issuer. */\n readonly issuer: string;\n /** The client id. */\n readonly clientId: string;\n /** The connection settings. */\n readonly connection: AuthioConnection;\n /** The discovery document. */\n readonly discovery: AuthioDiscoveryClient;\n /** The token endpoint. */\n readonly tokens: AuthioTokenClient;\n /** Cached client-credentials tokens. */\n readonly clientCredentials: AuthioClientCredentialsCache;\n /**\n * Introspects a token as this client (RFC 7662). Authio answers according to who asks: a token requested for a\n * resource (RFC 8707) is active only to the client that resource server names as its introspection client.\n */\n introspect(token: string, options?: { tokenTypeHint?: string } & AuthioCallOptions): Promise<AuthioIntrospectionResult>;\n /** Revokes a token (RFC 7009). */\n revoke(token: string, options?: { tokenTypeHint?: string } & AuthioCallOptions): Promise<void>;\n /**\n * Reads UserInfo. A UserInfo answered as `application/jwt` is decrypted with `clientEncryptionKey` when it is a\n * JWE, then verified against the realm's keys (`iss` the issuer, `aud` the client).\n */\n userInfo(accessToken: string, options?: AuthioCallOptions): Promise<AuthioUserInfo>;\n /**\n * A `fetch` that sends a cached client-credentials token, and on a `401` drops it and retries once.\n */\n clientCredentialsFetch(options?: { scopes?: Iterable<string> | string; resource?: string; fetch?: typeof fetch }): typeof fetch;\n /**\n * Builds the authorization URL (the parameters of the configured `checks`, and Authio's parameters) and the\n * transaction to keep until the callback.\n */\n createAuthorizationUrl(request?: AuthioAuthorizationRequest & AuthioCallOptions): Promise<AuthioAuthorizationUrl>;\n /**\n * Completes a sign-in: checks `state` (with the `state` check) and the `iss` parameter (RFC 9207), throws the OAuth\n * error Authio sent back, redeems the code (with the PKCE verifier, with the `pkce` check), and validates the ID\n * token (`nonce` with the `nonce` check, `at_hash`, `max_age`). A `state` the transaction did not ask for is ignored.\n *\n * @param callback The callback URL, its query, or its parameters (a `web_message` answer, a parsed query).\n * @param transaction What `createAuthorizationUrl` returned with the URL.\n * @throws AuthioCallbackError when the callback is not for this transaction.\n * @throws AuthioProtocolError for an OAuth error.\n * @throws AuthioTokenValidationError when the ID token does not validate.\n */\n handleAuthorizationCallback(\n callback: string | URL | URLSearchParams | Readonly<Record<string, unknown>>,\n transaction: AuthioAuthorizationTransaction,\n options?: AuthioCallOptions,\n ): Promise<AuthioAuthorizationResult>;\n /**\n * Validates an ID token: decrypted with `clientEncryptionKey` when it is a JWE, then signature (cached JWKS), `iss`,\n * `aud` = the client id, `exp` with the skew, payload `typ` = `ID`, and `nonce`, `at_hash` and `auth_time` when\n * given.\n *\n * @throws AuthioTokenValidationError naming why it was refused.\n */\n validateIdToken(idToken: string, expectations?: { nonce?: string; accessToken?: string; maxAge?: number } & AuthioCallOptions): Promise<AuthioIdTokenClaims>;\n /**\n * Validates a back-channel logout token Authio posted as `logout_token`.\n *\n * @throws AuthioTokenValidationError naming why it was refused (`invalid_logout_token` for the logout-specific rules).\n */\n validateLogoutToken(logoutToken: string, options?: AuthioCallOptions): Promise<AuthioLogoutToken>;\n /**\n * Reads a front-channel logout request Authio loaded in an iframe: `iss` must be the issuer, and `sid` comes with\n * it. End the sessions of `sessionId`, or the browser's own session when Authio sent none.\n *\n * @throws AuthioCallbackError when `iss` names another issuer, or `sid` comes without `iss`.\n */\n validateFrontChannelLogout(request: string | URL | URLSearchParams | Readonly<Record<string, unknown>>): AuthioFrontChannelLogout;\n /**\n * Reads an access token this client received from Authio: decrypted with `clientEncryptionKey` when it is a JWE,\n * then its signature (with `accessTokenSignedResponseAlg`), `iss` and `exp` checked. Its audience is the API's, so it is not checked. `undefined` for an\n * opaque token, or an encrypted one without `clientEncryptionKey`.\n *\n * @throws AuthioTokenValidationError naming why it was refused.\n */\n readAccessTokenClaims(accessToken: string, options?: AuthioCallOptions): Promise<JWTPayload | undefined>;\n /** Builds the end-session URL (RP-Initiated Logout). */\n createEndSessionUrl(request?: AuthioEndSessionRequest & AuthioCallOptions): Promise<string>;\n /**\n * Builds an authorization URL that satisfies an API's `insufficient_user_authentication` challenge (RFC 9470): its\n * `acr_values` and `max_age`, with `prompt=login` when the challenge asks for a sign-in made just now (`max_age=0`).\n *\n * @param challenge The `WWW-Authenticate` header value, or the challenge already parsed.\n */\n createStepUpAuthorizationUrl(\n challenge: string | AuthioBearerChallenge,\n request?: AuthioAuthorizationRequest & AuthioCallOptions,\n ): Promise<AuthioAuthorizationUrl>;\n}\n\n/**\n * Creates the Authio client.\n *\n * @throws AuthioConfigurationError when the settings are incomplete.\n */\nexport function createAuthioClient(options: AuthioClientOptions): AuthioClient {\n const connection = resolveConnection(options);\n const discovery = createAuthioDiscoveryClient(connection);\n const authenticator = createClientAuthenticator(options, connection);\n const refreshSkewMs = seconds(options.tokenRefreshSkew, AuthioDefaults.TokenRefreshSkew, \"tokenRefreshSkew\");\n const clockSkew = seconds(options.clockSkew, AuthioDefaults.ClockSkew, \"clockSkew\") / 1000;\n const encryptionKey = resolveEncryptionKey(options);\n const decrypt = createAuthioTokenDecrypter(encryptionKey, {\n setting: options.clientEncryptionKey === undefined && options.clientEncryptionKeyPath ? \"clientEncryptionKeyPath\" : \"clientEncryptionKey\",\n allowLegacyEncryptionAlgorithms: options.allowLegacyEncryptionAlgorithms,\n encryptionAlgorithms: options.encryptionAlgorithms,\n encryptionMethods: options.encryptionMethods,\n });\n const checks = resolveChecks(options.checks);\n const codeChallengeMethod = resolveCodeChallengeMethod(options.codeChallengeMethod);\n const responseMode = resolveResponseMode(options.responseMode);\n const idTokenAlgorithm = resolveSigningAlgorithm(options.idTokenSignedResponseAlg, \"idTokenSignedResponseAlg\", options.clientSecret);\n const userInfoAlgorithm = resolveSigningAlgorithm(options.userinfoSignedResponseAlg, \"userinfoSignedResponseAlg\", options.clientSecret) ?? idTokenAlgorithm;\n const accessTokenAlgorithm = resolveSigningAlgorithm(options.accessTokenSignedResponseAlg, \"accessTokenSignedResponseAlg\", options.clientSecret);\n const clientSecret = options.clientSecret === undefined ? undefined : () => readSecret(options.clientSecret!);\n const signingKeys = createAuthioSigningKeys(connection, discovery);\n const tokens = createTokenClient(connection, discovery, authenticator);\n const clientCredentials = createClientCredentialsCache(connection, authenticator.clientId, tokens, refreshSkewMs);\n const validationContext = async (signal?: AbortSignal) => {\n const document = await discovery.get(signal);\n\n return {\n keys: withClientSecret(await signingKeys(signal), clientSecret),\n decrypt,\n issuer: connection.issuer,\n clientId: authenticator.clientId,\n algorithms: acceptedSigningAlgorithms(idTokenAlgorithm, document.id_token_signing_alg_values_supported),\n clockSkew,\n now: connection.clock.now(),\n };\n };\n const validateIdToken: AuthioClient[\"validateIdToken\"] = async (idToken, expectations = {}) => {\n requireValue(idToken, \"idToken\");\n\n return validateAuthioIdToken(idToken, await validationContext(expectations.signal), expectations);\n };\n const createAuthorizationUrl: AuthioClient[\"createAuthorizationUrl\"] = async (request = {}) => {\n const redirectUri = request.redirectUri ?? options.redirectUri;\n\n requireValue(redirectUri, \"redirectUri\");\n\n const document = await discovery.get(request.signal);\n\n return buildAuthorizationUrl(requireEndpoint(document, \"authorization_endpoint\"), authenticator.clientId, {\n ...request,\n redirectUri,\n checks: request.checks ?? checks,\n codeChallengeMethod: request.codeChallengeMethod ?? codeChallengeMethod,\n responseMode: request.responseMode ?? responseMode,\n });\n };\n\n return {\n issuer: connection.issuer,\n clientId: authenticator.clientId,\n connection,\n discovery,\n tokens,\n clientCredentials,\n async introspect(token, callOptions = {}) {\n requireValue(token, \"token\");\n\n const response = await postForm(\n connection,\n discovery,\n authenticator,\n \"introspection_endpoint\",\n { token, token_type_hint: callOptions.tokenTypeHint },\n callOptions.signal,\n );\n\n return readProtocolJson<AuthioIntrospectionResult>(response);\n },\n async revoke(token, callOptions = {}) {\n requireValue(token, \"token\");\n\n const response = await postForm(\n connection,\n discovery,\n authenticator,\n \"revocation_endpoint\",\n { token, token_type_hint: callOptions.tokenTypeHint },\n callOptions.signal,\n );\n\n await ensureProtocolSuccess(response);\n },\n async userInfo(accessToken, callOptions = {}) {\n requireValue(accessToken, \"accessToken\");\n\n const document = await discovery.get(callOptions.signal);\n const response = await send(\n connection,\n requireEndpoint(document, \"userinfo_endpoint\"),\n { method: \"GET\", headers: { authorization: `Bearer ${accessToken}`, accept: \"application/json, application/jwt\" } },\n callOptions.signal,\n );\n const mediaType = response.headers.get(\"content-type\")?.split(\";\")[0]?.trim().toLowerCase();\n\n if (response.ok && mediaType === \"application/jwt\")\n return readUserInfoJwt(\n (await response.text()).trim(),\n document,\n connection,\n authenticator.clientId,\n decrypt,\n withClientSecret(await signingKeys(callOptions.signal), clientSecret),\n {\n algorithms: acceptedSigningAlgorithms(userInfoAlgorithm, document.userinfo_signing_alg_values_supported ?? document.id_token_signing_alg_values_supported),\n clockSkew,\n status: response.status,\n },\n );\n\n if (!response.ok) {\n const body = await response.text();\n const challenge = toErrorResponse(body) ? undefined : readBearerChallenge(response);\n\n throw challenge\n ? new AuthioProtocolError(challenge.error, challenge.description, undefined, response.status)\n : toProtocolError(body, response.status);\n }\n\n return readProtocolJson<AuthioUserInfo>(response);\n },\n createAuthorizationUrl,\n async handleAuthorizationCallback(callback, transaction, callOptions = {}) {\n if (!transaction?.redirectUri || !Array.isArray(transaction.checks))\n throw new TypeError(\"transaction is required: keep what createAuthorizationUrl returned.\");\n\n const parameters = readCallbackParameters(callback);\n\n if (transaction.checks.includes(\"state\") && (!transaction.state || parameters.state !== transaction.state))\n throw new AuthioCallbackError(\"state_mismatch\", \"The callback's state is not the one this sign-in was started with.\");\n\n const document = await discovery.get(callOptions.signal);\n\n if (parameters.iss !== undefined) {\n if (parameters.iss.replace(/\\/+$/, \"\") !== connection.issuer)\n throw new AuthioCallbackError(\"issuer_mismatch\", `The callback comes from the issuer '${parameters.iss}', not '${connection.issuer}' (RFC 9207).`);\n } else if (document.authorization_response_iss_parameter_supported === true) {\n throw new AuthioCallbackError(\"missing_issuer\", \"The callback carries no iss parameter, although Authio sends one (RFC 9207).\");\n }\n\n if (parameters.error) throw new AuthioProtocolError(parameters.error, parameters.error_description, parameters.error_code);\n if (!parameters.code) throw new AuthioCallbackError(\"missing_code\", \"The callback carries neither a code nor an error.\");\n\n const answer = await tokens.authorizationCode({\n code: parameters.code,\n redirectUri: transaction.redirectUri,\n codeVerifier: transaction.checks.includes(\"pkce\") ? transaction.codeVerifier : undefined,\n resource: transaction.resource,\n signal: callOptions.signal,\n });\n const idToken = answer.id_token\n ? await validateIdToken(answer.id_token, {\n nonce: transaction.checks.includes(\"nonce\") ? transaction.nonce : undefined,\n accessToken: answer.access_token,\n maxAge: transaction.maxAge,\n signal: callOptions.signal,\n })\n : undefined;\n\n return { tokens: answer, idToken };\n },\n validateIdToken,\n async validateLogoutToken(logoutToken, callOptions = {}) {\n requireValue(logoutToken, \"logoutToken\");\n\n return validateAuthioLogoutToken(logoutToken, await validationContext(callOptions.signal));\n },\n validateFrontChannelLogout(request) {\n return readAuthioFrontChannelLogout(request, connection.issuer);\n },\n async readAccessTokenClaims(accessToken, callOptions = {}) {\n requireValue(accessToken, \"accessToken\");\n\n if (isAuthioTokenEncrypted(accessToken) && encryptionKey === undefined) return undefined;\n\n const signed = await decrypt(accessToken);\n\n if (signed.split(\".\").length !== 3) return undefined;\n\n const document = await discovery.get(callOptions.signal);\n const { payload } = await verifyAuthioJwt(signed, withClientSecret(await signingKeys(callOptions.signal), clientSecret), {\n issuer: connection.issuer,\n algorithms: acceptedSigningAlgorithms(accessTokenAlgorithm, document.id_token_signing_alg_values_supported),\n clockSkew,\n now: connection.clock.now(),\n });\n\n return payload;\n },\n async createEndSessionUrl(request = {}) {\n const document = await discovery.get(request.signal);\n const url = new URL(requireEndpoint(document, \"end_session_endpoint\"));\n const locales =\n request.uiLocales === undefined ? undefined : (typeof request.uiLocales === \"string\" ? [request.uiLocales] : [...request.uiLocales]).join(\" \");\n const parameters: Record<string, string | undefined> = {\n id_token_hint: request.idTokenHint,\n post_logout_redirect_uri: request.postLogoutRedirectUri ?? options.postLogoutRedirectUri,\n state: request.state,\n ui_locales: locales,\n client_id: request.includeClientId === false ? undefined : authenticator.clientId,\n };\n\n for (const [name, value] of Object.entries(parameters)) if (value) url.searchParams.set(name, value);\n\n return url.toString();\n },\n async createStepUpAuthorizationUrl(challenge, request = {}) {\n const parsed = typeof challenge === \"string\" ? parseAuthioBearerChallenge(challenge) : challenge;\n\n if (!parsed || parsed.error !== AuthioOAuthErrors.InsufficientUserAuthentication)\n throw new TypeError(\"The challenge is not an insufficient_user_authentication bearer challenge.\");\n\n return createAuthorizationUrl({\n ...request,\n acrValues: request.acrValues ?? parsed.acrValues,\n maxAge: request.maxAge ?? parsed.maxAge,\n prompt: request.prompt ?? (parsed.maxAge === 0 ? \"login\" : undefined),\n });\n },\n clientCredentialsFetch(fetchOptions = {}) {\n const inner = fetchOptions.fetch ?? connection.fetch;\n const key = { scopes: fetchOptions.scopes, resource: fetchOptions.resource };\n\n return async (input, init) => {\n const request = new Request(input, init);\n const body = request.body ? await request.arrayBuffer() : undefined;\n const attempt = async (token: AuthioClientCredentialsToken) => {\n const headers = new Headers(request.headers);\n\n headers.set(\"authorization\", `${token.tokenType} ${token.accessToken}`);\n\n return inner(request.url, { method: request.method, headers, body, signal: request.signal, redirect: request.redirect });\n };\n\n const token = await clientCredentials.getToken({ ...key, signal: request.signal });\n const response = await attempt(token);\n\n if (response.status !== 401) return response;\n\n clientCredentials.invalidate({ ...key, accessToken: token.accessToken });\n\n return attempt(await clientCredentials.getToken({ ...key, signal: request.signal }));\n };\n },\n };\n}\n\nfunction createTokenClient(connection: AuthioConnection, discovery: AuthioDiscoveryClient, authenticator: AuthioClientAuthenticator): AuthioTokenClient {\n const requestToken = async (parameters: Record<string, string | undefined>, signal?: AbortSignal, authenticate = true) => {\n const response = await postForm(connection, discovery, authenticate ? authenticator : undefined, \"token_endpoint\", parameters, signal);\n const token = await readProtocolJson<AuthioTokenResponse>(response);\n\n return redact(token, [\"access_token\", \"refresh_token\", \"id_token\"]);\n };\n\n const pollDevice: AuthioTokenClient[\"pollDevice\"] = async (authorization, options = {}) => {\n requireValue(authorization?.device_code, \"device_code\");\n\n let wait = (authorization.interval && authorization.interval > 0 ? authorization.interval : AuthioDefaults.DeviceInterval) * 1000;\n const deadline =\n authorization.expires_in && authorization.expires_in > 0 ? connection.clock.now() + authorization.expires_in * 1000 : undefined;\n\n for (;;) {\n await connection.clock.sleep(wait, options.signal);\n\n if (deadline !== undefined && connection.clock.now() >= deadline)\n throw new AuthioProtocolError(AuthioOAuthErrors.ExpiredToken, \"The device code expired before the user approved it.\");\n\n try {\n return await requestToken({ grant_type: AuthioGrantTypes.DeviceCode, device_code: authorization.device_code }, options.signal);\n } catch (error) {\n if (!(error instanceof AuthioProtocolError)) throw error;\n\n const outcome = toDevicePollOutcome(error.error);\n\n if (outcome.outcome === \"failed\") throw error;\n\n wait += outcome.intervalIncrease * 1000;\n }\n }\n };\n\n return {\n clientCredentials: (options = {}) =>\n requestToken(\n { grant_type: AuthioGrantTypes.ClientCredentials, scope: toScopeString(options.scopes), resource: options.resource },\n options.signal,\n ),\n authorizationCode: (options) => {\n requireValue(options?.code, \"code\");\n requireValue(options.redirectUri, \"redirectUri\");\n\n return requestToken(\n {\n grant_type: AuthioGrantTypes.AuthorizationCode,\n code: options.code,\n redirect_uri: options.redirectUri,\n code_verifier: options.codeVerifier,\n resource: options.resource,\n },\n options.signal,\n );\n },\n refresh: (options) => {\n requireValue(options?.refreshToken, \"refreshToken\");\n\n return requestToken(\n { grant_type: AuthioGrantTypes.RefreshToken, refresh_token: options.refreshToken, scope: toScopeString(options.scopes), resource: options.resource },\n options.signal,\n );\n },\n exchange: (options) => {\n requireValue(options?.subjectToken, \"subjectToken\");\n\n return requestToken(\n {\n grant_type: AuthioGrantTypes.TokenExchange,\n subject_token: options.subjectToken,\n subject_token_type: AuthioTokenTypes.AccessTokenUrn,\n requested_token_type: AuthioTokenTypes.AccessTokenUrn,\n scope: toScopeString(options.scopes),\n resource: options.resource,\n },\n options.signal,\n );\n },\n async exchangeForConnection(options) {\n requireValue(options?.subjectToken, \"subjectToken\");\n requireValue(options.provider, \"provider\");\n\n const response = await postForm(\n connection,\n discovery,\n authenticator,\n \"token_endpoint\",\n {\n grant_type: AuthioGrantTypes.TokenExchange,\n subject_token: options.subjectToken,\n subject_token_type: AuthioTokenTypes.AccessTokenUrn,\n requested_token_type: AuthioTokenTypes.ConnectionAccessTokenUrn,\n connection_provider: options.provider,\n connection_id: options.connectionId,\n },\n options.signal,\n );\n\n return toConnectionExchangeResult(await response.text(), response.status, options.provider);\n },\n async deviceAuthorization(options = {}) {\n const response = await postForm(\n connection,\n discovery,\n authenticator,\n \"device_authorization_endpoint\",\n { scope: toScopeString(options.scopes) },\n options.signal,\n );\n\n return redact(await readProtocolJson<AuthioDeviceAuthorization>(response), [\"device_code\"]);\n },\n pollDevice,\n personalAccessToken: (options) => {\n requireValue(options?.token, \"token\");\n\n return requestToken(\n {\n grant_type: AuthioGrantTypes.PersonalAccessToken,\n client_secret: options.token,\n client_id: options.clientId,\n scope: toScopeString(options.scopes),\n resource: options.resource,\n },\n options.signal,\n false,\n );\n },\n password: (options) => {\n requireValue(options?.username, \"username\");\n\n if (typeof options.password !== \"string\") throw new TypeError(\"password is required.\");\n\n return requestToken(\n { grant_type: AuthioGrantTypes.Password, username: options.username, password: options.password, scope: toScopeString(options.scopes) },\n options.signal,\n );\n },\n };\n}\n\nfunction createClientCredentialsCache(\n connection: AuthioConnection,\n clientId: string,\n tokens: AuthioTokenClient,\n refreshSkewMs: number,\n): AuthioClientCredentialsCache {\n const entries = new Map<string, AuthioClientCredentialsToken>();\n const pending = new Map<string, Promise<AuthioClientCredentialsToken>>();\n\n const keyOf = (scope: string | undefined, resource: string | undefined) =>\n `${connection.issuer}|${clientId}|${(scope ?? \"\").split(\" \").filter(Boolean).sort().join(\" \")}|${resource ?? \"\"}`;\n\n return {\n async getToken(options = {}) {\n const scope = toScopeString(options.scopes);\n const key = keyOf(scope, options.resource);\n const cached = entries.get(key);\n\n if (cached && connection.clock.now() < cached.refreshAt) return cached;\n\n let request = pending.get(key);\n\n if (!request) {\n request = tokens\n .clientCredentials({ scopes: scope, resource: options.resource, signal: options.signal })\n .then((response) => {\n const token = toClientCredentialsToken(response, connection.clock.now(), refreshSkewMs);\n\n entries.set(key, token);\n return token;\n })\n .finally(() => pending.delete(key));\n pending.set(key, request);\n }\n\n return request;\n },\n invalidate(options = {}) {\n const key = keyOf(toScopeString(options.scopes), options.resource);\n\n if (options.accessToken === undefined || entries.get(key)?.accessToken === options.accessToken) entries.delete(key);\n },\n };\n}\n\n/**\n * When a token answer expires, and when a cache should renew it: `expires_in` (else 5 minutes) after `issuedAt`,\n * renewed `refreshSkewMs` before that, at most half its lifetime.\n */\nexport function toClientCredentialsToken(response: AuthioTokenResponse, issuedAt: number, refreshSkewMs: number): AuthioClientCredentialsToken {\n const lifetime = (response.expires_in && response.expires_in > 0 ? response.expires_in : AuthioDefaults.AssumedTokenLifetime) * 1000;\n const expiresAt = issuedAt + lifetime;\n const skew = Math.min(refreshSkewMs, lifetime / 2);\n\n return redact(\n {\n accessToken: response.access_token,\n tokenType: response.token_type?.trim() ? response.token_type : \"Bearer\",\n expiresAt,\n refreshAt: expiresAt - skew,\n scope: response.scope,\n },\n [\"accessToken\"],\n );\n}\n\n/**\n * Reads the answer of a connected-account token exchange (see `conformance/oauth-responses.json`).\n *\n * @internal\n */\nexport function toConnectionExchangeResult(body: string, status: number, provider: string): AuthioConnectionExchangeResult {\n if (status >= 200 && status < 300) {\n const token = parseProtocolJson<Record<string, unknown>>(body, status);\n\n if (typeof token.access_token === \"string\" && token.access_token)\n return redact(\n withoutUndefined({\n status: \"granted\" as const,\n accessToken: token.access_token,\n issuedTokenType: textOf(token.issued_token_type),\n tokenType: textOf(token.token_type),\n expiresIn: typeof token.expires_in === \"number\" ? token.expires_in : undefined,\n scope: textOf(token.scope),\n connectionId: textOf(token.connection_id),\n provider: textOf(token.provider) ?? provider,\n providerType: textOf(token.provider_type),\n externalAccount:\n token.external_account && typeof token.external_account === \"object\" ? (token.external_account as Record<string, unknown>) : undefined,\n }),\n [\"accessToken\"],\n );\n }\n\n const error = toErrorResponse(body);\n const errorDescription = error?.error_description?.trim()\n ? error.error_description\n : `Authio answered HTTP ${status} to the connected-account token exchange.`;\n const errorCode = textOf(error?.error_code);\n\n switch (error?.error) {\n case AuthioOAuthErrors.ConnectionRequired:\n return withoutUndefined({\n status: \"required\" as const,\n connectUri: textOf(error.connect_uri),\n provider: textOf(error.connection_provider) ?? provider,\n errorCode,\n errorDescription,\n });\n case AuthioOAuthErrors.ConnectionSelectionRequired:\n return withoutUndefined({\n status: \"selection_required\" as const,\n provider: textOf(error.connection_provider) ?? provider,\n connections: (Array.isArray(error.connections) ? error.connections : []).map(toConnectionChoice),\n errorCode,\n errorDescription,\n });\n default:\n return withoutUndefined({\n status: \"refused\" as const,\n error: error?.error ?? `http_${status}`,\n errorCode,\n errorDescription,\n connectUri: textOf(error?.connect_uri),\n });\n }\n}\n\n/**\n * What a device-flow poll's OAuth error means: keep polling (5 seconds slower after `slow_down`), or stop with it.\n */\nexport function toDevicePollOutcome(error: string): AuthioDevicePollOutcome {\n if (error === AuthioOAuthErrors.AuthorizationPending) return { outcome: \"keep_polling\", intervalIncrease: 0 };\n if (error === AuthioOAuthErrors.SlowDown) return { outcome: \"keep_polling\", intervalIncrease: AuthioDefaults.DeviceSlowDownIncrement };\n\n return { outcome: \"failed\", error };\n}\n\nfunction toConnectionChoice(value: unknown): AuthioConnectionChoice {\n const record = (value && typeof value === \"object\" ? value : {}) as Record<string, unknown>;\n\n return withoutUndefined({ id: textOf(record.id) ?? \"\", label: textOf(record.label), externalLogin: textOf(record.external_login) });\n}\n\nfunction textOf(value: unknown): string | undefined {\n return typeof value === \"string\" && value ? value : undefined;\n}\n\nfunction withoutUndefined<T extends object>(value: T): T {\n for (const key of Object.keys(value) as (keyof T)[]) if (value[key] === undefined) delete value[key];\n\n return value;\n}\n\nfunction resolveEncryptionKey(options: AuthioClientOptions): AuthioEncryptionKeySource | undefined {\n if (options.clientEncryptionKey !== undefined) return options.clientEncryptionKey;\n if (options.clientEncryptionKeyPath) return encryptionKeyFromFile(options.clientEncryptionKeyPath);\n\n return undefined;\n}\n\nasync function postForm(\n connection: AuthioConnection,\n discovery: AuthioDiscoveryClient,\n authenticator: AuthioClientAuthenticator | undefined,\n endpoint: \"token_endpoint\" | \"introspection_endpoint\" | \"revocation_endpoint\" | \"device_authorization_endpoint\",\n parameters: Record<string, string | undefined>,\n signal?: AbortSignal,\n): Promise<Response> {\n const document = await discovery.get(signal);\n const url = requireEndpoint(document, endpoint);\n const form = formBody(parameters);\n const headers = new Headers({ accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" });\n\n await authenticator?.apply(form, headers);\n\n return send(connection, url, { method: \"POST\", headers, body: form.toString() }, signal);\n}\n\nasync function readUserInfoJwt(\n jwt: string,\n document: AuthioDiscoveryDocument,\n connection: AuthioConnection,\n clientId: string,\n decrypt: AuthioTokenDecrypter,\n keys: JWTVerifyGetKey,\n settings: { algorithms: readonly string[]; clockSkew: number; status: number },\n): Promise<AuthioUserInfo> {\n try {\n const signed = isAuthioTokenEncrypted(jwt) ? await decrypt(jwt) : jwt;\n const { payload } = await verifyAuthioJwt(signed, keys, {\n issuer: document.issuer.replace(/\\/+$/, \"\"),\n audiences: [clientId],\n algorithms: settings.algorithms,\n clockSkew: settings.clockSkew,\n now: connection.clock.now(),\n requiredClaims: [\"sub\"],\n });\n\n return payload as AuthioUserInfo;\n } catch (error) {\n throw new AuthioProtocolError(\n \"invalid_userinfo\",\n `The userinfo JWT could not be verified: ${(error as Error)?.message ?? \"unknown reason.\"}`,\n undefined,\n settings.status,\n { cause: error },\n );\n }\n}\n\nfunction readBearerChallenge(response: Response): { error: string; description: string | undefined } | undefined {\n const header = response.headers.get(\"www-authenticate\");\n\n if (!header || !/^bearer\\s/i.test(header.trim())) return undefined;\n\n let error = \"\";\n let description: string | undefined;\n\n for (const match of header.matchAll(/([a-zA-Z_]+)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"|([a-zA-Z_]+)\\s*=\\s*([^,\\s]+)/g)) {\n const name = match[1] ?? match[3];\n const value = (match[2] ?? match[4] ?? \"\").replace(/\\\\(.)/g, \"$1\");\n\n if (name === \"error\") error = value;\n else if (name === \"error_description\") description = value;\n }\n\n return error ? { error, description } : undefined;\n}\n\nfunction resolveCodeChallengeMethod(method: AuthioCodeChallengeMethod | undefined): AuthioCodeChallengeMethod | undefined {\n if (method !== undefined && method !== \"S256\" && method !== \"plain\")\n throw new AuthioConfigurationError(`The Authio codeChallengeMethod '${String(method)}' is not S256 or plain.`);\n\n return method;\n}\n\nfunction resolveResponseMode(mode: AuthioResponseMode | undefined): AuthioResponseMode | undefined {\n if (mode !== undefined && mode !== \"query\" && mode !== \"web_message\")\n throw new AuthioConfigurationError(`The Authio responseMode '${String(mode)}' is not query or web_message.`);\n\n return mode;\n}\n\nfunction resolveSigningAlgorithm(algorithm: string | undefined, setting: string, clientSecret: unknown): string | undefined {\n if (algorithm === undefined || algorithm === \"\") return undefined;\n\n const symmetric = (AuthioHmacAlgorithms as readonly string[]).includes(algorithm);\n\n if (!symmetric && !(AuthioAsymmetricAlgorithms as readonly string[]).includes(algorithm))\n throw new AuthioConfigurationError(\n `The Authio ${setting} '${algorithm}' is not one of ${[...AuthioAsymmetricAlgorithms, ...AuthioHmacAlgorithms].join(\", \")}.`,\n );\n\n if (symmetric && !clientSecret)\n throw new AuthioConfigurationError(`The Authio ${setting} ${algorithm} is verified with the client secret (OpenID Connect Core §10.1): set clientSecret.`);\n\n if (symmetric && typeof clientSecret === \"string\") requireHmacSecretLength(algorithm, new TextEncoder().encode(clientSecret).length);\n\n return algorithm;\n}\n\nasync function readSecret(source: NonNullable<AuthioClientOptions[\"clientSecret\"]>): Promise<string> {\n const value = typeof source === \"function\" ? await source() : source;\n\n if (typeof value !== \"string\" || !value) throw new AuthioConfigurationError(\"The Authio clientSecret function returned no secret.\");\n\n return value;\n}\n\nfunction requireValue(value: unknown, name: string): asserts value is string {\n if (typeof value !== \"string\" || !value.trim()) throw new TypeError(`${name} is required.`);\n}\n","import { createAuthioClient, toClientCredentialsToken, type AuthioClient } from \"./client.js\";\nimport { AuthioDefaults } from \"./constants.js\";\nimport { AuthioAdminError, AuthioConfigurationError, type AuthioAdminNotification } from \"./errors.js\";\nimport { toScopeString } from \"./http.js\";\nimport type { AuthioClientCredentialsToken } from \"./models.js\";\nimport { seconds, systemClock, type AuthioConnectionOptions } from \"./options.js\";\n\n/**\n * A successful Admin API answer: the envelope's `data` (one object, or a listing's page `{ items, totalCount,\n * pageNumber, pageSize }`), nothing for `204`.\n */\nexport interface AuthioAdminSuccess<T = unknown> {\n readonly ok: true;\n readonly data?: T;\n}\n\n/**\n * A refused Admin API answer.\n */\nexport interface AuthioAdminFailure {\n readonly ok: false;\n readonly error: AuthioAdminError;\n}\n\n/**\n * An Admin API answer, read.\n */\nexport type AuthioAdminEnvelope<T = unknown> = AuthioAdminSuccess<T> | AuthioAdminFailure;\n\n/**\n * How an account credential is presented: `ak_` (API key), `cs_` (client secret, exchanged first) or `pat_`\n * (personal access token).\n */\nexport type AuthioAccountCredentialKind = \"api_key\" | \"client_secret\" | \"personal_access_token\";\n\n/**\n * Options of `createAuthioAccountCredential`.\n */\nexport interface AuthioAccountCredentialOptions extends Omit<AuthioConnectionOptions, \"issuer\" | \"realm\"> {\n /** Authio's base URL, such as `https://auth.example.com`. Required. */\n authority?: string;\n /** The credential's value: `ak_…`, `cs_…` or `pat_…`. */\n credential: string;\n /** The credential's id, needed to exchange a `cs_` secret (its `client_id` is `cred_` and the id without dashes). */\n credentialId?: string;\n /** How an `ak_` or `pat_` value is sent directly: `Authorization: Bearer` (default) or `x-api-key`. */\n presentAs?: \"bearer\" | \"x-api-key\";\n /** Exchanges a `pat_` value with the `personal_access_token` grant instead of sending it directly. */\n exchangePersonalAccessToken?: boolean;\n /** Narrows an exchanged token to these `admin:{permission}:{method}` scopes. */\n scopes?: Iterable<string> | string;\n /** Seconds before expiry an exchanged token is renewed (at most half its lifetime). Defaults to 60. */\n tokenRefreshSkew?: number;\n}\n\n/**\n * An account credential ready to call the Admin API with.\n */\nexport interface AuthioAccountCredential {\n /** How the credential is presented. */\n readonly kind: AuthioAccountCredentialKind;\n /** Whether it is exchanged at the `authio` realm's token endpoint before use. */\n readonly exchanged: boolean;\n /** The headers that authenticate a request: `Authorization` or `x-api-key`. */\n headers(signal?: AbortSignal): Promise<Record<string, string>>;\n /** Drops an exchanged token, so the next request exchanges again. */\n invalidate(): void;\n /**\n * A `fetch` that authenticates every request; on `401` with an exchanged token it exchanges again and retries once;\n * on `429` or `503` it waits `Retry-After` and retries an idempotent request (`GET`, `HEAD`, `PUT`, `DELETE`) once.\n */\n readonly fetch: typeof fetch;\n}\n\n/**\n * Reads an Admin API answer (see `conformance/admin-envelopes.json`). The status is the HTTP one, never the\n * envelope's numeric `statusCode`; `requestId` falls back to `X-Request-Id`, and `retryAfterSeconds` comes from\n * `Retry-After`.\n */\nexport function parseAuthioAdminEnvelope<T = unknown>(\n status: number,\n body: string | null | undefined,\n headers?: Headers | Readonly<Record<string, string | undefined>>,\n): AuthioAdminEnvelope<T> {\n const parsed = parseJson(body);\n\n if (status >= 200 && status < 300) {\n if (!parsed) return { ok: true };\n\n return withoutUndefined({ ok: true as const, data: parsed.data as T | undefined });\n }\n\n const notifications = Array.isArray(parsed?.notifications) ? parsed.notifications.map(toNotification).filter((item) => item.message) : [];\n\n return {\n ok: false,\n error: new AuthioAdminError({\n status,\n errorCode: textOf(parsed?.errorCode),\n notifications,\n requestId: textOf(parsed?.requestId) ?? headerOf(headers, AuthioDefaults.RequestIdHeader),\n retryAfterSeconds: retryAfterOf(headerOf(headers, \"Retry-After\")),\n }),\n };\n}\n\n/**\n * Reads an Admin API response, throwing `AuthioAdminError` when it is not a success.\n */\nexport async function readAuthioAdminResponse<T = unknown>(response: Response): Promise<AuthioAdminSuccess<T>> {\n const envelope = parseAuthioAdminEnvelope<T>(response.status, response.status === 204 ? null : await response.text(), response.headers);\n\n if (!envelope.ok) throw envelope.error;\n\n return envelope;\n}\n\n/**\n * Prepares an account credential for the Admin API: `ak_` and `pat_` go directly as `Authorization: Bearer` (or\n * `x-api-key`); a `cs_` secret is exchanged at `{authority}/realms/authio` with `client_credentials` and the\n * `client_id` `cred_{id}`; a `pat_` may be exchanged with the `personal_access_token` grant instead. Exchanged tokens\n * are cached and renewed before expiry.\n *\n * @throws AuthioConfigurationError when the value has no known prefix or a `cs_` secret comes without its id.\n */\nexport function createAuthioAccountCredential(options: AuthioAccountCredentialOptions): AuthioAccountCredential {\n const value = options.credential?.trim();\n\n if (!value) throw new AuthioConfigurationError(\"The account credential is required.\");\n\n const kind: AuthioAccountCredentialKind | undefined = value.startsWith(AuthioDefaults.ApiKeyPrefix)\n ? \"api_key\"\n : value.startsWith(AuthioDefaults.ClientSecretPrefix)\n ? \"client_secret\"\n : value.startsWith(AuthioDefaults.PersonalAccessTokenPrefix)\n ? \"personal_access_token\"\n : undefined;\n\n if (!kind)\n throw new AuthioConfigurationError(\n `The account credential must start with ${AuthioDefaults.ApiKeyPrefix}, ${AuthioDefaults.ClientSecretPrefix} or ${AuthioDefaults.PersonalAccessTokenPrefix}.`,\n );\n\n const exchanged = kind === \"client_secret\" || (kind === \"personal_access_token\" && options.exchangePersonalAccessToken === true);\n const clock = options.clock ?? systemClock;\n const inner = options.fetch ?? globalThis.fetch;\n const scope = toScopeString(options.scopes);\n const refreshSkewMs = seconds(options.tokenRefreshSkew, AuthioDefaults.TokenRefreshSkew, \"tokenRefreshSkew\");\n let client: AuthioClient | undefined;\n let cached: AuthioClientCredentialsToken | undefined;\n let pending: Promise<AuthioClientCredentialsToken> | undefined;\n\n if (exchanged) {\n if (kind === \"client_secret\" && !options.credentialId?.trim())\n throw new AuthioConfigurationError(\"A cs_ client secret is exchanged with its credential id: set credentialId.\");\n\n client = createAuthioClient({\n ...options,\n realm: AuthioDefaults.PlatformRealm,\n clientId: kind === \"client_secret\" ? toCredentialClientId(options.credentialId!) : AuthioDefaults.PlatformClientId,\n clientSecret: kind === \"client_secret\" ? value : undefined,\n tokenEndpointAuthMethod: kind === \"client_secret\" ? \"client_secret_post\" : \"none\",\n });\n }\n\n const exchange = async (signal?: AbortSignal): Promise<AuthioClientCredentialsToken> => {\n if (cached && clock.now() < cached.refreshAt) return cached;\n\n pending ??= (async () => {\n const issuedAt = clock.now();\n const answer =\n kind === \"client_secret\"\n ? await client!.tokens.clientCredentials({ scopes: scope, signal })\n : await client!.tokens.personalAccessToken({ token: value, scopes: scope, signal });\n\n cached = toClientCredentialsToken(answer, issuedAt, refreshSkewMs);\n return cached;\n })().finally(() => {\n pending = undefined;\n });\n\n return pending;\n };\n\n const headers = async (signal?: AbortSignal): Promise<Record<string, string>> => {\n if (exchanged) {\n const token = await exchange(signal);\n\n return { authorization: `${token.tokenType} ${token.accessToken}` };\n }\n\n return options.presentAs === \"x-api-key\" ? { [AuthioDefaults.ApiKeyHeader]: value } : { authorization: `Bearer ${value}` };\n };\n\n const authenticatedFetch: typeof fetch = async (input, init) => {\n const request = new Request(input, init);\n const body = request.body ? await request.arrayBuffer() : undefined;\n const idempotent = [\"GET\", \"HEAD\", \"PUT\", \"DELETE\"].includes(request.method.toUpperCase());\n const attempt = async () => {\n const merged = new Headers(request.headers);\n\n for (const [name, header] of Object.entries(await headers(request.signal))) merged.set(name, header);\n\n return inner(request.url, { method: request.method, headers: merged, body, signal: request.signal, redirect: request.redirect });\n };\n\n let response = await attempt();\n\n if (response.status === 401 && exchanged) {\n cached = undefined;\n response = await attempt();\n }\n\n if ((response.status === 429 || response.status === 503) && idempotent) {\n const wait = retryAfterOf(response.headers.get(\"retry-after\") ?? undefined);\n\n if (wait !== undefined) {\n await clock.sleep(wait * 1000, request.signal);\n response = await attempt();\n }\n }\n\n return response;\n };\n\n return {\n kind,\n exchanged,\n headers,\n invalidate() {\n cached = undefined;\n },\n fetch: authenticatedFetch,\n };\n}\n\n/**\n * The `client_id` an account credential's client secret is exchanged with: `cred_` and the id in format N (no dashes,\n * lower case). An id already starting with `cred_` is kept.\n */\nexport function toCredentialClientId(credentialId: string): string {\n const id = credentialId.trim();\n\n return id.startsWith(AuthioDefaults.CredentialClientIdPrefix) ? id : `${AuthioDefaults.CredentialClientIdPrefix}${id.replace(/[{}-]/g, \"\").toLowerCase()}`;\n}\n\nfunction parseJson(body: string | null | undefined): Record<string, unknown> | undefined {\n if (!body?.trim()) return undefined;\n\n try {\n return asRecord(JSON.parse(body));\n } catch {\n return undefined;\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toNotification(value: unknown): AuthioAdminNotification {\n const record = asRecord(value) ?? {};\n\n return withoutUndefined({ message: textOf(record.message) ?? \"\", field: textOf(record.field), code: textOf(record.code) });\n}\n\nfunction headerOf(headers: Headers | Readonly<Record<string, string | undefined>> | undefined, name: string): string | undefined {\n if (!headers) return undefined;\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n\n const wanted = name.toLowerCase();\n\n for (const [key, value] of Object.entries(headers as Record<string, string | undefined>)) if (key.toLowerCase() === wanted) return value;\n\n return undefined;\n}\n\nfunction retryAfterOf(value: string | undefined): number | undefined {\n if (!value?.trim()) return undefined;\n if (/^\\d+$/.test(value.trim())) return Number(value.trim());\n\n const date = Date.parse(value);\n\n return Number.isNaN(date) ? undefined : Math.max(0, Math.ceil((date - Date.now()) / 1000));\n}\n\nfunction textOf(value: unknown): string | undefined {\n return typeof value === \"string\" && value ? value : undefined;\n}\n\nfunction withoutUndefined<T extends object>(value: T): T {\n for (const key of Object.keys(value) as (keyof T)[]) if (value[key] === undefined) delete value[key];\n\n return value;\n}\n","import { AuthioResourceAccessClaims, type AuthioResourceAccessSource } from \"./constants.js\";\n\n/**\n * One role read from a `*_resource_access` claim, with the permissions it grants.\n */\nexport interface AuthioResourceAccessRole {\n /** The claim the role came from. */\n readonly source: AuthioResourceAccessSource;\n /** The role name. */\n readonly name: string;\n /** Resource → methods the role allows on it. */\n readonly permissions: Readonly<Record<string, readonly string[]>>;\n}\n\nconst claimSources = new Map(Object.entries(AuthioResourceAccessClaims).map(([name, source]) => [name.toLowerCase(), source]));\n\n/**\n * The roles and permissions a token carries in its `*_resource_access` claims, merged across sources.\n *\n * Every comparison is case-insensitive, as Authio's own check is. When a name appears in different case, the first\n * spelling read is the one listed.\n */\nexport class AuthioResourceAccess {\n /** No role at all. */\n static readonly empty = new AuthioResourceAccess([]);\n\n /** Every role read, in claim order, one entry per source it came from. */\n readonly entries: readonly AuthioResourceAccessRole[];\n /** Every distinct role name. */\n readonly roles: readonly string[];\n /** Resource → every method any role allows on it. */\n readonly permissions: Readonly<Record<string, readonly string[]>>;\n\n private readonly lookup: Map<string, Map<string, string>>;\n\n constructor(entries: Iterable<AuthioResourceAccessRole>) {\n this.entries = Object.freeze([...entries]);\n this.roles = Object.freeze(distinctIgnoringCase(this.entries.map((entry) => entry.name)));\n this.lookup = new Map();\n\n const permissions: Record<string, string[]> = {};\n const spelling = new Map<string, string>();\n\n for (const entry of this.entries) {\n for (const [resource, methods] of Object.entries(entry.permissions)) {\n const resourceKey = resource.toLowerCase();\n let allowed = this.lookup.get(resourceKey);\n\n if (!allowed) {\n allowed = new Map();\n this.lookup.set(resourceKey, allowed);\n spelling.set(resourceKey, resource);\n permissions[resource] = [];\n }\n\n for (const method of methods) {\n const methodKey = method.toLowerCase();\n\n if (allowed.has(methodKey)) continue;\n\n allowed.set(methodKey, method);\n permissions[spelling.get(resourceKey)!]!.push(method);\n }\n }\n }\n\n this.permissions = Object.freeze(Object.fromEntries(Object.entries(permissions).map(([name, methods]) => [name, Object.freeze(methods)])));\n }\n\n /** Whether no role was read. */\n get isEmpty(): boolean {\n return this.entries.length === 0;\n }\n\n /**\n * Whether the token holds the role, from any source or only from the given ones.\n */\n hasRole(role: string, sources?: readonly AuthioResourceAccessSource[]): boolean {\n if (!role) return false;\n\n const wanted = role.toLowerCase();\n\n return this.entries.some((entry) => inSources(entry, sources) && entry.name.toLowerCase() === wanted);\n }\n\n /**\n * Authio's grant rule: whether any role (from any source, or only from the given ones) allows `method` on\n * `resource`.\n */\n grants(resource: string, method: string, sources?: readonly AuthioResourceAccessSource[]): boolean {\n if (!resource || !method) return false;\n\n if (!sources || sources.length === 0) return this.lookup.get(resource.toLowerCase())?.has(method.toLowerCase()) ?? false;\n\n return this.entries.some((entry) => inSources(entry, sources) && entryGrants(entry, resource, method));\n }\n\n /**\n * The roles that came from one source.\n */\n fromSource(source: AuthioResourceAccessSource): AuthioResourceAccessRole[] {\n return this.entries.filter((entry) => entry.source === source);\n }\n}\n\n/**\n * The source a claim name stands for, when it is one of the seven `*_resource_access` claims.\n */\nexport function resourceAccessSourceOf(claimType: string | undefined | null): AuthioResourceAccessSource | undefined {\n return claimType ? claimSources.get(claimType.toLowerCase()) : undefined;\n}\n\n/**\n * Reads the roles of every `*_resource_access` claim. Takes a JWT payload or introspection answer, or\n * `[type, value]` pairs; each value may be the JSON object itself or its JSON text. Other claims are ignored.\n */\nexport function parseResourceAccess(claims: Readonly<Record<string, unknown>> | Iterable<readonly [string, unknown]>): AuthioResourceAccess {\n const pairs: Iterable<readonly [string, unknown]> = isIterable(claims) ? claims : Object.entries(claims);\n const roles: AuthioResourceAccessRole[] = [];\n\n for (const [type, value] of pairs) {\n const source = resourceAccessSourceOf(type);\n\n if (source) roles.push(...parseResourceAccessClaim(source, value));\n }\n\n return roles.length === 0 ? AuthioResourceAccess.empty : new AuthioResourceAccess(roles);\n}\n\n/**\n * Reads the roles of one claim value, as strictly as Authio does: a value that is not exactly\n * `{role: {resource: [method]}}` contributes nothing at all. `null` roles, resources and methods are allowed and grant\n * nothing.\n */\nexport function parseResourceAccessClaim(source: AuthioResourceAccessSource, value: unknown): AuthioResourceAccessRole[] {\n const root = typeof value === \"string\" ? parseJson(value) : value;\n\n if (!isPlainObject(root)) return [];\n\n const roles: AuthioResourceAccessRole[] = [];\n\n for (const [name, rolePermissions] of Object.entries(root)) {\n const permissions = readPermissions(rolePermissions);\n\n if (!permissions) return [];\n\n roles.push(Object.freeze({ source, name, permissions }));\n }\n\n return roles;\n}\n\nfunction readPermissions(value: unknown): Readonly<Record<string, readonly string[]>> | undefined {\n if (value === null) return Object.freeze({});\n if (!isPlainObject(value)) return undefined;\n\n const read: Record<string, readonly string[]> = {};\n const seen = new Set<string>();\n\n for (const [resource, methods] of Object.entries(value)) {\n const key = resource.toLowerCase();\n\n if (methods === null) {\n if (!seen.has(key)) {\n seen.add(key);\n read[resource] = Object.freeze([]);\n }\n continue;\n }\n\n if (!Array.isArray(methods)) return undefined;\n\n const allowed: string[] = [];\n\n for (const method of methods) {\n if (typeof method === \"string\") allowed.push(method);\n else if (method !== null) return undefined;\n }\n\n if (!seen.has(key)) {\n seen.add(key);\n read[resource] = Object.freeze(allowed);\n }\n }\n\n return Object.freeze(read);\n}\n\nfunction entryGrants(entry: AuthioResourceAccessRole, resource: string, method: string): boolean {\n const resourceKey = resource.toLowerCase();\n const methodKey = method.toLowerCase();\n\n for (const [name, methods] of Object.entries(entry.permissions)) {\n if (name.toLowerCase() === resourceKey) return methods.some((allowed) => allowed.toLowerCase() === methodKey);\n }\n\n return false;\n}\n\nfunction inSources(entry: AuthioResourceAccessRole, sources: readonly AuthioResourceAccessSource[] | undefined): boolean {\n return !sources || sources.length === 0 || sources.includes(entry.source);\n}\n\nfunction distinctIgnoringCase(values: readonly string[]): string[] {\n const seen = new Set<string>();\n\n return values.filter((value) => {\n const key = value.toLowerCase();\n\n if (seen.has(key)) return false;\n\n seen.add(key);\n return true;\n });\n}\n\nfunction parseJson(text: string): unknown {\n if (!text.trim()) return undefined;\n\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isIterable(value: unknown): value is Iterable<readonly [string, unknown]> {\n return typeof value === \"object\" && value !== null && typeof (value as Iterable<unknown>)[Symbol.iterator] === \"function\";\n}\n","import { AuthioDefaults, AuthioWebhookEventTypes } from \"./constants.js\";\n\n/**\n * Why a webhook delivery failed verification.\n */\nexport type AuthioWebhookVerificationFailure =\n | \"missing_signature\"\n | \"malformed_signature\"\n | \"signature_mismatch\"\n | \"timestamp_outside_tolerance\";\n\n/**\n * The outcome of verifying a webhook signature.\n */\nexport type AuthioWebhookVerificationResult =\n | { readonly valid: true; readonly timestamp: Date }\n | { readonly valid: false; readonly failure: AuthioWebhookVerificationFailure; readonly reason: string; readonly timestamp?: Date };\n\n/**\n * A webhook event. `data` holds the event-specific payload as delivered (snake_case); read it typed, in camelCase,\n * with the `as…` helpers.\n */\nexport interface AuthioWebhookEvent {\n readonly id: string;\n readonly type: string;\n /** Seconds since the epoch. */\n readonly created_at: number;\n readonly realm_id?: string | null;\n readonly client_id?: string | null;\n readonly data: unknown;\n [member: string]: unknown;\n}\n\n/** `user_created`, `user_updated`, `user_deleted`, as delivered. */\nexport interface AuthioWebhookUserData {\n id: string;\n username?: string | null;\n email?: string | null;\n first_name?: string | null;\n last_name?: string | null;\n email_confirmed: boolean;\n status?: string | null;\n realm_id?: string | null;\n client_id?: string | null;\n}\n\n/** `login_succeeded`, `login_failed`, as delivered. */\nexport interface AuthioWebhookLoginData {\n grant_type?: string | null;\n user_id?: string | null;\n username?: string | null;\n email?: string | null;\n ip_address?: string | null;\n user_agent?: string | null;\n session_id?: string | null;\n failure_reason?: string | null;\n resource?: string | null;\n scopes?: string[] | null;\n authentication_methods?: string[] | null;\n acr?: string | null;\n identity_provider?: string | null;\n consumer_id?: string | null;\n consumer_name?: string | null;\n}\n\n/** `user_locked_out`, as delivered. */\nexport interface AuthioWebhookUserLockedOutData {\n user_id: string;\n username?: string | null;\n email?: string | null;\n lockout_end?: string | null;\n access_failed_count: number;\n}\n\n/** `token_revoked`, as delivered. */\nexport interface AuthioWebhookTokenRevokedData {\n token_id?: string | null;\n subject?: string | null;\n session_id?: string | null;\n token_type_hint?: string | null;\n}\n\n/**\n * `keys_rotated`, as delivered: `rotation_days` and `automatic` on a scheduled rotation, `revoked_keys_count` on a\n * manual one.\n */\nexport interface AuthioWebhookKeysRotatedData {\n signing_key_id?: string | null;\n encryption_key_id?: string | null;\n revoked_keys_count?: number | null;\n rotation_days?: number | null;\n automatic?: boolean | null;\n}\n\n/** `token_reuse_detected`, as delivered. */\nexport interface AuthioWebhookTokenReuseDetectedData {\n token_id?: string | null;\n subject?: string | null;\n session_id?: string | null;\n ip_address?: string | null;\n user_agent?: string | null;\n}\n\n/** `admin_resource_created`, `admin_resource_updated`, `admin_resource_deleted`, as delivered. */\nexport interface AuthioWebhookAdminResourceData {\n action?: string | null;\n resource_type?: string | null;\n resource_id?: string | null;\n parent_id?: string | null;\n realm_id?: string | null;\n client_id?: string | null;\n /** `User` or `Credential`. */\n actor_type?: string | null;\n actor_user_id?: string | null;\n actor_username?: string | null;\n actor_email?: string | null;\n actor_credential_id?: string | null;\n actor_credential_name?: string | null;\n actor_platform_operator?: boolean | null;\n ip_address?: string | null;\n method?: string | null;\n path?: string | null;\n /** What changed, by resource type; kept as delivered. */\n details?: Record<string, unknown> | null;\n}\n\n/** `user_suspended`, `user_suspension_ended`, as delivered. */\nexport interface AuthioWebhookUserSuspensionData {\n id: string;\n user_id: string;\n level?: string | null;\n status?: string | null;\n starts_at?: string | null;\n ends_at?: string | null;\n restricted_scopes: string[];\n revokes_every_role: boolean;\n revoked_role_ids: string[];\n sessions_terminated_at?: string | null;\n lifted_at?: string | null;\n}\n\n/** `attack_detected`, as delivered: an attack on the realm and the measure Authio took. */\nexport interface AuthioWebhookAttackDetectedData {\n incident_id: string;\n /** Such as `credential_stuffing`. */\n kind?: string | null;\n severity?: string | null;\n /** Such as `source_blocked`. */\n measure?: string | null;\n ip_address?: string | null;\n country?: string | null;\n asn?: number | null;\n network_operator?: string | null;\n user_id?: string | null;\n started_at?: string | null;\n}\n\n/** `credential_compromised`, as delivered: a person's password was used by an attacker. */\nexport interface AuthioWebhookCredentialCompromisedData {\n incident_id: string;\n user_id?: string | null;\n username?: string | null;\n ip_address?: string | null;\n country?: string | null;\n asn?: number | null;\n network_operator?: string | null;\n password_change_required?: boolean | null;\n}\n\n/** `ping`, as delivered. */\nexport interface AuthioWebhookPingData {\n message?: string | null;\n subscription?: string | null;\n}\n\n/**\n * The data shape of each event type, as delivered (snake_case).\n */\nexport interface AuthioWebhookDataByType {\n user_created: AuthioWebhookUserData;\n user_updated: AuthioWebhookUserData;\n user_deleted: AuthioWebhookUserData;\n login_succeeded: AuthioWebhookLoginData;\n login_failed: AuthioWebhookLoginData;\n user_locked_out: AuthioWebhookUserLockedOutData;\n token_revoked: AuthioWebhookTokenRevokedData;\n keys_rotated: AuthioWebhookKeysRotatedData;\n token_reuse_detected: AuthioWebhookTokenReuseDetectedData;\n admin_resource_created: AuthioWebhookAdminResourceData;\n admin_resource_updated: AuthioWebhookAdminResourceData;\n admin_resource_deleted: AuthioWebhookAdminResourceData;\n user_suspended: AuthioWebhookUserSuspensionData;\n user_suspension_ended: AuthioWebhookUserSuspensionData;\n attack_detected: AuthioWebhookAttackDetectedData;\n credential_compromised: AuthioWebhookCredentialCompromisedData;\n ping: AuthioWebhookPingData;\n}\n\n/**\n * A snake_case name in camelCase.\n */\nexport type AuthioCamelCase<S extends string> = S extends `${infer Head}_${infer Tail}` ? `${Head}${Capitalize<AuthioCamelCase<Tail>>}` : S;\n\n/**\n * An object whose top-level member names are turned into camelCase, values unchanged.\n */\nexport type AuthioCamelCased<T> = { [K in keyof T as K extends string ? AuthioCamelCase<K> : K]: T[K] };\n\n/** The data of a user event, as the typed accessor exposes it. */\nexport type AuthioWebhookUser = AuthioCamelCased<AuthioWebhookUserData>;\n/** The data of a login event, as the typed accessor exposes it. */\nexport type AuthioWebhookLogin = AuthioCamelCased<AuthioWebhookLoginData>;\n/** The data of a lockout event, as the typed accessor exposes it. */\nexport type AuthioWebhookUserLockedOut = AuthioCamelCased<AuthioWebhookUserLockedOutData>;\n/** The data of a revocation event, as the typed accessor exposes it. */\nexport type AuthioWebhookTokenRevoked = AuthioCamelCased<AuthioWebhookTokenRevokedData>;\n/** The data of a key rotation event, as the typed accessor exposes it. */\nexport type AuthioWebhookKeysRotated = AuthioCamelCased<AuthioWebhookKeysRotatedData>;\n/** The data of a refresh token reuse event, as the typed accessor exposes it. */\nexport type AuthioWebhookTokenReuseDetected = AuthioCamelCased<AuthioWebhookTokenReuseDetectedData>;\n/** The data of an admin resource event, as the typed accessor exposes it. */\nexport type AuthioWebhookAdminResource = AuthioCamelCased<AuthioWebhookAdminResourceData>;\n/** The data of a suspension event, as the typed accessor exposes it. */\nexport type AuthioWebhookUserSuspension = AuthioCamelCased<AuthioWebhookUserSuspensionData>;\n/** The data of an attack event, as the typed accessor exposes it. */\nexport type AuthioWebhookAttackDetected = AuthioCamelCased<AuthioWebhookAttackDetectedData>;\n/** The data of a compromised credential event, as the typed accessor exposes it. */\nexport type AuthioWebhookCredentialCompromised = AuthioCamelCased<AuthioWebhookCredentialCompromisedData>;\n/** The data of a ping, as the typed accessor exposes it. */\nexport type AuthioWebhookPing = AuthioCamelCased<AuthioWebhookPingData>;\n\n/**\n * An event narrowed to one type, with its data typed as delivered.\n */\nexport type AuthioTypedWebhookEvent<T extends keyof AuthioWebhookDataByType> = AuthioWebhookEvent & {\n readonly type: T;\n readonly data: AuthioWebhookDataByType[T];\n};\n\nconst encoder = new TextEncoder();\n\n/**\n * Verifies the `X-Authio-Signature` header (`t={unixSeconds},v1={hex}`) against the raw body: HMAC-SHA256 of\n * `{t}.{body}` with the secret, compared in constant time, any matching `v1` accepted, the signature checked before\n * the timestamp.\n *\n * @param signatureHeader The header value.\n * @param rawBody The body exactly as received.\n * @param secret The webhook's secret.\n * @param options `tolerance` in seconds (default 300) and `now` in milliseconds (default the current time).\n */\nexport async function verifyWebhookSignature(\n signatureHeader: string | null | undefined,\n rawBody: string | Uint8Array,\n secret: string,\n options: { tolerance?: number; now?: number } = {},\n): Promise<AuthioWebhookVerificationResult> {\n if (!secret) throw new TypeError(\"secret is required.\");\n\n if (!signatureHeader?.trim())\n return { valid: false, failure: \"missing_signature\", reason: \"The X-Authio-Signature header is missing.\" };\n\n const parsed = parseSignatureHeader(signatureHeader);\n\n if (!parsed)\n return {\n valid: false,\n failure: \"malformed_signature\",\n reason: \"The X-Authio-Signature header is not of the form t={unixSeconds},v1={hex}.\",\n };\n\n const signedAt = new Date(parsed.timestamp * 1000);\n const expected = await computeSignature(parsed.timestamp, rawBody, secret);\n let matched = false;\n\n for (const signature of parsed.signatures) matched = constantTimeEquals(expected, signature) || matched;\n\n if (!matched)\n return {\n valid: false,\n failure: \"signature_mismatch\",\n reason: \"No v1 signature matches the body: the secret is wrong or the body was altered.\",\n timestamp: signedAt,\n };\n\n const tolerance = (options.tolerance ?? AuthioDefaults.WebhookTolerance) * 1000;\n const now = options.now ?? Date.now();\n\n if (Math.abs(now - signedAt.getTime()) > tolerance)\n return {\n valid: false,\n failure: \"timestamp_outside_tolerance\",\n reason: `The signature was made at ${signedAt.toISOString()}, more than ${tolerance / 1000} seconds from now.`,\n timestamp: signedAt,\n };\n\n return { valid: true, timestamp: signedAt };\n}\n\n/**\n * Computes the `X-Authio-Signature` value Authio would send, for tests and replays.\n *\n * @param timestamp Milliseconds since the epoch, or a date.\n */\nexport async function computeWebhookSignatureHeader(rawBody: string | Uint8Array, secret: string, timestamp: number | Date): Promise<string> {\n if (!secret) throw new TypeError(\"secret is required.\");\n\n const seconds = Math.floor((timestamp instanceof Date ? timestamp.getTime() : timestamp) / 1000);\n const signature = await computeSignature(seconds, rawBody, secret);\n\n return `t=${seconds},v1=${[...signature].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/**\n * Parses a webhook body.\n *\n * @throws SyntaxError when it is not JSON or has no `type`.\n */\nexport function parseWebhookEvent(rawBody: string | Uint8Array): AuthioWebhookEvent {\n const text = typeof rawBody === \"string\" ? rawBody : new TextDecoder().decode(rawBody);\n const value = JSON.parse(text) as AuthioWebhookEvent | null;\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new SyntaxError(\"The webhook body is empty.\");\n if (typeof value.type !== \"string\" || !value.type) throw new SyntaxError(\"The webhook body has no type.\");\n\n return value;\n}\n\n/**\n * Parses a webhook body, or returns `undefined` when it cannot be read.\n */\nexport function tryParseWebhookEvent(rawBody: string | Uint8Array | null | undefined): AuthioWebhookEvent | undefined {\n if (rawBody === null || rawBody === undefined) return undefined;\n\n try {\n return parseWebhookEvent(rawBody);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether the event is of one of the given types, narrowing its data.\n */\nexport function isWebhookEventOfType<T extends keyof AuthioWebhookDataByType>(\n event: AuthioWebhookEvent,\n ...types: T[]\n): event is AuthioTypedWebhookEvent<T> {\n return (types as string[]).includes(event.type);\n}\n\n/** The data of a user event in camelCase, or `undefined` for any other type. */\nexport const asUserEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookUser>(event, AuthioWebhookEventTypes.UserCreated, AuthioWebhookEventTypes.UserUpdated, AuthioWebhookEventTypes.UserDeleted);\n/** The data of a login event in camelCase, or `undefined` for any other type. */\nexport const asLoginEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookLogin>(event, AuthioWebhookEventTypes.LoginSucceeded, AuthioWebhookEventTypes.LoginFailed);\n/** The data of a lockout event in camelCase, or `undefined` for any other type. */\nexport const asUserLockedOutEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookUserLockedOut>(event, AuthioWebhookEventTypes.UserLockedOut);\n/** The data of a revocation event in camelCase, or `undefined` for any other type. */\nexport const asTokenRevokedEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookTokenRevoked>(event, AuthioWebhookEventTypes.TokenRevoked);\n/** The data of a key rotation event in camelCase, or `undefined` for any other type. */\nexport const asKeysRotatedEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookKeysRotated>(event, AuthioWebhookEventTypes.KeysRotated);\n/** The data of a refresh token reuse event in camelCase, or `undefined` for any other type. */\nexport const asTokenReuseDetectedEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookTokenReuseDetected>(event, AuthioWebhookEventTypes.TokenReuseDetected);\n/** The data of an admin resource event in camelCase, or `undefined` for any other type. */\nexport const asAdminResourceEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookAdminResource>(\n event,\n AuthioWebhookEventTypes.AdminResourceCreated,\n AuthioWebhookEventTypes.AdminResourceUpdated,\n AuthioWebhookEventTypes.AdminResourceDeleted,\n );\n/** The data of a suspension event in camelCase, or `undefined` for any other type. */\nexport const asUserSuspensionEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookUserSuspension>(event, AuthioWebhookEventTypes.UserSuspended, AuthioWebhookEventTypes.UserSuspensionEnded);\n/** The data of an attack event in camelCase, or `undefined` for any other type. */\nexport const asAttackDetectedEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookAttackDetected>(event, AuthioWebhookEventTypes.AttackDetected);\n/** The data of a compromised credential event in camelCase, or `undefined` for any other type. */\nexport const asCredentialCompromisedEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookCredentialCompromised>(event, AuthioWebhookEventTypes.CredentialCompromised);\n/** The data of a ping in camelCase, or `undefined` for any other type. */\nexport const asPingEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookPing>(event, AuthioWebhookEventTypes.Ping);\n\nconst knownEventTypes = new Set<string>(Object.values(AuthioWebhookEventTypes));\n\n/**\n * Whether Authio documents the event type. An unknown type still parses; read its `data` as delivered.\n */\nexport function isKnownWebhookEventType(type: string): type is keyof AuthioWebhookDataByType {\n return knownEventTypes.has(type);\n}\n\n/**\n * The data of any known event in camelCase (what the typed accessor of its type returns), or `undefined` for an\n * unknown type.\n */\nexport function readWebhookEventData(event: AuthioWebhookEvent): Record<string, unknown> | undefined {\n return isKnownWebhookEventType(event.type) ? dataWhen<Record<string, unknown>>(event, event.type) : undefined;\n}\n\n/**\n * Turns the top-level member names of an object from snake_case into camelCase, leaving the values as they are.\n */\nexport function toCamelCasedMembers<T extends object>(value: T): AuthioCamelCased<T> {\n const result: Record<string, unknown> = {};\n\n for (const [name, member] of Object.entries(value)) result[name.replace(/_([a-z0-9])/g, (_, letter: string) => letter.toUpperCase())] = member;\n\n return result as AuthioCamelCased<T>;\n}\n\nfunction dataWhen<T>(event: AuthioWebhookEvent, ...types: string[]): T | undefined {\n return types.includes(event.type) && event.data !== null && typeof event.data === \"object\" && !Array.isArray(event.data)\n ? (toCamelCasedMembers(event.data) as T)\n : undefined;\n}\n\nfunction parseSignatureHeader(header: string): { timestamp: number; signatures: Uint8Array[] } | undefined {\n let timestamp = 0;\n let timestamps = 0;\n const signatures: Uint8Array[] = [];\n\n for (const raw of header.split(\",\")) {\n const part = raw.trim();\n\n if (!part) continue;\n\n const separator = part.indexOf(\"=\");\n\n if (separator <= 0) return undefined;\n\n const key = part.slice(0, separator);\n const value = part.slice(separator + 1);\n\n if (key === \"t\") {\n timestamps++;\n\n if (!/^\\d+$/.test(value)) return undefined;\n\n timestamp = Number(value);\n } else if (key === \"v1\" && value.length === 64 && /^[0-9a-fA-F]+$/.test(value)) {\n signatures.push(Uint8Array.from(value.match(/../g)!.map((pair) => parseInt(pair, 16))));\n }\n }\n\n return timestamps === 1 && signatures.length > 0 && Number.isSafeInteger(timestamp) ? { timestamp, signatures } : undefined;\n}\n\nasync function computeSignature(timestamp: number, rawBody: string | Uint8Array, secret: string): Promise<Uint8Array> {\n const prefix = encoder.encode(`${timestamp}.`);\n const body = typeof rawBody === \"string\" ? encoder.encode(rawBody) : rawBody;\n const message = new Uint8Array(prefix.length + body.length);\n\n message.set(prefix, 0);\n message.set(body, prefix.length);\n\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n\n return new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, message));\n}\n\nfunction constantTimeEquals(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false;\n\n let difference = 0;\n\n for (let index = 0; index < left.length; index++) difference |= left[index]! ^ right[index]!;\n\n return difference === 0;\n}\n"]}
1
+ {"version":3,"sources":["../src/constants.ts","../src/errors.ts","../src/options.ts","../src/http.ts","../src/discovery.ts","../src/keys.ts","../src/client-authentication.ts","../src/encryption.ts","../src/token-validation.ts","../src/authorization.ts","../src/client.ts","../src/admin.ts","../src/resource-access.ts","../src/webhooks.ts"],"names":["importPKCS8","importJWK","errors","algorithmOf","decodeProtectedHeader","toBase64Url","token","withoutUndefined","textOf","parseJson","seconds"],"mappings":";;;AAGO,IAAM,gBAAA,GAAmB;AAAA,EAC9B,OAAA,EAAS,KAAA;AAAA,EACT,KAAA,EAAO,KAAA;AAAA,EACP,MAAA,EAAQ,KAAA;AAAA,EACR,QAAA,EAAU,KAAA;AAAA,EACV,UAAA,EAAY,KAAA;AAAA,EACZ,QAAA,EAAU,KAAA;AAAA,EACV,SAAA,EAAW,KAAA;AAAA,EACX,QAAA,EAAU,WAAA;AAAA,EACV,SAAA,EAAW,KAAA;AAAA,EACX,eAAA,EAAiB,KAAA;AAAA,EACjB,KAAA,EAAO,OAAA;AAAA,EACP,SAAA,EAAW,KAAA;AAAA,EACX,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n Audience: \"aud\",\n Expiration: \"exp\",\n IssuedAt: \"iat\",\n NotBefore: \"nbf\",\n AuthTime: \"auth_time\",\n TokenType: \"typ\",\n AuthorizedParty: \"azp\",\n Scope: \"scope\",\n SessionId: \"sid\",\n AuthenticationContextClass: \"acr\",\n AuthenticationMethods: \"amr\",\n IdentityProvider: \"idp\",\n Nonce: \"nonce\",\n AccessTokenHash: \"at_hash\",\n Events: \"events\",\n OrganizationId: \"org_id\",\n OrganizationAlias: \"org_alias\",\n AccountId: \"account_id\",\n Actor: \"act\",\n DelegationId: \"delegation_id\",\n ClientId: \"client_id\",\n Name: \"name\",\n GivenName: \"given_name\",\n FamilyName: \"family_name\",\n UniqueName: \"unique_name\",\n PreferredUsername: \"preferred_username\",\n UpdatedAt: \"updated_at\",\n Email: \"email\",\n EmailVerified: \"email_verified\",\n PhoneNumber: \"phone_number\",\n PhoneNumberVerified: \"phone_number_verified\",\n ConsumerName: \"consumer_name\",\n CredentialId: \"credential_id\",\n CredentialType: \"credential_type\",\n CredentialName: \"credential_name\",\n CredentialRealm: \"credential_realm\",\n CredentialClient: \"credential_client\",\n ActorType: \"actor_type\",\n OwnerUserId: \"owner_user_id\",\n OwnerUsername: \"owner_username\",\n UserResourceAccess: \"user_resource_access\",\n RealmResourceAccess: \"realm_resource_access\",\n ClientResourceAccess: \"client_resource_access\",\n PlanResourceAccess: \"plan_resource_access\",\n ConsumerResourceAccess: \"consumer_resource_access\",\n SecretResourceAccess: \"secret_resource_access\",\n SystemResourceAccess: \"system_resource_access\",\n} as const;\n\n/**\n * Where a role in a `*_resource_access` claim was granted.\n *\n * - `user`: to the person, directly or through one of their groups.\n * - `realm`: to everyone who signs in to the realm.\n * - `client`: to everyone who signs in through the client.\n * - `plan`: by the plan of an Authio platform account (platform users only).\n * - `consumer`: to a machine consumer of the client.\n * - `secret`: to an account credential (API key, client secret, personal access token).\n * - `system`: to an Authio platform user (the console).\n */\nexport type AuthioResourceAccessSource = \"user\" | \"realm\" | \"client\" | \"plan\" | \"consumer\" | \"secret\" | \"system\";\n\n/**\n * The seven `*_resource_access` claim names, mapped to their source.\n */\nexport const AuthioResourceAccessClaims: Readonly<Record<string, AuthioResourceAccessSource>> = Object.freeze({\n [AuthioClaimTypes.UserResourceAccess]: \"user\",\n [AuthioClaimTypes.RealmResourceAccess]: \"realm\",\n [AuthioClaimTypes.ClientResourceAccess]: \"client\",\n [AuthioClaimTypes.PlanResourceAccess]: \"plan\",\n [AuthioClaimTypes.ConsumerResourceAccess]: \"consumer\",\n [AuthioClaimTypes.SecretResourceAccess]: \"secret\",\n [AuthioClaimTypes.SystemResourceAccess]: \"system\",\n});\n\n/**\n * Scopes Authio defines.\n */\nexport const AuthioScopes = {\n OpenId: \"openid\",\n Profile: \"profile\",\n Email: \"email\",\n Phone: \"phone\",\n Roles: \"roles\",\n OfflineAccess: \"offline_access\",\n} as const;\n\n/**\n * Grant types Authio's token endpoint accepts.\n */\nexport const AuthioGrantTypes = {\n AuthorizationCode: \"authorization_code\",\n RefreshToken: \"refresh_token\",\n ClientCredentials: \"client_credentials\",\n Password: \"password\",\n DeviceCode: \"urn:ietf:params:oauth:grant-type:device_code\",\n TokenExchange: \"urn:ietf:params:oauth:grant-type:token-exchange\",\n PersonalAccessToken: \"personal_access_token\",\n} as const;\n\n/**\n * Token type identifiers.\n */\nexport const AuthioTokenTypes = {\n AccessTokenUrn: \"urn:ietf:params:oauth:token-type:access_token\",\n ConnectionAccessTokenUrn: \"urn:authio:params:oauth:token-type:connection-access-token\",\n AccessToken: \"access_token\",\n RefreshToken: \"refresh_token\",\n} as const;\n\n/**\n * OAuth error codes Authio answers with.\n */\nexport const AuthioOAuthErrors = {\n InvalidRequest: \"invalid_request\",\n InvalidClient: \"invalid_client\",\n InvalidGrant: \"invalid_grant\",\n UnauthorizedClient: \"unauthorized_client\",\n UnsupportedGrantType: \"unsupported_grant_type\",\n InvalidScope: \"invalid_scope\",\n InvalidTarget: \"invalid_target\",\n AccessDenied: \"access_denied\",\n InvalidToken: \"invalid_token\",\n AuthorizationPending: \"authorization_pending\",\n SlowDown: \"slow_down\",\n ExpiredToken: \"expired_token\",\n ConnectionRequired: \"connection_required\",\n ConnectionSelectionRequired: \"connection_selection_required\",\n ConnectionPolicyViolation: \"connection_policy_violation\",\n ServerError: \"server_error\",\n TemporarilyUnavailable: \"temporarily_unavailable\",\n LoginRequired: \"login_required\",\n InteractionRequired: \"interaction_required\",\n ConsentRequired: \"consent_required\",\n AccountSelectionRequired: \"account_selection_required\",\n InsufficientScope: \"insufficient_scope\",\n InsufficientUserAuthentication: \"insufficient_user_authentication\",\n} as const;\n\n/**\n * Webhook event types.\n */\nexport const AuthioWebhookEventTypes = {\n UserCreated: \"user_created\",\n UserUpdated: \"user_updated\",\n UserDeleted: \"user_deleted\",\n LoginSucceeded: \"login_succeeded\",\n LoginFailed: \"login_failed\",\n UserLockedOut: \"user_locked_out\",\n TokenRevoked: \"token_revoked\",\n KeysRotated: \"keys_rotated\",\n TokenReuseDetected: \"token_reuse_detected\",\n AdminResourceCreated: \"admin_resource_created\",\n AdminResourceUpdated: \"admin_resource_updated\",\n AdminResourceDeleted: \"admin_resource_deleted\",\n UserSuspended: \"user_suspended\",\n UserSuspensionEnded: \"user_suspension_ended\",\n AttackDetected: \"attack_detected\",\n CredentialCompromised: \"credential_compromised\",\n UserAuthenticatorAppEnrolled: \"user_authenticator_app_enrolled\",\n UserAuthenticatorAppRemoved: \"user_authenticator_app_removed\",\n UserRecoveryCodesRegenerated: \"user_recovery_codes_regenerated\",\n UserRecoveryCodeUsed: \"user_recovery_code_used\",\n Ping: \"ping\",\n} as const;\n\n/**\n * Headers Authio sends with a webhook delivery.\n */\nexport const AuthioWebhookHeaders = {\n Signature: \"X-Authio-Signature\",\n Event: \"X-Authio-Event\",\n EventId: \"X-Authio-Event-Id\",\n} as const;\n\n/**\n * Who called an API, read from the access token (see `conformance/callers.json`).\n *\n * - `user`: a person signed in (the token carries `auth_time`).\n * - `client`: a client authenticated as itself.\n * - `consumer`: a machine consumer of a client (`credential_type` `client_consumer`).\n * - `account_credential`: a credential of an Authio account (`credential_type` `account_secret`).\n */\nexport type AuthioCallerKind = \"user\" | \"client\" | \"consumer\" | \"account_credential\";\n\n/**\n * How a machine caller proved who it is.\n */\nexport type AuthioCredentialForm = \"client_secret\" | \"personal_access_token\" | \"api_key\" | \"consumer_api_key\";\n\n/**\n * The caller kinds.\n */\nexport const AuthioCallerKinds = [\"user\", \"client\", \"consumer\", \"account_credential\"] as const satisfies readonly AuthioCallerKind[];\n\n/**\n * The values of `prompt` Authio honours.\n */\nexport const AuthioPrompts = [\"none\", \"login\", \"select_account\", \"consent\"] as const;\n\n/**\n * A value of `prompt`.\n */\nexport type AuthioPrompt = (typeof AuthioPrompts)[number];\n\n/**\n * Asymmetric signing algorithms Authio issues tokens with and accepts in client assertions.\n */\nexport const AuthioAsymmetricAlgorithms = [\n \"RS256\",\n \"RS384\",\n \"RS512\",\n \"PS256\",\n \"PS384\",\n \"PS512\",\n \"ES256\",\n \"ES384\",\n \"ES512\",\n] as const;\n\n/**\n * Symmetric algorithms Authio may sign a client's tokens with. A client verifies them with its own client secret\n * (OpenID Connect Core §10.1), and only when `idTokenSignedResponseAlg` names one.\n */\nexport const AuthioHmacAlgorithms = [\"HS256\", \"HS384\", \"HS512\"] as const;\n\n/**\n * The shortest client secret, in bytes of its UTF-8 form, each HS* algorithm is verified with: the size of the hash\n * output (RFC 7518 §3.2). Authio refuses a shorter secret for the algorithm, and so do the SDKs.\n */\nexport const AuthioHmacMinimumSecretBytes = Object.freeze({ HS256: 32, HS384: 48, HS512: 64 }) as Readonly<Record<(typeof AuthioHmacAlgorithms)[number], number>>;\n\n/**\n * Defaults shared by every Authio SDK.\n */\nexport const AuthioDefaults = {\n DiscoveryPath: \"/.well-known/openid-configuration\",\n ProtectedResourceMetadataPath: \"/.well-known/oauth-protected-resource\",\n RedactedValue: \"[redacted]\",\n PlatformRealm: \"authio\",\n PlatformClientId: \"authio\",\n ApiKeyPrefix: \"ak_\",\n ClientSecretPrefix: \"cs_\",\n PersonalAccessTokenPrefix: \"pat_\",\n /** The `client_id` an account credential's client secret is exchanged with: `cred_` and the credential id (format N). */\n CredentialClientIdPrefix: \"cred_\",\n ApiKeyHeader: \"x-api-key\",\n RequestIdHeader: \"X-Request-Id\",\n /** The header `typ` of an access token (RFC 9068 §2.1). */\n AccessTokenType: \"at+jwt\",\n /** The header `typ` of a back-channel logout token. */\n LogoutTokenType: \"logout+jwt\",\n /** The event a back-channel logout token carries. */\n BackchannelLogoutEvent: \"http://schemas.openid.net/event/backchannel-logout\",\n /** Seconds. */\n ClockSkew: 30,\n /** Seconds. */\n ClientAssertionLifetime: 120,\n /** Seconds. */\n MaxClientAssertionLifetime: 3600,\n /** Seconds. */\n DeviceInterval: 5,\n /** Seconds. */\n DeviceSlowDownIncrement: 5,\n /** Seconds a token without `expires_in` is assumed to live. */\n AssumedTokenLifetime: 300,\n /** Seconds. */\n DiscoveryCacheDuration: 3600,\n /** Seconds. */\n HttpTimeout: 30,\n /** Seconds. */\n TokenRefreshSkew: 60,\n /** Seconds. */\n WebhookTolerance: 300,\n /** Smallest RSA key Authio verifies a client assertion from, in bits. */\n MinimumRsaKeySize: 2048,\n CredentialHeaders: [\"authorization\", \"proxy-authorization\", \"x-api-key\", \"cookie\", \"set-cookie\"],\n} as const;\n","/**\n * Base class of every error the Authio SDKs throw on purpose.\n */\nexport class AuthioError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/**\n * An OAuth error Authio answered with, or an answer the SDK could not read.\n *\n * `error` is the OAuth error code; `http_{status}` when the body carried none, and `invalid_response` when a success\n * body could not be read.\n */\nexport class AuthioProtocolError extends AuthioError {\n /** The OAuth error code. */\n readonly error: string;\n /** The OAuth error description. */\n readonly errorDescription: string | undefined;\n /** Authio's own error code (`error_code`), more specific than `error`. */\n readonly errorCode: string | undefined;\n /** The HTTP status, when the error came from a response. */\n readonly status: number | undefined;\n\n constructor(error: string, errorDescription?: string, errorCode?: string, status?: number, options?: { cause?: unknown }) {\n super(errorDescription ? `${error}: ${errorDescription}` : error, options);\n this.error = error;\n this.errorDescription = errorDescription;\n this.errorCode = errorCode;\n this.status = status;\n }\n}\n\n/**\n * The discovery document could not be read, or names another issuer.\n */\nexport class AuthioDiscoveryError extends AuthioError {}\n\n/**\n * The SDK was configured in a way it cannot work with.\n */\nexport class AuthioConfigurationError extends AuthioError {}\n\n/**\n * Why a token was refused, with the outcome names of `conformance/tokens.json`.\n */\nexport type AuthioTokenFailure =\n | \"not_access_token\"\n | \"not_id_token\"\n | \"invalid_audience\"\n | \"invalid_issuer\"\n | \"expired\"\n | \"not_yet_valid\"\n | \"invalid_signature\"\n | \"invalid_algorithm\"\n | \"reference_token\"\n | \"malformed\"\n | \"decryption_failed\"\n | \"legacy_algorithm\"\n | \"invalid_nonce\"\n | \"invalid_at_hash\"\n | \"authentication_too_old\"\n | \"invalid_logout_token\"\n | \"signing_keys_unavailable\";\n\n/**\n * A token (ID token, logout token, signed UserInfo, encrypted token) did not pass validation.\n */\nexport class AuthioTokenValidationError extends AuthioError {\n /** Why, as a stable code. */\n readonly reason: AuthioTokenFailure;\n\n constructor(reason: AuthioTokenFailure, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.reason = reason;\n }\n}\n\n/**\n * Why an authorization callback was refused before any code was exchanged.\n */\nexport type AuthioCallbackFailure = \"state_mismatch\" | \"issuer_mismatch\" | \"missing_issuer\" | \"missing_code\";\n\n/**\n * The authorization callback does not belong to the request this client made: `state` differs, the `iss` parameter\n * (RFC 9207) names another issuer or is missing where Authio sends it, or there is no code.\n */\nexport class AuthioCallbackError extends AuthioError {\n /** Why, as a stable code. */\n readonly reason: AuthioCallbackFailure;\n\n constructor(reason: AuthioCallbackFailure, message: string) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * One message of an Admin API error, optionally tied to a field of the request.\n */\nexport interface AuthioAdminNotification {\n readonly message: string;\n readonly field?: string;\n readonly code?: string;\n}\n\n/**\n * The Admin API refused a request. `errorCode` is the envelope's top-level `errorCode`; the HTTP status is read from\n * the response, never from the envelope's numeric `statusCode`.\n */\nexport class AuthioAdminError extends AuthioError {\n /** The HTTP status. */\n readonly status: number;\n /** Authio's error code, such as `ValidationFailed` or `RealmNotFound`. */\n readonly errorCode: string | undefined;\n /** The messages, with the field each one is about. */\n readonly notifications: readonly AuthioAdminNotification[];\n /** The request id, from the envelope or the `X-Request-Id` header. */\n readonly requestId: string | undefined;\n /** Seconds to wait before retrying, from `Retry-After` (`429` and `503`). */\n readonly retryAfterSeconds: number | undefined;\n\n constructor(details: {\n status: number;\n errorCode?: string;\n notifications?: readonly AuthioAdminNotification[];\n requestId?: string;\n retryAfterSeconds?: number;\n cause?: unknown;\n }) {\n const notifications = details.notifications ?? [];\n const summary = notifications.map((notification) => notification.message).filter(Boolean).join(\" \");\n\n super(\n `The Authio Admin API answered HTTP ${details.status}${details.errorCode ? ` (${details.errorCode})` : \"\"}${summary ? `: ${summary}` : \".\"}`,\n { cause: details.cause },\n );\n this.status = details.status;\n this.errorCode = details.errorCode;\n this.notifications = Object.freeze([...notifications]);\n this.requestId = details.requestId;\n this.retryAfterSeconds = details.retryAfterSeconds;\n }\n}\n","import { AuthioDefaults } from \"./constants.js\";\nimport { AuthioConfigurationError } from \"./errors.js\";\n\n/**\n * Time as the SDK sees it. Replace it in tests to control expiry, caching and device polling.\n */\nexport interface AuthioClock {\n /** Milliseconds since the epoch. */\n now(): number;\n /** Waits `ms` milliseconds; rejects when the signal aborts. */\n sleep(ms: number, signal?: AbortSignal): Promise<void>;\n}\n\n/**\n * The real clock.\n */\nexport const systemClock: AuthioClock = {\n now: () => Date.now(),\n sleep: (ms, signal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n }),\n};\n\n/**\n * Where Authio is and how to reach it. Shared by the client and the API verifier.\n */\nexport interface AuthioConnectionOptions {\n /**\n * The realm's issuer, such as `https://auth.example.com/realms/acme`. When absent it is composed from\n * `authority` and `realm`.\n */\n issuer?: string;\n /** Authio's base URL, such as `https://auth.example.com`. */\n authority?: string;\n /** The realm name. */\n realm?: string;\n /**\n * Refuses an `http` issuer or authority unless it is loopback. Defaults to `true`; turn it off only in\n * development.\n */\n requireHttps?: boolean;\n /** Seconds the discovery document is kept. Defaults to 3600. */\n discoveryCacheDuration?: number;\n /** Seconds every HTTP call may take. Defaults to 30. */\n httpTimeout?: number;\n /** The `fetch` every call goes through. Defaults to the global one. */\n fetch?: typeof fetch;\n /** The clock. Defaults to the system clock. */\n clock?: AuthioClock;\n}\n\n/**\n * How the client authenticates to the token, introspection, revocation and device endpoints: the client's\n * `token_endpoint_auth_method` in Authio, which Authio matches exactly.\n */\nexport type AuthioTokenEndpointAuthMethod = \"client_secret_basic\" | \"client_secret_post\" | \"private_key_jwt\" | \"none\";\n\n/**\n * The values of `tokenEndpointAuthMethod`.\n */\nexport const AuthioTokenEndpointAuthMethods = [\n \"client_secret_basic\",\n \"client_secret_post\",\n \"private_key_jwt\",\n \"none\",\n] as const satisfies readonly AuthioTokenEndpointAuthMethod[];\n\n/**\n * The connection settings, resolved once.\n */\nexport interface AuthioConnection {\n readonly issuer: string;\n readonly discoveryUrl: string;\n readonly requireHttps: boolean;\n readonly discoveryCacheDurationMs: number;\n readonly httpTimeoutMs: number;\n readonly fetch: typeof fetch;\n readonly clock: AuthioClock;\n}\n\n/**\n * Resolves and validates the connection settings.\n *\n * @throws AuthioConfigurationError when the issuer cannot be composed or is not HTTPS.\n */\nexport function resolveConnection(options: AuthioConnectionOptions): AuthioConnection {\n const requireHttps = options.requireHttps ?? true;\n const issuer = resolveIssuer(options);\n\n for (const [name, value] of [\n [\"authority\", options.authority],\n [\"issuer\", issuer],\n ] as const) {\n if (value && !isAllowedUrl(value, requireHttps))\n throw new AuthioConfigurationError(\n `The Authio ${name} '${value}' must be an absolute HTTPS URL (http is allowed only for loopback, or with requireHttps: false).`,\n );\n }\n\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n\n if (typeof fetchImplementation !== \"function\")\n throw new AuthioConfigurationError(\"No fetch implementation is available: pass options.fetch.\");\n\n return {\n issuer,\n discoveryUrl: issuer + AuthioDefaults.DiscoveryPath,\n requireHttps,\n discoveryCacheDurationMs: seconds(options.discoveryCacheDuration, AuthioDefaults.DiscoveryCacheDuration, \"discoveryCacheDuration\"),\n httpTimeoutMs: seconds(options.httpTimeout, AuthioDefaults.HttpTimeout, \"httpTimeout\"),\n fetch: fetchImplementation,\n clock: options.clock ?? systemClock,\n };\n}\n\n/**\n * The issuer: `issuer` when set, else `{authority}/realms/{realm}`.\n *\n * @throws AuthioConfigurationError when neither is configured.\n */\nexport function resolveIssuer(options: Pick<AuthioConnectionOptions, \"issuer\" | \"authority\" | \"realm\">): string {\n const issuer = options.issuer?.trim();\n\n if (issuer) return trimTrailingSlashes(issuer);\n\n const authority = options.authority?.trim();\n const realm = options.realm?.trim();\n\n if (!authority || !realm)\n throw new AuthioConfigurationError(\n \"The Authio issuer is not set, and authority and realm are not both set to compose it.\",\n );\n\n return `${trimTrailingSlashes(authority)}/realms/${escapeDataString(realm)}`;\n}\n\n/**\n * Whether a URL may be used to reach Authio: HTTPS, or HTTP on loopback (or anywhere when HTTPS is not required).\n */\nexport function isAllowedUrl(value: string, requireHttps: boolean): boolean {\n let url: URL;\n\n try {\n url = new URL(value);\n } catch {\n return false;\n }\n\n if (url.protocol === \"https:\") return true;\n\n return url.protocol === \"http:\" && (!requireHttps || isLoopback(url.hostname));\n}\n\n/**\n * Percent-encodes everything but RFC 3986 unreserved characters, as .NET's `Uri.EscapeDataString` does.\n */\nexport function escapeDataString(value: string): string {\n return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);\n}\n\n/**\n * Converts optional seconds to milliseconds, refusing negative or non-finite values.\n *\n * @internal\n */\nexport function seconds(value: number | undefined, fallback: number, name: string): number {\n const resolved = value ?? fallback;\n\n if (!Number.isFinite(resolved) || resolved < 0)\n throw new AuthioConfigurationError(`The Authio option ${name} must be a non-negative number of seconds.`);\n\n return resolved * 1000;\n}\n\nfunction trimTrailingSlashes(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction isLoopback(hostname: string): boolean {\n const host = hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n\n return host === \"localhost\" || host === \"::1\" || /^127(\\.\\d{1,3}){3}$/.test(host);\n}\n","import { AuthioDefaults } from \"./constants.js\";\nimport { AuthioProtocolError } from \"./errors.js\";\nimport type { AuthioConnection } from \"./options.js\";\n\n/**\n * The OAuth error body Authio answers with.\n */\nexport interface AuthioErrorResponse {\n error?: string;\n error_description?: string;\n error_code?: string;\n connect_uri?: string;\n connection_provider?: string;\n connections?: { id: string; label?: string; external_login?: string }[];\n [member: string]: unknown;\n}\n\n/**\n * Sends a request through the configured `fetch`, bounded by the HTTP timeout and the caller's signal.\n *\n * @internal\n */\nexport function send(connection: AuthioConnection, url: string, init: RequestInit, signal?: AbortSignal): Promise<Response> {\n const timeout = AbortSignal.timeout(connection.httpTimeoutMs);\n\n return connection.fetch(url, { ...init, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });\n}\n\n/**\n * Builds an `application/x-www-form-urlencoded` body, skipping empty values.\n *\n * @internal\n */\nexport function formBody(parameters: Record<string, string | undefined | null>): URLSearchParams {\n const form = new URLSearchParams();\n\n for (const [name, value] of Object.entries(parameters)) {\n if (value !== undefined && value !== null && value !== \"\") form.append(name, value);\n }\n\n return form;\n}\n\n/**\n * Joins scopes into one space-separated value, splitting values that already hold several and dropping duplicates.\n *\n * @returns `undefined` when there is no scope.\n */\nexport function toScopeString(scopes: Iterable<string> | string | undefined | null): string | undefined {\n if (scopes === undefined || scopes === null) return undefined;\n\n const values = typeof scopes === \"string\" ? [scopes] : [...scopes];\n const distinct = [...new Set(values.flatMap((scope) => (scope ?? \"\").split(\" \").filter(Boolean)))];\n\n return distinct.length === 0 ? undefined : distinct.join(\" \");\n}\n\n/**\n * Reads a JSON success body, or throws the OAuth error the response carries.\n *\n * @internal\n */\nexport async function readProtocolJson<T>(response: Response): Promise<T> {\n const body = await response.text();\n\n if (!response.ok) throw toProtocolError(body, response.status);\n\n return parseProtocolJson<T>(body, response.status);\n}\n\n/**\n * Throws the OAuth error a failed response carries.\n *\n * @internal\n */\nexport async function ensureProtocolSuccess(response: Response): Promise<void> {\n if (response.ok) return;\n\n throw toProtocolError(await response.text(), response.status);\n}\n\n/**\n * Parses a success body.\n *\n * @internal\n */\nexport function parseProtocolJson<T>(body: string, status: number): T {\n try {\n const value = JSON.parse(body) as unknown;\n\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new SyntaxError(\"The body is not a JSON object.\");\n\n return value as T;\n } catch (error) {\n throw new AuthioProtocolError(\n \"invalid_response\",\n `Authio answered with a body that could not be read: ${(error as Error).message}`,\n undefined,\n status,\n { cause: error },\n );\n }\n}\n\n/**\n * Reads the OAuth error of a body, when it has one.\n *\n * @internal\n */\nexport function toErrorResponse(body: string | undefined): AuthioErrorResponse | undefined {\n if (!body?.trim()) return undefined;\n\n try {\n const value = JSON.parse(body) as AuthioErrorResponse;\n\n return value && typeof value === \"object\" && typeof value.error === \"string\" && value.error ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The error a failed response stands for.\n *\n * @internal\n */\nexport function toProtocolError(body: string | undefined, status: number): AuthioProtocolError {\n const error = toErrorResponse(body);\n\n return error\n ? new AuthioProtocolError(error.error!, error.error_description, error.error_code, status)\n : new AuthioProtocolError(`http_${status}`, `Authio answered HTTP ${status} without an OAuth error.`, undefined, status);\n}\n\n/**\n * Makes `console.log` and `util.inspect` print `[redacted]` in place of the named members, without changing what\n * `JSON.stringify` or a spread sees.\n *\n * @internal\n */\nexport function redact<T extends object>(value: T, secrets: readonly string[]): T {\n Object.defineProperty(value, Symbol.for(\"nodejs.util.inspect.custom\"), {\n enumerable: false,\n value(this: Record<string, unknown>) {\n const copy: Record<string, unknown> = {};\n\n for (const [name, member] of Object.entries(this))\n copy[name] = secrets.includes(name) && member !== undefined && member !== null ? AuthioDefaults.RedactedValue : member;\n\n return copy;\n },\n });\n\n return value;\n}\n","import { AuthioDiscoveryError } from \"./errors.js\";\nimport { send } from \"./http.js\";\nimport { resolveConnection, type AuthioConnection, type AuthioConnectionOptions } from \"./options.js\";\n\n/**\n * The realm's OpenID Connect discovery document. Members not listed are kept as sent.\n */\nexport interface AuthioDiscoveryDocument {\n issuer: string;\n authorization_endpoint?: string;\n token_endpoint?: string;\n userinfo_endpoint?: string;\n jwks_uri?: string;\n introspection_endpoint?: string;\n revocation_endpoint?: string;\n end_session_endpoint?: string;\n device_authorization_endpoint?: string;\n pushed_authorization_request_endpoint?: string;\n scopes_supported?: string[];\n response_types_supported?: string[];\n response_modes_supported?: string[];\n grant_types_supported?: string[];\n subject_types_supported?: string[];\n id_token_signing_alg_values_supported?: string[];\n userinfo_signing_alg_values_supported?: string[];\n token_endpoint_auth_methods_supported?: string[];\n token_endpoint_auth_signing_alg_values_supported?: string[];\n introspection_endpoint_auth_methods_supported?: string[];\n revocation_endpoint_auth_methods_supported?: string[];\n code_challenge_methods_supported?: string[];\n claims_supported?: string[];\n prompt_values_supported?: string[];\n authorization_response_iss_parameter_supported?: boolean;\n frontchannel_logout_supported?: boolean;\n frontchannel_logout_session_supported?: boolean;\n [member: string]: unknown;\n}\n\n/**\n * Reads and caches the discovery document.\n */\nexport interface AuthioDiscoveryClient {\n /** The connection settings the client was built with. */\n readonly connection: AuthioConnection;\n /**\n * The document, read at most once per cache period (concurrent callers share one read).\n *\n * @throws AuthioDiscoveryError when it cannot be read or names another issuer.\n */\n get(signal?: AbortSignal): Promise<AuthioDiscoveryDocument>;\n /** Drops the cached document, so the next `get` reads it again. */\n invalidate(): void;\n}\n\n/**\n * Creates a discovery client. It needs no client credentials, so an API that only validates tokens can use it.\n */\nexport function createAuthioDiscoveryClient(options: AuthioConnectionOptions | AuthioConnection): AuthioDiscoveryClient {\n const connection = isConnection(options) ? options : resolveConnection(options);\n let cached: { document: AuthioDiscoveryDocument; fetchedAt: number } | undefined;\n let pending: Promise<AuthioDiscoveryDocument> | undefined;\n\n const fresh = () =>\n cached && connection.clock.now() - cached.fetchedAt < connection.discoveryCacheDurationMs ? cached.document : undefined;\n\n return {\n connection,\n async get(signal) {\n const current = fresh();\n\n if (current) return current;\n\n pending ??= fetchDocument(connection, signal)\n .then((document) => {\n cached = { document, fetchedAt: connection.clock.now() };\n return document;\n })\n .finally(() => {\n pending = undefined;\n });\n\n return pending;\n },\n invalidate() {\n cached = undefined;\n },\n };\n}\n\n/**\n * The endpoint the document names, or an error saying which one is missing.\n *\n * @internal\n */\nexport function requireEndpoint(document: AuthioDiscoveryDocument, member: keyof AuthioDiscoveryDocument & string): string {\n const value = document[member];\n\n if (typeof value !== \"string\" || !value)\n throw new AuthioDiscoveryError(`The Authio discovery document has no ${member}.`);\n\n return value;\n}\n\nasync function fetchDocument(connection: AuthioConnection, signal?: AbortSignal): Promise<AuthioDiscoveryDocument> {\n const url = connection.discoveryUrl;\n let body: string;\n\n try {\n const response = await send(connection, url, { method: \"GET\", headers: { accept: \"application/json\" } }, signal);\n\n body = await response.text();\n\n if (!response.ok) throw new AuthioDiscoveryError(`Authio answered HTTP ${response.status} for the discovery document at ${url}.`);\n } catch (error) {\n if (error instanceof AuthioDiscoveryError) throw error;\n if (signal?.aborted) throw error;\n\n const timedOut = (error as Error)?.name === \"TimeoutError\";\n\n throw new AuthioDiscoveryError(\n timedOut\n ? `Reading the Authio discovery document at ${url} timed out.`\n : `The Authio discovery document at ${url} could not be read.`,\n { cause: error },\n );\n }\n\n let document: AuthioDiscoveryDocument;\n\n try {\n document = JSON.parse(body) as AuthioDiscoveryDocument;\n } catch (error) {\n throw new AuthioDiscoveryError(`The Authio discovery document at ${url} is not valid JSON.`, { cause: error });\n }\n\n if (!document || typeof document !== \"object\" || typeof document.issuer !== \"string\" || !document.issuer.trim())\n throw new AuthioDiscoveryError(`The Authio discovery document at ${url} has no issuer.`);\n\n if (document.issuer.replace(/\\/+$/, \"\") !== connection.issuer)\n throw new AuthioDiscoveryError(\n `The Authio discovery document names the issuer '${document.issuer}', not the configured '${connection.issuer}'.`,\n );\n\n return document;\n}\n\nfunction isConnection(value: AuthioConnectionOptions | AuthioConnection): value is AuthioConnection {\n return typeof (value as AuthioConnection).discoveryUrl === \"string\" && typeof (value as AuthioConnection).httpTimeoutMs === \"number\";\n}\n","import { importJWK, importPKCS8, type CryptoKey, type JWK } from \"jose\";\nimport { AuthioAsymmetricAlgorithms, AuthioDefaults } from \"./constants.js\";\nimport { AuthioConfigurationError } from \"./errors.js\";\n\n/**\n * A private key as the SDK accepts it: PEM text (PKCS#8, PKCS#1 RSA or SEC1 EC; PKCS#1 and SEC1 need Node), a JWK\n * (object or JSON text), or a `CryptoKey`.\n */\nexport type AuthioPrivateKeyInput = string | JWK | CryptoKey;\n\n/**\n * A key ready to sign with, and the algorithm it signs with.\n */\nexport interface AuthioSigningKey {\n readonly key: CryptoKey | Uint8Array;\n readonly algorithm: string;\n readonly keyId: string | undefined;\n}\n\nconst curveAlgorithms: Record<string, string> = { \"P-256\": \"ES256\", \"P-384\": \"ES384\", \"P-521\": \"ES512\" };\n\n/**\n * Imports a signing key and settles its algorithm: the configured one when it suits the key, else RS256 for RSA and\n * the curve's ES algorithm for EC.\n *\n * @param input The key.\n * @param algorithm The configured algorithm, if any.\n * @param keyId The `kid` to send.\n * @param source The setting the key came from, named in errors.\n * @throws AuthioConfigurationError when the key cannot be read, is too weak, or does not suit the algorithm.\n */\nexport async function importSigningKey(\n input: AuthioPrivateKeyInput,\n algorithm: string | undefined,\n keyId: string | undefined,\n source: string,\n): Promise<AuthioSigningKey> {\n if (typeof input === \"string\") {\n const text = input.trim();\n\n if (text.startsWith(\"{\")) return importSigningKey(parseJwk(text, source), algorithm, keyId, source);\n\n return importPem(text, algorithm, keyId, source);\n }\n\n if (isCryptoKey(input)) {\n const shape = describeCryptoKey(input, source);\n\n return { key: input, algorithm: settleAlgorithm(shape, algorithm, source), keyId };\n }\n\n return importFromJwk(input, algorithm, keyId ?? (typeof input.kid === \"string\" ? input.kid : undefined), source);\n}\n\n/**\n * The algorithms a client assertion may be signed with.\n */\nexport const AuthioClientAssertionAlgorithms = AuthioAsymmetricAlgorithms;\n\ninterface KeyShape {\n readonly type: \"RSA\" | \"EC\";\n readonly curve?: string;\n readonly fixedAlgorithm?: string;\n}\n\nasync function importPem(pem: string, algorithm: string | undefined, keyId: string | undefined, source: string): Promise<AuthioSigningKey> {\n const nodeCrypto = await loadNodeCrypto();\n\n if (nodeCrypto) {\n let keyObject: import(\"node:crypto\").KeyObject;\n\n try {\n keyObject = nodeCrypto.createPrivateKey({ key: pem, format: \"pem\" });\n } catch (error) {\n throw new AuthioConfigurationError(`${source} could not be read as an RSA or EC private key.`, { cause: error });\n }\n\n const jwk = keyObject.export({ format: \"jwk\" }) as JWK;\n\n return importFromJwk(jwk, algorithm, keyId, source);\n }\n\n if (!pem.includes(\"-----BEGIN PRIVATE KEY-----\"))\n throw new AuthioConfigurationError(\n `${source} must be a PKCS#8 PEM (\"BEGIN PRIVATE KEY\") or a JWK outside Node; PKCS#1 and SEC1 keys need Node.`,\n );\n\n const chosen = algorithm?.trim() || \"RS256\";\n\n try {\n return { key: await importPKCS8(pem, chosen), algorithm: chosen, keyId };\n } catch (error) {\n throw new AuthioConfigurationError(`${source} could not be imported for ${chosen}.`, { cause: error });\n }\n}\n\nasync function importFromJwk(jwk: JWK, algorithm: string | undefined, keyId: string | undefined, source: string): Promise<AuthioSigningKey> {\n if (!jwk.d) throw new AuthioConfigurationError(`${source} is a public key; Authio needs the private key to sign.`);\n\n const shape = describeJwk(jwk, source);\n const chosen = settleAlgorithm(shape, algorithm ?? (typeof jwk.alg === \"string\" ? jwk.alg : undefined), source);\n\n try {\n const key = await importJWK({ ...jwk, alg: chosen }, chosen);\n\n return { key, algorithm: chosen, keyId };\n } catch (error) {\n throw new AuthioConfigurationError(`${source} could not be imported for ${chosen}.`, { cause: error });\n }\n}\n\nfunction describeJwk(jwk: JWK, source: string): KeyShape {\n if (jwk.kty === \"RSA\") {\n const bits = base64UrlLength(jwk.n ?? \"\") * 8;\n\n if (bits < AuthioDefaults.MinimumRsaKeySize)\n throw new AuthioConfigurationError(`${source} is a ${bits}-bit RSA key; use at least ${AuthioDefaults.MinimumRsaKeySize} bits.`);\n\n return { type: \"RSA\" };\n }\n\n if (jwk.kty === \"EC\") {\n if (!jwk.crv || !curveAlgorithms[jwk.crv])\n throw new AuthioConfigurationError(`${source} is an EC key on a curve Authio does not accept; use P-256, P-384 or P-521.`);\n\n return { type: \"EC\", curve: jwk.crv };\n }\n\n throw new AuthioConfigurationError(`${source} could not be read as an RSA or EC private key.`);\n}\n\nfunction describeCryptoKey(key: CryptoKey, source: string): KeyShape {\n const algorithm = key.algorithm as { name: string; namedCurve?: string; modulusLength?: number; hash?: { name: string } };\n\n if (algorithm.name === \"ECDSA\" && algorithm.namedCurve && curveAlgorithms[algorithm.namedCurve])\n return { type: \"EC\", curve: algorithm.namedCurve };\n\n if (algorithm.name === \"RSASSA-PKCS1-v1_5\" || algorithm.name === \"RSA-PSS\") {\n if ((algorithm.modulusLength ?? 0) < AuthioDefaults.MinimumRsaKeySize)\n throw new AuthioConfigurationError(\n `${source} is a ${algorithm.modulusLength}-bit RSA key; use at least ${AuthioDefaults.MinimumRsaKeySize} bits.`,\n );\n\n const size = algorithm.hash?.name.replace(\"SHA-\", \"\") ?? \"256\";\n\n return { type: \"RSA\", fixedAlgorithm: `${algorithm.name === \"RSA-PSS\" ? \"PS\" : \"RS\"}${size}` };\n }\n\n throw new AuthioConfigurationError(`${source} is a CryptoKey Authio cannot sign assertions with; use an RSA or EC signing key.`);\n}\n\nfunction settleAlgorithm(shape: KeyShape, configured: string | undefined, source: string): string {\n const suited =\n shape.fixedAlgorithm !== undefined\n ? [shape.fixedAlgorithm]\n : shape.type === \"EC\"\n ? [curveAlgorithms[shape.curve!]!]\n : AuthioAsymmetricAlgorithms.filter((name) => name.startsWith(\"RS\") || name.startsWith(\"PS\"));\n\n const chosen = configured?.trim() || suited[0]!;\n\n if (!suited.includes(chosen))\n throw new AuthioConfigurationError(\n `The signing algorithm '${chosen}' does not suit the key in ${source}; use one of: ${suited.join(\", \")}.`,\n );\n\n return chosen;\n}\n\nfunction parseJwk(text: string, source: string): JWK {\n try {\n const parsed = JSON.parse(text) as JWK & { keys?: JWK[] };\n\n if (Array.isArray(parsed.keys)) {\n if (parsed.keys.length !== 1) throw new Error(\"A JWK Set must hold exactly one key.\");\n return parsed.keys[0]!;\n }\n\n return parsed;\n } catch (error) {\n throw new AuthioConfigurationError(`${source} is not a valid JWK.`, { cause: error });\n }\n}\n\nfunction base64UrlLength(value: string): number {\n const clean = value.replace(/=+$/, \"\");\n return Math.floor((clean.length * 3) / 4);\n}\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n return typeof value === \"object\" && value !== null && \"algorithm\" in value && \"type\" in value && \"usages\" in value;\n}\n\nlet nodeCryptoModule: Promise<typeof import(\"node:crypto\") | undefined> | undefined;\n\n/**\n * Node's crypto module, or `undefined` outside Node.\n *\n * @internal\n */\nexport function loadNodeCrypto(): Promise<typeof import(\"node:crypto\") | undefined> {\n nodeCryptoModule ??= (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node\n ? import(\"node:crypto\").catch(() => undefined)\n : Promise.resolve(undefined);\n\n return nodeCryptoModule;\n}\n\n","import { SignJWT } from \"jose\";\nimport { AuthioDefaults } from \"./constants.js\";\nimport { AuthioConfigurationError } from \"./errors.js\";\nimport { importSigningKey, loadNodeCrypto, type AuthioPrivateKeyInput, type AuthioSigningKey } from \"./keys.js\";\nimport { escapeDataString, seconds, AuthioTokenEndpointAuthMethods, type AuthioConnection, type AuthioTokenEndpointAuthMethod } from \"./options.js\";\n\n/**\n * The client secret, or a function returning the current one, called for every request so a rotated secret is used\n * without a restart.\n */\nexport type AuthioSecretSource = string | (() => string | Promise<string>);\n\n/**\n * How the client proves who it is.\n */\nexport interface AuthioClientCredentialsSettings {\n /** The client id. */\n clientId: string;\n /**\n * The client secret, for `client_secret_basic` and `client_secret_post`; or a function returning the current one,\n * called for every request.\n */\n clientSecret?: AuthioSecretSource;\n /**\n * How the client authenticates, as registered in Authio (which matches it exactly). Defaults to\n * `client_secret_basic` with a `clientSecret`, `private_key_jwt` with only a private key, and `none` with neither.\n */\n tokenEndpointAuthMethod?: AuthioTokenEndpointAuthMethod;\n /** The private key for `private_key_jwt`. */\n clientPrivateKey?: AuthioPrivateKeyInput;\n /** A PEM file holding the private key for `private_key_jwt` (Node only); re-read when it changes. */\n clientPrivateKeyPath?: string;\n /** The `kid` of the key, as registered in Authio. */\n clientKeyId?: string;\n /** The assertion's signing algorithm. Defaults to RS256 for RSA keys and the curve's ES algorithm for EC keys. */\n clientSigningAlgorithm?: string;\n /** Seconds a client assertion lives. Defaults to 120, at most 3600. */\n clientAssertionLifetime?: number;\n}\n\n/**\n * Adds the client's credentials to a request to a protocol endpoint.\n *\n * @internal\n */\nexport interface AuthioClientAuthenticator {\n readonly clientId: string;\n readonly method: AuthioTokenEndpointAuthMethod;\n apply(form: URLSearchParams, headers: Headers): Promise<void>;\n}\n\n/**\n * Builds the HTTP Basic value for a client id and secret, escaping both first as RFC 6749 §2.3.1 asks.\n */\nexport function toBasicAuthorization(clientId: string, clientSecret: string): string {\n const bytes = new TextEncoder().encode(`${escapeDataString(clientId)}:${escapeDataString(clientSecret)}`);\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return `Basic ${btoa(binary)}`;\n}\n\n/**\n * Validates the credential settings and returns the authenticator.\n *\n * @throws AuthioConfigurationError when a setting the method needs is missing.\n * @internal\n */\nexport function createClientAuthenticator(settings: AuthioClientCredentialsSettings, connection: AuthioConnection): AuthioClientAuthenticator {\n const clientId = settings.clientId?.trim();\n\n if (!clientId) throw new AuthioConfigurationError(\"The Authio clientId is required.\");\n\n const hasKey = settings.clientPrivateKey !== undefined || !!settings.clientPrivateKeyPath;\n const method: AuthioTokenEndpointAuthMethod =\n settings.tokenEndpointAuthMethod ?? (settings.clientSecret ? \"client_secret_basic\" : hasKey ? \"private_key_jwt\" : \"none\");\n\n if (!(AuthioTokenEndpointAuthMethods as readonly string[]).includes(method))\n throw new AuthioConfigurationError(`The Authio tokenEndpointAuthMethod '${String(method)}' is not one of ${AuthioTokenEndpointAuthMethods.join(\", \")}.`);\n\n if ((method === \"client_secret_basic\" || method === \"client_secret_post\") && !settings.clientSecret)\n throw new AuthioConfigurationError(`The Authio clientSecret is required with ${method}.`);\n\n if (method === \"private_key_jwt\" && !hasKey)\n throw new AuthioConfigurationError(\"private_key_jwt needs clientPrivateKey or clientPrivateKeyPath.\");\n\n const lifetimeMs = seconds(settings.clientAssertionLifetime, AuthioDefaults.ClientAssertionLifetime, \"clientAssertionLifetime\");\n\n if (lifetimeMs <= 0 || lifetimeMs > AuthioDefaults.MaxClientAssertionLifetime * 1000)\n throw new AuthioConfigurationError(\n `The Authio clientAssertionLifetime must be more than 0 and at most ${AuthioDefaults.MaxClientAssertionLifetime} seconds.`,\n );\n\n const loadKey = method === \"private_key_jwt\" ? createKeyLoader(settings) : undefined;\n const secret = async () => {\n const value = typeof settings.clientSecret === \"function\" ? await settings.clientSecret() : settings.clientSecret;\n\n if (typeof value !== \"string\" || !value) throw new AuthioConfigurationError(\"The Authio clientSecret function returned no secret.\");\n\n return value;\n };\n\n return {\n clientId,\n method,\n async apply(form, headers) {\n switch (method) {\n case \"client_secret_basic\":\n headers.set(\"authorization\", toBasicAuthorization(clientId, await secret()));\n return;\n case \"client_secret_post\":\n form.set(\"client_id\", clientId);\n form.set(\"client_secret\", await secret());\n return;\n case \"private_key_jwt\":\n form.set(\"client_id\", clientId);\n form.set(\"client_assertion_type\", \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\");\n form.set(\"client_assertion\", await buildAssertion(clientId, connection, lifetimeMs, await loadKey!()));\n return;\n default:\n form.set(\"client_id\", clientId);\n }\n },\n };\n}\n\n/**\n * Signs a client assertion: `iss` = `sub` = the client id, `aud` = the issuer, `iat` = `nbf` = now,\n * `exp` = now + lifetime, a 128-bit random `jti`.\n *\n * @internal\n */\nexport async function buildAssertion(clientId: string, connection: AuthioConnection, lifetimeMs: number, signing: AuthioSigningKey): Promise<string> {\n const now = Math.floor(connection.clock.now() / 1000);\n const jti = [...crypto.getRandomValues(new Uint8Array(16))].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n return new SignJWT({ jti })\n .setProtectedHeader({ alg: signing.algorithm, typ: \"JWT\", ...(signing.keyId ? { kid: signing.keyId } : {}) })\n .setIssuer(clientId)\n .setSubject(clientId)\n .setAudience(connection.issuer)\n .setIssuedAt(now)\n .setNotBefore(now)\n .setExpirationTime(now + Math.floor(lifetimeMs / 1000))\n .sign(signing.key);\n}\n\nfunction createKeyLoader(settings: AuthioClientCredentialsSettings): () => Promise<AuthioSigningKey> {\n if (settings.clientPrivateKey !== undefined) {\n let loaded: Promise<AuthioSigningKey> | undefined;\n\n return () => {\n loaded ??= importSigningKey(settings.clientPrivateKey!, settings.clientSigningAlgorithm, settings.clientKeyId, \"clientPrivateKey\");\n loaded.catch(() => {\n loaded = undefined;\n });\n return loaded;\n };\n }\n\n const path = settings.clientPrivateKeyPath!;\n let current: { written: number; key: Promise<AuthioSigningKey> } | undefined;\n\n return async () => {\n const nodeCrypto = await loadNodeCrypto();\n\n if (!nodeCrypto) throw new AuthioConfigurationError(\"clientPrivateKeyPath needs Node; pass clientPrivateKey instead.\");\n\n const { readFile, stat } = await import(\"node:fs/promises\");\n let written: number;\n\n try {\n written = (await stat(path)).mtimeMs;\n } catch (error) {\n throw new AuthioConfigurationError(`clientPrivateKeyPath '${path}' could not be read.`, { cause: error });\n }\n\n if (!current || current.written !== written) {\n const key = readFile(path, \"utf8\").then((pem) =>\n importSigningKey(pem, settings.clientSigningAlgorithm, settings.clientKeyId, `clientPrivateKeyPath '${path}'`),\n );\n\n current = { written, key };\n key.catch(() => {\n if (current?.key === key) current = undefined;\n });\n }\n\n return current.key;\n };\n}\n","import { compactDecrypt, decodeProtectedHeader, errors, importJWK, importPKCS8, type CryptoKey, type JWK } from \"jose\";\nimport { AuthioConfigurationError, AuthioTokenValidationError } from \"./errors.js\";\nimport { loadNodeCrypto } from \"./keys.js\";\n\n/**\n * The client's own encryption key, the pair Authio encrypts the client's tokens and UserInfo to: the private JWK\n * Authio hands over when it generates the pair (object or JSON text), or a PEM private key (PKCS#8 or PKCS#1 RSA).\n */\nexport type AuthioEncryptionKey = string | JWK;\n\n/**\n * Where the encryption key comes from: the key itself, or a function returning it (read again on every new\n * algorithm, so a rotated key is picked up).\n */\nexport type AuthioEncryptionKeySource = AuthioEncryptionKey | (() => AuthioEncryptionKey | Promise<AuthioEncryptionKey>);\n\n/**\n * Opens a compact JWE and returns its plaintext; a token that is not a JWE comes back unchanged.\n *\n * @throws AuthioTokenValidationError with `legacy_algorithm` for RSA1_5 and `decryption_failed` when the key cannot\n * open it.\n */\nexport type AuthioTokenDecrypter = (token: string) => Promise<string>;\n\n/**\n * The key management algorithms Authio encrypts with, and this SDK decrypts.\n */\nexport const AuthioKeyManagementAlgorithms = [\"RSA-OAEP\", \"RSA-OAEP-256\"] as const;\n\n/**\n * Key management algorithms Authio may still use for clients registered long ago. Node and WebCrypto cannot decrypt\n * RSA1_5 (PKCS#1 v1.5), so this SDK refuses it even with `allowLegacyEncryptionAlgorithms`.\n */\nexport const AuthioLegacyKeyManagementAlgorithms = [\"RSA1_5\"] as const;\n\n/**\n * The content encryption algorithms Authio encrypts with to a client's own key, the default `encryptionMethods`.\n */\nexport const AuthioContentEncryptionAlgorithms = [\"A128CBC-HS256\", \"A192CBC-HS384\", \"A256CBC-HS512\"] as const;\n\n/**\n * Every content encryption algorithm `encryptionMethods` may list: the CBC-HS ones and AES-GCM.\n */\nexport const AuthioSupportedContentEncryptionAlgorithms = [...AuthioContentEncryptionAlgorithms, \"A128GCM\", \"A192GCM\", \"A256GCM\"] as const;\n\n/**\n * Options of the decrypter.\n */\nexport interface AuthioTokenDecrypterOptions {\n /** The setting the key came from, named in errors. Defaults to `clientEncryptionKey`. */\n setting?: string;\n /**\n * Accepted for parity with the other Authio SDKs. RSA1_5 stays refused here, with an error saying so, because\n * neither Node nor WebCrypto can decrypt PKCS#1 v1.5.\n */\n allowLegacyEncryptionAlgorithms?: boolean;\n /**\n * The key management algorithms (`alg`) accepted, as registered for the client in Authio. Defaults to RSA-OAEP and\n * RSA-OAEP-256. RSA1_5 cannot be listed: neither Node nor WebCrypto can decrypt it.\n */\n encryptionAlgorithms?: readonly string[];\n /** The content encryption algorithms (`enc`) accepted. Defaults to A128CBC-HS256, A192CBC-HS384 and A256CBC-HS512. */\n encryptionMethods?: readonly string[];\n}\n\nconst rsaAlgorithmIdentifier = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00];\n\n/**\n * Whether a value is a compact JWE (five segments).\n */\nexport function isAuthioTokenEncrypted(token: unknown): token is string {\n return typeof token === \"string\" && token.split(\".\").length === 5;\n}\n\n/**\n * Creates a decrypter for the client's own encryption key. Keys are imported once per algorithm.\n *\n * @param key The key, a function returning it, or `undefined` when none is configured: an encrypted token then throws.\n * @param options The setting name for errors, and the legacy algorithm switch. A string is taken as the setting name.\n */\nexport function createAuthioTokenDecrypter(\n key: AuthioEncryptionKeySource | undefined,\n options: AuthioTokenDecrypterOptions | string = {},\n): AuthioTokenDecrypter {\n const settings: AuthioTokenDecrypterOptions = typeof options === \"string\" ? { setting: options } : options;\n const setting = settings.setting ?? \"clientEncryptionKey\";\n const keyManagementAlgorithms = resolveAllowlist(settings.encryptionAlgorithms, AuthioKeyManagementAlgorithms, AuthioKeyManagementAlgorithms, \"encryptionAlgorithms\");\n const contentEncryptionAlgorithms = resolveAllowlist(\n settings.encryptionMethods,\n AuthioContentEncryptionAlgorithms,\n AuthioSupportedContentEncryptionAlgorithms,\n \"encryptionMethods\",\n );\n const imported = new Map<string, Promise<CryptoKey | Uint8Array>>();\n\n const importFor = (algorithm: string) => {\n let pending = imported.get(algorithm);\n\n if (!pending) {\n pending = Promise.resolve(typeof key === \"function\" ? key() : key!).then((value) => importDecryptionKey(value, algorithm, setting));\n imported.set(algorithm, pending);\n pending.catch(() => imported.delete(algorithm));\n }\n\n return pending;\n };\n\n return async (token) => {\n if (!isAuthioTokenEncrypted(token)) return token;\n\n const algorithm = algorithmOf(token);\n\n if ((AuthioLegacyKeyManagementAlgorithms as readonly string[]).includes(algorithm))\n throw new AuthioTokenValidationError(\n \"legacy_algorithm\",\n settings.allowLegacyEncryptionAlgorithms\n ? \"The token is encrypted with RSA1_5 (PKCS#1 v1.5), which Node and WebCrypto cannot decrypt even with allowLegacyEncryptionAlgorithms; register RSA-OAEP-256 as the client's encryption algorithm in Authio.\"\n : \"The token is encrypted with the legacy RSA1_5 algorithm, which is refused; register RSA-OAEP-256 as the client's encryption algorithm in Authio.\",\n );\n\n if (!keyManagementAlgorithms.includes(algorithm))\n throw new AuthioTokenValidationError(\n \"decryption_failed\",\n `The token is encrypted with '${algorithm}', and encryptionAlgorithms accepts ${keyManagementAlgorithms.join(\" or \")}.`,\n );\n\n const method = contentMethodOf(token);\n\n if (!contentEncryptionAlgorithms.includes(method))\n throw new AuthioTokenValidationError(\n \"decryption_failed\",\n `The token's content is encrypted with '${method}', and encryptionMethods accepts ${contentEncryptionAlgorithms.join(\" or \")}.`,\n );\n\n if (key === undefined || key === null || key === \"\")\n throw new AuthioTokenValidationError(\n \"decryption_failed\",\n `Authio encrypted this token to the client's own key; set ${setting} to the private key Authio showed when it generated the pair.`,\n );\n\n try {\n const { plaintext } = await compactDecrypt(token, (header) => importFor(header.alg), {\n keyManagementAlgorithms: [...keyManagementAlgorithms],\n contentEncryptionAlgorithms: [...contentEncryptionAlgorithms],\n });\n\n return new TextDecoder().decode(plaintext);\n } catch (error) {\n if (error instanceof AuthioConfigurationError) throw error;\n if (error instanceof errors.JOSEError)\n throw new AuthioTokenValidationError(\"decryption_failed\", `The token could not be decrypted with ${setting}: ${error.message}`, { cause: error });\n throw error;\n }\n };\n}\n\n/**\n * Reads the client's encryption key from a PEM or JWK file (Node only), again whenever the file changes.\n *\n * @internal\n */\nexport function encryptionKeyFromFile(path: string, setting = \"clientEncryptionKeyPath\"): () => Promise<AuthioEncryptionKey> {\n let current: { written: number; key: Promise<string> } | undefined;\n\n return async () => {\n const nodeCrypto = await loadNodeCrypto();\n\n if (!nodeCrypto) throw new AuthioConfigurationError(`${setting} needs Node; pass clientEncryptionKey instead.`);\n\n const { readFile, stat } = await import(\"node:fs/promises\");\n let written: number;\n\n try {\n written = (await stat(path)).mtimeMs;\n } catch (error) {\n throw new AuthioConfigurationError(`${setting} '${path}' could not be read.`, { cause: error });\n }\n\n if (!current || current.written !== written) current = { written, key: readFile(path, \"utf8\") };\n\n return current.key;\n };\n}\n\nfunction algorithmOf(token: string): string {\n try {\n return String(decodeProtectedHeader(token).alg ?? \"\");\n } catch (error) {\n throw new AuthioTokenValidationError(\"decryption_failed\", \"The encrypted token's header could not be read.\", { cause: error });\n }\n}\n\nfunction contentMethodOf(token: string): string {\n try {\n return String(decodeProtectedHeader(token).enc ?? \"\");\n } catch (error) {\n throw new AuthioTokenValidationError(\"decryption_failed\", \"The encrypted token's header could not be read.\", { cause: error });\n }\n}\n\nfunction resolveAllowlist(configured: readonly string[] | undefined, defaults: readonly string[], supported: readonly string[], setting: string): readonly string[] {\n if (configured === undefined || configured.length === 0) return defaults;\n\n for (const value of configured) {\n if ((AuthioLegacyKeyManagementAlgorithms as readonly string[]).includes(value))\n throw new AuthioConfigurationError(\n `${setting} cannot hold ${value}: Node and WebCrypto cannot decrypt PKCS#1 v1.5; register RSA-OAEP-256 as the client's encryption algorithm in Authio.`,\n );\n\n if (!supported.includes(value)) throw new AuthioConfigurationError(`${setting} holds '${value}'; it accepts ${supported.join(\", \")}.`);\n }\n\n return [...new Set(configured)];\n}\n\nasync function importDecryptionKey(key: AuthioEncryptionKey, algorithm: string, setting: string): Promise<CryptoKey | Uint8Array> {\n try {\n if (typeof key !== \"string\") return await importPrivateJwk(key, algorithm, setting);\n\n const text = key.trim();\n\n return text.startsWith(\"{\")\n ? await importPrivateJwk(JSON.parse(text) as JWK, algorithm, setting)\n : await importPKCS8(toPkcs8(text), algorithm);\n } catch (error) {\n if (error instanceof AuthioConfigurationError) throw error;\n throw new AuthioConfigurationError(`${setting} is neither a private JWK nor a PEM private key.`, { cause: error });\n }\n}\n\nfunction importPrivateJwk(jwk: JWK, algorithm: string, setting: string): Promise<CryptoKey | Uint8Array> {\n if (!jwk.d) throw new AuthioConfigurationError(`${setting} is a JWK without its private parameters; only the private key decrypts.`);\n\n return importJWK({ ...jwk, alg: algorithm, use: \"enc\", key_ops: undefined }, algorithm);\n}\n\nfunction toPkcs8(pem: string): string {\n const normalized = pem.replace(/\\\\n/g, \"\\n\").trim();\n\n if (!normalized.includes(\"BEGIN RSA PRIVATE KEY\")) return normalized;\n\n const pkcs1 = fromBase64(normalized.replace(/-----[^-]+-----|\\s/g, \"\"));\n const body = [0x02, 0x01, 0x00, ...rsaAlgorithmIdentifier, 0x04, ...derLength(pkcs1.length), ...pkcs1];\n const der = Uint8Array.from([0x30, ...derLength(body.length), ...body]);\n const lines = toBase64(der).match(/.{1,64}/g) ?? [];\n\n return `-----BEGIN PRIVATE KEY-----\\n${lines.join(\"\\n\")}\\n-----END PRIVATE KEY-----`;\n}\n\nfunction derLength(length: number): number[] {\n if (length < 0x80) return [length];\n\n const bytes: number[] = [];\n\n for (let rest = length; rest > 0; rest >>= 8) bytes.unshift(rest & 0xff);\n\n return [0x80 | bytes.length, ...bytes];\n}\n\nfunction fromBase64(text: string): Uint8Array {\n return Uint8Array.from(atob(text), (character) => character.charCodeAt(0));\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n}\n","import { createRemoteJWKSet, customFetch, decodeProtectedHeader, errors, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from \"jose\";\nimport { AuthioAsymmetricAlgorithms, AuthioClaimTypes, AuthioDefaults, AuthioHmacAlgorithms, AuthioHmacMinimumSecretBytes } from \"./constants.js\";\nimport type { AuthioDiscoveryClient } from \"./discovery.js\";\nimport { AuthioConfigurationError, AuthioError, AuthioTokenValidationError } from \"./errors.js\";\nimport { isAuthioTokenEncrypted, type AuthioTokenDecrypter } from \"./encryption.js\";\nimport type { AuthioConnection } from \"./options.js\";\n\n/**\n * The claims of a validated ID token. Authio writes `typ` = `ID`, `sid`, `auth_time`, `acr`, `amr`, `nonce` and\n * `at_hash`, besides the profile claims of the granted scopes.\n */\nexport interface AuthioIdTokenClaims extends JWTPayload {\n sub: string;\n sid?: string;\n nonce?: string;\n auth_time?: number;\n acr?: string;\n amr?: string[];\n at_hash?: string;\n [claim: string]: unknown;\n}\n\n/**\n * A validated back-channel logout token: end the sessions of `subject`, or the one session `sessionId` names.\n */\nexport interface AuthioLogoutToken {\n /** `sub`, when the token names the person. */\n readonly subject: string | undefined;\n /** `sid`, when the token names one session. */\n readonly sessionId: string | undefined;\n /** `jti`. */\n readonly tokenId: string | undefined;\n /** Every claim. */\n readonly claims: Readonly<JWTPayload>;\n}\n\n/**\n * The realm's signing keys, read from the discovery document's `jwks_uri` and cached; an unknown `kid` makes it read\n * them again (at most once every 30 seconds).\n *\n * @internal\n */\nexport type AuthioSigningKeys = (signal?: AbortSignal) => Promise<JWTVerifyGetKey>;\n\n/**\n * What a JWT is checked against.\n *\n * @internal\n */\nexport interface AuthioJwtExpectations {\n readonly issuer: string;\n /** The accepted audiences; `aud` is not checked when absent. */\n readonly audiences?: readonly string[];\n readonly algorithms?: readonly string[];\n /** Seconds. */\n readonly clockSkew?: number;\n /** Milliseconds since the epoch. */\n readonly now: number;\n readonly requiredClaims?: readonly string[];\n}\n\n/**\n * Creates the cached reader of the realm's signing keys.\n *\n * @internal\n */\nexport function createAuthioSigningKeys(connection: AuthioConnection, discovery: AuthioDiscoveryClient): AuthioSigningKeys {\n let keys: { uri: string; set: JWTVerifyGetKey } | undefined;\n\n return async (signal) => {\n const document = await discovery.get(signal);\n const uri = document.jwks_uri;\n\n if (!uri) throw new AuthioError(\"The Authio discovery document has no jwks_uri.\");\n\n if (!keys || keys.uri !== uri)\n keys = { uri, set: createRemoteJWKSet(new URL(uri), { [customFetch]: connection.fetch, timeoutDuration: connection.httpTimeoutMs }) };\n\n return keys.set;\n };\n}\n\n/**\n * Verifies a signed JWT: signature by a realm key with an accepted algorithm, `iss`, `aud`, `exp` (required) and\n * `nbf` with the clock skew.\n *\n * @throws AuthioTokenValidationError naming why the token was refused.\n * @internal\n */\nexport async function verifyAuthioJwt(token: string, keys: JWTVerifyGetKey, expected: AuthioJwtExpectations): Promise<{ payload: JWTPayload; header: Record<string, unknown> }> {\n if (!looksLikeJws(token))\n throw new AuthioTokenValidationError(\"reference_token\", \"The token is not a JWT; only introspection can resolve it ('introspectionOnly').\");\n\n try {\n const { payload, protectedHeader } = await jwtVerify(token, keys, {\n issuer: expected.issuer,\n audience: expected.audiences ? [...expected.audiences] : undefined,\n algorithms: [...(expected.algorithms && expected.algorithms.length > 0 ? expected.algorithms : AuthioAsymmetricAlgorithms)],\n clockTolerance: expected.clockSkew ?? AuthioDefaults.ClockSkew,\n requiredClaims: [...new Set([\"exp\", ...(expected.requiredClaims ?? [])])],\n currentDate: new Date(expected.now),\n });\n\n return { payload, header: protectedHeader as Record<string, unknown> };\n } catch (error) {\n if (error instanceof AuthioConfigurationError) throw error;\n\n throw toTokenValidationError(error, expected.audiences ?? [], token);\n }\n}\n\n/**\n * Wraps the realm's keys so an HS256, HS384 or HS512 signature is verified with the client secret instead (OpenID\n * Connect Core §10.1: the octets of its UTF-8 form). Only reached for an algorithm the allowlist accepts, so an HS*\n * token is verified with the secret only when `idTokenSignedResponseAlg` names that algorithm.\n *\n * @internal\n */\nexport function withClientSecret(keys: JWTVerifyGetKey, secret: (() => Promise<string>) | undefined): JWTVerifyGetKey {\n if (!secret) return keys;\n\n return async (header, token) => {\n const algorithm = String(header.alg);\n\n if (!(AuthioHmacAlgorithms as readonly string[]).includes(algorithm)) return keys(header, token);\n\n const bytes = new TextEncoder().encode(await secret());\n\n requireHmacSecretLength(algorithm, bytes.length);\n\n return bytes;\n };\n}\n\n/**\n * Refuses a client secret shorter than the HS* algorithm's hash output (RFC 7518 §3.2).\n *\n * @throws AuthioConfigurationError naming the algorithm and both lengths.\n * @internal\n */\nexport function requireHmacSecretLength(algorithm: string, length: number): void {\n const minimum = AuthioHmacMinimumSecretBytes[algorithm as keyof typeof AuthioHmacMinimumSecretBytes];\n\n if (minimum !== undefined && length < minimum)\n throw new AuthioConfigurationError(\n `The Authio clientSecret has ${length} bytes, and ${algorithm} needs at least ${minimum} (RFC 7518 §3.2): Authio refuses a shorter secret for it.`,\n );\n}\n\n/**\n * The algorithms a token is accepted with: the one configured, else the asymmetric ones the discovery document\n * announces for it, else every asymmetric one. HS* is never accepted unless configured.\n *\n * @internal\n */\nexport function acceptedSigningAlgorithms(configured: string | undefined, announced: unknown): readonly string[] {\n if (configured) return [configured];\n\n const asymmetric = (Array.isArray(announced) ? announced : []).filter(\n (algorithm): algorithm is string => typeof algorithm === \"string\" && (AuthioAsymmetricAlgorithms as readonly string[]).includes(algorithm),\n );\n\n return asymmetric.length > 0 ? asymmetric : AuthioAsymmetricAlgorithms;\n}\n\n/**\n * Turns a `jose` failure into the refusal it stands for, worded as ASP.NET Core's bearer handler words it.\n *\n * @internal\n */\nexport function toTokenValidationError(error: unknown, audiences: readonly string[], token: string): AuthioTokenValidationError {\n if (error instanceof AuthioTokenValidationError) return error;\n\n const refuse = (reason: ConstructorParameters<typeof AuthioTokenValidationError>[0], message: string) =>\n new AuthioTokenValidationError(reason, message, { cause: error });\n\n if (error instanceof errors.JWTExpired) {\n const exp = error.payload.exp;\n\n return refuse(\"expired\", typeof exp === \"number\" ? `The token expired at '${new Date(exp * 1000).toISOString()}'` : \"The token has expired\");\n }\n\n if (error instanceof errors.JWTClaimValidationFailed) {\n switch (error.claim) {\n case \"aud\":\n return refuse(\"invalid_audience\", describeAudience([error.payload.aud ?? []].flat(), audiences));\n case \"iss\":\n return refuse(\"invalid_issuer\", `The issuer '${error.payload.iss ?? \"\"}' is invalid`);\n case \"nbf\":\n return refuse(\n \"not_yet_valid\",\n typeof error.payload.nbf === \"number\" ? `The token is not valid before '${new Date(error.payload.nbf * 1000).toISOString()}'` : \"The token is not valid yet\",\n );\n case \"exp\":\n return refuse(\"expired\", \"The token has no expiration\");\n default:\n return refuse(\"malformed\", `The token's ${error.claim} claim is invalid`);\n }\n }\n\n if (error instanceof errors.JWSSignatureVerificationFailed) return refuse(\"invalid_signature\", \"The signature is invalid\");\n if (error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JWKSMultipleMatchingKeys)\n return refuse(\"invalid_signature\", \"The signature key was not found\");\n if (error instanceof errors.JOSEAlgNotAllowed) return refuse(\"invalid_algorithm\", `The algorithm '${algorithmOf(token)}' is not available`);\n if (error instanceof errors.JWKSTimeout || error instanceof errors.JWKSInvalid)\n return refuse(\"signing_keys_unavailable\", \"Authio could not be reached to read its signing keys.\");\n if (error instanceof errors.JWTInvalid || error instanceof errors.JWSInvalid) return refuse(\"malformed\", \"The token is malformed\");\n if (error instanceof errors.JOSEError) return refuse(\"malformed\", error.message);\n\n return refuse(\"signing_keys_unavailable\", \"Authio could not be reached to read its signing keys.\");\n}\n\n/**\n * The `at_hash` / `c_hash` of a value for a signing algorithm: the left half of its SHA-256, SHA-384 or SHA-512\n * digest, base64url-encoded (OpenID Connect Core §3.1.3.6).\n */\nexport async function computeAuthioTokenHash(value: string, algorithm: string): Promise<string> {\n const size = /(\\d{3})$/.exec(algorithm)?.[1];\n const hash = size === \"384\" ? \"SHA-384\" : size === \"512\" ? \"SHA-512\" : \"SHA-256\";\n const digest = new Uint8Array(await crypto.subtle.digest(hash, new TextEncoder().encode(value)));\n\n return toBase64Url(digest.subarray(0, digest.length / 2));\n}\n\n/**\n * Validates an ID token: decrypted first when it is a JWE, then signature, `iss`, `aud` = the client, `exp` with the\n * skew, payload `typ` = `ID`, `azp` when there are several audiences, `nonce`, `at_hash` and `auth_time` against\n * `maxAge`.\n *\n * @internal\n */\nexport async function validateAuthioIdToken(\n token: string,\n context: { keys: JWTVerifyGetKey; decrypt: AuthioTokenDecrypter; issuer: string; clientId: string; algorithms?: readonly string[]; clockSkew?: number; now: number },\n expectations: { nonce?: string; accessToken?: string; maxAge?: number } = {},\n): Promise<AuthioIdTokenClaims> {\n const signed = isAuthioTokenEncrypted(token) ? await context.decrypt(token) : token;\n const { payload, header } = await verifyAuthioJwt(signed, context.keys, {\n issuer: context.issuer,\n audiences: [context.clientId],\n algorithms: context.algorithms,\n clockSkew: context.clockSkew,\n now: context.now,\n requiredClaims: [\"sub\", \"iat\"],\n });\n const type = typeof payload.typ === \"string\" ? payload.typ : undefined;\n\n if (type !== undefined && type.toLowerCase() !== \"id\")\n throw new AuthioTokenValidationError(\"not_id_token\", `Only ID tokens are accepted; this token's typ is '${type}'.`);\n\n const audiences = [payload.aud ?? []].flat();\n\n if (audiences.length > 1 && payload.azp !== context.clientId)\n throw new AuthioTokenValidationError(\"invalid_audience\", `The ID token has several audiences and its azp is not '${context.clientId}'.`);\n\n if (expectations.nonce !== undefined && payload[AuthioClaimTypes.Nonce] !== expectations.nonce)\n throw new AuthioTokenValidationError(\n \"invalid_nonce\",\n payload[AuthioClaimTypes.Nonce] === undefined ? \"The ID token carries no nonce, although one was sent.\" : \"The ID token's nonce is not the one sent.\",\n );\n\n const atHash = payload[AuthioClaimTypes.AccessTokenHash];\n\n if (expectations.accessToken !== undefined && typeof atHash === \"string\") {\n const expected = await computeAuthioTokenHash(expectations.accessToken, String(header.alg ?? \"\"));\n\n if (expected !== atHash) throw new AuthioTokenValidationError(\"invalid_at_hash\", \"The ID token's at_hash does not match the access token.\");\n }\n\n if (expectations.maxAge !== undefined) {\n const authTime = payload[AuthioClaimTypes.AuthTime];\n const skew = context.clockSkew ?? AuthioDefaults.ClockSkew;\n\n if (typeof authTime !== \"number\")\n throw new AuthioTokenValidationError(\"authentication_too_old\", \"max_age was requested, and the ID token carries no auth_time.\");\n\n if ((authTime + expectations.maxAge + skew) * 1000 < context.now)\n throw new AuthioTokenValidationError(\n \"authentication_too_old\",\n `The person signed in at '${new Date(authTime * 1000).toISOString()}', more than ${expectations.maxAge} seconds ago.`,\n );\n }\n\n return payload as AuthioIdTokenClaims;\n}\n\n/**\n * Requires the header `typ` of an access token to be `at+jwt` (or `application/at+jwt`), as RFC 9068 §4 asks a\n * resource server to check, so an ID token or any other JWT is never taken for an access token.\n *\n * @param header The protected header of the verified token.\n * @throws AuthioTokenValidationError with the reason `not_access_token` otherwise.\n * @internal\n */\nexport function requireAccessTokenType(header: Record<string, unknown>): void {\n const type = typeof header.typ === \"string\" ? header.typ.toLowerCase() : undefined;\n\n if (type !== AuthioDefaults.AccessTokenType && type !== `application/${AuthioDefaults.AccessTokenType}`)\n throw new AuthioTokenValidationError(\n \"not_access_token\",\n `Only access tokens are accepted; this token's header typ is '${header.typ ?? \"\"}', not '${AuthioDefaults.AccessTokenType}'.`,\n );\n}\n\n/**\n * Validates a back-channel logout token (OpenID Connect Back-Channel Logout 1.0 §2.6): header `typ` =\n * `logout+jwt`, signature, `iss`, `aud` = the client, `exp`, the back-channel event, no `nonce`, and `sub` or `sid`.\n *\n * @internal\n */\nexport async function validateAuthioLogoutToken(\n token: string,\n context: { keys: JWTVerifyGetKey; decrypt: AuthioTokenDecrypter; issuer: string; clientId: string; algorithms?: readonly string[]; clockSkew?: number; now: number },\n): Promise<AuthioLogoutToken> {\n const signed = isAuthioTokenEncrypted(token) ? await context.decrypt(token) : token;\n const invalid = (message: string) => new AuthioTokenValidationError(\"invalid_logout_token\", message);\n let headerType: string | undefined;\n\n try {\n const header = decodeProtectedHeader(signed);\n\n headerType = typeof header.typ === \"string\" ? header.typ.toLowerCase() : undefined;\n } catch (error) {\n throw new AuthioTokenValidationError(\"malformed\", \"The logout token is malformed\", { cause: error });\n }\n\n const { payload } = await verifyAuthioJwt(signed, context.keys, {\n issuer: context.issuer,\n audiences: [context.clientId],\n algorithms: context.algorithms,\n clockSkew: context.clockSkew,\n now: context.now,\n requiredClaims: [\"iat\"],\n });\n\n if (headerType !== AuthioDefaults.LogoutTokenType && headerType !== `application/${AuthioDefaults.LogoutTokenType}`)\n throw invalid(`The token's header typ is '${headerType ?? \"\"}', not '${AuthioDefaults.LogoutTokenType}'.`);\n\n const events = payload[AuthioClaimTypes.Events];\n\n if (!events || typeof events !== \"object\" || Array.isArray(events) || typeof (events as Record<string, unknown>)[AuthioDefaults.BackchannelLogoutEvent] !== \"object\")\n throw invalid(\"The token carries no back-channel logout event.\");\n\n if (payload[AuthioClaimTypes.Nonce] !== undefined) throw invalid(\"A logout token must not carry a nonce.\");\n\n const subject = typeof payload.sub === \"string\" && payload.sub ? payload.sub : undefined;\n const sessionId = typeof payload.sid === \"string\" && payload.sid ? payload.sid : undefined;\n\n if (!subject && !sessionId) throw invalid(\"The logout token names neither a subject nor a session.\");\n\n return Object.freeze({ subject, sessionId, tokenId: typeof payload.jti === \"string\" ? payload.jti : undefined, claims: Object.freeze({ ...payload }) });\n}\n\nfunction describeAudience(tokenAudiences: readonly string[], audiences: readonly string[]): string {\n const known = tokenAudiences.length === 0 ? \"\" : ` ${tokenAudiences.map((audience) => `'${audience}'`).join(\" and \")}`;\n const accepted = audiences.map((audience) => `'${audience}'`).join(\" or \");\n\n return audiences.length === 1\n ? `The token is not addressed to this API: its audience${known} is not ${accepted}. Request the token for that resource (RFC 8707).`\n : `The token is not addressed to this API: its audience${known} is not ${accepted}. Request the token for one of those resources (RFC 8707).`;\n}\n\nfunction looksLikeJws(token: string): boolean {\n const parts = token.split(\".\");\n\n return parts.length === 3 && parts[0]!.length > 0;\n}\n\nfunction algorithmOf(token: string): string {\n try {\n return String(decodeProtectedHeader(token).alg ?? \"\");\n } catch {\n return \"\";\n }\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n","import type { AuthioPrompt } from \"./constants.js\";\nimport { AuthioCallbackError, AuthioConfigurationError } from \"./errors.js\";\nimport { toScopeString } from \"./http.js\";\n\n/**\n * The PKCE method (RFC 7636). `S256` is the default; `plain` only when asked for, for a client that cannot hash.\n */\nexport type AuthioCodeChallengeMethod = \"S256\" | \"plain\";\n\n/**\n * What the client checks on an authorization round trip, as the client is registered in Authio: `pkce` sends a code\n * challenge and redeems the code with its verifier, `state` binds the callback to the request, `nonce` binds the ID\n * token to it. `none` is the same as an empty list. Nothing is checked unless listed.\n */\nexport type AuthioCheck = \"pkce\" | \"state\" | \"nonce\" | \"none\";\n\n/**\n * How Authio answers the authorization request: `query` (a redirect) or `web_message` (posted to the opener window).\n */\nexport type AuthioResponseMode = \"query\" | \"web_message\";\n\n/**\n * The checks every Authio library accepts.\n */\nexport const AuthioChecks = [\"pkce\", \"state\", \"nonce\", \"none\"] as const satisfies readonly AuthioCheck[];\n\n/**\n * A PKCE pair: send `codeChallenge` with the authorization request and `codeVerifier` with the code exchange.\n */\nexport interface AuthioPkcePair {\n readonly codeVerifier: string;\n readonly codeChallenge: string;\n readonly codeChallengeMethod: AuthioCodeChallengeMethod;\n}\n\n/**\n * What an authorization request asks Authio for. Every member is optional; `redirectUri` falls back to the client's.\n */\nexport interface AuthioAuthorizationRequest {\n /** Where Authio sends the person back. Defaults to the client's `redirectUri`. */\n redirectUri?: string;\n /** Defaults to `openid`. */\n scopes?: Iterable<string> | string;\n /** The resource server the access token is for (RFC 8707). */\n resource?: string;\n /** The organization (its handle) the sign-in is for. Authoritative: the person cannot switch to another one. */\n organization?: string;\n /** `none` (silent), `login`, `select_account`, `consent`; several are joined with spaces. */\n prompt?: AuthioPrompt | readonly AuthioPrompt[];\n /** Seconds the person's sign-in may be old; Authio asks again past it, and the ID token's `auth_time` is checked. */\n maxAge?: number;\n /** Authentication context classes asked for: `1` one factor, `2` several, `3` one of them phishing-resistant. */\n acrValues?: string | readonly string[];\n /** Pre-fills the identifier on the sign-in screen. */\n loginHint?: string;\n /** A previously issued ID token, naming the person whose session is renewed. */\n idTokenHint?: string;\n /** Languages of the hosted screens, most preferred first. */\n uiLocales?: string | readonly string[];\n /** `page` (default) or `popup`, the layout of the hosted screens. */\n display?: \"page\" | \"popup\";\n /** `query` or `web_message` (the answer posted to the opener window). Defaults to the client's `responseMode`. */\n responseMode?: AuthioResponseMode;\n /** Shorthand for `display: \"popup\"` with `responseMode: \"web_message\"`. */\n popup?: boolean;\n /** The alias of the identity provider to go straight to, skipping Authio's sign-in screen. */\n idpHint?: string;\n /** The checks of this request. Defaults to the client's `checks`. */\n checks?: readonly AuthioCheck[];\n /** The PKCE method, when `checks` holds `pkce`. Defaults to the client's `codeChallengeMethod`, else `S256`. */\n codeChallengeMethod?: AuthioCodeChallengeMethod;\n /** A `state` of your own for the `state` check (a random one otherwise); without the check it is sent unchecked. */\n state?: string;\n /** A `nonce` of your own for the `nonce` check (a random one otherwise); without the check it is sent unchecked. */\n nonce?: string;\n /** Further parameters, sent as given. */\n extraParameters?: Record<string, string | undefined>;\n}\n\n/**\n * What the application keeps between the authorization request and the callback (in its session, a cookie, …), to\n * check the callback and redeem the code.\n */\nexport interface AuthioAuthorizationTransaction {\n /** The checks the request was made with; the callback checks exactly these. */\n readonly checks: readonly Exclude<AuthioCheck, \"none\">[];\n /** With the `state` check. */\n readonly state?: string;\n /** With the `nonce` check. */\n readonly nonce?: string;\n /** With the `pkce` check. */\n readonly codeVerifier?: string;\n /** With the `pkce` check. */\n readonly codeChallengeMethod?: AuthioCodeChallengeMethod;\n readonly redirectUri: string;\n readonly resource?: string;\n readonly maxAge?: number;\n}\n\n/**\n * An authorization URL and the transaction to keep until the callback.\n */\nexport interface AuthioAuthorizationUrl {\n readonly url: string;\n readonly transaction: AuthioAuthorizationTransaction;\n}\n\n/**\n * A `WWW-Authenticate` bearer challenge, as an API answers it (RFC 6750, RFC 9470, RFC 9728).\n */\nexport interface AuthioBearerChallenge {\n readonly error: string | undefined;\n readonly errorDescription: string | undefined;\n /** `insufficient_scope`: the scopes required. */\n readonly scope: string | undefined;\n /** `insufficient_user_authentication`: the context classes to ask for. */\n readonly acrValues: string | undefined;\n /** `insufficient_user_authentication`: how old the sign-in may be, in seconds. */\n readonly maxAge: number | undefined;\n /** RFC 9728: where the API's protected resource metadata is. */\n readonly resourceMetadata: string | undefined;\n}\n\n/**\n * Creates a PKCE pair: a 256-bit random verifier and its S256 (or plain) challenge.\n */\nexport async function createAuthioPkce(method: AuthioCodeChallengeMethod = \"S256\"): Promise<AuthioPkcePair> {\n if (method !== \"S256\" && method !== \"plain\") throw new TypeError(`The PKCE method '${String(method)}' is not S256 or plain.`);\n\n const codeVerifier = randomValue(32);\n const codeChallenge =\n method === \"plain\" ? codeVerifier : toBase64Url(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(codeVerifier))));\n\n return { codeVerifier, codeChallenge, codeChallengeMethod: method };\n}\n\n/**\n * A random, URL-safe value of `bytes` random bytes, for `state` and `nonce`.\n */\nexport function randomValue(bytes = 32): string {\n return toBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\n/**\n * The checks of a list, without duplicates and without `none`.\n *\n * @throws AuthioConfigurationError naming a value that is not a check.\n * @internal\n */\nexport function resolveChecks(checks: readonly AuthioCheck[] | undefined, setting = \"checks\"): readonly Exclude<AuthioCheck, \"none\">[] {\n const resolved: Exclude<AuthioCheck, \"none\">[] = [];\n\n for (const check of checks ?? []) {\n if (!(AuthioChecks as readonly string[]).includes(check))\n throw new AuthioConfigurationError(`The Authio ${setting} value '${String(check)}' is not one of ${AuthioChecks.join(\", \")}.`);\n\n if (check !== \"none\" && !resolved.includes(check)) resolved.push(check);\n }\n\n return Object.freeze(resolved);\n}\n\n/**\n * Builds the authorization URL and its transaction. Only the listed checks generate their parameter.\n *\n * @internal\n */\nexport async function buildAuthorizationUrl(\n endpoint: string,\n clientId: string,\n request: AuthioAuthorizationRequest & { redirectUri: string },\n): Promise<AuthioAuthorizationUrl> {\n const checks = resolveChecks(request.checks);\n const pkce = checks.includes(\"pkce\") ? await createAuthioPkce(request.codeChallengeMethod ?? \"S256\") : undefined;\n const state = checks.includes(\"state\") ? request.state?.trim() || randomValue() : undefined;\n const nonce = checks.includes(\"nonce\") ? request.nonce?.trim() || randomValue() : undefined;\n\n if (request.maxAge !== undefined && (!Number.isInteger(request.maxAge) || request.maxAge < 0))\n throw new RangeError(\"maxAge must be a non-negative whole number of seconds.\");\n\n const display = request.popup ? \"popup\" : request.display;\n const responseMode = request.popup ? \"web_message\" : request.responseMode;\n\n if (responseMode !== undefined && responseMode !== \"query\" && responseMode !== \"web_message\")\n throw new AuthioConfigurationError(`The Authio responseMode '${String(responseMode)}' is not query or web_message.`);\n\n const url = new URL(endpoint);\n const parameters: Record<string, string | undefined> = {\n ...request.extraParameters,\n response_type: \"code\",\n client_id: clientId,\n redirect_uri: request.redirectUri,\n scope: toScopeString(request.scopes) ?? \"openid\",\n state: state ?? request.state?.trim(),\n nonce: nonce ?? request.nonce?.trim(),\n code_challenge: pkce?.codeChallenge,\n code_challenge_method: pkce?.codeChallengeMethod,\n resource: request.resource,\n organization: request.organization,\n prompt: joined(request.prompt),\n max_age: request.maxAge?.toString(),\n acr_values: joined(request.acrValues),\n login_hint: request.loginHint,\n id_token_hint: request.idTokenHint,\n ui_locales: joined(request.uiLocales),\n display,\n response_mode: responseMode,\n idp_hint: request.idpHint,\n };\n\n for (const [name, value] of Object.entries(parameters)) if (value !== undefined && value !== \"\") url.searchParams.set(name, value);\n\n return {\n url: url.toString(),\n transaction: Object.freeze({\n checks,\n ...(state ? { state } : {}),\n ...(nonce ? { nonce } : {}),\n ...(pkce ? { codeVerifier: pkce.codeVerifier, codeChallengeMethod: pkce.codeChallengeMethod } : {}),\n redirectUri: request.redirectUri,\n ...(request.resource ? { resource: request.resource } : {}),\n ...(request.maxAge !== undefined ? { maxAge: request.maxAge } : {}),\n }),\n };\n}\n\n/**\n * Reads the parameters of an authorization callback: a full URL, its query, a `URLSearchParams`, or an object (a\n * `web_message` answer, or a parsed query).\n *\n * @internal\n */\nexport function readCallbackParameters(callback: string | URL | URLSearchParams | Readonly<Record<string, unknown>>): Record<string, string> {\n if (callback instanceof URLSearchParams) return Object.fromEntries(callback);\n if (callback instanceof URL) return Object.fromEntries(callback.searchParams);\n\n if (typeof callback === \"string\") {\n const text = callback.trim();\n const query = /^[a-z][a-z0-9+.-]*:/i.test(text) ? new URL(text).search : text.slice(text.indexOf(\"?\") + 1);\n\n return Object.fromEntries(new URLSearchParams(query));\n }\n\n const parameters: Record<string, string> = {};\n\n for (const [name, value] of Object.entries(callback ?? {})) {\n const first = Array.isArray(value) ? value[0] : value;\n\n if (typeof first === \"string\") parameters[name] = first;\n }\n\n return parameters;\n}\n\n/**\n * A front-channel logout request (OpenID Connect Front-Channel Logout 1.0): Authio loads the client's\n * `frontchannel_logout_uri` in an iframe, with `iss` and `sid` when the client requires the session.\n */\nexport interface AuthioFrontChannelLogout {\n /** `sid`: the Authio session that ended, when Authio sent it. */\n readonly sessionId: string | undefined;\n /** `iss`, when Authio sent it; always this client's issuer. */\n readonly issuer: string | undefined;\n}\n\n/**\n * Reads a front-channel logout request: `iss` and `sid` come together, and `iss` must be the issuer.\n *\n * @throws AuthioCallbackError with `issuer_mismatch` for another issuer, `missing_issuer` for a `sid` without `iss`.\n */\nexport function readAuthioFrontChannelLogout(\n request: string | URL | URLSearchParams | Readonly<Record<string, unknown>>,\n issuer: string,\n): AuthioFrontChannelLogout {\n const parameters = readCallbackParameters(request);\n const sessionId = parameters.sid?.trim() || undefined;\n const sentIssuer = parameters.iss?.trim() || undefined;\n\n if (sentIssuer !== undefined && sentIssuer.replace(/\\/+$/, \"\") !== issuer.replace(/\\/+$/, \"\"))\n throw new AuthioCallbackError(\"issuer_mismatch\", `The front-channel logout comes from the issuer '${sentIssuer}', not '${issuer}'.`);\n\n if (sessionId !== undefined && sentIssuer === undefined)\n throw new AuthioCallbackError(\"missing_issuer\", \"The front-channel logout names a sid without its iss.\");\n\n return Object.freeze({ sessionId, issuer: sentIssuer });\n}\n\n/**\n * Parses a `WWW-Authenticate` bearer challenge, or `undefined` when the header holds none. It reads the header only,\n * whatever the status: a step-up challenge (`insufficient_user_authentication`) comes with `401` (RFC 9470 §3), or\n * with `403` from servers before `@hyper.authio/server` 0.8.1 and `@hyper.authio/mcp` 0.4.1.\n */\nexport function parseAuthioBearerChallenge(header: string | null | undefined): AuthioBearerChallenge | undefined {\n if (!header || !/^\\s*bearer(\\s|$)/i.test(header)) return undefined;\n\n const values: Record<string, string> = {};\n\n for (const match of header.matchAll(/([a-zA-Z_]+)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"|([a-zA-Z_]+)\\s*=\\s*([^,\\s]+)/g)) {\n const name = (match[1] ?? match[3] ?? \"\").toLowerCase();\n\n values[name] ??= (match[2] ?? match[4] ?? \"\").replace(/\\\\(.)/g, \"$1\");\n }\n\n const maxAge = values.max_age !== undefined && /^\\d+$/.test(values.max_age) ? Number(values.max_age) : undefined;\n\n return {\n error: values.error,\n errorDescription: values.error_description,\n scope: values.scope,\n acrValues: values.acr_values,\n maxAge,\n resourceMetadata: values.resource_metadata,\n };\n}\n\nfunction joined(value: string | readonly string[] | undefined): string | undefined {\n if (value === undefined) return undefined;\n\n const text = (typeof value === \"string\" ? [value] : [...value]).map((item) => item.trim()).filter(Boolean).join(\" \");\n\n return text || undefined;\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n","import type { JWTPayload, JWTVerifyGetKey } from \"jose\";\nimport {\n buildAuthorizationUrl,\n parseAuthioBearerChallenge,\n readAuthioFrontChannelLogout,\n readCallbackParameters,\n resolveChecks,\n type AuthioAuthorizationRequest,\n type AuthioAuthorizationTransaction,\n type AuthioAuthorizationUrl,\n type AuthioBearerChallenge,\n type AuthioCheck,\n type AuthioCodeChallengeMethod,\n type AuthioFrontChannelLogout,\n type AuthioResponseMode,\n} from \"./authorization.js\";\nimport { createClientAuthenticator, type AuthioClientAuthenticator, type AuthioClientCredentialsSettings } from \"./client-authentication.js\";\nimport { AuthioAsymmetricAlgorithms, AuthioDefaults, AuthioGrantTypes, AuthioHmacAlgorithms, AuthioOAuthErrors, AuthioTokenTypes } from \"./constants.js\";\nimport { createAuthioDiscoveryClient, requireEndpoint, type AuthioDiscoveryClient, type AuthioDiscoveryDocument } from \"./discovery.js\";\nimport {\n createAuthioTokenDecrypter,\n encryptionKeyFromFile,\n isAuthioTokenEncrypted,\n type AuthioEncryptionKeySource,\n type AuthioTokenDecrypter,\n} from \"./encryption.js\";\nimport { AuthioCallbackError, AuthioConfigurationError, AuthioProtocolError } from \"./errors.js\";\nimport {\n acceptedSigningAlgorithms,\n createAuthioSigningKeys,\n validateAuthioIdToken,\n validateAuthioLogoutToken,\n requireAccessTokenType,\n verifyAuthioJwt,\n requireHmacSecretLength,\n withClientSecret,\n type AuthioIdTokenClaims,\n type AuthioLogoutToken,\n} from \"./token-validation.js\";\nimport {\n ensureProtocolSuccess,\n formBody,\n parseProtocolJson,\n readProtocolJson,\n redact,\n send,\n toErrorResponse,\n toProtocolError,\n toScopeString,\n} from \"./http.js\";\nimport type {\n AuthioClientCredentialsToken,\n AuthioConnectionChoice,\n AuthioConnectionExchangeResult,\n AuthioDeviceAuthorization,\n AuthioDevicePollOutcome,\n AuthioIntrospectionResult,\n AuthioTokenResponse,\n AuthioUserInfo,\n} from \"./models.js\";\nimport { resolveConnection, seconds, type AuthioConnection, type AuthioConnectionOptions } from \"./options.js\";\n\n/**\n * Everything the Authio client needs: where Authio is, and the client's credentials.\n */\nexport interface AuthioClientOptions extends AuthioConnectionOptions, AuthioClientCredentialsSettings {\n /**\n * Seconds before expiry a cached token is renewed (capped at half its lifetime). Defaults to 60.\n */\n tokenRefreshSkew?: number;\n /**\n * What the authorization round trip checks, as the client is registered in Authio: `pkce`, `state`, `nonce`, or\n * `none`. Only the listed checks are made; omitted, none is (a client that requires PKCE needs `[\"pkce\"]`).\n */\n checks?: readonly AuthioCheck[];\n /** The PKCE method, when `checks` holds `pkce`: one of the client's allowed methods. Defaults to `S256`. */\n codeChallengeMethod?: AuthioCodeChallengeMethod;\n /** The `response_mode` sent with every authorization request: `query` or `web_message`. Omitted, none is sent. */\n responseMode?: AuthioResponseMode;\n /**\n * The algorithm the client's ID tokens are signed with, as registered in Authio, which signs the client's logout\n * tokens with it too. HS256, HS384 and HS512 are verified with `clientSecret` (OpenID Connect Core\n * §10.1). Omitted, the asymmetric algorithms the discovery document announces are accepted (RS*, PS*, ES*).\n */\n idTokenSignedResponseAlg?: string;\n /** The algorithm a signed UserInfo answer is signed with. Defaults to `idTokenSignedResponseAlg`. */\n userinfoSignedResponseAlg?: string;\n /**\n * The algorithm the client's access tokens are signed with (Authio's second signing setting), for\n * `readAccessTokenClaims`. HS* is verified with `clientSecret`. Omitted, the asymmetric algorithms the discovery\n * document announces are accepted, and never HS*.\n */\n accessTokenSignedResponseAlg?: string;\n /**\n * The private half of the client's own encryption key, to read ID tokens, UserInfo and logout tokens Authio\n * encrypts to the client; or a function returning it. Without it, nothing is decrypted.\n */\n clientEncryptionKey?: AuthioEncryptionKeySource;\n /** A PEM or JWK file holding `clientEncryptionKey` (Node only), read on first use. */\n clientEncryptionKeyPath?: string;\n /**\n * The key management algorithms (`alg`) decrypted, as registered for the client. Defaults to RSA-OAEP and\n * RSA-OAEP-256; RSA1_5 cannot be listed, because Node and WebCrypto cannot decrypt it.\n */\n encryptionAlgorithms?: readonly string[];\n /** The content encryption algorithms (`enc`) decrypted. Defaults to A128CBC-HS256, A192CBC-HS384, A256CBC-HS512. */\n encryptionMethods?: readonly string[];\n /**\n * Accepted for parity with the other Authio SDKs; RSA1_5 stays refused here, because Node and WebCrypto cannot\n * decrypt it. Defaults to `false`.\n */\n allowLegacyEncryptionAlgorithms?: boolean;\n /** Where Authio sends the person back after signing in, unless a request names another. */\n redirectUri?: string;\n /** Where Authio sends the person after signing out, unless a request names another. */\n postLogoutRedirectUri?: string;\n /** Seconds of clock skew tolerated on ID tokens, logout tokens and signed UserInfo. Defaults to 30. */\n clockSkew?: number;\n}\n\n/**\n * What a completed sign-in yields.\n */\nexport interface AuthioAuthorizationResult {\n /** The token endpoint's answer: access token, refresh token, ID token. */\n readonly tokens: AuthioTokenResponse;\n /** The validated ID token's claims, when Authio issued one (the `openid` scope). */\n readonly idToken: AuthioIdTokenClaims | undefined;\n}\n\n/**\n * What the end-session URL carries (OpenID Connect RP-Initiated Logout).\n */\nexport interface AuthioEndSessionRequest {\n /** The ID token of the session to end. */\n idTokenHint?: string;\n /** Where to send the person afterwards; must be registered. Defaults to the client's `postLogoutRedirectUri`. */\n postLogoutRedirectUri?: string;\n /** Echoed back to `postLogoutRedirectUri`. */\n state?: string;\n /** The language of the signed-out screen. */\n uiLocales?: string | readonly string[];\n /** Sends the client id unless `false`, so Authio knows the client without an ID token. */\n includeClientId?: boolean;\n}\n\n/**\n * Per-call options.\n */\nexport interface AuthioCallOptions {\n /** Aborts the call. */\n signal?: AbortSignal;\n}\n\n/**\n * The token endpoint's grants.\n */\nexport interface AuthioTokenClient {\n /** `client_credentials`, optionally for a resource (RFC 8707). */\n clientCredentials(options?: { scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions): Promise<AuthioTokenResponse>;\n /** Redeems an authorization code. */\n authorizationCode(\n options: { code: string; redirectUri: string; codeVerifier?: string; resource?: string } & AuthioCallOptions,\n ): Promise<AuthioTokenResponse>;\n /**\n * Refreshes; the answer carries the rotated refresh token, which must be stored. `scopes` may only narrow the\n * granted ones; `resource` (RFC 8707) asks for an access token addressed to that resource server.\n */\n refresh(options: { refreshToken: string; scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions): Promise<AuthioTokenResponse>;\n /** Exchanges a user's access token for one addressed to another resource (RFC 8693, on-behalf-of). */\n exchange(\n options: { subjectToken: string; scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions,\n ): Promise<AuthioTokenResponse>;\n /**\n * Exchanges a user's access token for the token of one of their connected accounts. OAuth refusals come back as\n * a result, never thrown.\n */\n exchangeForConnection(\n options: { subjectToken: string; provider: string; connectionId?: string } & AuthioCallOptions,\n ): Promise<AuthioConnectionExchangeResult>;\n /** Starts the device flow (RFC 8628). */\n deviceAuthorization(options?: { scopes?: Iterable<string> | string } & AuthioCallOptions): Promise<AuthioDeviceAuthorization>;\n /**\n * Polls until the person approves: waits `interval` (default 5 s) before each poll, adds 5 s on `slow_down`, throws\n * on `access_denied` and `expired_token`, and throws `expired_token` when `expires_in` elapses locally.\n */\n pollDevice(\n authorization: AuthioDeviceAuthorization | { device_code: string; interval?: number; expires_in?: number },\n options?: AuthioCallOptions,\n ): Promise<AuthioTokenResponse>;\n /** The resource owner password grant, where the client allows it. */\n password(options: { username: string; password: string; scopes?: Iterable<string> | string } & AuthioCallOptions): Promise<AuthioTokenResponse>;\n /**\n * The `personal_access_token` grant: a `pat_` value presented as `client_secret`, with the consumer's client id for\n * a consumer's token or the platform client (`AuthioDefaults.PlatformClientId`) for an account's token. The client's\n * own credentials are not sent.\n */\n personalAccessToken(\n options: { token: string; clientId?: string; scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions,\n ): Promise<AuthioTokenResponse>;\n}\n\n/**\n * Client-credentials tokens, cached per scopes and resource.\n */\nexport interface AuthioClientCredentialsCache {\n /**\n * A token for the scopes and resource, renewed `tokenRefreshSkew` before expiry (at most half its lifetime);\n * concurrent callers for one key share one request.\n */\n getToken(options?: { scopes?: Iterable<string> | string; resource?: string } & AuthioCallOptions): Promise<AuthioClientCredentialsToken>;\n /** Drops the cached token; with `accessToken`, only when the cache still holds that token. */\n invalidate(options?: { scopes?: Iterable<string> | string; resource?: string; accessToken?: string }): void;\n}\n\n/**\n * The Authio client.\n */\nexport interface AuthioClient {\n /** The issuer. */\n readonly issuer: string;\n /** The client id. */\n readonly clientId: string;\n /** The connection settings. */\n readonly connection: AuthioConnection;\n /** The discovery document. */\n readonly discovery: AuthioDiscoveryClient;\n /** The token endpoint. */\n readonly tokens: AuthioTokenClient;\n /** Cached client-credentials tokens. */\n readonly clientCredentials: AuthioClientCredentialsCache;\n /**\n * Introspects a token as this client (RFC 7662). Authio answers according to who asks: a token requested for a\n * resource (RFC 8707) is active only to the client that resource server names as its introspection client.\n */\n introspect(token: string, options?: { tokenTypeHint?: string } & AuthioCallOptions): Promise<AuthioIntrospectionResult>;\n /** Revokes a token (RFC 7009). */\n revoke(token: string, options?: { tokenTypeHint?: string } & AuthioCallOptions): Promise<void>;\n /**\n * Reads UserInfo. A UserInfo answered as `application/jwt` is decrypted with `clientEncryptionKey` when it is a\n * JWE, then verified against the realm's keys (`iss` the issuer, `aud` the client).\n */\n userInfo(accessToken: string, options?: AuthioCallOptions): Promise<AuthioUserInfo>;\n /**\n * A `fetch` that sends a cached client-credentials token, and on a `401` drops it and retries once.\n */\n clientCredentialsFetch(options?: { scopes?: Iterable<string> | string; resource?: string; fetch?: typeof fetch }): typeof fetch;\n /**\n * Builds the authorization URL (the parameters of the configured `checks`, and Authio's parameters) and the\n * transaction to keep until the callback.\n */\n createAuthorizationUrl(request?: AuthioAuthorizationRequest & AuthioCallOptions): Promise<AuthioAuthorizationUrl>;\n /**\n * Completes a sign-in: checks `state` (with the `state` check) and the `iss` parameter (RFC 9207), throws the OAuth\n * error Authio sent back, redeems the code (with the PKCE verifier, with the `pkce` check), and validates the ID\n * token (`nonce` with the `nonce` check, `at_hash`, `max_age`). A `state` the transaction did not ask for is ignored.\n *\n * @param callback The callback URL, its query, or its parameters (a `web_message` answer, a parsed query).\n * @param transaction What `createAuthorizationUrl` returned with the URL.\n * @throws AuthioCallbackError when the callback is not for this transaction.\n * @throws AuthioProtocolError for an OAuth error.\n * @throws AuthioTokenValidationError when the ID token does not validate.\n */\n handleAuthorizationCallback(\n callback: string | URL | URLSearchParams | Readonly<Record<string, unknown>>,\n transaction: AuthioAuthorizationTransaction,\n options?: AuthioCallOptions,\n ): Promise<AuthioAuthorizationResult>;\n /**\n * Validates an ID token: decrypted with `clientEncryptionKey` when it is a JWE, then signature (cached JWKS), `iss`,\n * `aud` = the client id, `exp` with the skew, payload `typ` = `ID`, and `nonce`, `at_hash` and `auth_time` when\n * given.\n *\n * @throws AuthioTokenValidationError naming why it was refused.\n */\n validateIdToken(idToken: string, expectations?: { nonce?: string; accessToken?: string; maxAge?: number } & AuthioCallOptions): Promise<AuthioIdTokenClaims>;\n /**\n * Validates a back-channel logout token Authio posted as `logout_token`.\n *\n * @throws AuthioTokenValidationError naming why it was refused (`invalid_logout_token` for the logout-specific rules).\n */\n validateLogoutToken(logoutToken: string, options?: AuthioCallOptions): Promise<AuthioLogoutToken>;\n /**\n * Reads a front-channel logout request Authio loaded in an iframe: `iss` must be the issuer, and `sid` comes with\n * it. End the sessions of `sessionId`, or the browser's own session when Authio sent none.\n *\n * @throws AuthioCallbackError when `iss` names another issuer, or `sid` comes without `iss`.\n */\n validateFrontChannelLogout(request: string | URL | URLSearchParams | Readonly<Record<string, unknown>>): AuthioFrontChannelLogout;\n /**\n * Reads an access token this client received from Authio: decrypted with `clientEncryptionKey` when it is a JWE,\n * then its signature (with `accessTokenSignedResponseAlg`), `iss`, `exp` and the header `typ` `at+jwt` (RFC 9068 §4)\n * checked. Its audience is the API's, so it is not checked. `undefined` for an\n * opaque token, or an encrypted one without `clientEncryptionKey`.\n *\n * @throws AuthioTokenValidationError naming why it was refused.\n */\n readAccessTokenClaims(accessToken: string, options?: AuthioCallOptions): Promise<JWTPayload | undefined>;\n /** Builds the end-session URL (RP-Initiated Logout). */\n createEndSessionUrl(request?: AuthioEndSessionRequest & AuthioCallOptions): Promise<string>;\n /**\n * Builds an authorization URL that satisfies an API's `insufficient_user_authentication` challenge (RFC 9470): its\n * `acr_values` and `max_age`, with `prompt=login` when the challenge asks for a sign-in made just now (`max_age=0`).\n *\n * @param challenge The `WWW-Authenticate` header value, or the challenge already parsed.\n */\n createStepUpAuthorizationUrl(\n challenge: string | AuthioBearerChallenge,\n request?: AuthioAuthorizationRequest & AuthioCallOptions,\n ): Promise<AuthioAuthorizationUrl>;\n}\n\n/**\n * Creates the Authio client.\n *\n * @throws AuthioConfigurationError when the settings are incomplete.\n */\nexport function createAuthioClient(options: AuthioClientOptions): AuthioClient {\n const connection = resolveConnection(options);\n const discovery = createAuthioDiscoveryClient(connection);\n const authenticator = createClientAuthenticator(options, connection);\n const refreshSkewMs = seconds(options.tokenRefreshSkew, AuthioDefaults.TokenRefreshSkew, \"tokenRefreshSkew\");\n const clockSkew = seconds(options.clockSkew, AuthioDefaults.ClockSkew, \"clockSkew\") / 1000;\n const encryptionKey = resolveEncryptionKey(options);\n const decrypt = createAuthioTokenDecrypter(encryptionKey, {\n setting: options.clientEncryptionKey === undefined && options.clientEncryptionKeyPath ? \"clientEncryptionKeyPath\" : \"clientEncryptionKey\",\n allowLegacyEncryptionAlgorithms: options.allowLegacyEncryptionAlgorithms,\n encryptionAlgorithms: options.encryptionAlgorithms,\n encryptionMethods: options.encryptionMethods,\n });\n const checks = resolveChecks(options.checks);\n const codeChallengeMethod = resolveCodeChallengeMethod(options.codeChallengeMethod);\n const responseMode = resolveResponseMode(options.responseMode);\n const idTokenAlgorithm = resolveSigningAlgorithm(options.idTokenSignedResponseAlg, \"idTokenSignedResponseAlg\", options.clientSecret);\n const userInfoAlgorithm = resolveSigningAlgorithm(options.userinfoSignedResponseAlg, \"userinfoSignedResponseAlg\", options.clientSecret) ?? idTokenAlgorithm;\n const accessTokenAlgorithm = resolveSigningAlgorithm(options.accessTokenSignedResponseAlg, \"accessTokenSignedResponseAlg\", options.clientSecret);\n const clientSecret = options.clientSecret === undefined ? undefined : () => readSecret(options.clientSecret!);\n const signingKeys = createAuthioSigningKeys(connection, discovery);\n const tokens = createTokenClient(connection, discovery, authenticator);\n const clientCredentials = createClientCredentialsCache(connection, authenticator.clientId, tokens, refreshSkewMs);\n const validationContext = async (signal?: AbortSignal) => {\n const document = await discovery.get(signal);\n\n return {\n keys: withClientSecret(await signingKeys(signal), clientSecret),\n decrypt,\n issuer: connection.issuer,\n clientId: authenticator.clientId,\n algorithms: acceptedSigningAlgorithms(idTokenAlgorithm, document.id_token_signing_alg_values_supported),\n clockSkew,\n now: connection.clock.now(),\n };\n };\n const validateIdToken: AuthioClient[\"validateIdToken\"] = async (idToken, expectations = {}) => {\n requireValue(idToken, \"idToken\");\n\n return validateAuthioIdToken(idToken, await validationContext(expectations.signal), expectations);\n };\n const createAuthorizationUrl: AuthioClient[\"createAuthorizationUrl\"] = async (request = {}) => {\n const redirectUri = request.redirectUri ?? options.redirectUri;\n\n requireValue(redirectUri, \"redirectUri\");\n\n const document = await discovery.get(request.signal);\n\n return buildAuthorizationUrl(requireEndpoint(document, \"authorization_endpoint\"), authenticator.clientId, {\n ...request,\n redirectUri,\n checks: request.checks ?? checks,\n codeChallengeMethod: request.codeChallengeMethod ?? codeChallengeMethod,\n responseMode: request.responseMode ?? responseMode,\n });\n };\n\n return {\n issuer: connection.issuer,\n clientId: authenticator.clientId,\n connection,\n discovery,\n tokens,\n clientCredentials,\n async introspect(token, callOptions = {}) {\n requireValue(token, \"token\");\n\n const response = await postForm(\n connection,\n discovery,\n authenticator,\n \"introspection_endpoint\",\n { token, token_type_hint: callOptions.tokenTypeHint },\n callOptions.signal,\n );\n\n return readProtocolJson<AuthioIntrospectionResult>(response);\n },\n async revoke(token, callOptions = {}) {\n requireValue(token, \"token\");\n\n const response = await postForm(\n connection,\n discovery,\n authenticator,\n \"revocation_endpoint\",\n { token, token_type_hint: callOptions.tokenTypeHint },\n callOptions.signal,\n );\n\n await ensureProtocolSuccess(response);\n },\n async userInfo(accessToken, callOptions = {}) {\n requireValue(accessToken, \"accessToken\");\n\n const document = await discovery.get(callOptions.signal);\n const response = await send(\n connection,\n requireEndpoint(document, \"userinfo_endpoint\"),\n { method: \"GET\", headers: { authorization: `Bearer ${accessToken}`, accept: \"application/json, application/jwt\" } },\n callOptions.signal,\n );\n const mediaType = response.headers.get(\"content-type\")?.split(\";\")[0]?.trim().toLowerCase();\n\n if (response.ok && mediaType === \"application/jwt\")\n return readUserInfoJwt(\n (await response.text()).trim(),\n document,\n connection,\n authenticator.clientId,\n decrypt,\n withClientSecret(await signingKeys(callOptions.signal), clientSecret),\n {\n algorithms: acceptedSigningAlgorithms(userInfoAlgorithm, document.userinfo_signing_alg_values_supported ?? document.id_token_signing_alg_values_supported),\n clockSkew,\n status: response.status,\n },\n );\n\n if (!response.ok) {\n const body = await response.text();\n const challenge = toErrorResponse(body) ? undefined : readBearerChallenge(response);\n\n throw challenge\n ? new AuthioProtocolError(challenge.error, challenge.description, undefined, response.status)\n : toProtocolError(body, response.status);\n }\n\n return readProtocolJson<AuthioUserInfo>(response);\n },\n createAuthorizationUrl,\n async handleAuthorizationCallback(callback, transaction, callOptions = {}) {\n if (!transaction?.redirectUri || !Array.isArray(transaction.checks))\n throw new TypeError(\"transaction is required: keep what createAuthorizationUrl returned.\");\n\n const parameters = readCallbackParameters(callback);\n\n if (transaction.checks.includes(\"state\") && (!transaction.state || parameters.state !== transaction.state))\n throw new AuthioCallbackError(\"state_mismatch\", \"The callback's state is not the one this sign-in was started with.\");\n\n const document = await discovery.get(callOptions.signal);\n\n if (parameters.iss !== undefined) {\n if (parameters.iss.replace(/\\/+$/, \"\") !== connection.issuer)\n throw new AuthioCallbackError(\"issuer_mismatch\", `The callback comes from the issuer '${parameters.iss}', not '${connection.issuer}' (RFC 9207).`);\n } else if (document.authorization_response_iss_parameter_supported === true) {\n throw new AuthioCallbackError(\"missing_issuer\", \"The callback carries no iss parameter, although Authio sends one (RFC 9207).\");\n }\n\n if (parameters.error) throw new AuthioProtocolError(parameters.error, parameters.error_description, parameters.error_code);\n if (!parameters.code) throw new AuthioCallbackError(\"missing_code\", \"The callback carries neither a code nor an error.\");\n\n const answer = await tokens.authorizationCode({\n code: parameters.code,\n redirectUri: transaction.redirectUri,\n codeVerifier: transaction.checks.includes(\"pkce\") ? transaction.codeVerifier : undefined,\n resource: transaction.resource,\n signal: callOptions.signal,\n });\n const idToken = answer.id_token\n ? await validateIdToken(answer.id_token, {\n nonce: transaction.checks.includes(\"nonce\") ? transaction.nonce : undefined,\n accessToken: answer.access_token,\n maxAge: transaction.maxAge,\n signal: callOptions.signal,\n })\n : undefined;\n\n return { tokens: answer, idToken };\n },\n validateIdToken,\n async validateLogoutToken(logoutToken, callOptions = {}) {\n requireValue(logoutToken, \"logoutToken\");\n\n return validateAuthioLogoutToken(logoutToken, await validationContext(callOptions.signal));\n },\n validateFrontChannelLogout(request) {\n return readAuthioFrontChannelLogout(request, connection.issuer);\n },\n async readAccessTokenClaims(accessToken, callOptions = {}) {\n requireValue(accessToken, \"accessToken\");\n\n if (isAuthioTokenEncrypted(accessToken) && encryptionKey === undefined) return undefined;\n\n const signed = await decrypt(accessToken);\n\n if (signed.split(\".\").length !== 3) return undefined;\n\n const document = await discovery.get(callOptions.signal);\n const { payload, header } = await verifyAuthioJwt(signed, withClientSecret(await signingKeys(callOptions.signal), clientSecret), {\n issuer: connection.issuer,\n algorithms: acceptedSigningAlgorithms(accessTokenAlgorithm, document.id_token_signing_alg_values_supported),\n clockSkew,\n now: connection.clock.now(),\n });\n\n requireAccessTokenType(header);\n\n return payload;\n },\n async createEndSessionUrl(request = {}) {\n const document = await discovery.get(request.signal);\n const url = new URL(requireEndpoint(document, \"end_session_endpoint\"));\n const locales =\n request.uiLocales === undefined ? undefined : (typeof request.uiLocales === \"string\" ? [request.uiLocales] : [...request.uiLocales]).join(\" \");\n const parameters: Record<string, string | undefined> = {\n id_token_hint: request.idTokenHint,\n post_logout_redirect_uri: request.postLogoutRedirectUri ?? options.postLogoutRedirectUri,\n state: request.state,\n ui_locales: locales,\n client_id: request.includeClientId === false ? undefined : authenticator.clientId,\n };\n\n for (const [name, value] of Object.entries(parameters)) if (value) url.searchParams.set(name, value);\n\n return url.toString();\n },\n async createStepUpAuthorizationUrl(challenge, request = {}) {\n const parsed = typeof challenge === \"string\" ? parseAuthioBearerChallenge(challenge) : challenge;\n\n if (!parsed || parsed.error !== AuthioOAuthErrors.InsufficientUserAuthentication)\n throw new TypeError(\"The challenge is not an insufficient_user_authentication bearer challenge.\");\n\n return createAuthorizationUrl({\n ...request,\n acrValues: request.acrValues ?? parsed.acrValues,\n maxAge: request.maxAge ?? parsed.maxAge,\n prompt: request.prompt ?? (parsed.maxAge === 0 ? \"login\" : undefined),\n });\n },\n clientCredentialsFetch(fetchOptions = {}) {\n const inner = fetchOptions.fetch ?? connection.fetch;\n const key = { scopes: fetchOptions.scopes, resource: fetchOptions.resource };\n\n return async (input, init) => {\n const request = new Request(input, init);\n const body = request.body ? await request.arrayBuffer() : undefined;\n const attempt = async (token: AuthioClientCredentialsToken) => {\n const headers = new Headers(request.headers);\n\n headers.set(\"authorization\", `${token.tokenType} ${token.accessToken}`);\n\n return inner(request.url, { method: request.method, headers, body, signal: request.signal, redirect: request.redirect });\n };\n\n const token = await clientCredentials.getToken({ ...key, signal: request.signal });\n const response = await attempt(token);\n\n if (response.status !== 401 || isStepUpChallenge(response)) return response;\n\n clientCredentials.invalidate({ ...key, accessToken: token.accessToken });\n\n return attempt(await clientCredentials.getToken({ ...key, signal: request.signal }));\n };\n },\n };\n}\n\n/**\n * Whether a `401` asks for a stronger or more recent sign-in (RFC 9470 §3) rather than a new token, which a retry with\n * another token of the same kind cannot satisfy.\n */\nfunction isStepUpChallenge(response: Response): boolean {\n return parseAuthioBearerChallenge(response.headers.get(\"www-authenticate\"))?.error === AuthioOAuthErrors.InsufficientUserAuthentication;\n}\n\nfunction createTokenClient(connection: AuthioConnection, discovery: AuthioDiscoveryClient, authenticator: AuthioClientAuthenticator): AuthioTokenClient {\n const requestToken = async (parameters: Record<string, string | undefined>, signal?: AbortSignal, authenticate = true) => {\n const response = await postForm(connection, discovery, authenticate ? authenticator : undefined, \"token_endpoint\", parameters, signal);\n const token = await readProtocolJson<AuthioTokenResponse>(response);\n\n return redact(token, [\"access_token\", \"refresh_token\", \"id_token\"]);\n };\n\n const pollDevice: AuthioTokenClient[\"pollDevice\"] = async (authorization, options = {}) => {\n requireValue(authorization?.device_code, \"device_code\");\n\n let wait = (authorization.interval && authorization.interval > 0 ? authorization.interval : AuthioDefaults.DeviceInterval) * 1000;\n const deadline =\n authorization.expires_in && authorization.expires_in > 0 ? connection.clock.now() + authorization.expires_in * 1000 : undefined;\n\n for (;;) {\n await connection.clock.sleep(wait, options.signal);\n\n if (deadline !== undefined && connection.clock.now() >= deadline)\n throw new AuthioProtocolError(AuthioOAuthErrors.ExpiredToken, \"The device code expired before the user approved it.\");\n\n try {\n return await requestToken({ grant_type: AuthioGrantTypes.DeviceCode, device_code: authorization.device_code }, options.signal);\n } catch (error) {\n if (!(error instanceof AuthioProtocolError)) throw error;\n\n const outcome = toDevicePollOutcome(error.error);\n\n if (outcome.outcome === \"failed\") throw error;\n\n wait += outcome.intervalIncrease * 1000;\n }\n }\n };\n\n return {\n clientCredentials: (options = {}) =>\n requestToken(\n { grant_type: AuthioGrantTypes.ClientCredentials, scope: toScopeString(options.scopes), resource: options.resource },\n options.signal,\n ),\n authorizationCode: (options) => {\n requireValue(options?.code, \"code\");\n requireValue(options.redirectUri, \"redirectUri\");\n\n return requestToken(\n {\n grant_type: AuthioGrantTypes.AuthorizationCode,\n code: options.code,\n redirect_uri: options.redirectUri,\n code_verifier: options.codeVerifier,\n resource: options.resource,\n },\n options.signal,\n );\n },\n refresh: (options) => {\n requireValue(options?.refreshToken, \"refreshToken\");\n\n return requestToken(\n { grant_type: AuthioGrantTypes.RefreshToken, refresh_token: options.refreshToken, scope: toScopeString(options.scopes), resource: options.resource },\n options.signal,\n );\n },\n exchange: (options) => {\n requireValue(options?.subjectToken, \"subjectToken\");\n\n return requestToken(\n {\n grant_type: AuthioGrantTypes.TokenExchange,\n subject_token: options.subjectToken,\n subject_token_type: AuthioTokenTypes.AccessTokenUrn,\n requested_token_type: AuthioTokenTypes.AccessTokenUrn,\n scope: toScopeString(options.scopes),\n resource: options.resource,\n },\n options.signal,\n );\n },\n async exchangeForConnection(options) {\n requireValue(options?.subjectToken, \"subjectToken\");\n requireValue(options.provider, \"provider\");\n\n const response = await postForm(\n connection,\n discovery,\n authenticator,\n \"token_endpoint\",\n {\n grant_type: AuthioGrantTypes.TokenExchange,\n subject_token: options.subjectToken,\n subject_token_type: AuthioTokenTypes.AccessTokenUrn,\n requested_token_type: AuthioTokenTypes.ConnectionAccessTokenUrn,\n connection_provider: options.provider,\n connection_id: options.connectionId,\n },\n options.signal,\n );\n\n return toConnectionExchangeResult(await response.text(), response.status, options.provider);\n },\n async deviceAuthorization(options = {}) {\n const response = await postForm(\n connection,\n discovery,\n authenticator,\n \"device_authorization_endpoint\",\n { scope: toScopeString(options.scopes) },\n options.signal,\n );\n\n return redact(await readProtocolJson<AuthioDeviceAuthorization>(response), [\"device_code\"]);\n },\n pollDevice,\n personalAccessToken: (options) => {\n requireValue(options?.token, \"token\");\n\n return requestToken(\n {\n grant_type: AuthioGrantTypes.PersonalAccessToken,\n client_secret: options.token,\n client_id: options.clientId,\n scope: toScopeString(options.scopes),\n resource: options.resource,\n },\n options.signal,\n false,\n );\n },\n password: (options) => {\n requireValue(options?.username, \"username\");\n\n if (typeof options.password !== \"string\") throw new TypeError(\"password is required.\");\n\n return requestToken(\n { grant_type: AuthioGrantTypes.Password, username: options.username, password: options.password, scope: toScopeString(options.scopes) },\n options.signal,\n );\n },\n };\n}\n\nfunction createClientCredentialsCache(\n connection: AuthioConnection,\n clientId: string,\n tokens: AuthioTokenClient,\n refreshSkewMs: number,\n): AuthioClientCredentialsCache {\n const entries = new Map<string, AuthioClientCredentialsToken>();\n const pending = new Map<string, Promise<AuthioClientCredentialsToken>>();\n\n const keyOf = (scope: string | undefined, resource: string | undefined) =>\n `${connection.issuer}|${clientId}|${(scope ?? \"\").split(\" \").filter(Boolean).sort().join(\" \")}|${resource ?? \"\"}`;\n\n return {\n async getToken(options = {}) {\n const scope = toScopeString(options.scopes);\n const key = keyOf(scope, options.resource);\n const cached = entries.get(key);\n\n if (cached && connection.clock.now() < cached.refreshAt) return cached;\n\n let request = pending.get(key);\n\n if (!request) {\n request = tokens\n .clientCredentials({ scopes: scope, resource: options.resource, signal: options.signal })\n .then((response) => {\n const token = toClientCredentialsToken(response, connection.clock.now(), refreshSkewMs);\n\n entries.set(key, token);\n return token;\n })\n .finally(() => pending.delete(key));\n pending.set(key, request);\n }\n\n return request;\n },\n invalidate(options = {}) {\n const key = keyOf(toScopeString(options.scopes), options.resource);\n\n if (options.accessToken === undefined || entries.get(key)?.accessToken === options.accessToken) entries.delete(key);\n },\n };\n}\n\n/**\n * When a token answer expires, and when a cache should renew it: `expires_in` (else 5 minutes) after `issuedAt`,\n * renewed `refreshSkewMs` before that, at most half its lifetime.\n */\nexport function toClientCredentialsToken(response: AuthioTokenResponse, issuedAt: number, refreshSkewMs: number): AuthioClientCredentialsToken {\n const lifetime = (response.expires_in && response.expires_in > 0 ? response.expires_in : AuthioDefaults.AssumedTokenLifetime) * 1000;\n const expiresAt = issuedAt + lifetime;\n const skew = Math.min(refreshSkewMs, lifetime / 2);\n\n return redact(\n {\n accessToken: response.access_token,\n tokenType: response.token_type?.trim() ? response.token_type : \"Bearer\",\n expiresAt,\n refreshAt: expiresAt - skew,\n scope: response.scope,\n },\n [\"accessToken\"],\n );\n}\n\n/**\n * Reads the answer of a connected-account token exchange (see `conformance/oauth-responses.json`).\n *\n * @internal\n */\nexport function toConnectionExchangeResult(body: string, status: number, provider: string): AuthioConnectionExchangeResult {\n if (status >= 200 && status < 300) {\n const token = parseProtocolJson<Record<string, unknown>>(body, status);\n\n if (typeof token.access_token === \"string\" && token.access_token)\n return redact(\n withoutUndefined({\n status: \"granted\" as const,\n accessToken: token.access_token,\n issuedTokenType: textOf(token.issued_token_type),\n tokenType: textOf(token.token_type),\n expiresIn: typeof token.expires_in === \"number\" ? token.expires_in : undefined,\n scope: textOf(token.scope),\n connectionId: textOf(token.connection_id),\n provider: textOf(token.provider) ?? provider,\n providerType: textOf(token.provider_type),\n externalAccount:\n token.external_account && typeof token.external_account === \"object\" ? (token.external_account as Record<string, unknown>) : undefined,\n }),\n [\"accessToken\"],\n );\n }\n\n const error = toErrorResponse(body);\n const errorDescription = error?.error_description?.trim()\n ? error.error_description\n : `Authio answered HTTP ${status} to the connected-account token exchange.`;\n const errorCode = textOf(error?.error_code);\n\n switch (error?.error) {\n case AuthioOAuthErrors.ConnectionRequired:\n return withoutUndefined({\n status: \"required\" as const,\n connectUri: textOf(error.connect_uri),\n provider: textOf(error.connection_provider) ?? provider,\n errorCode,\n errorDescription,\n });\n case AuthioOAuthErrors.ConnectionSelectionRequired:\n return withoutUndefined({\n status: \"selection_required\" as const,\n provider: textOf(error.connection_provider) ?? provider,\n connections: (Array.isArray(error.connections) ? error.connections : []).map(toConnectionChoice),\n errorCode,\n errorDescription,\n });\n default:\n return withoutUndefined({\n status: \"refused\" as const,\n error: error?.error ?? `http_${status}`,\n errorCode,\n errorDescription,\n connectUri: textOf(error?.connect_uri),\n });\n }\n}\n\n/**\n * What a device-flow poll's OAuth error means: keep polling (5 seconds slower after `slow_down`), or stop with it.\n */\nexport function toDevicePollOutcome(error: string): AuthioDevicePollOutcome {\n if (error === AuthioOAuthErrors.AuthorizationPending) return { outcome: \"keep_polling\", intervalIncrease: 0 };\n if (error === AuthioOAuthErrors.SlowDown) return { outcome: \"keep_polling\", intervalIncrease: AuthioDefaults.DeviceSlowDownIncrement };\n\n return { outcome: \"failed\", error };\n}\n\nfunction toConnectionChoice(value: unknown): AuthioConnectionChoice {\n const record = (value && typeof value === \"object\" ? value : {}) as Record<string, unknown>;\n\n return withoutUndefined({ id: textOf(record.id) ?? \"\", label: textOf(record.label), externalLogin: textOf(record.external_login) });\n}\n\nfunction textOf(value: unknown): string | undefined {\n return typeof value === \"string\" && value ? value : undefined;\n}\n\nfunction withoutUndefined<T extends object>(value: T): T {\n for (const key of Object.keys(value) as (keyof T)[]) if (value[key] === undefined) delete value[key];\n\n return value;\n}\n\nfunction resolveEncryptionKey(options: AuthioClientOptions): AuthioEncryptionKeySource | undefined {\n if (options.clientEncryptionKey !== undefined) return options.clientEncryptionKey;\n if (options.clientEncryptionKeyPath) return encryptionKeyFromFile(options.clientEncryptionKeyPath);\n\n return undefined;\n}\n\nasync function postForm(\n connection: AuthioConnection,\n discovery: AuthioDiscoveryClient,\n authenticator: AuthioClientAuthenticator | undefined,\n endpoint: \"token_endpoint\" | \"introspection_endpoint\" | \"revocation_endpoint\" | \"device_authorization_endpoint\",\n parameters: Record<string, string | undefined>,\n signal?: AbortSignal,\n): Promise<Response> {\n const document = await discovery.get(signal);\n const url = requireEndpoint(document, endpoint);\n const form = formBody(parameters);\n const headers = new Headers({ accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" });\n\n await authenticator?.apply(form, headers);\n\n return send(connection, url, { method: \"POST\", headers, body: form.toString() }, signal);\n}\n\nasync function readUserInfoJwt(\n jwt: string,\n document: AuthioDiscoveryDocument,\n connection: AuthioConnection,\n clientId: string,\n decrypt: AuthioTokenDecrypter,\n keys: JWTVerifyGetKey,\n settings: { algorithms: readonly string[]; clockSkew: number; status: number },\n): Promise<AuthioUserInfo> {\n try {\n const signed = isAuthioTokenEncrypted(jwt) ? await decrypt(jwt) : jwt;\n const { payload } = await verifyAuthioJwt(signed, keys, {\n issuer: document.issuer.replace(/\\/+$/, \"\"),\n audiences: [clientId],\n algorithms: settings.algorithms,\n clockSkew: settings.clockSkew,\n now: connection.clock.now(),\n requiredClaims: [\"sub\"],\n });\n\n return payload as AuthioUserInfo;\n } catch (error) {\n throw new AuthioProtocolError(\n \"invalid_userinfo\",\n `The userinfo JWT could not be verified: ${(error as Error)?.message ?? \"unknown reason.\"}`,\n undefined,\n settings.status,\n { cause: error },\n );\n }\n}\n\nfunction readBearerChallenge(response: Response): { error: string; description: string | undefined } | undefined {\n const header = response.headers.get(\"www-authenticate\");\n\n if (!header || !/^bearer\\s/i.test(header.trim())) return undefined;\n\n let error = \"\";\n let description: string | undefined;\n\n for (const match of header.matchAll(/([a-zA-Z_]+)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"|([a-zA-Z_]+)\\s*=\\s*([^,\\s]+)/g)) {\n const name = match[1] ?? match[3];\n const value = (match[2] ?? match[4] ?? \"\").replace(/\\\\(.)/g, \"$1\");\n\n if (name === \"error\") error = value;\n else if (name === \"error_description\") description = value;\n }\n\n return error ? { error, description } : undefined;\n}\n\nfunction resolveCodeChallengeMethod(method: AuthioCodeChallengeMethod | undefined): AuthioCodeChallengeMethod | undefined {\n if (method !== undefined && method !== \"S256\" && method !== \"plain\")\n throw new AuthioConfigurationError(`The Authio codeChallengeMethod '${String(method)}' is not S256 or plain.`);\n\n return method;\n}\n\nfunction resolveResponseMode(mode: AuthioResponseMode | undefined): AuthioResponseMode | undefined {\n if (mode !== undefined && mode !== \"query\" && mode !== \"web_message\")\n throw new AuthioConfigurationError(`The Authio responseMode '${String(mode)}' is not query or web_message.`);\n\n return mode;\n}\n\nfunction resolveSigningAlgorithm(algorithm: string | undefined, setting: string, clientSecret: unknown): string | undefined {\n if (algorithm === undefined || algorithm === \"\") return undefined;\n\n const symmetric = (AuthioHmacAlgorithms as readonly string[]).includes(algorithm);\n\n if (!symmetric && !(AuthioAsymmetricAlgorithms as readonly string[]).includes(algorithm))\n throw new AuthioConfigurationError(\n `The Authio ${setting} '${algorithm}' is not one of ${[...AuthioAsymmetricAlgorithms, ...AuthioHmacAlgorithms].join(\", \")}.`,\n );\n\n if (symmetric && !clientSecret)\n throw new AuthioConfigurationError(`The Authio ${setting} ${algorithm} is verified with the client secret (OpenID Connect Core §10.1): set clientSecret.`);\n\n if (symmetric && typeof clientSecret === \"string\") requireHmacSecretLength(algorithm, new TextEncoder().encode(clientSecret).length);\n\n return algorithm;\n}\n\nasync function readSecret(source: NonNullable<AuthioClientOptions[\"clientSecret\"]>): Promise<string> {\n const value = typeof source === \"function\" ? await source() : source;\n\n if (typeof value !== \"string\" || !value) throw new AuthioConfigurationError(\"The Authio clientSecret function returned no secret.\");\n\n return value;\n}\n\nfunction requireValue(value: unknown, name: string): asserts value is string {\n if (typeof value !== \"string\" || !value.trim()) throw new TypeError(`${name} is required.`);\n}\n","import { createAuthioClient, toClientCredentialsToken, type AuthioClient } from \"./client.js\";\nimport { AuthioDefaults } from \"./constants.js\";\nimport { AuthioAdminError, AuthioConfigurationError, type AuthioAdminNotification } from \"./errors.js\";\nimport { toScopeString } from \"./http.js\";\nimport type { AuthioClientCredentialsToken } from \"./models.js\";\nimport { seconds, systemClock, type AuthioConnectionOptions } from \"./options.js\";\n\n/**\n * A successful Admin API answer: the envelope's `data` (one object, or a listing's page `{ items, totalCount,\n * pageNumber, pageSize }`), nothing for `204`.\n */\nexport interface AuthioAdminSuccess<T = unknown> {\n readonly ok: true;\n readonly data?: T;\n}\n\n/**\n * A refused Admin API answer.\n */\nexport interface AuthioAdminFailure {\n readonly ok: false;\n readonly error: AuthioAdminError;\n}\n\n/**\n * An Admin API answer, read.\n */\nexport type AuthioAdminEnvelope<T = unknown> = AuthioAdminSuccess<T> | AuthioAdminFailure;\n\n/**\n * How an account credential is presented: `ak_` (API key), `cs_` (client secret, exchanged first) or `pat_`\n * (personal access token).\n */\nexport type AuthioAccountCredentialKind = \"api_key\" | \"client_secret\" | \"personal_access_token\";\n\n/**\n * Options of `createAuthioAccountCredential`.\n */\nexport interface AuthioAccountCredentialOptions extends Omit<AuthioConnectionOptions, \"issuer\" | \"realm\"> {\n /** Authio's base URL, such as `https://auth.example.com`. Required. */\n authority?: string;\n /** The credential's value: `ak_…`, `cs_…` or `pat_…`. */\n credential: string;\n /** The credential's id, needed to exchange a `cs_` secret (its `client_id` is `cred_` and the id without dashes). */\n credentialId?: string;\n /** How an `ak_` or `pat_` value is sent directly: `Authorization: Bearer` (default) or `x-api-key`. */\n presentAs?: \"bearer\" | \"x-api-key\";\n /** Exchanges a `pat_` value with the `personal_access_token` grant instead of sending it directly. */\n exchangePersonalAccessToken?: boolean;\n /** Narrows an exchanged token to these `admin:{permission}:{method}` scopes. */\n scopes?: Iterable<string> | string;\n /** Seconds before expiry an exchanged token is renewed (at most half its lifetime). Defaults to 60. */\n tokenRefreshSkew?: number;\n}\n\n/**\n * An account credential ready to call the Admin API with.\n */\nexport interface AuthioAccountCredential {\n /** How the credential is presented. */\n readonly kind: AuthioAccountCredentialKind;\n /** Whether it is exchanged at the `authio` realm's token endpoint before use. */\n readonly exchanged: boolean;\n /** The headers that authenticate a request: `Authorization` or `x-api-key`. */\n headers(signal?: AbortSignal): Promise<Record<string, string>>;\n /** Drops an exchanged token, so the next request exchanges again. */\n invalidate(): void;\n /**\n * A `fetch` that authenticates every request; on `401` with an exchanged token it exchanges again and retries once;\n * on `429` or `503` it waits `Retry-After` and retries an idempotent request (`GET`, `HEAD`, `PUT`, `DELETE`) once.\n */\n readonly fetch: typeof fetch;\n}\n\n/**\n * Reads an Admin API answer (see `conformance/admin-envelopes.json`). The status is the HTTP one, never the\n * envelope's numeric `statusCode`; `requestId` falls back to `X-Request-Id`, and `retryAfterSeconds` comes from\n * `Retry-After`.\n */\nexport function parseAuthioAdminEnvelope<T = unknown>(\n status: number,\n body: string | null | undefined,\n headers?: Headers | Readonly<Record<string, string | undefined>>,\n): AuthioAdminEnvelope<T> {\n const parsed = parseJson(body);\n\n if (status >= 200 && status < 300) {\n if (!parsed) return { ok: true };\n\n return withoutUndefined({ ok: true as const, data: parsed.data as T | undefined });\n }\n\n const notifications = Array.isArray(parsed?.notifications) ? parsed.notifications.map(toNotification).filter((item) => item.message) : [];\n\n return {\n ok: false,\n error: new AuthioAdminError({\n status,\n errorCode: textOf(parsed?.errorCode),\n notifications,\n requestId: textOf(parsed?.requestId) ?? headerOf(headers, AuthioDefaults.RequestIdHeader),\n retryAfterSeconds: retryAfterOf(headerOf(headers, \"Retry-After\")),\n }),\n };\n}\n\n/**\n * Reads an Admin API response, throwing `AuthioAdminError` when it is not a success.\n */\nexport async function readAuthioAdminResponse<T = unknown>(response: Response): Promise<AuthioAdminSuccess<T>> {\n const envelope = parseAuthioAdminEnvelope<T>(response.status, response.status === 204 ? null : await response.text(), response.headers);\n\n if (!envelope.ok) throw envelope.error;\n\n return envelope;\n}\n\n/**\n * Prepares an account credential for the Admin API: `ak_` and `pat_` go directly as `Authorization: Bearer` (or\n * `x-api-key`); a `cs_` secret is exchanged at `{authority}/realms/authio` with `client_credentials` and the\n * `client_id` `cred_{id}`; a `pat_` may be exchanged with the `personal_access_token` grant instead. Exchanged tokens\n * are cached and renewed before expiry.\n *\n * @throws AuthioConfigurationError when the value has no known prefix or a `cs_` secret comes without its id.\n */\nexport function createAuthioAccountCredential(options: AuthioAccountCredentialOptions): AuthioAccountCredential {\n const value = options.credential?.trim();\n\n if (!value) throw new AuthioConfigurationError(\"The account credential is required.\");\n\n const kind: AuthioAccountCredentialKind | undefined = value.startsWith(AuthioDefaults.ApiKeyPrefix)\n ? \"api_key\"\n : value.startsWith(AuthioDefaults.ClientSecretPrefix)\n ? \"client_secret\"\n : value.startsWith(AuthioDefaults.PersonalAccessTokenPrefix)\n ? \"personal_access_token\"\n : undefined;\n\n if (!kind)\n throw new AuthioConfigurationError(\n `The account credential must start with ${AuthioDefaults.ApiKeyPrefix}, ${AuthioDefaults.ClientSecretPrefix} or ${AuthioDefaults.PersonalAccessTokenPrefix}.`,\n );\n\n const exchanged = kind === \"client_secret\" || (kind === \"personal_access_token\" && options.exchangePersonalAccessToken === true);\n const clock = options.clock ?? systemClock;\n const inner = options.fetch ?? globalThis.fetch;\n const scope = toScopeString(options.scopes);\n const refreshSkewMs = seconds(options.tokenRefreshSkew, AuthioDefaults.TokenRefreshSkew, \"tokenRefreshSkew\");\n let client: AuthioClient | undefined;\n let cached: AuthioClientCredentialsToken | undefined;\n let pending: Promise<AuthioClientCredentialsToken> | undefined;\n\n if (exchanged) {\n if (kind === \"client_secret\" && !options.credentialId?.trim())\n throw new AuthioConfigurationError(\"A cs_ client secret is exchanged with its credential id: set credentialId.\");\n\n client = createAuthioClient({\n ...options,\n realm: AuthioDefaults.PlatformRealm,\n clientId: kind === \"client_secret\" ? toCredentialClientId(options.credentialId!) : AuthioDefaults.PlatformClientId,\n clientSecret: kind === \"client_secret\" ? value : undefined,\n tokenEndpointAuthMethod: kind === \"client_secret\" ? \"client_secret_post\" : \"none\",\n });\n }\n\n const exchange = async (signal?: AbortSignal): Promise<AuthioClientCredentialsToken> => {\n if (cached && clock.now() < cached.refreshAt) return cached;\n\n pending ??= (async () => {\n const issuedAt = clock.now();\n const answer =\n kind === \"client_secret\"\n ? await client!.tokens.clientCredentials({ scopes: scope, signal })\n : await client!.tokens.personalAccessToken({ token: value, clientId: AuthioDefaults.PlatformClientId, scopes: scope, signal });\n\n cached = toClientCredentialsToken(answer, issuedAt, refreshSkewMs);\n return cached;\n })().finally(() => {\n pending = undefined;\n });\n\n return pending;\n };\n\n const headers = async (signal?: AbortSignal): Promise<Record<string, string>> => {\n if (exchanged) {\n const token = await exchange(signal);\n\n return { authorization: `${token.tokenType} ${token.accessToken}` };\n }\n\n return options.presentAs === \"x-api-key\" ? { [AuthioDefaults.ApiKeyHeader]: value } : { authorization: `Bearer ${value}` };\n };\n\n const authenticatedFetch: typeof fetch = async (input, init) => {\n const request = new Request(input, init);\n const body = request.body ? await request.arrayBuffer() : undefined;\n const idempotent = [\"GET\", \"HEAD\", \"PUT\", \"DELETE\"].includes(request.method.toUpperCase());\n const attempt = async () => {\n const merged = new Headers(request.headers);\n\n for (const [name, header] of Object.entries(await headers(request.signal))) merged.set(name, header);\n\n return inner(request.url, { method: request.method, headers: merged, body, signal: request.signal, redirect: request.redirect });\n };\n\n let response = await attempt();\n\n if (response.status === 401 && exchanged) {\n cached = undefined;\n response = await attempt();\n }\n\n if ((response.status === 429 || response.status === 503) && idempotent) {\n const wait = retryAfterOf(response.headers.get(\"retry-after\") ?? undefined);\n\n if (wait !== undefined) {\n await clock.sleep(wait * 1000, request.signal);\n response = await attempt();\n }\n }\n\n return response;\n };\n\n return {\n kind,\n exchanged,\n headers,\n invalidate() {\n cached = undefined;\n },\n fetch: authenticatedFetch,\n };\n}\n\n/**\n * The `client_id` an account credential's client secret is exchanged with: `cred_` and the id in format N (no dashes,\n * lower case). An id already starting with `cred_` is kept.\n */\nexport function toCredentialClientId(credentialId: string): string {\n const id = credentialId.trim();\n\n return id.startsWith(AuthioDefaults.CredentialClientIdPrefix) ? id : `${AuthioDefaults.CredentialClientIdPrefix}${id.replace(/[{}-]/g, \"\").toLowerCase()}`;\n}\n\nfunction parseJson(body: string | null | undefined): Record<string, unknown> | undefined {\n if (!body?.trim()) return undefined;\n\n try {\n return asRecord(JSON.parse(body));\n } catch {\n return undefined;\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toNotification(value: unknown): AuthioAdminNotification {\n const record = asRecord(value) ?? {};\n\n return withoutUndefined({ message: textOf(record.message) ?? \"\", field: textOf(record.field), code: textOf(record.code) });\n}\n\nfunction headerOf(headers: Headers | Readonly<Record<string, string | undefined>> | undefined, name: string): string | undefined {\n if (!headers) return undefined;\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n\n const wanted = name.toLowerCase();\n\n for (const [key, value] of Object.entries(headers as Record<string, string | undefined>)) if (key.toLowerCase() === wanted) return value;\n\n return undefined;\n}\n\nfunction retryAfterOf(value: string | undefined): number | undefined {\n if (!value?.trim()) return undefined;\n if (/^\\d+$/.test(value.trim())) return Number(value.trim());\n\n const date = Date.parse(value);\n\n return Number.isNaN(date) ? undefined : Math.max(0, Math.ceil((date - Date.now()) / 1000));\n}\n\nfunction textOf(value: unknown): string | undefined {\n return typeof value === \"string\" && value ? value : undefined;\n}\n\nfunction withoutUndefined<T extends object>(value: T): T {\n for (const key of Object.keys(value) as (keyof T)[]) if (value[key] === undefined) delete value[key];\n\n return value;\n}\n","import { AuthioResourceAccessClaims, type AuthioResourceAccessSource } from \"./constants.js\";\n\n/**\n * One role read from a `*_resource_access` claim, with the permissions it grants.\n */\nexport interface AuthioResourceAccessRole {\n /** The claim the role came from. */\n readonly source: AuthioResourceAccessSource;\n /** The role name. */\n readonly name: string;\n /** Resource → methods the role allows on it. */\n readonly permissions: Readonly<Record<string, readonly string[]>>;\n}\n\nconst claimSources = new Map(Object.entries(AuthioResourceAccessClaims).map(([name, source]) => [name.toLowerCase(), source]));\n\n/**\n * The roles and permissions a token carries in its `*_resource_access` claims, merged across sources.\n *\n * Every comparison is case-insensitive, as Authio's own check is. When a name appears in different case, the first\n * spelling read is the one listed.\n */\nexport class AuthioResourceAccess {\n /** No role at all. */\n static readonly empty = new AuthioResourceAccess([]);\n\n /** Every role read, in claim order, one entry per source it came from. */\n readonly entries: readonly AuthioResourceAccessRole[];\n /** Every distinct role name. */\n readonly roles: readonly string[];\n /** Resource → every method any role allows on it. */\n readonly permissions: Readonly<Record<string, readonly string[]>>;\n\n private readonly lookup: Map<string, Map<string, string>>;\n\n constructor(entries: Iterable<AuthioResourceAccessRole>) {\n this.entries = Object.freeze([...entries]);\n this.roles = Object.freeze(distinctIgnoringCase(this.entries.map((entry) => entry.name)));\n this.lookup = new Map();\n\n const permissions: Record<string, string[]> = {};\n const spelling = new Map<string, string>();\n\n for (const entry of this.entries) {\n for (const [resource, methods] of Object.entries(entry.permissions)) {\n const resourceKey = resource.toLowerCase();\n let allowed = this.lookup.get(resourceKey);\n\n if (!allowed) {\n allowed = new Map();\n this.lookup.set(resourceKey, allowed);\n spelling.set(resourceKey, resource);\n permissions[resource] = [];\n }\n\n for (const method of methods) {\n const methodKey = method.toLowerCase();\n\n if (allowed.has(methodKey)) continue;\n\n allowed.set(methodKey, method);\n permissions[spelling.get(resourceKey)!]!.push(method);\n }\n }\n }\n\n this.permissions = Object.freeze(Object.fromEntries(Object.entries(permissions).map(([name, methods]) => [name, Object.freeze(methods)])));\n }\n\n /** Whether no role was read. */\n get isEmpty(): boolean {\n return this.entries.length === 0;\n }\n\n /**\n * Whether the token holds the role, from any source or only from the given ones.\n */\n hasRole(role: string, sources?: readonly AuthioResourceAccessSource[]): boolean {\n if (!role) return false;\n\n const wanted = role.toLowerCase();\n\n return this.entries.some((entry) => inSources(entry, sources) && entry.name.toLowerCase() === wanted);\n }\n\n /**\n * Authio's grant rule: whether any role (from any source, or only from the given ones) allows `method` on\n * `resource`.\n */\n grants(resource: string, method: string, sources?: readonly AuthioResourceAccessSource[]): boolean {\n if (!resource || !method) return false;\n\n if (!sources || sources.length === 0) return this.lookup.get(resource.toLowerCase())?.has(method.toLowerCase()) ?? false;\n\n return this.entries.some((entry) => inSources(entry, sources) && entryGrants(entry, resource, method));\n }\n\n /**\n * The roles that came from one source.\n */\n fromSource(source: AuthioResourceAccessSource): AuthioResourceAccessRole[] {\n return this.entries.filter((entry) => entry.source === source);\n }\n}\n\n/**\n * The source a claim name stands for, when it is one of the seven `*_resource_access` claims.\n */\nexport function resourceAccessSourceOf(claimType: string | undefined | null): AuthioResourceAccessSource | undefined {\n return claimType ? claimSources.get(claimType.toLowerCase()) : undefined;\n}\n\n/**\n * Reads the roles of every `*_resource_access` claim. Takes a JWT payload or introspection answer, or\n * `[type, value]` pairs; each value may be the JSON object itself or its JSON text. Other claims are ignored.\n */\nexport function parseResourceAccess(claims: Readonly<Record<string, unknown>> | Iterable<readonly [string, unknown]>): AuthioResourceAccess {\n const pairs: Iterable<readonly [string, unknown]> = isIterable(claims) ? claims : Object.entries(claims);\n const roles: AuthioResourceAccessRole[] = [];\n\n for (const [type, value] of pairs) {\n const source = resourceAccessSourceOf(type);\n\n if (source) roles.push(...parseResourceAccessClaim(source, value));\n }\n\n return roles.length === 0 ? AuthioResourceAccess.empty : new AuthioResourceAccess(roles);\n}\n\n/**\n * Reads the roles of one claim value, as strictly as Authio does: a value that is not exactly\n * `{role: {resource: [method]}}` contributes nothing at all. `null` roles, resources and methods are allowed and grant\n * nothing.\n */\nexport function parseResourceAccessClaim(source: AuthioResourceAccessSource, value: unknown): AuthioResourceAccessRole[] {\n const root = typeof value === \"string\" ? parseJson(value) : value;\n\n if (!isPlainObject(root)) return [];\n\n const roles: AuthioResourceAccessRole[] = [];\n\n for (const [name, rolePermissions] of Object.entries(root)) {\n const permissions = readPermissions(rolePermissions);\n\n if (!permissions) return [];\n\n roles.push(Object.freeze({ source, name, permissions }));\n }\n\n return roles;\n}\n\nfunction readPermissions(value: unknown): Readonly<Record<string, readonly string[]>> | undefined {\n if (value === null) return Object.freeze({});\n if (!isPlainObject(value)) return undefined;\n\n const read: Record<string, readonly string[]> = {};\n const seen = new Set<string>();\n\n for (const [resource, methods] of Object.entries(value)) {\n const key = resource.toLowerCase();\n\n if (methods === null) {\n if (!seen.has(key)) {\n seen.add(key);\n read[resource] = Object.freeze([]);\n }\n continue;\n }\n\n if (!Array.isArray(methods)) return undefined;\n\n const allowed: string[] = [];\n\n for (const method of methods) {\n if (typeof method === \"string\") allowed.push(method);\n else if (method !== null) return undefined;\n }\n\n if (!seen.has(key)) {\n seen.add(key);\n read[resource] = Object.freeze(allowed);\n }\n }\n\n return Object.freeze(read);\n}\n\nfunction entryGrants(entry: AuthioResourceAccessRole, resource: string, method: string): boolean {\n const resourceKey = resource.toLowerCase();\n const methodKey = method.toLowerCase();\n\n for (const [name, methods] of Object.entries(entry.permissions)) {\n if (name.toLowerCase() === resourceKey) return methods.some((allowed) => allowed.toLowerCase() === methodKey);\n }\n\n return false;\n}\n\nfunction inSources(entry: AuthioResourceAccessRole, sources: readonly AuthioResourceAccessSource[] | undefined): boolean {\n return !sources || sources.length === 0 || sources.includes(entry.source);\n}\n\nfunction distinctIgnoringCase(values: readonly string[]): string[] {\n const seen = new Set<string>();\n\n return values.filter((value) => {\n const key = value.toLowerCase();\n\n if (seen.has(key)) return false;\n\n seen.add(key);\n return true;\n });\n}\n\nfunction parseJson(text: string): unknown {\n if (!text.trim()) return undefined;\n\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isIterable(value: unknown): value is Iterable<readonly [string, unknown]> {\n return typeof value === \"object\" && value !== null && typeof (value as Iterable<unknown>)[Symbol.iterator] === \"function\";\n}\n","import { AuthioDefaults, AuthioWebhookEventTypes } from \"./constants.js\";\n\n/**\n * Why a webhook delivery failed verification.\n */\nexport type AuthioWebhookVerificationFailure =\n | \"missing_signature\"\n | \"malformed_signature\"\n | \"signature_mismatch\"\n | \"timestamp_outside_tolerance\";\n\n/**\n * The outcome of verifying a webhook signature.\n */\nexport type AuthioWebhookVerificationResult =\n | { readonly valid: true; readonly timestamp: Date }\n | { readonly valid: false; readonly failure: AuthioWebhookVerificationFailure; readonly reason: string; readonly timestamp?: Date };\n\n/**\n * A webhook event. `data` holds the event-specific payload as delivered (snake_case); read it typed, in camelCase,\n * with the `as…` helpers.\n */\nexport interface AuthioWebhookEvent {\n readonly id: string;\n readonly type: string;\n /** Seconds since the epoch. */\n readonly created_at: number;\n readonly realm_id?: string | null;\n /**\n * The client the event came through. On a realm endpoint, `null` when there is none, such as a person created in\n * the realm.\n */\n readonly client_id?: string | null;\n readonly data: unknown;\n [member: string]: unknown;\n}\n\n/** `user_created`, `user_updated`, `user_deleted`, as delivered. */\nexport interface AuthioWebhookUserData {\n id: string;\n username?: string | null;\n email?: string | null;\n first_name?: string | null;\n last_name?: string | null;\n email_confirmed: boolean;\n status?: string | null;\n realm_id?: string | null;\n client_id?: string | null;\n}\n\n/** `login_succeeded`, `login_failed`, as delivered. */\nexport interface AuthioWebhookLoginData {\n grant_type?: string | null;\n user_id?: string | null;\n username?: string | null;\n email?: string | null;\n ip_address?: string | null;\n user_agent?: string | null;\n session_id?: string | null;\n failure_reason?: string | null;\n resource?: string | null;\n scopes?: string[] | null;\n authentication_methods?: string[] | null;\n acr?: string | null;\n identity_provider?: string | null;\n consumer_id?: string | null;\n consumer_name?: string | null;\n}\n\n/** `user_locked_out`, as delivered. */\nexport interface AuthioWebhookUserLockedOutData {\n user_id: string;\n username?: string | null;\n email?: string | null;\n lockout_end?: string | null;\n access_failed_count: number;\n}\n\n/** `token_revoked`, as delivered. */\nexport interface AuthioWebhookTokenRevokedData {\n token_id?: string | null;\n subject?: string | null;\n session_id?: string | null;\n token_type_hint?: string | null;\n}\n\n/**\n * `keys_rotated`, as delivered: `rotation_days` and `automatic` on a scheduled rotation, `revoked_keys_count` on a\n * manual one.\n */\nexport interface AuthioWebhookKeysRotatedData {\n signing_key_id?: string | null;\n encryption_key_id?: string | null;\n revoked_keys_count?: number | null;\n rotation_days?: number | null;\n automatic?: boolean | null;\n}\n\n/** `token_reuse_detected`, as delivered. */\nexport interface AuthioWebhookTokenReuseDetectedData {\n token_id?: string | null;\n subject?: string | null;\n session_id?: string | null;\n ip_address?: string | null;\n user_agent?: string | null;\n}\n\n/** `admin_resource_created`, `admin_resource_updated`, `admin_resource_deleted`, as delivered. */\nexport interface AuthioWebhookAdminResourceData {\n action?: string | null;\n resource_type?: string | null;\n resource_id?: string | null;\n parent_id?: string | null;\n realm_id?: string | null;\n client_id?: string | null;\n /** `User` or `Credential`. */\n actor_type?: string | null;\n actor_user_id?: string | null;\n actor_username?: string | null;\n actor_email?: string | null;\n actor_credential_id?: string | null;\n actor_credential_name?: string | null;\n actor_platform_operator?: boolean | null;\n ip_address?: string | null;\n method?: string | null;\n path?: string | null;\n /** What changed, by resource type; kept as delivered. */\n details?: Record<string, unknown> | null;\n}\n\n/** `user_suspended`, `user_suspension_ended`, as delivered. */\nexport interface AuthioWebhookUserSuspensionData {\n id: string;\n user_id: string;\n level?: string | null;\n status?: string | null;\n starts_at?: string | null;\n ends_at?: string | null;\n restricted_scopes: string[];\n revokes_every_role: boolean;\n revoked_role_ids: string[];\n sessions_terminated_at?: string | null;\n lifted_at?: string | null;\n}\n\n/** `attack_detected`, as delivered: an attack on the realm and the measure Authio took. */\nexport interface AuthioWebhookAttackDetectedData {\n incident_id: string;\n /** Such as `credential_stuffing`. */\n kind?: string | null;\n severity?: string | null;\n /** Such as `source_blocked`. */\n measure?: string | null;\n ip_address?: string | null;\n country?: string | null;\n asn?: number | null;\n network_operator?: string | null;\n user_id?: string | null;\n started_at?: string | null;\n}\n\n/** `credential_compromised`, as delivered: a person's password was used by an attacker. */\nexport interface AuthioWebhookCredentialCompromisedData {\n incident_id: string;\n user_id?: string | null;\n username?: string | null;\n ip_address?: string | null;\n country?: string | null;\n asn?: number | null;\n network_operator?: string | null;\n password_change_required?: boolean | null;\n}\n\n/**\n * `user_authenticator_app_enrolled`, `user_authenticator_app_removed`, `user_recovery_codes_regenerated` and\n * `user_recovery_code_used`, as delivered: a change to a person's authenticator app, never a code nor the secret.\n */\nexport interface AuthioWebhookAuthenticatorAppData {\n user_id: string;\n username?: string | null;\n email?: string | null;\n /** Who made the change: `user`, or `administrator` when an administrator reset the app. */\n actor?: string | null;\n /** The recovery codes the account has left after the change. */\n recovery_codes_remaining?: number | null;\n}\n\n/** `ping`, as delivered. */\nexport interface AuthioWebhookPingData {\n message?: string | null;\n subscription?: string | null;\n}\n\n/**\n * The data shape of each event type, as delivered (snake_case).\n */\nexport interface AuthioWebhookDataByType {\n user_created: AuthioWebhookUserData;\n user_updated: AuthioWebhookUserData;\n user_deleted: AuthioWebhookUserData;\n login_succeeded: AuthioWebhookLoginData;\n login_failed: AuthioWebhookLoginData;\n user_locked_out: AuthioWebhookUserLockedOutData;\n token_revoked: AuthioWebhookTokenRevokedData;\n keys_rotated: AuthioWebhookKeysRotatedData;\n token_reuse_detected: AuthioWebhookTokenReuseDetectedData;\n admin_resource_created: AuthioWebhookAdminResourceData;\n admin_resource_updated: AuthioWebhookAdminResourceData;\n admin_resource_deleted: AuthioWebhookAdminResourceData;\n user_suspended: AuthioWebhookUserSuspensionData;\n user_suspension_ended: AuthioWebhookUserSuspensionData;\n attack_detected: AuthioWebhookAttackDetectedData;\n credential_compromised: AuthioWebhookCredentialCompromisedData;\n user_authenticator_app_enrolled: AuthioWebhookAuthenticatorAppData;\n user_authenticator_app_removed: AuthioWebhookAuthenticatorAppData;\n user_recovery_codes_regenerated: AuthioWebhookAuthenticatorAppData;\n user_recovery_code_used: AuthioWebhookAuthenticatorAppData;\n ping: AuthioWebhookPingData;\n}\n\n/**\n * A snake_case name in camelCase.\n */\nexport type AuthioCamelCase<S extends string> = S extends `${infer Head}_${infer Tail}` ? `${Head}${Capitalize<AuthioCamelCase<Tail>>}` : S;\n\n/**\n * An object whose top-level member names are turned into camelCase, values unchanged.\n */\nexport type AuthioCamelCased<T> = { [K in keyof T as K extends string ? AuthioCamelCase<K> : K]: T[K] };\n\n/** The data of a user event, as the typed accessor exposes it. */\nexport type AuthioWebhookUser = AuthioCamelCased<AuthioWebhookUserData>;\n/** The data of a login event, as the typed accessor exposes it. */\nexport type AuthioWebhookLogin = AuthioCamelCased<AuthioWebhookLoginData>;\n/** The data of a lockout event, as the typed accessor exposes it. */\nexport type AuthioWebhookUserLockedOut = AuthioCamelCased<AuthioWebhookUserLockedOutData>;\n/** The data of a revocation event, as the typed accessor exposes it. */\nexport type AuthioWebhookTokenRevoked = AuthioCamelCased<AuthioWebhookTokenRevokedData>;\n/** The data of a key rotation event, as the typed accessor exposes it. */\nexport type AuthioWebhookKeysRotated = AuthioCamelCased<AuthioWebhookKeysRotatedData>;\n/** The data of a refresh token reuse event, as the typed accessor exposes it. */\nexport type AuthioWebhookTokenReuseDetected = AuthioCamelCased<AuthioWebhookTokenReuseDetectedData>;\n/** The data of an admin resource event, as the typed accessor exposes it. */\nexport type AuthioWebhookAdminResource = AuthioCamelCased<AuthioWebhookAdminResourceData>;\n/** The data of a suspension event, as the typed accessor exposes it. */\nexport type AuthioWebhookUserSuspension = AuthioCamelCased<AuthioWebhookUserSuspensionData>;\n/** The data of an attack event, as the typed accessor exposes it. */\nexport type AuthioWebhookAttackDetected = AuthioCamelCased<AuthioWebhookAttackDetectedData>;\n/** The data of a compromised credential event, as the typed accessor exposes it. */\nexport type AuthioWebhookCredentialCompromised = AuthioCamelCased<AuthioWebhookCredentialCompromisedData>;\n/** The data of an authenticator app event, as the typed accessor exposes it. */\nexport type AuthioWebhookAuthenticatorApp = AuthioCamelCased<AuthioWebhookAuthenticatorAppData>;\n/** The data of a ping, as the typed accessor exposes it. */\nexport type AuthioWebhookPing = AuthioCamelCased<AuthioWebhookPingData>;\n\n/**\n * An event narrowed to one type, with its data typed as delivered.\n */\nexport type AuthioTypedWebhookEvent<T extends keyof AuthioWebhookDataByType> = AuthioWebhookEvent & {\n readonly type: T;\n readonly data: AuthioWebhookDataByType[T];\n};\n\nconst encoder = new TextEncoder();\n\n/**\n * Verifies the `X-Authio-Signature` header (`t={unixSeconds},v1={hex}`) against the raw body: HMAC-SHA256 of\n * `{t}.{body}` with the secret, compared in constant time, any matching `v1` accepted, the signature checked before\n * the timestamp.\n *\n * @param signatureHeader The header value.\n * @param rawBody The body exactly as received.\n * @param secret The webhook's secret.\n * @param options `tolerance` in seconds (default 300) and `now` in milliseconds (default the current time).\n */\nexport async function verifyWebhookSignature(\n signatureHeader: string | null | undefined,\n rawBody: string | Uint8Array,\n secret: string,\n options: { tolerance?: number; now?: number } = {},\n): Promise<AuthioWebhookVerificationResult> {\n if (!secret) throw new TypeError(\"secret is required.\");\n\n if (!signatureHeader?.trim())\n return { valid: false, failure: \"missing_signature\", reason: \"The X-Authio-Signature header is missing.\" };\n\n const parsed = parseSignatureHeader(signatureHeader);\n\n if (!parsed)\n return {\n valid: false,\n failure: \"malformed_signature\",\n reason: \"The X-Authio-Signature header is not of the form t={unixSeconds},v1={hex}.\",\n };\n\n const signedAt = new Date(parsed.timestamp * 1000);\n const expected = await computeSignature(parsed.timestamp, rawBody, secret);\n let matched = false;\n\n for (const signature of parsed.signatures) matched = constantTimeEquals(expected, signature) || matched;\n\n if (!matched)\n return {\n valid: false,\n failure: \"signature_mismatch\",\n reason: \"No v1 signature matches the body: the secret is wrong or the body was altered.\",\n timestamp: signedAt,\n };\n\n const tolerance = (options.tolerance ?? AuthioDefaults.WebhookTolerance) * 1000;\n const now = options.now ?? Date.now();\n\n if (Math.abs(now - signedAt.getTime()) > tolerance)\n return {\n valid: false,\n failure: \"timestamp_outside_tolerance\",\n reason: `The signature was made at ${signedAt.toISOString()}, more than ${tolerance / 1000} seconds from now.`,\n timestamp: signedAt,\n };\n\n return { valid: true, timestamp: signedAt };\n}\n\n/**\n * Computes the `X-Authio-Signature` value Authio would send, for tests and replays.\n *\n * @param timestamp Milliseconds since the epoch, or a date.\n */\nexport async function computeWebhookSignatureHeader(rawBody: string | Uint8Array, secret: string, timestamp: number | Date): Promise<string> {\n if (!secret) throw new TypeError(\"secret is required.\");\n\n const seconds = Math.floor((timestamp instanceof Date ? timestamp.getTime() : timestamp) / 1000);\n const signature = await computeSignature(seconds, rawBody, secret);\n\n return `t=${seconds},v1=${[...signature].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/**\n * Parses a webhook body.\n *\n * @throws SyntaxError when it is not JSON or has no `type`.\n */\nexport function parseWebhookEvent(rawBody: string | Uint8Array): AuthioWebhookEvent {\n const text = typeof rawBody === \"string\" ? rawBody : new TextDecoder().decode(rawBody);\n const value = JSON.parse(text) as AuthioWebhookEvent | null;\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new SyntaxError(\"The webhook body is empty.\");\n if (typeof value.type !== \"string\" || !value.type) throw new SyntaxError(\"The webhook body has no type.\");\n\n return value;\n}\n\n/**\n * Parses a webhook body, or returns `undefined` when it cannot be read.\n */\nexport function tryParseWebhookEvent(rawBody: string | Uint8Array | null | undefined): AuthioWebhookEvent | undefined {\n if (rawBody === null || rawBody === undefined) return undefined;\n\n try {\n return parseWebhookEvent(rawBody);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether the event is of one of the given types, narrowing its data.\n */\nexport function isWebhookEventOfType<T extends keyof AuthioWebhookDataByType>(\n event: AuthioWebhookEvent,\n ...types: T[]\n): event is AuthioTypedWebhookEvent<T> {\n return (types as string[]).includes(event.type);\n}\n\n/** The data of a user event in camelCase, or `undefined` for any other type. */\nexport const asUserEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookUser>(event, AuthioWebhookEventTypes.UserCreated, AuthioWebhookEventTypes.UserUpdated, AuthioWebhookEventTypes.UserDeleted);\n/** The data of a login event in camelCase, or `undefined` for any other type. */\nexport const asLoginEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookLogin>(event, AuthioWebhookEventTypes.LoginSucceeded, AuthioWebhookEventTypes.LoginFailed);\n/** The data of a lockout event in camelCase, or `undefined` for any other type. */\nexport const asUserLockedOutEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookUserLockedOut>(event, AuthioWebhookEventTypes.UserLockedOut);\n/** The data of a revocation event in camelCase, or `undefined` for any other type. */\nexport const asTokenRevokedEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookTokenRevoked>(event, AuthioWebhookEventTypes.TokenRevoked);\n/** The data of a key rotation event in camelCase, or `undefined` for any other type. */\nexport const asKeysRotatedEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookKeysRotated>(event, AuthioWebhookEventTypes.KeysRotated);\n/** The data of a refresh token reuse event in camelCase, or `undefined` for any other type. */\nexport const asTokenReuseDetectedEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookTokenReuseDetected>(event, AuthioWebhookEventTypes.TokenReuseDetected);\n/** The data of an admin resource event in camelCase, or `undefined` for any other type. */\nexport const asAdminResourceEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookAdminResource>(\n event,\n AuthioWebhookEventTypes.AdminResourceCreated,\n AuthioWebhookEventTypes.AdminResourceUpdated,\n AuthioWebhookEventTypes.AdminResourceDeleted,\n );\n/** The data of a suspension event in camelCase, or `undefined` for any other type. */\nexport const asUserSuspensionEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookUserSuspension>(event, AuthioWebhookEventTypes.UserSuspended, AuthioWebhookEventTypes.UserSuspensionEnded);\n/** The data of an attack event in camelCase, or `undefined` for any other type. */\nexport const asAttackDetectedEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookAttackDetected>(event, AuthioWebhookEventTypes.AttackDetected);\n/** The data of a compromised credential event in camelCase, or `undefined` for any other type. */\nexport const asCredentialCompromisedEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookCredentialCompromised>(event, AuthioWebhookEventTypes.CredentialCompromised);\n/** The data of an authenticator app event in camelCase, or `undefined` for any other type. */\nexport const asAuthenticatorAppEvent = (event: AuthioWebhookEvent) =>\n dataWhen<AuthioWebhookAuthenticatorApp>(\n event,\n AuthioWebhookEventTypes.UserAuthenticatorAppEnrolled,\n AuthioWebhookEventTypes.UserAuthenticatorAppRemoved,\n AuthioWebhookEventTypes.UserRecoveryCodesRegenerated,\n AuthioWebhookEventTypes.UserRecoveryCodeUsed,\n );\n/** The data of a ping in camelCase, or `undefined` for any other type. */\nexport const asPingEvent = (event: AuthioWebhookEvent) => dataWhen<AuthioWebhookPing>(event, AuthioWebhookEventTypes.Ping);\n\nconst knownEventTypes = new Set<string>(Object.values(AuthioWebhookEventTypes));\n\n/**\n * Whether Authio documents the event type. An unknown type still parses; read its `data` as delivered.\n */\nexport function isKnownWebhookEventType(type: string): type is keyof AuthioWebhookDataByType {\n return knownEventTypes.has(type);\n}\n\n/**\n * The data of any known event in camelCase (what the typed accessor of its type returns), or `undefined` for an\n * unknown type.\n */\nexport function readWebhookEventData(event: AuthioWebhookEvent): Record<string, unknown> | undefined {\n return isKnownWebhookEventType(event.type) ? dataWhen<Record<string, unknown>>(event, event.type) : undefined;\n}\n\n/**\n * Turns the top-level member names of an object from snake_case into camelCase, leaving the values as they are.\n */\nexport function toCamelCasedMembers<T extends object>(value: T): AuthioCamelCased<T> {\n const result: Record<string, unknown> = {};\n\n for (const [name, member] of Object.entries(value)) result[name.replace(/_([a-z0-9])/g, (_, letter: string) => letter.toUpperCase())] = member;\n\n return result as AuthioCamelCased<T>;\n}\n\nfunction dataWhen<T>(event: AuthioWebhookEvent, ...types: string[]): T | undefined {\n return types.includes(event.type) && event.data !== null && typeof event.data === \"object\" && !Array.isArray(event.data)\n ? (toCamelCasedMembers(event.data) as T)\n : undefined;\n}\n\nfunction parseSignatureHeader(header: string): { timestamp: number; signatures: Uint8Array[] } | undefined {\n let timestamp = 0;\n let timestamps = 0;\n const signatures: Uint8Array[] = [];\n\n for (const raw of header.split(\",\")) {\n const part = raw.trim();\n\n if (!part) continue;\n\n const separator = part.indexOf(\"=\");\n\n if (separator <= 0) return undefined;\n\n const key = part.slice(0, separator);\n const value = part.slice(separator + 1);\n\n if (key === \"t\") {\n timestamps++;\n\n if (!/^\\d+$/.test(value)) return undefined;\n\n timestamp = Number(value);\n } else if (key === \"v1\" && value.length === 64 && /^[0-9a-fA-F]+$/.test(value)) {\n signatures.push(Uint8Array.from(value.match(/../g)!.map((pair) => parseInt(pair, 16))));\n }\n }\n\n return timestamps === 1 && signatures.length > 0 && Number.isSafeInteger(timestamp) ? { timestamp, signatures } : undefined;\n}\n\nasync function computeSignature(timestamp: number, rawBody: string | Uint8Array, secret: string): Promise<Uint8Array> {\n const prefix = encoder.encode(`${timestamp}.`);\n const body = typeof rawBody === \"string\" ? encoder.encode(rawBody) : rawBody;\n const message = new Uint8Array(prefix.length + body.length);\n\n message.set(prefix, 0);\n message.set(body, prefix.length);\n\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n\n return new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, message));\n}\n\nfunction constantTimeEquals(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false;\n\n let difference = 0;\n\n for (let index = 0; index < left.length; index++) difference |= left[index]! ^ right[index]!;\n\n return difference === 0;\n}\n"]}