@pontive/server 1.23.1 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -1
- package/dist/authorization.cjs +1 -1
- package/dist/authorization.js +2 -2
- package/dist/client-D80_tH4S.cjs +2 -0
- package/dist/client-D80_tH4S.cjs.map +1 -0
- package/dist/client-DWO-uz9e.js +6689 -0
- package/dist/client-DWO-uz9e.js.map +1 -0
- package/dist/env.d.cts +2 -0
- package/dist/env.d.ts +2 -0
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +219 -248
- package/dist/index.js.map +1 -1
- package/dist/management/client.d.cts +68 -0
- package/dist/management/client.d.ts +68 -0
- package/dist/management/core.d.cts +112 -0
- package/dist/management/core.d.ts +112 -0
- package/dist/management/errors.d.cts +78 -0
- package/dist/management/errors.d.ts +78 -0
- package/dist/management/generated/namespaces.d.cts +5400 -0
- package/dist/management/generated/namespaces.d.ts +5400 -0
- package/dist/management/generated/types.d.cts +14884 -0
- package/dist/management/generated/types.d.ts +14884 -0
- package/dist/management/index.d.cts +10 -0
- package/dist/management/index.d.ts +10 -0
- package/dist/management-credential--CmS8XaV.cjs +2 -0
- package/dist/management-credential--CmS8XaV.cjs.map +1 -0
- package/dist/management-credential-CynS93TR.js +166 -0
- package/dist/management-credential-CynS93TR.js.map +1 -0
- package/dist/management.cjs +2 -0
- package/dist/management.cjs.map +1 -0
- package/dist/management.js +20 -0
- package/dist/management.js.map +1 -0
- package/dist/resource-server.cjs +1 -1
- package/dist/resource-server.cjs.map +1 -1
- package/dist/resource-server.js +3 -4
- package/dist/resource-server.js.map +1 -1
- package/package.json +12 -2
- package/dist/management-credential-BNyhHagG.cjs +0 -2
- package/dist/management-credential-BNyhHagG.cjs.map +0 -1
- package/dist/management-credential-VhmMzGDl.js +0 -39
- package/dist/management-credential-VhmMzGDl.js.map +0 -1
- package/dist/oidc--We55Nrh.cjs +0 -2
- package/dist/oidc--We55Nrh.cjs.map +0 -1
- package/dist/oidc-CB0FqjFz.js +0 -131
- package/dist/oidc-CB0FqjFz.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-server.cjs","sources":["../src/resource-server.ts"],"sourcesContent":["import {\n createRemoteJWKSet,\n customFetch,\n decodeJwt,\n jwtVerify,\n type JWTPayload,\n type JWTVerifyGetKey,\n} from \"jose\";\n\nimport { managementBase, managementTokenSource, type ManagementCredential } from \"./management-credential\";\nimport { discover } from \"./oidc\";\n\n/**\n * Resource-server middleware: protect an API or an MCP server with tokens a\n * Pontive instance issued for it (pontive-spec 44 §11).\n *\n * `createResourceServer` verifies bearer tokens locally against each issuer's\n * keys, answers a missing or failing token with the `WWW-Authenticate`\n * challenge an MCP client follows, and serves the API's protected resource\n * metadata (RFC 9728). Per request it calls nothing but the cached JWKS.\n *\n * This entry speaks Web `Request`/`Response` (Next route handlers, Hono,\n * Workers, Bun, Deno). `@pontive/server/resource-server/express` and\n * `@pontive/server/resource-server/mcp` adapt it to Express and to the\n * MCP TypeScript SDK.\n */\n\n/** Who a verified token speaks for, told apart by the subject's id prefix. */\nexport type PrincipalKind = \"user\" | \"service_account\" | \"agent\";\n\n/** What every verified principal carries. */\ninterface PrincipalBase {\n /**\n * `usr_…`, `svc_…` or `agt_…`: whom the token speaks for.\n *\n * **For a delegated principal (`isDelegated`) this is the delegator, not the\n * caller.** The caller is the agent in `actor`, and its authority is the\n * intersection of the user's and the agent's, never the user's alone. Do not\n * read or write your own data by `principal.sub` alone for a delegated\n * principal: check by token with the authorization client\n * (`@pontive/server/authorization`), which evaluates the pair, or\n * branch on `principal.isDelegated`.\n */\n sub: string;\n /** From the sub's id prefix; no claim needed. A delegated token's subject is a user, so its kind is `\"user\"`. */\n kind: PrincipalKind;\n /** The client the token was issued to. */\n clientId: string;\n /** The organization the token is scoped to, when it is. */\n orgId?: string;\n /** The token's roles. For a delegated token, already intersected by Pontive (the delegator's roles the agent also holds). */\n roles: string[];\n /** The token's permissions. For a delegated token, already intersected by Pontive. */\n permissions: string[];\n /** The token's granted scopes. */\n scopes: string[];\n /** The agent instance, when the subject itself is an agent. */\n agentInstance?: string;\n /** The raw token, e.g. to check permissions by token. */\n token: string;\n /**\n * Every claim of the verified token: the claims template's (say\n * `legacy_user_id`) beside the standard ones the fields above are read\n * from. A claim is whatever the issuer wrote, so check its type before\n * using it.\n */\n claims: Record<string, unknown>;\n}\n\n/** Who acts for the subject, from the token's `act` claim (RFC 8693 §4.1). */\nexport interface PrincipalActor {\n /** `agt_…` for an agent acting for its delegator; `svc_…` for an API's backend calling downstream for the user. */\n sub: string;\n kind: \"agent\" | \"service_account\";\n /** The agent's running copy, when it named one. */\n agentInstance?: string;\n}\n\n/**\n * A token an agent holds for its delegator (profile (b), `act.sub` is\n * `agt_…`). `sub` is the user; `actor` is the agent. Its authority is the\n * intersection of both: answer it with a check by token, never by `sub`.\n */\nexport interface DelegatedPrincipal extends PrincipalBase {\n isDelegated: true;\n actor: PrincipalActor & { kind: \"agent\" };\n}\n\n/**\n * Any other token: the subject acts for itself. An `actor` here is a\n * registered API's backend service account calling downstream for the user\n * (profile (a)), a conduit: only the subject is evaluated.\n */\nexport interface UndelegatedPrincipal extends PrincipalBase {\n isDelegated: false;\n actor?: PrincipalActor & { kind: \"service_account\" };\n}\n\n/**\n * The verified caller, as the handler sees it. Narrow on `isDelegated`: a\n * delegated principal's `sub` is the user an agent acts for, and its authority\n * is narrower than that user's.\n */\nexport type Principal = DelegatedPrincipal | UndelegatedPrincipal;\n\n/** The protected resource metadata document (RFC 9728; pontive-spec 44 §9). */\nexport interface ProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n scopes_supported?: string[];\n bearer_methods_supported: string[];\n resource_name?: string;\n resource_documentation?: string;\n logo_uri?: string;\n}\n\n/**\n * How the resource server gets a management API token to read its own\n * metadata: a token, a function returning one, or the client credentials of\n * the API's backend service account (exchanged at the first issuer for a\n * management-audience token, and reused until it is about to expire).\n */\nexport type MetadataCredential = ManagementCredential;\nexport type { ManagementCredential };\n\n/** An MCP tool a scope covers (pontive-spec 44 §5, §12). Only `name` is read here. */\nexport interface ApiScopeTool {\n /** The MCP tool name, as `tools/call` sends it. */\n name: string;\n title?: string;\n read_only?: boolean;\n destructive?: boolean;\n}\n\n/**\n * An API scope as the management API returns it (`GET /v1/apis/{api_id}`,\n * pontive-spec 44 §5), so the dashboard's scopes can be pasted as they are.\n * Only `key` and `tools` are read here.\n */\nexport interface ApiScope {\n key: string;\n description?: string;\n display_name?: string;\n origin?: \"manual\" | \"tool_import\";\n /** The MCP tools the scope covers; a token holding the scope may call each of them (`requireTool`). */\n tools?: ApiScopeTool[];\n}\n\nexport interface ResourceServerConfig {\n /**\n * The instance's issuer: its auth domain, e.g.\n * `https://acme.auth.us.pontive.app`. A list when the instance has more than\n * one auth domain (a custom domain beside the default): a token from any of\n * them is accepted, and each is listed in `authorization_servers`.\n */\n issuer: string | string[];\n /**\n * The API's identifier, exactly as registered. Tokens must carry it in\n * `aud`, and it is the metadata's `resource`. When it is an http(s) URL the\n * metadata is served under its origin (RFC 9728 §3.1).\n */\n resource: string;\n /**\n * The API's scopes, for `scopes_supported`: keys, or the scopes as the\n * management API returns them (`ApiScope`). A scope's `tools` are the MCP\n * tools a token holding it may call (`requireTool`, pontive-spec 44 §12).\n */\n scopes?: (string | ApiScope)[];\n /**\n * What `requireTool` does with a tool no scope lists. `\"deny\"` (the\n * default) refuses it with a `403` that names no scope, since no scope\n * could allow it: a tool added to the server after the last tool import is\n * refused, and logged once, until the import lists it. `\"allow\"` lets any\n * valid token call it.\n */\n unlistedTools?: \"deny\" | \"allow\";\n /** The metadata's `resource_name`. */\n resourceName?: string;\n /** The metadata's `resource_documentation`. */\n resourceDocumentation?: string;\n /** The metadata's `logo_uri`. */\n logoUri?: string;\n /**\n * Read the metadata from Pontive instead of building it from this\n * configuration, for an API whose scopes and display fields are kept in the\n * dashboard. It is fetched on first use and cached for five minutes.\n *\n * When no configured scope lists tools, `requireTool` reads the scopes and\n * their tools from the same API (`GET /v1/apis/{api_id}`, with the\n * same credential and `sys:api:read`), cached the same way.\n */\n metadata?: {\n fetch: {\n /** The API's id (`api_…`). */\n apiId: string;\n /** A credential the management API accepts for `GET /v1/apis/{api_id}/resource-metadata`. */\n credential: MetadataCredential;\n /**\n * The management API's origin in the instance's region, e.g. `https://api.us.pontive.com`.\n * A `/v1`, `/mgmt` or `/mgmt/v1` suffix is dropped (`managementBase`).\n */\n managementUrl: string;\n };\n };\n /**\n * Also serve `/.well-known/oauth-authorization-server`, proxying the\n * issuer's own document, for older MCP clients that ask the resource server\n * for it. Default false.\n */\n authorizationServerMetadataProxy?: boolean;\n /** Clock skew allowed on `exp` and `nbf`. Default 60. */\n leewaySeconds?: number;\n /** Defaults to the global `fetch`. Used for discovery, JWKS and metadata. */\n fetch?: typeof fetch;\n /** Where configuration drift is reported. Defaults to `console`. */\n logger?: Pick<Console, \"warn\">;\n}\n\n/** What a route needs of the token beyond its being valid. */\nexport interface BearerOptions {\n /** Every one of these must be granted. */\n scopes?: string[];\n}\n\n/** Anything with request headers: a Web `Request`, `Headers`, or a Node/Express request. */\nexport type RequestLike =\n | Request\n | { headers: Headers | Record<string, string | string[] | undefined> };\n\n/** A route handler pair, e.g. to export from a Next `route.ts`. */\nexport interface RouteHandlers {\n GET(request: Request): Promise<Response>;\n OPTIONS(request: Request): Promise<Response>;\n}\n\n/**\n * Why a request was refused: a `401` (no token, or one that failed) or a\n * `403` (a valid token without a scope the route needs). `toResponse()` is the\n * answer to send.\n */\nexport class BearerError extends Error {\n constructor(\n readonly status: 401 | 403,\n /** Absent when no token was sent (RFC 6750 §3.1). */\n readonly code: \"invalid_token\" | \"insufficient_scope\" | undefined,\n /** The `WWW-Authenticate` header value. */\n readonly wwwAuthenticate: string,\n description: string,\n ) {\n super(description);\n this.name = \"BearerError\";\n }\n\n toResponse(): Response {\n return Response.json(\n { error: this.code ?? \"unauthorized\", error_description: this.message },\n { status: this.status, headers: { \"www-authenticate\": this.wwwAuthenticate, \"cache-control\": \"no-store\" } },\n );\n }\n}\n\nexport interface ResourceServer {\n /** The API identifier tokens must carry in `aud`. */\n readonly resource: string;\n /** The accepted issuers. */\n readonly issuers: readonly string[];\n /** The clock skew allowed on `exp` and `nbf`. */\n readonly leewaySeconds: number;\n /** The metadata's URL, named in every challenge; absent for an identifier that is not an http(s) URL. */\n readonly metadataUrl: string | undefined;\n /** The paths the metadata is served at: the RFC 9728 §3.1 path-suffixed one first. */\n readonly metadataPaths: readonly string[];\n\n /** Verifies the request's bearer token. Throws a `BearerError` when it is missing, fails, or lacks a scope. */\n verify(request: RequestLike, options?: BearerOptions): Promise<Principal>;\n /** Verifies a raw token, as `verify` does. */\n verifyToken(token: string, options?: BearerOptions): Promise<Principal>;\n /** The protected resource metadata document. */\n metadata(): Promise<ProtectedResourceMetadata>;\n /**\n * A guard for Web-standard handlers: the principal, or the `401`/`403`\n * response to return as it is.\n */\n requireBearer(options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /**\n * The scopes that list an MCP tool (pontive-spec 44 §12), from the\n * configured scopes, else from the API in Pontive when `metadata.fetch` is\n * set. Empty for a tool no scope lists.\n */\n scopesForTool(name: string): Promise<string[]>;\n /**\n * Refuses a principal that holds none of the scopes listing the tool: a\n * `BearerError` `403` with `error=\"insufficient_scope\"` and\n * `scope=\"<every scope listing the tool>\"`, any one of which would do. A\n * tool no scope lists follows `unlistedTools`.\n */\n authorizeTool(principal: Principal, name: string): Promise<void>;\n /**\n * `authorizeTool` for every `tools/call` in a JSON-RPC message or batch, as\n * an MCP client posts it; any other message passes. Throws the first refusal.\n * Run it on the parsed body before the MCP transport sees it, so the refusal\n * is an HTTP `403` the client can step up from.\n */\n authorizeToolCalls(principal: Principal, message: unknown): Promise<void>;\n /**\n * A guard for a Web-standard handler that serves one tool: the principal,\n * or the `401`/`403` response to return as it is.\n */\n requireTool(name: string, options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /** `GET` and `OPTIONS` for the protected resource metadata route. */\n readonly metadataRoute: RouteHandlers;\n /** `GET` and `OPTIONS` for the authorization server metadata proxy (404 unless the proxy is on). */\n readonly authorizationServerMetadataRoute: RouteHandlers;\n /**\n * Answers any of the well-known routes this server serves (both metadata\n * paths, and the AS-metadata proxy when on), or null for any other path. For\n * a catch-all: `return (await rs.handleWellKnown(req)) ?? next()`.\n */\n handleWellKnown(request: Request): Promise<Response | null>;\n}\n\nconst PRM_PATH = \"/.well-known/oauth-protected-resource\";\nconst AS_PATH = \"/.well-known/oauth-authorization-server\";\nconst METADATA_TTL_MS = 5 * 60 * 1000;\nconst AS_METADATA_TTL_MS = 10 * 60 * 1000;\n\n/** OIDC's own scopes, which a token may carry beside the API's. */\nconst OIDC_SCOPES = new Set([\"openid\", \"profile\", \"email\", \"address\", \"phone\", \"offline_access\"]);\n\nconst KINDS: Record<string, PrincipalKind> = { usr: \"user\", svc: \"service_account\", agt: \"agent\" };\n\n/** jose errors that mean the token is bad, rather than that the keys could not be fetched. */\nconst INVALID_TOKEN_CODES = new Set([\n \"ERR_JWT_EXPIRED\",\n \"ERR_JWT_CLAIM_VALIDATION_FAILED\",\n \"ERR_JWT_INVALID\",\n \"ERR_JWS_INVALID\",\n \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\",\n \"ERR_JWKS_NO_MATCHING_KEY\",\n \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\",\n \"ERR_JOSE_ALG_NOT_ALLOWED\",\n \"ERR_JOSE_NOT_SUPPORTED\",\n]);\n\nconst trimSlash = (value: string) => value.replace(/\\/+$/, \"\");\n\n/** Where the metadata lives for an http(s) identifier (RFC 9728 §3.1); undefined for any other. */\nfunction metadataLocation(resource: string): { url: string; paths: string[] } | undefined {\n let url: URL;\n try {\n url = new URL(resource);\n } catch {\n return undefined;\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return undefined;\n\n const suffix = url.pathname === \"/\" ? \"\" : trimSlash(url.pathname);\n return {\n url: `${url.origin}${PRM_PATH}${suffix}`,\n paths: suffix ? [`${PRM_PATH}${suffix}`, PRM_PATH] : [PRM_PATH],\n };\n}\n\nfunction quote(value: string): string {\n return `\"${value.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : [];\n}\n\nfunction headerOf(request: RequestLike, name: string): string | undefined {\n const headers = request.headers;\n if (headers instanceof Headers) return headers.get(name) ?? undefined;\n\n const value = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/** The token from `Authorization: Bearer …`, the only bearer method this server supports. */\nfunction bearerToken(request: RequestLike): string | undefined {\n const match = /^Bearer[ ]+([^ ]+)[ ]*$/i.exec(headerOf(request, \"authorization\") ?? \"\");\n return match?.[1];\n}\n\nconst corsHeaders = (request: Request): Record<string, string> => ({\n \"access-control-allow-origin\": \"*\",\n \"access-control-allow-methods\": \"GET, OPTIONS\",\n \"access-control-allow-headers\": request.headers.get(\"access-control-request-headers\") ?? \"*\",\n \"access-control-max-age\": \"86400\",\n});\n\n/**\n * A value fetched on first use and kept for five minutes. A failed refresh\n * keeps the last good value, logged; with none, the failure is thrown. One\n * fetch at a time.\n */\nfunction cachedLoader<T>(load: () => Promise<T>, what: string, logger: Pick<Console, \"warn\">) {\n let fetched: { at: number; value: T } | undefined;\n let fetching: Promise<T> | undefined;\n return {\n get last(): T | undefined {\n return fetched?.value;\n },\n get(): Promise<T> {\n if (fetched && Date.now() - fetched.at < METADATA_TTL_MS) return Promise.resolve(fetched.value);\n fetching ??= load()\n .then((value) => {\n fetched = { at: Date.now(), value };\n return value;\n })\n .catch((err: unknown) => {\n if (fetched) {\n logger.warn(`[pontive] ${what} refresh failed; serving the cached copy: ${String(err)}`);\n return fetched.value;\n }\n throw err;\n })\n .finally(() => {\n fetching = undefined;\n });\n return fetching;\n },\n };\n}\n\nexport function createResourceServer(config: ResourceServerConfig): ResourceServer {\n const issuers = (Array.isArray(config.issuer) ? config.issuer : [config.issuer]).map(trimSlash);\n if (issuers.length === 0 || issuers.some((i) => !i)) throw new Error(\"resource server: issuer is required\");\n if (!config.resource) throw new Error(\"resource server: resource is required\");\n\n const resource = config.resource;\n const fetchImpl = config.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const logger = config.logger ?? console;\n const leeway = config.leewaySeconds ?? 60;\n const location = metadataLocation(resource);\n const configuredScopes = (config.scopes ?? []).map((s) => (typeof s === \"string\" ? s : s.key));\n const unlistedTools = config.unlistedTools ?? \"deny\";\n\n if (config.metadata?.fetch && !location) {\n throw new Error(\"resource server: metadata is only served for an http(s) resource identifier\");\n }\n\n // One remote key set per issuer: jose caches the keys for ten minutes and\n // refetches on an unknown kid (at most every 30 s), which is how a key\n // rotation is picked up. A failed discovery is not cached.\n const keySets = new Map<string, Promise<JWTVerifyGetKey>>();\n const keySet = (issuer: string): Promise<JWTVerifyGetKey> => {\n let pending = keySets.get(issuer);\n if (!pending) {\n pending = discover(issuer, fetchImpl)\n .then((disc) => createRemoteJWKSet(new URL(disc.jwks_uri), { [customFetch]: fetchImpl }))\n .catch((err: unknown) => {\n keySets.delete(issuer);\n throw err;\n });\n keySets.set(issuer, pending);\n }\n return pending;\n };\n\n const challenge = (scopes: string[], error?: \"invalid_token\"): string => {\n const params: string[] = [];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n if (scopes.length) params.push(`scope=${quote(scopes.join(\" \"))}`);\n if (error) params.push(`error=${quote(error)}`);\n return params.length ? `Bearer ${params.join(\", \")}` : \"Bearer\";\n };\n\n const unauthorized = (scopes: string[], description: string, tokenSent: boolean) =>\n new BearerError(401, tokenSent ? \"invalid_token\" : undefined, challenge(scopes, tokenSent ? \"invalid_token\" : undefined), description);\n\n const insufficientScope = (scopes: string[], description = \"the token lacks a scope this route needs\") => {\n const params = [`error=\"insufficient_scope\"`, `scope=${quote(scopes.join(\" \"))}`];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n return new BearerError(403, \"insufficient_scope\", `Bearer ${params.join(\", \")}`, description);\n };\n\n // --- metadata -------------------------------------------------------------\n\n const localMetadata = (): ProtectedResourceMetadata => ({\n resource,\n authorization_servers: [...issuers],\n ...(configuredScopes.length ? { scopes_supported: [...configuredScopes] } : {}),\n bearer_methods_supported: [\"header\"],\n ...(config.resourceName ? { resource_name: config.resourceName } : {}),\n ...(config.resourceDocumentation ? { resource_documentation: config.resourceDocumentation } : {}),\n ...(config.logoUri ? { logo_uri: config.logoUri } : {}),\n });\n\n const credentialToken = config.metadata?.fetch\n ? managementTokenSource({ ...config.metadata.fetch, issuer: issuers[0]!, fetch: fetchImpl })\n : () => Promise.reject(new Error(\"resource server: no metadata credential\"));\n\n const fetchMetadata = async (): Promise<ProtectedResourceMetadata> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}/resource-metadata`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`resource metadata fetch failed: ${res.status}`);\n\n const doc = (await res.json()) as ProtectedResourceMetadata;\n // The metadata must describe the resource whose tokens this server accepts.\n if (doc.resource !== resource) {\n throw new Error(`resource metadata names ${doc.resource}, but this server accepts tokens for ${resource}`);\n }\n // Every issuer this server accepts is an authorization server for it.\n doc.authorization_servers = [...new Set([...(doc.authorization_servers ?? []), ...issuers])];\n doc.bearer_methods_supported = [\"header\"];\n return doc;\n };\n\n const fetchedMetadata = cachedLoader(fetchMetadata, \"resource metadata\", logger);\n\n const metadata = async (): Promise<ProtectedResourceMetadata> => {\n if (!location) throw new Error(`resource server: no metadata for ${resource}, which is not an http(s) URL`);\n if (!config.metadata?.fetch) return localMetadata();\n return fetchedMetadata.get();\n };\n\n // --- tool scopes (44 §12) -----------------------------------------------------\n\n // A tool's scopes: every scope whose `tools` lists it.\n const toolMapOf = (scopes: readonly (string | ApiScope)[]): Map<string, string[]> => {\n const map = new Map<string, string[]>();\n for (const scope of scopes) {\n if (typeof scope === \"string\" || !Array.isArray(scope.tools)) continue;\n for (const tool of scope.tools) {\n if (typeof tool?.name !== \"string\") continue;\n const keys = map.get(tool.name) ?? [];\n if (!keys.includes(scope.key)) keys.push(scope.key);\n map.set(tool.name, keys);\n }\n }\n return map;\n };\n\n const configuredToolMap = toolMapOf(config.scopes ?? []);\n\n const fetchToolMap = async (): Promise<Map<string, string[]>> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`api fetch failed: ${res.status}`);\n\n const api = (await res.json()) as { identifier?: string; scopes?: ApiScope[] };\n if (api.identifier !== resource) {\n throw new Error(`api ${apiId} is ${String(api.identifier)}, but this server accepts tokens for ${resource}`);\n }\n return toolMapOf(Array.isArray(api.scopes) ? api.scopes : []);\n };\n\n // Configured tools win; the API in Pontive is read only when none are configured.\n const fetchedToolMap =\n configuredToolMap.size === 0 && config.metadata?.fetch ? cachedLoader(fetchToolMap, \"api scopes\", logger) : undefined;\n\n const scopesForTool = async (name: string): Promise<string[]> => {\n const map = fetchedToolMap ? await fetchedToolMap.get() : configuredToolMap;\n return [...(map.get(name) ?? [])];\n };\n\n const warnedTools = new Set<string>();\n const authorizeTool = async (principal: Principal, name: string): Promise<void> => {\n const scopes = await scopesForTool(name);\n if (scopes.length === 0) {\n if (!warnedTools.has(name)) {\n warnedTools.add(name);\n logger.warn(\n `[pontive] the tool \"${name}\" is listed by no scope of ${resource}` +\n (unlistedTools === \"deny\" ? \"; calls to it are refused until a tool import lists it\" : \"\"),\n );\n }\n if (unlistedTools === \"allow\") return;\n // No scope could allow it, so the challenge names none and asks for no step-up.\n const params = location ? ` resource_metadata=${quote(location.url)}` : \"\";\n throw new BearerError(403, \"insufficient_scope\", `Bearer${params}`, `no scope of this API lists the tool \"${name}\"`);\n }\n if (scopes.some((scope) => principal.scopes.includes(scope))) return;\n throw insufficientScope(scopes, `the token holds none of the scopes that list the tool \"${name}\": ${scopes.join(\", \")}`);\n };\n\n const authorizeToolCalls = async (principal: Principal, message: unknown): Promise<void> => {\n for (const m of Array.isArray(message) ? message : [message]) {\n if (!m || typeof m !== \"object\") continue;\n const { method, params } = m as { method?: unknown; params?: { name?: unknown } };\n // A call without a name is the SDK's to refuse, as invalid params.\n if (method === \"tools/call\" && typeof params?.name === \"string\") await authorizeTool(principal, params.name);\n }\n };\n\n const requireTool = (name: string, options?: BearerOptions) => async (request: Request) => {\n try {\n const principal = await verify(request, options);\n await authorizeTool(principal, name);\n return principal;\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- scope drift ------------------------------------------------------------\n\n const warned = new Set<string>();\n const warnUnknownScopes = (scopes: string[]) => {\n const known = new Set([...configuredScopes, ...(fetchedMetadata.last?.scopes_supported ?? [])]);\n // Nothing declared, nothing to drift from.\n if (known.size === 0) return;\n\n for (const scope of scopes) {\n if (known.has(scope) || OIDC_SCOPES.has(scope) || warned.has(scope)) continue;\n warned.add(scope);\n logger.warn(\n `[pontive] a verified token for ${resource} carries the scope \"${scope}\", which this resource server's configuration does not list`,\n );\n }\n };\n\n // --- verification -----------------------------------------------------------\n\n const verifyToken = async (token: string, options?: BearerOptions): Promise<Principal> => {\n const required = options?.scopes ?? [];\n\n let unverified: JWTPayload;\n try {\n unverified = decodeJwt(token);\n } catch {\n throw unauthorized(required, \"the token is not a JWT\", true);\n }\n\n const issuer = typeof unverified.iss === \"string\" ? trimSlash(unverified.iss) : undefined;\n if (!issuer || !issuers.includes(issuer)) throw unauthorized(required, \"the token's issuer is not accepted\", true);\n\n let payload: JWTPayload;\n try {\n ({ payload } = await jwtVerify(token, await keySet(issuer), {\n issuer: unverified.iss as string,\n audience: resource,\n clockTolerance: leeway,\n // An access token (RFC 9068). An ID token is never one, and its\n // audience is the client besides.\n typ: \"at+jwt\",\n requiredClaims: [\"exp\", \"sub\"],\n }));\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code && INVALID_TOKEN_CODES.has(code)) throw unauthorized(required, (err as Error).message, true);\n throw err;\n }\n\n const sub = payload.sub!;\n const kind = KINDS[sub.slice(0, sub.indexOf(\"_\"))];\n if (!kind) throw unauthorized(required, \"the token's subject is not a user, service account or agent\", true);\n\n const base = {\n sub,\n kind,\n clientId: typeof payload.client_id === \"string\" ? payload.client_id : typeof payload.azp === \"string\" ? payload.azp : \"\",\n ...(typeof payload.org_id === \"string\" && payload.org_id ? { orgId: payload.org_id } : {}),\n roles: stringArray(payload.roles),\n permissions: stringArray(payload.permissions),\n scopes: typeof payload.scope === \"string\" ? payload.scope.split(\" \").filter(Boolean) : [],\n ...(kind === \"agent\" && typeof payload.agent_instance === \"string\"\n ? { agentInstance: payload.agent_instance }\n : {}),\n token,\n claims: payload,\n };\n\n const act = payload.act as { sub?: unknown; agent_instance?: unknown } | undefined;\n const actorSub = act && typeof act.sub === \"string\" ? act.sub : undefined;\n let principal: Principal;\n if (actorSub?.startsWith(\"agt_\")) {\n principal = {\n ...base,\n isDelegated: true,\n actor: {\n sub: actorSub,\n kind: \"agent\",\n ...(typeof act!.agent_instance === \"string\" ? { agentInstance: act!.agent_instance } : {}),\n },\n };\n } else if (actorSub?.startsWith(\"svc_\")) {\n principal = { ...base, isDelegated: false, actor: { sub: actorSub, kind: \"service_account\" } };\n } else if (actorSub) {\n // An act this server does not know how to evaluate: refuse it rather\n // than let the subject's authority stand for an unknown caller.\n throw unauthorized(required, \"the token's actor is not an agent or a service account\", true);\n } else {\n principal = { ...base, isDelegated: false };\n }\n\n warnUnknownScopes(principal.scopes);\n\n if (required.some((scope) => !principal.scopes.includes(scope))) throw insufficientScope(required);\n\n return principal;\n };\n\n const verify = async (request: RequestLike, options?: BearerOptions): Promise<Principal> => {\n const token = bearerToken(request);\n if (!token) throw unauthorized(options?.scopes ?? [], \"a bearer token is required\", false);\n return verifyToken(token, options);\n };\n\n const requireBearer = (options?: BearerOptions) => async (request: Request) => {\n try {\n return await verify(request, options);\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- well-known routes ------------------------------------------------------\n\n const metadataRoute: RouteHandlers = {\n async GET(request) {\n if (!location) return new Response(null, { status: 404 });\n try {\n return Response.json(await metadata(), {\n headers: { \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] resource metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 503, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n let asMetadata: { at: number; body: string } | undefined;\n const authorizationServerMetadata = async (): Promise<string> => {\n if (asMetadata && Date.now() - asMetadata.at < AS_METADATA_TTL_MS) return asMetadata.body;\n\n // RFC 8414's document, or the OIDC discovery document, which is a superset.\n for (const path of [AS_PATH, \"/.well-known/openid-configuration\"]) {\n const res = await fetchImpl(`${issuers[0]}${path}`);\n if (res.ok) {\n asMetadata = { at: Date.now(), body: await res.text() };\n return asMetadata.body;\n }\n }\n throw new Error(`no authorization server metadata at ${issuers[0]}`);\n };\n\n const authorizationServerMetadataRoute: RouteHandlers = {\n async GET(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n try {\n return new Response(await authorizationServerMetadata(), {\n headers: { \"content-type\": \"application/json\", \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] authorization server metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 502, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n const route = (handlers: RouteHandlers, request: Request): Promise<Response> => {\n if (request.method === \"GET\" || request.method === \"HEAD\") return handlers.GET(request);\n if (request.method === \"OPTIONS\") return handlers.OPTIONS(request);\n return Promise.resolve(new Response(null, { status: 405, headers: { allow: \"GET, OPTIONS\" } }));\n };\n\n const handleWellKnown = async (request: Request): Promise<Response | null> => {\n const path = trimSlash(new URL(request.url).pathname);\n if (location?.paths.includes(path)) return route(metadataRoute, request);\n if (config.authorizationServerMetadataProxy && path === AS_PATH) {\n return route(authorizationServerMetadataRoute, request);\n }\n return null;\n };\n\n return {\n resource,\n issuers,\n leewaySeconds: leeway,\n metadataUrl: location?.url,\n metadataPaths: location?.paths ?? [],\n verify,\n verifyToken,\n metadata,\n requireBearer,\n scopesForTool,\n authorizeTool,\n authorizeToolCalls,\n requireTool,\n metadataRoute,\n authorizationServerMetadataRoute,\n handleWellKnown,\n };\n}\n"],"names":["BearerError","status","code","wwwAuthenticate","description","PRM_PATH","AS_PATH","METADATA_TTL_MS","AS_METADATA_TTL_MS","OIDC_SCOPES","KINDS","INVALID_TOKEN_CODES","trimSlash","value","metadataLocation","resource","url","suffix","quote","stringArray","v","headerOf","request","name","headers","bearerToken","corsHeaders","cachedLoader","load","what","logger","fetched","fetching","err","createResourceServer","config","issuers","i","fetchImpl","args","leeway","location","configuredScopes","s","unlistedTools","keySets","keySet","issuer","pending","discover","disc","createRemoteJWKSet","customFetch","challenge","scopes","error","params","unauthorized","tokenSent","insufficientScope","localMetadata","credentialToken","managementTokenSource","fetchedMetadata","apiId","managementUrl","managementBase","res","doc","metadata","toolMapOf","map","scope","tool","keys","configuredToolMap","fetchToolMap","api","fetchedToolMap","scopesForTool","warnedTools","authorizeTool","principal","authorizeToolCalls","message","m","method","requireTool","options","verify","warned","warnUnknownScopes","known","verifyToken","token","required","unverified","decodeJwt","payload","jwtVerify","sub","kind","base","act","actorSub","requireBearer","metadataRoute","asMetadata","authorizationServerMetadata","path","authorization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AE,OAAQ,IAAK,CAEzF,CAAA,EAGIyF,EAAQ,CAACC,EAAyB1F,IAClCA,EAAQ,SAAW,OAASA,EAAQ,SAAW,OAAe0F,EAAS,IAAI1F,CAAO,EAClFA,EAAQ,SAAW,UAAkB0F,EAAS,QAAQ1F,CAAO,EAC1D,QAAQ,QAAQ,IAAI,SAAS,KAAM,CAAE,OAAQ,IAAK,QAAS,CAAE,MAAO,cAAA,CAAe,CAAG,CAAC,EAG1F2F,GAAkB,MAAO3F,GAA+C,CAC5E,MAAMuF,EAAOjG,EAAU,IAAI,IAAIU,EAAQ,GAAG,EAAE,QAAQ,EACpD,OAAImB,GAAU,MAAM,SAASoE,CAAI,EAAUE,EAAML,EAAepF,CAAO,EACnEa,EAAO,kCAAoC0E,IAASvG,EAC/CyG,EAAMD,EAAkCxF,CAAO,EAEjD,IACT,EAEA,MAAO,CACL,SAAAP,EACA,QAAAqB,EACA,cAAeI,EACf,YAAaC,GAAU,IACvB,cAAeA,GAAU,OAAS,CAAA,EAClC,OAAAgD,EACA,YAAAI,EACA,SAAAxB,EACA,cAAAoC,GACA,cAAA1B,EACA,cAAAE,EACA,mBAAAE,GACA,YAAAI,GACA,cAAAmB,EACA,iCAAAI,EACA,gBAAAG,EAAA,CAEJ"}
|
|
1
|
+
{"version":3,"file":"resource-server.cjs","sources":["../src/resource-server.ts"],"sourcesContent":["import {\n createRemoteJWKSet,\n customFetch,\n decodeJwt,\n jwtVerify,\n type JWTPayload,\n type JWTVerifyGetKey,\n} from \"jose\";\n\nimport { managementBase, managementTokenSource, type ManagementCredential } from \"./management-credential\";\nimport { discover } from \"./oidc\";\n\n/**\n * Resource-server middleware: protect an API or an MCP server with tokens a\n * Pontive instance issued for it (pontive-spec 44 §11).\n *\n * `createResourceServer` verifies bearer tokens locally against each issuer's\n * keys, answers a missing or failing token with the `WWW-Authenticate`\n * challenge an MCP client follows, and serves the API's protected resource\n * metadata (RFC 9728). Per request it calls nothing but the cached JWKS.\n *\n * This entry speaks Web `Request`/`Response` (Next route handlers, Hono,\n * Workers, Bun, Deno). `@pontive/server/resource-server/express` and\n * `@pontive/server/resource-server/mcp` adapt it to Express and to the\n * MCP TypeScript SDK.\n */\n\n/** Who a verified token speaks for, told apart by the subject's id prefix. */\nexport type PrincipalKind = \"user\" | \"service_account\" | \"agent\";\n\n/** What every verified principal carries. */\ninterface PrincipalBase {\n /**\n * `usr_…`, `svc_…` or `agt_…`: whom the token speaks for.\n *\n * **For a delegated principal (`isDelegated`) this is the delegator, not the\n * caller.** The caller is the agent in `actor`, and its authority is the\n * intersection of the user's and the agent's, never the user's alone. Do not\n * read or write your own data by `principal.sub` alone for a delegated\n * principal: check by token with the authorization client\n * (`@pontive/server/authorization`), which evaluates the pair, or\n * branch on `principal.isDelegated`.\n */\n sub: string;\n /** From the sub's id prefix; no claim needed. A delegated token's subject is a user, so its kind is `\"user\"`. */\n kind: PrincipalKind;\n /** The client the token was issued to. */\n clientId: string;\n /** The organization the token is scoped to, when it is. */\n orgId?: string;\n /** The token's roles. For a delegated token, already intersected by Pontive (the delegator's roles the agent also holds). */\n roles: string[];\n /** The token's permissions. For a delegated token, already intersected by Pontive. */\n permissions: string[];\n /** The token's granted scopes. */\n scopes: string[];\n /** The agent instance, when the subject itself is an agent. */\n agentInstance?: string;\n /** The raw token, e.g. to check permissions by token. */\n token: string;\n /**\n * Every claim of the verified token: the claims template's (say\n * `legacy_user_id`) beside the standard ones the fields above are read\n * from. A claim is whatever the issuer wrote, so check its type before\n * using it.\n */\n claims: Record<string, unknown>;\n}\n\n/** Who acts for the subject, from the token's `act` claim (RFC 8693 §4.1). */\nexport interface PrincipalActor {\n /** `agt_…` for an agent acting for its delegator; `svc_…` for an API's backend calling downstream for the user. */\n sub: string;\n kind: \"agent\" | \"service_account\";\n /** The agent's running copy, when it named one. */\n agentInstance?: string;\n}\n\n/**\n * A token an agent holds for its delegator (profile (b), `act.sub` is\n * `agt_…`). `sub` is the user; `actor` is the agent. Its authority is the\n * intersection of both: answer it with a check by token, never by `sub`.\n */\nexport interface DelegatedPrincipal extends PrincipalBase {\n isDelegated: true;\n actor: PrincipalActor & { kind: \"agent\" };\n}\n\n/**\n * Any other token: the subject acts for itself. An `actor` here is a\n * registered API's backend service account calling downstream for the user\n * (profile (a)), a conduit: only the subject is evaluated.\n */\nexport interface UndelegatedPrincipal extends PrincipalBase {\n isDelegated: false;\n actor?: PrincipalActor & { kind: \"service_account\" };\n}\n\n/**\n * The verified caller, as the handler sees it. Narrow on `isDelegated`: a\n * delegated principal's `sub` is the user an agent acts for, and its authority\n * is narrower than that user's.\n */\nexport type Principal = DelegatedPrincipal | UndelegatedPrincipal;\n\n/** The protected resource metadata document (RFC 9728; pontive-spec 44 §9). */\nexport interface ProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n scopes_supported?: string[];\n bearer_methods_supported: string[];\n resource_name?: string;\n resource_documentation?: string;\n logo_uri?: string;\n}\n\n/**\n * How the resource server gets a management API token to read its own\n * metadata: a token, a function returning one, or the client credentials of\n * the API's backend service account (exchanged at the first issuer for a\n * management-audience token, and reused until it is about to expire).\n */\nexport type MetadataCredential = ManagementCredential;\nexport type { ManagementCredential };\n\n/** An MCP tool a scope covers (pontive-spec 44 §5, §12). Only `name` is read here. */\nexport interface ApiScopeTool {\n /** The MCP tool name, as `tools/call` sends it. */\n name: string;\n title?: string;\n read_only?: boolean;\n destructive?: boolean;\n}\n\n/**\n * An API scope as the management API returns it (`GET /v1/apis/{api_id}`,\n * pontive-spec 44 §5), so the dashboard's scopes can be pasted as they are.\n * Only `key` and `tools` are read here.\n */\nexport interface ApiScope {\n key: string;\n description?: string;\n display_name?: string;\n origin?: \"manual\" | \"tool_import\";\n /** The MCP tools the scope covers; a token holding the scope may call each of them (`requireTool`). */\n tools?: ApiScopeTool[];\n}\n\nexport interface ResourceServerConfig {\n /**\n * The instance's issuer: its auth domain, e.g.\n * `https://acme.auth.us.pontive.app`. A list when the instance has more than\n * one auth domain (a custom domain beside the default): a token from any of\n * them is accepted, and each is listed in `authorization_servers`.\n */\n issuer: string | string[];\n /**\n * The API's identifier, exactly as registered. Tokens must carry it in\n * `aud`, and it is the metadata's `resource`. When it is an http(s) URL the\n * metadata is served under its origin (RFC 9728 §3.1).\n */\n resource: string;\n /**\n * The API's scopes, for `scopes_supported`: keys, or the scopes as the\n * management API returns them (`ApiScope`). A scope's `tools` are the MCP\n * tools a token holding it may call (`requireTool`, pontive-spec 44 §12).\n */\n scopes?: (string | ApiScope)[];\n /**\n * What `requireTool` does with a tool no scope lists. `\"deny\"` (the\n * default) refuses it with a `403` that names no scope, since no scope\n * could allow it: a tool added to the server after the last tool import is\n * refused, and logged once, until the import lists it. `\"allow\"` lets any\n * valid token call it.\n */\n unlistedTools?: \"deny\" | \"allow\";\n /** The metadata's `resource_name`. */\n resourceName?: string;\n /** The metadata's `resource_documentation`. */\n resourceDocumentation?: string;\n /** The metadata's `logo_uri`. */\n logoUri?: string;\n /**\n * Read the metadata from Pontive instead of building it from this\n * configuration, for an API whose scopes and display fields are kept in the\n * dashboard. It is fetched on first use and cached for five minutes.\n *\n * When no configured scope lists tools, `requireTool` reads the scopes and\n * their tools from the same API (`GET /v1/apis/{api_id}`, with the\n * same credential and `sys:api:read`), cached the same way.\n */\n metadata?: {\n fetch: {\n /** The API's id (`api_…`). */\n apiId: string;\n /** A credential the management API accepts for `GET /v1/apis/{api_id}/resource-metadata`. */\n credential: MetadataCredential;\n /**\n * The management API's origin in the instance's region, e.g. `https://api.us.pontive.com`.\n * A `/v1`, `/mgmt` or `/mgmt/v1` suffix is dropped (`managementBase`).\n */\n managementUrl: string;\n };\n };\n /**\n * Also serve `/.well-known/oauth-authorization-server`, proxying the\n * issuer's own document, for older MCP clients that ask the resource server\n * for it. Default false.\n */\n authorizationServerMetadataProxy?: boolean;\n /** Clock skew allowed on `exp` and `nbf`. Default 60. */\n leewaySeconds?: number;\n /** Defaults to the global `fetch`. Used for discovery, JWKS and metadata. */\n fetch?: typeof fetch;\n /** Where configuration drift is reported. Defaults to `console`. */\n logger?: Pick<Console, \"warn\">;\n}\n\n/** What a route needs of the token beyond its being valid. */\nexport interface BearerOptions {\n /** Every one of these must be granted. */\n scopes?: string[];\n}\n\n/** Anything with request headers: a Web `Request`, `Headers`, or a Node/Express request. */\nexport type RequestLike =\n | Request\n | { headers: Headers | Record<string, string | string[] | undefined> };\n\n/** A route handler pair, e.g. to export from a Next `route.ts`. */\nexport interface RouteHandlers {\n GET(request: Request): Promise<Response>;\n OPTIONS(request: Request): Promise<Response>;\n}\n\n/**\n * Why a request was refused: a `401` (no token, or one that failed) or a\n * `403` (a valid token without a scope the route needs). `toResponse()` is the\n * answer to send.\n */\nexport class BearerError extends Error {\n constructor(\n readonly status: 401 | 403,\n /** Absent when no token was sent (RFC 6750 §3.1). */\n readonly code: \"invalid_token\" | \"insufficient_scope\" | undefined,\n /** The `WWW-Authenticate` header value. */\n readonly wwwAuthenticate: string,\n description: string,\n ) {\n super(description);\n this.name = \"BearerError\";\n }\n\n toResponse(): Response {\n return Response.json(\n { error: this.code ?? \"unauthorized\", error_description: this.message },\n { status: this.status, headers: { \"www-authenticate\": this.wwwAuthenticate, \"cache-control\": \"no-store\" } },\n );\n }\n}\n\nexport interface ResourceServer {\n /** The API identifier tokens must carry in `aud`. */\n readonly resource: string;\n /** The accepted issuers. */\n readonly issuers: readonly string[];\n /** The clock skew allowed on `exp` and `nbf`. */\n readonly leewaySeconds: number;\n /** The metadata's URL, named in every challenge; absent for an identifier that is not an http(s) URL. */\n readonly metadataUrl: string | undefined;\n /** The paths the metadata is served at: the RFC 9728 §3.1 path-suffixed one first. */\n readonly metadataPaths: readonly string[];\n\n /** Verifies the request's bearer token. Throws a `BearerError` when it is missing, fails, or lacks a scope. */\n verify(request: RequestLike, options?: BearerOptions): Promise<Principal>;\n /** Verifies a raw token, as `verify` does. */\n verifyToken(token: string, options?: BearerOptions): Promise<Principal>;\n /** The protected resource metadata document. */\n metadata(): Promise<ProtectedResourceMetadata>;\n /**\n * A guard for Web-standard handlers: the principal, or the `401`/`403`\n * response to return as it is.\n */\n requireBearer(options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /**\n * The scopes that list an MCP tool (pontive-spec 44 §12), from the\n * configured scopes, else from the API in Pontive when `metadata.fetch` is\n * set. Empty for a tool no scope lists.\n */\n scopesForTool(name: string): Promise<string[]>;\n /**\n * Refuses a principal that holds none of the scopes listing the tool: a\n * `BearerError` `403` with `error=\"insufficient_scope\"` and\n * `scope=\"<every scope listing the tool>\"`, any one of which would do. A\n * tool no scope lists follows `unlistedTools`.\n */\n authorizeTool(principal: Principal, name: string): Promise<void>;\n /**\n * `authorizeTool` for every `tools/call` in a JSON-RPC message or batch, as\n * an MCP client posts it; any other message passes. Throws the first refusal.\n * Run it on the parsed body before the MCP transport sees it, so the refusal\n * is an HTTP `403` the client can step up from.\n */\n authorizeToolCalls(principal: Principal, message: unknown): Promise<void>;\n /**\n * A guard for a Web-standard handler that serves one tool: the principal,\n * or the `401`/`403` response to return as it is.\n */\n requireTool(name: string, options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /** `GET` and `OPTIONS` for the protected resource metadata route. */\n readonly metadataRoute: RouteHandlers;\n /** `GET` and `OPTIONS` for the authorization server metadata proxy (404 unless the proxy is on). */\n readonly authorizationServerMetadataRoute: RouteHandlers;\n /**\n * Answers any of the well-known routes this server serves (both metadata\n * paths, and the AS-metadata proxy when on), or null for any other path. For\n * a catch-all: `return (await rs.handleWellKnown(req)) ?? next()`.\n */\n handleWellKnown(request: Request): Promise<Response | null>;\n}\n\nconst PRM_PATH = \"/.well-known/oauth-protected-resource\";\nconst AS_PATH = \"/.well-known/oauth-authorization-server\";\nconst METADATA_TTL_MS = 5 * 60 * 1000;\nconst AS_METADATA_TTL_MS = 10 * 60 * 1000;\n\n/** OIDC's own scopes, which a token may carry beside the API's. */\nconst OIDC_SCOPES = new Set([\"openid\", \"profile\", \"email\", \"address\", \"phone\", \"offline_access\"]);\n\nconst KINDS: Record<string, PrincipalKind> = { usr: \"user\", svc: \"service_account\", agt: \"agent\" };\n\n/** jose errors that mean the token is bad, rather than that the keys could not be fetched. */\nconst INVALID_TOKEN_CODES = new Set([\n \"ERR_JWT_EXPIRED\",\n \"ERR_JWT_CLAIM_VALIDATION_FAILED\",\n \"ERR_JWT_INVALID\",\n \"ERR_JWS_INVALID\",\n \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\",\n \"ERR_JWKS_NO_MATCHING_KEY\",\n \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\",\n \"ERR_JOSE_ALG_NOT_ALLOWED\",\n \"ERR_JOSE_NOT_SUPPORTED\",\n]);\n\nconst trimSlash = (value: string) => value.replace(/\\/+$/, \"\");\n\n/** Where the metadata lives for an http(s) identifier (RFC 9728 §3.1); undefined for any other. */\nfunction metadataLocation(resource: string): { url: string; paths: string[] } | undefined {\n let url: URL;\n try {\n url = new URL(resource);\n } catch {\n return undefined;\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return undefined;\n\n const suffix = url.pathname === \"/\" ? \"\" : trimSlash(url.pathname);\n return {\n url: `${url.origin}${PRM_PATH}${suffix}`,\n paths: suffix ? [`${PRM_PATH}${suffix}`, PRM_PATH] : [PRM_PATH],\n };\n}\n\nfunction quote(value: string): string {\n return `\"${value.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : [];\n}\n\nfunction headerOf(request: RequestLike, name: string): string | undefined {\n const headers = request.headers;\n if (headers instanceof Headers) return headers.get(name) ?? undefined;\n\n const value = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/** The token from `Authorization: Bearer …`, the only bearer method this server supports. */\nfunction bearerToken(request: RequestLike): string | undefined {\n const match = /^Bearer[ ]+([^ ]+)[ ]*$/i.exec(headerOf(request, \"authorization\") ?? \"\");\n return match?.[1];\n}\n\nconst corsHeaders = (request: Request): Record<string, string> => ({\n \"access-control-allow-origin\": \"*\",\n \"access-control-allow-methods\": \"GET, OPTIONS\",\n \"access-control-allow-headers\": request.headers.get(\"access-control-request-headers\") ?? \"*\",\n \"access-control-max-age\": \"86400\",\n});\n\n/**\n * A value fetched on first use and kept for five minutes. A failed refresh\n * keeps the last good value, logged; with none, the failure is thrown. One\n * fetch at a time.\n */\nfunction cachedLoader<T>(load: () => Promise<T>, what: string, logger: Pick<Console, \"warn\">) {\n let fetched: { at: number; value: T } | undefined;\n let fetching: Promise<T> | undefined;\n return {\n get last(): T | undefined {\n return fetched?.value;\n },\n get(): Promise<T> {\n if (fetched && Date.now() - fetched.at < METADATA_TTL_MS) return Promise.resolve(fetched.value);\n fetching ??= load()\n .then((value) => {\n fetched = { at: Date.now(), value };\n return value;\n })\n .catch((err: unknown) => {\n if (fetched) {\n logger.warn(`[pontive] ${what} refresh failed; serving the cached copy: ${String(err)}`);\n return fetched.value;\n }\n throw err;\n })\n .finally(() => {\n fetching = undefined;\n });\n return fetching;\n },\n };\n}\n\nexport function createResourceServer(config: ResourceServerConfig): ResourceServer {\n const issuers = (Array.isArray(config.issuer) ? config.issuer : [config.issuer]).map(trimSlash);\n if (issuers.length === 0 || issuers.some((i) => !i)) throw new Error(\"resource server: issuer is required\");\n if (!config.resource) throw new Error(\"resource server: resource is required\");\n\n const resource = config.resource;\n const fetchImpl = config.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const logger = config.logger ?? console;\n const leeway = config.leewaySeconds ?? 60;\n const location = metadataLocation(resource);\n const configuredScopes = (config.scopes ?? []).map((s) => (typeof s === \"string\" ? s : s.key));\n const unlistedTools = config.unlistedTools ?? \"deny\";\n\n if (config.metadata?.fetch && !location) {\n throw new Error(\"resource server: metadata is only served for an http(s) resource identifier\");\n }\n\n // One remote key set per issuer: jose caches the keys for ten minutes and\n // refetches on an unknown kid (at most every 30 s), which is how a key\n // rotation is picked up. A failed discovery is not cached.\n const keySets = new Map<string, Promise<JWTVerifyGetKey>>();\n const keySet = (issuer: string): Promise<JWTVerifyGetKey> => {\n let pending = keySets.get(issuer);\n if (!pending) {\n pending = discover(issuer, fetchImpl)\n .then((disc) => createRemoteJWKSet(new URL(disc.jwks_uri), { [customFetch]: fetchImpl }))\n .catch((err: unknown) => {\n keySets.delete(issuer);\n throw err;\n });\n keySets.set(issuer, pending);\n }\n return pending;\n };\n\n const challenge = (scopes: string[], error?: \"invalid_token\"): string => {\n const params: string[] = [];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n if (scopes.length) params.push(`scope=${quote(scopes.join(\" \"))}`);\n if (error) params.push(`error=${quote(error)}`);\n return params.length ? `Bearer ${params.join(\", \")}` : \"Bearer\";\n };\n\n const unauthorized = (scopes: string[], description: string, tokenSent: boolean) =>\n new BearerError(401, tokenSent ? \"invalid_token\" : undefined, challenge(scopes, tokenSent ? \"invalid_token\" : undefined), description);\n\n const insufficientScope = (scopes: string[], description = \"the token lacks a scope this route needs\") => {\n const params = [`error=\"insufficient_scope\"`, `scope=${quote(scopes.join(\" \"))}`];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n return new BearerError(403, \"insufficient_scope\", `Bearer ${params.join(\", \")}`, description);\n };\n\n // --- metadata -------------------------------------------------------------\n\n const localMetadata = (): ProtectedResourceMetadata => ({\n resource,\n authorization_servers: [...issuers],\n ...(configuredScopes.length ? { scopes_supported: [...configuredScopes] } : {}),\n bearer_methods_supported: [\"header\"],\n ...(config.resourceName ? { resource_name: config.resourceName } : {}),\n ...(config.resourceDocumentation ? { resource_documentation: config.resourceDocumentation } : {}),\n ...(config.logoUri ? { logo_uri: config.logoUri } : {}),\n });\n\n const credentialToken = config.metadata?.fetch\n ? managementTokenSource({ ...config.metadata.fetch, issuer: issuers[0]!, fetch: fetchImpl })\n : () => Promise.reject(new Error(\"resource server: no metadata credential\"));\n\n const fetchMetadata = async (): Promise<ProtectedResourceMetadata> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}/resource-metadata`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`resource metadata fetch failed: ${res.status}`);\n\n const doc = (await res.json()) as ProtectedResourceMetadata;\n // The metadata must describe the resource whose tokens this server accepts.\n if (doc.resource !== resource) {\n throw new Error(`resource metadata names ${doc.resource}, but this server accepts tokens for ${resource}`);\n }\n // Every issuer this server accepts is an authorization server for it.\n doc.authorization_servers = [...new Set([...(doc.authorization_servers ?? []), ...issuers])];\n doc.bearer_methods_supported = [\"header\"];\n return doc;\n };\n\n const fetchedMetadata = cachedLoader(fetchMetadata, \"resource metadata\", logger);\n\n const metadata = async (): Promise<ProtectedResourceMetadata> => {\n if (!location) throw new Error(`resource server: no metadata for ${resource}, which is not an http(s) URL`);\n if (!config.metadata?.fetch) return localMetadata();\n return fetchedMetadata.get();\n };\n\n // --- tool scopes (44 §12) -----------------------------------------------------\n\n // A tool's scopes: every scope whose `tools` lists it.\n const toolMapOf = (scopes: readonly (string | ApiScope)[]): Map<string, string[]> => {\n const map = new Map<string, string[]>();\n for (const scope of scopes) {\n if (typeof scope === \"string\" || !Array.isArray(scope.tools)) continue;\n for (const tool of scope.tools) {\n if (typeof tool?.name !== \"string\") continue;\n const keys = map.get(tool.name) ?? [];\n if (!keys.includes(scope.key)) keys.push(scope.key);\n map.set(tool.name, keys);\n }\n }\n return map;\n };\n\n const configuredToolMap = toolMapOf(config.scopes ?? []);\n\n const fetchToolMap = async (): Promise<Map<string, string[]>> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`api fetch failed: ${res.status}`);\n\n const api = (await res.json()) as { identifier?: string; scopes?: ApiScope[] };\n if (api.identifier !== resource) {\n throw new Error(`api ${apiId} is ${String(api.identifier)}, but this server accepts tokens for ${resource}`);\n }\n return toolMapOf(Array.isArray(api.scopes) ? api.scopes : []);\n };\n\n // Configured tools win; the API in Pontive is read only when none are configured.\n const fetchedToolMap =\n configuredToolMap.size === 0 && config.metadata?.fetch ? cachedLoader(fetchToolMap, \"api scopes\", logger) : undefined;\n\n const scopesForTool = async (name: string): Promise<string[]> => {\n const map = fetchedToolMap ? await fetchedToolMap.get() : configuredToolMap;\n return [...(map.get(name) ?? [])];\n };\n\n const warnedTools = new Set<string>();\n const authorizeTool = async (principal: Principal, name: string): Promise<void> => {\n const scopes = await scopesForTool(name);\n if (scopes.length === 0) {\n if (!warnedTools.has(name)) {\n warnedTools.add(name);\n logger.warn(\n `[pontive] the tool \"${name}\" is listed by no scope of ${resource}` +\n (unlistedTools === \"deny\" ? \"; calls to it are refused until a tool import lists it\" : \"\"),\n );\n }\n if (unlistedTools === \"allow\") return;\n // No scope could allow it, so the challenge names none and asks for no step-up.\n const params = location ? ` resource_metadata=${quote(location.url)}` : \"\";\n throw new BearerError(403, \"insufficient_scope\", `Bearer${params}`, `no scope of this API lists the tool \"${name}\"`);\n }\n if (scopes.some((scope) => principal.scopes.includes(scope))) return;\n throw insufficientScope(scopes, `the token holds none of the scopes that list the tool \"${name}\": ${scopes.join(\", \")}`);\n };\n\n const authorizeToolCalls = async (principal: Principal, message: unknown): Promise<void> => {\n for (const m of Array.isArray(message) ? message : [message]) {\n if (!m || typeof m !== \"object\") continue;\n const { method, params } = m as { method?: unknown; params?: { name?: unknown } };\n // A call without a name is the SDK's to refuse, as invalid params.\n if (method === \"tools/call\" && typeof params?.name === \"string\") await authorizeTool(principal, params.name);\n }\n };\n\n const requireTool = (name: string, options?: BearerOptions) => async (request: Request) => {\n try {\n const principal = await verify(request, options);\n await authorizeTool(principal, name);\n return principal;\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- scope drift ------------------------------------------------------------\n\n const warned = new Set<string>();\n const warnUnknownScopes = (scopes: string[]) => {\n const known = new Set([...configuredScopes, ...(fetchedMetadata.last?.scopes_supported ?? [])]);\n // Nothing declared, nothing to drift from.\n if (known.size === 0) return;\n\n for (const scope of scopes) {\n if (known.has(scope) || OIDC_SCOPES.has(scope) || warned.has(scope)) continue;\n warned.add(scope);\n logger.warn(\n `[pontive] a verified token for ${resource} carries the scope \"${scope}\", which this resource server's configuration does not list`,\n );\n }\n };\n\n // --- verification -----------------------------------------------------------\n\n const verifyToken = async (token: string, options?: BearerOptions): Promise<Principal> => {\n const required = options?.scopes ?? [];\n\n let unverified: JWTPayload;\n try {\n unverified = decodeJwt(token);\n } catch {\n throw unauthorized(required, \"the token is not a JWT\", true);\n }\n\n const issuer = typeof unverified.iss === \"string\" ? trimSlash(unverified.iss) : undefined;\n if (!issuer || !issuers.includes(issuer)) throw unauthorized(required, \"the token's issuer is not accepted\", true);\n\n let payload: JWTPayload;\n try {\n ({ payload } = await jwtVerify(token, await keySet(issuer), {\n issuer: unverified.iss as string,\n audience: resource,\n clockTolerance: leeway,\n // An access token (RFC 9068). An ID token is never one, and its\n // audience is the client besides.\n typ: \"at+jwt\",\n requiredClaims: [\"exp\", \"sub\"],\n }));\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code && INVALID_TOKEN_CODES.has(code)) throw unauthorized(required, (err as Error).message, true);\n throw err;\n }\n\n const sub = payload.sub!;\n const kind = KINDS[sub.slice(0, sub.indexOf(\"_\"))];\n if (!kind) throw unauthorized(required, \"the token's subject is not a user, service account or agent\", true);\n\n const base = {\n sub,\n kind,\n clientId: typeof payload.client_id === \"string\" ? payload.client_id : typeof payload.azp === \"string\" ? payload.azp : \"\",\n ...(typeof payload.org_id === \"string\" && payload.org_id ? { orgId: payload.org_id } : {}),\n roles: stringArray(payload.roles),\n permissions: stringArray(payload.permissions),\n scopes: typeof payload.scope === \"string\" ? payload.scope.split(\" \").filter(Boolean) : [],\n ...(kind === \"agent\" && typeof payload.agent_instance === \"string\"\n ? { agentInstance: payload.agent_instance }\n : {}),\n token,\n claims: payload,\n };\n\n const act = payload.act as { sub?: unknown; agent_instance?: unknown } | undefined;\n const actorSub = act && typeof act.sub === \"string\" ? act.sub : undefined;\n let principal: Principal;\n if (actorSub?.startsWith(\"agt_\")) {\n principal = {\n ...base,\n isDelegated: true,\n actor: {\n sub: actorSub,\n kind: \"agent\",\n ...(typeof act!.agent_instance === \"string\" ? { agentInstance: act!.agent_instance } : {}),\n },\n };\n } else if (actorSub?.startsWith(\"svc_\")) {\n principal = { ...base, isDelegated: false, actor: { sub: actorSub, kind: \"service_account\" } };\n } else if (actorSub) {\n // An act this server does not know how to evaluate: refuse it rather\n // than let the subject's authority stand for an unknown caller.\n throw unauthorized(required, \"the token's actor is not an agent or a service account\", true);\n } else {\n principal = { ...base, isDelegated: false };\n }\n\n warnUnknownScopes(principal.scopes);\n\n if (required.some((scope) => !principal.scopes.includes(scope))) throw insufficientScope(required);\n\n return principal;\n };\n\n const verify = async (request: RequestLike, options?: BearerOptions): Promise<Principal> => {\n const token = bearerToken(request);\n if (!token) throw unauthorized(options?.scopes ?? [], \"a bearer token is required\", false);\n return verifyToken(token, options);\n };\n\n const requireBearer = (options?: BearerOptions) => async (request: Request) => {\n try {\n return await verify(request, options);\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- well-known routes ------------------------------------------------------\n\n const metadataRoute: RouteHandlers = {\n async GET(request) {\n if (!location) return new Response(null, { status: 404 });\n try {\n return Response.json(await metadata(), {\n headers: { \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] resource metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 503, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n let asMetadata: { at: number; body: string } | undefined;\n const authorizationServerMetadata = async (): Promise<string> => {\n if (asMetadata && Date.now() - asMetadata.at < AS_METADATA_TTL_MS) return asMetadata.body;\n\n // RFC 8414's document, or the OIDC discovery document, which is a superset.\n for (const path of [AS_PATH, \"/.well-known/openid-configuration\"]) {\n const res = await fetchImpl(`${issuers[0]}${path}`);\n if (res.ok) {\n asMetadata = { at: Date.now(), body: await res.text() };\n return asMetadata.body;\n }\n }\n throw new Error(`no authorization server metadata at ${issuers[0]}`);\n };\n\n const authorizationServerMetadataRoute: RouteHandlers = {\n async GET(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n try {\n return new Response(await authorizationServerMetadata(), {\n headers: { \"content-type\": \"application/json\", \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] authorization server metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 502, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n const route = (handlers: RouteHandlers, request: Request): Promise<Response> => {\n if (request.method === \"GET\" || request.method === \"HEAD\") return handlers.GET(request);\n if (request.method === \"OPTIONS\") return handlers.OPTIONS(request);\n return Promise.resolve(new Response(null, { status: 405, headers: { allow: \"GET, OPTIONS\" } }));\n };\n\n const handleWellKnown = async (request: Request): Promise<Response | null> => {\n const path = trimSlash(new URL(request.url).pathname);\n if (location?.paths.includes(path)) return route(metadataRoute, request);\n if (config.authorizationServerMetadataProxy && path === AS_PATH) {\n return route(authorizationServerMetadataRoute, request);\n }\n return null;\n };\n\n return {\n resource,\n issuers,\n leewaySeconds: leeway,\n metadataUrl: location?.url,\n metadataPaths: location?.paths ?? [],\n verify,\n verifyToken,\n metadata,\n requireBearer,\n scopesForTool,\n authorizeTool,\n authorizeToolCalls,\n requireTool,\n metadataRoute,\n authorizationServerMetadataRoute,\n handleWellKnown,\n };\n}\n"],"names":["BearerError","status","code","wwwAuthenticate","description","PRM_PATH","AS_PATH","METADATA_TTL_MS","AS_METADATA_TTL_MS","OIDC_SCOPES","KINDS","INVALID_TOKEN_CODES","trimSlash","value","metadataLocation","resource","url","suffix","quote","stringArray","v","headerOf","request","name","headers","bearerToken","corsHeaders","cachedLoader","load","what","logger","fetched","fetching","err","createResourceServer","config","issuers","i","fetchImpl","args","leeway","location","configuredScopes","s","unlistedTools","keySets","keySet","issuer","pending","discover","disc","createRemoteJWKSet","customFetch","challenge","scopes","error","params","unauthorized","tokenSent","insufficientScope","localMetadata","credentialToken","managementTokenSource","fetchedMetadata","apiId","managementUrl","managementBase","res","doc","metadata","toolMapOf","map","scope","tool","keys","configuredToolMap","fetchToolMap","api","fetchedToolMap","scopesForTool","warnedTools","authorizeTool","principal","authorizeToolCalls","message","m","method","requireTool","options","verify","warned","warnUnknownScopes","known","verifyToken","token","required","unverified","decodeJwt","payload","jwtVerify","sub","kind","base","act","actorSub","requireBearer","metadataRoute","asMetadata","authorizationServerMetadata","path","authorizationServerMetadataRoute","route","handlers","handleWellKnown"],"mappings":"0JAgPO,MAAMA,UAAoB,KAAM,CACrC,YACWC,EAEAC,EAEAC,EACTC,EACA,CACA,MAAMA,CAAW,EAPR,KAAA,OAAAH,EAEA,KAAA,KAAAC,EAEA,KAAA,gBAAAC,EAIT,KAAK,KAAO,aACd,CATW,OAEA,KAEA,gBAOX,YAAuB,CACrB,OAAO,SAAS,KACd,CAAE,MAAO,KAAK,MAAQ,eAAgB,kBAAmB,KAAK,OAAA,EAC9D,CAAE,OAAQ,KAAK,OAAQ,QAAS,CAAE,mBAAoB,KAAK,gBAAiB,gBAAiB,UAAA,CAAW,CAAE,CAE9G,CACF,CAgEA,MAAME,EAAW,wCACXC,EAAU,0CACVC,GAAkB,IAAS,IAC3BC,GAAqB,IAAU,IAG/BC,GAAc,IAAI,IAAI,CAAC,SAAU,UAAW,QAAS,UAAW,QAAS,gBAAgB,CAAC,EAE1FC,GAAuC,CAAE,IAAK,OAAQ,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A,GAAU,OAAS,CAAA,EAClC,OAAAgD,EACA,YAAAI,EACA,SAAAxB,EACA,cAAAoC,GACA,cAAA1B,EACA,cAAAE,EACA,mBAAAE,GACA,YAAAI,GACA,cAAAmB,EACA,iCAAAI,EACA,gBAAAG,EAAA,CAEJ"}
|
package/dist/resource-server.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { decodeJwt as ce, jwtVerify as ie, createRemoteJWKSet as ue, customFetch as le } from "jose";
|
|
2
|
-
import { a as he, m as V } from "./management-credential-
|
|
3
|
-
import { f as de } from "./oidc-CB0FqjFz.js";
|
|
2
|
+
import { a as he, d as de, m as V } from "./management-credential-CynS93TR.js";
|
|
4
3
|
class T extends Error {
|
|
5
4
|
constructor(a, n, i, l) {
|
|
6
5
|
super(l), this.status = a, this.code = n, this.wwwAuthenticate = i, this.name = "BearerError";
|
|
@@ -78,7 +77,7 @@ function q(o, a, n) {
|
|
|
78
77
|
}
|
|
79
78
|
};
|
|
80
79
|
}
|
|
81
|
-
function
|
|
80
|
+
function Re(o) {
|
|
82
81
|
const a = (Array.isArray(o.issuer) ? o.issuer : [o.issuer]).map(E);
|
|
83
82
|
if (a.length === 0 || a.some((e) => !e)) throw new Error("resource server: issuer is required");
|
|
84
83
|
if (!o.resource) throw new Error("resource server: resource is required");
|
|
@@ -296,6 +295,6 @@ function $e(o) {
|
|
|
296
295
|
}
|
|
297
296
|
export {
|
|
298
297
|
T as BearerError,
|
|
299
|
-
|
|
298
|
+
Re as createResourceServer
|
|
300
299
|
};
|
|
301
300
|
//# sourceMappingURL=resource-server.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-server.js","sources":["../src/resource-server.ts"],"sourcesContent":["import {\n createRemoteJWKSet,\n customFetch,\n decodeJwt,\n jwtVerify,\n type JWTPayload,\n type JWTVerifyGetKey,\n} from \"jose\";\n\nimport { managementBase, managementTokenSource, type ManagementCredential } from \"./management-credential\";\nimport { discover } from \"./oidc\";\n\n/**\n * Resource-server middleware: protect an API or an MCP server with tokens a\n * Pontive instance issued for it (pontive-spec 44 §11).\n *\n * `createResourceServer` verifies bearer tokens locally against each issuer's\n * keys, answers a missing or failing token with the `WWW-Authenticate`\n * challenge an MCP client follows, and serves the API's protected resource\n * metadata (RFC 9728). Per request it calls nothing but the cached JWKS.\n *\n * This entry speaks Web `Request`/`Response` (Next route handlers, Hono,\n * Workers, Bun, Deno). `@pontive/server/resource-server/express` and\n * `@pontive/server/resource-server/mcp` adapt it to Express and to the\n * MCP TypeScript SDK.\n */\n\n/** Who a verified token speaks for, told apart by the subject's id prefix. */\nexport type PrincipalKind = \"user\" | \"service_account\" | \"agent\";\n\n/** What every verified principal carries. */\ninterface PrincipalBase {\n /**\n * `usr_…`, `svc_…` or `agt_…`: whom the token speaks for.\n *\n * **For a delegated principal (`isDelegated`) this is the delegator, not the\n * caller.** The caller is the agent in `actor`, and its authority is the\n * intersection of the user's and the agent's, never the user's alone. Do not\n * read or write your own data by `principal.sub` alone for a delegated\n * principal: check by token with the authorization client\n * (`@pontive/server/authorization`), which evaluates the pair, or\n * branch on `principal.isDelegated`.\n */\n sub: string;\n /** From the sub's id prefix; no claim needed. A delegated token's subject is a user, so its kind is `\"user\"`. */\n kind: PrincipalKind;\n /** The client the token was issued to. */\n clientId: string;\n /** The organization the token is scoped to, when it is. */\n orgId?: string;\n /** The token's roles. For a delegated token, already intersected by Pontive (the delegator's roles the agent also holds). */\n roles: string[];\n /** The token's permissions. For a delegated token, already intersected by Pontive. */\n permissions: string[];\n /** The token's granted scopes. */\n scopes: string[];\n /** The agent instance, when the subject itself is an agent. */\n agentInstance?: string;\n /** The raw token, e.g. to check permissions by token. */\n token: string;\n /**\n * Every claim of the verified token: the claims template's (say\n * `legacy_user_id`) beside the standard ones the fields above are read\n * from. A claim is whatever the issuer wrote, so check its type before\n * using it.\n */\n claims: Record<string, unknown>;\n}\n\n/** Who acts for the subject, from the token's `act` claim (RFC 8693 §4.1). */\nexport interface PrincipalActor {\n /** `agt_…` for an agent acting for its delegator; `svc_…` for an API's backend calling downstream for the user. */\n sub: string;\n kind: \"agent\" | \"service_account\";\n /** The agent's running copy, when it named one. */\n agentInstance?: string;\n}\n\n/**\n * A token an agent holds for its delegator (profile (b), `act.sub` is\n * `agt_…`). `sub` is the user; `actor` is the agent. Its authority is the\n * intersection of both: answer it with a check by token, never by `sub`.\n */\nexport interface DelegatedPrincipal extends PrincipalBase {\n isDelegated: true;\n actor: PrincipalActor & { kind: \"agent\" };\n}\n\n/**\n * Any other token: the subject acts for itself. An `actor` here is a\n * registered API's backend service account calling downstream for the user\n * (profile (a)), a conduit: only the subject is evaluated.\n */\nexport interface UndelegatedPrincipal extends PrincipalBase {\n isDelegated: false;\n actor?: PrincipalActor & { kind: \"service_account\" };\n}\n\n/**\n * The verified caller, as the handler sees it. Narrow on `isDelegated`: a\n * delegated principal's `sub` is the user an agent acts for, and its authority\n * is narrower than that user's.\n */\nexport type Principal = DelegatedPrincipal | UndelegatedPrincipal;\n\n/** The protected resource metadata document (RFC 9728; pontive-spec 44 §9). */\nexport interface ProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n scopes_supported?: string[];\n bearer_methods_supported: string[];\n resource_name?: string;\n resource_documentation?: string;\n logo_uri?: string;\n}\n\n/**\n * How the resource server gets a management API token to read its own\n * metadata: a token, a function returning one, or the client credentials of\n * the API's backend service account (exchanged at the first issuer for a\n * management-audience token, and reused until it is about to expire).\n */\nexport type MetadataCredential = ManagementCredential;\nexport type { ManagementCredential };\n\n/** An MCP tool a scope covers (pontive-spec 44 §5, §12). Only `name` is read here. */\nexport interface ApiScopeTool {\n /** The MCP tool name, as `tools/call` sends it. */\n name: string;\n title?: string;\n read_only?: boolean;\n destructive?: boolean;\n}\n\n/**\n * An API scope as the management API returns it (`GET /v1/apis/{api_id}`,\n * pontive-spec 44 §5), so the dashboard's scopes can be pasted as they are.\n * Only `key` and `tools` are read here.\n */\nexport interface ApiScope {\n key: string;\n description?: string;\n display_name?: string;\n origin?: \"manual\" | \"tool_import\";\n /** The MCP tools the scope covers; a token holding the scope may call each of them (`requireTool`). */\n tools?: ApiScopeTool[];\n}\n\nexport interface ResourceServerConfig {\n /**\n * The instance's issuer: its auth domain, e.g.\n * `https://acme.auth.us.pontive.app`. A list when the instance has more than\n * one auth domain (a custom domain beside the default): a token from any of\n * them is accepted, and each is listed in `authorization_servers`.\n */\n issuer: string | string[];\n /**\n * The API's identifier, exactly as registered. Tokens must carry it in\n * `aud`, and it is the metadata's `resource`. When it is an http(s) URL the\n * metadata is served under its origin (RFC 9728 §3.1).\n */\n resource: string;\n /**\n * The API's scopes, for `scopes_supported`: keys, or the scopes as the\n * management API returns them (`ApiScope`). A scope's `tools` are the MCP\n * tools a token holding it may call (`requireTool`, pontive-spec 44 §12).\n */\n scopes?: (string | ApiScope)[];\n /**\n * What `requireTool` does with a tool no scope lists. `\"deny\"` (the\n * default) refuses it with a `403` that names no scope, since no scope\n * could allow it: a tool added to the server after the last tool import is\n * refused, and logged once, until the import lists it. `\"allow\"` lets any\n * valid token call it.\n */\n unlistedTools?: \"deny\" | \"allow\";\n /** The metadata's `resource_name`. */\n resourceName?: string;\n /** The metadata's `resource_documentation`. */\n resourceDocumentation?: string;\n /** The metadata's `logo_uri`. */\n logoUri?: string;\n /**\n * Read the metadata from Pontive instead of building it from this\n * configuration, for an API whose scopes and display fields are kept in the\n * dashboard. It is fetched on first use and cached for five minutes.\n *\n * When no configured scope lists tools, `requireTool` reads the scopes and\n * their tools from the same API (`GET /v1/apis/{api_id}`, with the\n * same credential and `sys:api:read`), cached the same way.\n */\n metadata?: {\n fetch: {\n /** The API's id (`api_…`). */\n apiId: string;\n /** A credential the management API accepts for `GET /v1/apis/{api_id}/resource-metadata`. */\n credential: MetadataCredential;\n /**\n * The management API's origin in the instance's region, e.g. `https://api.us.pontive.com`.\n * A `/v1`, `/mgmt` or `/mgmt/v1` suffix is dropped (`managementBase`).\n */\n managementUrl: string;\n };\n };\n /**\n * Also serve `/.well-known/oauth-authorization-server`, proxying the\n * issuer's own document, for older MCP clients that ask the resource server\n * for it. Default false.\n */\n authorizationServerMetadataProxy?: boolean;\n /** Clock skew allowed on `exp` and `nbf`. Default 60. */\n leewaySeconds?: number;\n /** Defaults to the global `fetch`. Used for discovery, JWKS and metadata. */\n fetch?: typeof fetch;\n /** Where configuration drift is reported. Defaults to `console`. */\n logger?: Pick<Console, \"warn\">;\n}\n\n/** What a route needs of the token beyond its being valid. */\nexport interface BearerOptions {\n /** Every one of these must be granted. */\n scopes?: string[];\n}\n\n/** Anything with request headers: a Web `Request`, `Headers`, or a Node/Express request. */\nexport type RequestLike =\n | Request\n | { headers: Headers | Record<string, string | string[] | undefined> };\n\n/** A route handler pair, e.g. to export from a Next `route.ts`. */\nexport interface RouteHandlers {\n GET(request: Request): Promise<Response>;\n OPTIONS(request: Request): Promise<Response>;\n}\n\n/**\n * Why a request was refused: a `401` (no token, or one that failed) or a\n * `403` (a valid token without a scope the route needs). `toResponse()` is the\n * answer to send.\n */\nexport class BearerError extends Error {\n constructor(\n readonly status: 401 | 403,\n /** Absent when no token was sent (RFC 6750 §3.1). */\n readonly code: \"invalid_token\" | \"insufficient_scope\" | undefined,\n /** The `WWW-Authenticate` header value. */\n readonly wwwAuthenticate: string,\n description: string,\n ) {\n super(description);\n this.name = \"BearerError\";\n }\n\n toResponse(): Response {\n return Response.json(\n { error: this.code ?? \"unauthorized\", error_description: this.message },\n { status: this.status, headers: { \"www-authenticate\": this.wwwAuthenticate, \"cache-control\": \"no-store\" } },\n );\n }\n}\n\nexport interface ResourceServer {\n /** The API identifier tokens must carry in `aud`. */\n readonly resource: string;\n /** The accepted issuers. */\n readonly issuers: readonly string[];\n /** The clock skew allowed on `exp` and `nbf`. */\n readonly leewaySeconds: number;\n /** The metadata's URL, named in every challenge; absent for an identifier that is not an http(s) URL. */\n readonly metadataUrl: string | undefined;\n /** The paths the metadata is served at: the RFC 9728 §3.1 path-suffixed one first. */\n readonly metadataPaths: readonly string[];\n\n /** Verifies the request's bearer token. Throws a `BearerError` when it is missing, fails, or lacks a scope. */\n verify(request: RequestLike, options?: BearerOptions): Promise<Principal>;\n /** Verifies a raw token, as `verify` does. */\n verifyToken(token: string, options?: BearerOptions): Promise<Principal>;\n /** The protected resource metadata document. */\n metadata(): Promise<ProtectedResourceMetadata>;\n /**\n * A guard for Web-standard handlers: the principal, or the `401`/`403`\n * response to return as it is.\n */\n requireBearer(options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /**\n * The scopes that list an MCP tool (pontive-spec 44 §12), from the\n * configured scopes, else from the API in Pontive when `metadata.fetch` is\n * set. Empty for a tool no scope lists.\n */\n scopesForTool(name: string): Promise<string[]>;\n /**\n * Refuses a principal that holds none of the scopes listing the tool: a\n * `BearerError` `403` with `error=\"insufficient_scope\"` and\n * `scope=\"<every scope listing the tool>\"`, any one of which would do. A\n * tool no scope lists follows `unlistedTools`.\n */\n authorizeTool(principal: Principal, name: string): Promise<void>;\n /**\n * `authorizeTool` for every `tools/call` in a JSON-RPC message or batch, as\n * an MCP client posts it; any other message passes. Throws the first refusal.\n * Run it on the parsed body before the MCP transport sees it, so the refusal\n * is an HTTP `403` the client can step up from.\n */\n authorizeToolCalls(principal: Principal, message: unknown): Promise<void>;\n /**\n * A guard for a Web-standard handler that serves one tool: the principal,\n * or the `401`/`403` response to return as it is.\n */\n requireTool(name: string, options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /** `GET` and `OPTIONS` for the protected resource metadata route. */\n readonly metadataRoute: RouteHandlers;\n /** `GET` and `OPTIONS` for the authorization server metadata proxy (404 unless the proxy is on). */\n readonly authorizationServerMetadataRoute: RouteHandlers;\n /**\n * Answers any of the well-known routes this server serves (both metadata\n * paths, and the AS-metadata proxy when on), or null for any other path. For\n * a catch-all: `return (await rs.handleWellKnown(req)) ?? next()`.\n */\n handleWellKnown(request: Request): Promise<Response | null>;\n}\n\nconst PRM_PATH = \"/.well-known/oauth-protected-resource\";\nconst AS_PATH = \"/.well-known/oauth-authorization-server\";\nconst METADATA_TTL_MS = 5 * 60 * 1000;\nconst AS_METADATA_TTL_MS = 10 * 60 * 1000;\n\n/** OIDC's own scopes, which a token may carry beside the API's. */\nconst OIDC_SCOPES = new Set([\"openid\", \"profile\", \"email\", \"address\", \"phone\", \"offline_access\"]);\n\nconst KINDS: Record<string, PrincipalKind> = { usr: \"user\", svc: \"service_account\", agt: \"agent\" };\n\n/** jose errors that mean the token is bad, rather than that the keys could not be fetched. */\nconst INVALID_TOKEN_CODES = new Set([\n \"ERR_JWT_EXPIRED\",\n \"ERR_JWT_CLAIM_VALIDATION_FAILED\",\n \"ERR_JWT_INVALID\",\n \"ERR_JWS_INVALID\",\n \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\",\n \"ERR_JWKS_NO_MATCHING_KEY\",\n \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\",\n \"ERR_JOSE_ALG_NOT_ALLOWED\",\n \"ERR_JOSE_NOT_SUPPORTED\",\n]);\n\nconst trimSlash = (value: string) => value.replace(/\\/+$/, \"\");\n\n/** Where the metadata lives for an http(s) identifier (RFC 9728 §3.1); undefined for any other. */\nfunction metadataLocation(resource: string): { url: string; paths: string[] } | undefined {\n let url: URL;\n try {\n url = new URL(resource);\n } catch {\n return undefined;\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return undefined;\n\n const suffix = url.pathname === \"/\" ? \"\" : trimSlash(url.pathname);\n return {\n url: `${url.origin}${PRM_PATH}${suffix}`,\n paths: suffix ? [`${PRM_PATH}${suffix}`, PRM_PATH] : [PRM_PATH],\n };\n}\n\nfunction quote(value: string): string {\n return `\"${value.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : [];\n}\n\nfunction headerOf(request: RequestLike, name: string): string | undefined {\n const headers = request.headers;\n if (headers instanceof Headers) return headers.get(name) ?? undefined;\n\n const value = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/** The token from `Authorization: Bearer …`, the only bearer method this server supports. */\nfunction bearerToken(request: RequestLike): string | undefined {\n const match = /^Bearer[ ]+([^ ]+)[ ]*$/i.exec(headerOf(request, \"authorization\") ?? \"\");\n return match?.[1];\n}\n\nconst corsHeaders = (request: Request): Record<string, string> => ({\n \"access-control-allow-origin\": \"*\",\n \"access-control-allow-methods\": \"GET, OPTIONS\",\n \"access-control-allow-headers\": request.headers.get(\"access-control-request-headers\") ?? \"*\",\n \"access-control-max-age\": \"86400\",\n});\n\n/**\n * A value fetched on first use and kept for five minutes. A failed refresh\n * keeps the last good value, logged; with none, the failure is thrown. One\n * fetch at a time.\n */\nfunction cachedLoader<T>(load: () => Promise<T>, what: string, logger: Pick<Console, \"warn\">) {\n let fetched: { at: number; value: T } | undefined;\n let fetching: Promise<T> | undefined;\n return {\n get last(): T | undefined {\n return fetched?.value;\n },\n get(): Promise<T> {\n if (fetched && Date.now() - fetched.at < METADATA_TTL_MS) return Promise.resolve(fetched.value);\n fetching ??= load()\n .then((value) => {\n fetched = { at: Date.now(), value };\n return value;\n })\n .catch((err: unknown) => {\n if (fetched) {\n logger.warn(`[pontive] ${what} refresh failed; serving the cached copy: ${String(err)}`);\n return fetched.value;\n }\n throw err;\n })\n .finally(() => {\n fetching = undefined;\n });\n return fetching;\n },\n };\n}\n\nexport function createResourceServer(config: ResourceServerConfig): ResourceServer {\n const issuers = (Array.isArray(config.issuer) ? config.issuer : [config.issuer]).map(trimSlash);\n if (issuers.length === 0 || issuers.some((i) => !i)) throw new Error(\"resource server: issuer is required\");\n if (!config.resource) throw new Error(\"resource server: resource is required\");\n\n const resource = config.resource;\n const fetchImpl = config.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const logger = config.logger ?? console;\n const leeway = config.leewaySeconds ?? 60;\n const location = metadataLocation(resource);\n const configuredScopes = (config.scopes ?? []).map((s) => (typeof s === \"string\" ? s : s.key));\n const unlistedTools = config.unlistedTools ?? \"deny\";\n\n if (config.metadata?.fetch && !location) {\n throw new Error(\"resource server: metadata is only served for an http(s) resource identifier\");\n }\n\n // One remote key set per issuer: jose caches the keys for ten minutes and\n // refetches on an unknown kid (at most every 30 s), which is how a key\n // rotation is picked up. A failed discovery is not cached.\n const keySets = new Map<string, Promise<JWTVerifyGetKey>>();\n const keySet = (issuer: string): Promise<JWTVerifyGetKey> => {\n let pending = keySets.get(issuer);\n if (!pending) {\n pending = discover(issuer, fetchImpl)\n .then((disc) => createRemoteJWKSet(new URL(disc.jwks_uri), { [customFetch]: fetchImpl }))\n .catch((err: unknown) => {\n keySets.delete(issuer);\n throw err;\n });\n keySets.set(issuer, pending);\n }\n return pending;\n };\n\n const challenge = (scopes: string[], error?: \"invalid_token\"): string => {\n const params: string[] = [];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n if (scopes.length) params.push(`scope=${quote(scopes.join(\" \"))}`);\n if (error) params.push(`error=${quote(error)}`);\n return params.length ? `Bearer ${params.join(\", \")}` : \"Bearer\";\n };\n\n const unauthorized = (scopes: string[], description: string, tokenSent: boolean) =>\n new BearerError(401, tokenSent ? \"invalid_token\" : undefined, challenge(scopes, tokenSent ? \"invalid_token\" : undefined), description);\n\n const insufficientScope = (scopes: string[], description = \"the token lacks a scope this route needs\") => {\n const params = [`error=\"insufficient_scope\"`, `scope=${quote(scopes.join(\" \"))}`];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n return new BearerError(403, \"insufficient_scope\", `Bearer ${params.join(\", \")}`, description);\n };\n\n // --- metadata -------------------------------------------------------------\n\n const localMetadata = (): ProtectedResourceMetadata => ({\n resource,\n authorization_servers: [...issuers],\n ...(configuredScopes.length ? { scopes_supported: [...configuredScopes] } : {}),\n bearer_methods_supported: [\"header\"],\n ...(config.resourceName ? { resource_name: config.resourceName } : {}),\n ...(config.resourceDocumentation ? { resource_documentation: config.resourceDocumentation } : {}),\n ...(config.logoUri ? { logo_uri: config.logoUri } : {}),\n });\n\n const credentialToken = config.metadata?.fetch\n ? managementTokenSource({ ...config.metadata.fetch, issuer: issuers[0]!, fetch: fetchImpl })\n : () => Promise.reject(new Error(\"resource server: no metadata credential\"));\n\n const fetchMetadata = async (): Promise<ProtectedResourceMetadata> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}/resource-metadata`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`resource metadata fetch failed: ${res.status}`);\n\n const doc = (await res.json()) as ProtectedResourceMetadata;\n // The metadata must describe the resource whose tokens this server accepts.\n if (doc.resource !== resource) {\n throw new Error(`resource metadata names ${doc.resource}, but this server accepts tokens for ${resource}`);\n }\n // Every issuer this server accepts is an authorization server for it.\n doc.authorization_servers = [...new Set([...(doc.authorization_servers ?? []), ...issuers])];\n doc.bearer_methods_supported = [\"header\"];\n return doc;\n };\n\n const fetchedMetadata = cachedLoader(fetchMetadata, \"resource metadata\", logger);\n\n const metadata = async (): Promise<ProtectedResourceMetadata> => {\n if (!location) throw new Error(`resource server: no metadata for ${resource}, which is not an http(s) URL`);\n if (!config.metadata?.fetch) return localMetadata();\n return fetchedMetadata.get();\n };\n\n // --- tool scopes (44 §12) -----------------------------------------------------\n\n // A tool's scopes: every scope whose `tools` lists it.\n const toolMapOf = (scopes: readonly (string | ApiScope)[]): Map<string, string[]> => {\n const map = new Map<string, string[]>();\n for (const scope of scopes) {\n if (typeof scope === \"string\" || !Array.isArray(scope.tools)) continue;\n for (const tool of scope.tools) {\n if (typeof tool?.name !== \"string\") continue;\n const keys = map.get(tool.name) ?? [];\n if (!keys.includes(scope.key)) keys.push(scope.key);\n map.set(tool.name, keys);\n }\n }\n return map;\n };\n\n const configuredToolMap = toolMapOf(config.scopes ?? []);\n\n const fetchToolMap = async (): Promise<Map<string, string[]>> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`api fetch failed: ${res.status}`);\n\n const api = (await res.json()) as { identifier?: string; scopes?: ApiScope[] };\n if (api.identifier !== resource) {\n throw new Error(`api ${apiId} is ${String(api.identifier)}, but this server accepts tokens for ${resource}`);\n }\n return toolMapOf(Array.isArray(api.scopes) ? api.scopes : []);\n };\n\n // Configured tools win; the API in Pontive is read only when none are configured.\n const fetchedToolMap =\n configuredToolMap.size === 0 && config.metadata?.fetch ? cachedLoader(fetchToolMap, \"api scopes\", logger) : undefined;\n\n const scopesForTool = async (name: string): Promise<string[]> => {\n const map = fetchedToolMap ? await fetchedToolMap.get() : configuredToolMap;\n return [...(map.get(name) ?? [])];\n };\n\n const warnedTools = new Set<string>();\n const authorizeTool = async (principal: Principal, name: string): Promise<void> => {\n const scopes = await scopesForTool(name);\n if (scopes.length === 0) {\n if (!warnedTools.has(name)) {\n warnedTools.add(name);\n logger.warn(\n `[pontive] the tool \"${name}\" is listed by no scope of ${resource}` +\n (unlistedTools === \"deny\" ? \"; calls to it are refused until a tool import lists it\" : \"\"),\n );\n }\n if (unlistedTools === \"allow\") return;\n // No scope could allow it, so the challenge names none and asks for no step-up.\n const params = location ? ` resource_metadata=${quote(location.url)}` : \"\";\n throw new BearerError(403, \"insufficient_scope\", `Bearer${params}`, `no scope of this API lists the tool \"${name}\"`);\n }\n if (scopes.some((scope) => principal.scopes.includes(scope))) return;\n throw insufficientScope(scopes, `the token holds none of the scopes that list the tool \"${name}\": ${scopes.join(\", \")}`);\n };\n\n const authorizeToolCalls = async (principal: Principal, message: unknown): Promise<void> => {\n for (const m of Array.isArray(message) ? message : [message]) {\n if (!m || typeof m !== \"object\") continue;\n const { method, params } = m as { method?: unknown; params?: { name?: unknown } };\n // A call without a name is the SDK's to refuse, as invalid params.\n if (method === \"tools/call\" && typeof params?.name === \"string\") await authorizeTool(principal, params.name);\n }\n };\n\n const requireTool = (name: string, options?: BearerOptions) => async (request: Request) => {\n try {\n const principal = await verify(request, options);\n await authorizeTool(principal, name);\n return principal;\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- scope drift ------------------------------------------------------------\n\n const warned = new Set<string>();\n const warnUnknownScopes = (scopes: string[]) => {\n const known = new Set([...configuredScopes, ...(fetchedMetadata.last?.scopes_supported ?? [])]);\n // Nothing declared, nothing to drift from.\n if (known.size === 0) return;\n\n for (const scope of scopes) {\n if (known.has(scope) || OIDC_SCOPES.has(scope) || warned.has(scope)) continue;\n warned.add(scope);\n logger.warn(\n `[pontive] a verified token for ${resource} carries the scope \"${scope}\", which this resource server's configuration does not list`,\n );\n }\n };\n\n // --- verification -----------------------------------------------------------\n\n const verifyToken = async (token: string, options?: BearerOptions): Promise<Principal> => {\n const required = options?.scopes ?? [];\n\n let unverified: JWTPayload;\n try {\n unverified = decodeJwt(token);\n } catch {\n throw unauthorized(required, \"the token is not a JWT\", true);\n }\n\n const issuer = typeof unverified.iss === \"string\" ? trimSlash(unverified.iss) : undefined;\n if (!issuer || !issuers.includes(issuer)) throw unauthorized(required, \"the token's issuer is not accepted\", true);\n\n let payload: JWTPayload;\n try {\n ({ payload } = await jwtVerify(token, await keySet(issuer), {\n issuer: unverified.iss as string,\n audience: resource,\n clockTolerance: leeway,\n // An access token (RFC 9068). An ID token is never one, and its\n // audience is the client besides.\n typ: \"at+jwt\",\n requiredClaims: [\"exp\", \"sub\"],\n }));\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code && INVALID_TOKEN_CODES.has(code)) throw unauthorized(required, (err as Error).message, true);\n throw err;\n }\n\n const sub = payload.sub!;\n const kind = KINDS[sub.slice(0, sub.indexOf(\"_\"))];\n if (!kind) throw unauthorized(required, \"the token's subject is not a user, service account or agent\", true);\n\n const base = {\n sub,\n kind,\n clientId: typeof payload.client_id === \"string\" ? payload.client_id : typeof payload.azp === \"string\" ? payload.azp : \"\",\n ...(typeof payload.org_id === \"string\" && payload.org_id ? { orgId: payload.org_id } : {}),\n roles: stringArray(payload.roles),\n permissions: stringArray(payload.permissions),\n scopes: typeof payload.scope === \"string\" ? payload.scope.split(\" \").filter(Boolean) : [],\n ...(kind === \"agent\" && typeof payload.agent_instance === \"string\"\n ? { agentInstance: payload.agent_instance }\n : {}),\n token,\n claims: payload,\n };\n\n const act = payload.act as { sub?: unknown; agent_instance?: unknown } | undefined;\n const actorSub = act && typeof act.sub === \"string\" ? act.sub : undefined;\n let principal: Principal;\n if (actorSub?.startsWith(\"agt_\")) {\n principal = {\n ...base,\n isDelegated: true,\n actor: {\n sub: actorSub,\n kind: \"agent\",\n ...(typeof act!.agent_instance === \"string\" ? { agentInstance: act!.agent_instance } : {}),\n },\n };\n } else if (actorSub?.startsWith(\"svc_\")) {\n principal = { ...base, isDelegated: false, actor: { sub: actorSub, kind: \"service_account\" } };\n } else if (actorSub) {\n // An act this server does not know how to evaluate: refuse it rather\n // than let the subject's authority stand for an unknown caller.\n throw unauthorized(required, \"the token's actor is not an agent or a service account\", true);\n } else {\n principal = { ...base, isDelegated: false };\n }\n\n warnUnknownScopes(principal.scopes);\n\n if (required.some((scope) => !principal.scopes.includes(scope))) throw insufficientScope(required);\n\n return principal;\n };\n\n const verify = async (request: RequestLike, options?: BearerOptions): Promise<Principal> => {\n const token = bearerToken(request);\n if (!token) throw unauthorized(options?.scopes ?? [], \"a bearer token is required\", false);\n return verifyToken(token, options);\n };\n\n const requireBearer = (options?: BearerOptions) => async (request: Request) => {\n try {\n return await verify(request, options);\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- well-known routes ------------------------------------------------------\n\n const metadataRoute: RouteHandlers = {\n async GET(request) {\n if (!location) return new Response(null, { status: 404 });\n try {\n return Response.json(await metadata(), {\n headers: { \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] resource metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 503, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n let asMetadata: { at: number; body: string } | undefined;\n const authorizationServerMetadata = async (): Promise<string> => {\n if (asMetadata && Date.now() - asMetadata.at < AS_METADATA_TTL_MS) return asMetadata.body;\n\n // RFC 8414's document, or the OIDC discovery document, which is a superset.\n for (const path of [AS_PATH, \"/.well-known/openid-configuration\"]) {\n const res = await fetchImpl(`${issuers[0]}${path}`);\n if (res.ok) {\n asMetadata = { at: Date.now(), body: await res.text() };\n return asMetadata.body;\n }\n }\n throw new Error(`no authorization server metadata at ${issuers[0]}`);\n };\n\n const authorizationServerMetadataRoute: RouteHandlers = {\n async GET(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n try {\n return new Response(await authorizationServerMetadata(), {\n headers: { \"content-type\": \"application/json\", \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] authorization server metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 502, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n const route = (handlers: RouteHandlers, request: Request): Promise<Response> => {\n if (request.method === \"GET\" || request.method === \"HEAD\") return handlers.GET(request);\n if (request.method === \"OPTIONS\") return handlers.OPTIONS(request);\n return Promise.resolve(new Response(null, { status: 405, headers: { allow: \"GET, OPTIONS\" } }));\n };\n\n const handleWellKnown = async (request: Request): Promise<Response | null> => {\n const path = trimSlash(new URL(request.url).pathname);\n if (location?.paths.includes(path)) return route(metadataRoute, request);\n if (config.authorizationServerMetadataProxy && path === AS_PATH) {\n return route(authorizationServerMetadataRoute, request);\n }\n return null;\n };\n\n return {\n resource,\n issuers,\n leewaySeconds: leeway,\n metadataUrl: location?.url,\n metadataPaths: location?.paths ?? [],\n verify,\n verifyToken,\n metadata,\n requireBearer,\n scopesForTool,\n authorizeTool,\n authorizeToolCalls,\n requireTool,\n metadataRoute,\n authorizationServerMetadataRoute,\n handleWellKnown,\n };\n}\n"],"names":["BearerError","status","code","wwwAuthenticate","description","PRM_PATH","AS_PATH","METADATA_TTL_MS","AS_METADATA_TTL_MS","OIDC_SCOPES","KINDS","INVALID_TOKEN_CODES","trimSlash","value","metadataLocation","resource","url","suffix","quote","stringArray","v","headerOf","request","name","headers","bearerToken","corsHeaders","cachedLoader","load","what","logger","fetched","fetching","err","createResourceServer","config","issuers","i","fetchImpl","args","leeway","location","configuredScopes","s","unlistedTools","keySets","keySet","issuer","pending","discover","disc","createRemoteJWKSet","customFetch","challenge","scopes","error","params","unauthorized","tokenSent","insufficientScope","localMetadata","credentialToken","managementTokenSource","fetchedMetadata","apiId","managementUrl","managementBase","res","doc","metadata","toolMapOf","map","scope","tool","keys","configuredToolMap","fetchToolMap","api","fetchedToolMap","scopesForTool","warnedTools","authorizeTool","principal","authorizeToolCalls","message","m","method","requireTool","options","verify","warned","warnUnknownScopes","known","verifyToken","token","required","unverified","decodeJwt","payload","jwtVerify","sub","kind","base","act","actorSub","requireBearer","metadataRoute","asMetadata","authorizationServerMetadata","path","authorizationServerMetadataRoute","route","handlers","handleWellKnown"],"mappings":";;;AAgPO,MAAMA,UAAoB,MAAM;AAAA,EACrC,YACWC,GAEAC,GAEAC,GACTC,GACA;AACA,UAAMA,CAAW,GAPR,KAAA,SAAAH,GAEA,KAAA,OAAAC,GAEA,KAAA,kBAAAC,GAIT,KAAK,OAAO;AAAA,EACd;AAAA,EATW;AAAA,EAEA;AAAA,EAEA;AAAA,EAOX,aAAuB;AACrB,WAAO,SAAS;AAAA,MACd,EAAE,OAAO,KAAK,QAAQ,gBAAgB,mBAAmB,KAAK,QAAA;AAAA,MAC9D,EAAE,QAAQ,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AA1B;AAAA,IACA,eAAAE;AAAA,IACA,oBAAAE;AAAA,IACA,aAAAI;AAAA,IACA,eAAAmB;AAAA,IACA,kCAAAI;AAAA,IACA,iBAAAG;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"resource-server.js","sources":["../src/resource-server.ts"],"sourcesContent":["import {\n createRemoteJWKSet,\n customFetch,\n decodeJwt,\n jwtVerify,\n type JWTPayload,\n type JWTVerifyGetKey,\n} from \"jose\";\n\nimport { managementBase, managementTokenSource, type ManagementCredential } from \"./management-credential\";\nimport { discover } from \"./oidc\";\n\n/**\n * Resource-server middleware: protect an API or an MCP server with tokens a\n * Pontive instance issued for it (pontive-spec 44 §11).\n *\n * `createResourceServer` verifies bearer tokens locally against each issuer's\n * keys, answers a missing or failing token with the `WWW-Authenticate`\n * challenge an MCP client follows, and serves the API's protected resource\n * metadata (RFC 9728). Per request it calls nothing but the cached JWKS.\n *\n * This entry speaks Web `Request`/`Response` (Next route handlers, Hono,\n * Workers, Bun, Deno). `@pontive/server/resource-server/express` and\n * `@pontive/server/resource-server/mcp` adapt it to Express and to the\n * MCP TypeScript SDK.\n */\n\n/** Who a verified token speaks for, told apart by the subject's id prefix. */\nexport type PrincipalKind = \"user\" | \"service_account\" | \"agent\";\n\n/** What every verified principal carries. */\ninterface PrincipalBase {\n /**\n * `usr_…`, `svc_…` or `agt_…`: whom the token speaks for.\n *\n * **For a delegated principal (`isDelegated`) this is the delegator, not the\n * caller.** The caller is the agent in `actor`, and its authority is the\n * intersection of the user's and the agent's, never the user's alone. Do not\n * read or write your own data by `principal.sub` alone for a delegated\n * principal: check by token with the authorization client\n * (`@pontive/server/authorization`), which evaluates the pair, or\n * branch on `principal.isDelegated`.\n */\n sub: string;\n /** From the sub's id prefix; no claim needed. A delegated token's subject is a user, so its kind is `\"user\"`. */\n kind: PrincipalKind;\n /** The client the token was issued to. */\n clientId: string;\n /** The organization the token is scoped to, when it is. */\n orgId?: string;\n /** The token's roles. For a delegated token, already intersected by Pontive (the delegator's roles the agent also holds). */\n roles: string[];\n /** The token's permissions. For a delegated token, already intersected by Pontive. */\n permissions: string[];\n /** The token's granted scopes. */\n scopes: string[];\n /** The agent instance, when the subject itself is an agent. */\n agentInstance?: string;\n /** The raw token, e.g. to check permissions by token. */\n token: string;\n /**\n * Every claim of the verified token: the claims template's (say\n * `legacy_user_id`) beside the standard ones the fields above are read\n * from. A claim is whatever the issuer wrote, so check its type before\n * using it.\n */\n claims: Record<string, unknown>;\n}\n\n/** Who acts for the subject, from the token's `act` claim (RFC 8693 §4.1). */\nexport interface PrincipalActor {\n /** `agt_…` for an agent acting for its delegator; `svc_…` for an API's backend calling downstream for the user. */\n sub: string;\n kind: \"agent\" | \"service_account\";\n /** The agent's running copy, when it named one. */\n agentInstance?: string;\n}\n\n/**\n * A token an agent holds for its delegator (profile (b), `act.sub` is\n * `agt_…`). `sub` is the user; `actor` is the agent. Its authority is the\n * intersection of both: answer it with a check by token, never by `sub`.\n */\nexport interface DelegatedPrincipal extends PrincipalBase {\n isDelegated: true;\n actor: PrincipalActor & { kind: \"agent\" };\n}\n\n/**\n * Any other token: the subject acts for itself. An `actor` here is a\n * registered API's backend service account calling downstream for the user\n * (profile (a)), a conduit: only the subject is evaluated.\n */\nexport interface UndelegatedPrincipal extends PrincipalBase {\n isDelegated: false;\n actor?: PrincipalActor & { kind: \"service_account\" };\n}\n\n/**\n * The verified caller, as the handler sees it. Narrow on `isDelegated`: a\n * delegated principal's `sub` is the user an agent acts for, and its authority\n * is narrower than that user's.\n */\nexport type Principal = DelegatedPrincipal | UndelegatedPrincipal;\n\n/** The protected resource metadata document (RFC 9728; pontive-spec 44 §9). */\nexport interface ProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n scopes_supported?: string[];\n bearer_methods_supported: string[];\n resource_name?: string;\n resource_documentation?: string;\n logo_uri?: string;\n}\n\n/**\n * How the resource server gets a management API token to read its own\n * metadata: a token, a function returning one, or the client credentials of\n * the API's backend service account (exchanged at the first issuer for a\n * management-audience token, and reused until it is about to expire).\n */\nexport type MetadataCredential = ManagementCredential;\nexport type { ManagementCredential };\n\n/** An MCP tool a scope covers (pontive-spec 44 §5, §12). Only `name` is read here. */\nexport interface ApiScopeTool {\n /** The MCP tool name, as `tools/call` sends it. */\n name: string;\n title?: string;\n read_only?: boolean;\n destructive?: boolean;\n}\n\n/**\n * An API scope as the management API returns it (`GET /v1/apis/{api_id}`,\n * pontive-spec 44 §5), so the dashboard's scopes can be pasted as they are.\n * Only `key` and `tools` are read here.\n */\nexport interface ApiScope {\n key: string;\n description?: string;\n display_name?: string;\n origin?: \"manual\" | \"tool_import\";\n /** The MCP tools the scope covers; a token holding the scope may call each of them (`requireTool`). */\n tools?: ApiScopeTool[];\n}\n\nexport interface ResourceServerConfig {\n /**\n * The instance's issuer: its auth domain, e.g.\n * `https://acme.auth.us.pontive.app`. A list when the instance has more than\n * one auth domain (a custom domain beside the default): a token from any of\n * them is accepted, and each is listed in `authorization_servers`.\n */\n issuer: string | string[];\n /**\n * The API's identifier, exactly as registered. Tokens must carry it in\n * `aud`, and it is the metadata's `resource`. When it is an http(s) URL the\n * metadata is served under its origin (RFC 9728 §3.1).\n */\n resource: string;\n /**\n * The API's scopes, for `scopes_supported`: keys, or the scopes as the\n * management API returns them (`ApiScope`). A scope's `tools` are the MCP\n * tools a token holding it may call (`requireTool`, pontive-spec 44 §12).\n */\n scopes?: (string | ApiScope)[];\n /**\n * What `requireTool` does with a tool no scope lists. `\"deny\"` (the\n * default) refuses it with a `403` that names no scope, since no scope\n * could allow it: a tool added to the server after the last tool import is\n * refused, and logged once, until the import lists it. `\"allow\"` lets any\n * valid token call it.\n */\n unlistedTools?: \"deny\" | \"allow\";\n /** The metadata's `resource_name`. */\n resourceName?: string;\n /** The metadata's `resource_documentation`. */\n resourceDocumentation?: string;\n /** The metadata's `logo_uri`. */\n logoUri?: string;\n /**\n * Read the metadata from Pontive instead of building it from this\n * configuration, for an API whose scopes and display fields are kept in the\n * dashboard. It is fetched on first use and cached for five minutes.\n *\n * When no configured scope lists tools, `requireTool` reads the scopes and\n * their tools from the same API (`GET /v1/apis/{api_id}`, with the\n * same credential and `sys:api:read`), cached the same way.\n */\n metadata?: {\n fetch: {\n /** The API's id (`api_…`). */\n apiId: string;\n /** A credential the management API accepts for `GET /v1/apis/{api_id}/resource-metadata`. */\n credential: MetadataCredential;\n /**\n * The management API's origin in the instance's region, e.g. `https://api.us.pontive.com`.\n * A `/v1`, `/mgmt` or `/mgmt/v1` suffix is dropped (`managementBase`).\n */\n managementUrl: string;\n };\n };\n /**\n * Also serve `/.well-known/oauth-authorization-server`, proxying the\n * issuer's own document, for older MCP clients that ask the resource server\n * for it. Default false.\n */\n authorizationServerMetadataProxy?: boolean;\n /** Clock skew allowed on `exp` and `nbf`. Default 60. */\n leewaySeconds?: number;\n /** Defaults to the global `fetch`. Used for discovery, JWKS and metadata. */\n fetch?: typeof fetch;\n /** Where configuration drift is reported. Defaults to `console`. */\n logger?: Pick<Console, \"warn\">;\n}\n\n/** What a route needs of the token beyond its being valid. */\nexport interface BearerOptions {\n /** Every one of these must be granted. */\n scopes?: string[];\n}\n\n/** Anything with request headers: a Web `Request`, `Headers`, or a Node/Express request. */\nexport type RequestLike =\n | Request\n | { headers: Headers | Record<string, string | string[] | undefined> };\n\n/** A route handler pair, e.g. to export from a Next `route.ts`. */\nexport interface RouteHandlers {\n GET(request: Request): Promise<Response>;\n OPTIONS(request: Request): Promise<Response>;\n}\n\n/**\n * Why a request was refused: a `401` (no token, or one that failed) or a\n * `403` (a valid token without a scope the route needs). `toResponse()` is the\n * answer to send.\n */\nexport class BearerError extends Error {\n constructor(\n readonly status: 401 | 403,\n /** Absent when no token was sent (RFC 6750 §3.1). */\n readonly code: \"invalid_token\" | \"insufficient_scope\" | undefined,\n /** The `WWW-Authenticate` header value. */\n readonly wwwAuthenticate: string,\n description: string,\n ) {\n super(description);\n this.name = \"BearerError\";\n }\n\n toResponse(): Response {\n return Response.json(\n { error: this.code ?? \"unauthorized\", error_description: this.message },\n { status: this.status, headers: { \"www-authenticate\": this.wwwAuthenticate, \"cache-control\": \"no-store\" } },\n );\n }\n}\n\nexport interface ResourceServer {\n /** The API identifier tokens must carry in `aud`. */\n readonly resource: string;\n /** The accepted issuers. */\n readonly issuers: readonly string[];\n /** The clock skew allowed on `exp` and `nbf`. */\n readonly leewaySeconds: number;\n /** The metadata's URL, named in every challenge; absent for an identifier that is not an http(s) URL. */\n readonly metadataUrl: string | undefined;\n /** The paths the metadata is served at: the RFC 9728 §3.1 path-suffixed one first. */\n readonly metadataPaths: readonly string[];\n\n /** Verifies the request's bearer token. Throws a `BearerError` when it is missing, fails, or lacks a scope. */\n verify(request: RequestLike, options?: BearerOptions): Promise<Principal>;\n /** Verifies a raw token, as `verify` does. */\n verifyToken(token: string, options?: BearerOptions): Promise<Principal>;\n /** The protected resource metadata document. */\n metadata(): Promise<ProtectedResourceMetadata>;\n /**\n * A guard for Web-standard handlers: the principal, or the `401`/`403`\n * response to return as it is.\n */\n requireBearer(options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /**\n * The scopes that list an MCP tool (pontive-spec 44 §12), from the\n * configured scopes, else from the API in Pontive when `metadata.fetch` is\n * set. Empty for a tool no scope lists.\n */\n scopesForTool(name: string): Promise<string[]>;\n /**\n * Refuses a principal that holds none of the scopes listing the tool: a\n * `BearerError` `403` with `error=\"insufficient_scope\"` and\n * `scope=\"<every scope listing the tool>\"`, any one of which would do. A\n * tool no scope lists follows `unlistedTools`.\n */\n authorizeTool(principal: Principal, name: string): Promise<void>;\n /**\n * `authorizeTool` for every `tools/call` in a JSON-RPC message or batch, as\n * an MCP client posts it; any other message passes. Throws the first refusal.\n * Run it on the parsed body before the MCP transport sees it, so the refusal\n * is an HTTP `403` the client can step up from.\n */\n authorizeToolCalls(principal: Principal, message: unknown): Promise<void>;\n /**\n * A guard for a Web-standard handler that serves one tool: the principal,\n * or the `401`/`403` response to return as it is.\n */\n requireTool(name: string, options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /** `GET` and `OPTIONS` for the protected resource metadata route. */\n readonly metadataRoute: RouteHandlers;\n /** `GET` and `OPTIONS` for the authorization server metadata proxy (404 unless the proxy is on). */\n readonly authorizationServerMetadataRoute: RouteHandlers;\n /**\n * Answers any of the well-known routes this server serves (both metadata\n * paths, and the AS-metadata proxy when on), or null for any other path. For\n * a catch-all: `return (await rs.handleWellKnown(req)) ?? next()`.\n */\n handleWellKnown(request: Request): Promise<Response | null>;\n}\n\nconst PRM_PATH = \"/.well-known/oauth-protected-resource\";\nconst AS_PATH = \"/.well-known/oauth-authorization-server\";\nconst METADATA_TTL_MS = 5 * 60 * 1000;\nconst AS_METADATA_TTL_MS = 10 * 60 * 1000;\n\n/** OIDC's own scopes, which a token may carry beside the API's. */\nconst OIDC_SCOPES = new Set([\"openid\", \"profile\", \"email\", \"address\", \"phone\", \"offline_access\"]);\n\nconst KINDS: Record<string, PrincipalKind> = { usr: \"user\", svc: \"service_account\", agt: \"agent\" };\n\n/** jose errors that mean the token is bad, rather than that the keys could not be fetched. */\nconst INVALID_TOKEN_CODES = new Set([\n \"ERR_JWT_EXPIRED\",\n \"ERR_JWT_CLAIM_VALIDATION_FAILED\",\n \"ERR_JWT_INVALID\",\n \"ERR_JWS_INVALID\",\n \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\",\n \"ERR_JWKS_NO_MATCHING_KEY\",\n \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\",\n \"ERR_JOSE_ALG_NOT_ALLOWED\",\n \"ERR_JOSE_NOT_SUPPORTED\",\n]);\n\nconst trimSlash = (value: string) => value.replace(/\\/+$/, \"\");\n\n/** Where the metadata lives for an http(s) identifier (RFC 9728 §3.1); undefined for any other. */\nfunction metadataLocation(resource: string): { url: string; paths: string[] } | undefined {\n let url: URL;\n try {\n url = new URL(resource);\n } catch {\n return undefined;\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return undefined;\n\n const suffix = url.pathname === \"/\" ? \"\" : trimSlash(url.pathname);\n return {\n url: `${url.origin}${PRM_PATH}${suffix}`,\n paths: suffix ? [`${PRM_PATH}${suffix}`, PRM_PATH] : [PRM_PATH],\n };\n}\n\nfunction quote(value: string): string {\n return `\"${value.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : [];\n}\n\nfunction headerOf(request: RequestLike, name: string): string | undefined {\n const headers = request.headers;\n if (headers instanceof Headers) return headers.get(name) ?? undefined;\n\n const value = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/** The token from `Authorization: Bearer …`, the only bearer method this server supports. */\nfunction bearerToken(request: RequestLike): string | undefined {\n const match = /^Bearer[ ]+([^ ]+)[ ]*$/i.exec(headerOf(request, \"authorization\") ?? \"\");\n return match?.[1];\n}\n\nconst corsHeaders = (request: Request): Record<string, string> => ({\n \"access-control-allow-origin\": \"*\",\n \"access-control-allow-methods\": \"GET, OPTIONS\",\n \"access-control-allow-headers\": request.headers.get(\"access-control-request-headers\") ?? \"*\",\n \"access-control-max-age\": \"86400\",\n});\n\n/**\n * A value fetched on first use and kept for five minutes. A failed refresh\n * keeps the last good value, logged; with none, the failure is thrown. One\n * fetch at a time.\n */\nfunction cachedLoader<T>(load: () => Promise<T>, what: string, logger: Pick<Console, \"warn\">) {\n let fetched: { at: number; value: T } | undefined;\n let fetching: Promise<T> | undefined;\n return {\n get last(): T | undefined {\n return fetched?.value;\n },\n get(): Promise<T> {\n if (fetched && Date.now() - fetched.at < METADATA_TTL_MS) return Promise.resolve(fetched.value);\n fetching ??= load()\n .then((value) => {\n fetched = { at: Date.now(), value };\n return value;\n })\n .catch((err: unknown) => {\n if (fetched) {\n logger.warn(`[pontive] ${what} refresh failed; serving the cached copy: ${String(err)}`);\n return fetched.value;\n }\n throw err;\n })\n .finally(() => {\n fetching = undefined;\n });\n return fetching;\n },\n };\n}\n\nexport function createResourceServer(config: ResourceServerConfig): ResourceServer {\n const issuers = (Array.isArray(config.issuer) ? config.issuer : [config.issuer]).map(trimSlash);\n if (issuers.length === 0 || issuers.some((i) => !i)) throw new Error(\"resource server: issuer is required\");\n if (!config.resource) throw new Error(\"resource server: resource is required\");\n\n const resource = config.resource;\n const fetchImpl = config.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const logger = config.logger ?? console;\n const leeway = config.leewaySeconds ?? 60;\n const location = metadataLocation(resource);\n const configuredScopes = (config.scopes ?? []).map((s) => (typeof s === \"string\" ? s : s.key));\n const unlistedTools = config.unlistedTools ?? \"deny\";\n\n if (config.metadata?.fetch && !location) {\n throw new Error(\"resource server: metadata is only served for an http(s) resource identifier\");\n }\n\n // One remote key set per issuer: jose caches the keys for ten minutes and\n // refetches on an unknown kid (at most every 30 s), which is how a key\n // rotation is picked up. A failed discovery is not cached.\n const keySets = new Map<string, Promise<JWTVerifyGetKey>>();\n const keySet = (issuer: string): Promise<JWTVerifyGetKey> => {\n let pending = keySets.get(issuer);\n if (!pending) {\n pending = discover(issuer, fetchImpl)\n .then((disc) => createRemoteJWKSet(new URL(disc.jwks_uri), { [customFetch]: fetchImpl }))\n .catch((err: unknown) => {\n keySets.delete(issuer);\n throw err;\n });\n keySets.set(issuer, pending);\n }\n return pending;\n };\n\n const challenge = (scopes: string[], error?: \"invalid_token\"): string => {\n const params: string[] = [];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n if (scopes.length) params.push(`scope=${quote(scopes.join(\" \"))}`);\n if (error) params.push(`error=${quote(error)}`);\n return params.length ? `Bearer ${params.join(\", \")}` : \"Bearer\";\n };\n\n const unauthorized = (scopes: string[], description: string, tokenSent: boolean) =>\n new BearerError(401, tokenSent ? \"invalid_token\" : undefined, challenge(scopes, tokenSent ? \"invalid_token\" : undefined), description);\n\n const insufficientScope = (scopes: string[], description = \"the token lacks a scope this route needs\") => {\n const params = [`error=\"insufficient_scope\"`, `scope=${quote(scopes.join(\" \"))}`];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n return new BearerError(403, \"insufficient_scope\", `Bearer ${params.join(\", \")}`, description);\n };\n\n // --- metadata -------------------------------------------------------------\n\n const localMetadata = (): ProtectedResourceMetadata => ({\n resource,\n authorization_servers: [...issuers],\n ...(configuredScopes.length ? { scopes_supported: [...configuredScopes] } : {}),\n bearer_methods_supported: [\"header\"],\n ...(config.resourceName ? { resource_name: config.resourceName } : {}),\n ...(config.resourceDocumentation ? { resource_documentation: config.resourceDocumentation } : {}),\n ...(config.logoUri ? { logo_uri: config.logoUri } : {}),\n });\n\n const credentialToken = config.metadata?.fetch\n ? managementTokenSource({ ...config.metadata.fetch, issuer: issuers[0]!, fetch: fetchImpl })\n : () => Promise.reject(new Error(\"resource server: no metadata credential\"));\n\n const fetchMetadata = async (): Promise<ProtectedResourceMetadata> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}/resource-metadata`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`resource metadata fetch failed: ${res.status}`);\n\n const doc = (await res.json()) as ProtectedResourceMetadata;\n // The metadata must describe the resource whose tokens this server accepts.\n if (doc.resource !== resource) {\n throw new Error(`resource metadata names ${doc.resource}, but this server accepts tokens for ${resource}`);\n }\n // Every issuer this server accepts is an authorization server for it.\n doc.authorization_servers = [...new Set([...(doc.authorization_servers ?? []), ...issuers])];\n doc.bearer_methods_supported = [\"header\"];\n return doc;\n };\n\n const fetchedMetadata = cachedLoader(fetchMetadata, \"resource metadata\", logger);\n\n const metadata = async (): Promise<ProtectedResourceMetadata> => {\n if (!location) throw new Error(`resource server: no metadata for ${resource}, which is not an http(s) URL`);\n if (!config.metadata?.fetch) return localMetadata();\n return fetchedMetadata.get();\n };\n\n // --- tool scopes (44 §12) -----------------------------------------------------\n\n // A tool's scopes: every scope whose `tools` lists it.\n const toolMapOf = (scopes: readonly (string | ApiScope)[]): Map<string, string[]> => {\n const map = new Map<string, string[]>();\n for (const scope of scopes) {\n if (typeof scope === \"string\" || !Array.isArray(scope.tools)) continue;\n for (const tool of scope.tools) {\n if (typeof tool?.name !== \"string\") continue;\n const keys = map.get(tool.name) ?? [];\n if (!keys.includes(scope.key)) keys.push(scope.key);\n map.set(tool.name, keys);\n }\n }\n return map;\n };\n\n const configuredToolMap = toolMapOf(config.scopes ?? []);\n\n const fetchToolMap = async (): Promise<Map<string, string[]>> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`api fetch failed: ${res.status}`);\n\n const api = (await res.json()) as { identifier?: string; scopes?: ApiScope[] };\n if (api.identifier !== resource) {\n throw new Error(`api ${apiId} is ${String(api.identifier)}, but this server accepts tokens for ${resource}`);\n }\n return toolMapOf(Array.isArray(api.scopes) ? api.scopes : []);\n };\n\n // Configured tools win; the API in Pontive is read only when none are configured.\n const fetchedToolMap =\n configuredToolMap.size === 0 && config.metadata?.fetch ? cachedLoader(fetchToolMap, \"api scopes\", logger) : undefined;\n\n const scopesForTool = async (name: string): Promise<string[]> => {\n const map = fetchedToolMap ? await fetchedToolMap.get() : configuredToolMap;\n return [...(map.get(name) ?? [])];\n };\n\n const warnedTools = new Set<string>();\n const authorizeTool = async (principal: Principal, name: string): Promise<void> => {\n const scopes = await scopesForTool(name);\n if (scopes.length === 0) {\n if (!warnedTools.has(name)) {\n warnedTools.add(name);\n logger.warn(\n `[pontive] the tool \"${name}\" is listed by no scope of ${resource}` +\n (unlistedTools === \"deny\" ? \"; calls to it are refused until a tool import lists it\" : \"\"),\n );\n }\n if (unlistedTools === \"allow\") return;\n // No scope could allow it, so the challenge names none and asks for no step-up.\n const params = location ? ` resource_metadata=${quote(location.url)}` : \"\";\n throw new BearerError(403, \"insufficient_scope\", `Bearer${params}`, `no scope of this API lists the tool \"${name}\"`);\n }\n if (scopes.some((scope) => principal.scopes.includes(scope))) return;\n throw insufficientScope(scopes, `the token holds none of the scopes that list the tool \"${name}\": ${scopes.join(\", \")}`);\n };\n\n const authorizeToolCalls = async (principal: Principal, message: unknown): Promise<void> => {\n for (const m of Array.isArray(message) ? message : [message]) {\n if (!m || typeof m !== \"object\") continue;\n const { method, params } = m as { method?: unknown; params?: { name?: unknown } };\n // A call without a name is the SDK's to refuse, as invalid params.\n if (method === \"tools/call\" && typeof params?.name === \"string\") await authorizeTool(principal, params.name);\n }\n };\n\n const requireTool = (name: string, options?: BearerOptions) => async (request: Request) => {\n try {\n const principal = await verify(request, options);\n await authorizeTool(principal, name);\n return principal;\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- scope drift ------------------------------------------------------------\n\n const warned = new Set<string>();\n const warnUnknownScopes = (scopes: string[]) => {\n const known = new Set([...configuredScopes, ...(fetchedMetadata.last?.scopes_supported ?? [])]);\n // Nothing declared, nothing to drift from.\n if (known.size === 0) return;\n\n for (const scope of scopes) {\n if (known.has(scope) || OIDC_SCOPES.has(scope) || warned.has(scope)) continue;\n warned.add(scope);\n logger.warn(\n `[pontive] a verified token for ${resource} carries the scope \"${scope}\", which this resource server's configuration does not list`,\n );\n }\n };\n\n // --- verification -----------------------------------------------------------\n\n const verifyToken = async (token: string, options?: BearerOptions): Promise<Principal> => {\n const required = options?.scopes ?? [];\n\n let unverified: JWTPayload;\n try {\n unverified = decodeJwt(token);\n } catch {\n throw unauthorized(required, \"the token is not a JWT\", true);\n }\n\n const issuer = typeof unverified.iss === \"string\" ? trimSlash(unverified.iss) : undefined;\n if (!issuer || !issuers.includes(issuer)) throw unauthorized(required, \"the token's issuer is not accepted\", true);\n\n let payload: JWTPayload;\n try {\n ({ payload } = await jwtVerify(token, await keySet(issuer), {\n issuer: unverified.iss as string,\n audience: resource,\n clockTolerance: leeway,\n // An access token (RFC 9068). An ID token is never one, and its\n // audience is the client besides.\n typ: \"at+jwt\",\n requiredClaims: [\"exp\", \"sub\"],\n }));\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code && INVALID_TOKEN_CODES.has(code)) throw unauthorized(required, (err as Error).message, true);\n throw err;\n }\n\n const sub = payload.sub!;\n const kind = KINDS[sub.slice(0, sub.indexOf(\"_\"))];\n if (!kind) throw unauthorized(required, \"the token's subject is not a user, service account or agent\", true);\n\n const base = {\n sub,\n kind,\n clientId: typeof payload.client_id === \"string\" ? payload.client_id : typeof payload.azp === \"string\" ? payload.azp : \"\",\n ...(typeof payload.org_id === \"string\" && payload.org_id ? { orgId: payload.org_id } : {}),\n roles: stringArray(payload.roles),\n permissions: stringArray(payload.permissions),\n scopes: typeof payload.scope === \"string\" ? payload.scope.split(\" \").filter(Boolean) : [],\n ...(kind === \"agent\" && typeof payload.agent_instance === \"string\"\n ? { agentInstance: payload.agent_instance }\n : {}),\n token,\n claims: payload,\n };\n\n const act = payload.act as { sub?: unknown; agent_instance?: unknown } | undefined;\n const actorSub = act && typeof act.sub === \"string\" ? act.sub : undefined;\n let principal: Principal;\n if (actorSub?.startsWith(\"agt_\")) {\n principal = {\n ...base,\n isDelegated: true,\n actor: {\n sub: actorSub,\n kind: \"agent\",\n ...(typeof act!.agent_instance === \"string\" ? { agentInstance: act!.agent_instance } : {}),\n },\n };\n } else if (actorSub?.startsWith(\"svc_\")) {\n principal = { ...base, isDelegated: false, actor: { sub: actorSub, kind: \"service_account\" } };\n } else if (actorSub) {\n // An act this server does not know how to evaluate: refuse it rather\n // than let the subject's authority stand for an unknown caller.\n throw unauthorized(required, \"the token's actor is not an agent or a service account\", true);\n } else {\n principal = { ...base, isDelegated: false };\n }\n\n warnUnknownScopes(principal.scopes);\n\n if (required.some((scope) => !principal.scopes.includes(scope))) throw insufficientScope(required);\n\n return principal;\n };\n\n const verify = async (request: RequestLike, options?: BearerOptions): Promise<Principal> => {\n const token = bearerToken(request);\n if (!token) throw unauthorized(options?.scopes ?? [], \"a bearer token is required\", false);\n return verifyToken(token, options);\n };\n\n const requireBearer = (options?: BearerOptions) => async (request: Request) => {\n try {\n return await verify(request, options);\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- well-known routes ------------------------------------------------------\n\n const metadataRoute: RouteHandlers = {\n async GET(request) {\n if (!location) return new Response(null, { status: 404 });\n try {\n return Response.json(await metadata(), {\n headers: { \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] resource metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 503, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n let asMetadata: { at: number; body: string } | undefined;\n const authorizationServerMetadata = async (): Promise<string> => {\n if (asMetadata && Date.now() - asMetadata.at < AS_METADATA_TTL_MS) return asMetadata.body;\n\n // RFC 8414's document, or the OIDC discovery document, which is a superset.\n for (const path of [AS_PATH, \"/.well-known/openid-configuration\"]) {\n const res = await fetchImpl(`${issuers[0]}${path}`);\n if (res.ok) {\n asMetadata = { at: Date.now(), body: await res.text() };\n return asMetadata.body;\n }\n }\n throw new Error(`no authorization server metadata at ${issuers[0]}`);\n };\n\n const authorizationServerMetadataRoute: RouteHandlers = {\n async GET(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n try {\n return new Response(await authorizationServerMetadata(), {\n headers: { \"content-type\": \"application/json\", \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] authorization server metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 502, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n const route = (handlers: RouteHandlers, request: Request): Promise<Response> => {\n if (request.method === \"GET\" || request.method === \"HEAD\") return handlers.GET(request);\n if (request.method === \"OPTIONS\") return handlers.OPTIONS(request);\n return Promise.resolve(new Response(null, { status: 405, headers: { allow: \"GET, OPTIONS\" } }));\n };\n\n const handleWellKnown = async (request: Request): Promise<Response | null> => {\n const path = trimSlash(new URL(request.url).pathname);\n if (location?.paths.includes(path)) return route(metadataRoute, request);\n if (config.authorizationServerMetadataProxy && path === AS_PATH) {\n return route(authorizationServerMetadataRoute, request);\n }\n return null;\n };\n\n return {\n resource,\n issuers,\n leewaySeconds: leeway,\n metadataUrl: location?.url,\n metadataPaths: location?.paths ?? [],\n verify,\n verifyToken,\n metadata,\n requireBearer,\n scopesForTool,\n authorizeTool,\n authorizeToolCalls,\n requireTool,\n metadataRoute,\n authorizationServerMetadataRoute,\n handleWellKnown,\n };\n}\n"],"names":["BearerError","status","code","wwwAuthenticate","description","PRM_PATH","AS_PATH","METADATA_TTL_MS","AS_METADATA_TTL_MS","OIDC_SCOPES","KINDS","INVALID_TOKEN_CODES","trimSlash","value","metadataLocation","resource","url","suffix","quote","stringArray","v","headerOf","request","name","headers","bearerToken","corsHeaders","cachedLoader","load","what","logger","fetched","fetching","err","createResourceServer","config","issuers","i","fetchImpl","args","leeway","location","configuredScopes","s","unlistedTools","keySets","keySet","issuer","pending","discover","disc","createRemoteJWKSet","customFetch","challenge","scopes","error","params","unauthorized","tokenSent","insufficientScope","localMetadata","credentialToken","managementTokenSource","fetchedMetadata","apiId","managementUrl","managementBase","res","doc","metadata","toolMapOf","map","scope","tool","keys","configuredToolMap","fetchToolMap","api","fetchedToolMap","scopesForTool","warnedTools","authorizeTool","principal","authorizeToolCalls","message","m","method","requireTool","options","verify","warned","warnUnknownScopes","known","verifyToken","token","required","unverified","decodeJwt","payload","jwtVerify","sub","kind","base","act","actorSub","requireBearer","metadataRoute","asMetadata","authorizationServerMetadata","path","authorizationServerMetadataRoute","route","hand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pD,WAAImB,GAAU,MAAM,SAASoE,CAAI,IAAUE,EAAML,GAAepF,CAAO,IACnEa,EAAO,oCAAoC0E,MAASvG,IAC/CyG,EAAMD,GAAkCxF,CAAO,IAEjD;AAAA,EACT;AAEA,SAAO;AAAA,IACL,UAAAP;AAAA,IACA,SAAAqB;AAAA,IACA,eAAeI;AAAA,IACf,aAAaC,GAAU;AAAA,IACvB,eAAeA,GAAU,SAAS,CAAA;AAAA,IAClC,QAAAgD;AAAA,IACA,aAAAI;AAAA,IACA,UAAAxB;AAAA,IACA,eAAAoC;AAAA,IACA,eAAA1B;AAAA,IACA,eAAAE;AAAA,IACA,oBAAAE;AAAA,IACA,aAAAI;AAAA,IACA,eAAAmB;AAAA,IACA,kCAAAI;AAAA,IACA,iBAAAG;AAAA,EAAA;AAEJ;"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pontive/server",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.25.0",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"description": "The Pontive SDK for TypeScript servers: sessions for apps (sign-in, a sealed session cookie, safe token refresh) and resource-server middleware for APIs and MCP servers, on Web Request/Response.",
|
|
5
|
+
"description": "The Pontive SDK for TypeScript servers: the management API client, sessions for apps (sign-in, a sealed session cookie, safe token refresh) and resource-server middleware for APIs and MCP servers, on Web Request/Response.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./dist/index.cjs",
|
|
8
8
|
"module": "./dist/index.js",
|
|
@@ -48,6 +48,16 @@
|
|
|
48
48
|
"default": "./dist/authorization.cjs"
|
|
49
49
|
}
|
|
50
50
|
},
|
|
51
|
+
"./management": {
|
|
52
|
+
"import": {
|
|
53
|
+
"types": "./dist/management/index.d.ts",
|
|
54
|
+
"default": "./dist/management.js"
|
|
55
|
+
},
|
|
56
|
+
"require": {
|
|
57
|
+
"types": "./dist/management/index.d.cts",
|
|
58
|
+
"default": "./dist/management.cjs"
|
|
59
|
+
}
|
|
60
|
+
},
|
|
51
61
|
"./resource-server/express": {
|
|
52
62
|
"import": {
|
|
53
63
|
"types": "./dist/resource-server-express.d.ts",
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const i=require("./oidc--We55Nrh.cjs");function s(n){const e=n.trim();let r=e;try{const t=new URL(e);r=`${t.origin}${t.pathname}`}catch{}return r.replace(/\/+$/,"").replace(/\/(mgmt(\/v1)?|v1)$/,"")}function c(n){const e=n.trim();try{return new URL(e).origin}catch{return e.replace(/\/+$/,"")}}function o(n){const{credential:e,managementUrl:r}=n;let t;return async()=>{if(typeof e=="string")return e;if(typeof e=="function")return e();if(t&&Date.now()<t.until)return t.value;if(!n.issuer)throw new Error("pontive: client credentials need the issuer to exchange them at");const a=await i.clientCredentialsToken({issuer:n.issuer,...e},n.fetch,{resource:c(r)});return t={value:a.access_token,until:Date.now()+((a.expires_in??300)-60)*1e3},a.access_token}}exports.managementAudience=c;exports.managementBase=s;exports.managementTokenSource=o;
|
|
2
|
-
//# sourceMappingURL=management-credential-BNyhHagG.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"management-credential-BNyhHagG.cjs","sources":["../src/management-credential.ts"],"sourcesContent":["import { clientCredentialsToken } from \"./oidc\";\n\n/**\n * How a server gets a management API token: a token, a function returning\n * one, or the client credentials of a service account (exchanged at the\n * issuer for a management-audience token, and reused until it is about to\n * expire).\n */\nexport type ManagementCredential =\n | string\n | (() => string | Promise<string>)\n | { clientId: string; clientSecret: string };\n\n/**\n * The management API's base for a configured `managementUrl`: its origin and\n * any gateway path, without a trailing slash and without a `/v1`, `/mgmt` or\n * `/mgmt/v1` suffix (as pontkit-core and oidc-client read `apiBaseUrl`). The\n * routes are built on it (`{base}/v1/…`, api-route-review D12), so\n * `https://api.us.pontive.com` and `…/v1` configure the same API. Query and\n * fragment are dropped.\n */\nexport function managementBase(managementUrl: string): string {\n const raw = managementUrl.trim();\n let base = raw;\n try {\n const url = new URL(raw);\n base = `${url.origin}${url.pathname}`;\n } catch {\n // Not an absolute URL: trimmed as given.\n }\n return base.replace(/\\/+$/, \"\").replace(/\\/(mgmt(\\/v1)?|v1)$/, \"\");\n}\n\n/**\n * The management API's audience for a configured `managementUrl`: its origin,\n * `https://api.us.pontive.com`, with no path and no trailing slash, whatever\n * path the URL carries (api-route-review D51; pontive-core's\n * `directory.ManagementAudience` and oidc-client's `managementAudience()`\n * derive it the same way). A value that is not an absolute URL is returned\n * trimmed, so the token request fails visibly.\n */\nexport function managementAudience(managementUrl: string): string {\n const raw = managementUrl.trim();\n try {\n return new URL(raw).origin;\n } catch {\n return raw.replace(/\\/+$/, \"\");\n }\n}\n\n/**\n * A function that returns a management API bearer token for `credential`.\n * Client credentials are exchanged at `issuer` for the management API's\n * audience (`managementAudience(managementUrl)`) and the token is reused until\n * a minute before it expires.\n */\nexport function managementTokenSource(input: {\n credential: ManagementCredential;\n managementUrl: string;\n issuer?: string;\n fetch: typeof fetch;\n}): () => Promise<string> {\n const { credential, managementUrl } = input;\n let cached: { value: string; until: number } | undefined;\n\n return async () => {\n if (typeof credential === \"string\") return credential;\n if (typeof credential === \"function\") return credential();\n if (cached && Date.now() < cached.until) return cached.value;\n if (!input.issuer) throw new Error(\"pontive: client credentials need the issuer to exchange them at\");\n\n const res = await clientCredentialsToken({ issuer: input.issuer, ...credential }, input.fetch, {\n resource: managementAudience(managementUrl),\n });\n cached = { value: res.access_token, until: Date.now() + ((res.expires_in ?? 300) - 60) * 1000 };\n return res.access_token;\n };\n}\n"],"names":["managementBase","managementUrl","raw","base","url","managementAudience","managementTokenSource","input","credential","cached","res","clientCredentialsToken"],"mappings":"oDAqBO,SAASA,EAAeC,EAA+B,CAC5D,MAAMC,EAAMD,EAAc,KAAA,EAC1B,IAAIE,EAAOD,EACX,GAAI,CACF,MAAME,EAAM,IAAI,IAAIF,CAAG,EACvBC,EAAO,GAAGC,EAAI,MAAM,GAAGA,EAAI,QAAQ,EACrC,MAAQ,CAER,CACA,OAAOD,EAAK,QAAQ,OAAQ,EAAE,EAAE,QAAQ,sBAAuB,EAAE,CACnE,CAUO,SAASE,EAAmBJ,EAA+B,CAChE,MAAMC,EAAMD,EAAc,KAAA,EAC1B,GAAI,CACF,OAAO,IAAI,IAAIC,CAAG,EAAE,MACtB,MAAQ,CACN,OAAOA,EAAI,QAAQ,OAAQ,EAAE,CAC/B,CACF,CAQO,SAASI,EAAsBC,EAKZ,CACxB,KAAM,CAAE,WAAAC,EAAY,cAAAP,CAAA,EAAkBM,EACtC,IAAIE,EAEJ,MAAO,UAAY,CACjB,GAAI,OAAOD,GAAe,SAAU,OAAOA,EAC3C,GAAI,OAAOA,GAAe,WAAY,OAAOA,EAAA,EAC7C,GAAIC,GAAU,KAAK,IAAA,EAAQA,EAAO,aAAcA,EAAO,MACvD,GAAI,CAACF,EAAM,OAAQ,MAAM,IAAI,MAAM,iEAAiE,EAEpG,MAAMG,EAAM,MAAMC,yBAAuB,CAAE,OAAQJ,EAAM,OAAQ,GAAGC,CAAA,EAAcD,EAAM,MAAO,CAC7F,SAAUF,EAAmBJ,CAAa,CAAA,CAC3C,EACD,OAAAQ,EAAS,CAAE,MAAOC,EAAI,aAAc,MAAO,KAAK,IAAA,IAAUA,EAAI,YAAc,KAAO,IAAM,GAAA,EAClFA,EAAI,YACb,CACF"}
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import { g as c } from "./oidc-CB0FqjFz.js";
|
|
2
|
-
function o(n) {
|
|
3
|
-
const e = n.trim();
|
|
4
|
-
let r = e;
|
|
5
|
-
try {
|
|
6
|
-
const t = new URL(e);
|
|
7
|
-
r = `${t.origin}${t.pathname}`;
|
|
8
|
-
} catch {
|
|
9
|
-
}
|
|
10
|
-
return r.replace(/\/+$/, "").replace(/\/(mgmt(\/v1)?|v1)$/, "");
|
|
11
|
-
}
|
|
12
|
-
function s(n) {
|
|
13
|
-
const e = n.trim();
|
|
14
|
-
try {
|
|
15
|
-
return new URL(e).origin;
|
|
16
|
-
} catch {
|
|
17
|
-
return e.replace(/\/+$/, "");
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
function u(n) {
|
|
21
|
-
const { credential: e, managementUrl: r } = n;
|
|
22
|
-
let t;
|
|
23
|
-
return async () => {
|
|
24
|
-
if (typeof e == "string") return e;
|
|
25
|
-
if (typeof e == "function") return e();
|
|
26
|
-
if (t && Date.now() < t.until) return t.value;
|
|
27
|
-
if (!n.issuer) throw new Error("pontive: client credentials need the issuer to exchange them at");
|
|
28
|
-
const a = await c({ issuer: n.issuer, ...e }, n.fetch, {
|
|
29
|
-
resource: s(r)
|
|
30
|
-
});
|
|
31
|
-
return t = { value: a.access_token, until: Date.now() + ((a.expires_in ?? 300) - 60) * 1e3 }, a.access_token;
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
export {
|
|
35
|
-
u as a,
|
|
36
|
-
s as b,
|
|
37
|
-
o as m
|
|
38
|
-
};
|
|
39
|
-
//# sourceMappingURL=management-credential-VhmMzGDl.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"management-credential-VhmMzGDl.js","sources":["../src/management-credential.ts"],"sourcesContent":["import { clientCredentialsToken } from \"./oidc\";\n\n/**\n * How a server gets a management API token: a token, a function returning\n * one, or the client credentials of a service account (exchanged at the\n * issuer for a management-audience token, and reused until it is about to\n * expire).\n */\nexport type ManagementCredential =\n | string\n | (() => string | Promise<string>)\n | { clientId: string; clientSecret: string };\n\n/**\n * The management API's base for a configured `managementUrl`: its origin and\n * any gateway path, without a trailing slash and without a `/v1`, `/mgmt` or\n * `/mgmt/v1` suffix (as pontkit-core and oidc-client read `apiBaseUrl`). The\n * routes are built on it (`{base}/v1/…`, api-route-review D12), so\n * `https://api.us.pontive.com` and `…/v1` configure the same API. Query and\n * fragment are dropped.\n */\nexport function managementBase(managementUrl: string): string {\n const raw = managementUrl.trim();\n let base = raw;\n try {\n const url = new URL(raw);\n base = `${url.origin}${url.pathname}`;\n } catch {\n // Not an absolute URL: trimmed as given.\n }\n return base.replace(/\\/+$/, \"\").replace(/\\/(mgmt(\\/v1)?|v1)$/, \"\");\n}\n\n/**\n * The management API's audience for a configured `managementUrl`: its origin,\n * `https://api.us.pontive.com`, with no path and no trailing slash, whatever\n * path the URL carries (api-route-review D51; pontive-core's\n * `directory.ManagementAudience` and oidc-client's `managementAudience()`\n * derive it the same way). A value that is not an absolute URL is returned\n * trimmed, so the token request fails visibly.\n */\nexport function managementAudience(managementUrl: string): string {\n const raw = managementUrl.trim();\n try {\n return new URL(raw).origin;\n } catch {\n return raw.replace(/\\/+$/, \"\");\n }\n}\n\n/**\n * A function that returns a management API bearer token for `credential`.\n * Client credentials are exchanged at `issuer` for the management API's\n * audience (`managementAudience(managementUrl)`) and the token is reused until\n * a minute before it expires.\n */\nexport function managementTokenSource(input: {\n credential: ManagementCredential;\n managementUrl: string;\n issuer?: string;\n fetch: typeof fetch;\n}): () => Promise<string> {\n const { credential, managementUrl } = input;\n let cached: { value: string; until: number } | undefined;\n\n return async () => {\n if (typeof credential === \"string\") return credential;\n if (typeof credential === \"function\") return credential();\n if (cached && Date.now() < cached.until) return cached.value;\n if (!input.issuer) throw new Error(\"pontive: client credentials need the issuer to exchange them at\");\n\n const res = await clientCredentialsToken({ issuer: input.issuer, ...credential }, input.fetch, {\n resource: managementAudience(managementUrl),\n });\n cached = { value: res.access_token, until: Date.now() + ((res.expires_in ?? 300) - 60) * 1000 };\n return res.access_token;\n };\n}\n"],"names":["managementBase","managementUrl","raw","base","url","managementAudience","managementTokenSource","input","credential","cached","res","clientCredentialsToken"],"mappings":";AAqBO,SAASA,EAAeC,GAA+B;AAC5D,QAAMC,IAAMD,EAAc,KAAA;AAC1B,MAAIE,IAAOD;AACX,MAAI;AACF,UAAME,IAAM,IAAI,IAAIF,CAAG;AACvB,IAAAC,IAAO,GAAGC,EAAI,MAAM,GAAGA,EAAI,QAAQ;AAAA,EACrC,QAAQ;AAAA,EAER;AACA,SAAOD,EAAK,QAAQ,QAAQ,EAAE,EAAE,QAAQ,uBAAuB,EAAE;AACnE;AAUO,SAASE,EAAmBJ,GAA+B;AAChE,QAAMC,IAAMD,EAAc,KAAA;AAC1B,MAAI;AACF,WAAO,IAAI,IAAIC,CAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAOA,EAAI,QAAQ,QAAQ,EAAE;AAAA,EAC/B;AACF;AAQO,SAASI,EAAsBC,GAKZ;AACxB,QAAM,EAAE,YAAAC,GAAY,eAAAP,EAAA,IAAkBM;AACtC,MAAIE;AAEJ,SAAO,YAAY;AACjB,QAAI,OAAOD,KAAe,SAAU,QAAOA;AAC3C,QAAI,OAAOA,KAAe,WAAY,QAAOA,EAAA;AAC7C,QAAIC,KAAU,KAAK,IAAA,IAAQA,EAAO,cAAcA,EAAO;AACvD,QAAI,CAACF,EAAM,OAAQ,OAAM,IAAI,MAAM,iEAAiE;AAEpG,UAAMG,IAAM,MAAMC,EAAuB,EAAE,QAAQJ,EAAM,QAAQ,GAAGC,EAAA,GAAcD,EAAM,OAAO;AAAA,MAC7F,UAAUF,EAAmBJ,CAAa;AAAA,IAAA,CAC3C;AACD,WAAAQ,IAAS,EAAE,OAAOC,EAAI,cAAc,OAAO,KAAK,IAAA,MAAUA,EAAI,cAAc,OAAO,MAAM,IAAA,GAClFA,EAAI;AAAA,EACb;AACF;"}
|