@hyper.authio/server 0.0.0-stage → 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/user.ts","../src/rules.ts","../src/errors.ts","../src/verifier.ts","../src/webhooks.ts","../src/downstream.ts"],"names":["AuthioClaimTypes","parseResourceAccess","seconds","AuthioError","AuthioConfigurationError","resolveConnection","createAuthioDiscoveryClient","client","AuthioAsymmetricAlgorithms","AuthioTokenTypes","createRemoteJWKSet","customFetch","isAuthioTokenEncrypted","jwtVerify","createAuthioClient","errors","decodeProtectedHeader","systemClock","AuthioWebhookHeaders","verifyWebhookSignature","tryParseWebhookEvent","until","toScopeString","AuthioDefaults","toClientCredentialsToken","token"],"mappings":";;;;;;AAgCO,IAAM,aAAN,MAAiB;AAAA;AAAA,EAEb,OAAA;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,aAAA;AAAA,EACA,IAAA;AAAA,EACA,iBAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,YAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EAIQ,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjB,WAAA,CAAY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AA,GAAW,OAAA,GAAU,OAAA,CAAQ,KAAA;AACzD","file":"index.cjs","sourcesContent":["import { AuthioClaimTypes, parseResourceAccess, type AuthioResourceAccess, type AuthioResourceAccessSource } 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 readonly actor: AuthioActor | undefined;\n}\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 or an introspection answer: identity, every form of\n * permission Authio 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 /** The client the token was issued to (`azp`, else `client_id`). */\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 /** Every claim, as the token or the introspection answer carried it. */\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 */\n constructor(claims: Readonly<Record<string, unknown>>, settings: AuthioUserClaimSettings = {}, token?: string) {\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.AuthorizedParty) ?? text(AuthioClaimTypes.ClientId);\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\n Object.defineProperty(this, \"token\", { value: token, enumerable: false });\n }\n\n /** Whether an actor exchanged the token on the subject's behalf. */\n get isDelegated(): boolean {\n return this.actor !== undefined;\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, isDelegated: this.isDelegated };\n }\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 : undefined,\n subject: typeof record.sub === \"string\" ? record.sub : undefined,\n actor: readActor(record.act, depth + 1),\n });\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 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}\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, and the error is the one asking for a stronger\n * sign-in, else the first one that has an error.\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 bearer = failures.find((failure) => failure.error === \"insufficient_user_authentication\") ?? failures.find((failure) => failure.error);\n\n return {\n message: failures.map((failure) => failure.message).join(\" \"),\n ...(bearer?.error ? { error: bearer.error } : {}),\n ...(bearer?.scope ? { scope: bearer.scope } : {}),\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.\n */\nexport function requireAuthenticationLevel(minimumLevel: number): AuthioRule {\n if (!Number.isInteger(minimumLevel) || minimumLevel < 0) throw new RangeError(\"The minimum level must be a non-negative integer.\");\n\n return {\n description: `Authio authentication level >= ${minimumLevel}`,\n check: (user) =>\n user.authenticationLevel !== undefined && user.authenticationLevel >= minimumLevel\n ? undefined\n : { message: `The authentication level must be at least ${minimumLevel}.`, error: \"insufficient_user_authentication\" },\n };\n}\n\n/**\n * Requires authentication methods (`amr`, case-insensitive), such as `otp`, `swk` or `fed`.\n */\nexport function requireAuthenticationMethod(methods: string | readonly string[], match: AuthioMatch = \"any\"): AuthioRule {\n const required = listOf(methods, \"authentication method\");\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 : { message: `The user must authenticate with (${match}): ${required.join(\", \")}.`, error: \"insufficient_user_authentication\" };\n },\n };\n}\n\n/**\n * Requires the token to have been issued to one of the clients (`azp`, else `client_id`).\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 describeSources(sources: readonly AuthioResourceAccessSource[] | undefined): string {\n return sources && sources.length > 0 ? ` from ${[...new Set(sources)].join(\", \")}` : \"\";\n}\n","import { AuthioError } 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\n constructor(description: string | undefined, options: { error?: \"invalid_token\" | undefined; cause?: unknown } = {}) {\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 }\n\n /** The `WWW-Authenticate` value. */\n get wwwAuthenticate(): string {\n if (!this.error) return \"Bearer\";\n\n return this.description ? `Bearer error=\"${this.error}\", error_description=\"${this.description}\"` : `Bearer error=\"${this.error}\"`;\n }\n}\n\n/**\n * The caller is known but not allowed: answer `403`, with `wwwAuthenticate` when the refusal has a bearer error.\n */\nexport class AuthioForbiddenError extends AuthioError {\n readonly status = 403;\n readonly failure: AuthioRuleFailure;\n\n constructor(failure: AuthioRuleFailure) {\n super(failure.message);\n this.failure = failure;\n }\n\n /** The `WWW-Authenticate` value, or `undefined` when the refusal is not about scopes or the sign-in. */\n get wwwAuthenticate(): string | undefined {\n return toForbiddenChallenge(this.failure);\n }\n}\n\n/**\n * The `WWW-Authenticate` value of a refusal: `insufficient_scope` (with `scope`) or\n * `insufficient_user_authentication`.\n */\nexport function toForbiddenChallenge(failure: AuthioRuleFailure): string | undefined {\n if (!failure.error) return undefined;\n\n const value = `Bearer error=\"${failure.error}\", error_description=\"${escapeQuoted(failure.message)}\"`;\n\n return failure.scope ? `${value}, scope=\"${escapeQuoted(failure.scope)}\"` : value;\n}\n\n/**\n * Problem details (RFC 9457) for a `401` or `403`.\n */\nexport function toProblemDetails(error: AuthioBearerError | AuthioForbiddenError): Record<string, unknown> {\n if (error instanceof AuthioBearerError)\n return {\n type: \"https://tools.ietf.org/html/rfc9110#section-15.5.2\",\n title: \"Unauthorized\",\n status: 401,\n detail: \"A valid Authio access token is required.\",\n };\n\n return {\n type: \"https://tools.ietf.org/html/rfc9110#section-15.5.4\",\n title: \"Forbidden\",\n status: 403,\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 };\n}\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 {\n AuthioAsymmetricAlgorithms,\n AuthioConfigurationError,\n AuthioError,\n AuthioTokenTypes,\n createAuthioClient,\n createAuthioDiscoveryClient,\n isAuthioTokenEncrypted,\n resolveConnection,\n seconds,\n type AuthioClient,\n type AuthioClientOptions,\n type AuthioConnection,\n type AuthioConnectionOptions,\n type AuthioDiscoveryClient,\n type AuthioIntrospectionResult,\n} from \"@hyper.authio/client\";\nimport { createRemoteJWKSet, customFetch, decodeProtectedHeader, errors, jwtVerify, type JWTPayload } from \"jose\";\nimport { AuthioBearerError } from \"./errors.js\";\nimport { AuthioUser, 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). Fastest; a revoked token stays\n * valid until it expires.\n * - `activeCheck`: validated locally, then confirmed active by introspection (cached per `jti`).\n * - `introspectionOnly`: introspection alone, for opaque (reference) or encrypted tokens.\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. */\n audiences: string | 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 /** Accepted signing algorithms. Defaults to the asymmetric ones (RS*, PS*, ES*). */\n validAlgorithms?: readonly string[];\n /** Refuses a token whose `typ` claim is present and not `Bearer` (an ID token, for one). Defaults to `true`. */\n rejectNonAccessTokens?: 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 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; validate it with introspection ('introspectionOnly').\",\n SigningKeysUnavailable: \"Authio could not be reached to read its signing keys.\",\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 audiences = [...new Set((typeof options.audiences === \"string\" ? [options.audiences] : [...(options.audiences ?? [])]).filter((value) => value?.trim()))];\n\n if (audiences.length === 0) 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 cacheDurationMs = seconds(options.introspectionCacheDuration, 30, \"introspectionCacheDuration\");\n const clockSkew = seconds(options.clockSkew, 30, \"clockSkew\") / 1000;\n const algorithms = options.validAlgorithms && options.validAlgorithms.length > 0 ? [...options.validAlgorithms] : [...AuthioAsymmetricAlgorithms];\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 let keys: { uri: string; set: ReturnType<typeof createRemoteJWKSet> } | undefined;\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 signingKeys = async (signal?: AbortSignal) => {\n const document = await discovery.get(signal);\n const uri = document.jwks_uri;\n\n if (!uri) throw new AuthioError(\"The Authio discovery document has no jwks_uri.\");\n\n if (!keys || keys.uri !== uri) keys = { uri, set: createRemoteJWKSet(new URL(uri), { [customFetch]: connection.fetch, timeoutDuration: connection.httpTimeoutMs }) };\n\n return keys.set;\n };\n\n const verifyJwt = async (token: string, signal?: AbortSignal): Promise<AuthioUser> => {\n if (isAuthioTokenEncrypted(token)) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Encrypted);\n\n let keySet: Awaited<ReturnType<typeof signingKeys>>;\n\n try {\n keySet = await signingKeys(signal);\n } catch (error) {\n throw new AuthioBearerError(AuthioBearerErrorDescriptions.SigningKeysUnavailable, { cause: error });\n }\n\n let payload: JWTPayload;\n\n try {\n ({ payload } = await jwtVerify(token, keySet, {\n issuer: connection.issuer,\n audience: audiences,\n algorithms,\n clockTolerance: clockSkew,\n requiredClaims: [\"exp\"],\n currentDate: new Date(connection.clock.now()),\n }));\n } catch (error) {\n throw new AuthioBearerError(describeJwtFailure(error, audiences, token), { cause: 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}'.`);\n\n if (introspection === \"activeCheck\") await confirmActive(token, payload, signal);\n\n return new AuthioUser(payload, claimSettings, token);\n };\n\n const confirmActive = async (token: string, payload: JWTPayload, signal?: AbortSignal) => {\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 });\n }\n\n if (!result) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Inactive);\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 });\n }\n\n if (!result) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Inactive);\n\n if (result.iss && result.iss !== connection.issuer) throw new AuthioBearerError(`The issuer '${result.iss}' is invalid`);\n\n const tokenAudiences = [result.aud ?? []].flat();\n\n if (!tokenAudiences.some((audience) => audiences.includes(audience))) throw new AuthioBearerError(describeAudience(tokenAudiences, audiences));\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()}'`);\n\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) 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 const type = typeof claims.typ === \"string\" ? claims.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}'.`);\n\n return new AuthioUser(claims, claimSettings, token);\n };\n\n const verify = async (token: string, signal?: AbortSignal): Promise<AuthioUser> => {\n if (typeof token !== \"string\" || !token.trim()) throw new AuthioBearerError(AuthioBearerErrorDescriptions.Empty);\n\n return introspection === \"introspectionOnly\" ? verifyByIntrospection(token.trim(), signal) : verifyJwt(token.trim(), signal);\n };\n\n return {\n connection,\n discovery,\n audiences,\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 });\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 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 describeJwtFailure(error: unknown, audiences: readonly string[], token: string): string | undefined {\n if (error instanceof errors.JWTExpired) {\n const exp = error.payload.exp;\n\n return typeof exp === \"number\" ? `The token expired at '${new Date(exp * 1000).toISOString()}'` : \"The token has expired\";\n }\n\n if (error instanceof errors.JWTClaimValidationFailed) {\n switch (error.claim) {\n case \"aud\":\n return describeAudience([error.payload.aud ?? []].flat(), audiences);\n case \"iss\":\n return `The issuer '${error.payload.iss ?? \"\"}' is invalid`;\n case \"nbf\":\n return typeof error.payload.nbf === \"number\" ? `The token is not valid before '${new Date(error.payload.nbf * 1000).toISOString()}'` : \"The token is not valid yet\";\n case \"exp\":\n return \"The token has no expiration\";\n default:\n return `The token's ${error.claim} claim is invalid`;\n }\n }\n\n if (error instanceof errors.JWSSignatureVerificationFailed) return \"The signature is invalid\";\n if (error instanceof errors.JWKSNoMatchingKey) return \"The signature key was not found\";\n if (error instanceof errors.JOSEAlgNotAllowed) return `The algorithm '${algorithmOf(token)}' is not available`;\n if (error instanceof errors.JWKSTimeout || error instanceof errors.JWKSInvalid) return AuthioBearerErrorDescriptions.SigningKeysUnavailable;\n if (error instanceof errors.JWTInvalid || error instanceof errors.JWSInvalid) return \"The token is malformed\";\n\n return undefined;\n}\n\nfunction describeAudience(tokenAudiences: readonly string[], audiences: readonly string[]): string {\n const known = tokenAudiences.length === 0 ? \"\" : ` ${tokenAudiences.map((audience) => `'${audience}'`).join(\" and \")}`;\n const accepted = audiences.map((audience) => `'${audience}'`).join(\" or \");\n\n return audiences.length === 1\n ? `The token is not addressed to this API: its audience${known} is not ${accepted}. Request the token for that resource (RFC 8707).`\n : `The token is not addressed to this API: its audience${known} is not ${accepted}. Request the token for one of those resources (RFC 8707).`;\n}\n\nfunction algorithmOf(token: string): string {\n try {\n return String(decodeProtectedHeader(token).alg ?? \"\");\n } catch {\n return \"\";\n }\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 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) return response;\n\n await invalidate(subject!, token.accessToken);\n\n return attempt(await getToken(subject, request.signal));\n };\n },\n };\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"]}
@@ -0,0 +1,439 @@
1
+ import { AuthioResourceAccess, AuthioResourceAccessSource, AuthioError, AuthioConnection, AuthioDiscoveryClient, AuthioClient, AuthioConnectionOptions, AuthioClientOptions, AuthioWebhookEvent, AuthioClock, AuthioWebhookDataByType, AuthioTypedWebhookEvent, AuthioClientCredentialsToken } from '@hyper.authio/client';
2
+
3
+ /**
4
+ * The party acting for the subject, from the `act` claim (RFC 8693): who exchanged the token, nested when the chain
5
+ * is longer.
6
+ */
7
+ interface AuthioActor {
8
+ readonly clientId: string | undefined;
9
+ readonly subject: string | undefined;
10
+ readonly actor: AuthioActor | undefined;
11
+ }
12
+ /**
13
+ * Where the user reads flat (non-`*_resource_access`) roles and groups from.
14
+ */
15
+ interface AuthioUserClaimSettings {
16
+ /**
17
+ * Claims holding role names directly, such as one written by a claim mapper with the Role source. They count for
18
+ * `hasRole` without a source filter. Defaults to `["role"]`.
19
+ */
20
+ roleClaims?: readonly string[];
21
+ /**
22
+ * Claims holding group names, such as one written by a claim mapper with the Group source. Defaults to
23
+ * `["groups"]`.
24
+ */
25
+ groupClaims?: readonly string[];
26
+ }
27
+ /**
28
+ * The caller of an API, read from a validated access token or an introspection answer: identity, every form of
29
+ * permission Authio issues, and the raw claims for anything else.
30
+ */
31
+ declare class AuthioUser {
32
+ /** `sub`: the person's id, or the credential's for a machine caller. */
33
+ readonly subject: string;
34
+ /** The client the token was issued to (`azp`, else `client_id`). */
35
+ readonly clientId: string | undefined;
36
+ /** `sid`. */
37
+ readonly sessionId: string | undefined;
38
+ /** `jti`. */
39
+ readonly tokenId: string | undefined;
40
+ /** `aud`. */
41
+ readonly audiences: readonly string[];
42
+ /** The granted scopes. */
43
+ readonly scopes: readonly string[];
44
+ /** The roles of the seven `*_resource_access` claims, with their source and permissions. */
45
+ readonly resourceAccess: AuthioResourceAccess;
46
+ /** Every role name: the `*_resource_access` roles, then the flat role claims. */
47
+ readonly roles: readonly string[];
48
+ /** Resource → every method any role allows on it. */
49
+ readonly permissions: Readonly<Record<string, readonly string[]>>;
50
+ /** The group names of the group claims. */
51
+ readonly groups: readonly string[];
52
+ /** `org_id`. */
53
+ readonly organizationId: string | undefined;
54
+ /** `org_alias`. */
55
+ readonly organizationAlias: string | undefined;
56
+ /** `account_id`. */
57
+ readonly accountId: string | undefined;
58
+ /** `acr`. */
59
+ readonly acr: string | undefined;
60
+ /** `acr` as a number: 1 one factor, 2 several, 3 one of them phishing-resistant. */
61
+ readonly authenticationLevel: number | undefined;
62
+ /** `amr`. */
63
+ readonly authenticationMethods: readonly string[];
64
+ /** `idp`. */
65
+ readonly identityProvider: string | undefined;
66
+ /** `auth_time`. */
67
+ readonly authenticatedAt: Date | undefined;
68
+ /** `act`. */
69
+ readonly actor: AuthioActor | undefined;
70
+ /** `delegation_id`. */
71
+ readonly delegationId: string | undefined;
72
+ readonly email: string | undefined;
73
+ readonly emailVerified: boolean | undefined;
74
+ readonly name: string | undefined;
75
+ readonly preferredUsername: string | undefined;
76
+ /** `credential_type`, on a token issued to an account credential or a consumer. */
77
+ readonly credentialType: string | undefined;
78
+ /** `credential_id`. */
79
+ readonly credentialId: string | undefined;
80
+ /** Every claim, as the token or the introspection answer carried it. */
81
+ readonly claims: Readonly<Record<string, unknown>>;
82
+ /** The access token the user was read from. Not enumerable, so it stays out of logs and JSON. */
83
+ readonly token: string | undefined;
84
+ private readonly flatRoles;
85
+ /**
86
+ * @param claims The token's payload, or the introspection answer's members.
87
+ * @param settings Where flat roles and groups are read from.
88
+ * @param token The access token, kept for forwarding and on-behalf-of.
89
+ */
90
+ constructor(claims: Readonly<Record<string, unknown>>, settings?: AuthioUserClaimSettings, token?: string);
91
+ /** Whether an actor exchanged the token on the subject's behalf. */
92
+ get isDelegated(): boolean;
93
+ /** Whether the scope was granted. */
94
+ hasScope(scope: string): boolean;
95
+ /**
96
+ * Whether the user holds the role. Without sources, from any `*_resource_access` claim or a flat role claim; with
97
+ * sources, only from those `*_resource_access` claims.
98
+ */
99
+ hasRole(role: string, options?: {
100
+ sources?: readonly AuthioResourceAccessSource[];
101
+ }): boolean;
102
+ /**
103
+ * Authio's grant rule: whether a role (from any source, or only from the given ones) allows `method` on
104
+ * `resource`. Case-insensitive.
105
+ */
106
+ hasPermission(resource: string, method: string, options?: {
107
+ sources?: readonly AuthioResourceAccessSource[];
108
+ }): boolean;
109
+ /** Whether the user is in the group (exact match). */
110
+ hasGroup(group: string): boolean;
111
+ /**
112
+ * Whether the claim is present (not `null`), and, given values, whether it holds one of them (exact match; an
113
+ * array claim matches when any item does).
114
+ */
115
+ hasClaim(type: string, ...values: string[]): boolean;
116
+ /**
117
+ * The claim's values as text: one for a scalar, one per item for an array, JSON text for an object.
118
+ */
119
+ claimValues(type: string): string[];
120
+ /** Every member but the raw token. */
121
+ toJSON(): Record<string, unknown>;
122
+ }
123
+
124
+ /**
125
+ * How several required values combine.
126
+ */
127
+ type AuthioMatch = "any" | "all";
128
+ /**
129
+ * Why a rule refused the caller.
130
+ */
131
+ interface AuthioRuleFailure {
132
+ /** What is missing, in words. */
133
+ readonly message: string;
134
+ /**
135
+ * The RFC 6750 / RFC 9470 error to put in `WWW-Authenticate`: `insufficient_scope` for scopes,
136
+ * `insufficient_user_authentication` for `acr`/`amr`, none otherwise.
137
+ */
138
+ readonly error?: "insufficient_scope" | "insufficient_user_authentication";
139
+ /** The required scopes, for `insufficient_scope`. */
140
+ readonly scope?: string;
141
+ }
142
+ /**
143
+ * A condition on the caller.
144
+ */
145
+ interface AuthioRule {
146
+ /** What the rule requires, for logs. */
147
+ readonly description: string;
148
+ /** `undefined` when the caller satisfies the rule, else why not. */
149
+ check(user: AuthioUser): AuthioRuleFailure | undefined;
150
+ }
151
+ /**
152
+ * Checks every rule. On refusal the message joins every rule's, and the error is the one asking for a stronger
153
+ * sign-in, else the first one that has an error.
154
+ */
155
+ declare function authorize(user: AuthioUser, ...rules: AuthioRule[]): AuthioRuleFailure | undefined;
156
+ /**
157
+ * Requires granted scopes.
158
+ */
159
+ declare function requireScope(scopes: string | readonly string[], match?: AuthioMatch): AuthioRule;
160
+ /**
161
+ * Requires roles, from any source or only from the given `*_resource_access` claims.
162
+ */
163
+ declare function requireRole(roles: string | readonly string[], options?: {
164
+ match?: AuthioMatch;
165
+ sources?: readonly AuthioResourceAccessSource[];
166
+ }): AuthioRule;
167
+ /**
168
+ * Requires a permission (`method` on `resource`), granted by a role from any source or only from the given ones.
169
+ */
170
+ declare function requirePermission(resource: string, method: string, options?: {
171
+ sources?: readonly AuthioResourceAccessSource[];
172
+ }): AuthioRule;
173
+ /**
174
+ * Requires groups, read from the group claims (a claim mapper with the Group source).
175
+ */
176
+ declare function requireGroup(groups: string | readonly string[], match?: AuthioMatch): AuthioRule;
177
+ /**
178
+ * Requires a claim: present, or holding one of the given values. Fits claim-mapper claims, the user's own claims and
179
+ * any other claim Authio issues.
180
+ */
181
+ declare function requireClaim(type: string, ...values: string[]): AuthioRule;
182
+ /**
183
+ * Requires an organization context, or a given organization (alias or id, case-insensitive).
184
+ */
185
+ declare function requireOrganization(organization?: string): AuthioRule;
186
+ /**
187
+ * Requires a minimum authentication level (`acr`): 1 one factor, 2 several, 3 one of them phishing-resistant.
188
+ */
189
+ declare function requireAuthenticationLevel(minimumLevel: number): AuthioRule;
190
+ /**
191
+ * Requires authentication methods (`amr`, case-insensitive), such as `otp`, `swk` or `fed`.
192
+ */
193
+ declare function requireAuthenticationMethod(methods: string | readonly string[], match?: AuthioMatch): AuthioRule;
194
+ /**
195
+ * Requires the token to have been issued to one of the clients (`azp`, else `client_id`).
196
+ */
197
+ declare function requireClient(clientIds: string | readonly string[]): AuthioRule;
198
+ /**
199
+ * Requires every rule.
200
+ */
201
+ declare function allOf(...rules: AuthioRule[]): AuthioRule;
202
+ /**
203
+ * Requires at least one rule; the refusal is the first rule's.
204
+ */
205
+ declare function anyOf(...rules: AuthioRule[]): AuthioRule;
206
+
207
+ /**
208
+ * The request carries no valid access token: answer `401` with `wwwAuthenticate`.
209
+ */
210
+ declare class AuthioBearerError extends AuthioError {
211
+ readonly status = 401;
212
+ /** `invalid_token`, or `undefined` when the request had no token at all (RFC 6750 §3.1). */
213
+ readonly error: "invalid_token" | undefined;
214
+ /** Why the token was refused, safe to send to the caller. */
215
+ readonly description: string | undefined;
216
+ constructor(description: string | undefined, options?: {
217
+ error?: "invalid_token" | undefined;
218
+ cause?: unknown;
219
+ });
220
+ /** The `WWW-Authenticate` value. */
221
+ get wwwAuthenticate(): string;
222
+ }
223
+ /**
224
+ * The caller is known but not allowed: answer `403`, with `wwwAuthenticate` when the refusal has a bearer error.
225
+ */
226
+ declare class AuthioForbiddenError extends AuthioError {
227
+ readonly status = 403;
228
+ readonly failure: AuthioRuleFailure;
229
+ constructor(failure: AuthioRuleFailure);
230
+ /** The `WWW-Authenticate` value, or `undefined` when the refusal is not about scopes or the sign-in. */
231
+ get wwwAuthenticate(): string | undefined;
232
+ }
233
+ /**
234
+ * The `WWW-Authenticate` value of a refusal: `insufficient_scope` (with `scope`) or
235
+ * `insufficient_user_authentication`.
236
+ */
237
+ declare function toForbiddenChallenge(failure: AuthioRuleFailure): string | undefined;
238
+ /**
239
+ * Problem details (RFC 9457) for a `401` or `403`.
240
+ */
241
+ declare function toProblemDetails(error: AuthioBearerError | AuthioForbiddenError): Record<string, unknown>;
242
+
243
+ /**
244
+ * Whether and how Authio's introspection endpoint takes part in validating a token.
245
+ *
246
+ * - `none`: the JWT is validated locally (signature, issuer, audience, lifetime). Fastest; a revoked token stays
247
+ * valid until it expires.
248
+ * - `activeCheck`: validated locally, then confirmed active by introspection (cached per `jti`).
249
+ * - `introspectionOnly`: introspection alone, for opaque (reference) or encrypted tokens.
250
+ */
251
+ type AuthioIntrospectionMode = "none" | "activeCheck" | "introspectionOnly";
252
+ /**
253
+ * How an API validates Authio access tokens.
254
+ */
255
+ interface AuthioVerifierOptions extends AuthioConnectionOptions, AuthioUserClaimSettings {
256
+ /** The audiences this API accepts: its resource identifier (RFC 8707) or client id. Required. */
257
+ audiences: string | readonly string[];
258
+ /** Defaults to `none`. */
259
+ introspection?: AuthioIntrospectionMode;
260
+ /**
261
+ * The API's confidential client, for introspection: a client already created, or its options (issuer settings are
262
+ * taken from these options when absent). It must be the client the resource server names as its introspection
263
+ * client, since Authio answers introspection according to who asks.
264
+ */
265
+ client?: AuthioClient | Omit<AuthioClientOptions, keyof AuthioConnectionOptions>;
266
+ /** Seconds an active introspection answer is kept (never past the token's expiry). Defaults to 30. */
267
+ introspectionCacheDuration?: number;
268
+ /** Seconds of clock skew tolerated on `exp` and `nbf`. Defaults to 30. */
269
+ clockSkew?: number;
270
+ /** Accepted signing algorithms. Defaults to the asymmetric ones (RS*, PS*, ES*). */
271
+ validAlgorithms?: readonly string[];
272
+ /** Refuses a token whose `typ` claim is present and not `Bearer` (an ID token, for one). Defaults to `true`. */
273
+ rejectNonAccessTokens?: boolean;
274
+ }
275
+ /**
276
+ * Validates Authio access tokens and reads the caller.
277
+ */
278
+ interface AuthioVerifier {
279
+ /** The connection settings. */
280
+ readonly connection: AuthioConnection;
281
+ /** The discovery document. */
282
+ readonly discovery: AuthioDiscoveryClient;
283
+ /** The accepted audiences. */
284
+ readonly audiences: readonly string[];
285
+ /** The introspection mode. */
286
+ readonly introspection: AuthioIntrospectionMode;
287
+ /** The client used for introspection, when there is one. */
288
+ readonly client: AuthioClient | undefined;
289
+ /**
290
+ * Validates a token and reads the caller.
291
+ *
292
+ * @throws AuthioBearerError when the token is not valid for this API.
293
+ */
294
+ verify(token: string, signal?: AbortSignal): Promise<AuthioUser>;
295
+ /**
296
+ * Validates the token of an `Authorization: Bearer` header.
297
+ *
298
+ * @throws AuthioBearerError without an error code when there is no bearer token, with `invalid_token` when it is
299
+ * not valid.
300
+ */
301
+ verifyAuthorizationHeader(header: string | null | undefined, signal?: AbortSignal): Promise<AuthioUser>;
302
+ }
303
+ /**
304
+ * Error descriptions of the refusals the SDK makes itself.
305
+ */
306
+ declare const AuthioBearerErrorDescriptions: {
307
+ readonly Inactive: "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.";
308
+ readonly Unconfirmed: "Authio could not be reached to confirm that the token is active.";
309
+ readonly Empty: "The token is empty.";
310
+ readonly Encrypted: "The token is encrypted; validate it with introspection ('introspectionOnly').";
311
+ readonly SigningKeysUnavailable: "Authio could not be reached to read its signing keys.";
312
+ };
313
+ /**
314
+ * Creates a token verifier.
315
+ *
316
+ * @throws AuthioConfigurationError when no audience is given, or introspection is asked for without a client.
317
+ */
318
+ declare function createAuthioVerifier(options: AuthioVerifierOptions): AuthioVerifier;
319
+ /**
320
+ * The token of an `Authorization: Bearer` header, or `undefined` when the header is absent or of another scheme.
321
+ */
322
+ declare function readBearerToken(header: string | null | undefined): string | undefined;
323
+
324
+ /**
325
+ * Remembers delivered event ids, so a redelivery is acknowledged without running the handlers twice.
326
+ */
327
+ interface AuthioWebhookDeduplicationStore {
328
+ /** Records the id; `false` when it was already recorded within the window. */
329
+ tryBegin(eventId: string, windowMs: number): boolean | Promise<boolean>;
330
+ /** Forgets the id, after a handler failed, so the redelivery runs again. */
331
+ release(eventId: string): void | Promise<void>;
332
+ }
333
+ /**
334
+ * How webhook deliveries are received.
335
+ */
336
+ interface AuthioWebhookOptions {
337
+ /** The webhook's secret. */
338
+ secret?: string;
339
+ /** Several secrets, while one is being rotated; a delivery signed with any of them is accepted. */
340
+ secrets?: readonly string[];
341
+ /** Seconds a signature's timestamp may differ from now. Defaults to 300. */
342
+ tolerance?: number;
343
+ /** `memory` (default), `none`, or a store shared between instances. */
344
+ deduplication?: "memory" | "none" | AuthioWebhookDeduplicationStore;
345
+ /** Seconds a delivered id is remembered. Defaults to 86400. */
346
+ deduplicationWindow?: number;
347
+ /** The largest body accepted, in bytes. Defaults to 1 MiB. */
348
+ maxBodySize?: number;
349
+ /** The clock. */
350
+ clock?: AuthioClock;
351
+ /** Called when a delivery is refused or a handler fails. */
352
+ onError?: (error: unknown, context: {
353
+ reason: string;
354
+ eventId?: string;
355
+ eventType?: string;
356
+ }) => void;
357
+ }
358
+ /**
359
+ * A handler of one event type, or of every type.
360
+ */
361
+ type AuthioWebhookHandler<E extends AuthioWebhookEvent = AuthioWebhookEvent> = (event: E) => void | Promise<void>;
362
+ /**
363
+ * What to answer a delivery with.
364
+ */
365
+ interface AuthioWebhookOutcome {
366
+ /** `200` handled, duplicate or ping; `400` unreadable; `401` bad or stale signature; `413` too large; `500` a handler failed. */
367
+ readonly status: 200 | 400 | 401 | 413 | 500;
368
+ /** Why, for logs. */
369
+ readonly reason: "handled" | "duplicate" | "unreadable" | "unsigned" | "too_large" | "handler_failed";
370
+ readonly event?: AuthioWebhookEvent;
371
+ }
372
+ /**
373
+ * Receives Authio webhook deliveries: verifies, deduplicates and dispatches them.
374
+ */
375
+ interface AuthioWebhooks {
376
+ /** Handles one event type, typed. */
377
+ on<T extends keyof AuthioWebhookDataByType>(type: T, handler: AuthioWebhookHandler<AuthioTypedWebhookEvent<T>>): AuthioWebhooks;
378
+ /** Handles another event type, or `*` for every type. */
379
+ on(type: string, handler: AuthioWebhookHandler): AuthioWebhooks;
380
+ /**
381
+ * Handles a delivery: the body exactly as received and the request headers.
382
+ */
383
+ handle(delivery: {
384
+ body: string | Uint8Array;
385
+ headers: Headers | Record<string, string | string[] | undefined>;
386
+ }): Promise<AuthioWebhookOutcome>;
387
+ /** The largest body accepted, in bytes. */
388
+ readonly maxBodySize: number;
389
+ }
390
+ /**
391
+ * Creates a webhook receiver. Handlers run in registration order; a `*` handler sees every event.
392
+ *
393
+ * @throws AuthioConfigurationError when no secret is configured.
394
+ */
395
+ declare function createAuthioWebhooks(options: AuthioWebhookOptions): AuthioWebhooks;
396
+ /**
397
+ * A deduplication store kept in this process's memory.
398
+ */
399
+ declare function createMemoryDeduplicationStore(clock?: AuthioClock): AuthioWebhookDeduplicationStore;
400
+
401
+ /**
402
+ * Who a downstream call is made for: a caller read by the verifier, or the incoming access token itself.
403
+ */
404
+ type AuthioDownstreamSubject = AuthioUser | string;
405
+ /**
406
+ * A `fetch` that forwards the caller's own access token, unchanged, to a downstream API that accepts the same
407
+ * audience. Sends no `Authorization` when there is no token.
408
+ */
409
+ declare function createForwardingFetch(subject: AuthioDownstreamSubject | undefined, inner?: typeof fetch): typeof fetch;
410
+ /**
411
+ * Exchanges the caller's token for one addressed to a downstream API (RFC 8693), and caches it.
412
+ */
413
+ interface AuthioOnBehalfOf {
414
+ /**
415
+ * A token for the downstream API on the caller's behalf: cached per incoming `jti` (else token hash), resource and
416
+ * sorted scopes, renewed `tokenRefreshSkew` before expiry (at most half its lifetime); concurrent callers share
417
+ * one exchange.
418
+ *
419
+ * @throws AuthioError when there is no incoming token.
420
+ */
421
+ getToken(subject: AuthioDownstreamSubject | undefined, signal?: AbortSignal): Promise<AuthioClientCredentialsToken>;
422
+ /** Drops a cached token; with `accessToken`, only when the cache still holds that token. */
423
+ invalidate(subject: AuthioDownstreamSubject, accessToken?: string): Promise<void>;
424
+ /** A `fetch` that sends the exchanged token, and on a `401` drops it and retries once. */
425
+ fetch(subject: AuthioDownstreamSubject | undefined, inner?: typeof fetch): typeof fetch;
426
+ }
427
+ /**
428
+ * Creates an on-behalf-of exchanger.
429
+ *
430
+ * @param options `client` (the API's confidential client), the downstream `resource` and `scopes`.
431
+ */
432
+ declare function createOnBehalfOf(options: {
433
+ client: AuthioClient;
434
+ resource?: string;
435
+ scopes?: Iterable<string> | string;
436
+ tokenRefreshSkew?: number;
437
+ }): AuthioOnBehalfOf;
438
+
439
+ export { type AuthioActor, AuthioBearerError, AuthioBearerErrorDescriptions, type AuthioDownstreamSubject, AuthioForbiddenError, type AuthioIntrospectionMode, type AuthioMatch, type AuthioOnBehalfOf, type AuthioRule, type AuthioRuleFailure, AuthioUser, type AuthioUserClaimSettings, type AuthioVerifier, type AuthioVerifierOptions, type AuthioWebhookDeduplicationStore, type AuthioWebhookHandler, type AuthioWebhookOptions, type AuthioWebhookOutcome, type AuthioWebhooks, allOf, anyOf, authorize, createAuthioVerifier, createAuthioWebhooks, createForwardingFetch, createMemoryDeduplicationStore, createOnBehalfOf, readBearerToken, requireAuthenticationLevel, requireAuthenticationMethod, requireClaim, requireClient, requireGroup, requireOrganization, requirePermission, requireRole, requireScope, toForbiddenChallenge, toProblemDetails };