import { c as OAuthErrorResponse, d as OAuthTokenRevocationRequest, f as OAuthTokens, i as AuthInfo, l as OAuthMetadata, s as OAuthClientInformationFull, t as FetchLike, u as OAuthProtectedResourceMetadata } from "./index-Lq7iBORO.cjs"; import express, { RequestHandler, Response } from "express"; import { Options } from "express-rate-limit"; //#region src/auth/clients.d.ts /** * Stores information about registered OAuth clients for this server. */ interface OAuthRegisteredClientsStore { /** * Returns information about a registered client, based on its ID. */ getClient(clientId: string): OAuthClientInformationFull | undefined | Promise; /** * Registers a new client with the server. The client ID and secret will be automatically generated by the library. A modified version of the client information can be returned to reflect specific values enforced by the server. * * NOTE: Implementations should NOT delete expired client secrets in-place. Auth middleware provided by this library will automatically check the `client_secret_expires_at` field and reject requests with expired secrets. Any custom logic for authenticating clients should check the `client_secret_expires_at` field as well. * * If unimplemented, dynamic client registration is unsupported. */ registerClient?(client: Omit): OAuthClientInformationFull | Promise; } //#endregion //#region src/auth/provider.d.ts type AuthorizationParams = { state?: string; scopes?: string[]; codeChallenge: string; redirectUri: string; resource?: URL; /** * The authorization server's own issuer identifier (the `issuerUrl` configured on * `mcpAuthRouter`). Informational: the bundled `authorizationHandler` already appends * this as the `iss` query parameter (RFC 9207 §2) to any `res.redirect(...)` your * `authorize()` issues to {@linkcode AuthorizationParams.redirectUri | redirectUri}. You * only need to append it yourself when the final callback redirect is issued from a * different response (e.g. after a separate consent-page POST). */ issuer?: string; }; /** * Implements an end-to-end OAuth server. */ interface OAuthServerProvider { /** * A store used to read information about registered OAuth clients. */ get clientsStore(): OAuthRegisteredClientsStore; /** * Begins the authorization flow, which can either be implemented by this server itself or via redirection to a separate authorization server. * * This server must eventually issue a redirect with an authorization response or an error response to the given redirect URI. Per OAuth 2.1: * - In the successful case, the redirect MUST include the `code` and `state` (if present) query parameters. * - In the error case, the redirect MUST include the `error` query parameter, and MAY include an optional `error_description` query parameter. * * RFC 9207: the bundled `authorizationHandler` appends `iss` **only** to `res.redirect(...)` calls you issue * on the supplied `res` to `params.redirectUri`, so an implementation that redirects that way requires no * change. If you emit the `Location` header another way (e.g. `res.writeHead(302, { Location: ... })`), or * issue the final callback redirect from a different response (e.g. after a separate consent step), append * {@linkcode AuthorizationParams.issuer | params.issuer} as `iss` yourself, or set * {@linkcode OAuthServerProvider.authorizationResponseIssParameterSupported} to `false` so the metadata does * not over-claim. */ authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; /** * Returns the `codeChallenge` that was used when the indicated authorization began. */ challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; /** * Exchanges an authorization code for an access token. */ exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; /** * Exchanges a refresh token for an access token. */ exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; /** * Verifies an access token and returns information about it. */ verifyAccessToken(token: string): Promise; /** * Revokes an access or refresh token. If unimplemented, token revocation is not supported (not recommended). * * If the given token is invalid or already revoked, this method should do nothing. */ revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise; /** * Whether this provider's authorization responses carry the RFC 9207 `iss` parameter. * Drives the `authorization_response_iss_parameter_supported` metadata field. Defaults to * `true` — the bundled `authorizationHandler` appends `iss` to redirects it issues to the * client's `redirect_uri`. Set to `false` when the callback is issued by an upstream * authorization server this provider delegates to (e.g. `ProxyOAuthServerProvider`), so the * published metadata does not over-claim support. */ authorizationResponseIssParameterSupported?: boolean; /** * Whether to skip local PKCE validation. * * If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server. * * NOTE: This should only be true if the upstream server is performing the actual PKCE validation. */ skipLocalPkceValidation?: boolean; } /** * Slim implementation useful for token verification */ interface OAuthTokenVerifier { /** * Verifies an access token and returns information about it. */ verifyAccessToken(token: string): Promise; } //#endregion //#region src/auth/handlers/authorize.d.ts type AuthorizationHandlerOptions = { provider: OAuthServerProvider; /** * The authorization server's issuer identifier. When set, the handler appends it as the * `iss` query parameter (RFC 9207) to any redirect — success or error — that targets the * client's validated `redirect_uri`, and also supplies it to the provider as * {@linkcode AuthorizationParams.issuer}. `mcpAuthRouter` always sets this from its * `issuerUrl`. */ issuerUrl?: URL; /** * Rate limiting configuration for the authorization endpoint. * Set to false to disable rate limiting for this endpoint. */ rateLimit?: Partial | false; }; /** * Validates a requested redirect_uri against a registered one. * * Per RFC 8252 §7.3 (OAuth 2.0 for Native Apps), authorization servers MUST * allow any port for loopback redirect URIs (localhost, 127.0.0.1, [::1]) to * accommodate native clients that obtain an ephemeral port from the OS. For * non-loopback URIs, exact match is required. * * @see https://datatracker.ietf.org/doc/html/rfc8252#section-7.3 */ declare function redirectUriMatches(requested: string, registered: string): boolean; declare function authorizationHandler({ provider, issuerUrl, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler; //#endregion //#region src/auth/handlers/register.d.ts type ClientRegistrationHandlerOptions = { /** * A store used to save information about dynamically registered OAuth clients. */ clientsStore: OAuthRegisteredClientsStore; /** * The number of seconds after which to expire issued client secrets, or 0 to prevent expiration of client secrets (not recommended). * * If not set, defaults to 30 days. */ clientSecretExpirySeconds?: number; /** * Rate limiting configuration for the client registration endpoint. * Set to false to disable rate limiting for this endpoint. * Registration endpoints are particularly sensitive to abuse and should be rate limited. */ rateLimit?: Partial | false; /** * Whether to generate a client ID before calling the client registration endpoint. * * If not set, defaults to true. */ clientIdGeneration?: boolean; }; declare function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds, rateLimit: rateLimitConfig, clientIdGeneration }: ClientRegistrationHandlerOptions): RequestHandler; //#endregion //#region src/auth/handlers/revoke.d.ts type RevocationHandlerOptions = { provider: OAuthServerProvider; /** * Rate limiting configuration for the token revocation endpoint. * Set to false to disable rate limiting for this endpoint. */ rateLimit?: Partial | false; }; declare function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler; //#endregion //#region src/auth/handlers/token.d.ts type TokenHandlerOptions = { provider: OAuthServerProvider; /** * Rate limiting configuration for the token endpoint. * Set to false to disable rate limiting for this endpoint. */ rateLimit?: Partial | false; }; declare function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler; //#endregion //#region src/auth/router.d.ts type AuthRouterOptions = { /** * A provider implementing the actual authorization logic for this router. */ provider: OAuthServerProvider; /** * The authorization server's issuer identifier, which is a URL that uses the "https" scheme and has no query or fragment components. */ issuerUrl: URL; /** * The base URL of the authorization server to use for the metadata endpoints. * * If not provided, the issuer URL will be used as the base URL. */ baseUrl?: URL; /** * An optional URL of a page containing human-readable information that developers might want or need to know when using the authorization server. */ serviceDocumentationUrl?: URL; /** * An optional list of scopes supported by this authorization server */ scopesSupported?: string[]; /** * The resource name to be displayed in protected resource metadata */ resourceName?: string; /** * The URL of the protected resource (RS) whose metadata we advertise. * If not provided, falls back to `baseUrl` and then to `issuerUrl` (AS=RS). */ resourceServerUrl?: URL; authorizationOptions?: Omit; clientRegistrationOptions?: Omit; revocationOptions?: Omit; tokenOptions?: Omit; }; declare const createOAuthMetadata: (options: { provider: OAuthServerProvider; issuerUrl: URL; baseUrl?: URL; serviceDocumentationUrl?: URL; scopesSupported?: string[]; }) => OAuthMetadata; /** * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. * * By default, rate limiting is applied to all endpoints to prevent abuse. * * This router MUST be installed at the application root, like so: * * const app = express(); * app.use(mcpAuthRouter(...)); */ declare function mcpAuthRouter(options: AuthRouterOptions): RequestHandler; type AuthMetadataOptions = { /** * OAuth Metadata as would be returned from the authorization server * this MCP server relies on */ oauthMetadata: OAuthMetadata; /** * The url of the MCP server, for use in protected resource metadata */ resourceServerUrl: URL; /** * The url for documentation for the MCP server */ serviceDocumentationUrl?: URL; /** * An optional list of scopes supported by this MCP server */ scopesSupported?: string[]; /** * An optional resource name to display in resource metadata */ resourceName?: string; }; declare function mcpAuthMetadataRouter(options: AuthMetadataOptions): express.Router; /** * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL * from a given server URL. This replaces the path with the standard metadata endpoint. * * @param serverUrl - The base URL of the protected resource server * @returns The URL for the OAuth protected resource metadata endpoint * * @example * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' */ declare function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string; //#endregion //#region src/auth/providers/proxyProvider.d.ts type ProxyEndpoints = { authorizationUrl: string; tokenUrl: string; revocationUrl?: string; registrationUrl?: string; }; type ProxyOptions = { /** * Individual endpoint URLs for proxying specific OAuth operations */ endpoints: ProxyEndpoints; /** * Function to verify access tokens and return auth info */ verifyAccessToken: (token: string) => Promise; /** * Function to fetch client information from the upstream server */ getClient: (clientId: string) => Promise; /** * Custom fetch implementation used for all network requests. */ fetch?: FetchLike; }; /** * Implements an OAuth server that proxies requests to another OAuth server. */ declare class ProxyOAuthServerProvider implements OAuthServerProvider { protected readonly _endpoints: ProxyEndpoints; protected readonly _verifyAccessToken: (token: string) => Promise; protected readonly _getClient: (clientId: string) => Promise; protected readonly _fetch?: FetchLike; skipLocalPkceValidation: boolean; /** * The proxy redirects the browser to the upstream AS's authorize endpoint with * `redirect_uri = params.redirectUri`, so the upstream — not this proxy — issues the * callback. The proxy cannot append its own `iss`, and any `iss` the upstream emits is the * upstream's issuer, not `issuerUrl`. Advertise `false` so the metadata does not over-claim — * a callback *without* `iss` then passes validation. Note: an upstream that *does* emit its * own `iss` will still mismatch this proxy's issuer and be rejected by RFC 9207 clients * regardless of this flag. */ authorizationResponseIssParameterSupported: boolean; revokeToken?: (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => Promise; constructor(options: ProxyOptions); get clientsStore(): OAuthRegisteredClientsStore; authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; challengeForAuthorizationCode(_client: OAuthClientInformationFull, _authorizationCode: string): Promise; exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; verifyAccessToken(token: string): Promise; } //#endregion //#region src/auth/handlers/metadata.d.ts declare function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler; //#endregion //#region src/auth/middleware/allowedMethods.d.ts /** * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. * * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) * @returns Express middleware that returns a 405 error if method not in allowed list */ declare function allowedMethods(allowedMethods: string[]): RequestHandler; //#endregion //#region src/auth/middleware/bearerAuth.d.ts type BearerAuthMiddlewareOptions = { /** * A provider used to verify tokens. */ verifier: OAuthTokenVerifier; /** * Optional scopes that the token must have. */ requiredScopes?: string[]; /** * Optional resource metadata URL to include in WWW-Authenticate header. */ resourceMetadataUrl?: string; }; declare module 'express-serve-static-core' { interface Request { /** * Information about the validated access token, if the `requireBearerAuth` middleware was used. */ auth?: AuthInfo; } } /** * Middleware that requires a valid Bearer token in the Authorization header. * * This will validate the token with the auth provider and add the resulting auth info to the request object. * * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. */ declare function requireBearerAuth({ verifier, requiredScopes, resourceMetadataUrl }: BearerAuthMiddlewareOptions): RequestHandler; //#endregion //#region src/auth/middleware/clientAuth.d.ts type ClientAuthenticationMiddlewareOptions = { /** * A store used to read information about registered OAuth clients. */ clientsStore: OAuthRegisteredClientsStore; }; declare module 'express-serve-static-core' { interface Request { /** * The authenticated client for this request, if the `authenticateClient` middleware was used. */ client?: OAuthClientInformationFull; } } declare function authenticateClient({ clientsStore }: ClientAuthenticationMiddlewareOptions): RequestHandler; //#endregion //#region src/auth/errors.d.ts /** * Base class for all OAuth errors */ declare class OAuthError extends Error { readonly errorUri?: string | undefined; static errorCode: string; constructor(message: string, errorUri?: string | undefined); /** * Converts the error to a standard OAuth error response object */ toResponseObject(): OAuthErrorResponse; get errorCode(): string; } /** * Invalid request error - The request is missing a required parameter, * includes an invalid parameter value, includes a parameter more than once, * or is otherwise malformed. */ declare class InvalidRequestError extends OAuthError { static errorCode: string; } /** * Invalid client error - Client authentication failed (e.g., unknown client, no client * authentication included, or unsupported authentication method). */ declare class InvalidClientError extends OAuthError { static errorCode: string; } /** * Invalid grant error - The provided authorization grant or refresh token is * invalid, expired, revoked, does not match the redirection URI used in the * authorization request, or was issued to another client. */ declare class InvalidGrantError extends OAuthError { static errorCode: string; } /** * Unauthorized client error - The authenticated client is not authorized to use * this authorization grant type. */ declare class UnauthorizedClientError extends OAuthError { static errorCode: string; } /** * Unsupported grant type error - The authorization grant type is not supported * by the authorization server. */ declare class UnsupportedGrantTypeError extends OAuthError { static errorCode: string; } /** * Invalid scope error - The requested scope is invalid, unknown, malformed, or * exceeds the scope granted by the resource owner. */ declare class InvalidScopeError extends OAuthError { static errorCode: string; } /** * Access denied error - The resource owner or authorization server denied the request. */ declare class AccessDeniedError extends OAuthError { static errorCode: string; } /** * Server error - The authorization server encountered an unexpected condition * that prevented it from fulfilling the request. */ declare class ServerError extends OAuthError { static errorCode: string; } /** * Temporarily unavailable error - The authorization server is currently unable to * handle the request due to a temporary overloading or maintenance of the server. */ declare class TemporarilyUnavailableError extends OAuthError { static errorCode: string; } /** * Unsupported response type error - The authorization server does not support * obtaining an authorization code using this method. */ declare class UnsupportedResponseTypeError extends OAuthError { static errorCode: string; } /** * Unsupported token type error - The authorization server does not support * the requested token type. */ declare class UnsupportedTokenTypeError extends OAuthError { static errorCode: string; } /** * Invalid token error - The access token provided is expired, revoked, malformed, * or invalid for other reasons. */ declare class InvalidTokenError extends OAuthError { static errorCode: string; } /** * Method not allowed error - The HTTP method used is not allowed for this endpoint. * (Custom, non-standard error) */ declare class MethodNotAllowedError extends OAuthError { static errorCode: string; } /** * Too many requests error - Rate limit exceeded. * (Custom, non-standard error based on RFC 6585) */ declare class TooManyRequestsError extends OAuthError { static errorCode: string; } /** * Invalid client metadata error - The client metadata is invalid. * (Custom error for dynamic client registration - RFC 7591) */ declare class InvalidClientMetadataError extends OAuthError { static errorCode: string; } /** * Insufficient scope error - The request requires higher privileges than provided by the access token. */ declare class InsufficientScopeError extends OAuthError { static errorCode: string; } /** * Invalid target error - The requested resource is invalid, missing, unknown, or malformed. * (Custom error for resource indicators - RFC 8707) */ declare class InvalidTargetError extends OAuthError { static errorCode: string; } /** * A utility class for defining one-off error codes */ declare class CustomOAuthError extends OAuthError { private readonly customErrorCode; constructor(customErrorCode: string, message: string, errorUri?: string); get errorCode(): string; } /** * A full list of all OAuthErrors, enabling parsing from error responses */ declare const OAUTH_ERRORS: { readonly [InvalidRequestError.errorCode]: typeof InvalidRequestError; readonly [InvalidClientError.errorCode]: typeof InvalidClientError; readonly [InvalidGrantError.errorCode]: typeof InvalidGrantError; readonly [UnauthorizedClientError.errorCode]: typeof UnauthorizedClientError; readonly [UnsupportedGrantTypeError.errorCode]: typeof UnsupportedGrantTypeError; readonly [InvalidScopeError.errorCode]: typeof InvalidScopeError; readonly [AccessDeniedError.errorCode]: typeof AccessDeniedError; readonly [ServerError.errorCode]: typeof ServerError; readonly [TemporarilyUnavailableError.errorCode]: typeof TemporarilyUnavailableError; readonly [UnsupportedResponseTypeError.errorCode]: typeof UnsupportedResponseTypeError; readonly [UnsupportedTokenTypeError.errorCode]: typeof UnsupportedTokenTypeError; readonly [InvalidTokenError.errorCode]: typeof InvalidTokenError; readonly [MethodNotAllowedError.errorCode]: typeof MethodNotAllowedError; readonly [TooManyRequestsError.errorCode]: typeof TooManyRequestsError; readonly [InvalidClientMetadataError.errorCode]: typeof InvalidClientMetadataError; readonly [InsufficientScopeError.errorCode]: typeof InsufficientScopeError; readonly [InvalidTargetError.errorCode]: typeof InvalidTargetError; }; //#endregion export { AuthMetadataOptions as A, ClientRegistrationHandlerOptions as B, BearerAuthMiddlewareOptions as C, ProxyEndpoints as D, metadataHandler as E, mcpAuthRouter as F, AuthorizationParams as G, AuthorizationHandlerOptions as H, TokenHandlerOptions as I, OAuthRegisteredClientsStore as J, OAuthServerProvider as K, tokenHandler as L, createOAuthMetadata as M, getOAuthProtectedResourceMetadataUrl as N, ProxyOAuthServerProvider as O, mcpAuthMetadataRouter as P, RevocationHandlerOptions as R, authenticateClient as S, allowedMethods as T, authorizationHandler as U, clientRegistrationHandler as V, redirectUriMatches as W, UnauthorizedClientError as _, InvalidClientMetadataError as a, UnsupportedTokenTypeError as b, InvalidScopeError as c, MethodNotAllowedError as d, OAUTH_ERRORS as f, TooManyRequestsError as g, TemporarilyUnavailableError as h, InvalidClientError as i, AuthRouterOptions as j, ProxyOptions as k, InvalidTargetError as l, ServerError as m, CustomOAuthError as n, InvalidGrantError as o, OAuthError as p, OAuthTokenVerifier as q, InsufficientScopeError as r, InvalidRequestError as s, AccessDeniedError as t, InvalidTokenError as u, UnsupportedGrantTypeError as v, requireBearerAuth as w, ClientAuthenticationMiddlewareOptions as x, UnsupportedResponseTypeError as y, revocationHandler as z }; //# sourceMappingURL=index-PX3-fmlH.d.cts.map