@hyper.authio/server 0.10.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -349,7 +349,7 @@ declare function toProblemDetails(error: AuthioBearerError | AuthioForbiddenErro
|
|
|
349
349
|
* - `activeCheck`: validated locally, then confirmed active by introspection (cached per `jti`). The caller is read
|
|
350
350
|
* from the token, and the introspection answer adds the claims the token does not carry: the answer has every claim
|
|
351
351
|
* of the complete token, so a lightweight access token's roles and permissions are read too. A claim the token
|
|
352
|
-
* carries keeps the token's value, which its signature vouches for
|
|
352
|
+
* carries keeps the token's value, which its signature vouches for, whatever the answer says.
|
|
353
353
|
* - `introspectionOnly`: introspection alone, for opaque (reference) tokens, or encrypted ones without the key. The
|
|
354
354
|
* caller is read from the answer.
|
|
355
355
|
*/
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/user.ts","../src/rules.ts","../src/errors.ts","../src/resource-metadata.ts","../src/verifier.ts","../src/webhooks.ts","../src/downstream.ts"],"names":["seconds","AuthioConfigurationError","systemClock","until","AuthioDefaults","AuthioError","token"],"mappings":";;;;AAiCA,IAAM,mCAAmB,IAAI,GAAA,CAAI,CAAC,QAAA,EAAU,SAAS,CAAC,CAAA;AAuB/C,IAAM,UAAA,GAAN,MAAM,WAAA,CAAW;AAAA;AAAA,EAEb,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,cAAA;AAAA;AAAA,EAEA,YAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,aAAA;AAAA;AAA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n type AuthioResourceAccessSource,\n} from \"@hyper.authio/client\";\n\n/**\n * The party acting for the subject, from the `act` claim (RFC 8693): who exchanged the token, nested when the chain\n * is longer.\n */\nexport interface AuthioActor {\n readonly clientId: string | undefined;\n readonly subject: string | undefined;\n /** `name`, on an impersonation: the administrator's display name. */\n readonly name: string | undefined;\n readonly actor: AuthioActor | undefined;\n}\n\n/**\n * The administrator who impersonates the subject (an `act` with `sub` and no `client_id`).\n */\nexport interface AuthioImpersonator {\n readonly subject: string;\n readonly name: string | undefined;\n}\n\n/**\n * Introspection `token_type` values that stand for an access token: `Bearer`, and `api_key` for a consumer's API key.\n */\nconst accessTokenTypes = new Set([\"bearer\", \"api_key\"]);\n\n/**\n * Where the user reads flat (non-`*_resource_access`) roles and groups from.\n */\nexport interface AuthioUserClaimSettings {\n /**\n * Claims holding role names directly, such as one written by a claim mapper with the Role source. They count for\n * `hasRole` without a source filter. Defaults to `[\"role\"]`.\n */\n roleClaims?: readonly string[];\n /**\n * Claims holding group names, such as one written by a claim mapper with the Group source. Defaults to\n * `[\"groups\"]`.\n */\n groupClaims?: readonly string[];\n}\n\n/**\n * The caller of an API, read from a validated access token, an introspection answer, or both (the token's claims and\n * those of the answer the token does not carry, as `activeCheck` reads it): identity, every form of permission Authio\n * issues, and the raw claims for anything else.\n */\nexport class AuthioUser {\n /** `sub`: the person's id, or the credential's for a machine caller. */\n readonly subject: string;\n /**\n * Who called: `user` (a person signed in), `client` (a client as itself), `consumer` (a machine consumer of a\n * client) or `account_credential` (a credential of an Authio account).\n */\n readonly kind: AuthioCallerKind;\n /**\n * How a machine caller proved who it is (`client_secret`, `personal_access_token`, `api_key`,\n * `consumer_api_key`); `undefined` for a person or a client.\n */\n readonly credentialForm: AuthioCredentialForm | undefined;\n /** `consumer_name`, for a consumer. */\n readonly consumerName: string | undefined;\n /** `credential_name`, for an account credential. */\n readonly credentialName: string | undefined;\n /** `owner_user_id`: the person who made the credential. */\n readonly ownerUserId: string | undefined;\n /**\n * `owner_username`: the person who made the credential. On an account credential Authio wrote it to\n * `consumer_name` before, which is read when `owner_username` is absent.\n */\n readonly ownerUsername: string | undefined;\n /** `credential_realm`: the one realm an account credential is limited to. */\n readonly credentialRealm: string | undefined;\n /** `credential_client`: the one client an account credential is limited to. */\n readonly credentialClient: string | undefined;\n /** Whether an administrator impersonates the subject. */\n readonly impersonated: boolean;\n /** The administrator impersonating the subject. */\n readonly impersonator: AuthioImpersonator | undefined;\n /** Whether a client acts for the subject through a delegation (`act` with `client_id`). */\n readonly delegated: boolean;\n /** The clients acting for the subject, outermost first. */\n readonly actorChain: readonly string[];\n /** `auth_time`, in seconds since the epoch. */\n readonly authTime: number | undefined;\n /** The client the token was issued to (`client_id`, RFC 9068 §2.2, else `azp`). */\n readonly clientId: string | undefined;\n /** `sid`. */\n readonly sessionId: string | undefined;\n /** `jti`. */\n readonly tokenId: string | undefined;\n /** `aud`. */\n readonly audiences: readonly string[];\n /** The granted scopes. */\n readonly scopes: readonly string[];\n /** The roles of the seven `*_resource_access` claims, with their source and permissions. */\n readonly resourceAccess: AuthioResourceAccess;\n /** Every role name: the `*_resource_access` roles, then the flat role claims. */\n readonly roles: readonly string[];\n /** Resource → every method any role allows on it. */\n readonly permissions: Readonly<Record<string, readonly string[]>>;\n /** The group names of the group claims. */\n readonly groups: readonly string[];\n /** `org_id`. */\n readonly organizationId: string | undefined;\n /** `org_alias`. */\n readonly organizationAlias: string | undefined;\n /** `account_id`. */\n readonly accountId: string | undefined;\n /** `acr`. */\n readonly acr: string | undefined;\n /** `acr` as a number: 1 one factor, 2 several, 3 one of them phishing-resistant. */\n readonly authenticationLevel: number | undefined;\n /** `amr`. */\n readonly authenticationMethods: readonly string[];\n /** `idp`. */\n readonly identityProvider: string | undefined;\n /** `auth_time`. */\n readonly authenticatedAt: Date | undefined;\n /** `act`. */\n readonly actor: AuthioActor | undefined;\n /** `delegation_id`. */\n readonly delegationId: string | undefined;\n readonly email: string | undefined;\n readonly emailVerified: boolean | undefined;\n readonly name: string | undefined;\n readonly preferredUsername: string | undefined;\n /** `credential_type`, on a token issued to an account credential or a consumer. */\n readonly credentialType: string | undefined;\n /** `credential_id`. */\n readonly credentialId: string | undefined;\n /**\n * Every claim, as the token or the introspection answer carried it (with `activeCheck`, the token's, plus the\n * answer's the token does not carry).\n */\n readonly claims: Readonly<Record<string, unknown>>;\n /** The access token the user was read from. Not enumerable, so it stays out of logs and JSON. */\n declare readonly token: string | undefined;\n\n private readonly flatRoles: readonly string[];\n\n /**\n * @param claims The token's payload, or the introspection answer's members.\n * @param settings Where flat roles and groups are read from.\n * @param token The access token, kept for forwarding and on-behalf-of.\n * @param source Where the claims come from: a JWT (default) or an introspection answer. An introspection answer for\n * a consumer that reports no `exp` and no `actor_type` is the consumer's API key (Authio reports no lifetime for a\n * key), so its `credentialForm` is `consumer_api_key`.\n */\n constructor(\n claims: Readonly<Record<string, unknown>>,\n settings: AuthioUserClaimSettings = {},\n token?: string,\n source: \"token\" | \"introspection\" = \"token\",\n ) {\n const text = (name: string) => (typeof claims[name] === \"string\" && claims[name] ? (claims[name] as string) : undefined);\n\n this.claims = Object.freeze({ ...claims });\n this.subject = text(AuthioClaimTypes.Subject) ?? \"\";\n this.clientId = text(AuthioClaimTypes.ClientId) ?? text(AuthioClaimTypes.AuthorizedParty);\n this.sessionId = text(AuthioClaimTypes.SessionId);\n this.tokenId = text(AuthioClaimTypes.JwtId);\n this.audiences = Object.freeze(distinct(valuesOf(claims[AuthioClaimTypes.Audience])));\n this.scopes = Object.freeze(distinct(valuesOf(claims[AuthioClaimTypes.Scope]).flatMap((scope) => scope.split(/\\s+/)).filter(Boolean)));\n this.resourceAccess = parseResourceAccess(claims);\n this.flatRoles = Object.freeze((settings.roleClaims ?? [\"role\"]).flatMap((name) => valuesOf(claims[name])));\n this.roles = Object.freeze(distinctIgnoringCase([...this.resourceAccess.roles, ...this.flatRoles]));\n this.permissions = this.resourceAccess.permissions;\n this.groups = Object.freeze(distinct((settings.groupClaims ?? [\"groups\"]).flatMap((name) => valuesOf(claims[name]))));\n this.organizationId = text(AuthioClaimTypes.OrganizationId);\n this.organizationAlias = text(AuthioClaimTypes.OrganizationAlias);\n this.accountId = text(AuthioClaimTypes.AccountId);\n this.acr = valuesOf(claims[AuthioClaimTypes.AuthenticationContextClass])[0];\n this.authenticationLevel = this.acr !== undefined && /^\\d+$/.test(this.acr) ? Number(this.acr) : undefined;\n this.authenticationMethods = Object.freeze(distinctIgnoringCase(valuesOf(claims[AuthioClaimTypes.AuthenticationMethods])));\n this.identityProvider = text(AuthioClaimTypes.IdentityProvider);\n this.authenticatedAt = toDate(claims[AuthioClaimTypes.AuthTime]);\n this.actor = readActor(claims[AuthioClaimTypes.Actor]);\n this.delegationId = text(AuthioClaimTypes.DelegationId);\n this.email = text(AuthioClaimTypes.Email);\n this.emailVerified = toBoolean(claims[AuthioClaimTypes.EmailVerified]);\n this.name = text(AuthioClaimTypes.Name);\n this.preferredUsername = text(AuthioClaimTypes.PreferredUsername);\n this.credentialType = text(AuthioClaimTypes.CredentialType);\n this.credentialId = text(AuthioClaimTypes.CredentialId);\n this.authTime = toSeconds(claims[AuthioClaimTypes.AuthTime]);\n this.kind =\n this.credentialType === \"client_consumer\"\n ? \"consumer\"\n : this.credentialType === \"account_secret\"\n ? \"account_credential\"\n : this.authTime !== undefined\n ? \"user\"\n : \"client\";\n\n const machine = this.kind === \"consumer\" || this.kind === \"account_credential\";\n\n const keyIntrospected = source === \"introspection\" && this.kind === \"consumer\" && claims[AuthioClaimTypes.Expiration] === undefined;\n\n this.credentialForm = machine\n ? ((text(AuthioClaimTypes.ActorType) as AuthioCredentialForm | undefined) ?? (keyIntrospected ? \"consumer_api_key\" : \"client_secret\"))\n : undefined;\n this.consumerName = this.kind === \"consumer\" ? text(AuthioClaimTypes.ConsumerName) : undefined;\n this.credentialName = text(AuthioClaimTypes.CredentialName);\n this.ownerUserId = text(AuthioClaimTypes.OwnerUserId);\n this.ownerUsername =\n text(AuthioClaimTypes.OwnerUsername) ?? (this.kind === \"account_credential\" ? text(AuthioClaimTypes.ConsumerName) : undefined);\n this.credentialRealm = text(AuthioClaimTypes.CredentialRealm);\n this.credentialClient = text(AuthioClaimTypes.CredentialClient);\n this.delegated = this.actor?.clientId !== undefined;\n this.actorChain = Object.freeze(chainOf(this.actor));\n this.impersonated = !this.delegated && this.actor?.subject !== undefined;\n this.impersonator = this.impersonated ? Object.freeze({ subject: this.actor!.subject!, name: this.actor!.name }) : undefined;\n\n Object.defineProperty(this, \"token\", { value: token, enumerable: false });\n }\n\n /**\n * Reads the caller from an introspection answer: `client_id` becomes `azp`, `username` becomes\n * `preferred_username`, and `token_type` becomes `typ` unless it is `api_key` (a consumer's API key).\n */\n static fromIntrospection(result: AuthioIntrospectionResult, settings: AuthioUserClaimSettings = {}, token?: string): AuthioUser {\n return new AuthioUser(claimsOfIntrospection(result), settings, token, \"introspection\");\n }\n\n /** Whether the scope was granted. */\n hasScope(scope: string): boolean {\n return this.scopes.includes(scope);\n }\n\n /**\n * Whether the user holds the role. Without sources, from any `*_resource_access` claim or a flat role claim; with\n * sources, only from those `*_resource_access` claims.\n */\n hasRole(role: string, options: { sources?: readonly AuthioResourceAccessSource[] } = {}): boolean {\n if (!role) return false;\n if (options.sources && options.sources.length > 0) return this.resourceAccess.hasRole(role, options.sources);\n\n const wanted = role.toLowerCase();\n\n return this.resourceAccess.hasRole(role) || this.flatRoles.some((name) => name.toLowerCase() === wanted);\n }\n\n /**\n * Authio's grant rule: whether a role (from any source, or only from the given ones) allows `method` on\n * `resource`. Case-insensitive.\n */\n hasPermission(resource: string, method: string, options: { sources?: readonly AuthioResourceAccessSource[] } = {}): boolean {\n return this.resourceAccess.grants(resource, method, options.sources);\n }\n\n /** Whether the user is in the group (exact match). */\n hasGroup(group: string): boolean {\n return this.groups.includes(group);\n }\n\n /**\n * Whether the claim is present (not `null`), and, given values, whether it holds one of them (exact match; an\n * array claim matches when any item does).\n */\n hasClaim(type: string, ...values: string[]): boolean {\n const present = this.claimValues(type);\n\n return values.length === 0 ? present.length > 0 : present.some((value) => values.includes(value));\n }\n\n /**\n * The claim's values as text: one for a scalar, one per item for an array, JSON text for an object.\n */\n claimValues(type: string): string[] {\n return valuesOf(this.claims[type]);\n }\n\n /** Every member but the raw token. */\n toJSON(): Record<string, unknown> {\n const { flatRoles: _flatRoles, ...members } = this as unknown as Record<string, unknown>;\n\n return { ...members, resourceAccess: this.resourceAccess.entries };\n }\n}\n\n/**\n * The claims an introspection answer stands for, named as in a JWT.\n *\n * @internal\n */\nexport function claimsOfIntrospection(result: AuthioIntrospectionResult): Record<string, unknown> {\n const { active: _active, token_type: tokenType, username, ...members } = result;\n const claims: Record<string, unknown> = { ...members };\n\n if (typeof tokenType === \"string\" && claims.typ === undefined && tokenType.toLowerCase() !== \"api_key\") claims.typ = tokenType;\n if (typeof username === \"string\" && claims.preferred_username === undefined) claims.preferred_username = username;\n if (typeof result.client_id === \"string\" && claims.azp === undefined) claims.azp = result.client_id;\n\n return claims;\n}\n\n/**\n * Whether an introspection `token_type` stands for an access token.\n *\n * @internal\n */\nexport function isAccessTokenType(type: string): boolean {\n return accessTokenTypes.has(type.toLowerCase());\n}\n\n/**\n * A claim's values as text.\n *\n * @internal\n */\nexport function valuesOf(value: unknown): string[] {\n if (value === undefined || value === null) return [];\n if (Array.isArray(value)) return value.flatMap((item) => (item === null || item === undefined ? [] : [toText(item)]));\n\n if (typeof value === \"string\" && value.startsWith(\"[\")) {\n try {\n const parsed = JSON.parse(value) as unknown;\n\n if (Array.isArray(parsed)) return valuesOf(parsed);\n } catch {\n return [value];\n }\n }\n\n return [toText(value)];\n}\n\nfunction toText(value: unknown): string {\n return typeof value === \"string\" ? value : typeof value === \"object\" ? JSON.stringify(value) : String(value);\n}\n\nfunction readActor(value: unknown, depth = 0): AuthioActor | undefined {\n let actor = value;\n\n if (typeof actor === \"string\") {\n try {\n actor = JSON.parse(actor);\n } catch {\n return undefined;\n }\n }\n\n if (!actor || typeof actor !== \"object\" || Array.isArray(actor) || depth > 16) return undefined;\n\n const record = actor as Record<string, unknown>;\n\n return Object.freeze({\n clientId: typeof record.client_id === \"string\" && record.client_id ? record.client_id : undefined,\n subject: typeof record.sub === \"string\" && record.sub ? record.sub : undefined,\n name: typeof record.name === \"string\" && record.name ? record.name : undefined,\n actor: readActor(record.act, depth + 1),\n });\n}\n\nfunction chainOf(actor: AuthioActor | undefined): string[] {\n const chain: string[] = [];\n\n for (let current = actor; current; current = current.actor) if (current.clientId) chain.push(current.clientId);\n\n return chain;\n}\n\nfunction toSeconds(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value) : undefined;\n}\n\nfunction toDate(value: unknown): Date | undefined {\n const seconds = typeof value === \"number\" ? value : typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value) : undefined;\n\n return seconds === undefined ? undefined : new Date(seconds * 1000);\n}\n\nfunction toBoolean(value: unknown): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n\n return undefined;\n}\n\nfunction distinct(values: readonly string[]): string[] {\n return [...new Set(values)];\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","import { systemClock, type AuthioCallerKind, type AuthioClock, type AuthioResourceAccessSource } from \"@hyper.authio/client\";\nimport type { AuthioUser } from \"./user.js\";\n\n/**\n * How several required values combine.\n */\nexport type AuthioMatch = \"any\" | \"all\";\n\n/**\n * Why a rule refused the caller.\n */\nexport interface AuthioRuleFailure {\n /** What is missing, in words. */\n readonly message: string;\n /**\n * The RFC 6750 / RFC 9470 error to put in `WWW-Authenticate`: `insufficient_scope` for scopes,\n * `insufficient_user_authentication` for `acr`/`amr`, none otherwise.\n */\n readonly error?: \"insufficient_scope\" | \"insufficient_user_authentication\";\n /** The required scopes, for `insufficient_scope`. */\n readonly scope?: string;\n /** The context classes to ask for again, for `insufficient_user_authentication` (RFC 9470 `acr_values`). */\n readonly acrValues?: string;\n /** How old the sign-in may be, in seconds, for `insufficient_user_authentication` (RFC 9470 `max_age`). */\n readonly maxAge?: number;\n}\n\n/**\n * A condition on the caller.\n */\nexport interface AuthioRule {\n /** What the rule requires, for logs. */\n readonly description: string;\n /** `undefined` when the caller satisfies the rule, else why not. */\n check(user: AuthioUser): AuthioRuleFailure | undefined;\n}\n\n/**\n * Checks every rule. On refusal the message joins every rule's. When a rule other than a step-up fails (a scope, role,\n * permission, group, claim, organization, client or caller kind), no stronger sign-in can satisfy the request: the\n * refusal is a `403`, with the first such rule's error (`insufficient_scope`) or none, and never asks for a step-up.\n * Only when every failing rule asks for a stronger or more recent sign-in is the error `insufficient_user_authentication`,\n * with the strongest `acr_values` and the shortest `max_age` they ask for.\n */\nexport function authorize(user: AuthioUser, ...rules: AuthioRule[]): AuthioRuleFailure | undefined {\n const failures = rules.map((rule) => rule.check(user)).filter((failure): failure is AuthioRuleFailure => failure !== undefined);\n\n if (failures.length === 0) return undefined;\n\n const others = failures.filter((failure) => failure.error !== \"insufficient_user_authentication\");\n const stepUps = others.length === 0 ? failures : [];\n const bearer = stepUps[0] ?? others.find((failure) => failure.error);\n const acrValues = strongestAcr(stepUps.map((failure) => failure.acrValues));\n const maxAges = stepUps.map((failure) => failure.maxAge).filter((value): value is number => value !== undefined);\n\n return {\n message: failures.map((failure) => failure.message).join(\" \"),\n ...(bearer?.error ? { error: bearer.error } : {}),\n ...(bearer?.scope ? { scope: bearer.scope } : {}),\n ...(acrValues ? { acrValues } : {}),\n ...(maxAges.length > 0 ? { maxAge: Math.min(...maxAges) } : {}),\n };\n}\n\n/**\n * Requires granted scopes.\n */\nexport function requireScope(scopes: string | readonly string[], match: AuthioMatch = \"any\"): AuthioRule {\n const required = listOf(scopes, \"scope\");\n\n return {\n description: `Authio scope (${match}): ${required.join(\" \")}`,\n check: (user) =>\n satisfies(required, match, (scope) => user.hasScope(scope))\n ? undefined\n : {\n message: `The token lacks the required scope (${match}): ${required.join(\" \")}.`,\n error: \"insufficient_scope\",\n scope: required.join(\" \"),\n },\n };\n}\n\n/**\n * Requires roles, from any source or only from the given `*_resource_access` claims.\n */\nexport function requireRole(\n roles: string | readonly string[],\n options: { match?: AuthioMatch; sources?: readonly AuthioResourceAccessSource[] } = {},\n): AuthioRule {\n const required = listOf(roles, \"role\");\n const match = options.match ?? \"any\";\n const from = describeSources(options.sources);\n\n return {\n description: `Authio role (${match}): ${required.join(\", \")}${from}`,\n check: (user) =>\n satisfies(required, match, (role) => user.hasRole(role, { sources: options.sources }))\n ? undefined\n : { message: `The caller lacks the required role (${match}): ${required.join(\", \")}${from}.` },\n };\n}\n\n/**\n * Requires a permission (`method` on `resource`), granted by a role from any source or only from the given ones.\n */\nexport function requirePermission(resource: string, method: string, options: { sources?: readonly AuthioResourceAccessSource[] } = {}): AuthioRule {\n if (!resource?.trim() || !method?.trim()) throw new TypeError(\"A permission needs a resource and a method.\");\n\n const from = describeSources(options.sources);\n\n return {\n description: `Authio permission: ${resource}:${method}${from}`,\n check: (user) =>\n user.hasPermission(resource, method, { sources: options.sources }) ? undefined : { message: `The caller lacks the permission ${resource}:${method}${from}.` },\n };\n}\n\n/**\n * Requires groups, read from the group claims (a claim mapper with the Group source).\n */\nexport function requireGroup(groups: string | readonly string[], match: AuthioMatch = \"any\"): AuthioRule {\n const required = listOf(groups, \"group\");\n\n return {\n description: `Authio group (${match}): ${required.join(\", \")}`,\n check: (user) =>\n satisfies(required, match, (group) => user.hasGroup(group))\n ? undefined\n : { message: `The caller is not in the required group (${match}): ${required.join(\", \")}.` },\n };\n}\n\n/**\n * Requires a claim: present, or holding one of the given values. Fits claim-mapper claims, the user's own claims and\n * any other claim Authio issues.\n */\nexport function requireClaim(type: string, ...values: string[]): AuthioRule {\n if (!type?.trim()) throw new TypeError(\"A claim rule needs a claim type.\");\n\n return {\n description: values.length === 0 ? `Authio claim: ${type}` : `Authio claim: ${type} in ${values.join(\", \")}`,\n check: (user) =>\n user.hasClaim(type, ...values)\n ? undefined\n : { message: values.length === 0 ? `The token lacks the claim ${type}.` : `The token's claim ${type} is not one of: ${values.join(\", \")}.` },\n };\n}\n\n/**\n * Requires an organization context, or a given organization (alias or id, case-insensitive).\n */\nexport function requireOrganization(organization?: string): AuthioRule {\n const wanted = organization?.trim() || undefined;\n\n return {\n description: `Authio organization: ${wanted ?? \"any\"}`,\n check: (user) => {\n const satisfied =\n !!user.organizationId &&\n (!wanted ||\n user.organizationAlias?.toLowerCase() === wanted.toLowerCase() ||\n user.organizationId.toLowerCase() === wanted.toLowerCase());\n\n return satisfied\n ? undefined\n : { message: wanted ? `The token is not in the organization ${wanted}.` : \"The token has no organization context.\" };\n },\n };\n}\n\n/**\n * Requires a minimum authentication level (`acr`): 1 one factor, 2 several, 3 one of them phishing-resistant. The\n * refusal asks for that level again (`acr_values`), and for a sign-in at most `maxAge` seconds old when given.\n */\nexport function requireAuthenticationLevel(minimumLevel: number, options: { maxAge?: number; clock?: AuthioClock } = {}): AuthioRule {\n if (!Number.isInteger(minimumLevel) || minimumLevel < 0) throw new RangeError(\"The minimum level must be a non-negative integer.\");\n\n const recency = options.maxAge === undefined ? undefined : requireRecentAuthentication(options.maxAge, { clock: options.clock });\n\n return {\n description: `Authio authentication level >= ${minimumLevel}${recency ? `, ${recency.description}` : \"\"}`,\n check: (user) => {\n const levelMet = user.authenticationLevel !== undefined && user.authenticationLevel >= minimumLevel;\n const recent = recency?.check(user);\n\n if (levelMet && !recent) return undefined;\n\n return {\n message: [levelMet ? undefined : `The authentication level must be at least ${minimumLevel}.`, recent?.message].filter(Boolean).join(\" \"),\n error: \"insufficient_user_authentication\",\n acrValues: String(minimumLevel),\n ...(options.maxAge !== undefined ? { maxAge: options.maxAge } : {}),\n };\n },\n };\n}\n\n/**\n * The context class each authentication method implies when an API asks for it again (Authio's `acr` levels).\n */\nconst methodLevels: Readonly<Record<string, string>> = { mfa: \"2\", otp: \"2\", mca: \"2\", sms: \"2\", swk: \"3\", hwk: \"3\" };\n\n/**\n * Requires authentication methods (`amr`, case-insensitive), such as `otp`, `swk` or `fed`. The refusal asks for the\n * context class the methods imply (`2` for `mfa`/`otp`/`mca`, `3` for `swk`/`hwk`), or for `acrValues` when given.\n */\nexport function requireAuthenticationMethod(\n methods: string | readonly string[],\n match: AuthioMatch = \"any\",\n options: { acrValues?: string } = {},\n): AuthioRule {\n const required = listOf(methods, \"authentication method\");\n const levels = required.map((method) => methodLevels[method.toLowerCase()]).filter((level): level is string => level !== undefined);\n const acrValues = options.acrValues ?? (levels.length === 0 ? undefined : match === \"all\" ? strongestAcr(levels) : weakestAcr(levels));\n\n return {\n description: `Authio authentication method (${match}): ${required.join(\", \")}`,\n check: (user) => {\n const used = user.authenticationMethods.map((method) => method.toLowerCase());\n\n return satisfies(required, match, (method) => used.includes(method.toLowerCase()))\n ? undefined\n : {\n message: `The user must authenticate with (${match}): ${required.join(\", \")}.`,\n error: \"insufficient_user_authentication\",\n ...(acrValues ? { acrValues } : {}),\n };\n },\n };\n}\n\n/**\n * Requires a sign-in at most `maxAge` seconds old (`auth_time`); the refusal asks for it with `max_age` (RFC 9470).\n */\nexport function requireRecentAuthentication(maxAge: number, options: { clock?: AuthioClock } = {}): AuthioRule {\n if (!Number.isInteger(maxAge) || maxAge < 0) throw new RangeError(\"maxAge must be a non-negative whole number of seconds.\");\n\n const clock = options.clock ?? systemClock;\n\n return {\n description: `Authio sign-in at most ${maxAge} s old`,\n check: (user) =>\n user.authTime !== undefined && clock.now() - user.authTime * 1000 <= maxAge * 1000\n ? undefined\n : {\n message:\n user.authTime === undefined\n ? `The token carries no sign-in time; a sign-in at most ${maxAge} seconds old is required.`\n : `The sign-in must be at most ${maxAge} seconds old.`,\n error: \"insufficient_user_authentication\",\n maxAge,\n },\n };\n}\n\n/**\n * Requires the caller to be of one of the kinds: `user`, `client`, `consumer`, `account_credential`.\n */\nexport function requireCallerKind(kinds: AuthioCallerKind | readonly AuthioCallerKind[]): AuthioRule {\n const required = listOf(kinds, \"caller kind\") as AuthioCallerKind[];\n\n return {\n description: `Authio caller kind: ${required.join(\", \")}`,\n check: (user) => (required.includes(user.kind) ? undefined : { message: `The caller is a ${user.kind}, not one of: ${required.join(\", \")}.` }),\n };\n}\n\n/**\n * Requires the token to have been issued to one of the clients (`client_id`, else `azp`).\n */\nexport function requireClient(clientIds: string | readonly string[]): AuthioRule {\n const required = listOf(clientIds, \"client id\");\n\n return {\n description: `Authio client: ${required.join(\", \")}`,\n check: (user) =>\n user.clientId !== undefined && required.includes(user.clientId)\n ? undefined\n : { message: `The token was not issued to an accepted client (${required.join(\", \")}).` },\n };\n}\n\n/**\n * Requires every rule.\n */\nexport function allOf(...rules: AuthioRule[]): AuthioRule {\n return {\n description: rules.map((rule) => rule.description).join(\" and \"),\n check: (user) => authorize(user, ...rules),\n };\n}\n\n/**\n * Requires at least one rule; the refusal is the first rule's.\n */\nexport function anyOf(...rules: AuthioRule[]): AuthioRule {\n if (rules.length === 0) throw new TypeError(\"anyOf needs at least one rule.\");\n\n return {\n description: rules.map((rule) => rule.description).join(\" or \"),\n check: (user) => {\n const failures = rules.map((rule) => rule.check(user));\n\n return failures.some((failure) => failure === undefined) ? undefined : failures[0];\n },\n };\n}\n\nfunction listOf(values: string | readonly string[], name: string): string[] {\n const list = [...new Set((typeof values === \"string\" ? [values] : [...values]).filter((value) => value?.trim()))];\n\n if (list.length === 0) throw new TypeError(`At least one ${name} is required.`);\n\n return list;\n}\n\nfunction satisfies(required: readonly string[], match: AuthioMatch, holds: (value: string) => boolean): boolean {\n return match === \"all\" ? required.every(holds) : required.some(holds);\n}\n\nfunction strongestAcr(values: readonly (string | undefined)[]): string | undefined {\n return rankAcr(values, (left, right) => right - left);\n}\n\nfunction weakestAcr(values: readonly (string | undefined)[]): string | undefined {\n return rankAcr(values, (left, right) => left - right);\n}\n\nfunction rankAcr(values: readonly (string | undefined)[], order: (left: number, right: number) => number): string | undefined {\n const known = values.filter((value): value is string => !!value);\n const numeric = known.filter((value) => /^\\d+$/.test(value)).sort((left, right) => order(Number(left), Number(right)));\n\n return numeric[0] ?? known[0];\n}\n\nfunction describeSources(sources: readonly AuthioResourceAccessSource[] | undefined): string {\n return sources && sources.length > 0 ? ` from ${[...new Set(sources)].join(\", \")}` : \"\";\n}\n","import { AuthioError, type AuthioTokenFailure } from \"@hyper.authio/client\";\nimport type { AuthioRuleFailure } from \"./rules.js\";\n\n/**\n * The request carries no valid access token: answer `401` with `wwwAuthenticate`.\n */\nexport class AuthioBearerError extends AuthioError {\n readonly status = 401;\n /** `invalid_token`, or `undefined` when the request had no token at all (RFC 6750 §3.1). */\n readonly error: \"invalid_token\" | undefined;\n /** Why the token was refused, safe to send to the caller. */\n readonly description: string | undefined;\n /** Why the token was refused, as a stable code; `undefined` when there was no token or Authio could not be asked. */\n readonly reason: AuthioTokenFailure | \"inactive\" | \"unconfirmed\" | undefined;\n /** The API's protected resource metadata URL (RFC 9728), sent as `resource_metadata` when configured. */\n readonly resourceMetadata: string | undefined;\n\n constructor(\n description: string | undefined,\n options: {\n error?: \"invalid_token\" | undefined;\n cause?: unknown;\n reason?: AuthioTokenFailure | \"inactive\" | \"unconfirmed\";\n resourceMetadata?: string;\n } = {},\n ) {\n super(description ?? \"A valid Authio access token is required.\", { cause: options.cause });\n this.error = \"error\" in options ? options.error : \"invalid_token\";\n this.description = description === undefined ? undefined : toHeaderText(description);\n this.reason = options.reason;\n this.resourceMetadata = options.resourceMetadata;\n }\n\n /** The same refusal, pointing at the API's protected resource metadata. */\n withResourceMetadata(resourceMetadata: string | undefined): AuthioBearerError {\n if (!resourceMetadata || resourceMetadata === this.resourceMetadata) return this;\n\n return new AuthioBearerError(this.description, { error: this.error, cause: this.cause, reason: this.reason, resourceMetadata });\n }\n\n /** The `WWW-Authenticate` value. */\n get wwwAuthenticate(): string {\n const parameters: string[] = [];\n\n if (this.error) parameters.push(`error=\"${this.error}\"`);\n if (this.error && this.description) parameters.push(`error_description=\"${this.description}\"`);\n if (this.resourceMetadata) parameters.push(`resource_metadata=\"${escapeQuoted(this.resourceMetadata)}\"`);\n\n return parameters.length === 0 ? \"Bearer\" : `Bearer ${parameters.join(\", \")}`;\n }\n}\n\n/**\n * A rule refused a caller whose token is valid. A refusal asking for a stronger or more recent sign-in\n * (`insufficient_user_authentication`) answers `401`, as RFC 9470 §3 has it, naming the protected resource metadata\n * (`resource_metadata`, RFC 9728 §5.1) when the API publishes it; every other refusal answers `403`, with\n * `wwwAuthenticate` when it is about scopes (`insufficient_scope`, RFC 6750 §3.1).\n */\nexport class AuthioForbiddenError extends AuthioError {\n /** `401` for a step-up (`insufficient_user_authentication`), `403` otherwise. */\n readonly status: 401 | 403;\n readonly failure: AuthioRuleFailure;\n /** The API's protected resource metadata URL (RFC 9728), sent as `resource_metadata` with a step-up `401`. */\n readonly resourceMetadata: string | undefined;\n\n constructor(failure: AuthioRuleFailure, options: { resourceMetadata?: string } = {}) {\n super(failure.message);\n this.failure = failure;\n this.status = failure.error === \"insufficient_user_authentication\" ? 401 : 403;\n this.resourceMetadata = options.resourceMetadata;\n }\n\n /** The same refusal, pointing at the API's protected resource metadata. */\n withResourceMetadata(resourceMetadata: string | undefined): AuthioForbiddenError {\n if (!resourceMetadata || resourceMetadata === this.resourceMetadata) return this;\n\n return new AuthioForbiddenError(this.failure, { resourceMetadata });\n }\n\n /**\n * The `WWW-Authenticate` value, or `undefined` when the refusal is not about scopes or the sign-in. A step-up `401`\n * carries `resource_metadata` when `resourceMetadata` is set.\n */\n get wwwAuthenticate(): string | undefined {\n const challenge = toForbiddenChallenge(this.failure);\n\n return challenge && this.status === 401 && this.resourceMetadata ? `${challenge}, resource_metadata=\"${escapeQuoted(this.resourceMetadata)}\"` : challenge;\n }\n}\n\n/**\n * The `WWW-Authenticate` value of a refusal: `insufficient_scope` (with `scope`) or `insufficient_user_authentication`\n * (with `acr_values` and `max_age`, RFC 9470).\n */\nexport function toForbiddenChallenge(failure: AuthioRuleFailure): string | undefined {\n if (!failure.error) return undefined;\n\n const parameters = [`error=\"${failure.error}\"`, `error_description=\"${escapeQuoted(toHeaderText(failure.message))}\"`];\n\n if (failure.scope) parameters.push(`scope=\"${escapeQuoted(failure.scope)}\"`);\n if (failure.acrValues) parameters.push(`acr_values=\"${escapeQuoted(failure.acrValues)}\"`);\n if (failure.maxAge !== undefined) parameters.push(`max_age=${failure.maxAge}`);\n\n return `Bearer ${parameters.join(\", \")}`;\n}\n\n/**\n * Problem details (RFC 9457) for a `401` or `403`, with the refusal's `status`: a step-up refusal is `401`\n * Unauthorized and carries `error`, `acr_values` and `max_age`.\n */\nexport function toProblemDetails(error: AuthioBearerError | AuthioForbiddenError): Record<string, unknown> {\n if (error instanceof AuthioBearerError)\n return {\n type: unauthorizedType,\n title: \"Unauthorized\",\n status: 401,\n detail: \"A valid Authio access token is required.\",\n };\n\n return {\n type: error.status === 401 ? unauthorizedType : \"https://tools.ietf.org/html/rfc9110#section-15.5.4\",\n title: error.status === 401 ? \"Unauthorized\" : \"Forbidden\",\n status: error.status,\n detail: error.failure.message || \"The caller is not allowed to access this resource.\",\n ...(error.failure.error ? { error: error.failure.error } : {}),\n ...(error.failure.scope ? { scope: error.failure.scope } : {}),\n ...(error.failure.acrValues ? { acr_values: error.failure.acrValues } : {}),\n ...(error.failure.maxAge !== undefined ? { max_age: error.failure.maxAge } : {}),\n };\n}\n\nconst unauthorizedType = \"https://tools.ietf.org/html/rfc9110#section-15.5.2\";\n\n/**\n * Keeps only the characters RFC 6750 §3 allows in an `error_description`.\n *\n * @internal\n */\nexport function toHeaderText(text: string): string {\n return [...text].map((character) => (character >= \" \" && character <= \"~\" && character !== '\"' && character !== \"\\\\\" ? character : \"?\")).join(\"\");\n}\n\nfunction escapeQuoted(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n","import { AuthioConfigurationError, AuthioDefaults, resolveIssuer, type AuthioConnectionOptions } from \"@hyper.authio/client\";\n\n/**\n * What an API publishes about itself as a protected resource (RFC 9728).\n */\nexport interface AuthioProtectedResourceMetadataOptions extends Pick<AuthioConnectionOptions, \"issuer\" | \"authority\" | \"realm\"> {\n /** The API's resource identifier (RFC 8707), such as `https://orders.example.com/api`. Required. */\n resource: string;\n /** Scopes a client can ask for to call the API. */\n scopesSupported?: readonly string[];\n /** A name to show to people. */\n resourceName?: string;\n /** A page documenting the API. */\n resourceDocumentation?: string;\n /** Further members, sent as given. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * The protected resource metadata document (RFC 9728 §2).\n */\nexport interface AuthioProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n bearer_methods_supported: string[];\n scopes_supported?: string[];\n resource_name?: string;\n resource_documentation?: string;\n [member: string]: unknown;\n}\n\n/**\n * Where a resource's metadata is published: `{origin}/.well-known/oauth-protected-resource{path}` (RFC 9728 §3.1),\n * the path being the resource's own, without a trailing slash.\n */\nexport function protectedResourceMetadataUrl(resource: string): string {\n const url = parseResource(resource);\n const path = url.pathname.replace(/\\/+$/, \"\");\n\n return `${url.origin}${AuthioDefaults.ProtectedResourceMetadataPath}${path}`;\n}\n\n/**\n * The path a resource's metadata is served at on the API itself: `/.well-known/oauth-protected-resource{path}`.\n */\nexport function protectedResourceMetadataPath(resource: string): string {\n return new URL(protectedResourceMetadataUrl(resource)).pathname;\n}\n\n/**\n * Builds the API's protected resource metadata: the resource, the realm's issuer as its authorization server, bearer\n * tokens in the `Authorization` header, and the optional scopes, name and documentation.\n */\nexport function createProtectedResourceMetadata(options: AuthioProtectedResourceMetadataOptions): AuthioProtectedResourceMetadata {\n parseResource(options.resource);\n\n const document: AuthioProtectedResourceMetadata = {\n ...options.extra,\n resource: options.resource,\n authorization_servers: [resolveIssuer(options)],\n bearer_methods_supported: [\"header\"],\n };\n\n if (options.scopesSupported && options.scopesSupported.length > 0) document.scopes_supported = [...options.scopesSupported];\n if (options.resourceName) document.resource_name = options.resourceName;\n if (options.resourceDocumentation) document.resource_documentation = options.resourceDocumentation;\n\n return document;\n}\n\nfunction parseResource(resource: string): URL {\n let url: URL;\n\n try {\n url = new URL(resource);\n } catch (error) {\n throw new AuthioConfigurationError(`The resource '${resource}' is not an absolute URL.`, { cause: error });\n }\n\n if (url.hash) throw new AuthioConfigurationError(`The resource '${resource}' must not carry a fragment (RFC 8707).`);\n\n return url;\n}\n","import {\n AuthioAsymmetricAlgorithms,\n AuthioConfigurationError,\n AuthioHmacAlgorithms,\n AuthioTokenTypes,\n AuthioTokenValidationError,\n createAuthioClient,\n createAuthioDiscoveryClient,\n createAuthioSigningKeys,\n createAuthioTokenDecrypter,\n encryptionKeyFromFile,\n isAuthioTokenEncrypted,\n requireHmacSecretLength,\n resolveConnection,\n seconds,\n requireAccessTokenType,\n verifyAuthioJwt,\n withClientSecret,\n type AuthioClient,\n type AuthioClientOptions,\n type AuthioConnection,\n type AuthioConnectionOptions,\n type AuthioDiscoveryClient,\n type AuthioEncryptionKeySource,\n type AuthioIntrospectionResult,\n} from \"@hyper.authio/client\";\nimport { decodeProtectedHeader, type JWTPayload } from \"jose\";\nimport { AuthioBearerError } from \"./errors.js\";\nimport { protectedResourceMetadataUrl } from \"./resource-metadata.js\";\nimport { AuthioUser, claimsOfIntrospection, isAccessTokenType, type AuthioUserClaimSettings } from \"./user.js\";\n\n/**\n * Whether and how Authio's introspection endpoint takes part in validating a token.\n *\n * - `none`: the JWT is validated locally (signature, issuer, audience, lifetime) and the caller is read from it alone.\n * Fastest; a revoked token stays valid until it expires. A lightweight access token carries no roles, permissions,\n * plan, profile or email, so it needs one of the modes below.\n * - `activeCheck`: validated locally, then confirmed active by introspection (cached per `jti`). The caller is read\n * from the token, and the introspection answer adds the claims the token does not carry: the answer has every claim\n * of the complete token, so a lightweight access token's roles and permissions are read too. A claim the token\n * carries keeps the token's value, which its signature vouches for (the answer names a single `aud`).\n * - `introspectionOnly`: introspection alone, for opaque (reference) tokens, or encrypted ones without the key. The\n * caller is read from the answer.\n */\nexport type AuthioIntrospectionMode = \"none\" | \"activeCheck\" | \"introspectionOnly\";\n\n/**\n * How an API validates Authio access tokens.\n */\nexport interface AuthioVerifierOptions extends AuthioConnectionOptions, AuthioUserClaimSettings {\n /** The audiences this API accepts: its resource identifier (RFC 8707) or client id. Required unless `resource` is set. */\n audiences?: string | readonly string[];\n /**\n * The API's own resource identifier (RFC 8707), such as `https://orders.example.com`. Added to `audiences`, and\n * the `resource` of its protected resource metadata (RFC 9728).\n */\n resource?: string;\n /**\n * Points `401` challenges at the API's protected resource metadata (RFC 9728) with `resource_metadata`: `true`\n * for `{origin of resource}/.well-known/oauth-protected-resource{path of resource}`, or the URL itself. Off by default.\n */\n resourceMetadata?: boolean | string;\n /** Scopes every request must carry (all of them); `authioBearer` answers `403 insufficient_scope` otherwise. */\n requiredScopes?: readonly string[];\n /** Defaults to `none`. */\n introspection?: AuthioIntrospectionMode;\n /**\n * The API's confidential client, for introspection: a client already created, or its options (issuer settings are\n * taken from these options when absent). It must be the client the resource server names as its introspection\n * client, since Authio answers introspection according to who asks.\n */\n client?: AuthioClient | Omit<AuthioClientOptions, keyof AuthioConnectionOptions>;\n /** Seconds an active introspection answer is kept (never past the token's expiry). Defaults to 30. */\n introspectionCacheDuration?: number;\n /** Seconds of clock skew tolerated on `exp` and `nbf`. Defaults to 30. */\n clockSkew?: number;\n /**\n * The algorithm (or algorithms) access tokens are signed with, as the client registered in Authio signs them:\n * RS/PS/ES 256/384/512, or HS256/384/512 verified with the `clientSecret` of `client` (its UTF-8 octets, at least\n * 32, 48 or 64 bytes as RFC 7518 §3.2 asks). Only the client's own API holds that secret, so only it validates an HS*\n * token locally; any other API validates such tokens with introspection. Left out, the asymmetric algorithms of the\n * realm's keys are accepted, and never HS*.\n */\n accessTokenSignedResponseAlg?: string | readonly string[];\n /**\n * Refuses a token whose `typ` claim is present and not `Bearer` (an ID token, for one). Defaults to `true`. A JWT\n * whose header `typ` is not `at+jwt` (RFC 9068 §4) is refused whatever this says.\n */\n rejectNonAccessTokens?: boolean;\n /**\n * The private half of the encryption key Authio encrypts this API's access tokens to (the resource server's or its\n * client's), so encrypted tokens are decrypted and validated locally (RSA-OAEP, RSA-OAEP-256).\n */\n clientEncryptionKey?: AuthioEncryptionKeySource;\n /** A PEM or JWK file holding `clientEncryptionKey` (Node only). */\n clientEncryptionKeyPath?: string;\n /**\n * The key management algorithms (`alg`) decrypted. Defaults to RSA-OAEP and RSA-OAEP-256; RSA1_5 cannot be listed,\n * because Node 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 /** Accepted for parity with the other Authio SDKs; RSA1_5 stays refused, because Node cannot decrypt it. */\n allowLegacyEncryptionAlgorithms?: boolean;\n}\n\n/**\n * Validates Authio access tokens and reads the caller.\n */\nexport interface AuthioVerifier {\n /** The connection settings. */\n readonly connection: AuthioConnection;\n /** The discovery document. */\n readonly discovery: AuthioDiscoveryClient;\n /** The accepted audiences. */\n readonly audiences: readonly string[];\n /** The API's resource identifier, when configured. */\n readonly resource: string | undefined;\n /** The protected resource metadata URL sent in challenges, when turned on. */\n readonly resourceMetadataUrl: string | undefined;\n /** Scopes every request must carry. */\n readonly requiredScopes: readonly string[];\n /** The introspection mode. */\n readonly introspection: AuthioIntrospectionMode;\n /** The client used for introspection, when there is one. */\n readonly client: AuthioClient | undefined;\n /**\n * Validates a token and reads the caller.\n *\n * @throws AuthioBearerError when the token is not valid for this API.\n */\n verify(token: string, signal?: AbortSignal): Promise<AuthioUser>;\n /**\n * Validates the token of an `Authorization: Bearer` header.\n *\n * @throws AuthioBearerError without an error code when there is no bearer token, with `invalid_token` when it is\n * not valid.\n */\n verifyAuthorizationHeader(header: string | null | undefined, signal?: AbortSignal): Promise<AuthioUser>;\n}\n\n/**\n * Error descriptions of the refusals the SDK makes itself.\n */\nexport const AuthioBearerErrorDescriptions = {\n Inactive:\n \"Authio reports the token as not active to this API's client. It was revoked or has expired or its session ended; or this API's client is not the introspection client of the resource server the token is for.\",\n Unconfirmed: \"Authio could not be reached to confirm that the token is active.\",\n Empty: \"The token is empty.\",\n Encrypted: \"The token is encrypted; set clientEncryptionKey to decrypt it, or validate it with introspection ('introspectionOnly').\",\n SigningKeysUnavailable: \"Authio could not be reached to read its signing keys.\",\n Symmetric:\n \"The token is signed with the client's secret (HS*): set accessTokenSignedResponseAlg and the client's clientSecret to validate it locally, or validate it with introspection ('introspectionOnly').\",\n} as const;\n\nconst maxCachedAnswers = 10_000;\n\n/**\n * Creates a token verifier.\n *\n * @throws AuthioConfigurationError when no audience is given, or introspection is asked for without a client.\n */\nexport function createAuthioVerifier(options: AuthioVerifierOptions): AuthioVerifier {\n const resource = options.resource?.trim() || undefined;\n const given = typeof options.audiences === \"string\" ? [options.audiences] : [...(options.audiences ?? [])];\n const audiences = [...new Set([...given, ...(resource ? [resource] : [])].filter((value) => value?.trim()))];\n\n if (audiences.length === 0)\n throw new AuthioConfigurationError(\"The Authio verifier needs at least one audience: the API's resource identifier or client id.\");\n\n const connection = resolveConnection(options);\n const discovery = createAuthioDiscoveryClient(connection);\n const introspection = options.introspection ?? \"none\";\n const client = resolveClient(options);\n\n if (introspection !== \"none\" && !client)\n throw new AuthioConfigurationError(\n `Authio introspection ('${introspection}') needs the API's confidential client: pass options.client with its clientId and clientSecret or private key.`,\n );\n\n const resourceMetadataUrl = resolveResourceMetadata(options.resourceMetadata, resource);\n const cacheDurationMs = seconds(options.introspectionCacheDuration, 30, \"introspectionCacheDuration\");\n const clockSkew = seconds(options.clockSkew, 30, \"clockSkew\") / 1000;\n const algorithms = resolveAccessTokenAlgorithms(options.accessTokenSignedResponseAlg);\n const symmetric = algorithms?.filter((algorithm) => (AuthioHmacAlgorithms as readonly string[]).includes(algorithm)) ?? [];\n const clientSecret = symmetric.length > 0 ? resolveClientSecret(options, symmetric) : undefined;\n const rejectNonAccessTokens = options.rejectNonAccessTokens ?? true;\n const claimSettings: AuthioUserClaimSettings = { roleClaims: options.roleClaims, groupClaims: options.groupClaims };\n const cache = new Map<string, { result: AuthioIntrospectionResult; until: number }>();\n const signingKeys = createAuthioSigningKeys(connection, discovery);\n const encryptionKey =\n options.clientEncryptionKey ?? (options.clientEncryptionKeyPath ? encryptionKeyFromFile(options.clientEncryptionKeyPath) : undefined);\n const decrypt =\n encryptionKey === undefined\n ? undefined\n : createAuthioTokenDecrypter(encryptionKey, {\n setting: options.clientEncryptionKey === undefined ? \"clientEncryptionKeyPath\" : \"clientEncryptionKey\",\n allowLegacyEncryptionAlgorithms: options.allowLegacyEncryptionAlgorithms,\n encryptionAlgorithms: options.encryptionAlgorithms,\n encryptionMethods: options.encryptionMethods,\n });\n const requiredScopes = Object.freeze([...new Set((options.requiredScopes ?? []).filter((scope) => scope?.trim()))]);\n\n const introspect = async (token: string, key: string, signal?: AbortSignal): Promise<AuthioIntrospectionResult | undefined> => {\n const now = connection.clock.now();\n const cached = cache.get(key);\n\n if (cached && cached.until > now) return cached.result;\n\n cache.delete(key);\n\n const result = await client!.introspect(token, { tokenTypeHint: AuthioTokenTypes.AccessToken, signal });\n\n if (!result.active) return undefined;\n\n const until = Math.min(now + cacheDurationMs, typeof result.exp === \"number\" ? result.exp * 1000 : Number.POSITIVE_INFINITY);\n\n if (until > now) {\n if (cache.size >= maxCachedAnswers) cache.delete(cache.keys().next().value!);\n cache.set(key, { result, until });\n }\n\n return result;\n };\n\n const verifyJwt = async (token: string, signal?: AbortSignal): Promise<AuthioUser> => {\n let signed = token;\n\n if (isAuthioTokenEncrypted(token)) {\n if (!decrypt) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Encrypted, { reason: \"decryption_failed\" });\n\n try {\n signed = await decrypt(token);\n } catch (error) {\n if (error instanceof AuthioTokenValidationError) throw new AuthioBearerError(error.message, { cause: error, reason: error.reason });\n throw error;\n }\n }\n\n let keySet: Awaited<ReturnType<typeof signingKeys>>;\n\n try {\n keySet = withClientSecret(await signingKeys(signal), clientSecret);\n } catch (error) {\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.SigningKeysUnavailable, { cause: error, reason: \"signing_keys_unavailable\" });\n }\n\n let payload: JWTPayload;\n\n try {\n let header: Record<string, unknown>;\n\n ({ payload, header } = await verifyAuthioJwt(signed, keySet, {\n issuer: connection.issuer,\n audiences,\n algorithms,\n clockSkew,\n now: connection.clock.now(),\n }));\n\n requireAccessTokenType(header);\n } catch (error) {\n if (error instanceof AuthioTokenValidationError && error.reason === \"invalid_algorithm\" && symmetric.length === 0 && isSymmetricToken(signed))\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.Symmetric, { cause: error, reason: error.reason });\n if (error instanceof AuthioTokenValidationError) throw new AuthioBearerError(error.message, { cause: error, reason: error.reason });\n throw error;\n }\n\n const type = typeof payload.typ === \"string\" ? payload.typ : undefined;\n\n if (rejectNonAccessTokens && type !== undefined && type.toLowerCase() !== \"bearer\")\n throw new AuthioBearerError(`Only access tokens are accepted; this token's typ is '${type}'.`, { reason: \"not_access_token\" });\n\n if (introspection !== \"activeCheck\") return new AuthioUser(payload, claimSettings, token);\n\n const answer = await confirmActive(token, payload, signal);\n\n return new AuthioUser({ ...claimsOfIntrospection(answer), ...payload }, claimSettings, token);\n };\n\n const confirmActive = async (token: string, payload: JWTPayload, signal?: AbortSignal): Promise<AuthioIntrospectionResult> => {\n const key = payload.jti ? `jti:${payload.jti}` : await keyForToken(token);\n let result: AuthioIntrospectionResult | undefined;\n\n try {\n result = await introspect(token, key, signal);\n } catch (error) {\n if (signal?.aborted) throw error;\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.Unconfirmed, { cause: error, reason: \"unconfirmed\" });\n }\n\n if (!result) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Inactive, { reason: \"inactive\" });\n\n return result;\n };\n\n const verifyByIntrospection = async (token: string, signal?: AbortSignal): Promise<AuthioUser> => {\n let result: AuthioIntrospectionResult | undefined;\n\n try {\n result = await introspect(token, await keyForToken(token), signal);\n } catch (error) {\n if (signal?.aborted) throw error;\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.Unconfirmed, { cause: error, reason: \"unconfirmed\" });\n }\n\n if (!result) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Inactive, { reason: \"inactive\" });\n\n if (result.iss && result.iss !== connection.issuer) throw new AuthioBearerError(`The issuer '${result.iss}' is invalid`, { reason: \"invalid_issuer\" });\n\n const tokenAudiences = [result.aud ?? []].flat();\n\n if (!tokenAudiences.some((audience) => audiences.includes(audience)))\n throw new AuthioBearerError(describeAudience(tokenAudiences, audiences), { reason: \"invalid_audience\" });\n\n if (typeof result.exp === \"number\" && (result.exp + clockSkew) * 1000 <= connection.clock.now())\n throw new AuthioBearerError(`The token expired at '${new Date(result.exp * 1000).toISOString()}'`, { reason: \"expired\" });\n\n const claims = claimsOfIntrospection(result);\n const type = typeof claims.typ === \"string\" ? claims.typ : undefined;\n\n if (rejectNonAccessTokens && type !== undefined && !isAccessTokenType(type))\n throw new AuthioBearerError(`Only access tokens are accepted; this token's typ is '${type}'.`, { reason: \"not_access_token\" });\n\n return new AuthioUser(claims, claimSettings, token, \"introspection\");\n };\n\n const verify = async (token: string, signal?: AbortSignal): Promise<AuthioUser> => {\n try {\n if (typeof token !== \"string\" || !token.trim()) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Empty, { reason: \"malformed\" });\n\n return introspection === \"introspectionOnly\" ? await verifyByIntrospection(token.trim(), signal) : await verifyJwt(token.trim(), signal);\n } catch (error) {\n throw error instanceof AuthioBearerError ? error.withResourceMetadata(resourceMetadataUrl) : error;\n }\n };\n\n return {\n connection,\n discovery,\n audiences,\n resource,\n resourceMetadataUrl,\n requiredScopes,\n introspection,\n client,\n verify,\n async verifyAuthorizationHeader(header, signal) {\n const token = readBearerToken(header);\n\n if (token === undefined) throw new AuthioBearerError(undefined, { error: undefined, resourceMetadata: resourceMetadataUrl });\n\n return verify(token, signal);\n },\n };\n}\n\n/**\n * The token of an `Authorization: Bearer` header, or `undefined` when the header is absent or of another scheme.\n */\nexport function readBearerToken(header: string | null | undefined): string | undefined {\n const match = /^\\s*Bearer\\s+(\\S+)\\s*$/i.exec(header ?? \"\");\n\n return match?.[1];\n}\n\n/**\n * The cache key of a token: `token:` and the hex SHA-256 of the token.\n *\n * @internal\n */\nexport async function keyForToken(token: string): Promise<string> {\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(token)));\n\n return `token:${[...digest].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction resolveResourceMetadata(setting: boolean | string | undefined, resource: string | undefined): string | undefined {\n if (!setting) return undefined;\n if (typeof setting === \"string\") return setting;\n if (!resource)\n throw new AuthioConfigurationError(\"resourceMetadata: true needs the API's resource identifier: set options.resource, or pass the metadata URL.\");\n\n return protectedResourceMetadataUrl(resource);\n}\n\nfunction resolveAccessTokenAlgorithms(setting: string | readonly string[] | undefined): string[] | undefined {\n const algorithms = [...new Set((typeof setting === \"string\" ? [setting] : [...(setting ?? [])]).map((algorithm) => algorithm.trim()).filter(Boolean))];\n const known = [...AuthioAsymmetricAlgorithms, ...AuthioHmacAlgorithms] as readonly string[];\n\n for (const algorithm of algorithms)\n if (!known.includes(algorithm))\n throw new AuthioConfigurationError(`The Authio accessTokenSignedResponseAlg '${algorithm}' is not one of ${known.join(\", \")}.`);\n\n return algorithms.length > 0 ? algorithms : undefined;\n}\n\nfunction resolveClientSecret(options: AuthioVerifierOptions, symmetric: readonly string[]): () => Promise<string> {\n const given = options.client;\n const source = given && !isClient(given) ? given.clientSecret : undefined;\n\n if (!source)\n throw new AuthioConfigurationError(\n `accessTokenSignedResponseAlg ${symmetric.join(\", \")} is verified with the client secret: pass options.client as { clientId, clientSecret } (an AuthioClient does not expose its secret).`,\n );\n\n if (typeof source === \"string\") for (const algorithm of symmetric) requireHmacSecretLength(algorithm, new TextEncoder().encode(source).length);\n\n return async () => {\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}\n\nfunction isSymmetricToken(token: string): boolean {\n try {\n return (AuthioHmacAlgorithms as readonly string[]).includes(String(decodeProtectedHeader(token).alg));\n } catch {\n return false;\n }\n}\n\nfunction resolveClient(options: AuthioVerifierOptions): AuthioClient | undefined {\n const given = options.client;\n\n if (!given) return undefined;\n if (isClient(given)) return given;\n\n return createAuthioClient({\n ...given,\n issuer: options.issuer,\n authority: options.authority,\n realm: options.realm,\n requireHttps: options.requireHttps,\n discoveryCacheDuration: options.discoveryCacheDuration,\n httpTimeout: options.httpTimeout,\n fetch: options.fetch,\n clock: options.clock,\n } as AuthioClientOptions);\n}\n\nfunction isClient(value: unknown): value is AuthioClient {\n return typeof (value as AuthioClient).introspect === \"function\" && typeof (value as AuthioClient).tokens === \"object\";\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","import {\n AuthioConfigurationError,\n AuthioWebhookHeaders,\n systemClock,\n tryParseWebhookEvent,\n verifyWebhookSignature,\n type AuthioClock,\n type AuthioTypedWebhookEvent,\n type AuthioWebhookDataByType,\n type AuthioWebhookEvent,\n} from \"@hyper.authio/client\";\n\n/**\n * Remembers delivered event ids, so a redelivery is acknowledged without running the handlers twice.\n */\nexport interface AuthioWebhookDeduplicationStore {\n /** Records the id; `false` when it was already recorded within the window. */\n tryBegin(eventId: string, windowMs: number): boolean | Promise<boolean>;\n /** Forgets the id, after a handler failed, so the redelivery runs again. */\n release(eventId: string): void | Promise<void>;\n}\n\n/**\n * How webhook deliveries are received.\n */\nexport interface AuthioWebhookOptions {\n /** The webhook's secret. */\n secret?: string;\n /** Several secrets, while one is being rotated; a delivery signed with any of them is accepted. */\n secrets?: readonly string[];\n /** Seconds a signature's timestamp may differ from now. Defaults to 300. */\n tolerance?: number;\n /** `memory` (default), `none`, or a store shared between instances. */\n deduplication?: \"memory\" | \"none\" | AuthioWebhookDeduplicationStore;\n /** Seconds a delivered id is remembered. Defaults to 86400. */\n deduplicationWindow?: number;\n /** The largest body accepted, in bytes. Defaults to 1 MiB. */\n maxBodySize?: number;\n /** The clock. */\n clock?: AuthioClock;\n /** Called when a delivery is refused or a handler fails. */\n onError?: (error: unknown, context: { reason: string; eventId?: string; eventType?: string }) => void;\n}\n\n/**\n * A handler of one event type, or of every type.\n */\nexport type AuthioWebhookHandler<E extends AuthioWebhookEvent = AuthioWebhookEvent> = (event: E) => void | Promise<void>;\n\n/**\n * What to answer a delivery with.\n */\nexport interface AuthioWebhookOutcome {\n /** `200` handled, duplicate or ping; `400` unreadable; `401` bad or stale signature; `413` too large; `500` a handler failed. */\n readonly status: 200 | 400 | 401 | 413 | 500;\n /** Why, for logs. */\n readonly reason: \"handled\" | \"duplicate\" | \"unreadable\" | \"unsigned\" | \"too_large\" | \"handler_failed\";\n readonly event?: AuthioWebhookEvent;\n}\n\n/**\n * Receives Authio webhook deliveries: verifies, deduplicates and dispatches them.\n */\nexport interface AuthioWebhooks {\n /** Handles one event type, typed. */\n on<T extends keyof AuthioWebhookDataByType>(type: T, handler: AuthioWebhookHandler<AuthioTypedWebhookEvent<T>>): AuthioWebhooks;\n /** Handles another event type, or `*` for every type. */\n on(type: string, handler: AuthioWebhookHandler): AuthioWebhooks;\n /**\n * Handles a delivery: the body exactly as received and the request headers.\n */\n handle(delivery: { body: string | Uint8Array; headers: Headers | Record<string, string | string[] | undefined> }): Promise<AuthioWebhookOutcome>;\n /** The largest body accepted, in bytes. */\n readonly maxBodySize: number;\n}\n\n/**\n * Creates a webhook receiver. Handlers run in registration order; a `*` handler sees every event.\n *\n * @throws AuthioConfigurationError when no secret is configured.\n */\nexport function createAuthioWebhooks(options: AuthioWebhookOptions): AuthioWebhooks {\n const secrets = [...new Set([options.secret, ...(options.secrets ?? [])].filter((secret): secret is string => !!secret?.trim()))];\n\n if (secrets.length === 0) throw new AuthioConfigurationError(\"Authio webhooks need the webhook's secret.\");\n\n const clock = options.clock ?? systemClock;\n const tolerance = options.tolerance ?? 300;\n const windowMs = (options.deduplicationWindow ?? 86_400) * 1000;\n const maxBodySize = options.maxBodySize ?? 1024 * 1024;\n const store = resolveStore(options.deduplication ?? \"memory\", clock);\n const handlers: { type: string; handler: AuthioWebhookHandler }[] = [];\n\n const webhooks: AuthioWebhooks = {\n maxBodySize,\n on(type: string, handler: AuthioWebhookHandler) {\n if (!type) throw new TypeError(\"An event type (or '*') is required.\");\n\n handlers.push({ type, handler });\n return webhooks;\n },\n async handle(delivery) {\n const body = typeof delivery.body === \"string\" ? new TextEncoder().encode(delivery.body) : delivery.body;\n\n if (body.byteLength > maxBodySize) return { status: 413, reason: \"too_large\" };\n\n const signature = headerOf(delivery.headers, AuthioWebhookHeaders.Signature);\n let refusal = \"no webhook secret matched\";\n\n for (const secret of secrets) {\n const result = await verifyWebhookSignature(signature, body, secret, { tolerance, now: clock.now() });\n\n if (result.valid) {\n refusal = \"\";\n break;\n }\n\n refusal = result.reason;\n }\n\n if (refusal) {\n options.onError?.(new Error(refusal), { reason: \"unsigned\" });\n return { status: 401, reason: \"unsigned\" };\n }\n\n const event = tryParseWebhookEvent(body);\n\n if (!event) return { status: 400, reason: \"unreadable\" };\n\n const eventId = headerOf(delivery.headers, AuthioWebhookHeaders.EventId)?.trim() || String(event.id ?? \"\");\n\n if (eventId && !(await store.tryBegin(eventId, windowMs))) return { status: 200, reason: \"duplicate\", event };\n\n try {\n for (const { type, handler } of handlers) if (type === \"*\" || type === event.type) await handler(event);\n } catch (error) {\n if (eventId) await store.release(eventId);\n options.onError?.(error, { reason: \"handler_failed\", eventId, eventType: event.type });\n return { status: 500, reason: \"handler_failed\", event };\n }\n\n return { status: 200, reason: \"handled\", event };\n },\n };\n\n return webhooks;\n}\n\n/**\n * A deduplication store kept in this process's memory.\n */\nexport function createMemoryDeduplicationStore(clock: AuthioClock = systemClock): AuthioWebhookDeduplicationStore {\n const seen = new Map<string, number>();\n\n return {\n tryBegin(eventId, windowMs) {\n const now = clock.now();\n\n for (const [id, until] of seen) {\n if (until > now) break;\n seen.delete(id);\n }\n\n const until = seen.get(eventId);\n\n if (until !== undefined && until > now) return false;\n\n seen.delete(eventId);\n seen.set(eventId, now + windowMs);\n return true;\n },\n release(eventId) {\n seen.delete(eventId);\n },\n };\n}\n\nfunction resolveStore(deduplication: NonNullable<AuthioWebhookOptions[\"deduplication\"]>, clock: AuthioClock): AuthioWebhookDeduplicationStore {\n if (deduplication === \"none\") return { tryBegin: () => true, release: () => undefined };\n if (deduplication === \"memory\") return createMemoryDeduplicationStore(clock);\n\n return deduplication;\n}\n\nfunction headerOf(headers: Headers | Record<string, string | string[] | undefined>, name: string): string | 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 | string[] | undefined>)) {\n if (key.toLowerCase() === wanted) return Array.isArray(value) ? value[0] : value;\n }\n\n return undefined;\n}\n","import {\n AuthioDefaults,\n AuthioError,\n AuthioOAuthErrors,\n parseAuthioBearerChallenge,\n seconds,\n toClientCredentialsToken,\n toScopeString,\n type AuthioClient,\n type AuthioClientCredentialsToken,\n} from \"@hyper.authio/client\";\nimport type { AuthioUser } from \"./user.js\";\nimport { keyForToken } from \"./verifier.js\";\n\n/**\n * Who a downstream call is made for: a caller read by the verifier, or the incoming access token itself.\n */\nexport type AuthioDownstreamSubject = AuthioUser | string;\n\n/**\n * A `fetch` that forwards the caller's own access token, unchanged, to a downstream API that accepts the same\n * audience. Sends no `Authorization` when there is no token.\n */\nexport function createForwardingFetch(subject: AuthioDownstreamSubject | undefined, inner: typeof fetch = globalThis.fetch): typeof fetch {\n const token = tokenOf(subject);\n\n return (input, init) => {\n if (!token) return inner(input, init);\n\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n\n headers.set(\"authorization\", `Bearer ${token}`);\n\n return inner(input, { ...init, headers });\n };\n}\n\n/**\n * Exchanges the caller's token for one addressed to a downstream API (RFC 8693), and caches it.\n */\nexport interface AuthioOnBehalfOf {\n /**\n * A token for the downstream API on the caller's behalf: cached per incoming `jti` (else token hash), resource and\n * sorted scopes, renewed `tokenRefreshSkew` before expiry (at most half its lifetime); concurrent callers share\n * one exchange.\n *\n * @throws AuthioError when there is no incoming token.\n */\n getToken(subject: AuthioDownstreamSubject | undefined, signal?: AbortSignal): Promise<AuthioClientCredentialsToken>;\n /** Drops a cached token; with `accessToken`, only when the cache still holds that token. */\n invalidate(subject: AuthioDownstreamSubject, accessToken?: string): Promise<void>;\n /** A `fetch` that sends the exchanged token, and on a `401` drops it and retries once. */\n fetch(subject: AuthioDownstreamSubject | undefined, inner?: typeof fetch): typeof fetch;\n}\n\n/**\n * Creates an on-behalf-of exchanger.\n *\n * @param options `client` (the API's confidential client), the downstream `resource` and `scopes`.\n */\nexport function createOnBehalfOf(options: { client: AuthioClient; resource?: string; scopes?: Iterable<string> | string; tokenRefreshSkew?: number }): AuthioOnBehalfOf {\n const { client } = options;\n const scope = toScopeString(options.scopes);\n const sortedScope = (scope ?? \"\").split(\" \").filter(Boolean).sort().join(\" \");\n const skewMs = seconds(options.tokenRefreshSkew, AuthioDefaults.TokenRefreshSkew, \"tokenRefreshSkew\");\n const entries = new Map<string, AuthioClientCredentialsToken>();\n const pending = new Map<string, Promise<AuthioClientCredentialsToken>>();\n\n const keyOf = async (subject: AuthioDownstreamSubject) => {\n const token = tokenOf(subject)!;\n const jti = typeof subject === \"string\" ? undefined : subject.tokenId;\n\n return `${jti ? `jti:${jti}` : await keyForToken(token)}|${options.resource ?? \"\"}|${sortedScope}`;\n };\n\n const getToken: AuthioOnBehalfOf[\"getToken\"] = async (subject, signal) => {\n const incoming = tokenOf(subject);\n\n if (!incoming) throw new AuthioError(\"On-behalf-of needs the caller's access token, and the request has none.\");\n\n const key = await keyOf(subject!);\n const cached = entries.get(key);\n\n if (cached && client.connection.clock.now() < cached.refreshAt) return cached;\n\n let request = pending.get(key);\n\n if (!request) {\n request = client.tokens\n .exchange({ subjectToken: incoming, scopes: scope, resource: options.resource, signal })\n .then((response) => {\n const token = toClientCredentialsToken(response, client.connection.clock.now(), skewMs);\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\n const invalidate: AuthioOnBehalfOf[\"invalidate\"] = async (subject, accessToken) => {\n const key = await keyOf(subject);\n\n if (accessToken === undefined || entries.get(key)?.accessToken === accessToken) entries.delete(key);\n };\n\n return {\n getToken,\n invalidate,\n fetch(subject, inner = client.connection.fetch) {\n return async (input, init) => {\n const request = new Request(input, init);\n const body = request.body ? await request.arrayBuffer() : undefined;\n const attempt = (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 getToken(subject, request.signal);\n const response = await attempt(token);\n\n if (response.status !== 401 || isStepUpChallenge(response)) return response;\n\n await invalidate(subject!, token.accessToken);\n\n return attempt(await getToken(subject, request.signal));\n };\n },\n };\n}\n\n/**\n * Whether a `401` asks for a stronger or more recent sign-in (RFC 9470 §3), which a new exchanged token cannot satisfy.\n */\nfunction isStepUpChallenge(response: Response): boolean {\n return parseAuthioBearerChallenge(response.headers.get(\"www-authenticate\"))?.error === AuthioOAuthErrors.InsufficientUserAuthentication;\n}\n\nfunction tokenOf(subject: AuthioDownstreamSubject | undefined): string | undefined {\n if (!subject) return undefined;\n\n return typeof subject === \"string\" ? subject : subject.token;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/user.ts","../src/rules.ts","../src/errors.ts","../src/resource-metadata.ts","../src/verifier.ts","../src/webhooks.ts","../src/downstream.ts"],"names":["seconds","AuthioConfigurationError","systemClock","until","AuthioDefaults","AuthioError","token"],"mappings":";;;;AAiCA,IAAM,mCAAmB,IAAI,GAAA,CAAI,CAAC,QAAA,EAAU,SAAS,CAAC,CAAA;AAuB/C,IAAM,UAAA,GAAN,MAAM,WAAA,CAAW;AAAA;AAAA,EAEb,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,cAAA;AAAA;AAAA,EAEA,YAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,aAAA;AAAA;AAAA,EAEA,eAAA;AAAA;AAAA,EAEA,gBAAA;AAAA;AAAA,EAEA,YAAA;AAAA;AAAA,EAEA,YAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,QAAA;AAAA;AAAA,EAEA,QAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,KAAA;AAAA;AAAA,EAEA,WAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,iBAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,GAAA;AAAA;AAAA,EAEA,mBAAA;AAAA;AAAA,EAEA,qBAAA;AAAA;AAAA,EAEA,gBAAA;AAAA;AAAA,EAEA,eAAA;AAAA;AAAA,EAEA,KAAA;AAAA;AAAA,EAEA,YAAA;AAAA,EACA,KAAA;AAAA,EACA,aAA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W,CAAA;AAE5C,QAAA,OAAO,QAAQ,MAAM,QAAA,CAAS,OAAA,EAAS,OAAA,CAAQ,MAAM,CAAC,CAAA;AAAA,MACxD,CAAA;AAAA,IACF;AAAA,GACF;AACF;AAKA,SAAS,kBAAkB,QAAA,EAA6B;AACtD,EAAA,OAAO,0BAAA,CAA2B,SAAS,OAAA,CAAQ,GAAA,CAAI,kBAAkB,CAAC,CAAA,EAAG,UAAU,iBAAA,CAAkB,8BAAA;AAC3G;AAEA,SAAS,QAAQ,OAAA,EAAkE;AACjF,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AAErB,EAAA,OAAO,OAAO,OAAA,KAAY,QAAA,GAAW,OAAA,GAAU,OAAA,CAAQ,KAAA;AACzD","file":"index.js","sourcesContent":["import {\n AuthioClaimTypes,\n parseResourceAccess,\n type AuthioCallerKind,\n type AuthioCredentialForm,\n type AuthioIntrospectionResult,\n type AuthioResourceAccess,\n type AuthioResourceAccessSource,\n} from \"@hyper.authio/client\";\n\n/**\n * The party acting for the subject, from the `act` claim (RFC 8693): who exchanged the token, nested when the chain\n * is longer.\n */\nexport interface AuthioActor {\n readonly clientId: string | undefined;\n readonly subject: string | undefined;\n /** `name`, on an impersonation: the administrator's display name. */\n readonly name: string | undefined;\n readonly actor: AuthioActor | undefined;\n}\n\n/**\n * The administrator who impersonates the subject (an `act` with `sub` and no `client_id`).\n */\nexport interface AuthioImpersonator {\n readonly subject: string;\n readonly name: string | undefined;\n}\n\n/**\n * Introspection `token_type` values that stand for an access token: `Bearer`, and `api_key` for a consumer's API key.\n */\nconst accessTokenTypes = new Set([\"bearer\", \"api_key\"]);\n\n/**\n * Where the user reads flat (non-`*_resource_access`) roles and groups from.\n */\nexport interface AuthioUserClaimSettings {\n /**\n * Claims holding role names directly, such as one written by a claim mapper with the Role source. They count for\n * `hasRole` without a source filter. Defaults to `[\"role\"]`.\n */\n roleClaims?: readonly string[];\n /**\n * Claims holding group names, such as one written by a claim mapper with the Group source. Defaults to\n * `[\"groups\"]`.\n */\n groupClaims?: readonly string[];\n}\n\n/**\n * The caller of an API, read from a validated access token, an introspection answer, or both (the token's claims and\n * those of the answer the token does not carry, as `activeCheck` reads it): identity, every form of permission Authio\n * issues, and the raw claims for anything else.\n */\nexport class AuthioUser {\n /** `sub`: the person's id, or the credential's for a machine caller. */\n readonly subject: string;\n /**\n * Who called: `user` (a person signed in), `client` (a client as itself), `consumer` (a machine consumer of a\n * client) or `account_credential` (a credential of an Authio account).\n */\n readonly kind: AuthioCallerKind;\n /**\n * How a machine caller proved who it is (`client_secret`, `personal_access_token`, `api_key`,\n * `consumer_api_key`); `undefined` for a person or a client.\n */\n readonly credentialForm: AuthioCredentialForm | undefined;\n /** `consumer_name`, for a consumer. */\n readonly consumerName: string | undefined;\n /** `credential_name`, for an account credential. */\n readonly credentialName: string | undefined;\n /** `owner_user_id`: the person who made the credential. */\n readonly ownerUserId: string | undefined;\n /**\n * `owner_username`: the person who made the credential. On an account credential Authio wrote it to\n * `consumer_name` before, which is read when `owner_username` is absent.\n */\n readonly ownerUsername: string | undefined;\n /** `credential_realm`: the one realm an account credential is limited to. */\n readonly credentialRealm: string | undefined;\n /** `credential_client`: the one client an account credential is limited to. */\n readonly credentialClient: string | undefined;\n /** Whether an administrator impersonates the subject. */\n readonly impersonated: boolean;\n /** The administrator impersonating the subject. */\n readonly impersonator: AuthioImpersonator | undefined;\n /** Whether a client acts for the subject through a delegation (`act` with `client_id`). */\n readonly delegated: boolean;\n /** The clients acting for the subject, outermost first. */\n readonly actorChain: readonly string[];\n /** `auth_time`, in seconds since the epoch. */\n readonly authTime: number | undefined;\n /** The client the token was issued to (`client_id`, RFC 9068 §2.2, else `azp`). */\n readonly clientId: string | undefined;\n /** `sid`. */\n readonly sessionId: string | undefined;\n /** `jti`. */\n readonly tokenId: string | undefined;\n /** `aud`. */\n readonly audiences: readonly string[];\n /** The granted scopes. */\n readonly scopes: readonly string[];\n /** The roles of the seven `*_resource_access` claims, with their source and permissions. */\n readonly resourceAccess: AuthioResourceAccess;\n /** Every role name: the `*_resource_access` roles, then the flat role claims. */\n readonly roles: readonly string[];\n /** Resource → every method any role allows on it. */\n readonly permissions: Readonly<Record<string, readonly string[]>>;\n /** The group names of the group claims. */\n readonly groups: readonly string[];\n /** `org_id`. */\n readonly organizationId: string | undefined;\n /** `org_alias`. */\n readonly organizationAlias: string | undefined;\n /** `account_id`. */\n readonly accountId: string | undefined;\n /** `acr`. */\n readonly acr: string | undefined;\n /** `acr` as a number: 1 one factor, 2 several, 3 one of them phishing-resistant. */\n readonly authenticationLevel: number | undefined;\n /** `amr`. */\n readonly authenticationMethods: readonly string[];\n /** `idp`. */\n readonly identityProvider: string | undefined;\n /** `auth_time`. */\n readonly authenticatedAt: Date | undefined;\n /** `act`. */\n readonly actor: AuthioActor | undefined;\n /** `delegation_id`. */\n readonly delegationId: string | undefined;\n readonly email: string | undefined;\n readonly emailVerified: boolean | undefined;\n readonly name: string | undefined;\n readonly preferredUsername: string | undefined;\n /** `credential_type`, on a token issued to an account credential or a consumer. */\n readonly credentialType: string | undefined;\n /** `credential_id`. */\n readonly credentialId: string | undefined;\n /**\n * Every claim, as the token or the introspection answer carried it (with `activeCheck`, the token's, plus the\n * answer's the token does not carry).\n */\n readonly claims: Readonly<Record<string, unknown>>;\n /** The access token the user was read from. Not enumerable, so it stays out of logs and JSON. */\n declare readonly token: string | undefined;\n\n private readonly flatRoles: readonly string[];\n\n /**\n * @param claims The token's payload, or the introspection answer's members.\n * @param settings Where flat roles and groups are read from.\n * @param token The access token, kept for forwarding and on-behalf-of.\n * @param source Where the claims come from: a JWT (default) or an introspection answer. An introspection answer for\n * a consumer that reports no `exp` and no `actor_type` is the consumer's API key (Authio reports no lifetime for a\n * key), so its `credentialForm` is `consumer_api_key`.\n */\n constructor(\n claims: Readonly<Record<string, unknown>>,\n settings: AuthioUserClaimSettings = {},\n token?: string,\n source: \"token\" | \"introspection\" = \"token\",\n ) {\n const text = (name: string) => (typeof claims[name] === \"string\" && claims[name] ? (claims[name] as string) : undefined);\n\n this.claims = Object.freeze({ ...claims });\n this.subject = text(AuthioClaimTypes.Subject) ?? \"\";\n this.clientId = text(AuthioClaimTypes.ClientId) ?? text(AuthioClaimTypes.AuthorizedParty);\n this.sessionId = text(AuthioClaimTypes.SessionId);\n this.tokenId = text(AuthioClaimTypes.JwtId);\n this.audiences = Object.freeze(distinct(valuesOf(claims[AuthioClaimTypes.Audience])));\n this.scopes = Object.freeze(distinct(valuesOf(claims[AuthioClaimTypes.Scope]).flatMap((scope) => scope.split(/\\s+/)).filter(Boolean)));\n this.resourceAccess = parseResourceAccess(claims);\n this.flatRoles = Object.freeze((settings.roleClaims ?? [\"role\"]).flatMap((name) => valuesOf(claims[name])));\n this.roles = Object.freeze(distinctIgnoringCase([...this.resourceAccess.roles, ...this.flatRoles]));\n this.permissions = this.resourceAccess.permissions;\n this.groups = Object.freeze(distinct((settings.groupClaims ?? [\"groups\"]).flatMap((name) => valuesOf(claims[name]))));\n this.organizationId = text(AuthioClaimTypes.OrganizationId);\n this.organizationAlias = text(AuthioClaimTypes.OrganizationAlias);\n this.accountId = text(AuthioClaimTypes.AccountId);\n this.acr = valuesOf(claims[AuthioClaimTypes.AuthenticationContextClass])[0];\n this.authenticationLevel = this.acr !== undefined && /^\\d+$/.test(this.acr) ? Number(this.acr) : undefined;\n this.authenticationMethods = Object.freeze(distinctIgnoringCase(valuesOf(claims[AuthioClaimTypes.AuthenticationMethods])));\n this.identityProvider = text(AuthioClaimTypes.IdentityProvider);\n this.authenticatedAt = toDate(claims[AuthioClaimTypes.AuthTime]);\n this.actor = readActor(claims[AuthioClaimTypes.Actor]);\n this.delegationId = text(AuthioClaimTypes.DelegationId);\n this.email = text(AuthioClaimTypes.Email);\n this.emailVerified = toBoolean(claims[AuthioClaimTypes.EmailVerified]);\n this.name = text(AuthioClaimTypes.Name);\n this.preferredUsername = text(AuthioClaimTypes.PreferredUsername);\n this.credentialType = text(AuthioClaimTypes.CredentialType);\n this.credentialId = text(AuthioClaimTypes.CredentialId);\n this.authTime = toSeconds(claims[AuthioClaimTypes.AuthTime]);\n this.kind =\n this.credentialType === \"client_consumer\"\n ? \"consumer\"\n : this.credentialType === \"account_secret\"\n ? \"account_credential\"\n : this.authTime !== undefined\n ? \"user\"\n : \"client\";\n\n const machine = this.kind === \"consumer\" || this.kind === \"account_credential\";\n\n const keyIntrospected = source === \"introspection\" && this.kind === \"consumer\" && claims[AuthioClaimTypes.Expiration] === undefined;\n\n this.credentialForm = machine\n ? ((text(AuthioClaimTypes.ActorType) as AuthioCredentialForm | undefined) ?? (keyIntrospected ? \"consumer_api_key\" : \"client_secret\"))\n : undefined;\n this.consumerName = this.kind === \"consumer\" ? text(AuthioClaimTypes.ConsumerName) : undefined;\n this.credentialName = text(AuthioClaimTypes.CredentialName);\n this.ownerUserId = text(AuthioClaimTypes.OwnerUserId);\n this.ownerUsername =\n text(AuthioClaimTypes.OwnerUsername) ?? (this.kind === \"account_credential\" ? text(AuthioClaimTypes.ConsumerName) : undefined);\n this.credentialRealm = text(AuthioClaimTypes.CredentialRealm);\n this.credentialClient = text(AuthioClaimTypes.CredentialClient);\n this.delegated = this.actor?.clientId !== undefined;\n this.actorChain = Object.freeze(chainOf(this.actor));\n this.impersonated = !this.delegated && this.actor?.subject !== undefined;\n this.impersonator = this.impersonated ? Object.freeze({ subject: this.actor!.subject!, name: this.actor!.name }) : undefined;\n\n Object.defineProperty(this, \"token\", { value: token, enumerable: false });\n }\n\n /**\n * Reads the caller from an introspection answer: `client_id` becomes `azp`, `username` becomes\n * `preferred_username`, and `token_type` becomes `typ` unless it is `api_key` (a consumer's API key).\n */\n static fromIntrospection(result: AuthioIntrospectionResult, settings: AuthioUserClaimSettings = {}, token?: string): AuthioUser {\n return new AuthioUser(claimsOfIntrospection(result), settings, token, \"introspection\");\n }\n\n /** Whether the scope was granted. */\n hasScope(scope: string): boolean {\n return this.scopes.includes(scope);\n }\n\n /**\n * Whether the user holds the role. Without sources, from any `*_resource_access` claim or a flat role claim; with\n * sources, only from those `*_resource_access` claims.\n */\n hasRole(role: string, options: { sources?: readonly AuthioResourceAccessSource[] } = {}): boolean {\n if (!role) return false;\n if (options.sources && options.sources.length > 0) return this.resourceAccess.hasRole(role, options.sources);\n\n const wanted = role.toLowerCase();\n\n return this.resourceAccess.hasRole(role) || this.flatRoles.some((name) => name.toLowerCase() === wanted);\n }\n\n /**\n * Authio's grant rule: whether a role (from any source, or only from the given ones) allows `method` on\n * `resource`. Case-insensitive.\n */\n hasPermission(resource: string, method: string, options: { sources?: readonly AuthioResourceAccessSource[] } = {}): boolean {\n return this.resourceAccess.grants(resource, method, options.sources);\n }\n\n /** Whether the user is in the group (exact match). */\n hasGroup(group: string): boolean {\n return this.groups.includes(group);\n }\n\n /**\n * Whether the claim is present (not `null`), and, given values, whether it holds one of them (exact match; an\n * array claim matches when any item does).\n */\n hasClaim(type: string, ...values: string[]): boolean {\n const present = this.claimValues(type);\n\n return values.length === 0 ? present.length > 0 : present.some((value) => values.includes(value));\n }\n\n /**\n * The claim's values as text: one for a scalar, one per item for an array, JSON text for an object.\n */\n claimValues(type: string): string[] {\n return valuesOf(this.claims[type]);\n }\n\n /** Every member but the raw token. */\n toJSON(): Record<string, unknown> {\n const { flatRoles: _flatRoles, ...members } = this as unknown as Record<string, unknown>;\n\n return { ...members, resourceAccess: this.resourceAccess.entries };\n }\n}\n\n/**\n * The claims an introspection answer stands for, named as in a JWT.\n *\n * @internal\n */\nexport function claimsOfIntrospection(result: AuthioIntrospectionResult): Record<string, unknown> {\n const { active: _active, token_type: tokenType, username, ...members } = result;\n const claims: Record<string, unknown> = { ...members };\n\n if (typeof tokenType === \"string\" && claims.typ === undefined && tokenType.toLowerCase() !== \"api_key\") claims.typ = tokenType;\n if (typeof username === \"string\" && claims.preferred_username === undefined) claims.preferred_username = username;\n if (typeof result.client_id === \"string\" && claims.azp === undefined) claims.azp = result.client_id;\n\n return claims;\n}\n\n/**\n * Whether an introspection `token_type` stands for an access token.\n *\n * @internal\n */\nexport function isAccessTokenType(type: string): boolean {\n return accessTokenTypes.has(type.toLowerCase());\n}\n\n/**\n * A claim's values as text.\n *\n * @internal\n */\nexport function valuesOf(value: unknown): string[] {\n if (value === undefined || value === null) return [];\n if (Array.isArray(value)) return value.flatMap((item) => (item === null || item === undefined ? [] : [toText(item)]));\n\n if (typeof value === \"string\" && value.startsWith(\"[\")) {\n try {\n const parsed = JSON.parse(value) as unknown;\n\n if (Array.isArray(parsed)) return valuesOf(parsed);\n } catch {\n return [value];\n }\n }\n\n return [toText(value)];\n}\n\nfunction toText(value: unknown): string {\n return typeof value === \"string\" ? value : typeof value === \"object\" ? JSON.stringify(value) : String(value);\n}\n\nfunction readActor(value: unknown, depth = 0): AuthioActor | undefined {\n let actor = value;\n\n if (typeof actor === \"string\") {\n try {\n actor = JSON.parse(actor);\n } catch {\n return undefined;\n }\n }\n\n if (!actor || typeof actor !== \"object\" || Array.isArray(actor) || depth > 16) return undefined;\n\n const record = actor as Record<string, unknown>;\n\n return Object.freeze({\n clientId: typeof record.client_id === \"string\" && record.client_id ? record.client_id : undefined,\n subject: typeof record.sub === \"string\" && record.sub ? record.sub : undefined,\n name: typeof record.name === \"string\" && record.name ? record.name : undefined,\n actor: readActor(record.act, depth + 1),\n });\n}\n\nfunction chainOf(actor: AuthioActor | undefined): string[] {\n const chain: string[] = [];\n\n for (let current = actor; current; current = current.actor) if (current.clientId) chain.push(current.clientId);\n\n return chain;\n}\n\nfunction toSeconds(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value) : undefined;\n}\n\nfunction toDate(value: unknown): Date | undefined {\n const seconds = typeof value === \"number\" ? value : typeof value === \"string\" && /^\\d+$/.test(value) ? Number(value) : undefined;\n\n return seconds === undefined ? undefined : new Date(seconds * 1000);\n}\n\nfunction toBoolean(value: unknown): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n\n return undefined;\n}\n\nfunction distinct(values: readonly string[]): string[] {\n return [...new Set(values)];\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","import { systemClock, type AuthioCallerKind, type AuthioClock, type AuthioResourceAccessSource } from \"@hyper.authio/client\";\nimport type { AuthioUser } from \"./user.js\";\n\n/**\n * How several required values combine.\n */\nexport type AuthioMatch = \"any\" | \"all\";\n\n/**\n * Why a rule refused the caller.\n */\nexport interface AuthioRuleFailure {\n /** What is missing, in words. */\n readonly message: string;\n /**\n * The RFC 6750 / RFC 9470 error to put in `WWW-Authenticate`: `insufficient_scope` for scopes,\n * `insufficient_user_authentication` for `acr`/`amr`, none otherwise.\n */\n readonly error?: \"insufficient_scope\" | \"insufficient_user_authentication\";\n /** The required scopes, for `insufficient_scope`. */\n readonly scope?: string;\n /** The context classes to ask for again, for `insufficient_user_authentication` (RFC 9470 `acr_values`). */\n readonly acrValues?: string;\n /** How old the sign-in may be, in seconds, for `insufficient_user_authentication` (RFC 9470 `max_age`). */\n readonly maxAge?: number;\n}\n\n/**\n * A condition on the caller.\n */\nexport interface AuthioRule {\n /** What the rule requires, for logs. */\n readonly description: string;\n /** `undefined` when the caller satisfies the rule, else why not. */\n check(user: AuthioUser): AuthioRuleFailure | undefined;\n}\n\n/**\n * Checks every rule. On refusal the message joins every rule's. When a rule other than a step-up fails (a scope, role,\n * permission, group, claim, organization, client or caller kind), no stronger sign-in can satisfy the request: the\n * refusal is a `403`, with the first such rule's error (`insufficient_scope`) or none, and never asks for a step-up.\n * Only when every failing rule asks for a stronger or more recent sign-in is the error `insufficient_user_authentication`,\n * with the strongest `acr_values` and the shortest `max_age` they ask for.\n */\nexport function authorize(user: AuthioUser, ...rules: AuthioRule[]): AuthioRuleFailure | undefined {\n const failures = rules.map((rule) => rule.check(user)).filter((failure): failure is AuthioRuleFailure => failure !== undefined);\n\n if (failures.length === 0) return undefined;\n\n const others = failures.filter((failure) => failure.error !== \"insufficient_user_authentication\");\n const stepUps = others.length === 0 ? failures : [];\n const bearer = stepUps[0] ?? others.find((failure) => failure.error);\n const acrValues = strongestAcr(stepUps.map((failure) => failure.acrValues));\n const maxAges = stepUps.map((failure) => failure.maxAge).filter((value): value is number => value !== undefined);\n\n return {\n message: failures.map((failure) => failure.message).join(\" \"),\n ...(bearer?.error ? { error: bearer.error } : {}),\n ...(bearer?.scope ? { scope: bearer.scope } : {}),\n ...(acrValues ? { acrValues } : {}),\n ...(maxAges.length > 0 ? { maxAge: Math.min(...maxAges) } : {}),\n };\n}\n\n/**\n * Requires granted scopes.\n */\nexport function requireScope(scopes: string | readonly string[], match: AuthioMatch = \"any\"): AuthioRule {\n const required = listOf(scopes, \"scope\");\n\n return {\n description: `Authio scope (${match}): ${required.join(\" \")}`,\n check: (user) =>\n satisfies(required, match, (scope) => user.hasScope(scope))\n ? undefined\n : {\n message: `The token lacks the required scope (${match}): ${required.join(\" \")}.`,\n error: \"insufficient_scope\",\n scope: required.join(\" \"),\n },\n };\n}\n\n/**\n * Requires roles, from any source or only from the given `*_resource_access` claims.\n */\nexport function requireRole(\n roles: string | readonly string[],\n options: { match?: AuthioMatch; sources?: readonly AuthioResourceAccessSource[] } = {},\n): AuthioRule {\n const required = listOf(roles, \"role\");\n const match = options.match ?? \"any\";\n const from = describeSources(options.sources);\n\n return {\n description: `Authio role (${match}): ${required.join(\", \")}${from}`,\n check: (user) =>\n satisfies(required, match, (role) => user.hasRole(role, { sources: options.sources }))\n ? undefined\n : { message: `The caller lacks the required role (${match}): ${required.join(\", \")}${from}.` },\n };\n}\n\n/**\n * Requires a permission (`method` on `resource`), granted by a role from any source or only from the given ones.\n */\nexport function requirePermission(resource: string, method: string, options: { sources?: readonly AuthioResourceAccessSource[] } = {}): AuthioRule {\n if (!resource?.trim() || !method?.trim()) throw new TypeError(\"A permission needs a resource and a method.\");\n\n const from = describeSources(options.sources);\n\n return {\n description: `Authio permission: ${resource}:${method}${from}`,\n check: (user) =>\n user.hasPermission(resource, method, { sources: options.sources }) ? undefined : { message: `The caller lacks the permission ${resource}:${method}${from}.` },\n };\n}\n\n/**\n * Requires groups, read from the group claims (a claim mapper with the Group source).\n */\nexport function requireGroup(groups: string | readonly string[], match: AuthioMatch = \"any\"): AuthioRule {\n const required = listOf(groups, \"group\");\n\n return {\n description: `Authio group (${match}): ${required.join(\", \")}`,\n check: (user) =>\n satisfies(required, match, (group) => user.hasGroup(group))\n ? undefined\n : { message: `The caller is not in the required group (${match}): ${required.join(\", \")}.` },\n };\n}\n\n/**\n * Requires a claim: present, or holding one of the given values. Fits claim-mapper claims, the user's own claims and\n * any other claim Authio issues.\n */\nexport function requireClaim(type: string, ...values: string[]): AuthioRule {\n if (!type?.trim()) throw new TypeError(\"A claim rule needs a claim type.\");\n\n return {\n description: values.length === 0 ? `Authio claim: ${type}` : `Authio claim: ${type} in ${values.join(\", \")}`,\n check: (user) =>\n user.hasClaim(type, ...values)\n ? undefined\n : { message: values.length === 0 ? `The token lacks the claim ${type}.` : `The token's claim ${type} is not one of: ${values.join(\", \")}.` },\n };\n}\n\n/**\n * Requires an organization context, or a given organization (alias or id, case-insensitive).\n */\nexport function requireOrganization(organization?: string): AuthioRule {\n const wanted = organization?.trim() || undefined;\n\n return {\n description: `Authio organization: ${wanted ?? \"any\"}`,\n check: (user) => {\n const satisfied =\n !!user.organizationId &&\n (!wanted ||\n user.organizationAlias?.toLowerCase() === wanted.toLowerCase() ||\n user.organizationId.toLowerCase() === wanted.toLowerCase());\n\n return satisfied\n ? undefined\n : { message: wanted ? `The token is not in the organization ${wanted}.` : \"The token has no organization context.\" };\n },\n };\n}\n\n/**\n * Requires a minimum authentication level (`acr`): 1 one factor, 2 several, 3 one of them phishing-resistant. The\n * refusal asks for that level again (`acr_values`), and for a sign-in at most `maxAge` seconds old when given.\n */\nexport function requireAuthenticationLevel(minimumLevel: number, options: { maxAge?: number; clock?: AuthioClock } = {}): AuthioRule {\n if (!Number.isInteger(minimumLevel) || minimumLevel < 0) throw new RangeError(\"The minimum level must be a non-negative integer.\");\n\n const recency = options.maxAge === undefined ? undefined : requireRecentAuthentication(options.maxAge, { clock: options.clock });\n\n return {\n description: `Authio authentication level >= ${minimumLevel}${recency ? `, ${recency.description}` : \"\"}`,\n check: (user) => {\n const levelMet = user.authenticationLevel !== undefined && user.authenticationLevel >= minimumLevel;\n const recent = recency?.check(user);\n\n if (levelMet && !recent) return undefined;\n\n return {\n message: [levelMet ? undefined : `The authentication level must be at least ${minimumLevel}.`, recent?.message].filter(Boolean).join(\" \"),\n error: \"insufficient_user_authentication\",\n acrValues: String(minimumLevel),\n ...(options.maxAge !== undefined ? { maxAge: options.maxAge } : {}),\n };\n },\n };\n}\n\n/**\n * The context class each authentication method implies when an API asks for it again (Authio's `acr` levels).\n */\nconst methodLevels: Readonly<Record<string, string>> = { mfa: \"2\", otp: \"2\", mca: \"2\", sms: \"2\", swk: \"3\", hwk: \"3\" };\n\n/**\n * Requires authentication methods (`amr`, case-insensitive), such as `otp`, `swk` or `fed`. The refusal asks for the\n * context class the methods imply (`2` for `mfa`/`otp`/`mca`, `3` for `swk`/`hwk`), or for `acrValues` when given.\n */\nexport function requireAuthenticationMethod(\n methods: string | readonly string[],\n match: AuthioMatch = \"any\",\n options: { acrValues?: string } = {},\n): AuthioRule {\n const required = listOf(methods, \"authentication method\");\n const levels = required.map((method) => methodLevels[method.toLowerCase()]).filter((level): level is string => level !== undefined);\n const acrValues = options.acrValues ?? (levels.length === 0 ? undefined : match === \"all\" ? strongestAcr(levels) : weakestAcr(levels));\n\n return {\n description: `Authio authentication method (${match}): ${required.join(\", \")}`,\n check: (user) => {\n const used = user.authenticationMethods.map((method) => method.toLowerCase());\n\n return satisfies(required, match, (method) => used.includes(method.toLowerCase()))\n ? undefined\n : {\n message: `The user must authenticate with (${match}): ${required.join(\", \")}.`,\n error: \"insufficient_user_authentication\",\n ...(acrValues ? { acrValues } : {}),\n };\n },\n };\n}\n\n/**\n * Requires a sign-in at most `maxAge` seconds old (`auth_time`); the refusal asks for it with `max_age` (RFC 9470).\n */\nexport function requireRecentAuthentication(maxAge: number, options: { clock?: AuthioClock } = {}): AuthioRule {\n if (!Number.isInteger(maxAge) || maxAge < 0) throw new RangeError(\"maxAge must be a non-negative whole number of seconds.\");\n\n const clock = options.clock ?? systemClock;\n\n return {\n description: `Authio sign-in at most ${maxAge} s old`,\n check: (user) =>\n user.authTime !== undefined && clock.now() - user.authTime * 1000 <= maxAge * 1000\n ? undefined\n : {\n message:\n user.authTime === undefined\n ? `The token carries no sign-in time; a sign-in at most ${maxAge} seconds old is required.`\n : `The sign-in must be at most ${maxAge} seconds old.`,\n error: \"insufficient_user_authentication\",\n maxAge,\n },\n };\n}\n\n/**\n * Requires the caller to be of one of the kinds: `user`, `client`, `consumer`, `account_credential`.\n */\nexport function requireCallerKind(kinds: AuthioCallerKind | readonly AuthioCallerKind[]): AuthioRule {\n const required = listOf(kinds, \"caller kind\") as AuthioCallerKind[];\n\n return {\n description: `Authio caller kind: ${required.join(\", \")}`,\n check: (user) => (required.includes(user.kind) ? undefined : { message: `The caller is a ${user.kind}, not one of: ${required.join(\", \")}.` }),\n };\n}\n\n/**\n * Requires the token to have been issued to one of the clients (`client_id`, else `azp`).\n */\nexport function requireClient(clientIds: string | readonly string[]): AuthioRule {\n const required = listOf(clientIds, \"client id\");\n\n return {\n description: `Authio client: ${required.join(\", \")}`,\n check: (user) =>\n user.clientId !== undefined && required.includes(user.clientId)\n ? undefined\n : { message: `The token was not issued to an accepted client (${required.join(\", \")}).` },\n };\n}\n\n/**\n * Requires every rule.\n */\nexport function allOf(...rules: AuthioRule[]): AuthioRule {\n return {\n description: rules.map((rule) => rule.description).join(\" and \"),\n check: (user) => authorize(user, ...rules),\n };\n}\n\n/**\n * Requires at least one rule; the refusal is the first rule's.\n */\nexport function anyOf(...rules: AuthioRule[]): AuthioRule {\n if (rules.length === 0) throw new TypeError(\"anyOf needs at least one rule.\");\n\n return {\n description: rules.map((rule) => rule.description).join(\" or \"),\n check: (user) => {\n const failures = rules.map((rule) => rule.check(user));\n\n return failures.some((failure) => failure === undefined) ? undefined : failures[0];\n },\n };\n}\n\nfunction listOf(values: string | readonly string[], name: string): string[] {\n const list = [...new Set((typeof values === \"string\" ? [values] : [...values]).filter((value) => value?.trim()))];\n\n if (list.length === 0) throw new TypeError(`At least one ${name} is required.`);\n\n return list;\n}\n\nfunction satisfies(required: readonly string[], match: AuthioMatch, holds: (value: string) => boolean): boolean {\n return match === \"all\" ? required.every(holds) : required.some(holds);\n}\n\nfunction strongestAcr(values: readonly (string | undefined)[]): string | undefined {\n return rankAcr(values, (left, right) => right - left);\n}\n\nfunction weakestAcr(values: readonly (string | undefined)[]): string | undefined {\n return rankAcr(values, (left, right) => left - right);\n}\n\nfunction rankAcr(values: readonly (string | undefined)[], order: (left: number, right: number) => number): string | undefined {\n const known = values.filter((value): value is string => !!value);\n const numeric = known.filter((value) => /^\\d+$/.test(value)).sort((left, right) => order(Number(left), Number(right)));\n\n return numeric[0] ?? known[0];\n}\n\nfunction describeSources(sources: readonly AuthioResourceAccessSource[] | undefined): string {\n return sources && sources.length > 0 ? ` from ${[...new Set(sources)].join(\", \")}` : \"\";\n}\n","import { AuthioError, type AuthioTokenFailure } from \"@hyper.authio/client\";\nimport type { AuthioRuleFailure } from \"./rules.js\";\n\n/**\n * The request carries no valid access token: answer `401` with `wwwAuthenticate`.\n */\nexport class AuthioBearerError extends AuthioError {\n readonly status = 401;\n /** `invalid_token`, or `undefined` when the request had no token at all (RFC 6750 §3.1). */\n readonly error: \"invalid_token\" | undefined;\n /** Why the token was refused, safe to send to the caller. */\n readonly description: string | undefined;\n /** Why the token was refused, as a stable code; `undefined` when there was no token or Authio could not be asked. */\n readonly reason: AuthioTokenFailure | \"inactive\" | \"unconfirmed\" | undefined;\n /** The API's protected resource metadata URL (RFC 9728), sent as `resource_metadata` when configured. */\n readonly resourceMetadata: string | undefined;\n\n constructor(\n description: string | undefined,\n options: {\n error?: \"invalid_token\" | undefined;\n cause?: unknown;\n reason?: AuthioTokenFailure | \"inactive\" | \"unconfirmed\";\n resourceMetadata?: string;\n } = {},\n ) {\n super(description ?? \"A valid Authio access token is required.\", { cause: options.cause });\n this.error = \"error\" in options ? options.error : \"invalid_token\";\n this.description = description === undefined ? undefined : toHeaderText(description);\n this.reason = options.reason;\n this.resourceMetadata = options.resourceMetadata;\n }\n\n /** The same refusal, pointing at the API's protected resource metadata. */\n withResourceMetadata(resourceMetadata: string | undefined): AuthioBearerError {\n if (!resourceMetadata || resourceMetadata === this.resourceMetadata) return this;\n\n return new AuthioBearerError(this.description, { error: this.error, cause: this.cause, reason: this.reason, resourceMetadata });\n }\n\n /** The `WWW-Authenticate` value. */\n get wwwAuthenticate(): string {\n const parameters: string[] = [];\n\n if (this.error) parameters.push(`error=\"${this.error}\"`);\n if (this.error && this.description) parameters.push(`error_description=\"${this.description}\"`);\n if (this.resourceMetadata) parameters.push(`resource_metadata=\"${escapeQuoted(this.resourceMetadata)}\"`);\n\n return parameters.length === 0 ? \"Bearer\" : `Bearer ${parameters.join(\", \")}`;\n }\n}\n\n/**\n * A rule refused a caller whose token is valid. A refusal asking for a stronger or more recent sign-in\n * (`insufficient_user_authentication`) answers `401`, as RFC 9470 §3 has it, naming the protected resource metadata\n * (`resource_metadata`, RFC 9728 §5.1) when the API publishes it; every other refusal answers `403`, with\n * `wwwAuthenticate` when it is about scopes (`insufficient_scope`, RFC 6750 §3.1).\n */\nexport class AuthioForbiddenError extends AuthioError {\n /** `401` for a step-up (`insufficient_user_authentication`), `403` otherwise. */\n readonly status: 401 | 403;\n readonly failure: AuthioRuleFailure;\n /** The API's protected resource metadata URL (RFC 9728), sent as `resource_metadata` with a step-up `401`. */\n readonly resourceMetadata: string | undefined;\n\n constructor(failure: AuthioRuleFailure, options: { resourceMetadata?: string } = {}) {\n super(failure.message);\n this.failure = failure;\n this.status = failure.error === \"insufficient_user_authentication\" ? 401 : 403;\n this.resourceMetadata = options.resourceMetadata;\n }\n\n /** The same refusal, pointing at the API's protected resource metadata. */\n withResourceMetadata(resourceMetadata: string | undefined): AuthioForbiddenError {\n if (!resourceMetadata || resourceMetadata === this.resourceMetadata) return this;\n\n return new AuthioForbiddenError(this.failure, { resourceMetadata });\n }\n\n /**\n * The `WWW-Authenticate` value, or `undefined` when the refusal is not about scopes or the sign-in. A step-up `401`\n * carries `resource_metadata` when `resourceMetadata` is set.\n */\n get wwwAuthenticate(): string | undefined {\n const challenge = toForbiddenChallenge(this.failure);\n\n return challenge && this.status === 401 && this.resourceMetadata ? `${challenge}, resource_metadata=\"${escapeQuoted(this.resourceMetadata)}\"` : challenge;\n }\n}\n\n/**\n * The `WWW-Authenticate` value of a refusal: `insufficient_scope` (with `scope`) or `insufficient_user_authentication`\n * (with `acr_values` and `max_age`, RFC 9470).\n */\nexport function toForbiddenChallenge(failure: AuthioRuleFailure): string | undefined {\n if (!failure.error) return undefined;\n\n const parameters = [`error=\"${failure.error}\"`, `error_description=\"${escapeQuoted(toHeaderText(failure.message))}\"`];\n\n if (failure.scope) parameters.push(`scope=\"${escapeQuoted(failure.scope)}\"`);\n if (failure.acrValues) parameters.push(`acr_values=\"${escapeQuoted(failure.acrValues)}\"`);\n if (failure.maxAge !== undefined) parameters.push(`max_age=${failure.maxAge}`);\n\n return `Bearer ${parameters.join(\", \")}`;\n}\n\n/**\n * Problem details (RFC 9457) for a `401` or `403`, with the refusal's `status`: a step-up refusal is `401`\n * Unauthorized and carries `error`, `acr_values` and `max_age`.\n */\nexport function toProblemDetails(error: AuthioBearerError | AuthioForbiddenError): Record<string, unknown> {\n if (error instanceof AuthioBearerError)\n return {\n type: unauthorizedType,\n title: \"Unauthorized\",\n status: 401,\n detail: \"A valid Authio access token is required.\",\n };\n\n return {\n type: error.status === 401 ? unauthorizedType : \"https://tools.ietf.org/html/rfc9110#section-15.5.4\",\n title: error.status === 401 ? \"Unauthorized\" : \"Forbidden\",\n status: error.status,\n detail: error.failure.message || \"The caller is not allowed to access this resource.\",\n ...(error.failure.error ? { error: error.failure.error } : {}),\n ...(error.failure.scope ? { scope: error.failure.scope } : {}),\n ...(error.failure.acrValues ? { acr_values: error.failure.acrValues } : {}),\n ...(error.failure.maxAge !== undefined ? { max_age: error.failure.maxAge } : {}),\n };\n}\n\nconst unauthorizedType = \"https://tools.ietf.org/html/rfc9110#section-15.5.2\";\n\n/**\n * Keeps only the characters RFC 6750 §3 allows in an `error_description`.\n *\n * @internal\n */\nexport function toHeaderText(text: string): string {\n return [...text].map((character) => (character >= \" \" && character <= \"~\" && character !== '\"' && character !== \"\\\\\" ? character : \"?\")).join(\"\");\n}\n\nfunction escapeQuoted(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n","import { AuthioConfigurationError, AuthioDefaults, resolveIssuer, type AuthioConnectionOptions } from \"@hyper.authio/client\";\n\n/**\n * What an API publishes about itself as a protected resource (RFC 9728).\n */\nexport interface AuthioProtectedResourceMetadataOptions extends Pick<AuthioConnectionOptions, \"issuer\" | \"authority\" | \"realm\"> {\n /** The API's resource identifier (RFC 8707), such as `https://orders.example.com/api`. Required. */\n resource: string;\n /** Scopes a client can ask for to call the API. */\n scopesSupported?: readonly string[];\n /** A name to show to people. */\n resourceName?: string;\n /** A page documenting the API. */\n resourceDocumentation?: string;\n /** Further members, sent as given. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * The protected resource metadata document (RFC 9728 §2).\n */\nexport interface AuthioProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n bearer_methods_supported: string[];\n scopes_supported?: string[];\n resource_name?: string;\n resource_documentation?: string;\n [member: string]: unknown;\n}\n\n/**\n * Where a resource's metadata is published: `{origin}/.well-known/oauth-protected-resource{path}` (RFC 9728 §3.1),\n * the path being the resource's own, without a trailing slash.\n */\nexport function protectedResourceMetadataUrl(resource: string): string {\n const url = parseResource(resource);\n const path = url.pathname.replace(/\\/+$/, \"\");\n\n return `${url.origin}${AuthioDefaults.ProtectedResourceMetadataPath}${path}`;\n}\n\n/**\n * The path a resource's metadata is served at on the API itself: `/.well-known/oauth-protected-resource{path}`.\n */\nexport function protectedResourceMetadataPath(resource: string): string {\n return new URL(protectedResourceMetadataUrl(resource)).pathname;\n}\n\n/**\n * Builds the API's protected resource metadata: the resource, the realm's issuer as its authorization server, bearer\n * tokens in the `Authorization` header, and the optional scopes, name and documentation.\n */\nexport function createProtectedResourceMetadata(options: AuthioProtectedResourceMetadataOptions): AuthioProtectedResourceMetadata {\n parseResource(options.resource);\n\n const document: AuthioProtectedResourceMetadata = {\n ...options.extra,\n resource: options.resource,\n authorization_servers: [resolveIssuer(options)],\n bearer_methods_supported: [\"header\"],\n };\n\n if (options.scopesSupported && options.scopesSupported.length > 0) document.scopes_supported = [...options.scopesSupported];\n if (options.resourceName) document.resource_name = options.resourceName;\n if (options.resourceDocumentation) document.resource_documentation = options.resourceDocumentation;\n\n return document;\n}\n\nfunction parseResource(resource: string): URL {\n let url: URL;\n\n try {\n url = new URL(resource);\n } catch (error) {\n throw new AuthioConfigurationError(`The resource '${resource}' is not an absolute URL.`, { cause: error });\n }\n\n if (url.hash) throw new AuthioConfigurationError(`The resource '${resource}' must not carry a fragment (RFC 8707).`);\n\n return url;\n}\n","import {\n AuthioAsymmetricAlgorithms,\n AuthioConfigurationError,\n AuthioHmacAlgorithms,\n AuthioTokenTypes,\n AuthioTokenValidationError,\n createAuthioClient,\n createAuthioDiscoveryClient,\n createAuthioSigningKeys,\n createAuthioTokenDecrypter,\n encryptionKeyFromFile,\n isAuthioTokenEncrypted,\n requireHmacSecretLength,\n resolveConnection,\n seconds,\n requireAccessTokenType,\n verifyAuthioJwt,\n withClientSecret,\n type AuthioClient,\n type AuthioClientOptions,\n type AuthioConnection,\n type AuthioConnectionOptions,\n type AuthioDiscoveryClient,\n type AuthioEncryptionKeySource,\n type AuthioIntrospectionResult,\n} from \"@hyper.authio/client\";\nimport { decodeProtectedHeader, type JWTPayload } from \"jose\";\nimport { AuthioBearerError } from \"./errors.js\";\nimport { protectedResourceMetadataUrl } from \"./resource-metadata.js\";\nimport { AuthioUser, claimsOfIntrospection, isAccessTokenType, type AuthioUserClaimSettings } from \"./user.js\";\n\n/**\n * Whether and how Authio's introspection endpoint takes part in validating a token.\n *\n * - `none`: the JWT is validated locally (signature, issuer, audience, lifetime) and the caller is read from it alone.\n * Fastest; a revoked token stays valid until it expires. A lightweight access token carries no roles, permissions,\n * plan, profile or email, so it needs one of the modes below.\n * - `activeCheck`: validated locally, then confirmed active by introspection (cached per `jti`). The caller is read\n * from the token, and the introspection answer adds the claims the token does not carry: the answer has every claim\n * of the complete token, so a lightweight access token's roles and permissions are read too. A claim the token\n * carries keeps the token's value, which its signature vouches for, whatever the answer says.\n * - `introspectionOnly`: introspection alone, for opaque (reference) tokens, or encrypted ones without the key. The\n * caller is read from the answer.\n */\nexport type AuthioIntrospectionMode = \"none\" | \"activeCheck\" | \"introspectionOnly\";\n\n/**\n * How an API validates Authio access tokens.\n */\nexport interface AuthioVerifierOptions extends AuthioConnectionOptions, AuthioUserClaimSettings {\n /** The audiences this API accepts: its resource identifier (RFC 8707) or client id. Required unless `resource` is set. */\n audiences?: string | readonly string[];\n /**\n * The API's own resource identifier (RFC 8707), such as `https://orders.example.com`. Added to `audiences`, and\n * the `resource` of its protected resource metadata (RFC 9728).\n */\n resource?: string;\n /**\n * Points `401` challenges at the API's protected resource metadata (RFC 9728) with `resource_metadata`: `true`\n * for `{origin of resource}/.well-known/oauth-protected-resource{path of resource}`, or the URL itself. Off by default.\n */\n resourceMetadata?: boolean | string;\n /** Scopes every request must carry (all of them); `authioBearer` answers `403 insufficient_scope` otherwise. */\n requiredScopes?: readonly string[];\n /** Defaults to `none`. */\n introspection?: AuthioIntrospectionMode;\n /**\n * The API's confidential client, for introspection: a client already created, or its options (issuer settings are\n * taken from these options when absent). It must be the client the resource server names as its introspection\n * client, since Authio answers introspection according to who asks.\n */\n client?: AuthioClient | Omit<AuthioClientOptions, keyof AuthioConnectionOptions>;\n /** Seconds an active introspection answer is kept (never past the token's expiry). Defaults to 30. */\n introspectionCacheDuration?: number;\n /** Seconds of clock skew tolerated on `exp` and `nbf`. Defaults to 30. */\n clockSkew?: number;\n /**\n * The algorithm (or algorithms) access tokens are signed with, as the client registered in Authio signs them:\n * RS/PS/ES 256/384/512, or HS256/384/512 verified with the `clientSecret` of `client` (its UTF-8 octets, at least\n * 32, 48 or 64 bytes as RFC 7518 §3.2 asks). Only the client's own API holds that secret, so only it validates an HS*\n * token locally; any other API validates such tokens with introspection. Left out, the asymmetric algorithms of the\n * realm's keys are accepted, and never HS*.\n */\n accessTokenSignedResponseAlg?: string | readonly string[];\n /**\n * Refuses a token whose `typ` claim is present and not `Bearer` (an ID token, for one). Defaults to `true`. A JWT\n * whose header `typ` is not `at+jwt` (RFC 9068 §4) is refused whatever this says.\n */\n rejectNonAccessTokens?: boolean;\n /**\n * The private half of the encryption key Authio encrypts this API's access tokens to (the resource server's or its\n * client's), so encrypted tokens are decrypted and validated locally (RSA-OAEP, RSA-OAEP-256).\n */\n clientEncryptionKey?: AuthioEncryptionKeySource;\n /** A PEM or JWK file holding `clientEncryptionKey` (Node only). */\n clientEncryptionKeyPath?: string;\n /**\n * The key management algorithms (`alg`) decrypted. Defaults to RSA-OAEP and RSA-OAEP-256; RSA1_5 cannot be listed,\n * because Node 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 /** Accepted for parity with the other Authio SDKs; RSA1_5 stays refused, because Node cannot decrypt it. */\n allowLegacyEncryptionAlgorithms?: boolean;\n}\n\n/**\n * Validates Authio access tokens and reads the caller.\n */\nexport interface AuthioVerifier {\n /** The connection settings. */\n readonly connection: AuthioConnection;\n /** The discovery document. */\n readonly discovery: AuthioDiscoveryClient;\n /** The accepted audiences. */\n readonly audiences: readonly string[];\n /** The API's resource identifier, when configured. */\n readonly resource: string | undefined;\n /** The protected resource metadata URL sent in challenges, when turned on. */\n readonly resourceMetadataUrl: string | undefined;\n /** Scopes every request must carry. */\n readonly requiredScopes: readonly string[];\n /** The introspection mode. */\n readonly introspection: AuthioIntrospectionMode;\n /** The client used for introspection, when there is one. */\n readonly client: AuthioClient | undefined;\n /**\n * Validates a token and reads the caller.\n *\n * @throws AuthioBearerError when the token is not valid for this API.\n */\n verify(token: string, signal?: AbortSignal): Promise<AuthioUser>;\n /**\n * Validates the token of an `Authorization: Bearer` header.\n *\n * @throws AuthioBearerError without an error code when there is no bearer token, with `invalid_token` when it is\n * not valid.\n */\n verifyAuthorizationHeader(header: string | null | undefined, signal?: AbortSignal): Promise<AuthioUser>;\n}\n\n/**\n * Error descriptions of the refusals the SDK makes itself.\n */\nexport const AuthioBearerErrorDescriptions = {\n Inactive:\n \"Authio reports the token as not active to this API's client. It was revoked or has expired or its session ended; or this API's client is not the introspection client of the resource server the token is for.\",\n Unconfirmed: \"Authio could not be reached to confirm that the token is active.\",\n Empty: \"The token is empty.\",\n Encrypted: \"The token is encrypted; set clientEncryptionKey to decrypt it, or validate it with introspection ('introspectionOnly').\",\n SigningKeysUnavailable: \"Authio could not be reached to read its signing keys.\",\n Symmetric:\n \"The token is signed with the client's secret (HS*): set accessTokenSignedResponseAlg and the client's clientSecret to validate it locally, or validate it with introspection ('introspectionOnly').\",\n} as const;\n\nconst maxCachedAnswers = 10_000;\n\n/**\n * Creates a token verifier.\n *\n * @throws AuthioConfigurationError when no audience is given, or introspection is asked for without a client.\n */\nexport function createAuthioVerifier(options: AuthioVerifierOptions): AuthioVerifier {\n const resource = options.resource?.trim() || undefined;\n const given = typeof options.audiences === \"string\" ? [options.audiences] : [...(options.audiences ?? [])];\n const audiences = [...new Set([...given, ...(resource ? [resource] : [])].filter((value) => value?.trim()))];\n\n if (audiences.length === 0)\n throw new AuthioConfigurationError(\"The Authio verifier needs at least one audience: the API's resource identifier or client id.\");\n\n const connection = resolveConnection(options);\n const discovery = createAuthioDiscoveryClient(connection);\n const introspection = options.introspection ?? \"none\";\n const client = resolveClient(options);\n\n if (introspection !== \"none\" && !client)\n throw new AuthioConfigurationError(\n `Authio introspection ('${introspection}') needs the API's confidential client: pass options.client with its clientId and clientSecret or private key.`,\n );\n\n const resourceMetadataUrl = resolveResourceMetadata(options.resourceMetadata, resource);\n const cacheDurationMs = seconds(options.introspectionCacheDuration, 30, \"introspectionCacheDuration\");\n const clockSkew = seconds(options.clockSkew, 30, \"clockSkew\") / 1000;\n const algorithms = resolveAccessTokenAlgorithms(options.accessTokenSignedResponseAlg);\n const symmetric = algorithms?.filter((algorithm) => (AuthioHmacAlgorithms as readonly string[]).includes(algorithm)) ?? [];\n const clientSecret = symmetric.length > 0 ? resolveClientSecret(options, symmetric) : undefined;\n const rejectNonAccessTokens = options.rejectNonAccessTokens ?? true;\n const claimSettings: AuthioUserClaimSettings = { roleClaims: options.roleClaims, groupClaims: options.groupClaims };\n const cache = new Map<string, { result: AuthioIntrospectionResult; until: number }>();\n const signingKeys = createAuthioSigningKeys(connection, discovery);\n const encryptionKey =\n options.clientEncryptionKey ?? (options.clientEncryptionKeyPath ? encryptionKeyFromFile(options.clientEncryptionKeyPath) : undefined);\n const decrypt =\n encryptionKey === undefined\n ? undefined\n : createAuthioTokenDecrypter(encryptionKey, {\n setting: options.clientEncryptionKey === undefined ? \"clientEncryptionKeyPath\" : \"clientEncryptionKey\",\n allowLegacyEncryptionAlgorithms: options.allowLegacyEncryptionAlgorithms,\n encryptionAlgorithms: options.encryptionAlgorithms,\n encryptionMethods: options.encryptionMethods,\n });\n const requiredScopes = Object.freeze([...new Set((options.requiredScopes ?? []).filter((scope) => scope?.trim()))]);\n\n const introspect = async (token: string, key: string, signal?: AbortSignal): Promise<AuthioIntrospectionResult | undefined> => {\n const now = connection.clock.now();\n const cached = cache.get(key);\n\n if (cached && cached.until > now) return cached.result;\n\n cache.delete(key);\n\n const result = await client!.introspect(token, { tokenTypeHint: AuthioTokenTypes.AccessToken, signal });\n\n if (!result.active) return undefined;\n\n const until = Math.min(now + cacheDurationMs, typeof result.exp === \"number\" ? result.exp * 1000 : Number.POSITIVE_INFINITY);\n\n if (until > now) {\n if (cache.size >= maxCachedAnswers) cache.delete(cache.keys().next().value!);\n cache.set(key, { result, until });\n }\n\n return result;\n };\n\n const verifyJwt = async (token: string, signal?: AbortSignal): Promise<AuthioUser> => {\n let signed = token;\n\n if (isAuthioTokenEncrypted(token)) {\n if (!decrypt) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Encrypted, { reason: \"decryption_failed\" });\n\n try {\n signed = await decrypt(token);\n } catch (error) {\n if (error instanceof AuthioTokenValidationError) throw new AuthioBearerError(error.message, { cause: error, reason: error.reason });\n throw error;\n }\n }\n\n let keySet: Awaited<ReturnType<typeof signingKeys>>;\n\n try {\n keySet = withClientSecret(await signingKeys(signal), clientSecret);\n } catch (error) {\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.SigningKeysUnavailable, { cause: error, reason: \"signing_keys_unavailable\" });\n }\n\n let payload: JWTPayload;\n\n try {\n let header: Record<string, unknown>;\n\n ({ payload, header } = await verifyAuthioJwt(signed, keySet, {\n issuer: connection.issuer,\n audiences,\n algorithms,\n clockSkew,\n now: connection.clock.now(),\n }));\n\n requireAccessTokenType(header);\n } catch (error) {\n if (error instanceof AuthioTokenValidationError && error.reason === \"invalid_algorithm\" && symmetric.length === 0 && isSymmetricToken(signed))\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.Symmetric, { cause: error, reason: error.reason });\n if (error instanceof AuthioTokenValidationError) throw new AuthioBearerError(error.message, { cause: error, reason: error.reason });\n throw error;\n }\n\n const type = typeof payload.typ === \"string\" ? payload.typ : undefined;\n\n if (rejectNonAccessTokens && type !== undefined && type.toLowerCase() !== \"bearer\")\n throw new AuthioBearerError(`Only access tokens are accepted; this token's typ is '${type}'.`, { reason: \"not_access_token\" });\n\n if (introspection !== \"activeCheck\") return new AuthioUser(payload, claimSettings, token);\n\n const answer = await confirmActive(token, payload, signal);\n\n return new AuthioUser({ ...claimsOfIntrospection(answer), ...payload }, claimSettings, token);\n };\n\n const confirmActive = async (token: string, payload: JWTPayload, signal?: AbortSignal): Promise<AuthioIntrospectionResult> => {\n const key = payload.jti ? `jti:${payload.jti}` : await keyForToken(token);\n let result: AuthioIntrospectionResult | undefined;\n\n try {\n result = await introspect(token, key, signal);\n } catch (error) {\n if (signal?.aborted) throw error;\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.Unconfirmed, { cause: error, reason: \"unconfirmed\" });\n }\n\n if (!result) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Inactive, { reason: \"inactive\" });\n\n return result;\n };\n\n const verifyByIntrospection = async (token: string, signal?: AbortSignal): Promise<AuthioUser> => {\n let result: AuthioIntrospectionResult | undefined;\n\n try {\n result = await introspect(token, await keyForToken(token), signal);\n } catch (error) {\n if (signal?.aborted) throw error;\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.Unconfirmed, { cause: error, reason: \"unconfirmed\" });\n }\n\n if (!result) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Inactive, { reason: \"inactive\" });\n\n if (result.iss && result.iss !== connection.issuer) throw new AuthioBearerError(`The issuer '${result.iss}' is invalid`, { reason: \"invalid_issuer\" });\n\n const tokenAudiences = [result.aud ?? []].flat();\n\n if (!tokenAudiences.some((audience) => audiences.includes(audience)))\n throw new AuthioBearerError(describeAudience(tokenAudiences, audiences), { reason: \"invalid_audience\" });\n\n if (typeof result.exp === \"number\" && (result.exp + clockSkew) * 1000 <= connection.clock.now())\n throw new AuthioBearerError(`The token expired at '${new Date(result.exp * 1000).toISOString()}'`, { reason: \"expired\" });\n\n const claims = claimsOfIntrospection(result);\n const type = typeof claims.typ === \"string\" ? claims.typ : undefined;\n\n if (rejectNonAccessTokens && type !== undefined && !isAccessTokenType(type))\n throw new AuthioBearerError(`Only access tokens are accepted; this token's typ is '${type}'.`, { reason: \"not_access_token\" });\n\n return new AuthioUser(claims, claimSettings, token, \"introspection\");\n };\n\n const verify = async (token: string, signal?: AbortSignal): Promise<AuthioUser> => {\n try {\n if (typeof token !== \"string\" || !token.trim()) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Empty, { reason: \"malformed\" });\n\n return introspection === \"introspectionOnly\" ? await verifyByIntrospection(token.trim(), signal) : await verifyJwt(token.trim(), signal);\n } catch (error) {\n throw error instanceof AuthioBearerError ? error.withResourceMetadata(resourceMetadataUrl) : error;\n }\n };\n\n return {\n connection,\n discovery,\n audiences,\n resource,\n resourceMetadataUrl,\n requiredScopes,\n introspection,\n client,\n verify,\n async verifyAuthorizationHeader(header, signal) {\n const token = readBearerToken(header);\n\n if (token === undefined) throw new AuthioBearerError(undefined, { error: undefined, resourceMetadata: resourceMetadataUrl });\n\n return verify(token, signal);\n },\n };\n}\n\n/**\n * The token of an `Authorization: Bearer` header, or `undefined` when the header is absent or of another scheme.\n */\nexport function readBearerToken(header: string | null | undefined): string | undefined {\n const match = /^\\s*Bearer\\s+(\\S+)\\s*$/i.exec(header ?? \"\");\n\n return match?.[1];\n}\n\n/**\n * The cache key of a token: `token:` and the hex SHA-256 of the token.\n *\n * @internal\n */\nexport async function keyForToken(token: string): Promise<string> {\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(token)));\n\n return `token:${[...digest].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction resolveResourceMetadata(setting: boolean | string | undefined, resource: string | undefined): string | undefined {\n if (!setting) return undefined;\n if (typeof setting === \"string\") return setting;\n if (!resource)\n throw new AuthioConfigurationError(\"resourceMetadata: true needs the API's resource identifier: set options.resource, or pass the metadata URL.\");\n\n return protectedResourceMetadataUrl(resource);\n}\n\nfunction resolveAccessTokenAlgorithms(setting: string | readonly string[] | undefined): string[] | undefined {\n const algorithms = [...new Set((typeof setting === \"string\" ? [setting] : [...(setting ?? [])]).map((algorithm) => algorithm.trim()).filter(Boolean))];\n const known = [...AuthioAsymmetricAlgorithms, ...AuthioHmacAlgorithms] as readonly string[];\n\n for (const algorithm of algorithms)\n if (!known.includes(algorithm))\n throw new AuthioConfigurationError(`The Authio accessTokenSignedResponseAlg '${algorithm}' is not one of ${known.join(\", \")}.`);\n\n return algorithms.length > 0 ? algorithms : undefined;\n}\n\nfunction resolveClientSecret(options: AuthioVerifierOptions, symmetric: readonly string[]): () => Promise<string> {\n const given = options.client;\n const source = given && !isClient(given) ? given.clientSecret : undefined;\n\n if (!source)\n throw new AuthioConfigurationError(\n `accessTokenSignedResponseAlg ${symmetric.join(\", \")} is verified with the client secret: pass options.client as { clientId, clientSecret } (an AuthioClient does not expose its secret).`,\n );\n\n if (typeof source === \"string\") for (const algorithm of symmetric) requireHmacSecretLength(algorithm, new TextEncoder().encode(source).length);\n\n return async () => {\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}\n\nfunction isSymmetricToken(token: string): boolean {\n try {\n return (AuthioHmacAlgorithms as readonly string[]).includes(String(decodeProtectedHeader(token).alg));\n } catch {\n return false;\n }\n}\n\nfunction resolveClient(options: AuthioVerifierOptions): AuthioClient | undefined {\n const given = options.client;\n\n if (!given) return undefined;\n if (isClient(given)) return given;\n\n return createAuthioClient({\n ...given,\n issuer: options.issuer,\n authority: options.authority,\n realm: options.realm,\n requireHttps: options.requireHttps,\n discoveryCacheDuration: options.discoveryCacheDuration,\n httpTimeout: options.httpTimeout,\n fetch: options.fetch,\n clock: options.clock,\n } as AuthioClientOptions);\n}\n\nfunction isClient(value: unknown): value is AuthioClient {\n return typeof (value as AuthioClient).introspect === \"function\" && typeof (value as AuthioClient).tokens === \"object\";\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","import {\n AuthioConfigurationError,\n AuthioWebhookHeaders,\n systemClock,\n tryParseWebhookEvent,\n verifyWebhookSignature,\n type AuthioClock,\n type AuthioTypedWebhookEvent,\n type AuthioWebhookDataByType,\n type AuthioWebhookEvent,\n} from \"@hyper.authio/client\";\n\n/**\n * Remembers delivered event ids, so a redelivery is acknowledged without running the handlers twice.\n */\nexport interface AuthioWebhookDeduplicationStore {\n /** Records the id; `false` when it was already recorded within the window. */\n tryBegin(eventId: string, windowMs: number): boolean | Promise<boolean>;\n /** Forgets the id, after a handler failed, so the redelivery runs again. */\n release(eventId: string): void | Promise<void>;\n}\n\n/**\n * How webhook deliveries are received.\n */\nexport interface AuthioWebhookOptions {\n /** The webhook's secret. */\n secret?: string;\n /** Several secrets, while one is being rotated; a delivery signed with any of them is accepted. */\n secrets?: readonly string[];\n /** Seconds a signature's timestamp may differ from now. Defaults to 300. */\n tolerance?: number;\n /** `memory` (default), `none`, or a store shared between instances. */\n deduplication?: \"memory\" | \"none\" | AuthioWebhookDeduplicationStore;\n /** Seconds a delivered id is remembered. Defaults to 86400. */\n deduplicationWindow?: number;\n /** The largest body accepted, in bytes. Defaults to 1 MiB. */\n maxBodySize?: number;\n /** The clock. */\n clock?: AuthioClock;\n /** Called when a delivery is refused or a handler fails. */\n onError?: (error: unknown, context: { reason: string; eventId?: string; eventType?: string }) => void;\n}\n\n/**\n * A handler of one event type, or of every type.\n */\nexport type AuthioWebhookHandler<E extends AuthioWebhookEvent = AuthioWebhookEvent> = (event: E) => void | Promise<void>;\n\n/**\n * What to answer a delivery with.\n */\nexport interface AuthioWebhookOutcome {\n /** `200` handled, duplicate or ping; `400` unreadable; `401` bad or stale signature; `413` too large; `500` a handler failed. */\n readonly status: 200 | 400 | 401 | 413 | 500;\n /** Why, for logs. */\n readonly reason: \"handled\" | \"duplicate\" | \"unreadable\" | \"unsigned\" | \"too_large\" | \"handler_failed\";\n readonly event?: AuthioWebhookEvent;\n}\n\n/**\n * Receives Authio webhook deliveries: verifies, deduplicates and dispatches them.\n */\nexport interface AuthioWebhooks {\n /** Handles one event type, typed. */\n on<T extends keyof AuthioWebhookDataByType>(type: T, handler: AuthioWebhookHandler<AuthioTypedWebhookEvent<T>>): AuthioWebhooks;\n /** Handles another event type, or `*` for every type. */\n on(type: string, handler: AuthioWebhookHandler): AuthioWebhooks;\n /**\n * Handles a delivery: the body exactly as received and the request headers.\n */\n handle(delivery: { body: string | Uint8Array; headers: Headers | Record<string, string | string[] | undefined> }): Promise<AuthioWebhookOutcome>;\n /** The largest body accepted, in bytes. */\n readonly maxBodySize: number;\n}\n\n/**\n * Creates a webhook receiver. Handlers run in registration order; a `*` handler sees every event.\n *\n * @throws AuthioConfigurationError when no secret is configured.\n */\nexport function createAuthioWebhooks(options: AuthioWebhookOptions): AuthioWebhooks {\n const secrets = [...new Set([options.secret, ...(options.secrets ?? [])].filter((secret): secret is string => !!secret?.trim()))];\n\n if (secrets.length === 0) throw new AuthioConfigurationError(\"Authio webhooks need the webhook's secret.\");\n\n const clock = options.clock ?? systemClock;\n const tolerance = options.tolerance ?? 300;\n const windowMs = (options.deduplicationWindow ?? 86_400) * 1000;\n const maxBodySize = options.maxBodySize ?? 1024 * 1024;\n const store = resolveStore(options.deduplication ?? \"memory\", clock);\n const handlers: { type: string; handler: AuthioWebhookHandler }[] = [];\n\n const webhooks: AuthioWebhooks = {\n maxBodySize,\n on(type: string, handler: AuthioWebhookHandler) {\n if (!type) throw new TypeError(\"An event type (or '*') is required.\");\n\n handlers.push({ type, handler });\n return webhooks;\n },\n async handle(delivery) {\n const body = typeof delivery.body === \"string\" ? new TextEncoder().encode(delivery.body) : delivery.body;\n\n if (body.byteLength > maxBodySize) return { status: 413, reason: \"too_large\" };\n\n const signature = headerOf(delivery.headers, AuthioWebhookHeaders.Signature);\n let refusal = \"no webhook secret matched\";\n\n for (const secret of secrets) {\n const result = await verifyWebhookSignature(signature, body, secret, { tolerance, now: clock.now() });\n\n if (result.valid) {\n refusal = \"\";\n break;\n }\n\n refusal = result.reason;\n }\n\n if (refusal) {\n options.onError?.(new Error(refusal), { reason: \"unsigned\" });\n return { status: 401, reason: \"unsigned\" };\n }\n\n const event = tryParseWebhookEvent(body);\n\n if (!event) return { status: 400, reason: \"unreadable\" };\n\n const eventId = headerOf(delivery.headers, AuthioWebhookHeaders.EventId)?.trim() || String(event.id ?? \"\");\n\n if (eventId && !(await store.tryBegin(eventId, windowMs))) return { status: 200, reason: \"duplicate\", event };\n\n try {\n for (const { type, handler } of handlers) if (type === \"*\" || type === event.type) await handler(event);\n } catch (error) {\n if (eventId) await store.release(eventId);\n options.onError?.(error, { reason: \"handler_failed\", eventId, eventType: event.type });\n return { status: 500, reason: \"handler_failed\", event };\n }\n\n return { status: 200, reason: \"handled\", event };\n },\n };\n\n return webhooks;\n}\n\n/**\n * A deduplication store kept in this process's memory.\n */\nexport function createMemoryDeduplicationStore(clock: AuthioClock = systemClock): AuthioWebhookDeduplicationStore {\n const seen = new Map<string, number>();\n\n return {\n tryBegin(eventId, windowMs) {\n const now = clock.now();\n\n for (const [id, until] of seen) {\n if (until > now) break;\n seen.delete(id);\n }\n\n const until = seen.get(eventId);\n\n if (until !== undefined && until > now) return false;\n\n seen.delete(eventId);\n seen.set(eventId, now + windowMs);\n return true;\n },\n release(eventId) {\n seen.delete(eventId);\n },\n };\n}\n\nfunction resolveStore(deduplication: NonNullable<AuthioWebhookOptions[\"deduplication\"]>, clock: AuthioClock): AuthioWebhookDeduplicationStore {\n if (deduplication === \"none\") return { tryBegin: () => true, release: () => undefined };\n if (deduplication === \"memory\") return createMemoryDeduplicationStore(clock);\n\n return deduplication;\n}\n\nfunction headerOf(headers: Headers | Record<string, string | string[] | undefined>, name: string): string | 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 | string[] | undefined>)) {\n if (key.toLowerCase() === wanted) return Array.isArray(value) ? value[0] : value;\n }\n\n return undefined;\n}\n","import {\n AuthioDefaults,\n AuthioError,\n AuthioOAuthErrors,\n parseAuthioBearerChallenge,\n seconds,\n toClientCredentialsToken,\n toScopeString,\n type AuthioClient,\n type AuthioClientCredentialsToken,\n} from \"@hyper.authio/client\";\nimport type { AuthioUser } from \"./user.js\";\nimport { keyForToken } from \"./verifier.js\";\n\n/**\n * Who a downstream call is made for: a caller read by the verifier, or the incoming access token itself.\n */\nexport type AuthioDownstreamSubject = AuthioUser | string;\n\n/**\n * A `fetch` that forwards the caller's own access token, unchanged, to a downstream API that accepts the same\n * audience. Sends no `Authorization` when there is no token.\n */\nexport function createForwardingFetch(subject: AuthioDownstreamSubject | undefined, inner: typeof fetch = globalThis.fetch): typeof fetch {\n const token = tokenOf(subject);\n\n return (input, init) => {\n if (!token) return inner(input, init);\n\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n\n headers.set(\"authorization\", `Bearer ${token}`);\n\n return inner(input, { ...init, headers });\n };\n}\n\n/**\n * Exchanges the caller's token for one addressed to a downstream API (RFC 8693), and caches it.\n */\nexport interface AuthioOnBehalfOf {\n /**\n * A token for the downstream API on the caller's behalf: cached per incoming `jti` (else token hash), resource and\n * sorted scopes, renewed `tokenRefreshSkew` before expiry (at most half its lifetime); concurrent callers share\n * one exchange.\n *\n * @throws AuthioError when there is no incoming token.\n */\n getToken(subject: AuthioDownstreamSubject | undefined, signal?: AbortSignal): Promise<AuthioClientCredentialsToken>;\n /** Drops a cached token; with `accessToken`, only when the cache still holds that token. */\n invalidate(subject: AuthioDownstreamSubject, accessToken?: string): Promise<void>;\n /** A `fetch` that sends the exchanged token, and on a `401` drops it and retries once. */\n fetch(subject: AuthioDownstreamSubject | undefined, inner?: typeof fetch): typeof fetch;\n}\n\n/**\n * Creates an on-behalf-of exchanger.\n *\n * @param options `client` (the API's confidential client), the downstream `resource` and `scopes`.\n */\nexport function createOnBehalfOf(options: { client: AuthioClient; resource?: string; scopes?: Iterable<string> | string; tokenRefreshSkew?: number }): AuthioOnBehalfOf {\n const { client } = options;\n const scope = toScopeString(options.scopes);\n const sortedScope = (scope ?? \"\").split(\" \").filter(Boolean).sort().join(\" \");\n const skewMs = seconds(options.tokenRefreshSkew, AuthioDefaults.TokenRefreshSkew, \"tokenRefreshSkew\");\n const entries = new Map<string, AuthioClientCredentialsToken>();\n const pending = new Map<string, Promise<AuthioClientCredentialsToken>>();\n\n const keyOf = async (subject: AuthioDownstreamSubject) => {\n const token = tokenOf(subject)!;\n const jti = typeof subject === \"string\" ? undefined : subject.tokenId;\n\n return `${jti ? `jti:${jti}` : await keyForToken(token)}|${options.resource ?? \"\"}|${sortedScope}`;\n };\n\n const getToken: AuthioOnBehalfOf[\"getToken\"] = async (subject, signal) => {\n const incoming = tokenOf(subject);\n\n if (!incoming) throw new AuthioError(\"On-behalf-of needs the caller's access token, and the request has none.\");\n\n const key = await keyOf(subject!);\n const cached = entries.get(key);\n\n if (cached && client.connection.clock.now() < cached.refreshAt) return cached;\n\n let request = pending.get(key);\n\n if (!request) {\n request = client.tokens\n .exchange({ subjectToken: incoming, scopes: scope, resource: options.resource, signal })\n .then((response) => {\n const token = toClientCredentialsToken(response, client.connection.clock.now(), skewMs);\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\n const invalidate: AuthioOnBehalfOf[\"invalidate\"] = async (subject, accessToken) => {\n const key = await keyOf(subject);\n\n if (accessToken === undefined || entries.get(key)?.accessToken === accessToken) entries.delete(key);\n };\n\n return {\n getToken,\n invalidate,\n fetch(subject, inner = client.connection.fetch) {\n return async (input, init) => {\n const request = new Request(input, init);\n const body = request.body ? await request.arrayBuffer() : undefined;\n const attempt = (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 getToken(subject, request.signal);\n const response = await attempt(token);\n\n if (response.status !== 401 || isStepUpChallenge(response)) return response;\n\n await invalidate(subject!, token.accessToken);\n\n return attempt(await getToken(subject, request.signal));\n };\n },\n };\n}\n\n/**\n * Whether a `401` asks for a stronger or more recent sign-in (RFC 9470 §3), which a new exchanged token cannot satisfy.\n */\nfunction isStepUpChallenge(response: Response): boolean {\n return parseAuthioBearerChallenge(response.headers.get(\"www-authenticate\"))?.error === AuthioOAuthErrors.InsufficientUserAuthentication;\n}\n\nfunction tokenOf(subject: AuthioDownstreamSubject | undefined): string | undefined {\n if (!subject) return undefined;\n\n return typeof subject === \"string\" ? subject : subject.token;\n}\n"]}
|