diff --git a/README.md b/README.md index 959b1c6..fae37ce 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ MCP Auth gives you everything you need to add production-ready auth to your MCP ### 1. Skip the specs. Skip the boilerplate. Just auth. -The MCP spec [requires OAuth 2.1 and other RFCs](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) for auth. Instead of spending weeks on them, use MCP Auth to connect to an trusted provider with a few lines of code. +The MCP spec [requires OAuth 2.1 and other RFCs](https://modelcontextprotocol.io/specification/latest/basic/authorization) for auth. Instead of spending weeks on them, use MCP Auth to connect to a trusted provider with a few lines of code. ### 2. Connect to any provider. It's provider-agnostic. diff --git a/docs/README.mdx b/docs/README.mdx index 96c013c..0838a53 100644 --- a/docs/README.mdx +++ b/docs/README.mdx @@ -4,174 +4,191 @@ sidebar_label: Get started --- import { NpmLikeInstallation } from '@site/src/components/NpmLikeInstallation'; +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; import ScopeValidationWarning from './snippets/_scope-validation-warning.mdx'; # Get started :::info MCP authorization specification support -This version supports the [MCP authorization specification (version 2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization). +MCP Auth implements the authorization requirements of the [latest MCP specification](https://modelcontextprotocol.io/specification/latest/basic/authorization) and works with any OAuth 2.0 / OpenID Connect provider that meets them. ::: -:::tip Python SDK available -MCP Auth is also available for Python! Check out the [Python SDK repository](https://github.com/mcp-auth/python) for installation and usage. -::: +## How it works \{#how-it-works} -## Choose a compatible OAuth 2.1 or OpenID Connect provider \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} +The MCP TypeScript SDK v2 (`@modelcontextprotocol/server`) ships the entire HTTP layer of MCP authorization itself: `requireBearerAuth`, `oauthMetadataResponse`, and official framework adapters like `@modelcontextprotocol/express`. What it asks you to bring is provider integration: verifying the access tokens your OAuth 2.0 / OpenID Connect provider issues, and describing that provider in your server's metadata. -MCP specification has [specific requirements](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#standards-compliance) for authorization. The authorization mechanism is based on established specifications, implementing a selected subset of their features to ensure security and interoperability while maintaining simplicity: +That is exactly what MCP Auth provides: -- OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13)) -- OAuth 2.0 Authorization Server Metadata ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) -- OAuth 2.0 Dynamic Client Registration Protocol ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) -- OAuth 2.0 Protected Resource Metadata ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) +1. **A token verifier**: the `MCPAuth` instance implements the SDK's `OAuthTokenVerifier` interface. It discovers your provider's metadata, fetches its JWKS, and verifies JWT access tokens (signature, issuer, audience, expiration, and the claims MCP servers need), with sensible caching throughout. +2. **Your auth metadata**: `mcpAuth.getAuthMetadataOptions()` returns the SDK's `AuthMetadataOptions`, ready to serve the OAuth discovery documents ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) Protected Resource Metadata and [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) Authorization Server Metadata). -These specifications work together to provide a secure and standardized authorization framework for MCP implementations. +## Choose a compatible OAuth 2.1 or OpenID Connect provider \{#choose-a-compatible-oauth-2-1-or-openid-connect-provider} -You can check the [MCP-compatible provider list](/provider-list) to see if your provider is supported. +MCP Auth works with any provider that meets the MCP specification's [authorization requirements](https://modelcontextprotocol.io/specification/latest/basic/authorization#standards-compliance). In practice, two things matter: -## Install MCP Auth SDK \{#install-mcp-auth-sdk} +- The provider supports standard metadata discovery ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) or [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html)), including a JWKS endpoint for token verification. +- The provider can issue JWT access tokens bound to your MCP server ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)); this is usually a matter of registering your server's identifier as a resource or audience. - +Check the [MCP-compatible provider list](/provider-list) to see how popular providers score, and the [Provider Guides](/docs/provider-guides) for concrete configuration steps. -## Init MCP Auth \{#init-mcp-auth} +## Install MCP Auth SDK \{#install-mcp-auth-sdk} -The first step is to define your resource identifier and configure the authorization server that will be trusted for authentication. MCP Auth now operates in resource server mode, conforming to the updated MCP specification that requires OAuth 2.0 Protected Resource Metadata (RFC 9728). + -If your provider conforms to: +`@modelcontextprotocol/server` v2 is a peer dependency of `mcp-auth`. The SDK is ESM only and requires Node.js >= 20, or any fetch-native runtime such as Cloudflare Workers, Deno, or Bun. -- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) -- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) +:::note Still on MCP SDK v1? +If your MCP server is built on the MCP TypeScript SDK v1 (`@modelcontextprotocol/sdk`), stay on the 0.2 line with `npm install mcp-auth@0.2` and check out the [v0.2 documentation](https://github.com/mcp-auth/js/tree/v0.2.0). When you move to the v2 SDK, follow the [migration guide](/docs/migrate-to-v1). +::: -You can use the built-in function to fetch the metadata and initialize the MCP Auth instance: +## Init MCP Auth \{#init-mcp-auth} -```ts -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +Declare your MCP server as a protected resource: give it a resource identifier ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)) and tell it which authorization server to trust: -// 1. Define your resource identifier and fetch the config for its trusted authorization server. -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); +```ts +import { MCPAuth } from 'mcp-auth'; -// 2. Initialize MCPAuth in resource server mode. -// `protectedResources` can be a single object or an array for multiple resources. const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, + protectedResourceMetadata: { + // The resource identifier of this MCP server; also the expected `aud` claim of access tokens + resource: 'https://api.example.com/mcp', + // The authorization server trusted by this MCP server + authorizationServer: { issuer: 'https://auth.example.com/oidc', type: 'oidc' }, // or 'oauth' + // The scopes this MCP server understands + scopesSupported: ['read:notes'], }, }); ``` -If you're using edge runtimes like Cloudflare Workers where top-level async fetch is not allowed, use on demand discovery instead: +With this discovery config, the authorization server metadata is fetched lazily when first needed and cached afterwards, which is safe for edge runtimes where network calls are not allowed during module initialization. If you prefer to fetch and validate the metadata at startup so misconfigurations fail fast, use `fetchServerConfig`: ```ts -const authServerConfig = { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }; -``` - -For other ways to configure authorization server metadata including custom metadata URLs, data transpilation, or manual metadata specification, check [Other ways to configure MCP Auth](./configure-server/mcp-auth.mdx#other-ways). +import { MCPAuth, fetchServerConfig } from 'mcp-auth'; -## Mount the protected resource metadata endpoint \{#mount-the-protected-resource-metadata-endpoint} +const mcpAuth = new MCPAuth({ + protectedResourceMetadata: { + resource: 'https://api.example.com/mcp', + authorizationServer: await fetchServerConfig('https://auth.example.com/oidc', { type: 'oidc' }), + scopesSupported: ['read:notes'], + }, +}); +``` -To conform to the updated MCP specification, MCP Auth mounts the OAuth 2.0 Protected Resource Metadata endpoint (RFC 9728) to your MCP server. This endpoint allows clients to discover: +One `MCPAuth` instance represents one protected resource trusting one authorization server. Everything in the declaration is published through the metadata endpoints, and the token verifier enforces what it declares: the `aud` claim of access tokens must match `resource`, and the `iss` claim must match the configured authorization server. -- Which authorization servers can issue valid tokens for your protected resources -- What scopes are supported for each resource -- Other metadata required for proper token validation +For other ways to provide the authorization server metadata (custom well-known URLs, data transpilation, or manual metadata), check [Configure MCP Auth](./configure-server/mcp-auth.mdx#other-ways). -The endpoint path is automatically determined by the path component of your resource identifier: +## Serve the metadata and protect your MCP endpoint \{#serve-the-metadata-and-protect-your-mcp-endpoint} -- **No path**: `https://api.example.com` → `/.well-known/oauth-protected-resource` -- **With path**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` +Two steps remain, and each is one call into the MCP SDK: -The MCP server now **serves as a resource server** that validates tokens and provides metadata about its protected resources, while relying entirely on external authorization servers for authentication and authorization. +1. **Serve the OAuth discovery documents** so MCP clients can find your authorization server: feed `mcpAuth.getAuthMetadataOptions()` to the SDK's metadata helpers. +2. **Gate your MCP endpoint** with the SDK's `requireBearerAuth`: `mcpAuth.getBearerAuthOptions()` bundles the token verifier with the resource metadata URL (and your required scopes) into the SDK's `BearerAuthOptions`. -You can use the SDK provided method to mount this endpoint: + + ```ts -import express from 'express'; - -const app = express(); - -// Mount the router to serve the Protected Resource Metadata. -// For resource "https://api.example.com" → endpoint: /.well-known/oauth-protected-resource -// For resource "https://api.example.com/notes" → endpoint: /.well-known/oauth-protected-resource/notes -app.use(mcpAuth.protectedResourceMetadataRouter()); +import { + createMcpHandler, + oauthMetadataResponse, + requireBearerAuth, +} from '@modelcontextprotocol/server'; + +// `createMcpServer` builds your `McpServer` instance with tools (see the next section) +const handler = createMcpHandler(createMcpServer); + +// Signature, issuer, audience, expiration, and scopes are all enforced by the gate +const gate = requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read:notes'] })); + +export default { + async fetch(request: Request): Promise { + // Serve the OAuth discovery documents + if (new URL(request.url).pathname.startsWith('/.well-known/')) { + const metadata = oauthMetadataResponse(request, await mcpAuth.getAuthMetadataOptions()); + if (metadata) return metadata; + } + + // Require a valid Bearer token for everything else + const auth = await gate(request); + if (auth instanceof Response) return auth; + return handler.fetch(request, { authInfo: auth }); + }, +}; ``` -## Use the Bearer auth middleware \{#use-the-bearer-auth-middleware} - -Once the MCP Auth instance is initialized, you can apply the Bearer auth middleware to protect your MCP routes. The middleware now requires specifying which resource the endpoint belongs to, enabling proper token validation: - -:::note Audience Validation -The `audience` parameter is **required** by the OAuth 2.0 specification for secure token validation. However, it is currently **optional** to maintain compatibility with authorization servers that do not yet support resource identifiers. For security reasons, **please always include the audience parameter** when possible. Future versions will enforce audience validation as mandatory to fully comply with the specification. -::: - - + + ```ts -import express from 'express'; - -const app = express(); - -// Mount the router to serve the Protected Resource Metadata. -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// Protect an API endpoint using the resource-specific policy. -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, - audience: resourceIdentifier, // Enable audience validation for security - requiredScopes: ['read:notes'], - }), - (req, res) => { - // If the token is valid, `req.auth` is populated with its claims. - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - } +import { + createMcpExpressApp, + mcpAuthMetadataRouter, + requireBearerAuth, +} from '@modelcontextprotocol/express'; +import { toNodeHandler } from '@modelcontextprotocol/node'; +import { createMcpHandler } from '@modelcontextprotocol/server'; + +// `createMcpServer` builds your `McpServer` instance with tools (see the next section) +const mcpNodeHandler = toNodeHandler(createMcpHandler(createMcpServer)); + +const app = createMcpExpressApp(); + +// Serve the OAuth discovery documents +app.use(mcpAuthMetadataRouter(await mcpAuth.getAuthMetadataOptions())); + +app.all( + '/mcp', + // Require a valid Bearer token; the verified auth info flows to the handler via `req.auth` + requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read:notes'] })), + // `createMcpExpressApp` applies `express.json()`, which drains the request stream, so the + // parsed body is passed along explicitly + async (request, response) => mcpNodeHandler(request, response, request.body) ); app.listen(3000); ``` -In the examples above, we specify the `jwt` token type and the resource identifier. The middleware will automatically validate the JWT token against the trusted authorization servers configured for that specific resource and populate the authenticated user's information. + + -:::info -Didn't hear about JWT (JSON Web Token) before? Don't worry, you can keep reading the documentation and we'll explain it when needed. You can also check [Auth Wiki](https://auth.wiki/jwt) for a quick introduction. -::: +The metadata helpers serve the Protected Resource Metadata document at the path derived from your resource identifier (for example, `https://api.example.com/mcp` → `/.well-known/oauth-protected-resource/mcp`), and also mirror the authorization server metadata for clients that look it up on your MCP server. Requests without a valid token receive a `401` response with a `WWW-Authenticate` challenge pointing at the resource metadata, which is how MCP clients discover where to sign in. -For more information on the Bearer auth configuration, check the [Configure Bearer auth](./configure-server/bearer-auth.mdx). +Using Hono or another framework on a fetch-native runtime? The [sample servers](https://github.com/mcp-auth/js/tree/master/packages/sample-servers) wrap the same two calls in Hono middlewares; the wiring is identical. -## Retrieve the auth info in your MCP implementation \{#retrieve-the-auth-info-in-your-mcp-implementation} + + +For more details on Bearer auth, including per-tool scope enforcement and opaque token verification, check [Configure Bearer auth](./configure-server/bearer-auth.mdx). -Once the Bearer auth middleware is applied, you can access the authenticated user's (or identity's) information in your MCP implementation: +## Retrieve the auth info in your MCP implementation \{#retrieve-the-auth-info-in-your-mcp-implementation} -The second argument of the tool handler will contain the `authInfo` object, which includes the authenticated user's information: +Inside tool callbacks (and other MCP request handlers), use `getAuthInfo` to read the verified identity: ```ts -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/server'; +import { getAuthInfo } from 'mcp-auth'; -const server = new McpServer(/* ... */); +const createMcpServer = () => { + const server = new McpServer({ name: 'Notes', version: '1.0.0' }); -// Initialize with MCP Auth as shown in previous examples -// ... + server.registerTool('whoami', { description: 'Get the current user' }, (context) => { + // Pass `{ requiredScopes: [...] }` as the second argument for per-tool authorization + const { subject, claims } = getAuthInfo(context); + return { content: [{ type: 'text', text: JSON.stringify({ subject, claims }) }] }; + }); -server.registerTool( - 'add', - { - description: 'Add two numbers', - inputSchema: { a: z.number(), b: z.number() }, - }, - async ({ a, b }, { authInfo }) => { - // Now you can use the `authInfo` object to access the authenticated information - } -); + return server; +}; ``` +`getAuthInfo` returns a `McpAuthInfo` object: the SDK's `AuthInfo` with guaranteed `issuer`, `subject` (the `sub` claim, typically the user ID), and the full verified JWT payload as `claims`. + +:::info +Didn't hear about JWT (JSON Web Token) before? Don't worry, you can keep reading the documentation and we'll explain it when needed. You can also check [Auth Wiki](https://auth.wiki/jwt) for a quick introduction. +::: + ## Next steps \{#next-steps} -Continue reading to learn an end-to-end example of how to integrate MCP Auth with your MCP server, and how to handle the auth flow in MCP clients. +Continue reading to learn an end-to-end example of how to integrate MCP Auth with your MCP server, and how to handle the auth flow in MCP clients. Upgrading an existing server from mcp-auth 0.2? Start with the [migration guide](/docs/migrate-to-v1). diff --git a/docs/configure-server/bearer-auth.mdx b/docs/configure-server/bearer-auth.mdx index 090d7fa..d14e170 100644 --- a/docs/configure-server/bearer-auth.mdx +++ b/docs/configure-server/bearer-auth.mdx @@ -3,133 +3,239 @@ sidebar_position: 2 sidebar_label: Bearer auth --- +import TabItem from '@theme/TabItem'; +import Tabs from '@theme/Tabs'; + +import ScopeValidationWarning from '../snippets/_scope-validation-warning.mdx'; + # Configure Bearer auth in MCP server -With the latest MCP specification, your MCP server acts as a **Resource Server** that validates access tokens for protected resources. MCP Auth provides various ways to configure Bearer authorization: +With the [latest MCP specification](https://modelcontextprotocol.io/specification/latest/basic/authorization), your MCP server acts as a **Resource Server** that validates access tokens for protected resources. This page covers the token verifier half of MCP Auth; [Configure MCP Auth](./mcp-auth.mdx) covers the configuration and metadata half. -- [JWT (JSON Web Token)](https://auth.wiki/jwt) mode: A built-in authorization method that verifies JWTs with claim assertions. -- Custom mode: Allows you to implement your own authorization logic. +The Bearer auth middleware itself comes from the MCP SDK: `requireBearerAuth`, available both fetch-native (from `@modelcontextprotocol/server`) and as framework adapters (e.g. from `@modelcontextprotocol/express`). What MCP Auth brings is the token verifier: the `MCPAuth` instance implements the SDK's `OAuthTokenVerifier` interface, and `mcpAuth.getBearerAuthOptions()` bundles everything into the SDK's `BearerAuthOptions`: -The Bearer auth middleware now requires specifying which resource the endpoint belongs to, enabling proper token validation against the configured authorization servers. +- `verifier`: the `MCPAuth` instance itself, verifying JWT access tokens against the trusted authorization server's JWKS +- `resourceMetadataUrl`: the RFC 9728 metadata URL, so the `WWW-Authenticate` challenge on `401` responses points clients at your resource metadata +- `requiredScopes`: the scopes you require for the endpoint, passed through -## Configure Bearer auth with JWT mode \{#configure-bearer-auth-with-jwt-mode} +## Protect your MCP endpoint \{#protect-your-mcp-endpoint} -If your OAuth / OIDC provider issues JWTs for authorization, you can use the built-in JWT mode in MCP Auth. It verifies the JWT signature, expiration, and other claims you specify; then it populates the authentication information in the request context for further processing in your MCP implementation. + + -### Scope and audience validation \{#scope-and-audience-validation} +```ts +import { requireBearerAuth } from '@modelcontextprotocol/server'; +import { MCPAuth } from 'mcp-auth'; -:::note Audience Validation -The `audience` parameter is **required** by the OAuth 2.0 specification for secure token validation. However, it is currently **optional** to maintain compatibility with authorization servers that do not yet support resource identifiers. For security reasons, **please always include the audience parameter** when possible. Future versions will enforce audience validation as mandatory to fully comply with the specification. -::: +const mcpAuth = new MCPAuth({ + /* ... */ +}); -import ScopeValidationWarning from '../snippets/_scope-validation-warning.mdx'; +const gate = requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read', 'write'] })); - +export default { + async fetch(request: Request): Promise { + // ... serve the OAuth discovery documents for `/.well-known/` paths -Here's an example of the basic scope and audience validation: + const auth = await gate(request); + if (auth instanceof Response) { + // The token is missing or invalid: a `401` response with a `WWW-Authenticate` challenge + return auth; + } + + // The token is valid: `auth` carries the verified auth info + return handler.fetch(request, { authInfo: auth }); + }, +}; +``` + + + ```ts -import express from 'express'; +import { requireBearerAuth } from '@modelcontextprotocol/express'; import { MCPAuth } from 'mcp-auth'; -const app = express(); const mcpAuth = new MCPAuth({ /* ... */ }); -const bearerAuth = mcpAuth.bearerAuth('jwt', { - resource: 'https://api.example.com', // Specify which resource this endpoint belongs to - audience: 'https://api.example.com', // Enable audience validation for security - requiredScopes: ['read', 'write'], -}); -app.use('/mcp', bearerAuth, (req, res) => { - // Now `req.auth` contains the auth info - console.log(req.auth); -}); +app.all( + '/mcp', + requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read', 'write'] })), + (request, response) => { + // The token is valid: `request.auth` carries the verified auth info + } +); ``` -In the example above: - -- The `audience` parameter validates the `aud` claim in the JWT to ensure the token was specifically issued for your MCP server resource. The audience value should typically match your resource identifier. -- The `requiredScopes` parameter specifies that the JWT requires the `read` and `write` scopes. If the token does not contain all of these scopes, an error will be thrown. + + -### Provide custom options to the JWT verification \{#provide-custom-options-to-the-jwt-verification} +Both `requireBearerAuth` variants accept the same options type, so `getBearerAuthOptions` works with either. Endpoints with different scope requirements call `getBearerAuthOptions` once each. -You can also provide custom options to the underlying JWT verification library. In Node.js SDK, we use [jose](https://github.com/panva/jose) library for JWT verification. You can provide the following options: +For every request, the middleware verifies: -- `jwtVerify`: Options for the JWT verification process (`jwtVerify` function from `jose`). -- `remoteJwtSet`: Options for fetching the remote JWT set (`createRemoteJWKSet` function from `jose`). +- **Signature**: the JWT is verified against the JWKS of the trusted authorization server +- **Issuer** (`iss`): must match the configured authorization server +- **Audience** (`aud`): must match the configured `resource` identifier +- **Expiration** (`exp`) and other standard time claims +- **Scopes**: the token must include all `requiredScopes` (if provided) -```ts {5-10} -const bearerAuth = mcpAuth.bearerAuth('jwt', { - resource: 'https://api.example.com', - audience: 'https://api.example.com', - requiredScopes: ['read', 'write'], - jwtVerify: { - clockTolerance: 60, // Allow a 60 seconds clock skew - }, - remoteJwtSet: { - timeoutDuration: 10 * 1000, // 10 seconds timeout for remote JWT set fetching - }, -}); -``` +:::info Audience validation is always on +The MCP specification requires access tokens to be bound to the resource they are issued for ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)). MCP Auth always validates the `aud` claim against your `resource` identifier. There is no opt-out and no override, so your provider must issue audience-bound access tokens. Tokens are also required to carry a `sub` claim (per [RFC 9068](https://datatracker.ietf.org/doc/html/rfc9068)), so the verified auth info always has a `subject`. +::: -## Configure Bearer auth with custom verification \{#configure-bearer-auth-with-custom-verification} + -If your OAuth / OIDC provider does not issue JWTs, or you want to implement your own authorization logic, MCP Auth allows you to create a custom verification function: +## Enforce scopes per tool \{#enforce-scopes-per-tool} -:::info -Since the Bearer auth middleware will check against issuer (`iss`), audience (`aud`), and required scopes (`scope`) with the given verification result, there's no need to implement these checks in your custom verification function. You can focus on verifying the token validity (e.g., signature, expiration, etc.) and returning the auth info object. -::: +On top of the endpoint-level `requiredScopes`, you can enforce scopes for individual tools with `getAuthInfo`: ```ts -const bearerAuth = mcpAuth.bearerAuth( - async (token) => { - // Implement your custom verification logic here - const info = await verifyToken(token); - if (!info) { - throw new MCPAuthJwtVerificationError('jwt_verification_failed'); - } - return info; // Return the auth info object - }, +import { getAuthInfo } from 'mcp-auth'; + +server.registerTool( + 'delete-note', { - resource: 'https://api.example.com', - audience: 'https://api.example.com', // Enable audience validation for security - requiredScopes: ['read', 'write'], + description: 'Delete a note by ID', + inputSchema: z.object({ id: z.string() }), + }, + ({ id }, context) => { + // Throws unless the token has the `write` scope; the MCP SDK surfaces the error to the + // model as a tool error result (`isError: true`) with an `insufficient_scope: ...` message + const { subject } = getAuthInfo(context, { requiredScopes: ['write'] }); + + // ... delete the note owned by `subject` } ); ``` -## Apply Bearer auth in your MCP server \{#apply-bearer-auth-in-your-mcp-server} +The returned `McpAuthInfo` object is the SDK's `AuthInfo` extended with the guarantees MCP Auth provides after verification: -To protect your MCP server with Bearer auth, you need to apply the Bearer auth middleware to your MCP server instance. +- `issuer`: the verified `iss` claim, always the configured trusted authorization server +- `subject`: the verified `sub` claim, typically the user ID +- `claims`: the full verified JWT payload, for access to any custom claims +- `scopes`: parsed from the `scope` claim (space-separated string) or the `scopes` claim (array) +- `clientId`: from the `client_id` claim, falling back to `azp` +- `token`: the raw access token, handy for calling downstream APIs on the user's behalf + +## Customize JWT verification \{#customize-jwt-verification} + +MCP Auth uses the [jose](https://github.com/panva/jose) library to verify JWTs. Use `jwtVerifyOptions` to pass options through to jose's `jwtVerify` function for advanced tuning: ```ts -const app = express(); -app.use( - mcpAuth.bearerAuth('jwt', { - resource: 'https://api.example.com', - audience: 'https://api.example.com', // Enable audience validation for security - requiredScopes: ['read', 'write'], - }) -); +const mcpAuth = new MCPAuth({ + protectedResourceMetadata: { + /* ... */ + }, + jwtVerifyOptions: { + clockTolerance: 60, // Allow a 60 seconds clock skew + requiredClaims: ['email'], // Reject tokens without these claims + }, +}); ``` -This will ensure that all incoming requests are authenticated and authorized according to the configured Bearer auth settings, and the auth information will be available in the request context. +The `issuer` and `audience` options are excluded: they always derive from the protected resource metadata declaration and cannot be overridden. + +## Verify opaque tokens (custom verification) \{#verify-opaque-tokens} -You can then access the information in your MCP server implementation: +`MCPAuth` verifies JWT access tokens against your provider's JWKS. Some authorization servers issue **opaque access tokens** instead: random strings with nothing to verify locally. The two halves of MCP Auth are decoupled, so this case is covered by bringing your own verifier: implement the SDK's `OAuthTokenVerifier` against your server's token introspection endpoint ([RFC 7662](https://datatracker.ietf.org/doc/html/rfc7662)), and keep using the metadata half. The discovery documents, the challenge URL, and `getAuthInfo()` all work unchanged. ```ts -// `authInfo` will be carried from the `req.auth` object -server.registerTool( - 'whoami', - { - description: 'Returns the current user info', - inputSchema: {}, +import { + OAuthError, + OAuthErrorCode, + requireBearerAuth, + type OAuthTokenVerifier, +} from '@modelcontextprotocol/server'; +import { MCPAuth, type McpAuthInfo } from 'mcp-auth'; + +const issuer = 'https://auth.example.com/oidc'; +const resource = 'https://api.example.com/mcp'; + +// The metadata half works exactly as before +const mcpAuth = new MCPAuth({ + protectedResourceMetadata: { + resource, + authorizationServer: { issuer, type: 'oidc' }, + scopesSupported: ['read:notes'], }, - ({ authInfo }) => { - console.log(`Authenticated user: ${authInfo.subject}`); - return { subject: authInfo.subject }; - } -); +}); + +const introspectionEndpoint = 'https://auth.example.com/oidc/token/introspection'; +// Most servers require a confidential client (e.g. a machine-to-machine app) to +// introspect tokens issued to other clients +const clientId = 'your-m2m-client-id'; +const clientSecret = 'your-m2m-client-secret'; + +const introspectionVerifier: OAuthTokenVerifier = { + async verifyAccessToken(token): Promise { + const response = await fetch(introspectionEndpoint, { + method: 'POST', + headers: { + 'content-type': 'application/x-www-form-urlencoded', + authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`, + }, + body: new URLSearchParams({ token, token_type_hint: 'access_token' }), + signal: AbortSignal.timeout(5000), + }); + + if (!response.ok) { + /* + * A plain `Error`, not an `OAuthError`: the SDK answers 500. The token could not be + * verified, which is different from being invalid; a 401 would send a client with a + * perfectly fine token into a pointless re-authorization. + */ + throw new Error(`Introspection request failed with status ${response.status}.`); + } + + const data = (await response.json()) as McpAuthInfo['claims']; + + // The MCP spec still requires these checks; introspection does not exempt them + if (data.active !== true) { + throw new OAuthError(OAuthErrorCode.InvalidToken, 'The token is not active.'); + } + + if (!(Array.isArray(data.aud) ? data.aud : [data.aud]).includes(resource)) { + throw new OAuthError(OAuthErrorCode.InvalidToken, 'The token audience does not match.'); + } + + if (typeof data.iss === 'string' && data.iss !== issuer) { + throw new OAuthError(OAuthErrorCode.InvalidToken, 'The token issuer is not trusted.'); + } + + if (typeof data.sub !== 'string' || typeof data.exp !== 'number') { + throw new OAuthError(OAuthErrorCode.InvalidToken, 'The token has no `sub` or `exp`.'); + } + + // The `McpAuthInfo` shape, so `getAuthInfo()` in tool callbacks works unchanged + return { + token, + issuer, + subject: data.sub, + clientId: typeof data.client_id === 'string' ? data.client_id : '', + scopes: typeof data.scope === 'string' ? data.scope.split(' ').filter(Boolean) : [], + expiresAt: data.exp, + claims: data, + }; + }, +}; + +// Only the gate changes; the discovery documents still come from `mcpAuth` +const gate = requireBearerAuth({ + verifier: introspectionVerifier, + resourceMetadataUrl: mcpAuth.resourceMetadataUrl, + requiredScopes: ['read:notes'], +}); ``` + +A few things to know: + +- **The endpoint**: some servers advertise it as `introspection_endpoint` in their metadata, others keep it off the public discovery document entirely (e.g. an internal admin API). Configure whatever yours is. +- **The credentials**: most servers only let authenticated confidential clients introspect tokens issued to other clients; some deployments protect the endpoint at the network level instead. Check your server's policy. +- **The cost**: every request is an introspection round-trip. That is also the point: revoked tokens are rejected immediately. Add caching only if you accept the revocation delay. + +## Error handling \{#error-handling} + +Token verification failures are thrown as the SDK's `OAuthError` (with code `invalid_token`), which the SDK bearer auth helpers map to a `401` response with a `WWW-Authenticate` challenge. Configuration and metadata discovery failures are thrown as `MCPAuthConfigError` / `MCPAuthAuthServerError`, which the SDK maps to a `500` response: the token could not be verified, which is different from being invalid. diff --git a/docs/configure-server/mcp-auth.mdx b/docs/configure-server/mcp-auth.mdx index 9d81cd5..c326c9a 100644 --- a/docs/configure-server/mcp-auth.mdx +++ b/docs/configure-server/mcp-auth.mdx @@ -5,64 +5,55 @@ sidebar_label: MCP Auth # Configure MCP Auth in MCP server -With the latest [MCP Specification (2025-06-18)](https://modelcontextprotocol.io/specification/2025-06-18), your MCP server acts as a **Resource Server** that validates access tokens issued by external authorization servers. +With the [latest MCP specification](https://modelcontextprotocol.io/specification/latest/basic/authorization), your MCP server acts as a **Resource Server** that validates access tokens issued by external authorization servers. -To configure MCP Auth, you need two main steps: +The MCP SDK asks you to bring two things: a token verifier and your auth metadata. Both come from one `MCPAuth` instance. This page covers its configuration and the metadata half; [Configure Bearer auth](./bearer-auth.mdx) covers the verifier half. -1. **Configure Authorization Server Metadata** - Define which authorization servers can issue valid tokens for your MCP server and guide MCP clients on where to obtain access tokens -2. **Configure Protected Resource Metadata** - Define your MCP server as a protected resource with supported scopes +Each `MCPAuth` instance represents **one protected resource trusting one authorization server**. Its configuration is the Protected Resource Metadata declaration of your MCP server ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)): everything you declare is published through the metadata endpoints, and the token verifier enforces what is declared. -## Step 1: Configure Authorization Server Metadata \{#configure-authorization-server-metadata} +Configuring MCP Auth takes three steps: -### Automatic metadata fetching \{#automatic-metadata-fetching} +1. **Provide the authorization server config**: tell MCP Auth which authorization server to trust and how to obtain its metadata +2. **Declare the protected resource metadata**: define your MCP server's resource identifier and supported scopes +3. **Serve the OAuth discovery documents**: feed the metadata to the MCP SDK's helpers so clients can discover it -The easiest way to configure authorization server metadata is by using the built-in functions that fetch the metadata from well-known URLs. If your provider conforms to one of the following standards: +## Step 1: Provide the authorization server config \{#provide-the-authorization-server-config} -- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) -- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) +### On-demand discovery \{#on-demand-discovery} -You can use the `fetchServerConfig` to automatically retrieve the metadata by providing the `issuer` URL: +The simplest way is to provide just the `issuer` and `type`. The metadata is fetched from the server's well-known endpoint when first needed and cached afterwards: ```ts -import { fetchServerConfig } from 'mcp-auth'; - -// Fetch authorization server metadata -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // or 'oauth' +const authServerConfig = { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }; // or 'oauth' ``` -If your issuer includes a path, the behavior differs slightly between OAuth 2.0 and OpenID Connect: - -- **OAuth 2.0**: The well-known URL is appended to the **domain** of the issuer. For example, if your issuer is `https://my-project.logto.app/oauth`, the well-known URL will be `https://auth.logto.io/.well-known/oauth-authorization-server/oauth`. -- **OpenID Connect**: The well-known URL is appended directly to the **issuer**. For example, if your issuer is `https://my-project.logto.app/oidc`, the well-known URL will be `https://auth.logto.io/oidc/.well-known/openid-configuration`. +This performs no I/O at startup, which makes it required for edge runtimes like Cloudflare Workers where network calls are not allowed during module initialization, and a fast default everywhere else. -#### On demand discovery \{#on-demand-discovery} +The well-known URL is derived from the issuer according to the server type: -If you're using edge runtimes like Cloudflare Workers where top-level async fetch is not allowed, you can use on demand discovery instead. Just provide the `issuer` and `type`, and the metadata will be fetched automatically when first needed: +- **OpenID Connect Discovery** (`type: 'oidc'`): the path is appended to the issuer. For example, issuer `https://my-project.logto.app/oidc` → `https://my-project.logto.app/oidc/.well-known/openid-configuration`. +- **OAuth 2.0 Authorization Server Metadata** (`type: 'oauth'`, [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)): the path is inserted between the origin and the issuer path. For example, issuer `https://my-project.logto.app/oauth` → `https://my-project.logto.app/.well-known/oauth-authorization-server/oauth`. -```ts -const authServerConfig = { issuer: '', type: 'oidc' }; // or 'oauth' -``` +### Pre-fetch the metadata at startup \{#pre-fetch-the-metadata-at-startup} -### Other ways to configure authorization server metadata \{#other-ways} +If your provider conforms to one of the following standards: -#### Custom data transpilation \{#custom-data-transpilation} +- [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) +- [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) -In some cases, the metadata returned by the provider may not conform to the expected format. If you are confident that the provider is compliant, you can use the `transpileData` option to modify the metadata before it is used: +You can use `fetchServerConfig` to retrieve and validate the metadata before initializing `MCPAuth`, so misconfigurations fail fast at startup. It also validates that the `issuer` field in the fetched metadata matches the issuer you provided: ```ts import { fetchServerConfig } from 'mcp-auth'; -const authServerConfig = await fetchServerConfig('', { - type: 'oidc', - transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] -}); +const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); // or 'oauth' ``` -This allows you to modify the metadata object before it is used by MCP Auth. For example, you can add or remove fields, change their values, or convert them to a different format. +### Other ways to configure authorization server metadata \{#other-ways} #### Fetch metadata from a specific URL \{#fetch-metadata-from-a-specific-url} -If your provider has a specific metadata URL rather than the standard ones, you can use it similarly: +If your provider serves its metadata from a non-standard URL, you can fetch it directly (no issuer match validation is performed in this case): ```ts import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; @@ -70,17 +61,21 @@ import { fetchServerConfigByWellKnownUrl } from 'mcp-auth'; const authServerConfig = await fetchServerConfigByWellKnownUrl('', { type: 'oidc' }); // or 'oauth' ``` -#### Fetch metadata from a specific URL with custom data transpilation \{#fetch-metadata-from-a-specific-url-with-custom-data-transpilation} +#### Custom data transpilation \{#custom-data-transpilation} -In some cases, the provider response may be malformed or not conforming to the expected metadata format. If you are confident that the provider is compliant, you can transpile the metadata via the config option: +In some cases, the metadata returned by the provider may not conform to the expected format. If you are confident that the provider is compliant, you can use the `transpileData` option to modify the metadata before it is used: ```ts -const authServerConfig = await fetchServerConfigByWellKnownUrl('', { +import { fetchServerConfig } from 'mcp-auth'; + +const authServerConfig = await fetchServerConfig('', { type: 'oidc', transpileData: (data) => ({ ...data, response_types_supported: ['code'] }), // [!code highlight] }); ``` +The `transpileData` option is available for both `fetchServerConfig` and `fetchServerConfigByWellKnownUrl`. + #### Manually provide metadata \{#manually-provide-metadata} If your provider does not support metadata fetching, you can manually provide the metadata object: @@ -89,57 +84,69 @@ If your provider does not support metadata fetching, you can manually provide th const authServerConfig = { metadata: { issuer: '', - // Metadata fields should be camelCase - authorizationEndpoint: '', + // Metadata fields use the wire format (snake_case), as defined by RFC 8414 + authorization_endpoint: '', + token_endpoint: '', + jwks_uri: '', + response_types_supported: ['code'], // ... other metadata fields }, type: 'oidc', // or 'oauth' }; ``` -## Step 2: Configure Protected Resource Metadata \{#configure-protected-resource-metadata} +:::note +The metadata stays in wire format (snake_case) end-to-end: it is validated as-is and passed verbatim to the MCP SDK's metadata helpers. The `jwks_uri` field is required by MCP Auth for JWT access token verification. +::: -After configuring the authorization server metadata, you need to initialize MCPAuth as a Resource Server by defining your protected resources metadata. +## Step 2: Declare the protected resource metadata \{#declare-the-protected-resource-metadata} -This step follows the [RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728) specification to describe your MCP server as a protected resource: +Initialize `MCPAuth` with your resource identifier and the authorization server config from Step 1: ```ts import { MCPAuth } from 'mcp-auth'; -// Define your resource identifier -const resourceIdentifier = 'https://api.example.com/notes'; - -// Initialize MCPAuth in resource server mode const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], // Using the config from Step 1 - scopesSupported: ['read:notes', 'write:notes'], - }, + protectedResourceMetadata: { + // The resource identifier of this MCP server (RFC 8707) + resource: 'https://api.example.com/notes', + // The authorization server config from Step 1 + authorizationServer: authServerConfig, + // The scopes this MCP server understands, advertised as `scopes_supported` + scopesSupported: ['read:notes', 'write:notes'], + // Optional: a human-readable name, advertised as `resource_name` + resourceName: 'Notes API', + // Optional: a documentation URL, advertised as `resource_documentation` + serviceDocumentationUrl: 'https://docs.example.com', }, }); ``` -For multiple resources, you can provide an array of protected resource configs, each with their own metadata configuration. +A few things to know: -The configuration shown above covers the basic setup. For more advanced metadata parameters, see [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata). +- The `resource` identifier must be an HTTP(S) URL without a fragment component. It is published as the `resource` value of the Protected Resource Metadata document and used as the expected `aud` (audience) claim of access tokens. The MCP specification requires access tokens to be bound to the resource they are issued for ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)), so audience validation is always on and cannot be disabled. +- The configuration is validated in the constructor so misconfigurations fail fast. For a resolved authorization server config, the metadata is validated immediately; for a discovery config, it is validated when first fetched. +- If your deployment serves **multiple resources**, create one `MCPAuth` instance per resource. -## Step 3: Mount the protected resource metadata endpoint \{#mount-the-protected-resource-metadata-endpoint} +For more advanced metadata parameters, see [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata). -Mount the router to serve the protected resource metadata endpoint. The endpoint path is automatically determined by the path component of your resource identifier: +## Step 3: Serve the OAuth discovery documents \{#serve-the-oauth-discovery-documents} -- **No path**: `https://api.example.com` → `/.well-known/oauth-protected-resource` -- **With path**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` +`mcpAuth.getAuthMetadataOptions()` returns the MCP SDK's `AuthMetadataOptions`, ready to feed to the SDK's metadata helpers. They serve both discovery documents: -```ts -import express from 'express'; +- **Protected Resource Metadata** ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)), at the path derived from your resource identifier: + - **No path**: `https://api.example.com` → `/.well-known/oauth-protected-resource` + - **With path**: `https://api.example.com/notes` → `/.well-known/oauth-protected-resource/notes` +- **Authorization Server Metadata** ([RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)), mirrored at `/.well-known/oauth-authorization-server` (and the OpenID Connect variant) for MCP clients that look it up on your MCP server. -const app = express(); +Serving them is one call into the SDK helper for your runtime: -const mcpAuth = new MCPAuth({ - /* ... */ -}); +```ts +// Fetch-native (Cloudflare Workers, Deno, Bun, Node.js): inside your fetch handler +const metadata = oauthMetadataResponse(request, await mcpAuth.getAuthMetadataOptions()); -app.use(mcpAuth.protectedResourceMetadataRouter()); +// Express: mount the router once +app.use(mcpAuthMetadataRouter(await mcpAuth.getAuthMetadataOptions())); ``` + +See [Get started](/docs#serve-the-metadata-and-protect-your-mcp-endpoint) for the complete wiring. With the metadata endpoints in place, the next step is to protect your MCP endpoint with Bearer auth: check [Configure Bearer auth](./bearer-auth.mdx). diff --git a/docs/migrate-to-v1.mdx b/docs/migrate-to-v1.mdx new file mode 100644 index 0000000..934bdd2 --- /dev/null +++ b/docs/migrate-to-v1.mdx @@ -0,0 +1,149 @@ +--- +sidebar_position: 2 +sidebar_label: Migrate to v1 +--- + +# Migrate the Node.js SDK to v1 + +mcp-auth 1.0 is a rewrite of the Node.js SDK targeting the MCP TypeScript SDK v2 (`@modelcontextprotocol/server`). This guide covers migrating an MCP server from mcp-auth 0.2 to 1.0. + +## Why the rewrite \{#why-the-rewrite} + +The MCP TypeScript SDK v2 ships the entire HTTP layer of MCP authorization itself: `requireBearerAuth`, `verifyBearerToken`, `oauthMetadataResponse`, `OAuthError`, plus official framework adapters (`@modelcontextprotocol/express`, `fastify`, `hono`, `node`). Everything mcp-auth's Express layer used to do is now provided and maintained upstream. + +mcp-auth 1.0 therefore wraps none of the SDK's HTTP handling. Its entire job is to supply the two inputs the SDK asks you to bring: **a token verifier and your auth metadata**, for any OAuth 2.0 / OpenID Connect provider. See [Get started](/docs) for the full picture of the new API. + +## Requirements \{#requirements} + +- **MCP TypeScript SDK v2**: `@modelcontextprotocol/server` is now a peer dependency; support for the v1 SDK (`@modelcontextprotocol/sdk`) is removed. +- **Node.js >= 20**, or any fetch-native runtime such as Cloudflare Workers, Deno, or Bun. +- **ESM only.** + +```bash +npm install mcp-auth @modelcontextprotocol/server +``` + +:::note Staying on MCP SDK v1? +If you cannot move to the v2 SDK yet, stay on the 0.2 line: `npm install mcp-auth@0.2`. The [v0.2 documentation](https://github.com/mcp-auth/js/tree/v0.2.0) remains available. Existing `^0.2.0` semver ranges are unaffected by the 1.0 release. +::: + +## Migration table \{#migration-table} + +| v0.2 | 1.0 | +| ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `new MCPAuth({ protectedResources: [{ metadata: { resource, authorizationServers: [as], scopesSupported } }] })` | `new MCPAuth({ protectedResourceMetadata: { resource, authorizationServer: as, scopesSupported } })` (one instance per resource) | +| `new MCPAuth({ server: config })` (legacy authorization server mode) | Removed; configure as a resource server | +| `mcpAuth.bearerAuth('jwt', { resource, audience, requiredScopes })` (Express middleware) | `requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes }))` from `@modelcontextprotocol/express` or the SDK core (same options type for both) | +| `mcpAuth.bearerAuth(verifyFn)` (custom verification) | Implement the SDK's `OAuthTokenVerifier` yourself and pass it to `requireBearerAuth` | +| `mcpAuth.protectedResourceMetadataRouter()` | `mcpAuthMetadataRouter(await mcpAuth.getAuthMetadataOptions())` from `@modelcontextprotocol/express`, or `oauthMetadataResponse(request, await mcpAuth.getAuthMetadataOptions())` in fetch handlers | +| `mcpAuth.delegatedRouter()` | Removed (the metadata helpers also serve the authorization server metadata for legacy clients) | +| `req.auth` (Express request augmentation) | `getAuthInfo(context)` in MCP request handlers | +| `audience` unset → no `aud` validation | `aud` always validated against the `resource` identifier (no opt-out, no override) | +| camelCase metadata (`authorizationEndpoint`, …) | Wire format (`authorization_endpoint`, …), typed with the SDK's `OAuthMetadata` | +| `AuthInfo.subject` optional | `McpAuthInfo.subject` required; tokens without `sub` are rejected | +| `MCPAuthBearerAuthError` / `MCPAuthTokenVerificationError` | The SDK's `OAuthError` (`invalid_token`) on the token path | +| `jwtVerify` / `remoteJwtSet` options of `bearerAuth('jwt', ...)` | `jwtVerifyOptions` in the `MCPAuth` config (`issuer` / `audience` cannot be set) | +| `fetchServerConfig(issuer, { type })` | Unchanged (result metadata is now snake_case; the fetched `issuer` must match exactly) | + +## Walk through the changes \{#walk-through-the-changes} + +### One instance, one resource, one authorization server \{#one-instance-one-resource-one-authorization-server} + +The config is now the [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) Protected Resource Metadata declaration of a single resource trusting a single authorization server: + +```ts +// v0.2 +const mcpAuth = new MCPAuth({ + protectedResources: [ + { + metadata: { + resource: 'https://api.example.com/notes', + authorizationServers: [authServerConfig], + scopesSupported: ['read:notes'], + }, + }, + ], +}); + +// 1.0 +const mcpAuth = new MCPAuth({ + protectedResourceMetadata: { + resource: 'https://api.example.com/notes', + authorizationServer: authServerConfig, + scopesSupported: ['read:notes'], + }, +}); +``` + +If your deployment serves multiple resources, create one `MCPAuth` instance per resource. The legacy authorization server mode (`server` config with `delegatedRouter()`) is removed: with the [latest MCP specification](https://modelcontextprotocol.io/specification/latest/basic/authorization), MCP servers are resource servers. + +### Express APIs move to the MCP SDK \{#express-apis-move-to-the-mcp-sdk} + +`bearerAuth()`, `protectedResourceMetadataRouter()`, and `delegatedRouter()` are removed in favor of the SDK's own helpers: + +```ts +// v0.2 +app.use(mcpAuth.protectedResourceMetadataRouter()); +app.use( + '/mcp', + mcpAuth.bearerAuth('jwt', { resource, audience: resource, requiredScopes: ['read:notes'] }) +); + +// 1.0 +import { mcpAuthMetadataRouter, requireBearerAuth } from '@modelcontextprotocol/express'; + +app.use(mcpAuthMetadataRouter(await mcpAuth.getAuthMetadataOptions())); +app.all( + '/mcp', + requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read:notes'] })) +); +``` + +The same `getBearerAuthOptions()` result also feeds the fetch-native `requireBearerAuth` from `@modelcontextprotocol/server`. See [Configure Bearer auth](/docs/configure-server/bearer-auth) for both variants. + +### Audience validation is always on \{#audience-validation-is-always-on} + +In 0.2, audience validation only ran when you passed `audience`. The MCP specification requires access tokens to be bound to the resource they are issued for ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)), so in 1.0 the `aud` claim is always validated against the `resource` identifier, with no opt-out and no override. If your provider does not issue audience-bound access tokens, fix the provider configuration (e.g. register the resource indicator) rather than looking for a bypass. + +Similarly, the `sub` claim is now required (per [RFC 9068](https://datatracker.ietf.org/doc/html/rfc9068)): tokens without it are rejected, and `McpAuthInfo.subject` is guaranteed to downstream code. + +### Reading the auth info \{#reading-the-auth-info} + +Tool callbacks read the verified identity with `getAuthInfo` instead of destructuring `authInfo` from the request context, and can enforce per-tool scopes at the same time: + +```ts +// v0.2 +mcpServer.registerTool('whoami', { description: '...' }, (_params, { authInfo }) => { + return { content: [{ type: 'text', text: JSON.stringify(authInfo?.claims ?? {}) }] }; +}); + +// 1.0 +import { getAuthInfo } from 'mcp-auth'; + +mcpServer.registerTool('whoami', { description: '...' }, (context) => { + const { claims } = getAuthInfo(context); // Throws if the wiring is broken instead of returning undefined + return { content: [{ type: 'text', text: JSON.stringify(claims) }] }; +}); +``` + +### Custom verification \{#custom-verification} + +The custom verify-function mode (`bearerAuth(verifyFn)`) and `getTokenVerifier()` are removed. A custom verifier is now just your own implementation of the SDK's `OAuthTokenVerifier` interface, passed to `requireBearerAuth`, while the metadata half of `MCPAuth` keeps working unchanged. See [Verify opaque tokens](/docs/configure-server/bearer-auth#verify-opaque-tokens) for a complete token introspection example. + +### Metadata stays in wire format \{#metadata-stays-in-wire-format} + +The camelCase metadata types (and the conversion layer behind them) are removed. Authorization server metadata is fetched, validated, provided, and served in wire format (snake_case), typed with the SDK's `OAuthMetadata`. If you manually provide metadata or use `transpileData`, switch the field names accordingly (`authorizationEndpoint` → `authorization_endpoint`, and so on). + +### Error types \{#error-types} + +`MCPAuthBearerAuthError` and `MCPAuthTokenVerificationError` are removed. Token verification failures are the SDK's `OAuthError` (code `invalid_token`), mapped to `401` with a `WWW-Authenticate` challenge by the SDK's bearer auth helpers. `MCPAuthError`, `MCPAuthConfigError`, and `MCPAuthAuthServerError` remain for configuration and discovery failures, mapped to `500`. + +## Verify the migration \{#verify-the-migration} + +After migrating, run your MCP server and check: + +1. `GET /.well-known/oauth-protected-resource[/]` returns your Protected Resource Metadata. +2. An MCP request without a token receives a `401` response whose `WWW-Authenticate` header includes `resource_metadata`. +3. An MCP request with a valid access token (correct `iss`, `aud` matching your resource identifier, unexpired) reaches your tools, and `getAuthInfo(context)` returns the expected `subject` and `claims`. + +The [sample servers](https://github.com/mcp-auth/js/tree/master/packages/sample-servers) are complete runnable projects on the new API: `whoami` and `todo-manager` as Cloudflare Workers, plus an Express variant built with `@modelcontextprotocol/express`. diff --git a/docs/provider-guides/logto.mdx b/docs/provider-guides/logto.mdx index af0ad39..056c7e7 100644 --- a/docs/provider-guides/logto.mdx +++ b/docs/provider-guides/logto.mdx @@ -60,7 +60,10 @@ To fetch an access token that can be used to access the userinfo endpoint, at le ## Register MCP client {#register-mcp-client} -Since Logto does not support Dynamic Client Registration yet, you need to manually register your MCP client in Logto Console. +There are two ways to onboard an MCP client: + +- **Dynamic apps (no pre-registration)**: enable [dynamic apps](https://docs.logto.io/integrate-logto/third-party-applications/dynamic-apps) in your tenant, and MCP clients that support [Client ID Metadata Documents](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/) can connect without being registered first. Dynamic clients are treated as third-party apps, go through the consent screen, and share a single permission set. +- **Manual registration**: register the client in Logto Console as described below. Use this for clients that identify with a plain App ID, or when you need per-client permissions and branding. ### Third-party vs. first-party applications diff --git a/docs/references/js/README.md b/docs/references/js/README.md index b7e76f3..3bb10c8 100644 --- a/docs/references/js/README.md +++ b/docs/references/js/README.md @@ -4,59 +4,35 @@ sidebar_label: Node.js SDK # MCP Auth Node.js SDK reference -## Classes {#classes} +## Classes - [MCPAuth](/references/js/classes/MCPAuth.md) - [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) - [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) - [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) -## Type Aliases {#type-aliases} +## Type Aliases -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) - [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) - [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) - [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) +- [AuthServerMetadata](/references/js/type-aliases/AuthServerMetadata.md) - [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) +- [GetAuthInfoOptions](/references/js/type-aliases/GetAuthInfoOptions.md) - [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) +- [McpAuthInfo](/references/js/type-aliases/McpAuthInfo.md) +- [ProtectedResourceMetadataConfig](/references/js/type-aliases/ProtectedResourceMetadataConfig.md) - [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) +- [ServerMetadataConfig](/references/js/type-aliases/ServerMetadataConfig.md) -## Variables {#variables} +## Variables -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) - [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) - [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) -## Functions {#functions} +## Functions -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) - [fetchServerConfig](/references/js/functions/fetchServerConfig.md) - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) +- [getAuthInfo](/references/js/functions/getAuthInfo.md) +- [isMcpAuthInfo](/references/js/functions/isMcpAuthInfo.md) diff --git a/docs/references/js/classes/MCPAuth.md b/docs/references/js/classes/MCPAuth.md index 629de38..e89abaf 100644 --- a/docs/references/js/classes/MCPAuth.md +++ b/docs/references/js/classes/MCPAuth.md @@ -4,329 +4,310 @@ sidebar_label: MCPAuth # Class: MCPAuth -The main class for the mcp-auth library. It acts as a factory and registry for creating -authentication policies for your protected resources. +The main class of the mcp-auth library, providing the two inputs the MCP TypeScript SDK asks +you to bring when protecting an MCP server — one method each: -It is initialized with your server configurations and provides a `bearerAuth` method -to generate Express middleware for token-based authentication. +1. **A token verifier** — the instance itself implements the SDK's `OAuthTokenVerifier` + interface, and [getBearerAuthOptions](/references/js/classes/MCPAuth.md#getbearerauthoptions) bundles it with the resource metadata URL + into the SDK's `BearerAuthOptions`, ready to feed to `requireBearerAuth` (fetch-native or + any of its framework adapters). +2. **Your auth metadata** — [getAuthMetadataOptions](/references/js/classes/MCPAuth.md#getauthmetadataoptions) returns the SDK's + `AuthMetadataOptions`, ready to feed to `oauthMetadataResponse` (fetch-native) or + `mcpAuthMetadataRouter` (from `@modelcontextprotocol/express`). -## Example {#example} +One instance represents one protected resource trusting one authorization server. Create +multiple instances if your deployment serves multiple resources. -### Usage in `resource server` mode {#usage-in-resource-server-mode} +## Example -This is the recommended approach for new applications. - -#### Option 1: Discovery config (recommended for edge runtimes) {#option-1-discovery-config-recommended-for-edge-runtimes} - -Use this when you want metadata to be fetched on-demand. This is especially useful for -edge runtimes like Cloudflare Workers where top-level async fetch is not allowed. +### Fetch-native runtimes (Cloudflare Workers, Deno, Bun, Node.js) ```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; +import { createMcpHandler, McpServer, oauthMetadataResponse, requireBearerAuth } from '@modelcontextprotocol/server'; +import { getAuthInfo, MCPAuth } from 'mcp-auth'; const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // Just pass issuer and type - metadata will be fetched on first request - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Option 2: Resolved config (pre-fetched metadata) {#option-2-resolved-config-pre-fetched-metadata} - -Use this when you want to fetch and validate metadata at startup time. - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], + protectedResourceMetadata: { + resource: 'https://api.example.com/mcp', + authorizationServer: { issuer: 'https://auth.example.com/oidc', type: 'oidc' }, + scopesSupported: ['read:notes'], + }, }); -``` -#### Using the middleware {#using-the-middleware} - -```ts -// Mount the router to handle Protected Resource Metadata -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// Protect an API endpoint for the configured resource -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // Specify which resource this endpoint belongs to - audience: resourceIdentifier, // Optionally, validate the 'aud' claim - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); +const createServer = () => { + const server = new McpServer({ name: 'Notes', version: '1.0.0' }); + server.registerTool('whoami', { description: 'Get the current user' }, (ctx) => { + const { subject, claims } = getAuthInfo(ctx); + return { content: [{ type: 'text', text: JSON.stringify({ subject, claims }) }] }; + }); + return server; +}; + +const handler = createMcpHandler(createServer); +const gate = requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read:notes'] })); + +export default { + async fetch(request: Request): Promise { + // Serve the OAuth discovery documents; the path guard keeps the (lazily fetched) + // metadata resolution off the request path of regular MCP traffic + if (new URL(request.url).pathname.startsWith('/.well-known/')) { + const metadataResponse = oauthMetadataResponse(request, await mcpAuth.getAuthMetadataOptions()); + if (metadataResponse) { + return metadataResponse; + } + } + + // Require a valid Bearer token for everything else + const auth = await gate(request); + if (auth instanceof Response) { + return auth; + } + + return handler.fetch(request, { authInfo: auth }); }, -); +}; ``` -### Legacy Usage in `authorization server` mode (Deprecated) {#legacy-usage-in-authorization-server-mode-deprecated} - -This approach is supported for backward compatibility. +### Express (via `@modelcontextprotocol/express`) ```ts -import express from 'express'; +import { createMcpExpressApp, mcpAuthMetadataRouter, requireBearerAuth } from '@modelcontextprotocol/express'; +import { toNodeHandler } from '@modelcontextprotocol/node'; +import { createMcpHandler } from '@modelcontextprotocol/server'; import { MCPAuth } from 'mcp-auth'; -const app = express(); const mcpAuth = new MCPAuth({ - // Discovery config - metadata fetched on-demand - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, + protectedResourceMetadata: { + resource: 'https://api.example.com/mcp', + authorizationServer: { issuer: 'https://auth.example.com/oidc', type: 'oidc' }, + scopesSupported: ['read:notes'], + }, }); -// Mount the router to handle legacy Authorization Server Metadata -app.use(mcpAuth.delegatedRouter()); +// Reuses `createServer` from the fetch-native example above +const mcpNodeHandler = toNodeHandler(createMcpHandler(createServer)); -// Protect an endpoint using the default policy -app.get( +const app = createMcpExpressApp(); +app.use(mcpAuthMetadataRouter(await mcpAuth.getAuthMetadataOptions())); +app.all( '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // Handle the MCP request here - }, + requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read:notes'] })), + // `createMcpExpressApp` applies `express.json()`, which drains the request stream, so the + // parsed body is passed along explicitly + async (request, response) => mcpNodeHandler(request, response, request.body) ); +app.listen(3000); ``` -## Constructors {#constructors} +## Implements + +- `OAuthTokenVerifier` + +## Constructors -### Constructor {#constructor} +### Constructor ```ts new MCPAuth(config: MCPAuthConfig): MCPAuth; ``` -Creates an instance of MCPAuth. -It validates the entire configuration upfront to fail fast on errors. +Creates an instance of MCPAuth and validates the configuration, so misconfigurations fail +fast at startup. For a resolved authorization server config, the metadata is validated +immediately; for a discovery config, the metadata is validated when it is first fetched. -#### Parameters {#parameters} +#### Parameters -##### config {#config} +##### config [`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) The authentication configuration. -#### Returns {#returns} +#### Returns `MCPAuth` -## Properties {#properties} +#### Throws -### config {#config} +if the configuration is malformed. -```ts -readonly config: MCPAuthConfig; -``` +#### Throws -The authentication configuration. +if the provided authorization server metadata is invalid +or does not satisfy the MCP authorization specification. -## Methods {#methods} +## Properties -### bearerAuth() {#bearerauth} - -#### Call Signature {#call-signature} +### config ```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; +readonly config: MCPAuthConfig; ``` -Creates a Bearer auth handler (Express middleware) that verifies the access token in the -`Authorization` header of the request. - -##### Parameters {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -A function that verifies the access token. It should accept the -access token as a string and return a promise (or a value) that resolves to the -verification result. - -**See** +The authentication configuration. -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) for the type definition of the -`verifyAccessToken` function. +## Accessors -###### config? {#config} +### resourceMetadataUrl -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> +#### Get Signature -Optional configuration for the Bearer auth handler. +```ts +get resourceMetadataUrl(): string; +``` -**See** +The RFC 9728 Protected Resource Metadata URL for the configured +[ProtectedResourceMetadataConfig.resource](/references/js/type-aliases/ProtectedResourceMetadataConfig.md#resource), built with the MCP SDK's +`getOAuthProtectedResourceMetadataUrl`. -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the available configuration options (excluding -`verifyAccessToken` and `issuer`). +Pass it as the `resourceMetadataUrl` option of the SDK's `requireBearerAuth` so the +`WWW-Authenticate` challenge on `401` responses points clients at the metadata document. -##### Returns {#returns} +##### Example -`RequestHandler` +```ts +const mcpAuth = new MCPAuth({ + protectedResourceMetadata: { resource: 'https://api.example.com/mcp', ... }, +}); +mcpAuth.resourceMetadataUrl +// → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' +``` -An Express middleware function that verifies the access token and adds the -verification result to the request object (`req.auth`). +##### Returns -##### See {#see} +`string` -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) for the implementation details and the extended types of the -`req.auth` (`AuthInfo`) object. +## Methods -#### Call Signature {#call-signature} +### getAuthMetadataOptions() ```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; +getAuthMetadataOptions(): Promise; ``` -Creates a Bearer auth handler (Express middleware) that verifies the access token in the -`Authorization` header of the request using a predefined mode of verification. +Builds the MCP SDK's `AuthMetadataOptions` from this instance's configuration and the +(possibly lazily fetched) authorization server metadata. -In the `'jwt'` mode, the handler will create a JWT verification function using the JWK Set -from the authorization server's JWKS URI. +Feed the result to the SDK's `oauthMetadataResponse` (fetch-native) or to +`mcpAuthMetadataRouter` from `@modelcontextprotocol/express` to serve the OAuth discovery +documents (RFC 9728 Protected Resource Metadata and RFC 8414 Authorization Server Metadata). -##### Parameters {#parameters} +#### Returns -###### mode {#mode} +`Promise`\<`AuthMetadataOptions`\> -`"jwt"` +A promise that resolves to the SDK's `AuthMetadataOptions`. -The mode of verification for the access token. Currently, only 'jwt' is supported. +#### Throws -**See** +if fetching the authorization server metadata fails. -[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) for the available modes. +#### Throws -###### config? {#config} +if the fetched metadata is invalid or does not satisfy the +MCP authorization specification. -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` +*** -Optional configuration for the Bearer auth handler, including JWT verification options and -remote JWK set options. +### getBearerAuthOptions() -**See** +```ts +getBearerAuthOptions(options?: Pick): BearerAuthOptions; +``` - - VerifyJwtConfig for the available configuration options for JWT -verification. - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the available configuration options (excluding -`verifyAccessToken` and `issuer`). +Builds the MCP SDK's `BearerAuthOptions` from this instance: the instance itself as the +`verifier` and [resourceMetadataUrl](/references/js/classes/MCPAuth.md#resourcemetadataurl) for the `WWW-Authenticate` challenge, plus the +per-endpoint `requiredScopes` you pass in. -##### Returns {#returns} +Feed the result to `requireBearerAuth` — the fetch-native one from +`@modelcontextprotocol/server` and the Express middleware from +`@modelcontextprotocol/express` accept the same options type. Endpoints with different +scope requirements call this method once each. -`RequestHandler` +#### Parameters -An Express middleware function that verifies the access token and adds the -verification result to the request object (`req.auth`). +##### options? -##### See {#see} +`Pick`\<`BearerAuthOptions`, `"requiredScopes"`\> -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) for the implementation details and the extended types of the -`req.auth` (`AuthInfo`) object. +Per-endpoint bearer-auth requirements. -##### Throws {#throws} +#### Returns -if the JWKS URI is not provided in the server metadata when -using the `'jwt'` mode. +`BearerAuthOptions` -*** +The SDK's `BearerAuthOptions`, ready to pass to `requireBearerAuth`. -### ~~delegatedRouter()~~ {#delegatedrouter} +#### Example ```ts -delegatedRouter(): Router; -``` +// Fetch-native (Cloudflare Workers, Deno, Bun, Node.js) +const gate = requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read:notes'] })); -Creates a delegated router for serving legacy OAuth 2.0 Authorization Server Metadata endpoint -(`/.well-known/oauth-authorization-server`) with the metadata provided to the instance. +// Express +app.post('/mcp', requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read:notes'] })), ...); +``` -#### Returns {#returns} +*** -`Router` +### verifyAccessToken() -A router that serves the OAuth 2.0 Authorization Server Metadata endpoint with the -metadata provided to the instance. +```ts +verifyAccessToken(token: string): Promise; +``` -#### Deprecated {#deprecated} +Verifies a JWT access token issued by the trusted authorization server and returns the +extended auth info ([McpAuthInfo](/references/js/type-aliases/McpAuthInfo.md)). -Use [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) instead. +This method implements the MCP SDK's `OAuthTokenVerifier` interface, so the instance can be +passed directly as the `verifier` to the SDK's `requireBearerAuth` / `verifyBearerToken` +(or their framework adapters). -#### Example {#example} +The verification flow: -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; +1. Decodes the token (without verifying) and rejects it unless its `iss` claim matches the + trusted issuer — before any metadata or JWKS request is made. +2. Resolves the authorization server metadata and JWK Set (both cached across calls). +3. Verifies the token signature and the `iss` and `aud` claims (the `aud` claim must match + the [ProtectedResourceMetadataConfig.resource](/references/js/type-aliases/ProtectedResourceMetadataConfig.md#resource) identifier, per the RFC 8707 + audience binding the MCP authorization specification requires), plus standard time + claims, via `jose.jwtVerify`. +4. Requires a non-empty `sub` claim (per RFC 9068) and maps the payload to + [McpAuthInfo](/references/js/type-aliases/McpAuthInfo.md): `clientId` from `client_id` (falling back to `azp`), `scopes` from + `scope` (space-separated) or `scopes` (array), and `expiresAt` from `exp`. -const app = express(); -const mcpAuth: MCPAuth; // Assume this is initialized -app.use(mcpAuth.delegatedRouter()); -``` +#### Parameters -#### Throws {#throws} +##### token -If called in `resource server` mode. +`string` -*** +The raw JWT access token. -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} +#### Returns -```ts -protectedResourceMetadataRouter(): Router; -``` +`Promise`\<[`McpAuthInfo`](/references/js/type-aliases/McpAuthInfo.md)\> -Creates a router that serves the OAuth 2.0 Protected Resource Metadata endpoint -for all configured resources. +A promise that resolves to the verified auth info. -This router automatically creates the correct `.well-known` endpoints for each -resource identifier provided in your configuration. +#### Throws -#### Returns {#returns} +(from `@modelcontextprotocol/server`, with code `invalid_token`) if the +token is malformed, from an untrusted issuer, or fails verification. The SDK bearer-auth +helpers map this to a `401` response with a `WWW-Authenticate` challenge. -`Router` +#### Throws -A router that serves the OAuth 2.0 Protected Resource Metadata endpoint. +if fetching the authorization server metadata fails; the SDK +bearer-auth helpers map non-`OAuthError` errors to a `500` response. -#### Throws {#throws} +#### Throws -If called in `authorization server` mode. +if the authorization server metadata is invalid or has no +JWKS URI. -#### Example {#example} +#### Implementation of ```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// Assuming mcpAuth is initialized with one or more `protectedResources` configs -const mcpAuth: MCPAuth; -const app = express(); - -// This will serve metadata at `/.well-known/oauth-protected-resource/...` -// based on your resource identifiers. -app.use(mcpAuth.protectedResourceMetadataRouter()); +OAuthTokenVerifier.verifyAccessToken ``` diff --git a/docs/references/js/classes/MCPAuthAuthServerError.md b/docs/references/js/classes/MCPAuthAuthServerError.md index 4b9c556..b035086 100644 --- a/docs/references/js/classes/MCPAuthAuthServerError.md +++ b/docs/references/js/classes/MCPAuthAuthServerError.md @@ -4,53 +4,54 @@ sidebar_label: MCPAuthAuthServerError # Class: MCPAuthAuthServerError -Error thrown when there is an issue with the remote authorization server. +Error thrown when there is an issue with the remote authorization server, such as invalid +metadata or a configuration that does not satisfy the MCP authorization specification. -## Extends {#extends} +## Extends - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) -## Constructors {#constructors} +## Constructors -### Constructor {#constructor} +### Constructor ```ts new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; ``` -#### Parameters {#parameters} +#### Parameters -##### code {#code} +##### code [`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) -##### cause? {#cause} +##### cause? `unknown` -#### Returns {#returns} +#### Returns `MCPAuthAuthServerError` -#### Overrides {#overrides} +#### Overrides [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) -## Properties {#properties} +## Properties -### cause? {#cause} +### cause? ```ts readonly optional cause: unknown; ``` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) *** -### code {#code} +### code ```ts readonly code: AuthServerErrorCode; @@ -58,49 +59,49 @@ readonly code: AuthServerErrorCode; The error code in snake_case format. -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) *** -### message {#message} +### message ```ts message: string; ``` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) *** -### name {#name} +### name ```ts name: string = 'MCPAuthAuthServerError'; ``` -#### Overrides {#overrides} +#### Overrides [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) *** -### stack? {#stack} +### stack? ```ts optional stack: string; ``` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) *** -### prepareStackTrace()? {#preparestacktrace} +### prepareStackTrace()? ```ts static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; @@ -108,70 +109,43 @@ static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; Optional override for formatting stack traces -#### Parameters {#parameters} +#### Parameters -##### err {#err} +##### err `Error` -##### stackTraces {#stacktraces} +##### stackTraces `CallSite`[] -#### Returns {#returns} +#### Returns `any` -#### See {#see} +#### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) *** -### stackTraceLimit {#stacktracelimit} +### stackTraceLimit ```ts static stackTraceLimit: number; ``` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) -## Methods {#methods} +## Methods -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converts the error to a HTTP response friendly JSON format. - -#### Parameters {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Whether to include the cause of the error in the JSON response. -Defaults to `false`. - -#### Returns {#returns} - -`Record`\<`string`, `unknown`\> - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} +### captureStackTrace() ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -179,20 +153,20 @@ static captureStackTrace(targetObject: object, constructorOpt?: Function): void; Create .stack property on a target object -#### Parameters {#parameters} +#### Parameters -##### targetObject {#targetobject} +##### targetObject `object` -##### constructorOpt? {#constructoropt} +##### constructorOpt? `Function` -#### Returns {#returns} +#### Returns `void` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/docs/references/js/classes/MCPAuthBearerAuthError.md b/docs/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index 7990bdc..0000000 --- a/docs/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# Class: MCPAuthBearerAuthError - -Error thrown when there is an issue when authenticating with Bearer tokens. - -## Extends {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructors {#constructors} - -### Constructor {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### Parameters {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### Returns {#returns} - -`MCPAuthBearerAuthError` - -#### Overrides {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Properties {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -The error code in snake_case format. - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### Overrides {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Optional override for formatting stack traces - -#### Parameters {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Returns {#returns} - -`any` - -#### See {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Methods {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converts the error to a HTTP response friendly JSON format. - -#### Parameters {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Whether to include the cause of the error in the JSON response. -Defaults to `false`. - -#### Returns {#returns} - -`Record`\<`string`, `unknown`\> - -#### Overrides {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Create .stack property on a target object - -#### Parameters {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Returns {#returns} - -`void` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/docs/references/js/classes/MCPAuthConfigError.md b/docs/references/js/classes/MCPAuthConfigError.md index 8047fdd..516640b 100644 --- a/docs/references/js/classes/MCPAuthConfigError.md +++ b/docs/references/js/classes/MCPAuthConfigError.md @@ -4,57 +4,58 @@ sidebar_label: MCPAuthConfigError # Class: MCPAuthConfigError -Error thrown when there is a configuration issue with mcp-auth. +Error thrown when there is a configuration issue with mcp-auth, such as an invalid resource +identifier or a failed metadata fetch. -## Extends {#extends} +## Extends - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) -## Constructors {#constructors} +## Constructors -### Constructor {#constructor} +### Constructor ```ts new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; ``` -#### Parameters {#parameters} +#### Parameters -##### code {#code} +##### code `string` The error code in snake_case format. -##### message {#message} +##### message `string` A human-readable description of the error. -#### Returns {#returns} +#### Returns `MCPAuthConfigError` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) -## Properties {#properties} +## Properties -### cause? {#cause} +### cause? ```ts optional cause: unknown; ``` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) *** -### code {#code} +### code ```ts readonly code: string; @@ -62,49 +63,49 @@ readonly code: string; The error code in snake_case format. -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) *** -### message {#message} +### message ```ts message: string; ``` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) *** -### name {#name} +### name ```ts name: string = 'MCPAuthConfigError'; ``` -#### Overrides {#overrides} +#### Overrides [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) *** -### stack? {#stack} +### stack? ```ts optional stack: string; ``` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) *** -### prepareStackTrace()? {#preparestacktrace} +### prepareStackTrace()? ```ts static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; @@ -112,70 +113,43 @@ static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; Optional override for formatting stack traces -#### Parameters {#parameters} +#### Parameters -##### err {#err} +##### err `Error` -##### stackTraces {#stacktraces} +##### stackTraces `CallSite`[] -#### Returns {#returns} +#### Returns `any` -#### See {#see} +#### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) *** -### stackTraceLimit {#stacktracelimit} +### stackTraceLimit ```ts static stackTraceLimit: number; ``` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) -## Methods {#methods} +## Methods -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converts the error to a HTTP response friendly JSON format. - -#### Parameters {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Whether to include the cause of the error in the JSON response. -Defaults to `false`. - -#### Returns {#returns} - -`Record`\<`string`, `unknown`\> - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} +### captureStackTrace() ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -183,20 +157,20 @@ static captureStackTrace(targetObject: object, constructorOpt?: Function): void; Create .stack property on a target object -#### Parameters {#parameters} +#### Parameters -##### targetObject {#targetobject} +##### targetObject `object` -##### constructorOpt? {#constructoropt} +##### constructorOpt? `Function` -#### Returns {#returns} +#### Returns `void` -#### Inherited from {#inherited-from} +#### Inherited from [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/docs/references/js/classes/MCPAuthError.md b/docs/references/js/classes/MCPAuthError.md index 6bffab7..d28b317 100644 --- a/docs/references/js/classes/MCPAuthError.md +++ b/docs/references/js/classes/MCPAuthError.md @@ -6,60 +6,61 @@ sidebar_label: MCPAuthError Base class for all mcp-auth errors. -It provides a standardized way to handle errors related to MCP authentication and authorization. +These errors cover configuration and authorization server discovery failures. Token +verification failures are intentionally NOT represented here — `MCPAuth#verifyAccessToken` +throws the MCP SDK's `OAuthError` instead, because the SDK bearer-auth helpers only map +`OAuthError` to proper `401` challenge responses (anything else becomes a `500`). -## Extends {#extends} +## Extends - `Error` -## Extended by {#extended-by} +## Extended by - [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) - [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) -## Constructors {#constructors} +## Constructors -### Constructor {#constructor} +### Constructor ```ts new MCPAuthError(code: string, message: string): MCPAuthError; ``` -#### Parameters {#parameters} +#### Parameters -##### code {#code} +##### code `string` The error code in snake_case format. -##### message {#message} +##### message `string` A human-readable description of the error. -#### Returns {#returns} +#### Returns `MCPAuthError` -#### Overrides {#overrides} +#### Overrides ```ts Error.constructor ``` -## Properties {#properties} +## Properties -### cause? {#cause} +### cause? ```ts optional cause: unknown; ``` -#### Inherited from {#inherited-from} +#### Inherited from ```ts Error.cause @@ -67,7 +68,7 @@ Error.cause *** -### code {#code} +### code ```ts readonly code: string; @@ -77,13 +78,13 @@ The error code in snake_case format. *** -### message {#message} +### message ```ts message: string; ``` -#### Inherited from {#inherited-from} +#### Inherited from ```ts Error.message @@ -91,13 +92,13 @@ Error.message *** -### name {#name} +### name ```ts name: string = 'MCPAuthError'; ``` -#### Overrides {#overrides} +#### Overrides ```ts Error.name @@ -105,13 +106,13 @@ Error.name *** -### stack? {#stack} +### stack? ```ts optional stack: string; ``` -#### Inherited from {#inherited-from} +#### Inherited from ```ts Error.stack @@ -119,7 +120,7 @@ Error.stack *** -### prepareStackTrace()? {#preparestacktrace} +### prepareStackTrace()? ```ts static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; @@ -127,25 +128,25 @@ static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; Optional override for formatting stack traces -#### Parameters {#parameters} +#### Parameters -##### err {#err} +##### err `Error` -##### stackTraces {#stacktraces} +##### stackTraces `CallSite`[] -#### Returns {#returns} +#### Returns `any` -#### See {#see} +#### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces -#### Inherited from {#inherited-from} +#### Inherited from ```ts Error.prepareStackTrace @@ -153,44 +154,21 @@ Error.prepareStackTrace *** -### stackTraceLimit {#stacktracelimit} +### stackTraceLimit ```ts static stackTraceLimit: number; ``` -#### Inherited from {#inherited-from} +#### Inherited from ```ts Error.stackTraceLimit ``` -## Methods {#methods} +## Methods -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converts the error to a HTTP response friendly JSON format. - -#### Parameters {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Whether to include the cause of the error in the JSON response. -Defaults to `false`. - -#### Returns {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} +### captureStackTrace() ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -198,21 +176,21 @@ static captureStackTrace(targetObject: object, constructorOpt?: Function): void; Create .stack property on a target object -#### Parameters {#parameters} +#### Parameters -##### targetObject {#targetobject} +##### targetObject `object` -##### constructorOpt? {#constructoropt} +##### constructorOpt? `Function` -#### Returns {#returns} +#### Returns `void` -#### Inherited from {#inherited-from} +#### Inherited from ```ts Error.captureStackTrace diff --git a/docs/references/js/classes/MCPAuthTokenVerificationError.md b/docs/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index 78be151..0000000 --- a/docs/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# Class: MCPAuthTokenVerificationError - -Error thrown when there is an issue when verifying tokens. - -## Extends {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructors {#constructors} - -### Constructor {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### Parameters {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### Returns {#returns} - -`MCPAuthTokenVerificationError` - -#### Overrides {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Properties {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -The error code in snake_case format. - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### Overrides {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Optional override for formatting stack traces - -#### Parameters {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Returns {#returns} - -`any` - -#### See {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Methods {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converts the error to a HTTP response friendly JSON format. - -#### Parameters {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Whether to include the cause of the error in the JSON response. -Defaults to `false`. - -#### Returns {#returns} - -`Record`\<`string`, `unknown`\> - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Create .stack property on a target object - -#### Parameters {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Returns {#returns} - -`void` - -#### Inherited from {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/docs/references/js/functions/createVerifyJwt.md b/docs/references/js/functions/createVerifyJwt.md deleted file mode 100644 index c7126e8..0000000 --- a/docs/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# Function: createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -Creates a function to verify JWT access tokens using the provided key retrieval function -and options. - -## Parameters {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -The function to retrieve the key used to verify the JWT. - -**See** - -JWTVerifyGetKey for the type definition of the key retrieval function. - -### options? {#options} - -`JWTVerifyOptions` - -Optional JWT verification options. - -**See** - -JWTVerifyOptions for the type definition of the options. - -## Returns {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -A function that verifies JWT access tokens and returns an AuthInfo object if -the token is valid. It requires the JWT to contain the fields `iss`, `client_id`, and `sub` in -its payload, and it can optionally contain `scope` or `scopes` fields. The function uses the -`jose` library under the hood to perform the JWT verification. - -## See {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) for the type definition of the returned function. diff --git a/docs/references/js/functions/fetchServerConfig.md b/docs/references/js/functions/fetchServerConfig.md index 97175e5..99b13d9 100644 --- a/docs/references/js/functions/fetchServerConfig.md +++ b/docs/references/js/functions/fetchServerConfig.md @@ -10,55 +10,60 @@ function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promis Fetches the server configuration according to the issuer and authorization server type. -This function automatically determines the well-known URL based on the server type, as OAuth and -OpenID Connect servers have different conventions for their metadata endpoints. +This function automatically determines the well-known URL based on the server type, as OAuth +and OpenID Connect servers have different conventions for their metadata endpoints. It also +validates that the `issuer` field in the fetched metadata matches the expected issuer, as +required by RFC 8414 and OpenID Connect Discovery. -## Parameters {#parameters} +## Parameters -### issuer {#issuer} +### issuer `string` The issuer URL of the authorization server. -### config {#config} +### config -`ServerMetadataConfig` +[`ServerMetadataConfig`](/references/js/type-aliases/ServerMetadataConfig.md) The configuration object containing the server type and optional transpile function. -## Returns {#returns} +## Returns `Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -A promise that resolves to the static server configuration with fetched metadata. +A promise that resolves to the resolved server configuration with fetched metadata. -## See {#see} +## See - - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) for the underlying implementation. - - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) for the OAuth 2.0 Authorization Server Metadata -specification. + - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) for the underlying implementation, which can be +used directly when the well-known URL differs from the standard conventions (no issuer match +validation is performed in that case). + - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) for the OAuth 2.0 Authorization Server +Metadata specification. - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) for the OpenID Connect Discovery specification. -## Example {#example} +## Example ```ts import { fetchServerConfig } from 'mcp-auth'; + // Fetching OAuth server configuration -// This will fetch the metadata from `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` +// This fetches the metadata from `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); // Fetching OpenID Connect server configuration -// This will fetch the metadata from `https://auth.logto.io/oidc/.well-known/openid-configuration` +// This fetches the metadata from `https://auth.logto.io/oidc/.well-known/openid-configuration` const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); ``` -## Throws {#throws} +## Throws if the fetch operation fails. -## Throws {#throws} +## Throws -if the server metadata is invalid or does not match the -MCP specification. +if the server metadata is invalid, does not match the +MCP specification, or its issuer does not match the expected issuer. diff --git a/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md b/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md index ebc56b5..33f097e 100644 --- a/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ b/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md @@ -15,32 +15,32 @@ If the server metadata does not conform to the expected schema, but you are sure compatible, you can define a `transpileData` function to transform the metadata into the expected format. -## Parameters {#parameters} +## Parameters -### wellKnownUrl {#wellknownurl} +### wellKnownUrl The well-known URL to fetch the server configuration from. This can be a string or a URL object. `string` | `URL` -### config {#config} +### config -`ServerMetadataConfig` +[`ServerMetadataConfig`](/references/js/type-aliases/ServerMetadataConfig.md) The configuration object containing the server type and optional transpile function. -## Returns {#returns} +## Returns `Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -A promise that resolves to the static server configuration with fetched metadata. +A promise that resolves to the resolved server configuration with fetched metadata. -## Throws {#throws} +## Throws if the fetch operation fails. -## Throws {#throws} +## Throws if the server metadata is invalid or does not match the MCP specification. diff --git a/docs/references/js/functions/getAuthInfo.md b/docs/references/js/functions/getAuthInfo.md new file mode 100644 index 0000000..f5e08d9 --- /dev/null +++ b/docs/references/js/functions/getAuthInfo.md @@ -0,0 +1,59 @@ +--- +sidebar_label: getAuthInfo +--- + +# Function: getAuthInfo() + +```ts +function getAuthInfo(context: BaseContext, options?: GetAuthInfoOptions): McpAuthInfo; +``` + +Extracts the verified [McpAuthInfo](/references/js/type-aliases/McpAuthInfo.md) from an MCP request handler context (e.g. a tool +callback's second argument), optionally enforcing per-tool scopes. + +The bearer-auth middleware guarantees the auth info is present on every authenticated HTTP +request, so a missing value indicates a wiring problem — for example, the MCP endpoint is not +protected by `requireBearerAuth`, or a different token verifier than `MCPAuth` is in use. + +## Parameters + +### context + +`BaseContext` + +The request handler context provided by the MCP SDK. + +### options? + +[`GetAuthInfoOptions`](/references/js/type-aliases/GetAuthInfoOptions.md) + +Optional per-tool authorization requirements. + +## Returns + +[`McpAuthInfo`](/references/js/type-aliases/McpAuthInfo.md) + +The verified auth info. + +## Example + +```ts +import { getAuthInfo } from 'mcp-auth'; + +server.registerTool('whoami', { description: 'Get the current user' }, (ctx) => { + const { subject, claims } = getAuthInfo(ctx); + return { content: [{ type: 'text', text: JSON.stringify({ subject, claims }) }] }; +}); + +server.registerTool('purge-notes', { description: 'Delete every note' }, (ctx) => { + // Throws unless the token has the `notes:write` scope; the SDK surfaces the error to the + // model as a tool error result. + const { subject } = getAuthInfo(ctx, { requiredScopes: ['notes:write'] }); + // ... +}); +``` + +## Throws + +if the context has no auth info, the auth info was not produced by +`MCPAuth#verifyAccessToken`, or a required scope is missing. diff --git a/docs/references/js/functions/getIssuer.md b/docs/references/js/functions/getIssuer.md deleted file mode 100644 index 0ce55ef..0000000 --- a/docs/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# Function: getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -Get the issuer URL from an auth server config. - -- Resolved config: extracts from `metadata.issuer` -- Discovery config: returns `issuer` directly - -## Parameters {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## Returns {#returns} - -`string` diff --git a/docs/references/js/functions/handleBearerAuth.md b/docs/references/js/functions/handleBearerAuth.md deleted file mode 100644 index ddb403e..0000000 --- a/docs/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# Function: handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -Creates a middleware function for handling Bearer auth in an Express application. - -This middleware extracts the Bearer token from the `Authorization` header, verifies it using the -provided `verifyAccessToken` function, and checks the issuer, audience, and required scopes. - -- If the token is valid, it adds the auth information to the `request.auth` property; -if not, it responds with an appropriate error message. -- If access token verification fails, it responds with a 401 Unauthorized error. -- If the token does not have the required scopes, it responds with a 403 Forbidden error. -- If unexpected errors occur during the auth process, the middleware will re-throw them. - -**Note:** The `request.auth` object will contain extended fields compared to the standard -AuthInfo interface defined in the `@modelcontextprotocol/sdk` module. See the extended -interface in this file for details. - -## Parameters {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Configuration for the Bearer auth handler. - -## Returns {#returns} - -`RequestHandler` - -A middleware function for Express that handles Bearer auth. - -## See {#see} - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the configuration options. diff --git a/docs/references/js/functions/isMcpAuthInfo.md b/docs/references/js/functions/isMcpAuthInfo.md new file mode 100644 index 0000000..7f437c9 --- /dev/null +++ b/docs/references/js/functions/isMcpAuthInfo.md @@ -0,0 +1,22 @@ +--- +sidebar_label: isMcpAuthInfo +--- + +# Function: isMcpAuthInfo() + +```ts +function isMcpAuthInfo(info: AuthInfo): info is McpAuthInfo; +``` + +Checks whether an `AuthInfo` object carries the mcp-auth guarantees ([McpAuthInfo](/references/js/type-aliases/McpAuthInfo.md)), +i.e. it was produced by `MCPAuth#verifyAccessToken`. + +## Parameters + +### info + +`AuthInfo` + +## Returns + +`info is McpAuthInfo` diff --git a/docs/references/js/type-aliases/AuthServerConfig.md b/docs/references/js/type-aliases/AuthServerConfig.md index 42f777a..cf9a46a 100644 --- a/docs/references/js/type-aliases/AuthServerConfig.md +++ b/docs/references/js/type-aliases/AuthServerConfig.md @@ -10,8 +10,9 @@ type AuthServerConfig = | AuthServerDiscoveryConfig; ``` -Configuration for the remote authorization server integrated with the MCP server. +Configuration for the remote authorization server trusted by the MCP server. Can be either: -- **Resolved**: Contains `metadata` - no network request needed -- **Discovery**: Contains only `issuer` and `type` - metadata fetched on-demand via discovery + +- **Discovery**: contains `issuer` and `type` — metadata is fetched on-demand and cached +- **Resolved**: contains `metadata` — no network request needed diff --git a/docs/references/js/type-aliases/AuthServerConfigError.md b/docs/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index 05371c1..0000000 --- a/docs/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# Type Alias: AuthServerConfigError - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -Represents an error that occurs during the validation of the authorization server metadata. - -## Properties {#properties} - -### cause? {#cause} - -```ts -optional cause: Error; -``` - -An optional cause of the error, typically an instance of `Error` that provides more context. - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -The code representing the specific validation error. - -*** - -### description {#description} - -```ts -description: string; -``` - -A human-readable description of the error. diff --git a/docs/references/js/type-aliases/AuthServerConfigErrorCode.md b/docs/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index 9ba4f41..0000000 --- a/docs/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# Type Alias: AuthServerConfigErrorCode - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -The codes for errors that can occur when validating the authorization server metadata. diff --git a/docs/references/js/type-aliases/AuthServerConfigWarning.md b/docs/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index f093e35..0000000 --- a/docs/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# Type Alias: AuthServerConfigWarning - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -Represents a warning that occurs during the validation of the authorization server metadata. - -## Properties {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -The code representing the specific validation warning. - -*** - -### description {#description} - -```ts -description: string; -``` - -A human-readable description of the warning. diff --git a/docs/references/js/type-aliases/AuthServerConfigWarningCode.md b/docs/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index c5a297d..0000000 --- a/docs/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# Type Alias: AuthServerConfigWarningCode - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -The codes for warnings that can occur when validating the authorization server metadata. diff --git a/docs/references/js/type-aliases/AuthServerDiscoveryConfig.md b/docs/references/js/type-aliases/AuthServerDiscoveryConfig.md index 108c4d0..9e52eb6 100644 --- a/docs/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ b/docs/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -13,40 +13,35 @@ type AuthServerDiscoveryConfig = { Discovery configuration for the remote authorization server. -Use this when you want the metadata to be fetched on-demand via discovery when first needed. -This is useful for edge runtimes like Cloudflare Workers where top-level async fetch -is not allowed. +Use this when you want the metadata to be fetched on-demand when first needed. This is +required for edge runtimes like Cloudflare Workers where network requests are not allowed +during module initialization, and it avoids a startup fetch elsewhere. -## Example {#example} +## Example -```typescript +```ts const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, + protectedResourceMetadata: { + resource: 'https://api.example.com/mcp', + authorizationServer: { issuer: 'https://auth.example.com/oidc', type: 'oidc' }, }, }); ``` -## Properties {#properties} +## Properties -### issuer {#issuer} +### issuer ```ts issuer: string; ``` The issuer URL of the authorization server. The metadata will be fetched from the -well-known endpoint derived from this issuer. +well-known endpoint derived from this issuer according to the server type. *** -### type {#type} +### type ```ts type: AuthServerType; @@ -54,6 +49,6 @@ type: AuthServerType; The type of the authorization server. -#### See {#see} +#### See [AuthServerType](/references/js/type-aliases/AuthServerType.md) for the possible values. diff --git a/docs/references/js/type-aliases/AuthServerMetadata.md b/docs/references/js/type-aliases/AuthServerMetadata.md new file mode 100644 index 0000000..8adf9d9 --- /dev/null +++ b/docs/references/js/type-aliases/AuthServerMetadata.md @@ -0,0 +1,41 @@ +--- +sidebar_label: AuthServerMetadata +--- + +# Type Alias: AuthServerMetadata + +```ts +type AuthServerMetadata = OAuthMetadata & { + jwks_uri?: string; +}; +``` + +Authorization server metadata in wire format (snake_case), as fetched from the server's +discovery endpoint or provided directly in the configuration. + +This is the MCP SDK's RFC 8414 `OAuthMetadata` type, extended with the `jwks_uri` field that +mcp-auth requires for JWT verification. The metadata is passed verbatim (no key-casing +transformation) to the SDK's metadata helpers such as `oauthMetadataResponse` and +`mcpAuthMetadataRouter`. + +Note: mcp-auth validates the fields it consumes (`issuer`, `authorization_endpoint`, +`token_endpoint`, `response_types_supported`, `jwks_uri`, `grant_types_supported`, +`code_challenge_methods_supported`, `registration_endpoint`); other fields are passed through +as-is. + +## Type declaration + +### jwks\_uri? + +```ts +optional jwks_uri: string; +``` + +URL of the authorization server's JWK Set document, used to verify JWT access token +signatures. Required by OpenID Connect Discovery; optional in RFC 8414 but required by +mcp-auth when verifying tokens. + +## See + + - [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) + - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) diff --git a/docs/references/js/type-aliases/AuthServerModeConfig.md b/docs/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index da4c827..0000000 --- a/docs/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# Type Alias: ~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -Configuration for the legacy, MCP server as authorization server mode. - -## Deprecated {#deprecated} - -Use `ResourceServerModeConfig` config instead. - -## Properties {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -The single authorization server configuration. - -#### Deprecated {#deprecated} - -Use `protectedResources` config instead. diff --git a/docs/references/js/type-aliases/AuthServerSuccessCode.md b/docs/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index 7bb5610..0000000 --- a/docs/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# Type Alias: AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -The codes for successful validation of the authorization server metadata. diff --git a/docs/references/js/type-aliases/AuthServerType.md b/docs/references/js/type-aliases/AuthServerType.md index 21fa06b..169df57 100644 --- a/docs/references/js/type-aliases/AuthServerType.md +++ b/docs/references/js/type-aliases/AuthServerType.md @@ -8,6 +8,9 @@ sidebar_label: AuthServerType type AuthServerType = "oauth" | "oidc"; ``` -The type of the authorization server. This information should be provided by the server -configuration and indicates whether the server is an OAuth 2.0 or OpenID Connect (OIDC) -authorization server. +The type of the authorization server. It determines which discovery convention is used to +locate the server metadata: + +- `'oidc'`: OpenID Connect Discovery (`/.well-known/openid-configuration`) +- `'oauth'`: OAuth 2.0 Authorization Server Metadata (RFC 8414 path insertion, + `/.well-known/oauth-authorization-server`) diff --git a/docs/references/js/type-aliases/AuthorizationServerMetadata.md b/docs/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index 055f293..0000000 --- a/docs/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: AuthorizationServerMetadata ---- - -# Type Alias: AuthorizationServerMetadata - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -Schema for OAuth 2.0 Authorization Server Metadata as defined in RFC 8414. - -## See {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 diff --git a/docs/references/js/type-aliases/BearerAuthConfig.md b/docs/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index cfb0f36..0000000 --- a/docs/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# Type Alias: BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## Properties {#properties} - -### audience? {#audience} - -```ts -optional audience: string; -``` - -The expected audience of the access token (`aud` claim). This is typically the resource server -(API) that the token is intended for. If not provided, the audience check will be skipped. - -**Note:** If your authorization server does not support Resource Indicators (RFC 8707), -you can omit this field since the audience may not be relevant. - -#### See {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -A string representing a valid issuer, or a function for validating the issuer of the access token. - -If a string is provided, it will be used as the expected issuer value for direct comparison. - -If a function is provided, it should validate the issuer according to the rules in -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md). - -#### See {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) for more details about the validation function. - -*** - -### requiredScopes? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -An array of required scopes that the access token must have. If the token does not contain -all of these scopes, an error will be thrown. - -**Note:** The handler will check the `scope` claim in the token, which may be a space- -separated string or an array of strings, depending on the authorization server's -implementation. If the `scope` claim is not present, the handler will check the `scopes` claim -if available. - -*** - -### resource? {#resource} - -```ts -optional resource: string; -``` - -The identifier of the protected resource. When provided, the handler will use the -authorization servers configured for this resource to validate the received token. -It's required when using the handler with a `protectedResources` configuration. - -*** - -### showErrorDetails? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -Whether to show detailed error information in the response. This is useful for debugging -during development, but should be disabled in production to avoid leaking sensitive -information. - -#### Default {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -Function type for verifying an access token. - -This function should throw an [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) if the token is invalid, -or return an AuthInfo object if the token is valid. - -#### See {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) for more details. diff --git a/docs/references/js/type-aliases/BearerAuthErrorCode.md b/docs/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index 5887161..0000000 --- a/docs/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# Type Alias: BearerAuthErrorCode - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/docs/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/docs/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index 612d471..0000000 --- a/docs/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# Type Alias: CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -The camelCase version of the OAuth 2.0 Authorization Server Metadata type. - -## See {#see} - -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) for the original type and field information. diff --git a/docs/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/docs/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index 248191b..0000000 --- a/docs/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# Type Alias: CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -The camelCase version of the OAuth 2.0 Protected Resource Metadata type. - -## See {#see} - -[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) for the original type and field information. diff --git a/docs/references/js/type-aliases/GetAuthInfoOptions.md b/docs/references/js/type-aliases/GetAuthInfoOptions.md new file mode 100644 index 0000000..82d4690 --- /dev/null +++ b/docs/references/js/type-aliases/GetAuthInfoOptions.md @@ -0,0 +1,27 @@ +--- +sidebar_label: GetAuthInfoOptions +--- + +# Type Alias: GetAuthInfoOptions + +```ts +type GetAuthInfoOptions = { + requiredScopes?: string[]; +}; +``` + +## Properties + +### requiredScopes? + +```ts +optional requiredScopes: string[]; +``` + +Scopes the access token must include, for per-tool authorization on top of the +endpoint-level `requiredScopes` of the SDK's `requireBearerAuth`. + +When any are missing, an [MCPAuthError](/references/js/classes/MCPAuthError.md) with code `'missing_required_scopes'` is +thrown. The MCP SDK converts errors thrown in tool callbacks into tool error results +(`isError: true`), so the model receives a graceful `insufficient_scope: ...` refusal +instead of a failed request. diff --git a/docs/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/docs/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index 9961d48..0000000 --- a/docs/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# Type Alias: MCPAuthBearerAuthErrorDetails - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## Properties {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/docs/references/js/type-aliases/MCPAuthConfig.md b/docs/references/js/type-aliases/MCPAuthConfig.md index 52bed28..ce1bf1c 100644 --- a/docs/references/js/type-aliases/MCPAuthConfig.md +++ b/docs/references/js/type-aliases/MCPAuthConfig.md @@ -5,10 +5,45 @@ sidebar_label: MCPAuthConfig # Type Alias: MCPAuthConfig ```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; +type MCPAuthConfig = { + jwtVerifyOptions?: Omit; + protectedResourceMetadata: ProtectedResourceMetadataConfig; +}; ``` -Config for the [MCPAuth](/references/js/classes/MCPAuth.md) class, supporting either a single legacy `authorization server` -or the `resource server` configuration. +Config for the [MCPAuth](/references/js/classes/MCPAuth.md) class. One instance protects one resource and trusts one +authorization server. + +## Properties + +### jwtVerifyOptions? + +```ts +optional jwtVerifyOptions: Omit; +``` + +Per-call options passed to the underlying `jose.jwtVerify` function, e.g. `clockTolerance` +or `requiredClaims`. The `issuer` and `audience` options are derived from +[protectedResourceMetadata](/references/js/type-aliases/MCPAuthConfig.md#protectedresourcemetadata) and cannot be set here: the MCP authorization +specification requires access tokens to be bound to this server's `resource` identifier +(RFC 8707), and accepting unbound tokens would let a token issued for a different resource +of the same authorization server be replayed against this MCP server. + +#### See + +JWTVerifyOptions + +*** + +### protectedResourceMetadata + +```ts +protectedResourceMetadata: ProtectedResourceMetadataConfig; +``` + +The Protected Resource Metadata declaration (RFC 9728) of this MCP server, published +through the SDK's metadata helpers and enforced by the token verifier. + +#### See + +[ProtectedResourceMetadataConfig](/references/js/type-aliases/ProtectedResourceMetadataConfig.md) diff --git a/docs/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/docs/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index e3d2754..0000000 --- a/docs/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# Type Alias: MCPAuthTokenVerificationErrorCode - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/docs/references/js/type-aliases/McpAuthInfo.md b/docs/references/js/type-aliases/McpAuthInfo.md new file mode 100644 index 0000000..2cbdcf6 --- /dev/null +++ b/docs/references/js/type-aliases/McpAuthInfo.md @@ -0,0 +1,47 @@ +--- +sidebar_label: McpAuthInfo +--- + +# Type Alias: McpAuthInfo + +```ts +type McpAuthInfo = AuthInfo & { + claims: JWTPayload; + issuer: string; + subject: string; +}; +``` + +The MCP SDK's `AuthInfo`, extended with the guarantees mcp-auth provides after successful JWT +verification: + +- `issuer`: the verified `iss` claim — always the configured trusted authorization server +- `subject`: the verified `sub` claim, identifying the end user or client (required, per + RFC 9068) +- `claims`: the full verified JWT payload for access to any custom claims + +## Type declaration + +### claims + +```ts +claims: JWTPayload; +``` + +The full verified JWT payload. + +### issuer + +```ts +issuer: string; +``` + +The issuer of the token (the `iss` claim). + +### subject + +```ts +subject: string; +``` + +The subject of the token (the `sub` claim), typically the user ID. diff --git a/docs/references/js/type-aliases/ProtectedResourceMetadata.md b/docs/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index 3910f56..0000000 --- a/docs/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# Type Alias: ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -Schema for OAuth 2.0 Protected Resource Metadata. diff --git a/docs/references/js/type-aliases/ProtectedResourceMetadataConfig.md b/docs/references/js/type-aliases/ProtectedResourceMetadataConfig.md new file mode 100644 index 0000000..f02325f --- /dev/null +++ b/docs/references/js/type-aliases/ProtectedResourceMetadataConfig.md @@ -0,0 +1,84 @@ +--- +sidebar_label: ProtectedResourceMetadataConfig +--- + +# Type Alias: ProtectedResourceMetadataConfig + +```ts +type ProtectedResourceMetadataConfig = { + authorizationServer: AuthServerConfig; + resource: string; + resourceName?: string; + scopesSupported?: string[]; + serviceDocumentationUrl?: string; +}; +``` + +The RFC 9728 Protected Resource Metadata declaration of this MCP server: its identity +(`resource`), the authorization server it trusts, and the optional advertised fields. + +Everything in this declaration is published through the SDK's metadata helpers (via +[MCPAuth.getAuthMetadataOptions](/references/js/classes/MCPAuth.md#getauthmetadataoptions)), and the token verifier enforces what is declared: +the `aud` claim of access tokens must match `resource`, and the `iss` claim must match the +configured authorization server — what is advertised is what is enforced. + +## Properties + +### authorizationServer + +```ts +authorizationServer: AuthServerConfig; +``` + +The authorization server trusted by this MCP server, published as the single entry of +`authorization_servers` in the Protected Resource Metadata document. Either a discovery +config (`{ issuer, type }`, metadata fetched lazily on first use) or a resolved config with +metadata — hardcoded or pre-fetched via [fetchServerConfig](/references/js/functions/fetchServerConfig.md). + +#### See + +[AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) for the two variants. + +*** + +### resource + +```ts +resource: string; +``` + +The resource identifier of this MCP server (RFC 8707), e.g. `https://api.example.com/mcp`. + +It is published as the `resource` value of the Protected Resource Metadata document, used +as the expected `aud` (audience) claim of access tokens, and used to build +[MCPAuth.resourceMetadataUrl](/references/js/classes/MCPAuth.md#resourcemetadataurl). + +*** + +### resourceName? + +```ts +optional resourceName: string; +``` + +A human-readable name for this MCP server, advertised as `resource_name`. + +*** + +### scopesSupported? + +```ts +optional scopesSupported: string[]; +``` + +The scopes this MCP server understands, advertised as `scopes_supported`. + +*** + +### serviceDocumentationUrl? + +```ts +optional serviceDocumentationUrl: string; +``` + +A documentation URL for this MCP server, advertised as `resource_documentation`. diff --git a/docs/references/js/type-aliases/ResolvedAuthServerConfig.md b/docs/references/js/type-aliases/ResolvedAuthServerConfig.md index bc0efcc..e4718d4 100644 --- a/docs/references/js/type-aliases/ResolvedAuthServerConfig.md +++ b/docs/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -6,42 +6,34 @@ sidebar_label: ResolvedAuthServerConfig ```ts type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; + metadata: AuthServerMetadata; type: AuthServerType; }; ``` Resolved configuration for the remote authorization server with metadata. -Use this when the metadata is already available, either hardcoded or fetched beforehand -via `fetchServerConfig()`. +Use this when the metadata is already available — either provided directly or fetched +beforehand via [fetchServerConfig](/references/js/functions/fetchServerConfig.md). The metadata is validated in the `MCPAuth` +constructor so misconfigurations fail fast. -## Properties {#properties} +## Properties -### metadata {#metadata} +### metadata ```ts -metadata: CamelCaseAuthorizationServerMetadata; +metadata: AuthServerMetadata; ``` -The metadata of the authorization server, which should conform to the MCP specification -(based on OAuth 2.0 Authorization Server Metadata). +The metadata of the authorization server in wire format (snake_case). -This metadata is typically fetched from the server's well-known endpoint (OAuth 2.0 -Authorization Server Metadata or OpenID Connect Discovery); it can also be provided -directly in the configuration if the server does not support such endpoints. +#### See -**Note:** The metadata should be in camelCase format as per preferred by the mcp-auth -library. - -#### See {#see} - - - [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) +[AuthServerMetadata](/references/js/type-aliases/AuthServerMetadata.md) for the type definition. *** -### type {#type} +### type ```ts type: AuthServerType; @@ -49,6 +41,6 @@ type: AuthServerType; The type of the authorization server. -#### See {#see} +#### See [AuthServerType](/references/js/type-aliases/AuthServerType.md) for the possible values. diff --git a/docs/references/js/type-aliases/ResourceServerModeConfig.md b/docs/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index a87ce1b..0000000 --- a/docs/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# Type Alias: ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -Configuration for the MCP server as resource server mode. - -## Properties {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -A single resource server configuration or an array of them. diff --git a/docs/references/js/type-aliases/ServerMetadataConfig.md b/docs/references/js/type-aliases/ServerMetadataConfig.md new file mode 100644 index 0000000..8469e5c --- /dev/null +++ b/docs/references/js/type-aliases/ServerMetadataConfig.md @@ -0,0 +1,49 @@ +--- +sidebar_label: ServerMetadataConfig +--- + +# Type Alias: ServerMetadataConfig + +```ts +type ServerMetadataConfig = { + transpileData?: (data: object) => + | Record + | Promise>; + type: AuthServerType; +}; +``` + +## Properties + +### transpileData()? + +```ts +optional transpileData: (data: object) => + | Record +| Promise>; +``` + +A function to transpile the fetched metadata into the expected format. This is useful if the +server metadata does not conform to the standard schema or if you want to customize the +transformation of the metadata. The function may be synchronous or return a promise. + +#### Parameters + +##### data + +`object` + +#### Returns + + \| `Record`\<`string`, `unknown`\> + \| `Promise`\<`Record`\<`string`, `unknown`\>\> + +*** + +### type + +```ts +type: AuthServerType; +``` + +The type of the remote authorization server. diff --git a/docs/references/js/type-aliases/ValidateIssuerFunction.md b/docs/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index b6f1d9f..0000000 --- a/docs/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# Type Alias: ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -Function type for validating the issuer of the access token. - -This function should throw an [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) with code 'invalid_issuer' if the issuer -is not valid. The issuer should be validated against: - -1. The authorization servers configured in MCP-Auth's auth server metadata -2. The authorization servers listed in the protected resource's metadata - -## Parameters {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## Returns {#returns} - -`void` - -## Throws {#throws} - -When the issuer is not recognized or invalid. diff --git a/docs/references/js/type-aliases/VerifyAccessTokenFunction.md b/docs/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index 2bb7325..0000000 --- a/docs/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# Type Alias: VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -Function type for verifying an access token. - -This function should throw an [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) if the token is invalid, -or return an AuthInfo object if the token is valid. - -For example, if you have a JWT verification function, it should at least check the token's -signature, validate its expiration, and extract the necessary claims to return an `AuthInfo` -object. - -**Note:** There's no need to verify the following fields in the token, as they will be checked -by the handler: - -- `iss` (issuer) -- `aud` (audience) -- `scope` (scopes) - -## Parameters {#parameters} - -### token {#token} - -`string` - -The access token string to verify. - -## Returns {#returns} - -`MaybePromise`\<`AuthInfo`\> - -A promise that resolves to an AuthInfo object or a synchronous value if the -token is valid. diff --git a/docs/references/js/type-aliases/VerifyAccessTokenMode.md b/docs/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index 479f65b..0000000 --- a/docs/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# Type Alias: VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -The built-in verification modes supported by `bearerAuth`. diff --git a/docs/references/js/variables/authorizationServerMetadataSchema.md b/docs/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index 64ec501..0000000 --- a/docs/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# Variable: authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -Zod schema for OAuth 2.0 Authorization Server Metadata as defined in RFC 8414. - -## See {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 diff --git a/docs/references/js/variables/bearerAuthErrorDescription.md b/docs/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index ed1a931..0000000 --- a/docs/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# Variable: bearerAuthErrorDescription - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index b8c34d5..0000000 --- a/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# Variable: camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -The camelCase version of the OAuth 2.0 Authorization Server Metadata Zod schema. - -## See {#see} - -[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) for the original schema and field information. diff --git a/docs/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/docs/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index 086f269..0000000 --- a/docs/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# Variable: camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -The camelCase version of the OAuth 2.0 Protected Resource Metadata Zod schema. - -## See {#see} - -[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) for the original schema and field information. diff --git a/docs/references/js/variables/defaultValues.md b/docs/references/js/variables/defaultValues.md deleted file mode 100644 index c29ea72..0000000 --- a/docs/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# Variable: defaultValues - -```ts -const defaultValues: Readonly>; -``` diff --git a/docs/references/js/variables/protectedResourceMetadataSchema.md b/docs/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index 4b3236d..0000000 --- a/docs/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# Variable: protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -Zod schema for OAuth 2.0 Protected Resource Metadata. diff --git a/docs/references/js/variables/tokenVerificationErrorDescription.md b/docs/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index 3d6e760..0000000 --- a/docs/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: tokenVerificationErrorDescription ---- - -# Variable: tokenVerificationErrorDescription - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` diff --git a/docs/references/js/variables/validateServerConfig.md b/docs/references/js/variables/validateServerConfig.md deleted file mode 100644 index e60de41..0000000 --- a/docs/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# Variable: validateServerConfig - -```ts -const validateServerConfig: ValidateServerConfig; -``` diff --git a/docs/snippets/_get-started-code.mdx b/docs/snippets/_get-started-code.mdx index 21e4315..ca4deee 100644 --- a/docs/snippets/_get-started-code.mdx +++ b/docs/snippets/_get-started-code.mdx @@ -1,39 +1,29 @@ ```ts -const server = new McpServer(/* ... */); -const resourceIdentifier = 'https://api.example.com'; - -const authServerConfig = await fetchServerConfig('', { type: 'oidc' }); - +// 1. Declare this MCP server and the authorization server it trusts const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read', 'write'], - }, + protectedResourceMetadata: { + resource: 'https://api.example.com/mcp', + authorizationServer: { issuer: 'https://auth.example.com/oidc', type: 'oidc' }, + scopesSupported: ['read', 'write'], }, }); -const app = express(); +// 2. Gate your MCP endpoint with the MCP SDK's `requireBearerAuth`: +// signature, issuer, audience, expiration, and scopes all enforced +const gate = requireBearerAuth(mcpAuth.getBearerAuthOptions({ requiredScopes: ['read'] })); -app.use(mcpAuth.protectedResourceMetadataRouter()); - -app.use( - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, - audience: resourceIdentifier, - requiredScopes: ['read', 'write'], - }) -); +// 3. Serve the OAuth discovery documents with the MCP SDK's metadata helpers +const metadata = oauthMetadataResponse(request, await mcpAuth.getAuthMetadataOptions()); +// 4. Read the verified identity in your tools server.registerTool( 'whoami', { description: 'Returns the current user info', - inputSchema: {}, }, - ({ authInfo }) => { - return authInfo.claims; + (context) => { + const { subject, claims } = getAuthInfo(context); + return { content: [{ type: 'text', text: JSON.stringify({ subject, claims }) }] }; } ); ``` diff --git a/docs/snippets/_scope-validation-warning.mdx b/docs/snippets/_scope-validation-warning.mdx index 2ef6084..241ba7a 100644 --- a/docs/snippets/_scope-validation-warning.mdx +++ b/docs/snippets/_scope-validation-warning.mdx @@ -1,5 +1,5 @@ :::warning Always Validate Scopes -In OAuth 2.0, **scopes are the primary mechanism for permission control**. A valid token with the correct `audience` does NOT guarantee the user has permission to perform an action — authorization servers may issue tokens with an empty or limited scope. +In OAuth 2.0, **scopes are the primary mechanism for permission control**. A valid token with the correct `audience` does NOT guarantee the user has permission to perform an action: authorization servers may issue tokens with an empty or limited scope. Always use `requiredScopes` to enforce that the token contains the necessary permissions for each operation. Never assume a valid token implies full access. ::: diff --git a/docs/tutorials/todo-manager/README.mdx b/docs/tutorials/todo-manager/README.mdx index 79a40ab..6018c41 100644 --- a/docs/tutorials/todo-manager/README.mdx +++ b/docs/tutorials/todo-manager/README.mdx @@ -1,5 +1,5 @@ --- -sidebar_position: 2 +sidebar_position: 3 sidebar_label: 'Build a todo manager' --- @@ -11,10 +11,6 @@ import { NpmLikeInstallation } from '@site/src/components/NpmLikeInstallation'; This tutorial uses [Logto](https://logto.io) as the example authorization server. If you're using a different provider, check out our [Provider Guides](/docs/provider-guides) for configuration steps. ::: -:::tip Python SDK available -MCP Auth is also available for Python! Check out the [Python SDK repository](https://github.com/mcp-auth/python) for installation and usage. -::: - In this tutorial, we will build a todo manager MCP server with user authentication and authorization. Following the latest MCP specification, our MCP server will act as an OAuth 2.0 **Resource Server** that validates access tokens and enforces scope-based permissions. After completing this tutorial, you will have: @@ -69,33 +65,9 @@ sequenceDiagram To implement [role-based access control (RBAC)](https://auth.wiki/rbac) in your MCP server, your authorization server needs to support issuing access tokens with scopes. Scopes represent the permissions that a user has been granted. -[Logto](https://logto.io) provides RBAC support through its API resources (conforming [RFC 8707: Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) and roles features. Here's a quick overview: - -1. Sign in to [Logto Console](https://cloud.logto.io) (or your self-hosted Logto Console) - -2. Create API resource and scopes: - - - Go to "API Resources" - - Create a new API resource named "Todo Manager" - - Add the following scopes: - - `create:todos`: "Create new todo items" - - `read:todos`: "Read all todo items" - - `delete:todos`: "Delete any todo item" - -3. Create roles (recommended for easier management): - - - Go to "Roles" - - Create an "Admin" role and assign all scopes (`create:todos`, `read:todos`, `delete:todos`) - - Create a "User" role and assign only the `create:todos` scope - -4. Assign permissions: - - Go to "Users" - - Select a user - - You can either: - - Assign roles in the "Roles" tab (recommended) - - Or directly assign scopes in the "Permissions" tab +[Logto](https://logto.io) provides RBAC support through its API resources (conforming [RFC 8707: Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707)) and roles features: you define scopes on an API resource, group them into roles, and assign roles to users. The granted scopes end up in the JWT access token's `scope` claim as a space-separated string. -The scopes will be included in the JWT access token's `scope` claim as a space-separated string. +We'll walk through the actual Logto configuration in [Configure authorization in your provider](#configure-authorization-in-your-provider) below. > 📖 See [Logto Provider Guide](/docs/provider-guides/logto) for detailed setup instructions. @@ -247,7 +219,7 @@ After configuring your authorization server, users will receive access tokens co ## Set up the MCP server \{#set-up-the-mcp-server} -We will use the [MCP official SDKs](https://github.com/modelcontextprotocol) to create our todo manager MCP server. +We will use the [MCP official SDK](https://github.com/modelcontextprotocol) v2 to create our todo manager MCP server. ### Create a new project \{#create-a-new-project} @@ -263,17 +235,21 @@ npm pkg set scripts.start="node --experimental-strip-types todo-manager.ts" ``` :::note -We're using TypeScript in our examples as Node.js v22.6.0+ supports running TypeScript natively using the `--experimental-strip-types` flag. If you're using JavaScript, the code will be similar - just ensure you're using Node.js v22.6.0 or later. See Node.js docs for details. +We're using TypeScript in our examples as Node.js v22.6.0+ supports running TypeScript natively using the `--experimental-strip-types` flag. If you're using JavaScript, the code will be similar - just ensure you're using Node.js v20 or later (required by the MCP SDK v2 and MCP Auth, which are ESM only). See Node.js docs for details. ::: ### Install the MCP SDK and dependencies \{#install-the-mcp-sdk-and-dependencies} ```bash -npm install @modelcontextprotocol/sdk express zod +npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node express zod ``` Or any other package manager you prefer, such as `pnpm` or `yarn`. +- `@modelcontextprotocol/server` is the core MCP SDK, which speaks web-standard `Request` / `Response`. +- `@modelcontextprotocol/express` and `@modelcontextprotocol/node` adapt it to Express on Node.js. +- `zod` defines the input schemas for the tools. + ### Create the MCP server \{#create-the-mcp-server} Create a file named `todo-manager.ts` and add the following code: @@ -281,13 +257,13 @@ Create a file named `todo-manager.ts` and add the following code: ```ts // todo-manager.ts +import { createMcpExpressApp } from '@modelcontextprotocol/express'; +import { toNodeHandler } from '@modelcontextprotocol/node'; +import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'; import { z } from 'zod'; -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import express, { type Request, type Response } from 'express'; // Factory function to create an MCP server instance -// In stateless mode, each request needs its own server instance +// Each request gets its own server instance, keeping requests isolated const createMcpServer = () => { const mcpServer = new McpServer({ name: 'Todo Manager', @@ -298,7 +274,7 @@ const createMcpServer = () => { 'create-todo', { description: 'Create a new todo', - inputSchema: { content: z.string() }, + inputSchema: z.object({ content: z.string() }), }, async ({ content }) => { return { @@ -311,7 +287,6 @@ const createMcpServer = () => { 'get-todos', { description: 'List all todos', - inputSchema: {}, }, async () => { return { @@ -324,7 +299,7 @@ const createMcpServer = () => { 'delete-todo', { description: 'Delete a todo by id', - inputSchema: { id: z.string() }, + inputSchema: z.object({ id: z.string() }), }, async ({ id }) => { return { @@ -336,41 +311,19 @@ const createMcpServer = () => { return mcpServer; }; -// Below is the boilerplate code from MCP SDK documentation const PORT = 3001; -const app = express(); - -app.post('/', async (request: Request, response: Response) => { - // In stateless mode, create a new instance of transport and server for each request - // to ensure complete isolation. A single instance would cause request ID collisions - // when multiple clients connect concurrently. - const mcpServer = createMcpServer(); - - try { - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: undefined, - }); - await mcpServer.connect(transport); - await transport.handleRequest(request, response, request.body); - response.on('close', () => { - console.log('Request closed'); - void transport.close(); - void mcpServer.close(); - }); - } catch (error) { - console.error('Error handling MCP request:', error); - if (!response.headersSent) { - response.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32_603, - message: 'Internal server error', - }, - id: null, - }); - } - } -}); + +// The MCP handler speaks web-standard Request / Response; `toNodeHandler` adapts it to Express +const mcpNodeHandler = toNodeHandler(createMcpHandler(createMcpServer)); + +const app = createMcpExpressApp(); + +app.all( + '/', + // `createMcpExpressApp` applies `express.json()`, which drains the request stream, so the + // parsed body is passed along explicitly + async (request, response) => mcpNodeHandler(request, response, request.body) +); app.listen(PORT); ``` @@ -383,30 +336,7 @@ npm start ## Integrate with your authorization server \{#integrate-with-your-authorization-server} -To complete this section, there are several considerations to take into account: - -
-**The issuer URL of your authorization server** - -This is usually the base URL of your authorization server, such as `https://auth.example.com`. Some providers may have a path like `https://example.logto.app/oidc`, so make sure to check your provider's documentation. - -
- -
-**How to retrieve the authorization server metadata** - -- If your authorization server conforms to the [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) or [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html), you can use the MCP Auth built-in utilities to fetch the metadata automatically. -- If your authorization server does not conform to these standards, you will need to manually specify the metadata URL or endpoints in the MCP server configuration. Check your provider's documentation for the specific endpoints. - -
- -
-**How to register the MCP client in your authorization server** - -- If your authorization server supports [Dynamic Client Registration](https://datatracker.ietf.org/doc/html/rfc7591), you can skip this step as the MCP client will automatically register itself. -- If your authorization server does not support Dynamic Client Registration, you will need to manually register the MCP client in your authorization server. - -
+The basics (issuer URL, metadata discovery, and client registration) work the same as in the [whoami tutorial](/docs/tutorials/whoami#integrate-with-your-authorization-server). What's new in this tutorial is scopes:
**Understand token request parameters** @@ -458,6 +388,10 @@ When requesting access tokens from different authorization servers, you'll encou - Consider using resource indicators when available for better access control ::: +:::note +MCP Auth validates the access token's audience (`aud`) against your MCP server's resource identifier, as required by the MCP specification. Make sure your authorization server issues JWT access tokens bound to the resource; with Logto, the API resource we created earlier takes care of this. +::: +
While each provider may have its own specific requirements, the following steps will guide you through the process of integrating VS Code and the MCP server. @@ -470,7 +404,7 @@ Since VS Code is not controlled by you (the MCP server operator), it should be r If you're building your own MCP client, check the [Logto Provider Guide](/docs/provider-guides/logto#register-mcp-client) for first-party app registration. ::: -Since Logto does not support Dynamic Client Registration yet, you will need to manually register your MCP client (VS Code) as a third-party app in your Logto tenant: +This tutorial registers VS Code manually as a third-party app, which gives it the per-client permissions we need. (Logto's [dynamic apps](https://docs.logto.io/integrate-logto/third-party-applications/dynamic-apps) can onboard MCP clients without pre-registration; see the [Logto provider guide](/docs/provider-guides/logto#register-mcp-client).) 1. Sign in to [Logto Console](https://cloud.logto.io) (or your self-hosted Logto Console). 2. Navigate to **Applications > Third-party apps** and click on "Create application". @@ -493,105 +427,88 @@ First, install the MCP Auth SDK in your MCP server project. -Now we need to initialize MCP Auth in your MCP server. With the protected resource mode, you need to configure your resource metadata including the authorization servers. - -There are two ways to configure authorization servers: +Now, declare your MCP server as a protected resource: its resource identifier, the authorization server it trusts, and the scopes it understands. -- **Pre-fetched (Recommended)**: Use `fetchServerConfig()` to fetch the metadata before initializing MCPAuth. This ensures the configuration is validated at startup. -- **On-demand discovery**: Only provide `issuer` and `type` - metadata will be fetched on-demand when first needed. This is useful for edge runtimes (like Cloudflare Workers) where top-level async fetch is not allowed. +Get your authorization server's issuer URL first. In Logto, you can find the issuer URL on your application details page within Logto Console, under the "Endpoints & Credentials / Issuer endpoint" section. It should look like `https://my-project.logto.app/oidc`. -#### Configure protected resource metadata \{#configure-protected-resource-metadata} - -First, get your authorization server's issuer URL. In Logto, you can find the issuer URL on your application details page within Logto Console, under the "Endpoints & Credentials / Issuer endpoint" section. It should look like `https://my-project.logto.app/oidc`. - -Now, configure the Protected Resource Metadata when building the MCP Auth instance: - -```js +```ts // todo-manager.ts -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const issuerUrl = ''; // Replace with your authorization server's issuer URL -// Define the resource identifier for this MCP server -const resourceId = 'http://localhost:3001/'; - -// Pre-fetch authorization server configuration (recommended) -const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); - -// Configure MCP Auth with protected resource metadata const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: resourceId, - authorizationServers: [authServerConfig], - // Scopes this MCP server understands - scopesSupported: ['create:todos', 'read:todos', 'delete:todos'], - }, + protectedResourceMetadata: { + // The resource identifier for this MCP server; must match the resource indicator + // registered in your provider + resource: 'http://localhost:3001/', + // The authorization server trusted by this MCP server + authorizationServer: { issuer: issuerUrl, type: 'oidc' }, + // Scopes this MCP server understands + scopesSupported: ['create:todos', 'read:todos', 'delete:todos'], }, }); ``` -### Update MCP server \{#update-mcp-server} - -We are almost done! It's time to update the MCP server to apply the MCP Auth route and middleware function, then implement the permission-based access control for the todo manager tools based on the user's scopes. - -Now, apply protected resource metadata routes so that MCP clients can retrieve expected resource metadata from the MCP server. +With this discovery config, the authorization server metadata is fetched on-demand when first needed and cached afterwards, which also works on edge runtimes (like Cloudflare Workers) where top-level async fetch is not allowed. If you prefer to fetch and validate the metadata at startup, use `fetchServerConfig`: ```ts -// todo-manager.ts +import { fetchServerConfig } from 'mcp-auth'; -// Set up Protected Resource Metadata routes -// This exposes metadata about this resource server for OAuth clients -app.use(mcpAuth.protectedResourceMetadataRouter()); +const authServerConfig = await fetchServerConfig(issuerUrl, { type: 'oidc' }); ``` -Next, we will apply the MCP Auth middleware to the MCP server. This middleware will handle authentication and authorization for incoming requests, ensuring that only authorized users can access the todo manager tools. +> 📖 See [Configure MCP Auth](/docs/configure-server/mcp-auth) for all configuration options. + +### Update MCP server \{#update-mcp-server} + +We are almost done! It's time to update the MCP server to serve the OAuth discovery documents and apply the MCP SDK's Bearer auth middleware, then implement the permission-based access control for the todo manager tools based on the user's scopes. + +First, serve the OAuth discovery documents and protect the MCP endpoint: ```ts // todo-manager.ts -app.use(mcpAuth.protectedResourceMetadataRouter()); +import { mcpAuthMetadataRouter, requireBearerAuth } from '@modelcontextprotocol/express'; + +// Serve the OAuth discovery documents so MCP clients can find your authorization server +app.use(mcpAuthMetadataRouter(await mcpAuth.getAuthMetadataOptions())); -// Apply the MCP Auth middleware -app.use( - mcpAuth.bearerAuth('jwt', { - resource: resourceId, - audience: resourceId, - }) +// Replace the previous MCP route: require a valid Bearer token before handling MCP requests. +// Signature, issuer, audience, and expiration are all enforced by the middleware, and the +// verified auth info flows to the handler via `req.auth`. +app.all('/', requireBearerAuth(mcpAuth.getBearerAuthOptions()), async (request, response) => + mcpNodeHandler(request, response, request.body) ); ``` -At this point, we can update the todo manager tools to leverage the MCP Auth middleware for authentication and authorization. +We don't pass endpoint-level `requiredScopes` here since each tool has different scope requirements. Instead, we'll enforce scopes per tool with `getAuthInfo`. + +At this point, we can update the todo manager tools to leverage the verified auth info for authorization. Let's update the implementation of the tools. -```js +```ts // todo-manager.ts // other imports... -import assert from 'node:assert'; -import { fetchServerConfig, MCPAuth, MCPAuthBearerAuthError } from 'mcp-auth'; -import { type AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js'; +import { type CallToolResult } from '@modelcontextprotocol/server'; +import { getAuthInfo } from 'mcp-auth'; // Will mention in the next section import { TodoService } from './todo-service.js'; -const assertUserId = (authInfo?: AuthInfo) => { - const { subject } = authInfo ?? {}; - assert(subject, 'Invalid auth info'); - return subject; -}; - -const hasRequiredScopes = (userScopes: string[], requiredScopes: string[]): boolean => { - return requiredScopes.every((scope) => userScopes.includes(scope)); -}; +const errorResult = (message: string): CallToolResult => ({ + content: [{ type: 'text', text: JSON.stringify({ error: message }) }], + isError: true, +}); // TodoService is a singleton since we need to share state across requests const todoService = new TodoService(); // Factory function to create an MCP server instance -// In stateless mode, each request needs its own server instance +// Each request gets its own server instance, keeping requests isolated const createMcpServer = () => { const mcpServer = new McpServer({ name: 'Todo Manager', @@ -602,17 +519,14 @@ const createMcpServer = () => { 'create-todo', { description: 'Create a new todo', - inputSchema: { content: z.string() }, + inputSchema: z.object({ content: z.string() }), }, - ({ content }, { authInfo }) => { - const userId = assertUserId(authInfo); - + ({ content }, context) => { /** - * Only users with 'create:todos' scope can create todos + * Only users with 'create:todos' scope can create todos; `getAuthInfo` throws otherwise + * and the MCP SDK surfaces the error to the model as a tool error result. */ - if (!hasRequiredScopes(authInfo?.scopes ?? [], ['create:todos'])) { - throw new MCPAuthBearerAuthError('missing_required_scopes'); - } + const { subject: userId } = getAuthInfo(context, { requiredScopes: ['create:todos'] }); const createdTodo = todoService.createTodo({ content, ownerId: userId }); @@ -626,18 +540,15 @@ const createMcpServer = () => { 'get-todos', { description: 'List all todos', - inputSchema: {}, }, - (_params, { authInfo }) => { - const userId = assertUserId(authInfo); + (context) => { + const { subject: userId, scopes } = getAuthInfo(context); /** * If user has 'read:todos' scope, they can access all todos (todoOwnerId = undefined) * If user doesn't have 'read:todos' scope, they can only access their own todos (todoOwnerId = userId) */ - const todoOwnerId = hasRequiredScopes(authInfo?.scopes ?? [], ['read:todos']) - ? undefined - : userId; + const todoOwnerId = scopes.includes('read:todos') ? undefined : userId; const todos = todoService.getAllTodos(todoOwnerId); @@ -651,32 +562,24 @@ const createMcpServer = () => { 'delete-todo', { description: 'Delete a todo by id', - inputSchema: { id: z.string() }, + inputSchema: z.object({ id: z.string() }), }, - ({ id }, { authInfo }) => { - const userId = assertUserId(authInfo); + ({ id }, context) => { + const { subject: userId, scopes } = getAuthInfo(context); const todo = todoService.getTodoById(id); if (!todo) { - return { - content: [{ type: 'text', text: JSON.stringify({ error: 'Failed to delete todo' }) }], - }; + return errorResult('Failed to delete todo'); } /** - * Users can only delete their own todos - * Users with 'delete:todos' scope can delete any todo + * Users can delete their own todos; the 'delete:todos' scope allows deleting any todo */ - if (todo.ownerId !== userId && !hasRequiredScopes(authInfo?.scopes ?? [], ['delete:todos'])) { - return { - content: [ - { - type: 'text', - text: JSON.stringify({ error: 'Failed to delete todo' }), - }, - ], - }; + const canDelete = todo.ownerId === userId || scopes.includes('delete:todos'); + + if (!canDelete) { + return errorResult('Failed to delete todo'); } const deletedTodo = todoService.deleteTodo(id); @@ -739,7 +642,6 @@ export class TodoService { createdAt: new Date().toISOString(), }; - // eslint-disable-next-line @silverhand/fp/no-mutating-methods this.todos.push(todo); return todo; } @@ -751,7 +653,6 @@ export class TodoService { return undefined; } - // eslint-disable-next-line @silverhand/fp/no-mutating-methods const [deleted] = this.todos.splice(index, 1); return deleted; } @@ -765,7 +666,7 @@ export class TodoService { Congratulations! We've successfully implemented a complete MCP server with authentication and authorization! :::info -Check out the [MCP Auth Node.js SDK repository](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) for the complete code of the MCP server (OIDC version). +Check out the [sample servers](https://github.com/mcp-auth/js/tree/master/packages/sample-servers) in the MCP Auth Node.js SDK repository for complete runnable projects, including a `todo-manager` sample built as a Cloudflare Worker with Hono on the same MCP Auth API. ::: ## Checkpoint: Run the `todo-manager` tools \{#checkpoint-run-the-todo-manager-tools} @@ -802,7 +703,7 @@ You can test these different permission levels by: This demonstrates how role-based access control (RBAC) works in practice, where different users have different levels of access to the system's functionality. :::info -Check out the [MCP Auth Node.js SDK repository](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) for the complete code of the MCP server (OIDC version). +Check out the [sample servers](https://github.com/mcp-auth/js/tree/master/packages/sample-servers) in the MCP Auth Node.js SDK repository for complete runnable projects. ::: ## Closing notes \{#closing-notes} diff --git a/docs/tutorials/whoami/README.mdx b/docs/tutorials/whoami/README.mdx index 3e8ac64..27df599 100644 --- a/docs/tutorials/whoami/README.mdx +++ b/docs/tutorials/whoami/README.mdx @@ -1,5 +1,5 @@ --- -sidebar_position: 3 +sidebar_position: 2 sidebar_label: 'Who am I?' --- @@ -9,22 +9,18 @@ sidebar_label: 'Who am I?' This tutorial uses [Logto](https://logto.io) as the example authorization server. If you're using a different provider, check out our [Provider Guides](/docs/provider-guides) for configuration steps. ::: -:::tip Python SDK available -MCP Auth is also available for Python! Check out the [Python SDK repository](https://github.com/mcp-auth/python) for installation and usage. -::: - -This tutorial will guide you through the process of setting up MCP Auth to authenticate users and retrieve their identity information from the authorization server. +This tutorial will guide you through the process of setting up MCP Auth to authenticate users and return their verified identity from the access token. After completing this tutorial, you will have: - ✅ A basic understanding of how to use MCP Auth to authenticate users. -- ✅ A MCP server that offers a tool to retrieve user identity information. +- ✅ A MCP server that offers a tool to retrieve the current user's identity. ## Overview \{#overview} The tutorial will involve the following components: -- **MCP server**: A simple MCP server that uses MCP official SDKs to handle requests. +- **MCP server**: A simple MCP server that uses the MCP official SDK to handle requests, protected by MCP Auth. - **VS Code**: A code editor with built-in MCP support. It also acts as an OAuth / OIDC client to initiate the authorization flow and retrieve access tokens. - **Authorization server**: An OAuth 2.1 or OpenID Connect provider that manages user identities and issues access tokens. @@ -38,28 +34,29 @@ sequenceDiagram Client->>Server: Request tool `whoami` Server->>Client: Return 401 Unauthorized + Client->>Server: Fetch protected resource metadata + Server->>Client: Return metadata with authorization server info Client->>Auth: Initiate authorization flow Auth->>Auth: Complete authorization flow Auth->>Client: Redirect back with authorization code Client->>Auth: Exchange code for access token - Auth->>Client: Return access token + Auth->>Client: Return access token (JWT) Client->>Server: Request `whoami` with access token - Server->>Auth: Fetch user identity with access token - Auth->>Server: Return user identity - Server->>Client: Return user identity + Server->>Server: Verify access token against the
authorization server's JWKS + Server->>Client: Return the verified identity claims ``` ## Understand your authorization server \{#understand-your-authorization-server} -### Retrieving user identity information \{#retrieving-user-identity-information} +### JWT access tokens bound to your MCP server \{#jwt-access-tokens-bound-to-your-mcp-server} -To complete this tutorial, your authorization server should offer an API to retrieve user identity information. +MCP Auth verifies JWT access tokens locally against your authorization server's JWKS, with no extra network call per request. The verified token claims (such as `sub`, the user's ID) are what the `whoami` tool will return. -[Logto](https://logto.io) is an OpenID Connect provider that supports the standard [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) to retrieve user identity information. +The [latest MCP specification](https://modelcontextprotocol.io/specification/latest/basic/authorization) requires access tokens to be bound to the resource they are issued for ([RFC 8707](https://datatracker.ietf.org/doc/html/rfc8707)), and MCP Auth enforces it: the token's `aud` claim must match your MCP server's resource identifier. This means your authorization server should issue JWT access tokens with the correct audience when the MCP client requests them. -To fetch an access token that can be used to access the userinfo endpoint, at least two scopes are required: `openid` and `profile`. You can continue reading as we'll cover the scope configuration later. +[Logto](https://logto.io) supports this through its API resources feature: create an API resource whose indicator matches your MCP server's URL, and Logto will issue audience-bound JWT access tokens for it. We'll cover the configuration later in this tutorial. -> 📖 See [Generic OAuth 2.0 / OIDC Provider Guide](/docs/provider-guides/generic#retrieving-user-identity) for details on user identity retrieval with other providers. +> 📖 See [Generic OAuth 2.0 / OIDC Provider Guide](/docs/provider-guides/generic#token-request-parameters) for how other providers handle resource and audience parameters. ### Dynamic Client Registration \{#dynamic-client-registration} @@ -67,7 +64,7 @@ Dynamic Client Registration is not required for this tutorial, but it can be use ## Set up the MCP server \{#set-up-the-mcp-server} -We will use the [MCP official SDKs](https://github.com/modelcontextprotocol) to create a MCP server with a `whoami` tool that retrieves user identity information from the authorization server. +We will use the [MCP official SDK](https://github.com/modelcontextprotocol) v2 to create a MCP server with a `whoami` tool that returns the current user's identity. ### Create a new project \{#create-a-new-project} @@ -82,29 +79,34 @@ npm pkg set main="whoami.js" npm pkg set scripts.start="node whoami.js" ``` +:::note +The MCP SDK v2 and MCP Auth are ESM only and require Node.js >= 20. +::: + ### Install the MCP SDK and dependencies \{#install-the-mcp-sdk-and-dependencies} ```bash -npm install @modelcontextprotocol/sdk express +npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node express ``` Or any other package manager you prefer, such as `pnpm` or `yarn`. +- `@modelcontextprotocol/server` is the core MCP SDK, which speaks web-standard `Request` / `Response`. +- `@modelcontextprotocol/express` and `@modelcontextprotocol/node` adapt it to Express on Node.js. + ### Create the MCP server \{#create-the-mcp-server} First, let's create an MCP server that implements a `whoami` tool. -You can also use `pnpm` or `yarn` if you prefer. - Create a file named `whoami.js` and add the following code: ```js -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; -import express from 'express'; +import { createMcpExpressApp } from '@modelcontextprotocol/express'; +import { toNodeHandler } from '@modelcontextprotocol/node'; +import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'; // Factory function to create an MCP server instance -// In stateless mode, each request needs its own server instance +// Each request gets its own server instance, keeping requests isolated const createMcpServer = () => { const mcpServer = new McpServer({ name: 'WhoAmI', @@ -116,7 +118,6 @@ const createMcpServer = () => { 'whoami', { description: 'Get the current user information', - inputSchema: {}, }, () => { return { @@ -129,21 +130,18 @@ const createMcpServer = () => { }; const PORT = 3001; -const app = express(); - -app.post('/', async (request, response) => { - // In stateless mode, create a new instance of transport and server for each request - // to ensure complete isolation. A single instance would cause request ID collisions - // when multiple clients connect concurrently. - const mcpServer = createMcpServer(); - const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); - await mcpServer.connect(transport); - await transport.handleRequest(request, response, request.body); - response.on('close', () => { - transport.close(); - mcpServer.close(); - }); -}); + +// The MCP handler speaks web-standard Request / Response; `toNodeHandler` adapts it to Express +const mcpNodeHandler = toNodeHandler(createMcpHandler(createMcpServer)); + +const app = createMcpExpressApp(); + +app.all( + '/', + // `createMcpExpressApp` applies `express.json()`, which drains the request stream, so the + // parsed body is passed along explicitly + async (request, response) => mcpNodeHandler(request, response, request.body) +); app.listen(PORT); ``` @@ -168,7 +166,7 @@ This is usually the base URL of your authorization server, such as `https://auth
**How to retrieve the authorization server metadata** -- If your authorization server conforms to the [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) or [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html), you can use the MCP Auth built-in utilities to fetch the metadata automatically. +- If your authorization server conforms to the [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) or [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html), MCP Auth fetches the metadata automatically from the issuer URL. - If your authorization server does not conform to these standards, you will need to manually specify the metadata URL or endpoints in the MCP server configuration. Check your provider's documentation for the specific endpoints.
@@ -182,11 +180,13 @@ This is usually the base URL of your authorization server, such as `https://auth
-**How to retrieve user identity information and how to configure the authorization request parameters** +**How to make your authorization server issue JWT access tokens for your MCP server** + +MCP Auth validates the access token's audience (`aud`) against your MCP server's resource identifier, so the authorization server must issue JWT access tokens bound to that resource. Most providers do this when the client includes a resource or audience parameter in the authorization request. VS Code sends the resource parameter automatically based on your MCP server's protected resource metadata. -For OpenID Connect providers like Logto: you need to request at least the `openid` and `profile` scopes when initiating the authorization flow. This will ensure that the access token returned by the authorization server contains the necessary scopes to access the [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) to retrieve user identity information. +For Logto: create an API resource whose indicator matches your MCP server's URL. We'll walk through this below. -> 📖 See [Generic OAuth 2.0 / OIDC Provider Guide](/docs/provider-guides/generic#retrieving-user-identity) for details on other providers. +> 📖 See [Generic OAuth 2.0 / OIDC Provider Guide](/docs/provider-guides/generic#token-request-parameters) for details on other providers.
@@ -194,9 +194,7 @@ While each provider may have its own specific requirements, the following steps ### Register VS Code as a client \{#register-vs-code-as-a-client} -Integrating with [Logto](https://logto.io) is straightforward as it's an OpenID Connect provider that supports the standard [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) to retrieve user identity information. - -Since Logto does not support Dynamic Client Registration yet, you will need to manually register VS Code as a client in your Logto tenant: +This tutorial registers VS Code manually in your Logto tenant. (Logto can also onboard MCP clients without pre-registration through [dynamic apps](https://docs.logto.io/integrate-logto/third-party-applications/dynamic-apps); see the [Logto provider guide](/docs/provider-guides/logto#register-mcp-client).) 1. Sign in to [Logto Console](https://cloud.logto.io) (or your self-hosted Logto Console). 2. Navigate to the "Applications" tab, click on "Create application". In the bottom of the page, click on "Create app without framework". @@ -212,105 +210,85 @@ Since Logto does not support Dynamic Client Registration yet, you will need to m > 📖 See [Logto Provider Guide](/docs/provider-guides/logto#register-mcp-client) for more details on registering MCP clients. -### Set up MCP auth \{#set-up-mcp-auth} +### Create an API resource for the MCP server \{#create-an-api-resource-for-the-mcp-server} -In your MCP server project, you need to install the MCP Auth SDK and configure it to use your authorization server metadata. +To make Logto issue JWT access tokens bound to your MCP server, create an API resource whose indicator matches the MCP server's URL: + +1. In Logto Console, go to "API Resources" and click on "Create API resource". +2. Fill in the details, then click on "Create API resource": + - **API name**: Enter a name, e.g., "Who am I". + - **API identifier**: Enter `http://localhost:3001/`. It must match the resource identifier we'll configure in the MCP server. + +:::note[Trailing slash in resource indicator] +Always include a trailing slash (`/`) in the resource indicator. Due to a current bug in the MCP official SDK, clients using the SDK will automatically append a trailing slash to resource identifiers when initiating auth requests. If your resource indicator doesn't include the trailing slash, resource validation will fail for those clients. (VS Code is not affected by this bug.) +::: + +### Set up MCP auth \{#set-up-mcp-auth} -First, install the `mcp-auth` package: +In your MCP server project, install the MCP Auth SDK: ```bash npm install mcp-auth ``` -MCP Auth requires the authorization server metadata to be able to initialize. The issuer URL can be found in your application details page in Logto Console, in the "Endpoints & Credentials / Issuer endpoint" section. It should look like `https://my-project.logto.app/oidc`. +Now, declare your MCP server as a protected resource: its resource identifier and the authorization server it trusts. The issuer URL can be found in your application details page in Logto Console, in the "Endpoints & Credentials / Issuer endpoint" section. It should look like `https://my-project.logto.app/oidc`. Update the `whoami.js` to include the MCP Auth configuration: ```js -import { fetchServerConfig, MCPAuth } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const authIssuer = ''; // Replace with your issuer endpoint -const authServerConfig = await fetchServerConfig(authIssuer, { type: 'oidc' }); const mcpAuth = new MCPAuth({ - server: authServerConfig, + protectedResourceMetadata: { + // The resource identifier; must match the API resource indicator registered in your provider + resource: 'http://localhost:3001/', + // The authorization server trusted by this MCP server + authorizationServer: { issuer: authIssuer, type: 'oidc' }, + }, }); ``` +The authorization server metadata is fetched lazily when first needed and cached afterwards. The `MCPAuth` instance verifies JWT access tokens against the server's JWKS; signature, issuer, audience, and expiration are all enforced. + :::note -If your provider does not support OpenID Connect Discovery, you can manually specify the metadata URL or endpoints. Check [Other ways to initialize MCP Auth](/docs/configure-server/mcp-auth#other-ways) for more details. +If your provider does not support OpenID Connect Discovery, you can manually specify the metadata URL or endpoints. Check [Other ways to configure MCP Auth](/docs/configure-server/mcp-auth#other-ways) for more details. ::: -Now, we need to create a custom access token verifier that will fetch the user identity information from the authorization server using the access token provided by the MCP client. - -```js -import { MCPAuthTokenVerificationError } from 'mcp-auth'; - -/** - * Verifies the provided Bearer token by fetching user information from the authorization server. - * If the token is valid, it returns an `AuthInfo` object containing the user's information. - */ -const verifyToken = async (token) => { - const { issuer, userinfoEndpoint } = authServerConfig.metadata; - - if (!userinfoEndpoint) { - throw new Error('Userinfo endpoint is not configured in the server metadata'); - } - - const response = await fetch(userinfoEndpoint, { - headers: { Authorization: `Bearer ${token}` }, - }); - - if (!response.ok) { - throw new MCPAuthTokenVerificationError('token_verification_failed', response); - } - - const userInfo = await response.json(); - - if (typeof userInfo !== 'object' || userInfo === null || !('sub' in userInfo)) { - throw new MCPAuthTokenVerificationError('invalid_token', response); - } - - return { - token, - issuer, - subject: String(userInfo.sub), // 'sub' is a standard claim for the subject (user's ID) - clientId: '', // Client ID is not used in this example, but can be set if needed - scopes: [], - claims: userInfo, - }; -}; -``` - ### Update MCP server \{#update-mcp-server} -We are almost done! It's time to update the MCP server to apply the MCP Auth route and middleware function, then make the `whoami` tool return the actual user identity information. +We are almost done! It's time to update the MCP server to serve the OAuth discovery documents, protect the MCP endpoint with the SDK's Bearer auth middleware, and make the `whoami` tool return the actual user identity. ```js -// In the factory function, update the `whoami` tool to return the actual user identity +import { mcpAuthMetadataRouter, requireBearerAuth } from '@modelcontextprotocol/express'; +import { getAuthInfo } from 'mcp-auth'; + +// In the factory function, update the `whoami` tool to return the verified identity claims mcpServer.registerTool( 'whoami', { description: 'Get the current user information', - inputSchema: {}, }, - (_params, { authInfo }) => { + (context) => { + const { claims } = getAuthInfo(context); return { - content: [ - { - type: 'text', - text: JSON.stringify(authInfo?.claims ?? { error: 'Not authenticated' }), - }, - ], + content: [{ type: 'text', text: JSON.stringify(claims) }], }; } ); // ... -// Apply MCP Auth middleware before the MCP endpoint -app.use(mcpAuth.delegatedRouter()); -app.use(mcpAuth.bearerAuth(verifyToken)); +// Serve the OAuth discovery documents (`/.well-known/...`) so VS Code can find your +// authorization server +app.use(mcpAuthMetadataRouter(await mcpAuth.getAuthMetadataOptions())); + +// Replace the previous MCP route: require a valid Bearer token before handling MCP requests. +// The verified auth info flows to the handler via `req.auth`. +app.all('/', requireBearerAuth(mcpAuth.getBearerAuthOptions()), async (request, response) => + mcpNodeHandler(request, response, request.body) +); ``` ## Checkpoint: Run the `whoami` tool with authentication \{#checkpoint-run-the-whoami-tool-with-authentication} @@ -325,10 +303,10 @@ Restart your MCP server and connect VS Code to it. Here's how to connect with au 6. Since we don't have an **App Secret** (it's a public client), just press Enter to skip. 7. Complete the sign-in flow in your browser. -Once you sign in, you can use the `whoami` tool in VS Code. This time, you should see the user identity information returned by the authorization server. +Once you sign in, you can use the `whoami` tool in VS Code. This time, you should see the verified identity claims from the access token, including `sub` (the user's ID), `iss` (the issuer), and `aud` (your MCP server's resource identifier). :::info -Check out the [MCP Auth Node.js SDK repository](https://github.com/mcp-auth/js/blob/master/packages/sample-servers/src) for the complete code of the MCP server (OIDC version). This directory contains both TypeScript and JavaScript versions of the code. +Check out the [sample servers](https://github.com/mcp-auth/js/tree/master/packages/sample-servers) in the MCP Auth Node.js SDK repository for complete runnable projects: the `whoami` sample as a Cloudflare Worker, plus an Express variant (`whoami-express`) matching this tutorial. ::: ## Closing notes \{#closing-notes} @@ -337,11 +315,11 @@ Check out the [MCP Auth Node.js SDK repository](https://github.com/mcp-auth/js/b - Setting up a basic MCP server with the `whoami` tool - Integrating the MCP server with an authorization server using MCP Auth -- Configuring VS Code to authenticate users and retrieve their identity information +- Configuring VS Code to authenticate users and retrieve their identity from the verified access token You may also want to explore some advanced topics, including: -- Using [JWT (JSON Web Token)](https://auth.wiki/jwt) for authentication and authorization +- Enforcing [scope-based permissions](/docs/tutorials/todo-manager) for your tools - Leveraging [resource indicators (RFC 8707)](https://auth-wiki.logto.io/resource-indicator) to specify the resources being accessed - Implementing custom access control mechanisms, such as [role-based access control (RBAC)](https://auth.wiki/rbac) or [attribute-based access control (ABAC)](https://auth.wiki/abac) diff --git a/docusaurus.config.ts b/docusaurus.config.ts index 64506e3..82c2529 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -103,7 +103,7 @@ const config: Config = { }, { type: 'doc', - docId: 'tutorials/todo-manager/README', + docId: 'tutorials/whoami/README', label: 'Tutorials', position: 'right', }, diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/README.md deleted file mode 100644 index 3818cfb..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/README.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -sidebar_label: Node.js SDK ---- - -# MCP Auth Node.js SDK Referenz - -## Klassen {#classes} - -- [MCPAuth](/references/js/classes/MCPAuth.md) -- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) -- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) -- [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) - -## Typalias {#type-aliases} - -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) -- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) -- [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) -- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) -- [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) -- [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) - -## Variablen {#variables} - -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) -- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) -- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) - -## Funktionen {#functions} - -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) -- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) -- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md deleted file mode 100644 index 0cd1581..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md +++ /dev/null @@ -1,329 +0,0 @@ ---- -sidebar_label: MCPAuth ---- - -# Klasse: MCPAuth - -Die Hauptklasse der mcp-auth-Bibliothek. Sie fungiert als Factory und Registry zur Erstellung von Authentifizierungsrichtlinien für deine geschützten Ressourcen. - -Sie wird mit deinen Serverkonfigurationen initialisiert und stellt eine `bearerAuth`-Methode bereit, um Express-Middleware für tokenbasierte Authentifizierung zu generieren. - -## Beispiel {#example} - -### Verwendung im `Resource Server`-Modus {#usage-in-resource-server-mode} - -Dies ist der empfohlene Ansatz für neue Anwendungen. - -#### Option 1: Discovery-Konfiguration (empfohlen für Edge-Runtimes) {#option-1-discovery-config-recommended-for-edge-runtimes} - -Verwende dies, wenn Metadaten bei Bedarf abgerufen werden sollen. Dies ist besonders nützlich für Edge-Runtimes wie Cloudflare Workers, bei denen asynchrone Fetch-Operationen auf Top-Level-Ebene nicht erlaubt sind. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // Nur issuer und type angeben – Metadaten werden bei der ersten Anfrage abgerufen - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Option 2: Resolved-Konfiguration (vorgefetchte Metadaten) {#option-2-resolved-config-pre-fetched-metadata} - -Verwende dies, wenn du Metadaten beim Start abrufen und validieren möchtest. - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Verwendung der Middleware {#using-the-middleware} - -```ts -// Router für Protected Resource Metadata einbinden -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// Einen API-Endpunkt für die konfigurierte Ressource schützen -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // Gibt an, zu welcher Ressource dieser Endpunkt gehört - audience: resourceIdentifier, // Optional: das 'aud'-Claim validieren - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - }, -); -``` - -### Legacy-Verwendung im `Authorization Server`-Modus (Veraltet) {#legacy-usage-in-authorization-server-mode-deprecated} - -Dieser Ansatz wird aus Gründen der Abwärtskompatibilität unterstützt. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth = new MCPAuth({ - // Discovery-Konfiguration – Metadaten werden bei Bedarf abgerufen - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, -}); - -// Router für Legacy Authorization Server Metadata einbinden -app.use(mcpAuth.delegatedRouter()); - -// Einen Endpunkt mit der Standardrichtlinie schützen -app.get( - '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // Hier die MCP-Anfrage bearbeiten - }, -); -``` - -## Konstruktoren {#constructors} - -### Konstruktor {#constructor} - -```ts -new MCPAuth(config: MCPAuthConfig): MCPAuth; -``` - -Erstellt eine Instanz von MCPAuth. -Die gesamte Konfiguration wird im Voraus validiert, um Fehler frühzeitig zu erkennen. - -#### Parameter {#parameters} - -##### config {#config} - -[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) - -Die Authentifizierungskonfiguration. - -#### Rückgabewert {#returns} - -`MCPAuth` - -## Eigenschaften {#properties} - -### config {#config} - -```ts -readonly config: MCPAuthConfig; -``` - -Die Authentifizierungskonfiguration. - -## Methoden {#methods} - -### bearerAuth() {#bearerauth} - -#### Aufrufsignatur {#call-signature} - -```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; -``` - -Erstellt einen Bearer-Auth-Handler (Express-Middleware), der das Zugangstoken (Access token) im -`Authorization`-Header der Anfrage überprüft. - -##### Parameter {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -Eine Funktion, die das Zugangstoken (Access token) überprüft. Sie sollte das -Zugangstoken als String akzeptieren und ein Promise (oder einen Wert) zurückgeben, das/die das -Überprüfungsergebnis liefert. - -**Siehe** - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) für die Typdefinition der -`verifyAccessToken`-Funktion. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> - -Optionale Konfiguration für den Bearer-Auth-Handler. - -**Siehe** - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die verfügbaren Konfigurationsoptionen (ohne -`verifyAccessToken` und `issuer`). - -##### Rückgabewert {#returns} - -`RequestHandler` - -Eine Express-Middleware-Funktion, die das Zugangstoken (Access token) überprüft und das -Überprüfungsergebnis dem Request-Objekt (`req.auth`) hinzufügt. - -##### Siehe {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) für die Implementierungsdetails und die erweiterten Typen des -`req.auth` (`AuthInfo`) Objekts. - -#### Aufrufsignatur {#call-signature} - -```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; -``` - -Erstellt einen Bearer-Auth-Handler (Express-Middleware), der das Zugangstoken (Access token) im -`Authorization`-Header der Anfrage mit einem vordefinierten Verifizierungsmodus überprüft. - -Im `'jwt'`-Modus erstellt der Handler eine JWT-Überprüfungsfunktion unter Verwendung des JWK-Sets -von der JWKS-URI des Authorization Servers. - -##### Parameter {#parameters} - -###### mode {#mode} - -`"jwt"` - -Der Verifizierungsmodus für das Zugangstoken (Access token). Derzeit wird nur 'jwt' unterstützt. - -**Siehe** - -[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) für die verfügbaren Modi. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` - -Optionale Konfiguration für den Bearer-Auth-Handler, einschließlich JWT-Überprüfungsoptionen und -Remote-JWK-Set-Optionen. - -**Siehe** - - - VerifyJwtConfig für die verfügbaren Konfigurationsoptionen für die JWT- -Überprüfung. - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die verfügbaren Konfigurationsoptionen (ohne -`verifyAccessToken` und `issuer`). - -##### Rückgabewert {#returns} - -`RequestHandler` - -Eine Express-Middleware-Funktion, die das Zugangstoken (Access token) überprüft und das -Überprüfungsergebnis dem Request-Objekt (`req.auth`) hinzufügt. - -##### Siehe {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) für die Implementierungsdetails und die erweiterten Typen des -`req.auth` (`AuthInfo`) Objekts. - -##### Wirft {#throws} - -wenn die JWKS-URI in den Server-Metadaten nicht angegeben ist, wenn -der `'jwt'`-Modus verwendet wird. - -*** - -### ~~delegatedRouter()~~ {#delegatedrouter} - -```ts -delegatedRouter(): Router; -``` - -Erstellt einen Delegated Router, um den veralteten OAuth 2.0 Authorization Server Metadata Endpoint -(`/.well-known/oauth-authorization-server`) mit den der Instanz bereitgestellten Metadaten bereitzustellen. - -#### Rückgabewert {#returns} - -`Router` - -Ein Router, der den OAuth 2.0 Authorization Server Metadata Endpoint mit den -der Instanz bereitgestellten Metadaten bereitstellt. - -#### Veraltet {#deprecated} - -Verwende stattdessen [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter). - -#### Beispiel {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth: MCPAuth; // Angenommen, dies ist initialisiert -app.use(mcpAuth.delegatedRouter()); -``` - -#### Wirft {#throws} - -Wenn im `Resource Server`-Modus aufgerufen. - -*** - -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} - -```ts -protectedResourceMetadataRouter(): Router; -``` - -Erstellt einen Router, der den OAuth 2.0 Protected Resource Metadata Endpoint -für alle konfigurierten Ressourcen bereitstellt. - -Dieser Router erstellt automatisch die korrekten `.well-known`-Endpunkte für jede -Ressourcenkennung, die in deiner Konfiguration angegeben ist. - -#### Rückgabewert {#returns} - -`Router` - -Ein Router, der den OAuth 2.0 Protected Resource Metadata Endpoint bereitstellt. - -#### Wirft {#throws} - -Wenn im `Authorization Server`-Modus aufgerufen. - -#### Beispiel {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// Angenommen, mcpAuth ist mit einer oder mehreren `protectedResources`-Konfigurationen initialisiert -const mcpAuth: MCPAuth; -const app = express(); - -// Dies stellt Metadaten unter `/.well-known/oauth-protected-resource/...` bereit -// basierend auf deinen Ressourcenkennungen. -app.use(mcpAuth.protectedResourceMetadataRouter()); -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md deleted file mode 100644 index 67fbe95..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthAuthServerError ---- - -# Klasse: MCPAuthAuthServerError - -Fehler, der ausgelöst wird, wenn ein Problem mit dem entfernten Autorisierungsserver auftritt. - -## Erbt von {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Konstruktoren {#constructors} - -### Konstruktor {#constructor} - -```ts -new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; -``` - -#### Parameter {#parameters} - -##### code {#code} - -[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### Rückgabewert {#returns} - -`MCPAuthAuthServerError` - -#### Überschreibt {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Eigenschaften {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: AuthServerErrorCode; -``` - -Der Fehlercode im snake_case-Format. - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthAuthServerError'; -``` - -#### Überschreibt {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Optionale Überschreibung zur Formatierung von Stacktraces - -#### Parameter {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Rückgabewert {#returns} - -`any` - -#### Siehe {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Methoden {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. - -#### Parameter {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Gibt an, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. -Standardmäßig `false`. - -#### Rückgabewert {#returns} - -`Record`\<`string`, `unknown`\> - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Erstellt die .stack-Eigenschaft auf einem Zielobjekt - -#### Parameter {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Rückgabewert {#returns} - -`void` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index c70f4af..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# Klasse: MCPAuthBearerAuthError - -Fehler, der ausgelöst wird, wenn es ein Problem bei der Authentifizierung mit Bearer-Tokens gibt. - -## Erweitert {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Konstruktoren {#constructors} - -### Konstruktor {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### Parameter {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### Rückgabewert {#returns} - -`MCPAuthBearerAuthError` - -#### Überschreibt {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Eigenschaften {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -Der Fehlercode im snake_case-Format. - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### Überschreibt {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Optionale Überschreibung zur Formatierung von Stacktraces - -#### Parameter {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Rückgabewert {#returns} - -`any` - -#### Siehe {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Methoden {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. - -#### Parameter {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Gibt an, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. -Standardmäßig `false`. - -#### Rückgabewert {#returns} - -`Record`\<`string`, `unknown`\> - -#### Überschreibt {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Erstellt die .stack-Eigenschaft auf einem Zielobjekt - -#### Parameter {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Rückgabewert {#returns} - -`void` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md deleted file mode 100644 index 0103c4e..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebar_label: MCPAuthConfigError ---- - -# Klasse: MCPAuthConfigError - -Fehler, der ausgelöst wird, wenn ein Konfigurationsproblem mit mcp-auth vorliegt. - -## Erbt von {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Konstruktoren {#constructors} - -### Konstruktor {#constructor} - -```ts -new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; -``` - -#### Parameter {#parameters} - -##### code {#code} - -`string` - -Der Fehlercode im snake_case-Format. - -##### message {#message} - -`string` - -Eine menschenlesbare Beschreibung des Fehlers. - -#### Rückgabe {#returns} - -`MCPAuthConfigError` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Eigenschaften {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -Der Fehlercode im snake_case-Format. - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthConfigError'; -``` - -#### Überschreibt {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Optionale Überschreibung zur Formatierung von Stacktraces - -#### Parameter {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Rückgabe {#returns} - -`any` - -#### Siehe {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Methoden {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. - -#### Parameter {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. -Standardmäßig `false`. - -#### Rückgabe {#returns} - -`Record`\<`string`, `unknown`\> - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Erstellt die .stack-Eigenschaft auf einem Zielobjekt - -#### Parameter {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Rückgabe {#returns} - -`void` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md deleted file mode 100644 index 88dce09..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -sidebar_label: MCPAuthError ---- - -# Klasse: MCPAuthError - -Basisklasse für alle mcp-auth Fehler. - -Sie bietet eine standardisierte Möglichkeit, Fehler im Zusammenhang mit MCP Authentifizierung (Authentication) und Autorisierung (Authorization) zu behandeln. - -## Erweitert {#extends} - -- `Error` - -## Erweitert von {#extended-by} - -- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) -- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) - -## Konstruktoren {#constructors} - -### Konstruktor {#constructor} - -```ts -new MCPAuthError(code: string, message: string): MCPAuthError; -``` - -#### Parameter {#parameters} - -##### code {#code} - -`string` - -Der Fehlercode im snake_case-Format. - -##### message {#message} - -`string` - -Eine menschenlesbare Beschreibung des Fehlers. - -#### Rückgabe {#returns} - -`MCPAuthError` - -#### Überschreibt {#overrides} - -```ts -Error.constructor -``` - -## Eigenschaften {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### Geerbt von {#inherited-from} - -```ts -Error.cause -``` - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -Der Fehlercode im snake_case-Format. - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Geerbt von {#inherited-from} - -```ts -Error.message -``` - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthError'; -``` - -#### Überschreibt {#overrides} - -```ts -Error.name -``` - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Geerbt von {#inherited-from} - -```ts -Error.stack -``` - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Optionale Überschreibung zur Formatierung von Stacktraces - -#### Parameter {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Rückgabe {#returns} - -`any` - -#### Siehe {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Geerbt von {#inherited-from} - -```ts -Error.prepareStackTrace -``` - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Geerbt von {#inherited-from} - -```ts -Error.stackTraceLimit -``` - -## Methoden {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. - -#### Parameter {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. -Standardmäßig `false`. - -#### Rückgabe {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Erstellt die .stack Eigenschaft auf einem Zielobjekt - -#### Parameter {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Rückgabe {#returns} - -`void` - -#### Geerbt von {#inherited-from} - -```ts -Error.captureStackTrace -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index ef70223..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# Klasse: MCPAuthTokenVerificationError - -Fehler, der ausgelöst wird, wenn beim Überprüfen von Tokens ein Problem auftritt. - -## Erbt von {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Konstruktoren {#constructors} - -### Konstruktor {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### Parameter {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### Rückgabewert {#returns} - -`MCPAuthTokenVerificationError` - -#### Überschreibt {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Eigenschaften {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -Der Fehlercode im snake_case-Format. - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### Überschreibt {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Optionale Überschreibung zur Formatierung von Stacktraces - -#### Parameter {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Rückgabewert {#returns} - -`any` - -#### Siehe {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Methoden {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Wandelt den Fehler in ein HTTP-Response-freundliches JSON-Format um. - -#### Parameter {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Gibt an, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. -Standardmäßig `false`. - -#### Rückgabewert {#returns} - -`Record`\<`string`, `unknown`\> - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Erstellt die .stack-Eigenschaft auf einem Zielobjekt - -#### Parameter {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Rückgabewert {#returns} - -`void` - -#### Geerbt von {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md deleted file mode 100644 index 66ef89c..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# Funktion: createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -Erstellt eine Funktion zur Überprüfung von JWT-Zugangstokens (Access tokens), indem die bereitgestellte Schlüsselabruffunktion und Optionen verwendet werden. - -## Parameter {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -Die Funktion zum Abrufen des Schlüssels, der zur Überprüfung des JWT verwendet wird. - -**Siehe** - -JWTVerifyGetKey für die Typdefinition der Schlüsselabruffunktion. - -### options? {#options} - -`JWTVerifyOptions` - -Optionale Optionen zur JWT-Überprüfung. - -**Siehe** - -JWTVerifyOptions für die Typdefinition der Optionen. - -## Rückgabewert {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -Eine Funktion, die JWT-Zugangstokens (Access tokens) überprüft und ein AuthInfo-Objekt zurückgibt, wenn das Token gültig ist. Es wird vorausgesetzt, dass das JWT die Felder `iss`, `client_id` und `sub` im Payload enthält; optional können auch die Felder `scope` oder `scopes` enthalten sein. Die Funktion verwendet intern die `jose`-Bibliothek, um die JWT-Überprüfung durchzuführen. - -## Siehe {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) für die Typdefinition der zurückgegebenen Funktion. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md deleted file mode 100644 index ef52dcb..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -sidebar_label: fetchServerConfig ---- - -# Funktion: fetchServerConfig() - -```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; -``` - -Ruft die Serverkonfiguration entsprechend dem Aussteller (Issuer) und dem Typ des Autorisierungsservers ab. - -Diese Funktion bestimmt automatisch die Well-known-URL basierend auf dem Servertyp, da OAuth 2.0 (OAuth 2.0) und OpenID Connect (OpenID Connect) Server unterschiedliche Konventionen für ihre Metadatenendpunkte haben. - -## Parameter {#parameters} - -### issuer {#issuer} - -`string` - -Die Aussteller-URL (Issuer URL) des Autorisierungsservers. - -### config {#config} - -`ServerMetadataConfig` - -Das Konfigurationsobjekt, das den Servertyp und eine optionale Transpilierungsfunktion enthält. - -## Rückgabewert {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -Ein Promise, das mit der statischen Serverkonfiguration und den abgerufenen Metadaten aufgelöst wird. - -## Siehe auch {#see} - - - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) für die zugrundeliegende Implementierung. - - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) für die OAuth 2.0 Authorization Server Metadata Spezifikation. - - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) für die OpenID Connect (OpenID Connect) Discovery Spezifikation. - -## Beispiel {#example} - -```ts -import { fetchServerConfig } from 'mcp-auth'; -// Abrufen der OAuth 2.0 (OAuth 2.0) Serverkonfiguration -// Dies ruft die Metadaten von `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` ab -const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); - -// Abrufen der OpenID Connect (OpenID Connect) Serverkonfiguration -// Dies ruft die Metadaten von `https://auth.logto.io/oidc/.well-known/openid-configuration` ab -const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); -``` - -## Fehlerauslösung {#throws} - -wenn der Abrufvorgang fehlschlägt. - -## Fehlerauslösung {#throws} - -wenn die Server-Metadaten ungültig sind oder nicht der MCP-Spezifikation entsprechen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md deleted file mode 100644 index b6ffce8..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -sidebar_label: fetchServerConfigByWellKnownUrl ---- - -# Funktion: fetchServerConfigByWellKnownUrl() - -```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; -``` - -Ruft die Serverkonfiguration von der angegebenen Well-Known-URL ab und validiert sie gegen die -MCP-Spezifikation. - -Wenn die Server-Metadaten nicht dem erwarteten Schema entsprechen, du dir aber sicher bist, dass sie -kompatibel sind, kannst du eine `transpileData`-Funktion definieren, um die Metadaten in das -erwartete Format zu transformieren. - -## Parameter {#parameters} - -### wellKnownUrl {#wellknownurl} - -Die Well-Known-URL, von der die Serverkonfiguration abgerufen werden soll. Dies kann ein -String oder ein URL-Objekt sein. - -`string` | `URL` - -### config {#config} - -`ServerMetadataConfig` - -Das Konfigurationsobjekt, das den Servertyp und optional eine Transpile-Funktion enthält. - -## Rückgabewert {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -Ein Promise, das mit der statischen Serverkonfiguration und den abgerufenen Metadaten aufgelöst wird. - -## Löst aus {#throws} - -wenn der Abrufvorgang fehlschlägt. - -## Löst aus {#throws} - -wenn die Server-Metadaten ungültig sind oder nicht der -MCP-Spezifikation entsprechen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md deleted file mode 100644 index ce75b9c..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# Funktion: getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -Gibt die Aussteller-URL (Issuer URL) aus einer Auth-Server-Konfiguration zurück. - -- Aufgelöste Konfiguration: Extrahiert aus `metadata.issuer` -- Discovery-Konfiguration: Gibt `issuer` direkt zurück - -## Parameter {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## Rückgabewert {#returns} - -`string` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md deleted file mode 100644 index b8d551f..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# Funktion: handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -Erstellt eine Middleware-Funktion zur Behandlung der Bearer-Authentifizierung in einer Express-Anwendung. - -Diese Middleware extrahiert das Bearer-Token aus dem `Authorization`-Header, überprüft es mit der bereitgestellten Funktion `verifyAccessToken` und prüft den Aussteller (Issuer), die Zielgruppe (Audience) und die erforderlichen Berechtigungen (Scopes). - -- Wenn das Token gültig ist, fügt es die Authentifizierungsinformationen zur Eigenschaft `request.auth` hinzu; andernfalls antwortet es mit einer entsprechenden Fehlermeldung. -- Wenn die Überprüfung des Zugangstokens (Access token) fehlschlägt, wird mit einem 401 Unauthorized-Fehler geantwortet. -- Wenn das Token nicht über die erforderlichen Berechtigungen (Scopes) verfügt, wird mit einem 403 Forbidden-Fehler geantwortet. -- Wenn während des Authentifizierungsprozesses unerwartete Fehler auftreten, wird die Middleware diese erneut auslösen. - -**Hinweis:** Das Objekt `request.auth` enthält erweiterte Felder im Vergleich zur Standard-AuthInfo-Schnittstelle, die im Modul `@modelcontextprotocol/sdk` definiert ist. Siehe die erweiterte Schnittstelle in dieser Datei für Details. - -## Parameter {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Konfiguration für den Bearer-Authentifizierungs-Handler. - -## Rückgabewert {#returns} - -`RequestHandler` - -Eine Middleware-Funktion für Express, die die Bearer-Authentifizierung behandelt. - -## Siehe auch {#see} - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die Konfigurationsoptionen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md deleted file mode 100644 index cc6092e..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerConfig ---- - -# Typalias: AuthServerConfig - -```ts -type AuthServerConfig = - | ResolvedAuthServerConfig - | AuthServerDiscoveryConfig; -``` - -Konfiguration für den entfernten Autorisierungsserver (Authorization server), der mit dem MCP-Server integriert ist. - -Kann entweder sein: -- **Aufgelöst (Resolved)**: Enthält `metadata` – keine Netzwerkabfrage erforderlich -- **Discovery**: Enthält nur `issuer` und `type` – Metadaten werden bei Bedarf per Discovery abgerufen \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index 9cf5cbd..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# Typalias: AuthServerConfigError - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -Repräsentiert einen Fehler, der während der Validierung der Metadaten des Autorisierungsservers (authorization server) auftritt. - -## Eigenschaften {#properties} - -### cause? {#cause} - -```ts -optional cause: Error; -``` - -Eine optionale Ursache des Fehlers, typischerweise eine Instanz von `Error`, die mehr Kontext liefert. - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -Der Code, der den spezifischen Validierungsfehler repräsentiert. - -*** - -### description {#description} - -```ts -description: string; -``` - -Eine menschenlesbare Beschreibung des Fehlers. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index e942349..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# Typalias: AuthServerConfigErrorCode - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -Die Codes für Fehler, die beim Validieren der Metadaten des Autorisierungsservers auftreten können. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index b803176..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# Typalias: AuthServerConfigWarning - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -Stellt eine Warnung dar, die während der Validierung der Metadaten des Autorisierungsservers auftritt. - -## Eigenschaften {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -Der Code, der die spezifische Validierungswarnung darstellt. - -*** - -### description {#description} - -```ts -description: string; -``` - -Eine für Menschen lesbare Beschreibung der Warnung. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index d6aca4c..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# Typalias: AuthServerConfigWarningCode - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -Die Codes für Warnungen, die beim Validieren der Metadaten des Autorisierungsservers auftreten können. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md deleted file mode 100644 index 31a5505..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -sidebar_label: AuthServerDiscoveryConfig ---- - -# Typalias: AuthServerDiscoveryConfig - -```ts -type AuthServerDiscoveryConfig = { - issuer: string; - type: AuthServerType; -}; -``` - -Discovery-Konfiguration für den entfernten Aussteller (Issuer) des Autorisierungsservers. - -Verwende dies, wenn die Metadaten bei Bedarf per Discovery abgerufen werden sollen, sobald sie das erste Mal benötigt werden. -Dies ist nützlich für Edge-Runtimes wie Cloudflare Workers, bei denen asynchrones Fetch auf Top-Level-Ebene -nicht erlaubt ist. - -## Beispiel {#example} - -```typescript -const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, - }, -}); -``` - -## Eigenschaften {#properties} - -### issuer {#issuer} - -```ts -issuer: string; -``` - -Die Aussteller-URL (Issuer URL) des Autorisierungsservers. Die Metadaten werden vom -well-known Endpoint abgerufen, der von diesem Aussteller abgeleitet wird. - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -Der Typ des Autorisierungsservers. - -#### Siehe {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) für die möglichen Werte. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md deleted file mode 100644 index fe86fa0..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: AuthServerErrorCode ---- - -# Typalias: AuthServerErrorCode - -```ts -type AuthServerErrorCode = - | "invalid_server_metadata" - | "invalid_server_config" - | "missing_jwks_uri"; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index 9352a7e..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# Typalias: ~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -Konfiguration für den veralteten, MCP-Server als Autorisierungsserver-Modus. - -## Veraltet {#deprecated} - -Verwende stattdessen die `ResourceServerModeConfig`-Konfiguration. - -## Eigenschaften {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -Die einzelne Autorisierungsserver-Konfiguration. - -#### Veraltet {#deprecated} - -Verwende stattdessen die `protectedResources`-Konfiguration. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index e20bee1..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# Typalias: AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -Die Codes für die erfolgreiche Validierung der Metadaten des Autorisierungsservers (authorization server metadata). \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md deleted file mode 100644 index 0c9692c..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerType ---- - -# Typalias: AuthServerType - -```ts -type AuthServerType = "oauth" | "oidc"; -``` - -Der Typ des Autorisierungsservers. Diese Information sollte durch die Serverkonfiguration bereitgestellt werden und gibt an, ob der Server ein OAuth 2.0- oder OpenID Connect (OIDC)-Autorisierungsserver ist. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index 561617e..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: AuthorizationServerMetadata ---- - -# Typalias: AuthorizationServerMetadata - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -Schema für OAuth 2.0 Authorization Server Metadata wie in RFC 8414 definiert. - -## Siehe {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index 0c38965..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# Typalias: BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## Eigenschaften {#properties} - -### audience? {#audience} - -```ts -optional audience: string; -``` - -Die erwartete Zielgruppe (Audience) des Zugangstokens (Zugangstoken (`aud` Anspruch)). Dies ist typischerweise der Ressourcenserver -(API), für den das Token bestimmt ist. Wenn nicht angegeben, wird die Überprüfung der Zielgruppe übersprungen. - -**Hinweis:** Wenn dein Autorisierungsserver keine Ressourcenindikatoren (RFC 8707) unterstützt, -kannst du dieses Feld weglassen, da die Zielgruppe möglicherweise nicht relevant ist. - -#### Siehe {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -Ein String, der einen gültigen Aussteller (Issuer) darstellt, oder eine Funktion zur Validierung des Ausstellers des Zugangstokens. - -Wenn ein String angegeben wird, wird dieser als erwarteter Ausstellerwert für den direkten Vergleich verwendet. - -Wenn eine Funktion angegeben wird, sollte sie den Aussteller gemäß den Regeln in -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) validieren. - -#### Siehe {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) für weitere Details zur Validierungsfunktion. - -*** - -### requiredScopes? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -Ein Array der erforderlichen Berechtigungen (Berechtigungen), die das Zugangstoken enthalten muss. Wenn das Token nicht -alle diese Berechtigungen enthält, wird ein Fehler ausgelöst. - -**Hinweis:** Der Handler prüft den `scope`-Anspruch im Token, der je nach Implementierung des Autorisierungsservers eine durch Leerzeichen getrennte Zeichenkette oder ein Array von Zeichenketten sein kann. Wenn der `scope`-Anspruch nicht vorhanden ist, prüft der Handler den `scopes`-Anspruch, -sofern verfügbar. - -*** - -### resource? {#resource} - -```ts -optional resource: string; -``` - -Der Bezeichner der geschützten Ressource. Wenn angegeben, verwendet der Handler die -für diese Ressource konfigurierten Autorisierungsserver, um das empfangene Token zu validieren. -Dies ist erforderlich, wenn der Handler mit einer `protectedResources`-Konfiguration verwendet wird. - -*** - -### showErrorDetails? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -Ob detaillierte Fehlerinformationen in der Antwort angezeigt werden sollen. Dies ist während der Entwicklung zum Debuggen nützlich, -sollte jedoch in der Produktion deaktiviert werden, um das Offenlegen sensibler Informationen zu vermeiden. - -#### Standardwert {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -Funktionstyp zur Überprüfung eines Zugangstokens. - -Diese Funktion sollte einen [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) auslösen, wenn das Token ungültig ist, -oder ein AuthInfo-Objekt zurückgeben, wenn das Token gültig ist. - -#### Siehe {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) für weitere Details. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index 290f126..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# Typalias: BearerAuthErrorCode - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index 4c9cd1b..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# Typalias: CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -Die camelCase-Version des OAuth 2.0 Authorization Server Metadata-Typs. - -## Siehe auch {#see} - -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) für den Originaltyp und Feldinformationen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index 0870841..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# Typalias: CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -Die camelCase-Version des OAuth 2.0 Protected Resource Metadata-Typs. - -## Siehe auch {#see} - -[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) für den Originaltyp und Feldinformationen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index f8be37f..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# Typalias: MCPAuthBearerAuthErrorDetails - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## Eigenschaften {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md deleted file mode 100644 index 171b4c5..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -sidebar_label: MCPAuthConfig ---- - -# Typalias: MCPAuthConfig - -```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; -``` - -Konfiguration für die [MCPAuth](/references/js/classes/MCPAuth.md)-Klasse, die entweder einen einzelnen Legacy-`Autorisierungsserver` oder die `Resource Server`-Konfiguration unterstützt. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index d090ace..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# Typalias: MCPAuthTokenVerificationErrorCode - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index be5d259..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# Typalias: ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -Schema für OAuth 2.0 Geschützte Ressourcen-Metadaten (Protected Resource Metadata). \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md deleted file mode 100644 index 64ed252..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -sidebar_label: ResolvedAuthServerConfig ---- - -# Typalias: ResolvedAuthServerConfig - -```ts -type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; -``` - -Aufgelöste Konfiguration für den entfernten Autorisierungsserver (authorization server) mit Metadaten. - -Verwende dies, wenn die Metadaten bereits verfügbar sind, entweder fest codiert oder zuvor abgerufen -über `fetchServerConfig()`. - -## Eigenschaften {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -Die Metadaten des Autorisierungsservers (authorization server), die der MCP-Spezifikation -(basierend auf OAuth 2.0 Authorization Server Metadata) entsprechen sollten. - -Diese Metadaten werden typischerweise vom Well-known-Endpunkt des Servers abgerufen (OAuth 2.0 -Authorization Server Metadata oder OpenID Connect Discovery); sie können auch direkt in der Konfiguration bereitgestellt werden, wenn der Server solche Endpunkte nicht unterstützt. - -**Hinweis:** Die Metadaten sollten im camelCase-Format vorliegen, wie von der mcp-auth- -Bibliothek bevorzugt. - -#### Siehe {#see} - - - [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -Der Typ des Autorisierungsservers (authorization server). - -#### Siehe {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) für die möglichen Werte. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index 65b1a7b..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# Typalias: ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -Konfiguration für den MCP-Server im Resource-Server-Modus. - -## Eigenschaften {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -Eine einzelne Resource-Server-Konfiguration oder ein Array davon. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index 67e1339..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# Typalias: ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -Funktionstyp zur Validierung des Ausstellers (Issuer) des Zugangstokens (Access token). - -Diese Funktion sollte einen [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) mit dem Code 'invalid_issuer' auslösen, wenn der Aussteller -nicht gültig ist. Der Aussteller sollte anhand folgender Kriterien validiert werden: - -1. Die in den Auth-Server-Metadaten von MCP-Auth konfigurierten Autorisierungsserver (Authorization servers) -2. Die in den Metadaten der geschützten Ressource aufgeführten Autorisierungsserver (Authorization servers) - -## Parameter {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## Rückgabewert {#returns} - -`void` - -## Ausnahmen {#throws} - -Wenn der Aussteller nicht erkannt oder ungültig ist. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index 95f8cbb..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# Typalias: VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -Funktionstyp zur Überprüfung eines Zugangstokens (Access token). - -Diese Funktion sollte einen [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) auslösen, wenn das Token ungültig ist, -oder ein AuthInfo-Objekt zurückgeben, wenn das Token gültig ist. - -Wenn du beispielsweise eine JWT-Überprüfungsfunktion hast, sollte sie mindestens die Signatur des Tokens -überprüfen, das Ablaufdatum validieren und die notwendigen Ansprüche (Claims) extrahieren, um ein `AuthInfo`- -Objekt zurückzugeben. - -**Hinweis:** Es ist nicht notwendig, die folgenden Felder im Token zu überprüfen, da sie vom Handler geprüft werden: - -- `iss` (Aussteller / issuer) -- `aud` (Zielgruppe / audience) -- `scope` (Berechtigungen / scopes) - -## Parameter {#parameters} - -### token {#token} - -`string` - -Der zu überprüfende Zugangstoken-String (Access token string). - -## Rückgabewert {#returns} - -`MaybePromise`\<`AuthInfo`\> - -Ein Promise, das auf ein AuthInfo-Objekt aufgelöst wird, oder ein synchroner Wert, wenn das -Token gültig ist. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index b0576e7..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# Typalias: VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -Die von `bearerAuth` unterstützten integrierten Überprüfungsmodi. \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md deleted file mode 100644 index b4726e8..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: authServerErrorDescription ---- - -# Variable: authServerErrorDescription - -```ts -const authServerErrorDescription: Readonly>; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index 9244274..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# Variable: authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -Zod-Schema für OAuth 2.0 Authorization Server Metadata wie in RFC 8414 definiert (Zod schema for OAuth 2.0 Authorization Server Metadata as defined in RFC 8414). - -## Siehe {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index ed1a931..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# Variable: bearerAuthErrorDescription - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index 671bfea..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# Variable: camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -Die camelCase-Version des OAuth 2.0 Authorization Server Metadata Zod-Schemas. - -## Siehe auch {#see} - -[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) für das ursprüngliche Schema und Feldinformationen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index c032784..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# Variable: camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -Die camelCase-Version des OAuth 2.0 Protected Resource Metadata Zod-Schemas. - -## Siehe auch {#see} - -[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) für das ursprüngliche Schema und Feldinformationen. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md deleted file mode 100644 index c29ea72..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# Variable: defaultValues - -```ts -const defaultValues: Readonly>; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index 2e248f8..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# Variable: protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -Zod-Schema für OAuth 2.0 Geschützte Ressourcen-Metadaten (OAuth 2.0 Protected Resource Metadata). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md deleted file mode 100644 index 68cbf41..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: serverMetadataPaths ---- - -# Variable: serverMetadataPaths - -```ts -const serverMetadataPaths: Readonly<{ - oauth: "/.well-known/oauth-authorization-server"; - oidc: "/.well-known/openid-configuration"; -}>; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index 3d6e760..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: tokenVerificationErrorDescription ---- - -# Variable: tokenVerificationErrorDescription - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` diff --git a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md deleted file mode 100644 index e60de41..0000000 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# Variable: validateServerConfig - -```ts -const validateServerConfig: ValidateServerConfig; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/README.md deleted file mode 100644 index aead9d7..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/README.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -sidebar_label: Node.js SDK ---- - -# Referencia del SDK MCP Auth Node.js - -## Clases {#classes} - -- [MCPAuth](/references/js/classes/MCPAuth.md) -- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) -- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) -- [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) - -## Alias de tipos {#type-aliases} - -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) -- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) -- [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) -- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) -- [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) -- [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) - -## Variables {#variables} - -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) -- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) -- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) - -## Funciones {#functions} - -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) -- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) -- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md deleted file mode 100644 index 4635993..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md +++ /dev/null @@ -1,323 +0,0 @@ ---- -sidebar_label: MCPAuth ---- - -# Clase: MCPAuth - -La clase principal para la librería mcp-auth. Actúa como una fábrica y registro para crear políticas de autenticación para tus recursos protegidos. - -Se inicializa con las configuraciones de tu servidor y proporciona un método `bearerAuth` para generar middleware de Express para autenticación basada en tokens. - -## Ejemplo {#example} - -### Uso en modo `servidor de recursos` {#usage-in-resource-server-mode} - -Este es el enfoque recomendado para nuevas aplicaciones. - -#### Opción 1: Configuración de descubrimiento (recomendado para runtimes edge) {#option-1-discovery-config-recommended-for-edge-runtimes} - -Utiliza esto cuando quieras que los metadatos se obtengan bajo demanda. Esto es especialmente útil para runtimes edge como Cloudflare Workers donde no se permite el fetch asíncrono a nivel superior. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // Solo pasa issuer y type - los metadatos se obtendrán en la primera solicitud - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Opción 2: Configuración resuelta (metadatos pre-obtenidos) {#option-2-resolved-config-pre-fetched-metadata} - -Utiliza esto cuando quieras obtener y validar los metadatos en el momento de inicio. - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Uso del middleware {#using-the-middleware} - -```ts -// Monta el router para manejar los metadatos de recursos protegidos -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// Protege un endpoint de API para el recurso configurado -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // Especifica a qué recurso pertenece este endpoint - audience: resourceIdentifier, // Opcionalmente, valida el reclamo 'aud' - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - }, -); -``` - -### Uso heredado en modo `servidor de autorización` (Obsoleto) {#legacy-usage-in-authorization-server-mode-deprecated} - -Este enfoque se admite por compatibilidad con versiones anteriores. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth = new MCPAuth({ - // Configuración de descubrimiento - los metadatos se obtienen bajo demanda - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, -}); - -// Monta el router para manejar los metadatos heredados del servidor de autorización -app.use(mcpAuth.delegatedRouter()); - -// Protege un endpoint usando la política predeterminada -app.get( - '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // Maneja la solicitud MCP aquí - }, -); -``` - -## Constructores {#constructors} - -### Constructor {#constructor} - -```ts -new MCPAuth(config: MCPAuthConfig): MCPAuth; -``` - -Crea una instancia de MCPAuth. -Valida toda la configuración por adelantado para fallar rápido en caso de errores. - -#### Parámetros {#parameters} - -##### config {#config} - -[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) - -La configuración de autenticación. - -#### Retorna {#returns} - -`MCPAuth` - -## Propiedades {#properties} - -### config {#config} - -```ts -readonly config: MCPAuthConfig; -``` - -La configuración de autenticación. - -## Métodos {#methods} - -### bearerAuth() {#bearerauth} - -#### Firma de llamada {#call-signature} - -```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; -``` - -Crea un manejador Bearer auth (middleware de Express) que verifica el token de acceso en el encabezado -`Authorization` de la solicitud. - -##### Parámetros {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -Una función que verifica el token de acceso. Debe aceptar el token de acceso como una cadena y devolver una promesa (o un valor) que resuelva el resultado de la verificación. - -**Ver** - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para la definición de tipo de la función -`verifyAccessToken`. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> - -Configuración opcional para el manejador Bearer auth. - -**Ver** - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para las opciones de configuración disponibles (excluyendo -`verifyAccessToken` y `issuer`). - -##### Retorna {#returns} - -`RequestHandler` - -Una función middleware de Express que verifica el token de acceso y añade el resultado de la verificación al objeto de la solicitud (`req.auth`). - -##### Ver {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) para los detalles de implementación y los tipos extendidos del objeto -`req.auth` (`AuthInfo`). - -#### Firma de llamada {#call-signature} - -```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; -``` - -Crea un manejador Bearer auth (middleware de Express) que verifica el token de acceso en el encabezado -`Authorization` de la solicitud usando un modo de verificación predefinido. - -En el modo `'jwt'`, el manejador creará una función de verificación JWT usando el JWK Set -del URI JWKS del servidor de autorización. - -##### Parámetros {#parameters} - -###### mode {#mode} - -`"jwt"` - -El modo de verificación para el token de acceso. Actualmente, solo se admite 'jwt'. - -**Ver** - -[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) para los modos disponibles. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` - -Configuración opcional para el manejador Bearer auth, incluyendo opciones de verificación JWT y opciones remotas de JWK set. - -**Ver** - - - VerifyJwtConfig para las opciones de configuración disponibles para la verificación JWT. - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para las opciones de configuración disponibles (excluyendo -`verifyAccessToken` y `issuer`). - -##### Retorna {#returns} - -`RequestHandler` - -Una función middleware de Express que verifica el token de acceso y añade el resultado de la verificación al objeto de la solicitud (`req.auth`). - -##### Ver {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) para los detalles de implementación y los tipos extendidos del objeto -`req.auth` (`AuthInfo`). - -##### Lanza {#throws} - -si el URI JWKS no se proporciona en los metadatos del servidor al -usar el modo `'jwt'`. - -*** - -### ~~delegatedRouter()~~ {#delegatedrouter} - -```ts -delegatedRouter(): Router; -``` - -Crea un router delegado para servir el endpoint heredado de metadatos del servidor de autorización OAuth 2.0 -(`/.well-known/oauth-authorization-server`) con los metadatos proporcionados a la instancia. - -#### Retorna {#returns} - -`Router` - -Un router que sirve el endpoint de metadatos del servidor de autorización OAuth 2.0 con los -metadatos proporcionados a la instancia. - -#### Obsoleto {#deprecated} - -Usa [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) en su lugar. - -#### Ejemplo {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth: MCPAuth; // Se asume que está inicializado -app.use(mcpAuth.delegatedRouter()); -``` - -#### Lanza {#throws} - -Si se llama en modo `servidor de recursos`. - -*** - -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} - -```ts -protectedResourceMetadataRouter(): Router; -``` - -Crea un router que sirve el endpoint de metadatos de recursos protegidos OAuth 2.0 -para todos los recursos configurados. - -Este router crea automáticamente los endpoints `.well-known` correctos para cada -identificador de recurso proporcionado en tu configuración. - -#### Retorna {#returns} - -`Router` - -Un router que sirve el endpoint de metadatos de recursos protegidos OAuth 2.0. - -#### Lanza {#throws} - -Si se llama en modo `servidor de autorización`. - -#### Ejemplo {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// Suponiendo que mcpAuth está inicializado con una o más configuraciones de `protectedResources` -const mcpAuth: MCPAuth; -const app = express(); - -// Esto servirá metadatos en `/.well-known/oauth-protected-resource/...` -// basado en tus identificadores de recursos. -app.use(mcpAuth.protectedResourceMetadataRouter()); -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md deleted file mode 100644 index 6042bc9..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthAuthServerError ---- - -# Clase: MCPAuthAuthServerError - -Error lanzado cuando hay un problema con el servidor de autorización remoto. - -## Hereda de {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructores {#constructors} - -### Constructor {#constructor} - -```ts -new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; -``` - -#### Parámetros {#parameters} - -##### code {#code} - -[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### Devuelve {#returns} - -`MCPAuthAuthServerError` - -#### Sobrescribe {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propiedades {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: AuthServerErrorCode; -``` - -El código de error en formato snake_case. - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthAuthServerError'; -``` - -#### Sobrescribe {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescritura opcional para formatear los stack traces - -#### Parámetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Devuelve {#returns} - -`any` - -#### Ver {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convierte el error a un formato JSON amigable para respuestas HTTP. - -#### Parámetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indica si se debe incluir la causa del error en la respuesta JSON. -Por defecto es `false`. - -#### Devuelve {#returns} - -`Record`\<`string`, `unknown`\> - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crea la propiedad .stack en un objeto objetivo - -#### Parámetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Devuelve {#returns} - -`void` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index 3bb856f..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# Clase: MCPAuthBearerAuthError - -Error lanzado cuando hay un problema al autenticar con tokens Bearer. - -## Hereda de {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructores {#constructors} - -### Constructor {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### Parámetros {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### Devuelve {#returns} - -`MCPAuthBearerAuthError` - -#### Sobrescribe {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propiedades {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -El código de error en formato snake_case. - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### Sobrescribe {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescritura opcional para formatear los stack traces - -#### Parámetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Devuelve {#returns} - -`any` - -#### Ver {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convierte el error a un formato JSON amigable para respuestas HTTP. - -#### Parámetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indica si se debe incluir la causa del error en la respuesta JSON. -Por defecto es `false`. - -#### Devuelve {#returns} - -`Record`\<`string`, `unknown`\> - -#### Sobrescribe {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crea la propiedad .stack en un objeto objetivo - -#### Parámetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Devuelve {#returns} - -`void` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md deleted file mode 100644 index 08177c8..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebar_label: MCPAuthConfigError ---- - -# Clase: MCPAuthConfigError - -Error lanzado cuando hay un problema de configuración con mcp-auth. - -## Hereda de {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructores {#constructors} - -### Constructor {#constructor} - -```ts -new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; -``` - -#### Parámetros {#parameters} - -##### code {#code} - -`string` - -El código de error en formato snake_case. - -##### message {#message} - -`string` - -Una descripción legible para humanos del error. - -#### Devuelve {#returns} - -`MCPAuthConfigError` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propiedades {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -El código de error en formato snake_case. - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthConfigError'; -``` - -#### Sobrescribe {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescritura opcional para formatear los stack traces - -#### Parámetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Devuelve {#returns} - -`any` - -#### Ver {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convierte el error a un formato JSON apto para respuestas HTTP. - -#### Parámetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indica si se debe incluir la causa del error en la respuesta JSON. -Por defecto es `false`. - -#### Devuelve {#returns} - -`Record`\<`string`, `unknown`\> - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crea la propiedad .stack en un objeto objetivo - -#### Parámetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Devuelve {#returns} - -`void` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md deleted file mode 100644 index 4304c19..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -sidebar_label: MCPAuthError ---- - -# Clase: MCPAuthError - -Clase base para todos los errores de mcp-auth. - -Proporciona una forma estandarizada de manejar errores relacionados con la autenticación (Authentication) y autorización (Authorization) de MCP. - -## Hereda de {#extends} - -- `Error` - -## Extendida por {#extended-by} - -- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) -- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) - -## Constructores {#constructors} - -### Constructor {#constructor} - -```ts -new MCPAuthError(code: string, message: string): MCPAuthError; -``` - -#### Parámetros {#parameters} - -##### code {#code} - -`string` - -El código de error en formato snake_case. - -##### message {#message} - -`string` - -Una descripción legible para humanos del error. - -#### Devuelve {#returns} - -`MCPAuthError` - -#### Sobrescribe {#overrides} - -```ts -Error.constructor -``` - -## Propiedades {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### Heredado de {#inherited-from} - -```ts -Error.cause -``` - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -El código de error en formato snake_case. - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Heredado de {#inherited-from} - -```ts -Error.message -``` - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthError'; -``` - -#### Sobrescribe {#overrides} - -```ts -Error.name -``` - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Heredado de {#inherited-from} - -```ts -Error.stack -``` - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescritura opcional para formatear los stack traces - -#### Parámetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Devuelve {#returns} - -`any` - -#### Ver {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Heredado de {#inherited-from} - -```ts -Error.prepareStackTrace -``` - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Heredado de {#inherited-from} - -```ts -Error.stackTraceLimit -``` - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convierte el error a un formato JSON apto para respuestas HTTP. - -#### Parámetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indica si se debe incluir la causa del error en la respuesta JSON. -Por defecto es `false`. - -#### Devuelve {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crea la propiedad .stack en un objeto objetivo - -#### Parámetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Devuelve {#returns} - -`void` - -#### Heredado de {#inherited-from} - -```ts -Error.captureStackTrace -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index db3ef51..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# Clase: MCPAuthTokenVerificationError - -Error lanzado cuando hay un problema al verificar tokens. - -## Hereda de {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructores {#constructors} - -### Constructor {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### Parámetros {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### Devuelve {#returns} - -`MCPAuthTokenVerificationError` - -#### Sobrescribe {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propiedades {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -El código de error en formato snake_case. - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### Sobrescribe {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescritura opcional para formatear los stack traces - -#### Parámetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Devuelve {#returns} - -`any` - -#### Ver {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convierte el error a un formato JSON apto para respuestas HTTP. - -#### Parámetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indica si se debe incluir la causa del error en la respuesta JSON. -Por defecto es `false`. - -#### Devuelve {#returns} - -`Record`\<`string`, `unknown`\> - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crea la propiedad .stack en un objeto objetivo - -#### Parámetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Devuelve {#returns} - -`void` - -#### Heredado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md deleted file mode 100644 index 6e455a2..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# Función: createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -Crea una función para verificar tokens de acceso JWT (Access tokens) utilizando la función de recuperación de clave proporcionada y opciones. - -## Parámetros {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -La función para recuperar la clave utilizada para verificar el JWT. - -**Ver** - -JWTVerifyGetKey para la definición de tipo de la función de recuperación de clave. - -### options? {#options} - -`JWTVerifyOptions` - -Opciones opcionales de verificación de JWT. - -**Ver** - -JWTVerifyOptions para la definición de tipo de las opciones. - -## Retorna {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -Una función que verifica tokens de acceso JWT (Access tokens) y retorna un objeto AuthInfo si el token es válido. Requiere que el JWT contenga los campos `iss`, `client_id` y `sub` en su payload, y opcionalmente puede contener los campos `scope` o `scopes`. La función utiliza la librería `jose` internamente para realizar la verificación del JWT. - -## Ver {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para la definición de tipo de la función retornada. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md deleted file mode 100644 index 51cc618..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -sidebar_label: fetchServerConfig ---- - -# Función: fetchServerConfig() - -```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; -``` - -Obtiene la configuración del servidor según el emisor (Issuer) y el tipo de servidor de autorización (Authorization). - -Esta función determina automáticamente la URL well-known en función del tipo de servidor, ya que los servidores OAuth y OpenID Connect tienen convenciones diferentes para sus endpoints de metadatos. - -## Parámetros {#parameters} - -### issuer {#issuer} - -`string` - -La URL del emisor (Issuer) del servidor de autorización (Authorization). - -### config {#config} - -`ServerMetadataConfig` - -El objeto de configuración que contiene el tipo de servidor y una función de transpilación opcional. - -## Devuelve {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -Una promesa que se resuelve con la configuración estática del servidor y los metadatos obtenidos. - -## Ver también {#see} - - - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) para la implementación subyacente. - - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) para la especificación de metadatos del servidor de autorización OAuth 2.0 (Authorization). - - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) para la especificación de descubrimiento de OpenID Connect. - -## Ejemplo {#example} - -```ts -import { fetchServerConfig } from 'mcp-auth'; -// Obtener la configuración del servidor OAuth -// Esto obtendrá los metadatos de `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` -const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); - -// Obtener la configuración del servidor OpenID Connect -// Esto obtendrá los metadatos de `https://auth.logto.io/oidc/.well-known/openid-configuration` -const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); -``` - -## Lanza {#throws} - -si la operación de obtención falla. - -## Lanza {#throws} - -si los metadatos del servidor son inválidos o no coinciden con la especificación MCP. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md deleted file mode 100644 index 507ecd3..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: fetchServerConfigByWellKnownUrl ---- - -# Función: fetchServerConfigByWellKnownUrl() - -```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; -``` - -Obtiene la configuración del servidor desde la URL well-known proporcionada y la valida según la especificación MCP. - -Si los metadatos del servidor no se ajustan al esquema esperado, pero estás seguro de que son compatibles, puedes definir una función `transpileData` para transformar los metadatos al formato esperado. - -## Parámetros {#parameters} - -### wellKnownUrl {#wellknownurl} - -La URL well-known desde la cual obtener la configuración del servidor. Puede ser una cadena de texto o un objeto URL. - -`string` | `URL` - -### config {#config} - -`ServerMetadataConfig` - -El objeto de configuración que contiene el tipo de servidor y una función opcional de transpile. - -## Devuelve {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -Una promesa que se resuelve con la configuración estática del servidor junto con los metadatos obtenidos. - -## Lanza {#throws} - -si la operación de obtención falla. - -## Lanza {#throws} - -si los metadatos del servidor son inválidos o no cumplen con la especificación MCP. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md deleted file mode 100644 index eaf9c00..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# Función: getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -Obtiene la URL del emisor (Issuer) desde una configuración de servidor de autenticación. - -- Configuración resuelta: extrae de `metadata.issuer` -- Configuración de descubrimiento: devuelve `issuer` directamente - -## Parámetros {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## Devuelve {#returns} - -`string` \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md deleted file mode 100644 index 29d778a..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# Función: handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -Crea una función middleware para manejar la autenticación Bearer en una aplicación Express. - -Este middleware extrae el token Bearer del encabezado `Authorization`, lo verifica usando la función -`verifyAccessToken` proporcionada y comprueba el emisor (Issuer), la audiencia (Audience) y los alcances (Scopes) requeridos. - -- Si el token es válido, añade la información de autenticación al campo `request.auth`; -si no, responde con un mensaje de error apropiado. -- Si la verificación del token de acceso (Access token) falla, responde con un error 401 No autorizado. -- Si el token no tiene los alcances (Scopes) requeridos, responde con un error 403 Prohibido. -- Si ocurren errores inesperados durante el proceso de autenticación (Authentication), el middleware los volverá a lanzar. - -**Nota:** El objeto `request.auth` contendrá campos extendidos en comparación con la interfaz estándar -AuthInfo definida en el módulo `@modelcontextprotocol/sdk`. Consulta la interfaz extendida en este archivo para más detalles. - -## Parámetros {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Configuración para el manejador de autenticación Bearer. - -## Retorna {#returns} - -`RequestHandler` - -Una función middleware para Express que maneja la autenticación Bearer. - -## Consulta {#see} - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para las opciones de configuración. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md deleted file mode 100644 index 4b6c772..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerConfig ---- - -# Alias de tipo: AuthServerConfig - -```ts -type AuthServerConfig = - | ResolvedAuthServerConfig - | AuthServerDiscoveryConfig; -``` - -Configuración para el servidor de autorización remoto integrado con el servidor MCP. - -Puede ser: -- **Resuelto**: Contiene `metadata` - no se necesita solicitud de red -- **Descubrimiento**: Contiene solo `issuer` y `type` - los metadatos se obtienen bajo demanda mediante descubrimiento \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index eb9b91f..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# Alias de tipo: AuthServerConfigError - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -Representa un error que ocurre durante la validación de los metadatos del servidor de autorización (authorization server). - -## Propiedades {#properties} - -### cause? {#cause} - -```ts -optional cause: Error; -``` - -Una causa opcional del error, típicamente una instancia de `Error` que proporciona más contexto. - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -El código que representa el error de validación específico. - -*** - -### description {#description} - -```ts -description: string; -``` - -Una descripción legible para humanos del error. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index 8ff6e61..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# Alias de tipo: AuthServerConfigErrorCode - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -Los códigos para los errores que pueden ocurrir al validar los metadatos del servidor de autorización. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index b2f60ad..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# Alias de tipo: AuthServerConfigWarning - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -Representa una advertencia que ocurre durante la validación de los metadatos del servidor de autorización (authorization server). - -## Propiedades {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -El código que representa la advertencia de validación específica. - -*** - -### description {#description} - -```ts -description: string; -``` - -Una descripción legible para humanos de la advertencia. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index a55f500..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# Alias de tipo: AuthServerConfigWarningCode - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -Los códigos para advertencias que pueden ocurrir al validar los metadatos del servidor de autorización (authorization server metadata). \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md deleted file mode 100644 index 555732b..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -sidebar_label: AuthServerDiscoveryConfig ---- - -# Alias de tipo: AuthServerDiscoveryConfig - -```ts -type AuthServerDiscoveryConfig = { - issuer: string; - type: AuthServerType; -}; -``` - -Configuración de descubrimiento para el servidor de autorización remoto. - -Utiliza esto cuando quieras que los metadatos se obtengan bajo demanda mediante descubrimiento la primera vez que se necesiten. -Esto es útil para entornos edge como Cloudflare Workers donde no se permite el fetch asíncrono a nivel superior. - -## Ejemplo {#example} - -```typescript -const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, - }, -}); -``` - -## Propiedades {#properties} - -### issuer {#issuer} - -```ts -issuer: string; -``` - -La URL del emisor (Issuer) del servidor de autorización. Los metadatos se obtendrán del -endpoint well-known derivado de este emisor. - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -El tipo del servidor de autorización. - -#### Ver {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) para los valores posibles. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md deleted file mode 100644 index 98ed927..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: AuthServerErrorCode ---- - -# Alias de tipo: AuthServerErrorCode - -```ts -type AuthServerErrorCode = - | "invalid_server_metadata" - | "invalid_server_config" - | "missing_jwks_uri"; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index e251a2a..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# Alias de tipo: ~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -Configuración para el modo de servidor de autorización heredado, MCP. - -## Obsoleto {#deprecated} - -Utiliza la configuración `ResourceServerModeConfig` en su lugar. - -## Propiedades {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -La configuración del único servidor de autorización. - -#### Obsoleto {#deprecated} - -Utiliza la configuración `protectedResources` en su lugar. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index 4a6ba45..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# Alias de tipo: AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -Los códigos para la validación exitosa de los metadatos del servidor de autorización. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md deleted file mode 100644 index 9b36c07..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerType ---- - -# Alias de tipo: AuthServerType - -```ts -type AuthServerType = "oauth" | "oidc"; -``` - -El tipo del servidor de autorización (authorization server). Esta información debe ser proporcionada por la configuración del servidor y señala si el servidor es un servidor de autorización OAuth 2.0 o OpenID Connect (OIDC). \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index d31d596..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: AuthorizationServerMetadata ---- - -# Alias de tipo: AuthorizationServerMetadata - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -Esquema para los metadatos del servidor de Autorización (Authorization) OAuth 2.0 según lo definido en la RFC 8414. - -## Ver {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index 346a556..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# Alias de tipo: BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## Propiedades {#properties} - -### audience? {#audience} - -```ts -optional audience: string; -``` - -La audiencia esperada del token de acceso (reclamo `aud`). Normalmente, este es el servidor de recursos (API) para el que está destinado el token. Si no se proporciona, se omitirá la verificación de audiencia. - -**Nota:** Si tu servidor de autorización no admite Indicadores de recurso (RFC 8707), puedes omitir este campo ya que la audiencia puede no ser relevante. - -#### Ver {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -Una cadena que representa un emisor válido, o una función para validar el emisor del token de acceso. - -Si se proporciona una cadena, se usará como el valor de emisor esperado para la comparación directa. - -Si se proporciona una función, debe validar el emisor según las reglas en -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md). - -#### Ver {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) para más detalles sobre la función de validación. - -*** - -### requiredScopes? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -Un arreglo de alcances requeridos (scopes) que el token de acceso debe tener. Si el token no contiene todos estos alcances, se lanzará un error. - -**Nota:** El manejador verificará el reclamo `scope` en el token, que puede ser una cadena separada por espacios o un arreglo de cadenas, dependiendo de la implementación del servidor de autorización. Si el reclamo `scope` no está presente, el manejador verificará el reclamo `scopes` si está disponible. - -*** - -### resource? {#resource} - -```ts -optional resource: string; -``` - -El identificador del recurso protegido. Cuando se proporciona, el manejador usará los servidores de autorización configurados para este recurso para validar el token recibido. Es obligatorio cuando se utiliza el manejador con una configuración de `protectedResources`. - -*** - -### showErrorDetails? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -Indica si se debe mostrar información detallada de errores en la respuesta. Esto es útil para depuración durante el desarrollo, pero debe deshabilitarse en producción para evitar la filtración de información sensible. - -#### Valor predeterminado {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -Tipo de función para verificar un token de acceso. - -Esta función debe lanzar un [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) si el token es inválido, o devolver un objeto AuthInfo si el token es válido. - -#### Ver {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para más detalles. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index f752c9f..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# Alias de tipo: BearerAuthErrorCode - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index 80c3228..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# Alias de tipo: CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -La versión en camelCase del tipo de metadatos del servidor de autorización OAuth 2.0. - -## Ver también {#see} - -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) para el tipo original y la información de los campos. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index aa10df1..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# Alias de tipo: CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -La versión en camelCase del tipo de metadatos de recurso protegido de OAuth 2.0. - -## Ver también {#see} - -[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) para el tipo original e información de los campos. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index c215b31..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# Alias de tipo: MCPAuthBearerAuthErrorDetails - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## Propiedades {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md deleted file mode 100644 index 147a991..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -sidebar_label: MCPAuthConfig ---- - -# Alias de tipo: MCPAuthConfig - -```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; -``` - -Configuración para la clase [MCPAuth](/references/js/classes/MCPAuth.md), compatible con un único `servidor de autorización` heredado o la configuración de `servidor de recursos`. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index 58f095e..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# Alias de tipo: MCPAuthTokenVerificationErrorCode (Type Alias: MCPAuthTokenVerificationErrorCode) - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index 6f1ddec..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# Alias de tipo: ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -Esquema para los metadatos de recursos protegidos de OAuth 2.0. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md deleted file mode 100644 index 4be631b..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -sidebar_label: ResolvedAuthServerConfig ---- - -# Alias de tipo: ResolvedAuthServerConfig - -```ts -type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; -``` - -Configuración resuelta para el servidor de autorización remoto con metadatos. - -Utiliza esto cuando los metadatos ya estén disponibles, ya sea codificados directamente o recuperados previamente -a través de `fetchServerConfig()`. - -## Propiedades {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -Los metadatos del servidor de autorización (authorization server), que deben cumplir con la especificación MCP -(basada en los metadatos del servidor de autorización OAuth 2.0). - -Estos metadatos normalmente se obtienen del endpoint well-known del servidor (metadatos del servidor de autorización OAuth 2.0 -u OpenID Connect Discovery); también se pueden proporcionar directamente en la configuración si el servidor no admite dichos endpoints. - -**Nota:** Los metadatos deben estar en formato camelCase según lo preferido por la librería mcp-auth. - -#### Ver {#see} - - - [Metadatos del servidor de autorización OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -El tipo de servidor de autorización (authorization server). - -#### Ver {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) para los valores posibles. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index 7760029..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# Alias de tipo: ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -Configuración para el servidor MCP en modo servidor de recursos. - -## Propiedades {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -Una sola configuración de servidor de recursos o un arreglo de ellas. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index 0b59d23..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# Alias de tipo: ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -Tipo de función para validar el emisor (Issuer) del token de acceso (Access token). - -Esta función debe lanzar un [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) con el código 'invalid_issuer' si el emisor -no es válido. El emisor debe validarse contra: - -1. Los servidores de autorización configurados en los metadatos del servidor de autenticación de MCP-Auth -2. Los servidores de autorización listados en los metadatos del recurso protegido - -## Parámetros {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## Devuelve {#returns} - -`void` - -## Lanza {#throws} - -Cuando el emisor (Issuer) no es reconocido o es inválido. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index cbd21bd..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# Alias de tipo: VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -Tipo de función para verificar un token de acceso (Access token). - -Esta función debe lanzar un [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) si el token es inválido, -o devolver un objeto AuthInfo si el token es válido. - -Por ejemplo, si tienes una función de verificación de JWT, al menos debe comprobar la -firma del token, validar su expiración y extraer los reclamos (Claims) necesarios para devolver un objeto `AuthInfo`. - -**Nota:** No es necesario verificar los siguientes campos en el token, ya que serán comprobados -por el manejador: - -- `iss` (emisor / issuer) -- `aud` (audiencia / audience) -- `scope` (alcances / scopes) - -## Parámetros {#parameters} - -### token {#token} - -`string` - -La cadena del token de acceso (Access token) a verificar. - -## Devuelve {#returns} - -`MaybePromise`\<`AuthInfo`\> - -Una promesa que resuelve en un objeto AuthInfo o un valor síncrono si el -token es válido. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index 6e88a1a..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# Alias de tipo: VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -Los modos de verificación integrados admitidos por `bearerAuth`. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md deleted file mode 100644 index b4726e8..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: authServerErrorDescription ---- - -# Variable: authServerErrorDescription - -```ts -const authServerErrorDescription: Readonly>; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index b6ebc17..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# Variable: authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -Esquema Zod para los metadatos del Servidor de Autorización OAuth 2.0 según lo definido en RFC 8414. - -## Ver {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index ed1a931..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# Variable: bearerAuthErrorDescription - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index d6f27f7..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# Variable: camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -La versión en camelCase del esquema Zod de metadatos del servidor de autorización OAuth 2.0. - -## Ver {#see} - -[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) para el esquema original e información de los campos. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index 09b6e9d..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# Variable: camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -La versión en camelCase del esquema Zod de metadatos de recursos protegidos de OAuth 2.0. - -## Ver {#see} - -[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) para el esquema original e información de los campos. \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md deleted file mode 100644 index c29ea72..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# Variable: defaultValues - -```ts -const defaultValues: Readonly>; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index 2baee5f..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# Variable: protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -Esquema Zod para los metadatos de recursos protegidos de OAuth 2.0 (OAuth 2.0 Protected Resource Metadata). \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md deleted file mode 100644 index 68cbf41..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: serverMetadataPaths ---- - -# Variable: serverMetadataPaths - -```ts -const serverMetadataPaths: Readonly<{ - oauth: "/.well-known/oauth-authorization-server"; - oidc: "/.well-known/openid-configuration"; -}>; -``` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index b0004b3..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: tokenVerificationErrorDescription ---- - -# Variable: tokenVerificationErrorDescription - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` \ No newline at end of file diff --git a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md deleted file mode 100644 index e60de41..0000000 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# Variable: validateServerConfig - -```ts -const validateServerConfig: ValidateServerConfig; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md deleted file mode 100644 index c8ed099..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -sidebar_label: SDK Node.js ---- - -# Référence du SDK MCP Auth Node.js - -## Classes {#classes} - -- [MCPAuth](/references/js/classes/MCPAuth.md) -- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) -- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) -- [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) - -## Alias de types {#type-aliases} - -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) -- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) -- [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) -- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) -- [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) -- [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) - -## Variables {#variables} - -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) -- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) -- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) - -## Fonctions {#functions} - -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) -- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) -- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md deleted file mode 100644 index 8e70140..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -sidebar_label: MCPAuth ---- - -# Classe : MCPAuth - -La classe principale de la bibliothèque mcp-auth. Elle agit comme une fabrique et un registre pour créer des politiques d'authentification pour vos ressources protégées. - -Elle est initialisée avec les configurations de votre serveur et fournit une méthode `bearerAuth` pour générer un middleware Express pour l'authentification basée sur les jetons. - -## Exemple {#example} - -### Utilisation en mode `resource server` {#usage-in-resource-server-mode} - -C'est l'approche recommandée pour les nouvelles applications. - -#### Option 1 : Configuration par découverte (recommandée pour les runtimes edge) {#option-1-discovery-config-recommended-for-edge-runtimes} - -Utilisez cette option lorsque vous souhaitez que les métadonnées soient récupérées à la demande. Ceci est particulièrement utile pour les runtimes edge comme Cloudflare Workers où la récupération asynchrone au niveau supérieur n'est pas autorisée. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // Passez simplement l'issuer et le type - les métadonnées seront récupérées lors de la première requête - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Option 2 : Configuration résolue (métadonnées pré-récupérées) {#option-2-resolved-config-pre-fetched-metadata} - -Utilisez cette option lorsque vous souhaitez récupérer et valider les métadonnées au démarrage. - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Utilisation du middleware {#using-the-middleware} - -```ts -// Montez le routeur pour gérer les métadonnées des ressources protégées -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// Protégez un endpoint API pour la ressource configurée -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // Spécifiez à quelle ressource appartient ce endpoint - audience: resourceIdentifier, // Optionnellement, validez la revendication 'aud' - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - }, -); -``` - -### Utilisation héritée en mode `authorization server` (Obsolète) {#legacy-usage-in-authorization-server-mode-deprecated} - -Cette approche est prise en charge pour la rétrocompatibilité. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth = new MCPAuth({ - // Configuration par découverte - métadonnées récupérées à la demande - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, -}); - -// Montez le routeur pour gérer les métadonnées héritées du serveur d'autorisation -app.use(mcpAuth.delegatedRouter()); - -// Protégez un endpoint en utilisant la politique par défaut -app.get( - '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // Gérez ici la requête MCP - }, -); -``` - -## Constructeurs {#constructors} - -### Constructeur {#constructor} - -```ts -new MCPAuth(config: MCPAuthConfig): MCPAuth; -``` - -Crée une instance de MCPAuth. -Elle valide toute la configuration en amont pour échouer rapidement en cas d'erreur. - -#### Paramètres {#parameters} - -##### config {#config} - -[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) - -La configuration d'authentification. - -#### Retourne {#returns} - -`MCPAuth` - -## Propriétés {#properties} - -### config {#config} - -```ts -readonly config: MCPAuthConfig; -``` - -La configuration d'authentification. - -## Méthodes {#methods} - -### bearerAuth() {#bearerauth} - -#### Signature d'appel {#call-signature} - -```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; -``` - -Crée un gestionnaire d'authentification Bearer (middleware Express) qui vérifie le jeton d’accès (Access token) dans l'en-tête `Authorization` de la requête. - -##### Paramètres {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -Une fonction qui vérifie le jeton d’accès (Access token). Elle doit accepter le jeton d’accès (Access token) sous forme de chaîne et retourner une promesse (ou une valeur) qui se résout avec le résultat de la vérification. - -**Voir** - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) pour la définition du type de la fonction `verifyAccessToken`. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> - -Configuration optionnelle pour le gestionnaire d'authentification Bearer. - -**Voir** - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) pour les options de configuration disponibles (à l'exclusion de `verifyAccessToken` et `issuer`). - -##### Retourne {#returns} - -`RequestHandler` - -Une fonction middleware Express qui vérifie le jeton d’accès (Access token) et ajoute le résultat de la vérification à l'objet requête (`req.auth`). - -##### Voir {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) pour les détails d'implémentation et les types étendus de l'objet `req.auth` (`AuthInfo`). - -#### Signature d'appel {#call-signature} - -```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; -``` - -Crée un gestionnaire d'authentification Bearer (middleware Express) qui vérifie le jeton d’accès (Access token) dans l'en-tête `Authorization` de la requête en utilisant un mode de vérification prédéfini. - -En mode `'jwt'`, le gestionnaire créera une fonction de vérification JWT en utilisant le JWK Set de l'URI JWKS du serveur d'autorisation. - -##### Paramètres {#parameters} - -###### mode {#mode} - -`"jwt"` - -Le mode de vérification pour le jeton d’accès (Access token). Actuellement, seul 'jwt' est pris en charge. - -**Voir** - -[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) pour les modes disponibles. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` - -Configuration optionnelle pour le gestionnaire d'authentification Bearer, incluant les options de vérification JWT et les options du JWK Set distant. - -**Voir** - - - VerifyJwtConfig pour les options de configuration disponibles pour la vérification JWT. - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) pour les options de configuration disponibles (à l'exclusion de `verifyAccessToken` et `issuer`). - -##### Retourne {#returns} - -`RequestHandler` - -Une fonction middleware Express qui vérifie le jeton d’accès (Access token) et ajoute le résultat de la vérification à l'objet requête (`req.auth`). - -##### Voir {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) pour les détails d'implémentation et les types étendus de l'objet `req.auth` (`AuthInfo`). - -##### Lève {#throws} - -si l'URI JWKS n'est pas fourni dans les métadonnées du serveur lors de l'utilisation du mode `'jwt'`. - -*** - -### ~~delegatedRouter()~~ {#delegatedrouter} - -```ts -delegatedRouter(): Router; -``` - -Crée un routeur délégué pour servir l'endpoint hérité des métadonnées du serveur d'autorisation OAuth 2.0 (`/.well-known/oauth-authorization-server`) avec les métadonnées fournies à l'instance. - -#### Retourne {#returns} - -`Router` - -Un routeur qui sert l'endpoint des métadonnées du serveur d'autorisation OAuth 2.0 avec les métadonnées fournies à l'instance. - -#### Obsolète {#deprecated} - -Utilisez [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) à la place. - -#### Exemple {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth: MCPAuth; // Supposons que ceci est initialisé -app.use(mcpAuth.delegatedRouter()); -``` - -#### Lève {#throws} - -Si appelé en mode `resource server`. - -*** - -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} - -```ts -protectedResourceMetadataRouter(): Router; -``` - -Crée un routeur qui sert l'endpoint OAuth 2.0 des métadonnées des ressources protégées pour toutes les ressources configurées. - -Ce routeur crée automatiquement les bons endpoints `.well-known` pour chaque identifiant de ressource fourni dans votre configuration. - -#### Retourne {#returns} - -`Router` - -Un routeur qui sert l'endpoint OAuth 2.0 des métadonnées des ressources protégées. - -#### Lève {#throws} - -Si appelé en mode `authorization server`. - -#### Exemple {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// Supposons que mcpAuth est initialisé avec une ou plusieurs configurations `protectedResources` -const mcpAuth: MCPAuth; -const app = express(); - -// Ceci servira les métadonnées à `/.well-known/oauth-protected-resource/...` -// en fonction de vos identifiants de ressources. -app.use(mcpAuth.protectedResourceMetadataRouter()); -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md deleted file mode 100644 index d8c5193..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthAuthServerError ---- - -# Classe : MCPAuthAuthServerError - -Erreur levée lorsqu'il y a un problème avec le serveur d’autorisation distant. - -## Hérite de {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructeurs {#constructors} - -### Constructeur {#constructor} - -```ts -new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; -``` - -#### Paramètres {#parameters} - -##### code {#code} - -[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) - -##### cause ? {#cause} - -`unknown` - -#### Retourne {#returns} - -`MCPAuthAuthServerError` - -#### Redéfinit {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propriétés {#properties} - -### cause ? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: AuthServerErrorCode; -``` - -Le code d’erreur au format snake_case. - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthAuthServerError'; -``` - -#### Redéfinit {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack ? {#stack} - -```ts -optional stack: string; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace() ? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Surcharge optionnelle pour le formatage des traces de pile - -#### Paramètres {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retourne {#returns} - -`any` - -#### Voir {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Méthodes {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convertit l’erreur au format JSON adapté à une réponse HTTP. - -#### Paramètres {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indique s’il faut inclure la cause de l’erreur dans la réponse JSON. -Par défaut à `false`. - -#### Retourne {#returns} - -`Record`\<`string`, `unknown`\> - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crée la propriété .stack sur un objet cible - -#### Paramètres {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt ? {#constructoropt} - -`Function` - -#### Retourne {#returns} - -`void` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index 004d87a..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# Classe : MCPAuthBearerAuthError - -Erreur levée lorsqu'il y a un problème lors de l'authentification avec des jetons Bearer. - -## Hérite de {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructeurs {#constructors} - -### Constructeur {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### Paramètres {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause ? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### Retourne {#returns} - -`MCPAuthBearerAuthError` - -#### Redéfinit {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propriétés {#properties} - -### cause ? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -Le code d'erreur au format snake_case. - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### Redéfinit {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack ? {#stack} - -```ts -optional stack: string; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace() ? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Surcharge optionnelle pour formater les traces de pile - -#### Paramètres {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retourne {#returns} - -`any` - -#### Voir {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Méthodes {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convertit l'erreur en un format JSON adapté à une réponse HTTP. - -#### Paramètres {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. -Par défaut à `false`. - -#### Retourne {#returns} - -`Record`\<`string`, `unknown`\> - -#### Redéfinit {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crée la propriété .stack sur un objet cible - -#### Paramètres {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt ? {#constructoropt} - -`Function` - -#### Retourne {#returns} - -`void` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md deleted file mode 100644 index 53ce46b..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebar_label: MCPAuthConfigError ---- - -# Classe : MCPAuthConfigError - -Erreur levée lorsqu'il y a un problème de configuration avec mcp-auth. - -## Hérite de {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructeurs {#constructors} - -### Constructeur {#constructor} - -```ts -new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; -``` - -#### Paramètres {#parameters} - -##### code {#code} - -`string` - -Le code d'erreur au format snake_case. - -##### message {#message} - -`string` - -Une description lisible par l'humain de l'erreur. - -#### Retourne {#returns} - -`MCPAuthConfigError` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propriétés {#properties} - -### cause ? {#cause} - -```ts -optional cause: unknown; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -Le code d'erreur au format snake_case. - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthConfigError'; -``` - -#### Redéfinit {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack ? {#stack} - -```ts -optional stack: string; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace() ? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Surcharge optionnelle pour formater les traces de pile - -#### Paramètres {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retourne {#returns} - -`any` - -#### Voir {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Méthodes {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convertit l'erreur en un format JSON adapté à une réponse HTTP. - -#### Paramètres {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. -Par défaut à `false`. - -#### Retourne {#returns} - -`Record`\<`string`, `unknown`\> - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crée la propriété .stack sur un objet cible - -#### Paramètres {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt ? {#constructoropt} - -`Function` - -#### Retourne {#returns} - -`void` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md deleted file mode 100644 index 2ffb784..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -sidebar_label: MCPAuthError ---- - -# Classe : MCPAuthError - -Classe de base pour toutes les erreurs mcp-auth. - -Elle fournit un moyen standardisé de gérer les erreurs liées à l’authentification (Authentication) et à l’autorisation (Authorization) MCP. - -## Hérite de {#extends} - -- `Error` - -## Étendue par {#extended-by} - -- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) -- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) - -## Constructeurs {#constructors} - -### Constructeur {#constructor} - -```ts -new MCPAuthError(code: string, message: string): MCPAuthError; -``` - -#### Paramètres {#parameters} - -##### code {#code} - -`string` - -Le code d’erreur au format snake_case. - -##### message {#message} - -`string` - -Une description lisible de l’erreur. - -#### Retourne {#returns} - -`MCPAuthError` - -#### Redéfinit {#overrides} - -```ts -Error.constructor -``` - -## Propriétés {#properties} - -### cause ? {#cause} - -```ts -optional cause: unknown; -``` - -#### Hérité de {#inherited-from} - -```ts -Error.cause -``` - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -Le code d’erreur au format snake_case. - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Hérité de {#inherited-from} - -```ts -Error.message -``` - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthError'; -``` - -#### Redéfinit {#overrides} - -```ts -Error.name -``` - -*** - -### stack ? {#stack} - -```ts -optional stack: string; -``` - -#### Hérité de {#inherited-from} - -```ts -Error.stack -``` - -*** - -### prepareStackTrace() ? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Surcharge optionnelle pour le formatage des traces de pile - -#### Paramètres {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retourne {#returns} - -`any` - -#### Voir {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Hérité de {#inherited-from} - -```ts -Error.prepareStackTrace -``` - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Hérité de {#inherited-from} - -```ts -Error.stackTraceLimit -``` - -## Méthodes {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convertit l’erreur en un format JSON adapté à une réponse HTTP. - -#### Paramètres {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indique s’il faut inclure la cause de l’erreur dans la réponse JSON. -Par défaut à `false`. - -#### Retourne {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crée la propriété .stack sur un objet cible - -#### Paramètres {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt ? {#constructoropt} - -`Function` - -#### Retourne {#returns} - -`void` - -#### Hérité de {#inherited-from} - -```ts -Error.captureStackTrace -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index 15c4842..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# Classe : MCPAuthTokenVerificationError - -Erreur levée lorsqu'il y a un problème lors de la vérification des jetons. - -## Hérite de {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Constructeurs {#constructors} - -### Constructeur {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### Paramètres {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause ? {#cause} - -`unknown` - -#### Retourne {#returns} - -`MCPAuthTokenVerificationError` - -#### Redéfinit {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propriétés {#properties} - -### cause ? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -Le code d'erreur au format snake_case. - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### Redéfinit {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack ? {#stack} - -```ts -optional stack: string; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace() ? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Surcharge optionnelle pour le formatage des traces de pile - -#### Paramètres {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retourne {#returns} - -`any` - -#### Voir {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Méthodes {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Convertit l'erreur en un format JSON adapté à une réponse HTTP. - -#### Paramètres {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. -La valeur par défaut est `false`. - -#### Retourne {#returns} - -`Record`\<`string`, `unknown`\> - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Crée la propriété .stack sur un objet cible - -#### Paramètres {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt ? {#constructoropt} - -`Function` - -#### Retourne {#returns} - -`void` - -#### Hérité de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md deleted file mode 100644 index 1b01722..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# Fonction : createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -Crée une fonction pour vérifier les jetons d’accès JWT (Access token) en utilisant la fonction de récupération de clé fournie et les options. - -## Paramètres {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -La fonction permettant de récupérer la clé utilisée pour vérifier le JWT. - -**Voir** - -JWTVerifyGetKey pour la définition du type de la fonction de récupération de clé. - -### options? {#options} - -`JWTVerifyOptions` - -Options facultatives de vérification du JWT. - -**Voir** - -JWTVerifyOptions pour la définition du type des options. - -## Retourne {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -Une fonction qui vérifie les jetons d’accès JWT (Access token) et retourne un objet AuthInfo si le jeton est valide. Elle exige que le JWT contienne les champs `iss`, `client_id` et `sub` dans sa charge utile, et peut éventuellement contenir les champs `scope` ou `scopes`. La fonction utilise la bibliothèque `jose` en interne pour effectuer la vérification du JWT. - -## Voir {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) pour la définition du type de la fonction retournée. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md deleted file mode 100644 index 9021caa..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -sidebar_label: fetchServerConfig ---- - -# Fonction : fetchServerConfig() - -```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; -``` - -Récupère la configuration du serveur selon l’émetteur (Issuer) et le type de serveur d’autorisation (Authorization). - -Cette fonction détermine automatiquement l’URL well-known en fonction du type de serveur, car les serveurs OAuth et OpenID Connect ont des conventions différentes pour leurs points de terminaison de métadonnées. - -## Paramètres {#parameters} - -### issuer {#issuer} - -`string` - -L’URL de l’émetteur (Issuer) du serveur d’autorisation (Authorization). - -### config {#config} - -`ServerMetadataConfig` - -L’objet de configuration contenant le type de serveur et une fonction de transpilation optionnelle. - -## Retourne {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -Une promesse qui se résout avec la configuration statique du serveur et les métadonnées récupérées. - -## Voir aussi {#see} - - - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) pour l’implémentation sous-jacente. - - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) pour la spécification OAuth 2.0 Authorization Server Metadata. - - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) pour la spécification OpenID Connect Discovery. - -## Exemple {#example} - -```ts -import { fetchServerConfig } from 'mcp-auth'; -// Récupération de la configuration du serveur OAuth -// Cela va récupérer les métadonnées depuis `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` -const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); - -// Récupération de la configuration du serveur OpenID Connect -// Cela va récupérer les métadonnées depuis `https://auth.logto.io/oidc/.well-known/openid-configuration` -const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); -``` - -## Exceptions {#throws} - -si l’opération de récupération échoue. - -## Exceptions {#throws} - -si les métadonnées du serveur sont invalides ou ne correspondent pas à la spécification MCP. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md deleted file mode 100644 index 7d534c0..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: fetchServerConfigByWellKnownUrl ---- - -# Fonction : fetchServerConfigByWellKnownUrl() - -```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; -``` - -Récupère la configuration du serveur à partir de l’URL bien connue fournie et la valide selon la spécification MCP. - -Si les métadonnées du serveur ne sont pas conformes au schéma attendu, mais que vous êtes certain qu’elles sont compatibles, vous pouvez définir une fonction `transpileData` pour transformer les métadonnées dans le format attendu. - -## Paramètres {#parameters} - -### wellKnownUrl {#wellknownurl} - -L’URL bien connue à partir de laquelle récupérer la configuration du serveur. Cela peut être une chaîne de caractères ou un objet URL. - -`string` | `URL` - -### config {#config} - -`ServerMetadataConfig` - -L’objet de configuration contenant le type de serveur et éventuellement la fonction de transpilation. - -## Retourne {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -Une promesse qui se résout avec la configuration statique du serveur et les métadonnées récupérées. - -## Déclenche une exception {#throws} - -si l’opération de récupération échoue. - -## Déclenche une exception {#throws} - -si les métadonnées du serveur sont invalides ou ne correspondent pas à la spécification MCP. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md deleted file mode 100644 index 53bdd92..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# Fonction : getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -Obtenir l’URL de l’émetteur (Issuer) à partir d’une configuration de serveur d’authentification. - -- Configuration résolue : extrait depuis `metadata.issuer` -- Configuration de découverte : retourne directement `issuer` - -## Paramètres {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## Retourne {#returns} - -`string` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md deleted file mode 100644 index 3348934..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# Fonction : handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -Crée une fonction middleware pour gérer l’authentification Bearer dans une application Express. - -Ce middleware extrait le jeton Bearer de l’en-tête `Authorization`, le vérifie à l’aide de la fonction -`verifyAccessToken` fournie, et contrôle l’issuer (Émetteur), l’audience (Audience) et les portées (Scopes) requises. - -- Si le jeton est valide, il ajoute les informations d’authentification à la propriété `request.auth` ; -sinon, il répond avec un message d’erreur approprié. -- Si la vérification du jeton d’accès (Jeton d’accès) échoue, il répond avec une erreur 401 Unauthorized. -- Si le jeton ne possède pas les portées (Portées) requises, il répond avec une erreur 403 Forbidden. -- Si des erreurs inattendues surviennent lors du processus d’authentification (Authentification), le middleware les relancera. - -**Remarque :** L’objet `request.auth` contiendra des champs étendus par rapport à l’interface standard -AuthInfo définie dans le module `@modelcontextprotocol/sdk`. Voir l’interface étendue dans ce fichier pour plus de détails. - -## Paramètres {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Configuration pour le gestionnaire d’authentification Bearer. - -## Retourne {#returns} - -`RequestHandler` - -Une fonction middleware pour Express qui gère l’authentification Bearer. - -## Voir aussi {#see} - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) pour les options de configuration. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md deleted file mode 100644 index 2aca815..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerConfig ---- - -# Alias de type : AuthServerConfig - -```ts -type AuthServerConfig = - | ResolvedAuthServerConfig - | AuthServerDiscoveryConfig; -``` - -Configuration pour le serveur d’autorisation distant intégré au serveur MCP. - -Peut être soit : -- **Résolu** : Contient `metadata` - aucune requête réseau nécessaire -- **Découverte** : Contient uniquement `issuer` et `type` - les métadonnées sont récupérées à la demande via la découverte \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index 3fa77a1..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# Alias de type : AuthServerConfigError - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -Représente une erreur qui se produit lors de la validation des métadonnées du serveur d’autorisation (Authorization server). - -## Propriétés {#properties} - -### cause ? {#cause} - -```ts -optional cause: Error; -``` - -Une cause optionnelle de l’erreur, généralement une instance de `Error` qui fournit plus de contexte. - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -Le code représentant l’erreur de validation spécifique. - -*** - -### description {#description} - -```ts -description: string; -``` - -Une description lisible par l’humain de l’erreur. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index 06ada65..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# Alias de type : AuthServerConfigErrorCode - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -Les codes des erreurs pouvant survenir lors de la validation des métadonnées du serveur d’autorisation. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index 6677393..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# Alias de type : AuthServerConfigWarning - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -Représente un avertissement qui se produit lors de la validation des métadonnées du serveur d’autorisation. - -## Propriétés {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -Le code représentant l’avertissement de validation spécifique. - -*** - -### description {#description} - -```ts -description: string; -``` - -Une description lisible par l’humain de l’avertissement. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index 375439b..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# Alias de type : AuthServerConfigWarningCode - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -Les codes des avertissements pouvant survenir lors de la validation des métadonnées du serveur d’autorisation. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md deleted file mode 100644 index 8a3820d..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -sidebar_label: AuthServerDiscoveryConfig ---- - -# Alias de type : AuthServerDiscoveryConfig - -```ts -type AuthServerDiscoveryConfig = { - issuer: string; - type: AuthServerType; -}; -``` - -Configuration de découverte pour le serveur d’autorisation distant. - -Utilisez ceci lorsque vous souhaitez que les métadonnées soient récupérées à la demande via la découverte lors de la première utilisation. -Ceci est utile pour les environnements edge comme Cloudflare Workers où l’appel asynchrone fetch au niveau supérieur n’est pas autorisé. - -## Exemple {#example} - -```typescript -const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, - }, -}); -``` - -## Propriétés {#properties} - -### issuer {#issuer} - -```ts -issuer: string; -``` - -L’URL de l’émetteur (Issuer) du serveur d’autorisation. Les métadonnées seront récupérées à partir du point de terminaison well-known dérivé de cet émetteur. - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -Le type du serveur d’autorisation (Authorization). - -#### Voir {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) pour les valeurs possibles. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md deleted file mode 100644 index 64c30a9..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: AuthServerErrorCode ---- - -# Alias de type : AuthServerErrorCode - -```ts -type AuthServerErrorCode = - | "invalid_server_metadata" - | "invalid_server_config" - | "missing_jwks_uri"; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index e58a42c..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# Alias de type : ~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -Configuration pour l'ancien serveur MCP en mode serveur d’autorisation (authorization server). - -## Obsolète {#deprecated} - -Utilisez la configuration `ResourceServerModeConfig` à la place. - -## Propriétés {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -La configuration du serveur d’autorisation (authorization server) unique. - -#### Obsolète {#deprecated} - -Utilisez la configuration `protectedResources` à la place. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index f1bcc6c..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# Alias de type : AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -Les codes pour la validation réussie des métadonnées du serveur d’autorisation. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md deleted file mode 100644 index 794cfae..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerType ---- - -# Alias de type : AuthServerType - -```ts -type AuthServerType = "oauth" | "oidc"; -``` - -Le type du serveur d’autorisation (authorization server). Cette information doit être fournie par la configuration du serveur et indique si le serveur est un serveur d’autorisation OAuth 2.0 ou OpenID Connect (OIDC). diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index 46d2e16..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: AuthorizationServerMetadata ---- - -# Alias de type : AuthorizationServerMetadata - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -Schéma pour les métadonnées du serveur d’autorisation OAuth 2.0 telles que définies dans la RFC 8414. - -## Voir aussi {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index d17bfdc..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# Alias de type : BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## Propriétés {#properties} - -### audience ? {#audience} - -```ts -optional audience: string; -``` - -L’audience attendue du jeton d’accès (Jeton d’accès (Access token)) (`aud` revendication (Claim)). Il s’agit généralement du serveur de ressources (API) auquel le jeton est destiné. Si ce champ n’est pas renseigné, la vérification de l’audience sera ignorée. - -**Remarque :** Si votre serveur d’autorisation ne prend pas en charge les indicateurs de ressource (Indicateurs de ressource (Resource indicators)) (RFC 8707), vous pouvez omettre ce champ car l’audience peut ne pas être pertinente. - -#### Voir {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -Une chaîne représentant un émetteur (Émetteur (Issuer)) valide, ou une fonction pour valider l’émetteur du jeton d’accès (Jeton d’accès (Access token)). - -Si une chaîne est fournie, elle sera utilisée comme valeur d’émetteur attendue pour une comparaison directe. - -Si une fonction est fournie, elle doit valider l’émetteur selon les règles de -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md). - -#### Voir {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) pour plus de détails sur la fonction de validation. - -*** - -### requiredScopes ? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -Un tableau des portées (Portées (Scopes)) requises que le jeton d’accès (Jeton d’accès (Access token)) doit posséder. Si le jeton ne contient pas toutes ces portées, une erreur sera levée. - -**Remarque :** Le gestionnaire vérifiera la revendication (Claim) `scope` dans le jeton, qui peut être une chaîne séparée par des espaces ou un tableau de chaînes, selon l’implémentation du serveur d’autorisation. Si la revendication `scope` n’est pas présente, le gestionnaire vérifiera la revendication `scopes` si elle est disponible. - -*** - -### resource ? {#resource} - -```ts -optional resource: string; -``` - -L’identifiant de la ressource protégée. Lorsqu’il est renseigné, le gestionnaire utilisera les serveurs d’autorisation configurés pour cette ressource afin de valider le jeton reçu. -Ce champ est requis lors de l’utilisation du gestionnaire avec une configuration `protectedResources`. - -*** - -### showErrorDetails ? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -Indique s’il faut afficher des informations détaillées sur les erreurs dans la réponse. Ceci est utile pour le débogage pendant le développement, mais doit être désactivé en production afin d’éviter de divulguer des informations sensibles. - -#### Valeur par défaut {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -Type de fonction pour vérifier un jeton d’accès (Jeton d’accès (Access token)). - -Cette fonction doit lever une [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) si le jeton est invalide, ou retourner un objet AuthInfo si le jeton est valide. - -#### Voir {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) pour plus de détails. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index 5a5207c..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# Alias de type : BearerAuthErrorCode - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index e134ac3..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# Alias de type : CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -La version camelCase du type de métadonnées du serveur d’autorisation OAuth 2.0. - -## Voir aussi {#see} - -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) pour le type original et les informations sur les champs. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index 7474b83..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# Alias de type : CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -La version camelCase du type de métadonnées de ressource protégée OAuth 2.0. - -## Voir aussi {#see} - -[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) pour le type original et les informations sur les champs. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index 74bb257..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# Alias de type : MCPAuthBearerAuthErrorDetails - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## Propriétés {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md deleted file mode 100644 index dc62bfb..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -sidebar_label: MCPAuthConfig ---- - -# Alias de type : MCPAuthConfig - -```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; -``` - -Configuration pour la classe [MCPAuth](/references/js/classes/MCPAuth.md), prenant en charge soit un unique `authorization server` hérité, soit la configuration du `resource server`. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index 083a31d..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# Alias de type : MCPAuthTokenVerificationErrorCode - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index f3879cb..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# Alias de type : ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -Schéma pour les métadonnées de ressource protégée OAuth 2.0. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md deleted file mode 100644 index dc37e49..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -sidebar_label: ResolvedAuthServerConfig ---- - -# Alias de type : ResolvedAuthServerConfig - -```ts -type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; -``` - -Configuration résolue pour le serveur d'autorisation distant avec métadonnées. - -Utilisez ceci lorsque les métadonnées sont déjà disponibles, soit codées en dur, soit récupérées au préalable -via `fetchServerConfig()`. - -## Propriétés {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -Les métadonnées du serveur d’autorisation (Authorization Server), qui doivent être conformes à la spécification MCP -(basée sur OAuth 2.0 Authorization Server Metadata). - -Ces métadonnées sont généralement récupérées à partir du point de terminaison well-known du serveur (OAuth 2.0 -Authorization Server Metadata ou OpenID Connect Discovery) ; elles peuvent également être fournies -directement dans la configuration si le serveur ne prend pas en charge de tels points de terminaison. - -**Remarque :** Les métadonnées doivent être au format camelCase comme préféré par la bibliothèque mcp-auth. - -#### Voir {#see} - - - [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -Le type du serveur d’autorisation (Authorization Server). - -#### Voir {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) pour les valeurs possibles. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index b059862..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# Alias de type : ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -Configuration pour le serveur MCP en mode serveur de ressources. - -## Propriétés {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -Une configuration unique de serveur de ressources ou un tableau de celles-ci. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index f914b90..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# Alias de type : ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -Type de fonction pour valider l’émetteur (Issuer) du jeton d’accès (Access token). - -Cette fonction doit lever une [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) avec le code 'invalid_issuer' si l’émetteur n’est pas valide. L’émetteur doit être validé par rapport à : - -1. Les serveurs d’autorisation configurés dans les métadonnées du serveur d’authentification de MCP-Auth -2. Les serveurs d’autorisation listés dans les métadonnées de la ressource protégée - -## Paramètres {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## Retourne {#returns} - -`void` - -## Exceptions {#throws} - -Lorsque l’émetteur n’est pas reconnu ou invalide. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index 9dcc1f7..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# Alias de type : VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -Type de fonction pour vérifier un jeton d’accès (Access token). - -Cette fonction doit lever une [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) si le jeton est invalide, -ou retourner un objet AuthInfo si le jeton est valide. - -Par exemple, si vous disposez d'une fonction de vérification JWT, elle doit au minimum vérifier la signature du jeton, -valider son expiration et extraire les revendications (Claims) nécessaires pour retourner un objet `AuthInfo`. - -**Remarque :** Il n'est pas nécessaire de vérifier les champs suivants dans le jeton, car ils seront contrôlés -par le gestionnaire : - -- `iss` (Émetteur (Issuer)) -- `aud` (Audience) -- `scope` (Portées (Scopes)) - -## Paramètres {#parameters} - -### token {#token} - -`string` - -La chaîne du jeton d’accès (Access token) à vérifier. - -## Retourne {#returns} - -`MaybePromise`\<`AuthInfo`\> - -Une promesse qui se résout en un objet AuthInfo ou une valeur synchrone si le -jeton est valide. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index b06a1fb..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# Alias de type : VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -Les modes de vérification intégrés pris en charge par `bearerAuth`. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md deleted file mode 100644 index 9001d1d..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: authServerErrorDescription ---- - -# Variable : authServerErrorDescription - -```ts -const authServerErrorDescription: Readonly>; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index 807e091..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# Variable : authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -Schéma Zod pour les métadonnées du serveur d’autorisation OAuth 2.0 telles que définies dans la RFC 8414. - -## Voir aussi {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index 2a5bbc0..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# Variable : bearerAuthErrorDescription - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index 7646f52..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# Variable : camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -La version camelCase du schéma Zod des métadonnées du serveur d’autorisation OAuth 2.0. - -## Voir aussi {#see} - -[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) pour le schéma original et les informations sur les champs. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index 532f586..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# Variable : camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -La version camelCase du schéma Zod OAuth 2.0 Protected Resource Metadata. - -## Voir aussi {#see} - -[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) pour le schéma original et les informations sur les champs. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md deleted file mode 100644 index ec267a0..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# Variable : defaultValues - -```ts -const defaultValues: Readonly>; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index 9e70d72..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# Variable : protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -Schéma Zod pour les métadonnées de ressource protégée OAuth 2.0. \ No newline at end of file diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md deleted file mode 100644 index 33d94c8..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: serverMetadataPaths ---- - -# Variable : serverMetadataPaths - -```ts -const serverMetadataPaths: Readonly<{ - oauth: "/.well-known/oauth-authorization-server"; - oidc: "/.well-known/openid-configuration"; -}>; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index b614049..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: tokenVerificationErrorDescription ---- - -# Variable : tokenVerificationErrorDescription - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md deleted file mode 100644 index a307d3a..0000000 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# Variable : validateServerConfig - -```ts -const validateServerConfig: ValidateServerConfig; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md deleted file mode 100644 index faca9e5..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -sidebar_label: Node.js SDK ---- - -# MCP Auth Node.js SDK リファレンス - -## クラス {#classes} - -- [MCPAuth](/references/js/classes/MCPAuth.md) -- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) -- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) -- [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) - -## 型エイリアス {#type-aliases} - -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) -- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) -- [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) -- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) -- [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) -- [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) - -## 変数 {#variables} - -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) -- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) -- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) - -## 関数 {#functions} - -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) -- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) -- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md deleted file mode 100644 index a2d24bf..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -sidebar_label: MCPAuth ---- - -# クラス: MCPAuth - -mcp-auth ライブラリのメインクラスです。保護されたリソースのための認証 (Authentication) ポリシーを作成するためのファクトリーおよびレジストリとして機能します。 - -サーバー構成で初期化され、トークンベースの認証 (Authentication) 用 Express ミドルウェアを生成する `bearerAuth` メソッドを提供します。 - -## 例 {#example} - -### `resource server` モードでの利用例 {#usage-in-resource-server-mode} - -新しいアプリケーションにはこの方法が推奨されます。 - -#### オプション 1: Discovery 設定(エッジランタイム推奨) {#option-1-discovery-config-recommended-for-edge-runtimes} - -メタデータをオンデマンドで取得したい場合に使用します。特に Cloudflare Workers のようなエッジランタイムでトップレベルの async fetch が許可されていない場合に便利です。 - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // issuer と type だけ渡せばOK。メタデータは初回リクエスト時に取得されます - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### オプション 2: Resolved 設定(メタデータを事前取得) {#option-2-resolved-config-pre-fetched-metadata} - -起動時にメタデータを取得・検証したい場合に使用します。 - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### ミドルウェアの利用 {#using-the-middleware} - -```ts -// Protected Resource Metadata を処理するルーターをマウント -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// 設定済みリソースの API エンドポイントを保護 -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // このエンドポイントが属するリソースを指定 - audience: resourceIdentifier, // 必要に応じて 'aud' クレームを検証 - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - }, -); -``` - -### レガシーな `authorization server` モードでの利用(非推奨) {#legacy-usage-in-authorization-server-mode-deprecated} - -後方互換性のためにサポートされています。 - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth = new MCPAuth({ - // Discovery 設定 - メタデータはオンデマンド取得 - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, -}); - -// レガシーな Authorization Server Metadata を処理するルーターをマウント -app.use(mcpAuth.delegatedRouter()); - -// デフォルトポリシーでエンドポイントを保護 -app.get( - '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // ここで MCP リクエストを処理 - }, -); -``` - -## コンストラクター {#constructors} - -### コンストラクター {#constructor} - -```ts -new MCPAuth(config: MCPAuthConfig): MCPAuth; -``` - -MCPAuth のインスタンスを作成します。 -エラー時にすぐ失敗できるよう、構成全体を事前に検証します。 - -#### パラメーター {#parameters} - -##### config {#config} - -[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) - -認証 (Authentication) 構成。 - -#### 戻り値 {#returns} - -`MCPAuth` - -## プロパティ {#properties} - -### config {#config} - -```ts -readonly config: MCPAuthConfig; -``` - -認証 (Authentication) 構成。 - -## メソッド {#methods} - -### bearerAuth() {#bearerauth} - -#### 呼び出しシグネチャ {#call-signature} - -```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; -``` - -リクエストの `Authorization` ヘッダー内の アクセス トークン (Access token) を検証する Bearer 認証 (Authentication) ハンドラー(Express ミドルウェア)を作成します。 - -##### パラメーター {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -アクセス トークン (Access token) を検証する関数。文字列としてアクセス トークン (Access token) を受け取り、検証結果を解決する promise(または値)を返す必要があります。 - -**参照** - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) — `verifyAccessToken` 関数の型定義。 - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> - -Bearer 認証 (Authentication) ハンドラーのためのオプション設定。 - -**参照** - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) — 利用可能な設定オプション(`verifyAccessToken` と `issuer` を除く)。 - -##### 戻り値 {#returns} - -`RequestHandler` - -アクセス トークン (Access token) を検証し、その検証結果をリクエストオブジェクト(`req.auth`)に追加する Express ミドルウェア関数。 - -##### 参照 {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) — 実装詳細および `req.auth`(`AuthInfo`)オブジェクトの拡張型。 - -#### 呼び出しシグネチャ {#call-signature} - -```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; -``` - -リクエストの `Authorization` ヘッダー内の アクセス トークン (Access token) を、事前定義された検証モードで検証する Bearer 認証 (Authentication) ハンドラー(Express ミドルウェア)を作成します。 - -`'jwt'` モードでは、認可サーバーの JWKS URI から JWK Set を使って JWT 検証関数を作成します。 - -##### パラメーター {#parameters} - -###### mode {#mode} - -`"jwt"` - -アクセス トークン (Access token) の検証モード。現在サポートされているのは 'jwt' のみです。 - -**参照** - -[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) — 利用可能なモード。 - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` - -JWT 検証オプションやリモート JWK set オプションを含む、Bearer 認証 (Authentication) ハンドラーのためのオプション設定。 - -**参照** - - - VerifyJwtConfig — JWT 検証のための利用可能な設定オプション。 - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) — 利用可能な設定オプション(`verifyAccessToken` と `issuer` を除く)。 - -##### 戻り値 {#returns} - -`RequestHandler` - -アクセス トークン (Access token) を検証し、その検証結果をリクエストオブジェクト(`req.auth`)に追加する Express ミドルウェア関数。 - -##### 参照 {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) — 実装詳細および `req.auth`(`AuthInfo`)オブジェクトの拡張型。 - -##### 例外 {#throws} - -`'jwt'` モード利用時にサーバーメタデータに JWKS URI が指定されていない場合。 - -*** - -### ~~delegatedRouter()~~ {#delegatedrouter} - -```ts -delegatedRouter(): Router; -``` - -レガシー OAuth 2.0 認可サーバーメタデータエンドポイント -(`/.well-known/oauth-authorization-server`)をインスタンスに提供されたメタデータで提供するためのデリゲートルーターを作成します。 - -#### 戻り値 {#returns} - -`Router` - -インスタンスに提供されたメタデータで OAuth 2.0 認可サーバーメタデータエンドポイントを提供するルーター。 - -#### 非推奨 {#deprecated} - -代わりに [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) を使用してください。 - -#### 例 {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth: MCPAuth; // 初期化済みと仮定 -app.use(mcpAuth.delegatedRouter()); -``` - -#### 例外 {#throws} - -`resource server` モードで呼び出された場合。 - -*** - -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} - -```ts -protectedResourceMetadataRouter(): Router; -``` - -設定されたすべてのリソースに対して OAuth 2.0 Protected Resource Metadata エンドポイントを提供するルーターを作成します。 - -このルーターは、構成で指定した各リソース識別子に基づいて、正しい `.well-known` エンドポイントを自動的に作成します。 - -#### 戻り値 {#returns} - -`Router` - -OAuth 2.0 Protected Resource Metadata エンドポイントを提供するルーター。 - -#### 例外 {#throws} - -`authorization server` モードで呼び出された場合。 - -#### 例 {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// mcpAuth が 1 つ以上の `protectedResources` 設定で初期化されていると仮定 -const mcpAuth: MCPAuth; -const app = express(); - -// 構成したリソース識別子に基づき、`/.well-known/oauth-protected-resource/...` でメタデータを提供 -app.use(mcpAuth.protectedResourceMetadataRouter()); -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md deleted file mode 100644 index 015eb65..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthAuthServerError ---- - -# クラス: MCPAuthAuthServerError - -リモート認可 (Authorization) サーバーで問題が発生した場合にスローされるエラーです。 - -## 継承 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## コンストラクター {#constructors} - -### コンストラクター {#constructor} - -```ts -new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; -``` - -#### パラメーター {#parameters} - -##### code {#code} - -[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### 戻り値 {#returns} - -`MCPAuthAuthServerError` - -#### オーバーライド {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## プロパティ {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: AuthServerErrorCode; -``` - -スネークケース形式のエラーコードです。 - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthAuthServerError'; -``` - -#### オーバーライド {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド - -#### パラメーター {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 戻り値 {#returns} - -`any` - -#### 参照 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## メソッド {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -エラーを HTTP レスポンスに適した JSON 形式に変換します。 - -#### パラメーター {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON レスポンスにエラーの原因を含めるかどうかを指定します。 -デフォルトは `false` です。 - -#### 戻り値 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -ターゲットオブジェクトに .stack プロパティを作成します - -#### パラメーター {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 戻り値 {#returns} - -`void` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index 4c805d7..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# クラス: MCPAuthBearerAuthError - -Bearer トークンによる認証 (Authentication) 時に問題が発生した場合にスローされるエラーです。 - -## 継承 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## コンストラクター {#constructors} - -### コンストラクター {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### パラメーター {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### 戻り値 {#returns} - -`MCPAuthBearerAuthError` - -#### オーバーライド {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## プロパティ {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -スネークケース形式のエラーコードです。 - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### オーバーライド {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド - -#### パラメーター {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 戻り値 {#returns} - -`any` - -#### 参照 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## メソッド {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -エラーを HTTP レスポンスに適した JSON 形式に変換します。 - -#### パラメーター {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON レスポンスにエラーの原因を含めるかどうか。 -デフォルトは `false` です。 - -#### 戻り値 {#returns} - -`Record`\<`string`, `unknown`\> - -#### オーバーライド {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -ターゲットオブジェクトに .stack プロパティを作成します - -#### パラメーター {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 戻り値 {#returns} - -`void` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md deleted file mode 100644 index 4b1f455..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebar_label: MCPAuthConfigError ---- - -# クラス: MCPAuthConfigError - -mcp-auth の設定に問題がある場合にスローされるエラーです。 - -## 継承 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## コンストラクター {#constructors} - -### コンストラクター {#constructor} - -```ts -new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; -``` - -#### パラメーター {#parameters} - -##### code {#code} - -`string` - -スネークケース形式のエラーコード。 - -##### message {#message} - -`string` - -エラーの人間が読める説明。 - -#### 戻り値 {#returns} - -`MCPAuthConfigError` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## プロパティ {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -スネークケース形式のエラーコード。 - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthConfigError'; -``` - -#### オーバーライド {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド - -#### パラメーター {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 戻り値 {#returns} - -`any` - -#### 参照 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## メソッド {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -エラーを HTTP レスポンスに適した JSON 形式に変換します。 - -#### パラメーター {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON レスポンスにエラーの原因を含めるかどうか。 -デフォルトは `false` です。 - -#### 戻り値 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -ターゲットオブジェクトに .stack プロパティを作成します - -#### パラメーター {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 戻り値 {#returns} - -`void` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md deleted file mode 100644 index 1bfd3af..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -sidebar_label: MCPAuthError ---- - -# クラス: MCPAuthError - -すべての mcp-auth エラーの基底クラスです。 - -MCP の認証 (Authentication) および認可 (Authorization) に関連するエラーを標準化された方法で処理する手段を提供します。 - -## 継承元 {#extends} - -- `Error` - -## 継承先 {#extended-by} - -- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) -- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) - -## コンストラクター {#constructors} - -### コンストラクター {#constructor} - -```ts -new MCPAuthError(code: string, message: string): MCPAuthError; -``` - -#### パラメーター {#parameters} - -##### code {#code} - -`string` - -スネークケース形式のエラーコード。 - -##### message {#message} - -`string` - -エラーの人間が読める説明。 - -#### 戻り値 {#returns} - -`MCPAuthError` - -#### オーバーライド {#overrides} - -```ts -Error.constructor -``` - -## プロパティ {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### 継承元 {#inherited-from} - -```ts -Error.cause -``` - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -スネークケース形式のエラーコード。 - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 継承元 {#inherited-from} - -```ts -Error.message -``` - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthError'; -``` - -#### オーバーライド {#overrides} - -```ts -Error.name -``` - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 継承元 {#inherited-from} - -```ts -Error.stack -``` - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド - -#### パラメーター {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 戻り値 {#returns} - -`any` - -#### 参考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 継承元 {#inherited-from} - -```ts -Error.prepareStackTrace -``` - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 継承元 {#inherited-from} - -```ts -Error.stackTraceLimit -``` - -## メソッド {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -エラーを HTTP レスポンスに適した JSON 形式に変換します。 - -#### パラメーター {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON レスポンスにエラーの原因を含めるかどうか。 -デフォルトは `false` です。 - -#### 戻り値 {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -ターゲットオブジェクトに .stack プロパティを作成します - -#### パラメーター {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 戻り値 {#returns} - -`void` - -#### 継承元 {#inherited-from} - -```ts -Error.captureStackTrace -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index 59c2c89..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# クラス: MCPAuthTokenVerificationError - -トークンの検証時に問題が発生した場合にスローされるエラーです。 - -## 継承 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## コンストラクター {#constructors} - -### コンストラクター {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### パラメーター {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### 戻り値 {#returns} - -`MCPAuthTokenVerificationError` - -#### オーバーライド {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## プロパティ {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -スネークケース形式のエラーコードです。 - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### オーバーライド {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド - -#### パラメーター {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 戻り値 {#returns} - -`any` - -#### 参考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## メソッド {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -エラーを HTTP レスポンスに適した JSON 形式に変換します。 - -#### パラメーター {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON レスポンスにエラーの原因を含めるかどうかを指定します。 -デフォルトは `false` です。 - -#### 戻り値 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -ターゲットオブジェクトに .stack プロパティを作成します - -#### パラメーター {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 戻り値 {#returns} - -`void` - -#### 継承元 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md deleted file mode 100644 index 3cf84d5..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# 関数: createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -指定されたキー取得関数およびオプションを使用して、JWT アクセス トークン (Access token) を検証する関数を作成します。 - -## パラメーター {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -JWT を検証するために使用されるキーを取得する関数。 - -**参照** - -キー取得関数の型定義については JWTVerifyGetKey を参照してください。 - -### options? {#options} - -`JWTVerifyOptions` - -オプションの JWT 検証オプション。 - -**参照** - -オプションの型定義については JWTVerifyOptions を参照してください。 - -## 戻り値 {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -JWT アクセス トークン (Access token) を検証し、トークンが有効な場合は AuthInfo オブジェクトを返す関数です。この関数は、JWT のペイロードに `iss`、`client_id`、`sub` フィールドが含まれている必要があり、オプションで `scope` または `scopes` フィールドを含めることができます。内部的には `jose` ライブラリを使用して JWT の検証を行います。 - -## 参照 {#see} - -返される関数の型定義については [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md deleted file mode 100644 index 715e3a9..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -sidebar_label: fetchServerConfig ---- - -# 関数: fetchServerConfig() - -```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; -``` - -発行者 (Issuer) と認可サーバーの種類に基づいてサーバー構成を取得します。 - -この関数はサーバーの種類に応じて自動的に well-known URL を判別します。OAuth および OpenID Connect サーバーはメタデータエンドポイントの規約が異なります。 - -## パラメーター {#parameters} - -### issuer {#issuer} - -`string` - -認可サーバーの発行者 (Issuer) URL。 - -### config {#config} - -`ServerMetadataConfig` - -サーバーの種類やオプションのトランスパイル関数を含む設定オブジェクト。 - -## 戻り値 {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -取得したメタデータを含む静的なサーバー構成を解決する Promise。 - -## 参照 {#see} - - - 基本実装については [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) を参照してください。 - - OAuth 2.0 認可サーバーメタデータ仕様については [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) を参照してください。 - - OpenID Connect Discovery 仕様については [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) を参照してください。 - -## 例 {#example} - -```ts -import { fetchServerConfig } from 'mcp-auth'; -// OAuth サーバー構成の取得 -// これは `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` からメタデータを取得します -const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); - -// OpenID Connect サーバー構成の取得 -// これは `https://auth.logto.io/oidc/.well-known/openid-configuration` からメタデータを取得します -const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); -``` - -## 例外 {#throws} - -フェッチ操作に失敗した場合にスローされます。 - -## 例外 {#throws} - -サーバーメタデータが無効、または MCP 仕様と一致しない場合にスローされます。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md deleted file mode 100644 index 66f5a27..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: fetchServerConfigByWellKnownUrl ---- - -# 関数: fetchServerConfigByWellKnownUrl() - -```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; -``` - -指定された well-known URL からサーバー構成を取得し、それを MCP 仕様に対して検証します。 - -サーバーメタデータが期待されるスキーマに準拠していない場合でも、互換性があると確信している場合は、`transpileData` 関数を定義してメタデータを期待される形式に変換できます。 - -## パラメーター {#parameters} - -### wellKnownUrl {#wellknownurl} - -サーバー構成を取得するための well-known URL。これは文字列または URL オブジェクトで指定できます。 - -`string` | `URL` - -### config {#config} - -`ServerMetadataConfig` - -サーバータイプおよびオプションのトランスパイル関数を含む構成オブジェクト。 - -## 戻り値 {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -取得したメタデータを含む静的サーバー構成に解決される Promise。 - -## 例外 {#throws} - -フェッチ操作が失敗した場合にスローされます。 - -## 例外 {#throws} - -サーバーメタデータが無効、または MCP 仕様と一致しない場合にスローされます。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md deleted file mode 100644 index 46c156c..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# 関数: getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -認証サーバー設定から発行者 (Issuer) の URL を取得します。 - -- 解決済み設定: `metadata.issuer` から抽出 -- ディスカバリー設定: `issuer` を直接返す - -## パラメーター {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## 戻り値 {#returns} - -`string` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md deleted file mode 100644 index 03812c3..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# 関数: handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -Express アプリケーションで Bearer 認証を処理するためのミドルウェア関数を作成します。 - -このミドルウェアは、`Authorization` ヘッダーから Bearer トークンを抽出し、指定された `verifyAccessToken` 関数を使って検証し、発行者 (Issuer)、オーディエンス (Audience)、および必要なスコープ (Scope) をチェックします。 - -- トークンが有効な場合、認証情報を `request.auth` プロパティに追加します。有効でない場合は、適切なエラーメッセージで応答します。 -- アクセス トークン (Access token) の検証に失敗した場合、401 Unauthorized エラーで応答します。 -- トークンに必要なスコープ (Scope) が含まれていない場合、403 Forbidden エラーで応答します。 -- 認証 (Authentication) プロセス中に予期しないエラーが発生した場合、ミドルウェアはそれらを再スローします。 - -**注意:** `request.auth` オブジェクトには、`@modelcontextprotocol/sdk` モジュールで定義されている標準の AuthInfo インターフェースよりも拡張されたフィールドが含まれます。詳細はこのファイル内の拡張インターフェースを参照してください。 - -## パラメーター {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Bearer 認証 (Authentication) ハンドラーの設定。 - -## 戻り値 {#returns} - -`RequestHandler` - -Bearer 認証 (Authentication) を処理する Express 用のミドルウェア関数。 - -## 参照 {#see} - -設定オプションについては [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md deleted file mode 100644 index f0dbc99..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerConfig ---- - -# 型エイリアス: AuthServerConfig - -```ts -type AuthServerConfig = - | ResolvedAuthServerConfig - | AuthServerDiscoveryConfig; -``` - -MCP サーバーと統合されたリモート認可サーバー (Authorization server) の設定。 - -次のいずれかになります: -- **解決済み (Resolved)**:`metadata` を含む — ネットワークリクエストは不要 -- **ディスカバリー (Discovery)**:`issuer` と `type` のみを含む — メタデータはディスカバリー経由でオンデマンド取得 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index 5c5b68d..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# 型エイリアス: AuthServerConfigError - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -認可サーバーメタデータの検証中に発生するエラーを表します。 - -## プロパティ {#properties} - -### cause? {#cause} - -```ts -optional cause: Error; -``` - -エラーのオプションの原因です。通常は、より多くのコンテキストを提供する `Error` のインスタンスです。 - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -特定の検証エラーを表すコードです。 - -*** - -### description {#description} - -```ts -description: string; -``` - -エラーの人間が読める説明です。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index 81df4a9..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# 型エイリアス: AuthServerConfigErrorCode - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -認可サーバーメタデータの検証時に発生する可能性があるエラーのコードです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index 8142835..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# 型エイリアス: AuthServerConfigWarning - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -認可サーバーメタデータの検証中に発生する警告を表します。 - -## プロパティ {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -特定の検証警告を表すコードです。 - -*** - -### description {#description} - -```ts -description: string; -``` - -警告の人間が読める説明です。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index a11e5a4..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# 型エイリアス: AuthServerConfigWarningCode - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -認可サーバーメタデータの検証時に発生する可能性がある警告のコードです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md deleted file mode 100644 index 6c039e4..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -sidebar_label: AuthServerDiscoveryConfig ---- - -# 型エイリアス: AuthServerDiscoveryConfig - -```ts -type AuthServerDiscoveryConfig = { - issuer: string; - type: AuthServerType; -}; -``` - -リモート認可サーバー (Authorization server) のディスカバリー設定です。 - -初めて必要になったときにディスカバリー経由でメタデータをオンデマンド取得したい場合に使用します。 -これは、Cloudflare Workers のようなエッジランタイムでトップレベルの非同期 fetch が許可されていない場合に便利です。 - -## 例 {#example} - -```typescript -const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, - }, -}); -``` - -## プロパティ {#properties} - -### issuer {#issuer} - -```ts -issuer: string; -``` - -認可サーバー (Authorization server) の発行者 (Issuer) URL です。この発行者 (Issuer) から導出される well-known エンドポイントからメタデータが取得されます。 - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -認可サーバー (Authorization server) のタイプです。 - -#### 参照 {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) で利用可能な値を確認できます。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md deleted file mode 100644 index bfa1379..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: AuthServerErrorCode ---- - -# 型エイリアス: AuthServerErrorCode - -```ts -type AuthServerErrorCode = - | "invalid_server_metadata" - | "invalid_server_config" - | "missing_jwks_uri"; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index 8a4012e..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# 型エイリアス: ~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -レガシーの MCP サーバーを認可サーバーモードとして使用するための設定です。 - -## 非推奨 {#deprecated} - -代わりに `ResourceServerModeConfig` 設定を使用してください。 - -## プロパティ {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -単一の認可サーバー設定です。 - -#### 非推奨 {#deprecated} - -代わりに `protectedResources` 設定を使用してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index e9db26d..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# 型エイリアス: AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -認可サーバーメタデータの検証が成功した場合のコードです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md deleted file mode 100644 index 9777ddd..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerType ---- - -# 型エイリアス: AuthServerType - -```ts -type AuthServerType = "oauth" | "oidc"; -``` - -認可サーバー (Authorization server) の種類です。この情報はサーバーの設定によって提供され、サーバーが OAuth 2.0 か OpenID Connect (OIDC) の認可サーバー (Authorization server) であるかを示します。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index 62db32d..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: AuthorizationServerMetadata ---- - -# 型エイリアス: AuthorizationServerMetadata - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -RFC 8414 で定義されている OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) のスキーマです。 - -## 参照 {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index 61cb290..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# 型エイリアス: BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## プロパティ {#properties} - -### audience? {#audience} - -```ts -optional audience: string; -``` - -アクセス トークン (アクセス トークン) の期待されるオーディエンス (`aud` クレーム)。これは通常、トークンが意図されているリソースサーバー (API) です。指定しない場合、オーディエンスのチェックはスキップされます。 - -**注:** 認可サーバーがリソースインジケーター (RFC 8707) をサポートしていない場合、このフィールドは省略できます。なぜなら、オーディエンスが関連しない場合があるためです。 - -#### 参照 {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -有効な発行者 (Issuer) を表す文字列、またはアクセス トークンの発行者を検証するための関数。 - -文字列が指定された場合、それが期待される発行者 (Issuer) の値として直接比較に使用されます。 - -関数が指定された場合は、[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) のルールに従って発行者 (Issuer) を検証する必要があります。 - -#### 参照 {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) で検証関数の詳細を確認できます。 - -*** - -### requiredScopes? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -アクセス トークンが持つべき必須スコープ (スコープ) の配列。トークンにこれらすべてのスコープが含まれていない場合、エラーがスローされます。 - -**注:** ハンドラーはトークン内の `scope` クレームをチェックします。これは認可サーバーの実装によって、スペース区切りの文字列または文字列配列である場合があります。`scope` クレームが存在しない場合、`scopes` クレームがあればそちらをチェックします。 - -*** - -### resource? {#resource} - -```ts -optional resource: string; -``` - -保護されたリソースの識別子。指定された場合、ハンドラーはこのリソース用に設定された認可サーバーを使用して受信したトークンを検証します。`protectedResources` 設定とともにハンドラーを使用する場合は必須です。 - -*** - -### showErrorDetails? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -レスポンスに詳細なエラー情報を表示するかどうか。これは開発中のデバッグに便利ですが、本番環境では機密情報漏洩を防ぐため無効にするべきです。 - -#### デフォルト {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -アクセス トークンを検証するための関数型。 - -この関数は、トークンが無効な場合は [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) をスローし、有効な場合は AuthInfo オブジェクトを返す必要があります。 - -#### 参照 {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) で詳細を確認できます。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index 908bb65..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# 型エイリアス: BearerAuthErrorCode - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index d8df81f..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# 型エイリアス: CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -OAuth 2.0 認可サーバーメタデータ型の camelCase バージョンです。 - -## 参照 {#see} - -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) で元の型およびフィールド情報を確認できます。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index c197dad..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# 型エイリアス: CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -OAuth 2.0 Protected Resource Metadata 型の camelCase バージョンです。 - -## 参照 {#see} - -元の型およびフィールド情報については、 [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) を参照してください。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index 4012d4c..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# 型エイリアス: MCPAuthBearerAuthErrorDetails - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## プロパティ {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md deleted file mode 100644 index 774d77d..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -sidebar_label: MCPAuthConfig ---- - -# 型エイリアス: MCPAuthConfig - -```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; -``` - -[MCPAuth](/references/js/classes/MCPAuth.md) クラスの設定であり、単一のレガシー `authorization server` または `resource server` 設定のいずれかをサポートします。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index 36e1f1a..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# 型エイリアス: MCPAuthTokenVerificationErrorCode - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index fda97ab..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# 型エイリアス: ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -OAuth 2.0 保護されたリソースメタデータのスキーマです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md deleted file mode 100644 index 3a921df..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -sidebar_label: ResolvedAuthServerConfig ---- - -# 型エイリアス: ResolvedAuthServerConfig - -```ts -type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; -``` - -メタデータ付きのリモート認可サーバー (Authorization server) の解決済み設定。 - -この型は、メタデータがすでに利用可能な場合(ハードコーディングされているか、事前に `fetchServerConfig()` で取得されている場合)に使用します。 - -## プロパティ {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -認可サーバー (Authorization server) のメタデータで、MCP 仕様(OAuth 2.0 認可サーバーメタデータに基づく)に準拠している必要があります。 - -このメタデータは通常、サーバーの well-known エンドポイント(OAuth 2.0 認可サーバーメタデータまたは OpenID Connect Discovery)から取得されます。サーバーがそのようなエンドポイントをサポートしていない場合は、設定に直接指定することもできます。 - -**注意:** メタデータは mcp-auth ライブラリの推奨に従い、camelCase 形式である必要があります。 - -#### 参考 {#see} - - - [OAuth 2.0 認可サーバーメタデータ](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -認可サーバー (Authorization server) のタイプ。 - -#### 参考 {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) で利用可能な値を確認できます。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index b263b81..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# 型エイリアス: ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -MCP サーバーをリソースサーバーモードとして構成するための設定です。 - -## プロパティ {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -単一のリソースサーバー設定、またはその配列です。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index b67b52c..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# 型エイリアス: ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -アクセス トークン (Access token) の発行者 (Issuer) を検証するための関数型です。 - -この関数は、発行者 (Issuer) が有効でない場合、コード 'invalid_issuer' の [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) をスローする必要があります。発行者 (Issuer) は以下に対して検証されるべきです: - -1. MCP-Auth の認可サーバーメタデータで設定された認可サーバー -2. 保護されたリソースのメタデータに記載されている認可サーバー - -## パラメーター {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## 戻り値 {#returns} - -`void` - -## 例外 {#throws} - -発行者 (Issuer) が認識されない、または無効な場合にスローされます。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index 6eea922..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# 型エイリアス: VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -アクセス トークン (Access token) を検証するための関数型です。 - -この関数は、トークンが無効な場合は [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) をスローし、有効な場合は AuthInfo オブジェクトを返す必要があります。 - -例えば、JWT 検証関数がある場合、少なくともトークンの署名を確認し、有効期限を検証し、必要なクレーム (Claims) を抽出して `AuthInfo` オブジェクトを返す必要があります。 - -**注意:** 次のフィールドはハンドラーによって検証されるため、トークン内で検証する必要はありません: - -- `iss` (発行者) -- `aud` (オーディエンス) -- `scope` (スコープ) - -## パラメーター {#parameters} - -### token {#token} - -`string` - -検証するアクセス トークン (Access token) の文字列。 - -## 戻り値 {#returns} - -`MaybePromise`\<`AuthInfo`\> - -トークンが有効な場合、AuthInfo オブジェクトを解決する Promise または同期値。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index 28efbbb..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# 型エイリアス: VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -`bearerAuth` でサポートされている組み込みの検証モードです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md deleted file mode 100644 index fec4bec..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: authServerErrorDescription ---- - -# 変数: authServerErrorDescription - -```ts -const authServerErrorDescription: Readonly>; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index 66a4f6b..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# 変数: authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -RFC 8414 で定義されている OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) 用の Zod スキーマです。 - -## 参照 {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index 445c574..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# 変数: bearerAuthErrorDescription - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index d00d981..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# 変数: camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 認可サーバーメタデータ Zod スキーマの camelCase バージョンです。 - -## 参照 {#see} - -元のスキーマとフィールド情報については [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index 8ead61e..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# 変数: camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 Protected Resource Metadata Zod スキーマの camelCase バージョンです。 - -## 参照 {#see} - -元のスキーマおよびフィールド情報については、 [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) を参照してください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md deleted file mode 100644 index 99aeb6b..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# 変数: defaultValues - -```ts -const defaultValues: Readonly>; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index 48765ef..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# 変数: protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 保護されたリソースメタデータのための Zod スキーマです。 \ No newline at end of file diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md deleted file mode 100644 index 698258c..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: serverMetadataPaths ---- - -# 変数: serverMetadataPaths - -```ts -const serverMetadataPaths: Readonly<{ - oauth: "/.well-known/oauth-authorization-server"; - oidc: "/.well-known/openid-configuration"; -}>; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index f5bf4c8..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: tokenVerificationErrorDescription ---- - -# 変数: tokenVerificationErrorDescription - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md deleted file mode 100644 index 3725276..0000000 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# 変数: validateServerConfig - -```ts -const validateServerConfig: ValidateServerConfig; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md deleted file mode 100644 index 888b8d6..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -sidebar_label: Node.js SDK ---- - -# MCP Auth Node.js SDK 참고서 - -## 클래스 {#classes} - -- [MCPAuth](/references/js/classes/MCPAuth.md) -- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) -- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) -- [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) - -## 타입 별칭 {#type-aliases} - -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) -- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) -- [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) -- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) -- [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) -- [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) - -## 변수 {#variables} - -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) -- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) -- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) - -## 함수 {#functions} - -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) -- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) -- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md deleted file mode 100644 index 642678f..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -sidebar_label: MCPAuth ---- - -# 클래스: MCPAuth - -mcp-auth 라이브러리의 주요 클래스입니다. 보호된 리소스에 대한 인증 (Authentication) 정책을 생성하기 위한 팩토리이자 레지스트리 역할을 합니다. - -서버 구성으로 초기화되며, 토큰 기반 인증 (Authentication)을 위한 Express 미들웨어를 생성하는 `bearerAuth` 메서드를 제공합니다. - -## 예시 {#example} - -### `resource server` 모드에서의 사용 {#usage-in-resource-server-mode} - -신규 애플리케이션에 권장되는 접근 방식입니다. - -#### 옵션 1: Discovery config (엣지 런타임에 권장) {#option-1-discovery-config-recommended-for-edge-runtimes} - -메타데이터를 필요할 때마다 가져오고 싶을 때 사용하세요. 이는 Cloudflare Workers와 같이 최상위 async fetch가 허용되지 않는 엣지 런타임에서 특히 유용합니다. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // 발급자와 타입만 전달하면, 메타데이터는 첫 요청 시 가져옵니다 - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### 옵션 2: Resolved config (미리 가져온 메타데이터) {#option-2-resolved-config-pre-fetched-metadata} - -애플리케이션 시작 시 메타데이터를 미리 가져와 검증하고 싶을 때 사용하세요. - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### 미들웨어 사용하기 {#using-the-middleware} - -```ts -// 보호된 리소스 메타데이터를 처리하는 라우터를 마운트합니다 -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// 구성된 리소스에 대해 API 엔드포인트를 보호합니다 -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // 이 엔드포인트가 속한 리소스를 지정 - audience: resourceIdentifier, // 선택적으로 'aud' 클레임을 검증 - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - }, -); -``` - -### `authorization server` 모드의 레거시 사용법 (더 이상 권장되지 않음) {#legacy-usage-in-authorization-server-mode-deprecated} - -이 방식은 하위 호환성을 위해 지원됩니다. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth = new MCPAuth({ - // Discovery config - 메타데이터를 필요할 때마다 가져옵니다 - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, -}); - -// 레거시 인가 (Authorization) 서버 메타데이터를 처리하는 라우터를 마운트합니다 -app.use(mcpAuth.delegatedRouter()); - -// 기본 정책을 사용하여 엔드포인트를 보호합니다 -app.get( - '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // 여기서 MCP 요청을 처리합니다 - }, -); -``` - -## 생성자 {#constructors} - -### 생성자 {#constructor} - -```ts -new MCPAuth(config: MCPAuthConfig): MCPAuth; -``` - -MCPAuth 인스턴스를 생성합니다. -전체 구성을 사전에 검증하여 오류 발생 시 빠르게 실패하도록 합니다. - -#### 매개변수 {#parameters} - -##### config {#config} - -[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) - -인증 (Authentication) 구성입니다. - -#### 반환값 {#returns} - -`MCPAuth` - -## 속성 {#properties} - -### config {#config} - -```ts -readonly config: MCPAuthConfig; -``` - -인증 (Authentication) 구성입니다. - -## 메서드 {#methods} - -### bearerAuth() {#bearerauth} - -#### 호출 시그니처 {#call-signature} - -```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; -``` - -요청의 `Authorization` 헤더에 있는 액세스 토큰 (Access token)을 검증하는 Bearer 인증 (Authentication) 핸들러 (Express 미들웨어)를 생성합니다. - -##### 매개변수 {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -액세스 토큰 (Access token)을 검증하는 함수입니다. 문자열로 액세스 토큰을 받아, 검증 결과로 resolve되는 promise (또는 값)를 반환해야 합니다. - -**참고** - -`verifyAccessToken` 함수의 타입 정의는 [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)에서 확인하세요. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> - -Bearer 인증 (Authentication) 핸들러의 선택적 구성입니다. - -**참고** - -사용 가능한 구성 옵션은 [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)에서 확인하세요 (`verifyAccessToken` 및 `issuer` 제외). - -##### 반환값 {#returns} - -`RequestHandler` - -액세스 토큰 (Access token)을 검증하고, 검증 결과를 요청 객체 (`req.auth`)에 추가하는 Express 미들웨어 함수입니다. - -##### 참고 {#see} - -구현 세부사항 및 확장된 `req.auth` (`AuthInfo`) 객체 타입은 [handleBearerAuth](/references/js/functions/handleBearerAuth.md)에서 확인하세요. - -#### 호출 시그니처 {#call-signature} - -```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; -``` - -미리 정의된 검증 모드를 사용하여 요청의 `Authorization` 헤더에 있는 액세스 토큰 (Access token)을 검증하는 Bearer 인증 (Authentication) 핸들러 (Express 미들웨어)를 생성합니다. - -`'jwt'` 모드에서는 인가 (Authorization) 서버의 JWKS URI에서 JWK Set을 사용하여 JWT 검증 함수를 생성합니다. - -##### 매개변수 {#parameters} - -###### mode {#mode} - -`"jwt"` - -액세스 토큰 (Access token) 검증 모드입니다. 현재는 'jwt'만 지원됩니다. - -**참고** - -사용 가능한 모드는 [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md)에서 확인하세요. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` - -JWT 검증 옵션 및 원격 JWK set 옵션을 포함한 Bearer 인증 (Authentication) 핸들러의 선택적 구성입니다. - -**참고** - - - JWT 검증을 위한 구성 옵션은 VerifyJwtConfig에서 확인하세요. - - 사용 가능한 구성 옵션은 [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)에서 확인하세요 (`verifyAccessToken` 및 `issuer` 제외). - -##### 반환값 {#returns} - -`RequestHandler` - -액세스 토큰 (Access token)을 검증하고, 검증 결과를 요청 객체 (`req.auth`)에 추가하는 Express 미들웨어 함수입니다. - -##### 참고 {#see} - -구현 세부사항 및 확장된 `req.auth` (`AuthInfo`) 객체 타입은 [handleBearerAuth](/references/js/functions/handleBearerAuth.md)에서 확인하세요. - -##### 예외 {#throws} - -'jwt' 모드 사용 시 서버 메타데이터에 JWKS URI가 제공되지 않은 경우 예외가 발생합니다. - -*** - -### ~~delegatedRouter()~~ {#delegatedrouter} - -```ts -delegatedRouter(): Router; -``` - -인스턴스에 제공된 메타데이터로 레거시 OAuth 2.0 인가 (Authorization) 서버 메타데이터 엔드포인트 -(`/.well-known/oauth-authorization-server`)를 제공하는 delegated 라우터를 생성합니다. - -#### 반환값 {#returns} - -`Router` - -인스턴스에 제공된 메타데이터로 OAuth 2.0 인가 (Authorization) 서버 메타데이터 엔드포인트를 제공하는 라우터입니다. - -#### 더 이상 사용되지 않음 {#deprecated} - -대신 [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter)를 사용하세요. - -#### 예시 {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth: MCPAuth; // 초기화되어 있다고 가정 -app.use(mcpAuth.delegatedRouter()); -``` - -#### 예외 {#throws} - -`resource server` 모드에서 호출 시 예외가 발생합니다. - -*** - -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} - -```ts -protectedResourceMetadataRouter(): Router; -``` - -구성된 모든 리소스에 대해 OAuth 2.0 보호된 리소스 메타데이터 엔드포인트를 제공하는 라우터를 생성합니다. - -이 라우터는 구성에 제공된 각 리소스 식별자에 대해 올바른 `.well-known` 엔드포인트를 자동으로 생성합니다. - -#### 반환값 {#returns} - -`Router` - -OAuth 2.0 보호된 리소스 메타데이터 엔드포인트를 제공하는 라우터입니다. - -#### 예외 {#throws} - -`authorization server` 모드에서 호출 시 예외가 발생합니다. - -#### 예시 {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// mcpAuth가 하나 이상의 `protectedResources` 구성으로 초기화되어 있다고 가정 -const mcpAuth: MCPAuth; -const app = express(); - -// 리소스 식별자에 따라 `/.well-known/oauth-protected-resource/...`에서 메타데이터를 제공합니다. -app.use(mcpAuth.protectedResourceMetadataRouter()); -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md deleted file mode 100644 index f845631..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthAuthServerError ---- - -# 클래스: MCPAuthAuthServerError - -원격 인가 (Authorization) 서버에 문제가 있을 때 발생하는 오류입니다. - -## 상속 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 생성자 {#constructors} - -### 생성자 {#constructor} - -```ts -new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; -``` - -#### 매개변수 {#parameters} - -##### code {#code} - -[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### 반환값 {#returns} - -`MCPAuthAuthServerError` - -#### 오버라이드 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 프로퍼티 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: AuthServerErrorCode; -``` - -스네이크 케이스 형식의 오류 코드입니다. - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthAuthServerError'; -``` - -#### 오버라이드 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -스택 트레이스 포맷팅을 위한 선택적 오버라이드 - -#### 매개변수 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 반환값 {#returns} - -`any` - -#### 참고 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 메서드 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. - -#### 매개변수 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON 응답에 오류의 원인을 포함할지 여부입니다. -기본값은 `false`입니다. - -#### 반환값 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -대상 객체에 .stack 프로퍼티를 생성합니다 - -#### 매개변수 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 반환값 {#returns} - -`void` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index 8f7e168..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# 클래스: MCPAuthBearerAuthError - -Bearer 토큰으로 인증 (Authentication) 시 문제가 발생할 때 발생하는 오류입니다. - -## 상속 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 생성자 {#constructors} - -### 생성자 {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### 매개변수 {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### 반환값 {#returns} - -`MCPAuthBearerAuthError` - -#### 오버라이드 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 프로퍼티 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -스네이크 케이스 형식의 오류 코드입니다. - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### 오버라이드 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -스택 트레이스 포맷팅을 위한 선택적 오버라이드 - -#### 매개변수 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 반환값 {#returns} - -`any` - -#### 참고 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 메서드 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. - -#### 매개변수 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON 응답에 오류의 원인을 포함할지 여부입니다. -기본값은 `false`입니다. - -#### 반환값 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 오버라이드 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -대상 객체에 .stack 프로퍼티를 생성합니다 - -#### 매개변수 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 반환값 {#returns} - -`void` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md deleted file mode 100644 index 8d529a0..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebar_label: MCPAuthConfigError ---- - -# 클래스: MCPAuthConfigError - -mcp-auth의 구성 문제 발생 시 발생하는 오류입니다. - -## 상속 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 생성자 {#constructors} - -### 생성자 {#constructor} - -```ts -new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; -``` - -#### 매개변수 {#parameters} - -##### code {#code} - -`string` - -스네이크 케이스(snake_case) 형식의 오류 코드입니다. - -##### message {#message} - -`string` - -오류에 대한 사람이 읽을 수 있는 설명입니다. - -#### 반환값 {#returns} - -`MCPAuthConfigError` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 프로퍼티 {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -스네이크 케이스(snake_case) 형식의 오류 코드입니다. - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthConfigError'; -``` - -#### 오버라이드 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -스택 트레이스 형식을 지정하기 위한 선택적 오버라이드 - -#### 매개변수 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 반환값 {#returns} - -`any` - -#### 참고 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 메서드 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. - -#### 매개변수 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON 응답에 오류의 원인을 포함할지 여부입니다. -기본값은 `false`입니다. - -#### 반환값 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -대상 객체에 .stack 프로퍼티를 생성합니다 - -#### 매개변수 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 반환값 {#returns} - -`void` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md deleted file mode 100644 index 8f4103e..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -sidebar_label: MCPAuthError ---- - -# 클래스: MCPAuthError - -모든 mcp-auth 오류의 기본 클래스입니다. - -MCP 인증 (Authentication) 및 인가 (Authorization)와 관련된 오류를 표준화된 방식으로 처리할 수 있도록 제공합니다. - -## 상속 {#extends} - -- `Error` - -## 확장 클래스 {#extended-by} - -- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) -- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) - -## 생성자 {#constructors} - -### 생성자 {#constructor} - -```ts -new MCPAuthError(code: string, message: string): MCPAuthError; -``` - -#### 매개변수 {#parameters} - -##### code {#code} - -`string` - -스네이크 케이스 형식의 오류 코드입니다. - -##### message {#message} - -`string` - -오류에 대한 사람이 읽을 수 있는 설명입니다. - -#### 반환값 {#returns} - -`MCPAuthError` - -#### 오버라이드 {#overrides} - -```ts -Error.constructor -``` - -## 속성 {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### 상속됨 {#inherited-from} - -```ts -Error.cause -``` - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -스네이크 케이스 형식의 오류 코드입니다. - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 상속됨 {#inherited-from} - -```ts -Error.message -``` - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthError'; -``` - -#### 오버라이드 {#overrides} - -```ts -Error.name -``` - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 상속됨 {#inherited-from} - -```ts -Error.stack -``` - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -스택 트레이스 포맷팅을 위한 선택적 오버라이드 - -#### 매개변수 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 반환값 {#returns} - -`any` - -#### 참고 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 상속됨 {#inherited-from} - -```ts -Error.prepareStackTrace -``` - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 상속됨 {#inherited-from} - -```ts -Error.stackTraceLimit -``` - -## 메서드 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. - -#### 매개변수 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. -기본값은 `false`입니다. - -#### 반환값 {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -대상 객체에 .stack 속성을 생성합니다 - -#### 매개변수 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 반환값 {#returns} - -`void` - -#### 상속됨 {#inherited-from} - -```ts -Error.captureStackTrace -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index a26a1af..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# 클래스: MCPAuthTokenVerificationError - -토큰을 검증하는 과정에서 문제가 발생했을 때 발생하는 오류입니다. - -## 상속 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 생성자 {#constructors} - -### 생성자 {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### 매개변수 {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### 반환값 {#returns} - -`MCPAuthTokenVerificationError` - -#### 오버라이드 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 프로퍼티 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -스네이크 케이스 형식의 오류 코드입니다. - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### 오버라이드 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -스택 트레이스 포맷팅을 위한 선택적 오버라이드 - -#### 매개변수 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 반환값 {#returns} - -`any` - -#### 참고 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 메서드 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -오류를 HTTP 응답에 적합한 JSON 형식으로 변환합니다. - -#### 매개변수 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -JSON 응답에 오류의 원인을 포함할지 여부입니다. -기본값은 `false`입니다. - -#### 반환값 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -대상 객체에 .stack 프로퍼티를 생성합니다 - -#### 매개변수 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 반환값 {#returns} - -`void` - -#### 상속됨 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md deleted file mode 100644 index 3005a3f..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# 함수: createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -제공된 키 검색 함수와 옵션을 사용하여 JWT 액세스 토큰 (Access token)을 검증하는 함수를 생성합니다. - -## 매개변수 {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -JWT를 검증하는 데 사용되는 키를 검색하는 함수입니다. - -**참고** - -키 검색 함수의 타입 정의는 JWTVerifyGetKey를 참고하세요. - -### options? {#options} - -`JWTVerifyOptions` - -선택적 JWT 검증 옵션입니다. - -**참고** - -옵션의 타입 정의는 JWTVerifyOptions를 참고하세요. - -## 반환값 {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -JWT 액세스 토큰 (Access token)을 검증하고, 토큰이 유효할 경우 AuthInfo 객체를 반환하는 함수입니다. 이 함수는 JWT의 페이로드에 `iss`, `client_id`, `sub` 필드가 반드시 포함되어야 하며, 선택적으로 `scope` 또는 `scopes` 필드를 포함할 수 있습니다. JWT 검증은 내부적으로 `jose` 라이브러리를 사용하여 수행됩니다. - -## 참고 {#see} - -반환되는 함수의 타입 정의는 [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)을 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md deleted file mode 100644 index 702ec1c..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -sidebar_label: fetchServerConfig ---- - -# 함수: fetchServerConfig() - -```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; -``` - -발급자 (Issuer)와 인가 서버 유형에 따라 서버 구성을 가져옵니다. - -이 함수는 서버 유형에 따라 well-known URL을 자동으로 결정합니다. OAuth 및 OpenID Connect 서버는 메타데이터 엔드포인트에 대해 서로 다른 규칙을 가지고 있기 때문입니다. - -## 매개변수 {#parameters} - -### issuer {#issuer} - -`string` - -인가 서버의 발급자 (Issuer) URL입니다. - -### config {#config} - -`ServerMetadataConfig` - -서버 유형과 선택적 트랜스파일 함수가 포함된 구성 객체입니다. - -## 반환값 {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -가져온 메타데이터와 함께 정적 서버 구성으로 해결되는 프로미스입니다. - -## 참고 {#see} - - - 내부 구현에 대해서는 [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md)을 참고하세요. - - OAuth 2.0 인가 서버 메타데이터 사양은 [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414)에서 확인할 수 있습니다. - - OpenID Connect Discovery 사양은 [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html)에서 확인할 수 있습니다. - -## 예시 {#example} - -```ts -import { fetchServerConfig } from 'mcp-auth'; -// OAuth 서버 구성 가져오기 -// 이는 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth`에서 메타데이터를 가져옵니다. -const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); - -// OpenID Connect 서버 구성 가져오기 -// 이는 `https://auth.logto.io/oidc/.well-known/openid-configuration`에서 메타데이터를 가져옵니다. -const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); -``` - -## 예외 {#throws} - -가져오기 작업이 실패할 경우 예외가 발생합니다. - -## 예외 {#throws} - -서버 메타데이터가 유효하지 않거나 MCP 사양과 일치하지 않을 경우 예외가 발생합니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md deleted file mode 100644 index 6cc3041..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: fetchServerConfigByWellKnownUrl ---- - -# 함수: fetchServerConfigByWellKnownUrl() - -```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; -``` - -제공된 well-known URL에서 서버 구성을 가져오고 MCP 사양에 따라 유효성을 검사합니다. - -서버 메타데이터가 예상된 스키마와 일치하지 않지만 호환된다고 확신하는 경우, `transpileData` 함수를 정의하여 메타데이터를 예상 형식으로 변환할 수 있습니다. - -## 매개변수 {#parameters} - -### wellKnownUrl {#wellknownurl} - -서버 구성을 가져올 well-known URL입니다. 문자열 또는 URL 객체일 수 있습니다. - -`string` | `URL` - -### config {#config} - -`ServerMetadataConfig` - -서버 유형과 선택적 변환 함수(transpile function)를 포함하는 구성 객체입니다. - -## 반환값 {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -가져온 메타데이터와 함께 정적 서버 구성으로 해결되는 프로미스입니다. - -## 예외 발생 {#throws} - -가져오기 작업이 실패할 경우 예외가 발생합니다. - -## 예외 발생 {#throws} - -서버 메타데이터가 유효하지 않거나 MCP 사양과 일치하지 않을 경우 예외가 발생합니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md deleted file mode 100644 index e0485f1..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# 함수: getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -인증 서버 구성에서 발급자 (Issuer) URL을 가져옵니다. - -- 해석된 구성: `metadata.issuer`에서 추출 -- 디스커버리 구성: `issuer`를 직접 반환 - -## 매개변수 {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## 반환값 {#returns} - -`string` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md deleted file mode 100644 index 21f3e96..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# 함수: handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -Express 애플리케이션에서 Bearer 인증 (Authentication)을 처리하는 미들웨어 함수를 생성합니다. - -이 미들웨어는 `Authorization` 헤더에서 Bearer 토큰을 추출하고, 제공된 `verifyAccessToken` 함수를 사용하여 토큰을 검증하며, 발급자 (Issuer), 대상 (Audience), 그리고 필요한 스코프 (Scope)를 확인합니다. - -- 토큰이 유효한 경우, 인증 (Authentication) 정보를 `request.auth` 속성에 추가합니다. - 유효하지 않은 경우, 적절한 오류 메시지로 응답합니다. -- 액세스 토큰 (Access token) 검증에 실패하면 401 Unauthorized 오류로 응답합니다. -- 토큰에 필요한 스코프 (Scope)가 없으면 403 Forbidden 오류로 응답합니다. -- 인증 (Authentication) 과정 중 예기치 않은 오류가 발생하면, 미들웨어가 해당 오류를 다시 throw 합니다. - -**참고:** `request.auth` 객체는 `@modelcontextprotocol/sdk` 모듈에 정의된 표준 AuthInfo 인터페이스보다 확장된 필드를 포함합니다. 자세한 내용은 이 파일의 확장 인터페이스를 참고하세요. - -## 매개변수 {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Bearer 인증 (Authentication) 핸들러를 위한 설정입니다. - -## 반환값 {#returns} - -`RequestHandler` - -Bearer 인증 (Authentication)을 처리하는 Express용 미들웨어 함수입니다. - -## 참고 {#see} - -설정 옵션에 대해서는 [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)를 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md deleted file mode 100644 index e449ca4..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerConfig ---- - -# 타입 별칭: AuthServerConfig - -```ts -type AuthServerConfig = - | ResolvedAuthServerConfig - | AuthServerDiscoveryConfig; -``` - -MCP 서버와 통합된 원격 인가 서버 (Authorization server)의 구성입니다. - -다음 중 하나일 수 있습니다: -- **Resolved**: `metadata`를 포함하며, 네트워크 요청이 필요하지 않습니다 -- **Discovery**: `issuer`와 `type`만 포함하며, 메타데이터는 디스커버리(Discovery)를 통해 필요 시 가져옵니다 \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index a281c35..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# 타입 별칭: AuthServerConfigError - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -인가 (Authorization) 서버 메타데이터의 검증 중에 발생하는 오류를 나타냅니다. - -## 속성 {#properties} - -### cause? {#cause} - -```ts -optional cause: Error; -``` - -오류의 선택적 원인입니다. 일반적으로 더 많은 맥락을 제공하는 `Error` 인스턴스입니다. - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -특정 검증 오류를 나타내는 코드입니다. - -*** - -### description {#description} - -```ts -description: string; -``` - -오류에 대한 사람이 읽을 수 있는 설명입니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index b6ecf79..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# 타입 별칭: AuthServerConfigErrorCode - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -인가 서버 메타데이터를 검증할 때 발생할 수 있는 오류 코드입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index 49e9a0a..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# 타입 별칭: AuthServerConfigWarning - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -인가 서버 메타데이터를 검증하는 동안 발생하는 경고를 나타냅니다. - -## 속성 {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -특정 검증 경고를 나타내는 코드입니다. - -*** - -### description {#description} - -```ts -description: string; -``` - -경고에 대한 사람이 읽을 수 있는 설명입니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index c12a26a..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# 타입 별칭: AuthServerConfigWarningCode - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -인가 (Authorization) 서버 메타데이터를 검증할 때 발생할 수 있는 경고 코드입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md deleted file mode 100644 index 97bf4c9..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -sidebar_label: AuthServerDiscoveryConfig ---- - -# 타입 별칭: AuthServerDiscoveryConfig - -```ts -type AuthServerDiscoveryConfig = { - issuer: string; - type: AuthServerType; -}; -``` - -원격 인가 서버의 디스커버리(Discovery) 구성입니다. - -메타데이터가 처음 필요할 때 디스커버리를 통해 온디맨드로 가져오고 싶을 때 사용하세요. -이는 Cloudflare Workers와 같이 최상위 async fetch가 허용되지 않는 엣지 런타임에서 유용합니다. - -## 예시 {#example} - -```typescript -const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, - }, -}); -``` - -## 속성 {#properties} - -### issuer {#issuer} - -```ts -issuer: string; -``` - -인가 (Authorization) 서버의 발급자 (Issuer) URL입니다. 이 발급자에서 파생된 well-known 엔드포인트에서 메타데이터가 가져와집니다. - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -인가 (Authorization) 서버의 유형입니다. - -#### 참고 {#see} - -가능한 값은 [AuthServerType](/references/js/type-aliases/AuthServerType.md) 을 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md deleted file mode 100644 index a22222e..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: AuthServerErrorCode ---- - -# 타입 별칭: AuthServerErrorCode - -```ts -type AuthServerErrorCode = - | "invalid_server_metadata" - | "invalid_server_config" - | "missing_jwks_uri"; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index a361233..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# 타입 별칭: ~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -레거시, MCP 서버를 인가 서버 모드로 사용하는 구성입니다. - -## 사용 중단됨 {#deprecated} - -대신 `ResourceServerModeConfig` 구성을 사용하세요. - -## 속성 {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -단일 인가 서버 구성입니다. - -#### 사용 중단됨 {#deprecated} - -대신 `protectedResources` 구성을 사용하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index d1236d8..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# 타입 별칭: AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -인가 서버 메타데이터의 성공적인 검증을 나타내는 코드입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md deleted file mode 100644 index df7aded..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerType ---- - -# 타입 별칭: AuthServerType - -```ts -type AuthServerType = "oauth" | "oidc"; -``` - -인가 서버의 타입입니다. 이 정보는 서버 구성에서 제공되어야 하며, 서버가 OAuth 2.0 또는 OpenID Connect (OIDC) 인가 서버인지 나타냅니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index 4daf7c2..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: AuthorizationServerMetadata ---- - -# 타입 별칭: AuthorizationServerMetadata - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -RFC 8414에 정의된 OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata) 스키마입니다. - -## 참고 {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index 5a247ab..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# 타입 별칭: BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## 속성(Properties) {#properties} - -### audience? {#audience} - -```ts -optional audience: string; -``` - -액세스 토큰 (Access token)의 예상 대상 (Audience) (`aud` 클레임 (Claim)). 일반적으로 토큰이 의도된 리소스 서버 (API)입니다. 제공하지 않으면 대상 (Audience) 확인이 건너뜁니다. - -**참고:** 인가 서버가 리소스 지표 (Resource Indicator) (RFC 8707)를 지원하지 않는 경우, 대상 (Audience)이 관련 없을 수 있으므로 이 필드를 생략할 수 있습니다. - -#### 참고(See) {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -유효한 발급자 (Issuer)를 나타내는 문자열 또는 액세스 토큰 (Access token)의 발급자 (Issuer)를 검증하는 함수. - -문자열이 제공되면, 예상 발급자 (Issuer) 값으로 직접 비교에 사용됩니다. - -함수가 제공되면, [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md)의 규칙에 따라 발급자 (Issuer)를 검증해야 합니다. - -#### 참고(See) {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md)에서 검증 함수에 대한 자세한 내용을 확인하세요. - -*** - -### requiredScopes? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -액세스 토큰 (Access token)이 반드시 가져야 하는 필수 스코프 (Scope)들의 배열. 토큰에 이 모든 스코프 (Scope)가 포함되어 있지 않으면 오류가 발생합니다. - -**참고:** 핸들러는 토큰의 `scope` 클레임 (Claim)을 확인합니다. 이 값은 인가 서버의 구현에 따라 공백으로 구분된 문자열이거나 문자열 배열일 수 있습니다. `scope` 클레임 (Claim)이 없으면, 핸들러는 `scopes` 클레임 (Claim)이 있는지 확인합니다. - -*** - -### resource? {#resource} - -```ts -optional resource: string; -``` - -보호된 리소스의 식별자. 제공된 경우, 핸들러는 이 리소스에 대해 구성된 인가 서버를 사용하여 받은 토큰을 검증합니다. `protectedResources` 구성과 함께 핸들러를 사용할 때 필수입니다. - -*** - -### showErrorDetails? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -응답에 상세 오류 정보를 표시할지 여부. 개발 중 디버깅에 유용하지만, 민감한 정보 노출을 방지하기 위해 운영 환경에서는 비활성화해야 합니다. - -#### 기본값(Default) {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -액세스 토큰 (Access token) 검증을 위한 함수 타입. - -이 함수는 토큰이 유효하지 않은 경우 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md)를 throw 하거나, 토큰이 유효한 경우 AuthInfo 객체를 반환해야 합니다. - -#### 참고(See) {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)에서 자세한 내용을 확인하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index ae5ae5d..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# 타입 별칭: BearerAuthErrorCode (BearerAuthErrorCode) - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index 880cb1a..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# 타입 별칭: CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata) 타입의 camelCase 버전입니다. - -## 참고 {#see} - -원본 타입 및 필드 정보는 [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 를 참조하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index 23a94c8..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# 타입 별칭: CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -OAuth 2.0 보호된 리소스 메타데이터(Protected Resource Metadata) 타입의 camelCase 버전입니다. - -## 참고 {#see} - -원본 타입 및 필드 정보는 [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) 를 참조하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index 7166e5b..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# 타입 별칭: MCPAuthBearerAuthErrorDetails (Type Alias: MCPAuthBearerAuthErrorDetails) - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## 속성(Properties) {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md deleted file mode 100644 index 879159d..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -sidebar_label: MCPAuthConfig ---- - -# 타입 별칭: MCPAuthConfig - -```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; -``` - -[MCPAuth](/references/js/classes/MCPAuth.md) 클래스의 설정으로, 단일 레거시 `인가 서버 (authorization server)` 또는 `리소스 서버 (resource server)` 구성을 지원합니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index cecafed..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# 타입 별칭: MCPAuthTokenVerificationErrorCode - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index afbb627..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# 타입 별칭: ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -OAuth 2.0 보호된 리소스 메타데이터(Protected Resource Metadata)를 위한 스키마입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md deleted file mode 100644 index 0ba2158..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -sidebar_label: ResolvedAuthServerConfig ---- - -# 타입 별칭: ResolvedAuthServerConfig - -```ts -type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; -``` - -메타데이터와 함께 원격 인가 서버 (Authorization Server)의 해석된 (resolved) 구성입니다. - -이 메타데이터가 이미 하드코딩되어 있거나, 사전에 `fetchServerConfig()`를 통해 가져온 경우에 사용하세요. - -## 속성(Properties) {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -인가 서버 (Authorization Server)의 메타데이터로, MCP 명세 (OAuth 2.0 인가 서버 메타데이터 기반)를 준수해야 합니다. - -이 메타데이터는 일반적으로 서버의 well-known 엔드포인트 (OAuth 2.0 인가 서버 메타데이터 또는 OpenID Connect Discovery)에서 가져오며, 서버가 해당 엔드포인트를 지원하지 않는 경우 구성에 직접 제공할 수도 있습니다. - -**참고:** 메타데이터는 mcp-auth 라이브러리에서 권장하는 대로 camelCase 형식이어야 합니다. - -#### 참고(See) {#see} - - - [OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata)](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -인가 서버 (Authorization Server)의 유형입니다. - -#### 참고(See) {#see} - -가능한 값은 [AuthServerType](/references/js/type-aliases/AuthServerType.md) 을 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index 44b38dd..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# 타입 별칭: ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -MCP 서버를 리소스 서버 모드로 설정하는 구성입니다. - -## 속성 {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -단일 리소스 서버 구성 또는 그 배열입니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index 8d73885..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# 타입 별칭: ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -액세스 토큰 (Access token)의 발급자 (Issuer)를 검증하는 함수 타입입니다. - -이 함수는 발급자가 유효하지 않은 경우 코드가 'invalid_issuer'인 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)를 throw해야 합니다. 발급자는 다음을 기준으로 검증해야 합니다: - -1. MCP-Auth의 인증 서버 메타데이터에 구성된 인가 서버 (Authorization server) -2. 보호된 리소스의 메타데이터에 나열된 인가 서버 (Authorization server) - -## 매개변수 {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## 반환값 {#returns} - -`void` - -## 예외 발생 {#throws} - -발급자가 인식되지 않거나 유효하지 않은 경우 예외가 발생합니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index aea5510..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# 타입 별칭: VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -액세스 토큰 (Access token) 검증을 위한 함수 타입입니다. - -이 함수는 토큰이 유효하지 않은 경우 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md)를 throw 해야 하며, -토큰이 유효한 경우 AuthInfo 객체를 반환해야 합니다. - -예를 들어, JWT 검증 함수가 있다면, 최소한 토큰의 서명을 확인하고, 만료를 검증하며, -필요한 클레임 (Claim)을 추출하여 `AuthInfo` 객체를 반환해야 합니다. - -**참고:** 다음 필드는 핸들러에서 확인하므로 토큰에서 별도로 검증할 필요가 없습니다: - -- `iss` (발급자 (Issuer)) -- `aud` (대상 (Audience)) -- `scope` (스코프 (Scopes)) - -## 매개변수 {#parameters} - -### token {#token} - -`string` - -검증할 액세스 토큰 (Access token) 문자열입니다. - -## 반환값 {#returns} - -`MaybePromise`\<`AuthInfo`\> - -토큰이 유효한 경우 AuthInfo 객체 또는 동기 값으로 resolve 되는 promise 입니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index e66f87b..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# 타입 별칭: VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -`bearerAuth`에서 지원하는 내장 검증 모드입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md deleted file mode 100644 index 4c3c8d0..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: authServerErrorDescription ---- - -# 변수: authServerErrorDescription (authServerErrorDescription) - -```ts -const authServerErrorDescription: Readonly>; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index 32a66c9..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# 변수: authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -RFC 8414에서 정의된 OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata)를 위한 Zod 스키마입니다. - -## 참고 {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index a5eaf5d..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# 변수: bearerAuthErrorDescription - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index 4b2bf93..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# 변수: camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 인가 서버 메타데이터 Zod 스키마의 camelCase 버전입니다. - -## 참고 {#see} - -원본 스키마 및 필드 정보는 [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) 를 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index d62cbd3..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# 변수: camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 불투명 토큰 (Opaque token) 보호 리소스 메타데이터 Zod 스키마의 camelCase 버전입니다. - -## 참고 {#see} - -원본 스키마 및 필드 정보는 [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 를 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md deleted file mode 100644 index 90accbb..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# 변수: defaultValues - -```ts -const defaultValues: Readonly>; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index 1f888df..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# 변수: protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 보호된 리소스 메타데이터를 위한 Zod 스키마입니다. \ No newline at end of file diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md deleted file mode 100644 index 81b2ee3..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: serverMetadataPaths ---- - -# 변수: serverMetadataPaths - -```ts -const serverMetadataPaths: Readonly<{ - oauth: "/.well-known/oauth-authorization-server"; - oidc: "/.well-known/openid-configuration"; -}>; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index 8442d41..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: tokenVerificationErrorDescription ---- - -# 변수: tokenVerificationErrorDescription (tokenVerificationErrorDescription) - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md deleted file mode 100644 index b686996..0000000 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# 변수: validateServerConfig - -```ts -const validateServerConfig: ValidateServerConfig; -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/README.md deleted file mode 100644 index 2e9e8d7..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/README.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -sidebar_label: Node.js SDK ---- - -# Referência do MCP Auth Node.js SDK - -## Classes {#classes} - -- [MCPAuth](/references/js/classes/MCPAuth.md) -- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) -- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) -- [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) - -## Apelidos de Tipos (Type Aliases) {#type-aliases} - -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) -- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) -- [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) -- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) -- [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) -- [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) - -## Variáveis {#variables} - -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) -- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) -- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) - -## Funções {#functions} - -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) -- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) -- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md deleted file mode 100644 index 18a20d3..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md +++ /dev/null @@ -1,331 +0,0 @@ ---- -sidebar_label: MCPAuth ---- - -# Classe: MCPAuth - -A classe principal da biblioteca mcp-auth. Atua como uma fábrica e registro para criar -políticas de autenticação para seus recursos protegidos. - -Ela é inicializada com as configurações do seu servidor e fornece um método `bearerAuth` -para gerar middleware Express para autenticação baseada em token. - -## Exemplo {#example} - -### Uso no modo `resource server` {#usage-in-resource-server-mode} - -Esta é a abordagem recomendada para novas aplicações. - -#### Opção 1: Configuração de descoberta (recomendado para runtimes edge) {#option-1-discovery-config-recommended-for-edge-runtimes} - -Use isto quando quiser que os metadados sejam buscados sob demanda. Isso é especialmente útil para -runtimes edge como Cloudflare Workers, onde não é permitido fetch assíncrono no topo do arquivo. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // Basta passar issuer e type - os metadados serão buscados na primeira requisição - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Opção 2: Configuração resolvida (metadados pré-buscados) {#option-2-resolved-config-pre-fetched-metadata} - -Use isto quando quiser buscar e validar os metadados no momento da inicialização. - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### Usando o middleware {#using-the-middleware} - -```ts -// Monta o router para lidar com Protected Resource Metadata -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// Protege um endpoint de API para o recurso configurado -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // Especifique a qual recurso este endpoint pertence - audience: resourceIdentifier, // Opcionalmente, valide a reivindicação 'aud' - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - }, -); -``` - -### Uso legado no modo `authorization server` (Descontinuado) {#legacy-usage-in-authorization-server-mode-deprecated} - -Esta abordagem é suportada para compatibilidade retroativa. - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth = new MCPAuth({ - // Configuração de descoberta - metadados buscados sob demanda - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, -}); - -// Monta o router para lidar com metadados legados do Authorization Server -app.use(mcpAuth.delegatedRouter()); - -// Protege um endpoint usando a política padrão -app.get( - '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // Lide com a requisição MCP aqui - }, -); -``` - -## Construtores {#constructors} - -### Construtor {#constructor} - -```ts -new MCPAuth(config: MCPAuthConfig): MCPAuth; -``` - -Cria uma instância de MCPAuth. -Valida toda a configuração antecipadamente para falhar rapidamente em caso de erros. - -#### Parâmetros {#parameters} - -##### config {#config} - -[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) - -A configuração de autenticação. - -#### Retorna {#returns} - -`MCPAuth` - -## Propriedades {#properties} - -### config {#config} - -```ts -readonly config: MCPAuthConfig; -``` - -A configuração de autenticação. - -## Métodos {#methods} - -### bearerAuth() {#bearerauth} - -#### Assinatura de chamada {#call-signature} - -```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; -``` - -Cria um handler Bearer auth (middleware Express) que verifica o token de acesso no -cabeçalho `Authorization` da requisição. - -##### Parâmetros {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -Uma função que verifica o token de acesso. Deve aceitar o -token de acesso como uma string e retornar uma promise (ou valor) que resolve para o -resultado da verificação. - -**Veja também** - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para a definição do tipo da função -`verifyAccessToken`. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> - -Configuração opcional para o handler Bearer auth. - -**Veja também** - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para as opções de configuração disponíveis (excluindo -`verifyAccessToken` e `issuer`). - -##### Retorna {#returns} - -`RequestHandler` - -Uma função middleware Express que verifica o token de acesso e adiciona o -resultado da verificação ao objeto da requisição (`req.auth`). - -##### Veja também {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) para detalhes da implementação e os tipos estendidos do -objeto `req.auth` (`AuthInfo`). - -#### Assinatura de chamada {#call-signature} - -```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; -``` - -Cria um handler Bearer auth (middleware Express) que verifica o token de acesso no -cabeçalho `Authorization` da requisição usando um modo de verificação predefinido. - -No modo `'jwt'`, o handler criará uma função de verificação JWT usando o JWK Set -do JWKS URI do servidor de autorização. - -##### Parâmetros {#parameters} - -###### mode {#mode} - -`"jwt"` - -O modo de verificação para o token de acesso. Atualmente, apenas 'jwt' é suportado. - -**Veja também** - -[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) para os modos disponíveis. - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` - -Configuração opcional para o handler Bearer auth, incluindo opções de verificação JWT e -opções remotas de JWK set. - -**Veja também** - - - VerifyJwtConfig para as opções de configuração disponíveis para verificação JWT. - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para as opções de configuração disponíveis (excluindo -`verifyAccessToken` e `issuer`). - -##### Retorna {#returns} - -`RequestHandler` - -Uma função middleware Express que verifica o token de acesso e adiciona o -resultado da verificação ao objeto da requisição (`req.auth`). - -##### Veja também {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) para detalhes da implementação e os tipos estendidos do -objeto `req.auth` (`AuthInfo`). - -##### Lança exceção {#throws} - -se o JWKS URI não for fornecido nos metadados do servidor ao -usar o modo `'jwt'`. - -*** - -### ~~delegatedRouter()~~ {#delegatedrouter} - -```ts -delegatedRouter(): Router; -``` - -Cria um router delegado para servir o endpoint legado OAuth 2.0 Authorization Server Metadata -(`/.well-known/oauth-authorization-server`) com os metadados fornecidos à instância. - -#### Retorna {#returns} - -`Router` - -Um router que serve o endpoint OAuth 2.0 Authorization Server Metadata com os -metadados fornecidos à instância. - -#### Descontinuado {#deprecated} - -Use [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) em vez disso. - -#### Exemplo {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth: MCPAuth; // Suponha que está inicializado -app.use(mcpAuth.delegatedRouter()); -``` - -#### Lança exceção {#throws} - -Se chamado no modo `resource server`. - -*** - -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} - -```ts -protectedResourceMetadataRouter(): Router; -``` - -Cria um router que serve o endpoint OAuth 2.0 Protected Resource Metadata -para todos os recursos configurados. - -Este router cria automaticamente os endpoints `.well-known` corretos para cada -identificador de recurso fornecido na sua configuração. - -#### Retorna {#returns} - -`Router` - -Um router que serve o endpoint OAuth 2.0 Protected Resource Metadata. - -#### Lança exceção {#throws} - -Se chamado no modo `authorization server`. - -#### Exemplo {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// Supondo que mcpAuth foi inicializado com uma ou mais configs `protectedResources` -const mcpAuth: MCPAuth; -const app = express(); - -// Isso servirá metadados em `/.well-known/oauth-protected-resource/...` -// baseado nos seus identificadores de recurso. -app.use(mcpAuth.protectedResourceMetadataRouter()); -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md deleted file mode 100644 index 9c47118..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthAuthServerError ---- - -# Classe: MCPAuthAuthServerError - -Erro lançado quando há um problema com o servidor de autorização remoto. - -## Estende {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Construtores {#constructors} - -### Construtor {#constructor} - -```ts -new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; -``` - -#### Parâmetros {#parameters} - -##### code {#code} - -[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### Retorna {#returns} - -`MCPAuthAuthServerError` - -#### Sobrescreve {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propriedades {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: AuthServerErrorCode; -``` - -O código de erro no formato snake_case. - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthAuthServerError'; -``` - -#### Sobrescreve {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescrita opcional para formatação de rastreamentos de pilha - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converte o erro para um formato JSON amigável para resposta HTTP. - -#### Parâmetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Se deve incluir a causa do erro na resposta JSON. -O padrão é `false`. - -#### Retorna {#returns} - -`Record`\<`string`, `unknown`\> - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Cria a propriedade .stack em um objeto alvo - -#### Parâmetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Retorna {#returns} - -`void` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index 287dd1b..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# Classe: MCPAuthBearerAuthError - -Erro lançado quando há um problema ao autenticar com tokens Bearer. - -## Estende {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Construtores {#constructors} - -### Construtor {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### Parâmetros {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### Retorna {#returns} - -`MCPAuthBearerAuthError` - -#### Sobrescreve {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propriedades {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -O código do erro no formato snake_case. - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### Sobrescreve {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescrita opcional para formatação de stack traces - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converte o erro para um formato JSON amigável para resposta HTTP. - -#### Parâmetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Se deve incluir a causa do erro na resposta JSON. -O padrão é `false`. - -#### Retorna {#returns} - -`Record`\<`string`, `unknown`\> - -#### Sobrescreve {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Cria a propriedade .stack em um objeto alvo - -#### Parâmetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Retorna {#returns} - -`void` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md deleted file mode 100644 index 723509d..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebar_label: MCPAuthConfigError ---- - -# Classe: MCPAuthConfigError - -Erro lançado quando há um problema de configuração com o mcp-auth. - -## Estende {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Construtores {#constructors} - -### Construtor {#constructor} - -```ts -new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; -``` - -#### Parâmetros {#parameters} - -##### code {#code} - -`string` - -O código de erro no formato snake_case. - -##### message {#message} - -`string` - -Uma descrição legível do erro. - -#### Retorna {#returns} - -`MCPAuthConfigError` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propriedades {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -O código de erro no formato snake_case. - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthConfigError'; -``` - -#### Sobrescreve {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescrita opcional para formatação de rastreamentos de pilha - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converte o erro para um formato JSON amigável para resposta HTTP. - -#### Parâmetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Se deve incluir a causa do erro na resposta JSON. -O padrão é `false`. - -#### Retorna {#returns} - -`Record`\<`string`, `unknown`\> - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Cria a propriedade .stack em um objeto alvo - -#### Parâmetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Retorna {#returns} - -`void` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md deleted file mode 100644 index 57aec67..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -sidebar_label: MCPAuthError ---- - -# Classe: MCPAuthError - -Classe base para todos os erros do mcp-auth. - -Ela fornece uma maneira padronizada de lidar com erros relacionados à autenticação (Authentication) e autorização (Authorization) MCP. - -## Estende {#extends} - -- `Error` - -## Estendida por {#extended-by} - -- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) -- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) - -## Construtores {#constructors} - -### Construtor {#constructor} - -```ts -new MCPAuthError(code: string, message: string): MCPAuthError; -``` - -#### Parâmetros {#parameters} - -##### code {#code} - -`string` - -O código do erro no formato snake_case. - -##### message {#message} - -`string` - -Uma descrição legível do erro. - -#### Retorna {#returns} - -`MCPAuthError` - -#### Sobrescreve {#overrides} - -```ts -Error.constructor -``` - -## Propriedades {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### Herdado de {#inherited-from} - -```ts -Error.cause -``` - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -O código do erro no formato snake_case. - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Herdado de {#inherited-from} - -```ts -Error.message -``` - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthError'; -``` - -#### Sobrescreve {#overrides} - -```ts -Error.name -``` - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Herdado de {#inherited-from} - -```ts -Error.stack -``` - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescrita opcional para formatação de stack traces - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Herdado de {#inherited-from} - -```ts -Error.prepareStackTrace -``` - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Herdado de {#inherited-from} - -```ts -Error.stackTraceLimit -``` - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converte o erro para um formato JSON amigável para resposta HTTP. - -#### Parâmetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Se deve incluir a causa do erro na resposta JSON. -Padrão é `false`. - -#### Retorna {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Cria a propriedade .stack em um objeto alvo - -#### Parâmetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Retorna {#returns} - -`void` - -#### Herdado de {#inherited-from} - -```ts -Error.captureStackTrace -``` \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index 991eef4..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# Classe: MCPAuthTokenVerificationError - -Erro lançado quando há um problema ao verificar tokens. - -## Estende {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## Construtores {#constructors} - -### Construtor {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### Parâmetros {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### Retorna {#returns} - -`MCPAuthTokenVerificationError` - -#### Sobrescreve {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## Propriedades {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -O código do erro no formato snake_case. - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### Sobrescreve {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -Sobrescrita opcional para formatação de rastreamentos de pilha - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## Métodos {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -Converte o erro para um formato JSON amigável para resposta HTTP. - -#### Parâmetros {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -Se deve incluir a causa do erro na resposta JSON. -O padrão é `false`. - -#### Retorna {#returns} - -`Record`\<`string`, `unknown`\> - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -Cria a propriedade .stack em um objeto alvo - -#### Parâmetros {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### Retorna {#returns} - -`void` - -#### Herdado de {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md deleted file mode 100644 index 4cb911d..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# Função: createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -Cria uma função para verificar tokens de acesso JWT (Access tokens) usando a função de recuperação de chave fornecida e opções. - -## Parâmetros {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -A função para recuperar a chave usada para verificar o JWT. - -**Veja também** - -JWTVerifyGetKey para a definição de tipo da função de recuperação de chave. - -### options? {#options} - -`JWTVerifyOptions` - -Opções opcionais de verificação do JWT. - -**Veja também** - -JWTVerifyOptions para a definição de tipo das opções. - -## Retorno {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -Uma função que verifica tokens de acesso JWT (Access tokens) e retorna um objeto AuthInfo se o token for válido. Ela exige que o JWT contenha os campos `iss`, `client_id` e `sub` em seu payload, e pode opcionalmente conter os campos `scope` ou `scopes`. A função utiliza a biblioteca `jose` internamente para realizar a verificação do JWT. - -## Veja também {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para a definição de tipo da função retornada. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md deleted file mode 100644 index f169f76..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -sidebar_label: fetchServerConfig ---- - -# Função: fetchServerConfig() - -```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; -``` - -Busca a configuração do servidor de acordo com o emissor (Issuer) e o tipo de servidor de autorização (Authorization). - -Esta função determina automaticamente a URL well-known com base no tipo de servidor, já que servidores OAuth e OpenID Connect possuem convenções diferentes para seus endpoints de metadados. - -## Parâmetros {#parameters} - -### issuer {#issuer} - -`string` - -A URL do emissor (Issuer) do servidor de autorização. - -### config {#config} - -`ServerMetadataConfig` - -O objeto de configuração contendo o tipo de servidor e a função de transpilação opcional. - -## Retorna {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -Uma promise que resolve para a configuração estática do servidor com os metadados buscados. - -## Veja também {#see} - - - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) para a implementação subjacente. - - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) para a especificação de Metadados do Servidor de Autorização OAuth 2.0. - - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) para a especificação de Descoberta do OpenID Connect. - -## Exemplo {#example} - -```ts -import { fetchServerConfig } from 'mcp-auth'; -// Buscando configuração do servidor OAuth -// Isso buscará os metadados de `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` -const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); - -// Buscando configuração do servidor OpenID Connect -// Isso buscará os metadados de `https://auth.logto.io/oidc/.well-known/openid-configuration` -const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); -``` - -## Lança exceção {#throws} - -se a operação de busca falhar. - -## Lança exceção {#throws} - -se os metadados do servidor forem inválidos ou não corresponderem à especificação MCP. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md deleted file mode 100644 index 4ca6bc2..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: fetchServerConfigByWellKnownUrl ---- - -# Função: fetchServerConfigByWellKnownUrl() - -```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; -``` - -Busca a configuração do servidor a partir da well-known URL fornecida e a valida conforme a especificação MCP. - -Se os metadados do servidor não estiverem em conformidade com o esquema esperado, mas você tiver certeza de que são compatíveis, é possível definir uma função `transpileData` para transformar os metadados no formato esperado. - -## Parâmetros {#parameters} - -### wellKnownUrl {#wellknownurl} - -A well-known URL de onde buscar a configuração do servidor. Pode ser uma string ou um objeto URL. - -`string` | `URL` - -### config {#config} - -`ServerMetadataConfig` - -O objeto de configuração contendo o tipo do servidor e, opcionalmente, a função de transpile. - -## Retorno {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -Uma promise que resolve para a configuração estática do servidor com os metadados buscados. - -## Lança exceção {#throws} - -se a operação de busca falhar. - -## Lança exceção {#throws} - -se os metadados do servidor forem inválidos ou não corresponderem à especificação MCP. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md deleted file mode 100644 index bd74823..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# Função: getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -Obtém a URL do emissor (Issuer) a partir de uma configuração de servidor de autenticação. - -- Configuração resolvida: extrai de `metadata.issuer` -- Configuração de descoberta: retorna `issuer` diretamente - -## Parâmetros {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## Retorna {#returns} - -`string` \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md deleted file mode 100644 index aad396f..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# Função: handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -Cria uma função middleware para lidar com autenticação Bearer em uma aplicação Express. - -Este middleware extrai o token Bearer do cabeçalho `Authorization`, verifica-o usando a função -`verifyAccessToken` fornecida e checa o emissor, público e escopos necessários. - -- Se o token for válido, adiciona as informações de autenticação à propriedade `request.auth`; -caso contrário, responde com uma mensagem de erro apropriada. -- Se a verificação do token de acesso falhar, responde com um erro 401 Não autorizado. -- Se o token não possuir os escopos necessários, responde com um erro 403 Proibido. -- Se ocorrerem erros inesperados durante o processo de autenticação, o middleware irá relançá-los. - -**Nota:** O objeto `request.auth` conterá campos estendidos em comparação com a interface padrão -AuthInfo definida no módulo `@modelcontextprotocol/sdk`. Veja a interface estendida neste arquivo para mais detalhes. - -## Parâmetros {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Configuração para o manipulador de autenticação Bearer. - -## Retorno {#returns} - -`RequestHandler` - -Uma função middleware para Express que lida com autenticação Bearer. - -## Veja também {#see} - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para as opções de configuração. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md deleted file mode 100644 index 0a7ffc9..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerConfig ---- - -# Alias de Tipo: AuthServerConfig - -```ts -type AuthServerConfig = - | ResolvedAuthServerConfig - | AuthServerDiscoveryConfig; -``` - -Configuração para o servidor de autorização remoto integrado com o servidor MCP. - -Pode ser: -- **Resolvido**: Contém `metadata` - nenhuma requisição de rede necessária -- **Descoberta**: Contém apenas `issuer` e `type` - os metadados são buscados sob demanda via discovery \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index 665d98e..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# Alias de Tipo: AuthServerConfigError - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -Representa um erro que ocorre durante a validação dos metadados do servidor de autorização. - -## Propriedades {#properties} - -### cause? {#cause} - -```ts -optional cause: Error; -``` - -Uma causa opcional do erro, normalmente uma instância de `Error` que fornece mais contexto. - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -O código que representa o erro de validação específico. - -*** - -### description {#description} - -```ts -description: string; -``` - -Uma descrição legível do erro. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index d6e374d..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# Alias de Tipo: AuthServerConfigErrorCode - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -Os códigos para erros que podem ocorrer ao validar os metadados do servidor de autorização. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index 047abd2..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# Alias de Tipo: AuthServerConfigWarning - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -Representa um aviso que ocorre durante a validação dos metadados do servidor de autorização (authorization server). - -## Propriedades {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -O código que representa o aviso de validação específico. - -*** - -### description {#description} - -```ts -description: string; -``` - -Uma descrição legível do aviso. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index 3e2035f..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# Alias de Tipo: AuthServerConfigWarningCode - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -Os códigos para avisos que podem ocorrer ao validar os metadados do servidor de autorização. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md deleted file mode 100644 index 37b00d6..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -sidebar_label: AuthServerDiscoveryConfig ---- - -# Alias de Tipo: AuthServerDiscoveryConfig - -```ts -type AuthServerDiscoveryConfig = { - issuer: string; - type: AuthServerType; -}; -``` - -Configuração de descoberta para o servidor de autorização remoto. - -Use isto quando quiser que os metadados sejam buscados sob demanda via descoberta quando necessário pela primeira vez. -Isso é útil para ambientes edge como Cloudflare Workers, onde não é permitido fazer fetch assíncrono no topo do escopo. - -## Exemplo {#example} - -```typescript -const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, - }, -}); -``` - -## Propriedades {#properties} - -### issuer {#issuer} - -```ts -issuer: string; -``` - -A URL do emissor (Issuer) do servidor de autorização. Os metadados serão buscados do endpoint well-known derivado deste emissor. - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -O tipo do servidor de autorização. - -#### Veja também {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) para os valores possíveis. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md deleted file mode 100644 index 5c2a3fd..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: AuthServerErrorCode ---- - -# Alias de Tipo: AuthServerErrorCode - -```ts -type AuthServerErrorCode = - | "invalid_server_metadata" - | "invalid_server_config" - | "missing_jwks_uri"; -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index 9cdde09..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# Alias de Tipo: ~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -Configuração para o modo legado de servidor MCP como servidor de autorização. - -## Obsoleto {#deprecated} - -Use a configuração `ResourceServerModeConfig` em vez disso. - -## Propriedades {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -A configuração do único servidor de autorização. - -#### Obsoleto {#deprecated} - -Use a configuração `protectedResources` em vez disso. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index a5cb4c5..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# Alias de Tipo: AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -Os códigos para validação bem-sucedida dos metadados do servidor de autorização. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md deleted file mode 100644 index 1252cf4..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerType ---- - -# Alias de Tipo: AuthServerType - -```ts -type AuthServerType = "oauth" | "oidc"; -``` - -O tipo do servidor de autorização (authorization server). Esta informação deve ser fornecida pela configuração do servidor e indica se o servidor é um servidor de autorização OAuth 2.0 ou OpenID Connect (OIDC). \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index d2b9621..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: AuthorizationServerMetadata ---- - -# Alias de Tipo: AuthorizationServerMetadata - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -Esquema para Metadados do Servidor de Autorização OAuth 2.0 conforme definido na RFC 8414. - -## Veja também {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index dd6c28e..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# Alias de Tipo: BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## Propriedades {#properties} - -### audience? {#audience} - -```ts -optional audience: string; -``` - -O público (Audience) esperado do token de acesso (`aud` claim). Normalmente, este é o servidor de recursos -(API) para o qual o token se destina. Se não for fornecido, a verificação do público será ignorada. - -**Nota:** Se seu servidor de autorização não suporta Indicadores de Recurso (Resource Indicators) (RFC 8707), -você pode omitir este campo, já que o público pode não ser relevante. - -#### Veja {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -Uma string representando um emissor (Issuer) válido, ou uma função para validar o emissor do token de acesso. - -Se uma string for fornecida, ela será usada como o valor esperado do emissor para comparação direta. - -Se uma função for fornecida, ela deve validar o emissor de acordo com as regras em -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md). - -#### Veja {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) para mais detalhes sobre a função de validação. - -*** - -### requiredScopes? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -Um array de escopos (Scopes) obrigatórios que o token de acesso deve possuir. Se o token não contiver -todos esses escopos, um erro será lançado. - -**Nota:** O handler verificará a reivindicação `scope` no token, que pode ser uma string separada por espaços -ou um array de strings, dependendo da implementação do servidor de autorização. Se a reivindicação `scope` não estiver presente, o handler verificará a reivindicação `scopes` -se disponível. - -*** - -### resource? {#resource} - -```ts -optional resource: string; -``` - -O identificador do recurso protegido. Quando fornecido, o handler usará os -servidores de autorização configurados para este recurso para validar o token recebido. -É obrigatório ao usar o handler com uma configuração `protectedResources`. - -*** - -### showErrorDetails? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -Se deve mostrar informações detalhadas de erro na resposta. Isso é útil para depuração -durante o desenvolvimento, mas deve ser desativado em produção para evitar vazamento de informações sensíveis. - -#### Padrão {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -Tipo de função para verificar um token de acesso (Access token). - -Esta função deve lançar um [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) se o token for inválido, -ou retornar um objeto AuthInfo se o token for válido. - -#### Veja {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) para mais detalhes. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index 45363f7..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# Alias de Tipo: BearerAuthErrorCode - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index 08c11ae..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# Alias de Tipo: CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -A versão em camelCase do tipo de Metadados do Servidor de Autorização (Authorization Server Metadata) do OAuth 2.0. - -## Veja também {#see} - -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) para o tipo original e informações dos campos. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index c2d56b3..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# Alias de Tipo: CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -A versão em camelCase do tipo de Metadados de Recurso Protegido do OAuth 2.0. - -## Veja também {#see} - -[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) para o tipo original e informações dos campos. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index b2ebc3e..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# Alias de Tipo: MCPAuthBearerAuthErrorDetails - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## Propriedades {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md deleted file mode 100644 index 6ff49a8..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -sidebar_label: MCPAuthConfig ---- - -# Alias de Tipo: MCPAuthConfig - -```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; -``` - -Configuração para a classe [MCPAuth](/references/js/classes/MCPAuth.md), suportando tanto um único `authorization server` legado quanto a configuração de `resource server`. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index 2df9187..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# Alias de Tipo: MCPAuthTokenVerificationErrorCode (Type Alias: MCPAuthTokenVerificationErrorCode) - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index 86a0ebc..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# Alias de Tipo: ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -Esquema para Metadados de Recurso Protegido do OAuth 2.0. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md deleted file mode 100644 index 0bcb309..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -sidebar_label: ResolvedAuthServerConfig ---- - -# Alias de Tipo: ResolvedAuthServerConfig - -```ts -type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; -``` - -Configuração resolvida para o servidor de autorização remoto com metadados. - -Use isto quando os metadados já estiverem disponíveis, seja codificados diretamente ou obtidos previamente -via `fetchServerConfig()`. - -## Propriedades {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -Os metadados do servidor de autorização (Authorization Server), que devem estar em conformidade com a especificação MCP -(baseada nos Metadados do Servidor de Autorização OAuth 2.0). - -Esses metadados são normalmente obtidos do endpoint well-known do servidor (Metadados do Servidor de Autorização OAuth 2.0 -ou OpenID Connect Discovery); também podem ser fornecidos -diretamente na configuração caso o servidor não suporte tais endpoints. - -**Nota:** Os metadados devem estar no formato camelCase conforme preferido pela biblioteca mcp-auth. - -#### Veja também {#see} - - - [OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -O tipo do servidor de autorização (Authorization Server). - -#### Veja também {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) para os valores possíveis. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index 3299106..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# Alias de Tipo: ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -Configuração para o servidor MCP no modo de servidor de recursos. - -## Propriedades {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -Uma única configuração de servidor de recursos ou um array delas. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index 35b96f7..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# Alias de Tipo: ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -Tipo de função para validar o emissor (Issuer) do token de acesso (Access token). - -Esta função deve lançar um [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) com o código 'invalid_issuer' se o emissor não for válido. O emissor deve ser validado em relação a: - -1. Os servidores de autorização configurados nos metadados do servidor de autenticação do MCP-Auth -2. Os servidores de autorização listados nos metadados do recurso protegido - -## Parâmetros {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## Retorno {#returns} - -`void` - -## Lança exceção {#throws} - -Quando o emissor (Issuer) não é reconhecido ou é inválido. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index a16a14c..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# Alias de Tipo: VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -Tipo de função para verificar um token de acesso (Access token). - -Esta função deve lançar um [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) se o token for inválido, -ou retornar um objeto AuthInfo se o token for válido. - -Por exemplo, se você tiver uma função de verificação de JWT, ela deve pelo menos verificar a -assinatura do token, validar sua expiração e extrair as reivindicações (Claims) necessárias para retornar um objeto `AuthInfo`. - -**Nota:** Não há necessidade de verificar os seguintes campos no token, pois eles serão verificados -pelo handler: - -- `iss` (emissor / issuer) -- `aud` (público / audience) -- `scope` (escopos / scopes) - -## Parâmetros {#parameters} - -### token {#token} - -`string` - -A string do token de acesso (Access token) a ser verificada. - -## Retorno {#returns} - -`MaybePromise`\<`AuthInfo`\> - -Uma promise que resolve para um objeto AuthInfo ou um valor síncrono se o -token for válido. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index f20ba05..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# Alias de Tipo: VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -Os modos de verificação integrados suportados por `bearerAuth`. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md deleted file mode 100644 index 940ff45..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: authServerErrorDescription ---- - -# Variável: authServerErrorDescription - -```ts -const authServerErrorDescription: Readonly>; -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index 426eca9..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# Variável: authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -Schema Zod para Metadados do Servidor de Autorização OAuth 2.0 conforme definido na RFC 8414. - -## Veja também {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index 0f6a202..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# Variável: bearerAuthErrorDescription - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index 4b08e9b..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# Variável: camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -A versão camelCase do schema Zod de Metadados do Servidor de Autorização OAuth 2.0. - -## Veja também {#see} - -[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) para o schema original e informações dos campos. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index 816a3ec..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# Variável: camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -A versão camelCase do schema Zod de Metadados de Recurso Protegido do OAuth 2.0. - -## Veja também {#see} - -[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) para o schema original e informações dos campos. \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md deleted file mode 100644 index d0e76b1..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# Variável: defaultValues - -```ts -const defaultValues: Readonly>; -``` diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index 5080765..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# Variável: protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -Schema Zod para Metadados de Recurso Protegido do OAuth 2.0 (OAuth 2.0 Protected Resource Metadata). \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md deleted file mode 100644 index 13265ff..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: serverMetadataPaths ---- - -# Variável: serverMetadataPaths - -```ts -const serverMetadataPaths: Readonly<{ - oauth: "/.well-known/oauth-authorization-server"; - oidc: "/.well-known/openid-configuration"; -}>; -``` \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index 755437b..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: tokenVerificationErrorDescription ---- - -# Variável: tokenVerificationErrorDescription - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` \ No newline at end of file diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md deleted file mode 100644 index 29e1bcb..0000000 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# Variável: validateServerConfig - -```ts -const validateServerConfig: ValidateServerConfig; -``` \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/README.md deleted file mode 100644 index 6e8e663..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/README.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -sidebar_label: Node.js SDK ---- - -# MCP Auth Node.js SDK 参考 - -## 类 {#classes} - -- [MCPAuth](/references/js/classes/MCPAuth.md) -- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) -- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) -- [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) - -## 类型别名 {#type-aliases} - -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) -- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) -- [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) -- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) -- [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) -- [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) - -## 变量 {#variables} - -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) -- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) -- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) - -## 函数 {#functions} - -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) -- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) -- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md deleted file mode 100644 index 500711a..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md +++ /dev/null @@ -1,311 +0,0 @@ ---- -sidebar_label: MCPAuth ---- - -# 类:MCPAuth - -mcp-auth 库的主类。它作为工厂和注册中心,用于为你的受保护资源创建认证 (Authentication) 策略。 - -它通过你的服务器配置进行初始化,并提供 `bearerAuth` 方法,用于生成基于令牌的 Express 中间件认证 (Authentication)。 - -## 示例 {#example} - -### 在 `资源服务器` 模式下的用法 {#usage-in-resource-server-mode} - -这是新应用程序推荐的方式。 - -#### 选项 1:发现配置(推荐用于边缘运行时) {#option-1-discovery-config-recommended-for-edge-runtimes} - -当你希望按需获取元数据时使用此方式。对于如 Cloudflare Workers 这类不允许顶层异步 fetch 的边缘运行时尤其有用。 - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // 只需传递 issuer 和 type —— 元数据将在首次请求时获取 - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### 选项 2:已解析配置(预先获取元数据) {#option-2-resolved-config-pre-fetched-metadata} - -当你希望在启动时获取并验证元数据时使用此方式。 - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### 使用中间件 {#using-the-middleware} - -```ts -// 挂载路由以处理受保护资源元数据 -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// 为已配置资源保护 API 端点 -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // 指定该端点属于哪个资源 - audience: resourceIdentifier, // 可选,校验 'aud' 声明 (Claim) - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - }, -); -``` - -### 传统 `授权 (Authorization) 服务器` 模式用法(已弃用) {#legacy-usage-in-authorization-server-mode-deprecated} - -此方式为向后兼容而保留。 - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth = new MCPAuth({ - // 发现配置 - 按需获取元数据 - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, -}); - -// 挂载路由以处理传统授权 (Authorization) 服务器元数据 -app.use(mcpAuth.delegatedRouter()); - -// 使用默认策略保护端点 -app.get( - '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // 在此处理 MCP 请求 - }, -); -``` - -## 构造函数 {#constructors} - -### 构造函数 {#constructor} - -```ts -new MCPAuth(config: MCPAuthConfig): MCPAuth; -``` - -创建 MCPAuth 实例。 -它会提前验证整个配置,以便在出错时快速失败。 - -#### 参数 {#parameters} - -##### config {#config} - -[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) - -认证 (Authentication) 配置。 - -#### 返回值 {#returns} - -`MCPAuth` - -## 属性 {#properties} - -### config {#config} - -```ts -readonly config: MCPAuthConfig; -``` - -认证 (Authentication) 配置。 - -## 方法 {#methods} - -### bearerAuth() {#bearerauth} - -#### 调用签名 {#call-signature} - -```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; -``` - -创建一个 Bearer 认证 (Authentication) 处理器(Express 中间件),用于验证请求的 `Authorization` 头中的访问令牌 (Access token)。 - -##### 参数 {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -用于验证访问令牌 (Access token) 的函数。它应接受访问令牌 (Access token) 字符串,并返回一个 promise(或值),解析为验证结果。 - -**参见** - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以获取 `verifyAccessToken` 函数的类型定义。 - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> - -Bearer 认证 (Authentication) 处理器的可选配置。 - -**参见** - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以获取可用的配置选项(不包括 `verifyAccessToken` 和 `issuer`)。 - -##### 返回值 {#returns} - -`RequestHandler` - -一个 Express 中间件函数,用于验证访问令牌 (Access token) 并将验证结果添加到请求对象 (`req.auth`)。 - -##### 参见 {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以了解实现细节及 `req.auth` (`AuthInfo`) 对象的扩展类型。 - -#### 调用签名 {#call-signature} - -```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; -``` - -创建一个 Bearer 认证 (Authentication) 处理器(Express 中间件),使用预定义的验证模式验证请求的 `Authorization` 头中的访问令牌 (Access token)。 - -在 `'jwt'` 模式下,处理器将使用授权 (Authorization) 服务器的 JWKS URI 创建 JWT 验证函数。 - -##### 参数 {#parameters} - -###### mode {#mode} - -`"jwt"` - -访问令牌 (Access token) 的验证模式。目前仅支持 'jwt'。 - -**参见** - -[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) 以获取可用模式。 - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` - -Bearer 认证 (Authentication) 处理器的可选配置,包括 JWT 验证选项和远程 JWK set 选项。 - -**参见** - - - VerifyJwtConfig 以获取 JWT 验证的可用配置选项。 - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以获取可用的配置选项(不包括 `verifyAccessToken` 和 `issuer`)。 - -##### 返回值 {#returns} - -`RequestHandler` - -一个 Express 中间件函数,用于验证访问令牌 (Access token) 并将验证结果添加到请求对象 (`req.auth`)。 - -##### 参见 {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以了解实现细节及 `req.auth` (`AuthInfo`) 对象的扩展类型。 - -##### 抛出 {#throws} - -当在 `'jwt'` 模式下,服务器元数据中未提供 JWKS URI 时抛出。 - -*** - -### ~~delegatedRouter()~~ {#delegatedrouter} - -```ts -delegatedRouter(): Router; -``` - -创建一个代理路由器,用于提供传统 OAuth 2.0 授权 (Authorization) 服务器元数据端点 -(`/.well-known/oauth-authorization-server`),并使用实例提供的元数据。 - -#### 返回值 {#returns} - -`Router` - -用于提供 OAuth 2.0 授权 (Authorization) 服务器元数据端点的路由器,使用实例提供的元数据。 - -#### 已弃用 {#deprecated} - -请改用 [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter)。 - -#### 示例 {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth: MCPAuth; // 假设已初始化 -app.use(mcpAuth.delegatedRouter()); -``` - -#### 抛出 {#throws} - -如果在 `资源服务器` 模式下调用,则抛出。 - -*** - -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} - -```ts -protectedResourceMetadataRouter(): Router; -``` - -创建一个路由器,用于为所有已配置资源提供 OAuth 2.0 受保护资源元数据端点。 - -该路由器会根据你配置中提供的每个资源标识符,自动创建正确的 `.well-known` 端点。 - -#### 返回值 {#returns} - -`Router` - -用于提供 OAuth 2.0 受保护资源元数据端点的路由器。 - -#### 抛出 {#throws} - -如果在 `授权 (Authorization) 服务器` 模式下调用,则抛出。 - -#### 示例 {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// 假设 mcpAuth 已通过一个或多个 `protectedResources` 配置初始化 -const mcpAuth: MCPAuth; -const app = express(); - -// 这将在 `/.well-known/oauth-protected-resource/...` 路径下 -// 根据你的资源标识符提供元数据。 -app.use(mcpAuth.protectedResourceMetadataRouter()); -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md deleted file mode 100644 index 75a6081..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthAuthServerError ---- - -# 类:MCPAuthAuthServerError - -当远程授权 (Authorization) 服务器出现问题时抛出的错误。 - -## 继承自 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 构造函数 {#constructors} - -### 构造函数 {#constructor} - -```ts -new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; -``` - -#### 参数 {#parameters} - -##### code {#code} - -[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### 返回 {#returns} - -`MCPAuthAuthServerError` - -#### 重写自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 属性 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: AuthServerErrorCode; -``` - -以 snake_case 格式表示的错误代码。 - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthAuthServerError'; -``` - -#### 重写自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可选的堆栈跟踪格式化重写 - -#### 参数 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 返回 {#returns} - -`any` - -#### 参考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -将错误转换为适合 HTTP 响应的 JSON 格式。 - -#### 参数 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 响应中包含错误原因。 -默认为 `false`。 - -#### 返回 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目标对象上创建 .stack 属性 - -#### 参数 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 返回 {#returns} - -`void` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index 04accac..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# 类:MCPAuthBearerAuthError - -当使用 Bearer 令牌进行认证 (Authentication) 时出现问题时抛出的错误。 - -## 继承自 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 构造函数 {#constructors} - -### 构造函数 {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### 参数 {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### 返回值 {#returns} - -`MCPAuthBearerAuthError` - -#### 重写自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 属性 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -错误码,采用 snake_case 格式。 - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### 重写自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可选的堆栈跟踪格式化重写 - -#### 参数 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 返回值 {#returns} - -`any` - -#### 参考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -将错误转换为适合 HTTP 响应的 JSON 格式。 - -#### 参数 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 响应中包含错误原因。 -默认为 `false`。 - -#### 返回值 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 重写自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目标对象上创建 .stack 属性 - -#### 参数 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 返回值 {#returns} - -`void` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md deleted file mode 100644 index b79c254..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebar_label: MCPAuthConfigError ---- - -# 类:MCPAuthConfigError - -当 mcp-auth 配置出现问题时抛出的错误。 - -## 继承自 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 构造函数 {#constructors} - -### 构造函数 {#constructor} - -```ts -new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; -``` - -#### 参数 {#parameters} - -##### code {#code} - -`string` - -以 snake_case 格式表示的错误代码。 - -##### message {#message} - -`string` - -对错误的人类可读描述。 - -#### 返回值 {#returns} - -`MCPAuthConfigError` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 属性 {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -以 snake_case 格式表示的错误代码。 - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthConfigError'; -``` - -#### 重写自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可选的堆栈跟踪格式化重写 - -#### 参数 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 返回值 {#returns} - -`any` - -#### 参考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -将错误转换为适合 HTTP 响应的 JSON 格式。 - -#### 参数 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 响应中包含错误原因。 -默认为 `false`。 - -#### 返回值 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目标对象上创建 .stack 属性 - -#### 参数 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 返回值 {#returns} - -`void` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md deleted file mode 100644 index e20aab8..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -sidebar_label: MCPAuthError ---- - -# 类:MCPAuthError - -所有 mcp-auth 错误的基类。 - -它为处理与 MCP 认证 (Authentication) 和授权 (Authorization) 相关的错误提供了标准化方式。 - -## 继承自 {#extends} - -- `Error` - -## 被以下类继承 {#extended-by} - -- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) -- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) - -## 构造函数 {#constructors} - -### 构造函数 {#constructor} - -```ts -new MCPAuthError(code: string, message: string): MCPAuthError; -``` - -#### 参数 {#parameters} - -##### code {#code} - -`string` - -以 snake_case 格式表示的错误代码。 - -##### message {#message} - -`string` - -对错误的人类可读描述。 - -#### 返回 {#returns} - -`MCPAuthError` - -#### 重写自 {#overrides} - -```ts -Error.constructor -``` - -## 属性 {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### 继承自 {#inherited-from} - -```ts -Error.cause -``` - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -以 snake_case 格式表示的错误代码。 - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 继承自 {#inherited-from} - -```ts -Error.message -``` - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthError'; -``` - -#### 重写自 {#overrides} - -```ts -Error.name -``` - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 继承自 {#inherited-from} - -```ts -Error.stack -``` - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可选的堆栈跟踪格式化重写 - -#### 参数 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 返回 {#returns} - -`any` - -#### 参考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 继承自 {#inherited-from} - -```ts -Error.prepareStackTrace -``` - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 继承自 {#inherited-from} - -```ts -Error.stackTraceLimit -``` - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -将错误转换为适合 HTTP 响应的 JSON 格式。 - -#### 参数 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 响应中包含错误原因。 -默认为 `false`。 - -#### 返回 {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目标对象上创建 .stack 属性 - -#### 参数 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 返回 {#returns} - -`void` - -#### 继承自 {#inherited-from} - -```ts -Error.captureStackTrace -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index 2784c6d..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# 类:MCPAuthTokenVerificationError - -在验证令牌时出现问题时抛出的错误。 - -## 继承自 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 构造函数 {#constructors} - -### 构造函数 {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### 参数 {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### 返回值 {#returns} - -`MCPAuthTokenVerificationError` - -#### 重写自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 属性 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -错误代码,采用 snake_case 格式。 - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### 重写自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可选的堆栈跟踪格式化重写 - -#### 参数 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 返回值 {#returns} - -`any` - -#### 参考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -将错误转换为适合 HTTP 响应的 JSON 格式。 - -#### 参数 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 响应中包含错误原因。 -默认为 `false`。 - -#### 返回值 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目标对象上创建 .stack 属性 - -#### 参数 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 返回值 {#returns} - -`void` - -#### 继承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md deleted file mode 100644 index b3c3169..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# 函数:createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -使用提供的密钥检索函数和选项,创建一个用于验证 JWT 访问令牌 (Access token) 的函数。 - -## 参数 {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -用于检索验证 JWT 所需密钥的函数。 - -**参见** - -JWTVerifyGetKey 以获取密钥检索函数的类型定义。 - -### options? {#options} - -`JWTVerifyOptions` - -可选的 JWT 验证选项。 - -**参见** - -JWTVerifyOptions 以获取选项的类型定义。 - -## 返回值 {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -一个用于验证 JWT 访问令牌 (Access token) 的函数,如果令牌有效,则返回一个 AuthInfo 对象。该函数要求 JWT 的 payload 中包含 `iss`、`client_id` 和 `sub` 字段,并且可以选择性地包含 `scope` 或 `scopes` 字段。该函数底层使用 `jose` 库来执行 JWT 验证。 - -## 参见 {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以获取返回函数的类型定义。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md deleted file mode 100644 index f826435..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -sidebar_label: fetchServerConfig ---- - -# 函数:fetchServerConfig() - -```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; -``` - -根据发行者 (Issuer) 和授权 (Authorization) 服务器类型获取服务器配置。 - -此函数会根据服务器类型自动确定 well-known URL,因为 OAuth 和 OpenID Connect 服务器在其元数据端点上有不同的约定。 - -## 参数 {#parameters} - -### issuer {#issuer} - -`string` - -授权 (Authorization) 服务器的发行者 (Issuer) URL。 - -### config {#config} - -`ServerMetadataConfig` - -包含服务器类型和可选转译函数的配置对象。 - -## 返回值 {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -一个 promise,解析为带有获取到元数据的静态服务器配置。 - -## 参见 {#see} - - - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) 了解底层实现。 - - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) 查看 OAuth 2.0 授权 (Authorization) 服务器元数据规范。 - - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) 查看 OpenID Connect 发现规范。 - -## 示例 {#example} - -```ts -import { fetchServerConfig } from 'mcp-auth'; -// 获取 OAuth 服务器配置 -// 这将从 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` 获取元数据 -const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); - -// 获取 OpenID Connect 服务器配置 -// 这将从 `https://auth.logto.io/oidc/.well-known/openid-configuration` 获取元数据 -const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); -``` - -## 抛出 {#throws} - -如果获取操作失败。 - -## 抛出 {#throws} - -如果服务器元数据无效或不符合 MCP 规范。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md deleted file mode 100644 index 871ca9d..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: fetchServerConfigByWellKnownUrl ---- - -# 函数:fetchServerConfigByWellKnownUrl() - -```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; -``` - -从提供的 well-known URL 获取服务器配置,并根据 MCP 规范进行校验。 - -如果服务器元数据不符合预期的 schema,但你确定它是兼容的,你可以定义一个 `transpileData` 函数,将元数据转换为预期格式。 - -## 参数 {#parameters} - -### wellKnownUrl {#wellknownurl} - -用于获取服务器配置的 well-known URL。可以是字符串或 URL 对象。 - -`string` | `URL` - -### config {#config} - -`ServerMetadataConfig` - -包含服务器类型和可选 transpile 函数的配置对象。 - -## 返回值 {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -一个 promise,解析为带有获取到的元数据的静态服务器配置。 - -## 抛出异常 {#throws} - -如果获取操作失败。 - -## 抛出异常 {#throws} - -如果服务器元数据无效或不符合 MCP 规范。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md deleted file mode 100644 index 338c84c..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# 函数:getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -从认证服务器配置中获取发行者 (Issuer) URL。 - -- 已解析配置:从 `metadata.issuer` 提取 -- 发现配置:直接返回 `issuer` - -## 参数 {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## 返回值 {#returns} - -`string` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md deleted file mode 100644 index 5b761ea..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# 函数:handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -在 Express 应用中创建用于处理 Bearer 认证 (Authentication) 的中间件函数。 - -该中间件会从 `Authorization` 头中提取 Bearer 令牌,使用提供的 `verifyAccessToken` 函数进行验证,并检查发行者 (Issuer)、受众 (Audience) 和所需权限 (Scopes)。 - -- 如果令牌有效,会将认证 (Authentication) 信息添加到 `request.auth` 属性; - 如果无效,则返回相应的错误信息。 -- 如果访问令牌 (Access token) 验证失败,则返回 401 未授权错误。 -- 如果令牌不包含所需的权限 (Scopes),则返回 403 禁止访问错误。 -- 如果在认证 (Authentication) 过程中发生意外错误,中间件会重新抛出这些错误。 - -**注意:** `request.auth` 对象会包含比 `@modelcontextprotocol/sdk` 模块中定义的标准 AuthInfo 接口更多的扩展字段。详细信息请参见本文件中的扩展接口。 - -## 参数 {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Bearer 认证 (Authentication) 处理器的配置。 - -## 返回值 {#returns} - -`RequestHandler` - -用于 Express 的 Bearer 认证 (Authentication) 中间件函数。 - -## 参见 {#see} - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以了解配置选项。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md deleted file mode 100644 index 36b0b97..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerConfig ---- - -# 类型别名:AuthServerConfig - -```ts -type AuthServerConfig = - | ResolvedAuthServerConfig - | AuthServerDiscoveryConfig; -``` - -与 MCP 服务器集成的远程授权服务器 (Authorization server) 配置。 - -可以是以下两种之一: -- **已解析(Resolved)**:包含 `metadata` —— 无需网络请求 -- **发现(Discovery)**:仅包含 `issuer` 和 `type` —— 通过发现按需获取元数据 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index 94d1e9c..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# 类型别名:AuthServerConfigError - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -表示在验证授权服务器元数据时发生的错误。 - -## 属性 {#properties} - -### cause? {#cause} - -```ts -optional cause: Error; -``` - -错误的可选原因,通常是 `Error` 的实例,用于提供更多上下文信息。 - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -表示具体验证错误的代码。 - -*** - -### description {#description} - -```ts -description: string; -``` - -对错误的人类可读描述。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index a5b9d02..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# 类型别名:AuthServerConfigErrorCode - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -在验证授权服务器元数据时可能出现的错误代码。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index ec6df03..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# 类型别名:AuthServerConfigWarning - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -表示在验证授权服务器元数据时发生的警告。 - -## 属性 {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -表示特定验证警告的代码。 - -*** - -### description {#description} - -```ts -description: string; -``` - -该警告的人类可读描述。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index 2f51a52..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# 类型别名:AuthServerConfigWarningCode - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -在验证授权服务器元数据时可能出现的警告代码。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md deleted file mode 100644 index e43d00a..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -sidebar_label: AuthServerDiscoveryConfig ---- - -# 类型别名:AuthServerDiscoveryConfig - -```ts -type AuthServerDiscoveryConfig = { - issuer: string; - type: AuthServerType; -}; -``` - -远程授权 (Authorization) 服务器的发现配置。 - -当你希望在首次需要时通过发现按需获取元数据时使用此配置。 -这对于像 Cloudflare Workers 这样的边缘运行时非常有用,因为不允许顶层异步 fetch。 - -## 示例 {#example} - -```typescript -const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, - }, -}); -``` - -## 属性 {#properties} - -### issuer {#issuer} - -```ts -issuer: string; -``` - -授权 (Authorization) 服务器的发行者 (Issuer) URL。元数据将从由此发行者 (Issuer) 派生的 well-known 端点获取。 - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -授权 (Authorization) 服务器的类型。 - -#### 参见 {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) 以获取可能的取值。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md deleted file mode 100644 index f285c5a..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: AuthServerErrorCode ---- - -# 类型别名:AuthServerErrorCode - -```ts -type AuthServerErrorCode = - | "invalid_server_metadata" - | "invalid_server_config" - | "missing_jwks_uri"; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index 95c24f3..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# 类型别名:~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -用于传统 MCP 服务器作为授权服务器模式的配置。 - -## 已弃用 {#deprecated} - -请改用 `ResourceServerModeConfig` 配置。 - -## 属性 {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -单一授权服务器配置。 - -#### 已弃用 {#deprecated} - -请改用 `protectedResources` 配置。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index 18fcf46..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# 类型别名:AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -用于授权服务器元数据验证成功的代码。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md deleted file mode 100644 index 0e4748a..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerType ---- - -# 类型别名:AuthServerType - -```ts -type AuthServerType = "oauth" | "oidc"; -``` - -授权 (Authorization) 服务器的类型。此信息应由服务器配置提供,并指示该服务器是 OAuth 2.0 还是 OpenID Connect (OIDC) 授权 (Authorization) 服务器。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index 52c5694..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: AuthorizationServerMetadata ---- - -# 类型别名:AuthorizationServerMetadata - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -OAuth 2.0 授权服务器元数据 (Authorization Server Metadata) 的模式,定义见 RFC 8414。 - -## 参考 {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index edd3620..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# 类型别名:BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## 属性 {#properties} - -### audience? {#audience} - -```ts -optional audience: string; -``` - -访问令牌 (Access token) 的预期受众 (Audience)(`aud` 声明 (Claim))。这通常是令牌所针对的资源服务器(API)。如果未提供,将跳过受众 (Audience) 检查。 - -**注意:** 如果你的授权服务器不支持资源指示器 (Resource Indicators)(RFC 8707),你可以省略此字段,因为受众 (Audience) 可能不相关。 - -#### 参见 {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -表示有效发行者 (Issuer) 的字符串,或用于验证访问令牌 (Access token) 发行者 (Issuer) 的函数。 - -如果提供字符串,则将其用作预期的发行者 (Issuer) 值进行直接比较。 - -如果提供函数,则应根据 [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 中的规则验证发行者 (Issuer)。 - -#### 参见 {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 以获取有关验证函数的更多详细信息。 - -*** - -### requiredScopes? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -访问令牌 (Access token) 必须具备的权限 (Scopes) 数组。如果令牌未包含所有这些权限 (Scopes),将抛出错误。 - -**注意:** 处理程序会检查令牌中的 `scope` 声明 (Claim),该声明 (Claim) 可能是以空格分隔的字符串或字符串数组,具体取决于授权服务器的实现。如果未包含 `scope` 声明 (Claim),处理程序会检查 `scopes` 声明 (Claim)(如果可用)。 - -*** - -### resource? {#resource} - -```ts -optional resource: string; -``` - -受保护资源的标识符。当提供该字段时,处理程序将使用为此资源配置的授权服务器来验证收到的令牌。在使用带有 `protectedResources` 配置的处理程序时是必需的。 - -*** - -### showErrorDetails? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -是否在响应中显示详细的错误信息。这对于开发期间调试很有用,但在生产环境中应禁用,以避免泄露敏感信息。 - -#### 默认值 {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -用于验证访问令牌 (Access token) 的函数类型。 - -如果令牌无效,此函数应抛出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md);如果令牌有效,则返回 AuthInfo 对象。 - -#### 参见 {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以获取更多详细信息。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index becf5bb..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# 类型别名:BearerAuthErrorCode - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index ef9d329..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# 类型别名:CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -OAuth 2.0 授权服务器元数据 (Authorization Server Metadata) 类型的 camelCase 版本。 - -## 参见 {#see} - -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 以获取原始类型和字段信息。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index 7cbb4f0..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# 类型别名:CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -OAuth 2.0 受保护资源元数据类型的 camelCase 版本。 - -## 参见 {#see} - -[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) 以获取原始类型和字段信息。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index c29c7f4..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# 类型别名:MCPAuthBearerAuthErrorDetails - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## 属性 {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md deleted file mode 100644 index dfe0b52..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -sidebar_label: MCPAuthConfig ---- - -# 类型别名:MCPAuthConfig - -```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; -``` - -用于 [MCPAuth](/references/js/classes/MCPAuth.md) 类的配置,支持单一传统 `authorization server` 或 `resource server` 配置。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index 6daa15a..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# 类型别名:MCPAuthTokenVerificationErrorCode - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index db7b426..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# 类型别名:ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -OAuth 2.0 受保护资源元数据的模式 (Schema)。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md deleted file mode 100644 index 35f66b4..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -sidebar_label: ResolvedAuthServerConfig ---- - -# 类型别名:ResolvedAuthServerConfig - -```ts -type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; -``` - -带有元数据的远程授权 (Authorization) 服务器的已解析配置。 - -当元数据已经可用时(无论是硬编码还是通过 `fetchServerConfig()` 预先获取),可以使用此类型。 - -## 属性 {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -授权 (Authorization) 服务器的元数据,应符合 MCP 规范(基于 OAuth 2.0 授权 (Authorization) 服务器元数据)。 - -此元数据通常从服务器的 well-known 端点(OAuth 2.0 授权 (Authorization) 服务器元数据或 OpenID Connect 发现)获取;如果服务器不支持这些端点,也可以直接在配置中提供。 - -**注意:** 元数据应为 camelCase 格式,这是 mcp-auth 库推荐的格式。 - -#### 参见 {#see} - - - [OAuth 2.0 授权 (Authorization) 服务器元数据](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect 发现](https://openid.net/specs/openid-connect-discovery-1_0.html) - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -授权 (Authorization) 服务器的类型。 - -#### 参见 {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) 以获取可能的取值。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index 2b45c0b..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# 类型别名:ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -MCP 服务器作为资源服务器模式的配置。 - -## 属性 {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -单个资源服务器配置或其数组。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index 2168813..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# 类型别名:ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -用于验证访问令牌 (Access token) 发行者 (Issuer) 的函数类型。 - -如果发行者 (Issuer) 无效,此函数应抛出一个带有代码 'invalid_issuer' 的 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)。发行者 (Issuer) 应根据以下内容进行验证: - -1. MCP-Auth 的授权服务器 (Authorization server) 元数据中配置的授权服务器 (Authorization server) -2. 受保护资源元数据中列出的授权服务器 (Authorization server) - -## 参数 {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## 返回值 {#returns} - -`void` - -## 抛出 {#throws} - -当发行者 (Issuer) 未被识别或无效时抛出。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index 514817a..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# 类型别名:VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -用于验证访问令牌 (Access token) 的函数类型。 - -如果令牌无效,此函数应抛出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md); -如果令牌有效,则返回一个 AuthInfo 对象。 - -例如,如果你有一个 JWT 验证函数,它至少应检查令牌的签名、验证其过期时间,并提取必要的声明 (Claims) 以返回一个 `AuthInfo` 对象。 - -**注意:** 无需验证令牌中的以下字段,因为它们会由处理程序检查: - -- `iss`(发行者 (Issuer)) -- `aud`(受众 (Audience)) -- `scope`(权限 (Scopes)) - -## 参数 {#parameters} - -### token {#token} - -`string` - -要验证的访问令牌 (Access token) 字符串。 - -## 返回值 {#returns} - -`MaybePromise`\<`AuthInfo`\> - -一个 Promise,当令牌有效时解析为 AuthInfo 对象,或同步返回该对象。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index a616dbc..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# 类型别名:VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -`bearerAuth` 支持的内置验证模式。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md deleted file mode 100644 index ebd2c2d..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: authServerErrorDescription ---- - -# 变量:authServerErrorDescription - -```ts -const authServerErrorDescription: Readonly>; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index 95c6120..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# 变量:authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -用于 OAuth 2.0 授权服务器元数据(Authorization Server Metadata)的 Zod schema,定义见 RFC 8414。 - -## 参考 {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index 17d19d6..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# 变量:bearerAuthErrorDescription - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index e969080..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# 变量:camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 授权服务器元数据 Zod schema 的 camelCase 版本。 - -## 参见 {#see} - -[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) 以获取原始 schema 和字段信息。 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index 9766dba..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# 变量:camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 受保护资源元数据 Zod schema 的 camelCase 版本。 - -## 参见 {#see} - -[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 以获取原始 schema 和字段信息。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md deleted file mode 100644 index 6563112..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# 变量:defaultValues - -```ts -const defaultValues: Readonly>; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index 6b6f99b..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# 变量:protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -用于 OAuth 2.0 受保护资源元数据的 Zod schema。 \ No newline at end of file diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md deleted file mode 100644 index 1c3c1a6..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: serverMetadataPaths ---- - -# 变量:serverMetadataPaths - -```ts -const serverMetadataPaths: Readonly<{ - oauth: "/.well-known/oauth-authorization-server"; - oidc: "/.well-known/openid-configuration"; -}>; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index 06504fa..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: tokenVerificationErrorDescription ---- - -# 变量:tokenVerificationErrorDescription - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md deleted file mode 100644 index 5428676..0000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# 变量:validateServerConfig - -```ts -const validateServerConfig: ValidateServerConfig; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/README.md deleted file mode 100644 index 25fb0f5..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/README.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -sidebar_label: Node.js SDK ---- - -# MCP Auth Node.js SDK 參考文件 (MCP Auth Node.js SDK reference) - -## 類別 (Classes) {#classes} - -- [MCPAuth](/references/js/classes/MCPAuth.md) -- [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) -- [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) -- [MCPAuthConfigError](/references/js/classes/MCPAuthConfigError.md) -- [MCPAuthError](/references/js/classes/MCPAuthError.md) -- [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md) - -## 型別別名 (Type Aliases) {#type-aliases} - -- [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) -- [AuthServerConfig](/references/js/type-aliases/AuthServerConfig.md) -- [AuthServerConfigError](/references/js/type-aliases/AuthServerConfigError.md) -- [AuthServerConfigErrorCode](/references/js/type-aliases/AuthServerConfigErrorCode.md) -- [AuthServerConfigWarning](/references/js/type-aliases/AuthServerConfigWarning.md) -- [AuthServerConfigWarningCode](/references/js/type-aliases/AuthServerConfigWarningCode.md) -- [AuthServerDiscoveryConfig](/references/js/type-aliases/AuthServerDiscoveryConfig.md) -- [AuthServerErrorCode](/references/js/type-aliases/AuthServerErrorCode.md) -- [~~AuthServerModeConfig~~](/references/js/type-aliases/AuthServerModeConfig.md) -- [AuthServerSuccessCode](/references/js/type-aliases/AuthServerSuccessCode.md) -- [AuthServerType](/references/js/type-aliases/AuthServerType.md) -- [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) -- [BearerAuthErrorCode](/references/js/type-aliases/BearerAuthErrorCode.md) -- [CamelCaseAuthorizationServerMetadata](/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md) -- [CamelCaseProtectedResourceMetadata](/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md) -- [MCPAuthBearerAuthErrorDetails](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -- [MCPAuthConfig](/references/js/type-aliases/MCPAuthConfig.md) -- [MCPAuthTokenVerificationErrorCode](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -- [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) -- [ResolvedAuthServerConfig](/references/js/type-aliases/ResolvedAuthServerConfig.md) -- [ResourceServerModeConfig](/references/js/type-aliases/ResourceServerModeConfig.md) -- [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) -- [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) -- [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) - -## 變數 (Variables) {#variables} - -- [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) -- [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) -- [bearerAuthErrorDescription](/references/js/variables/bearerAuthErrorDescription.md) -- [camelCaseAuthorizationServerMetadataSchema](/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md) -- [camelCaseProtectedResourceMetadataSchema](/references/js/variables/camelCaseProtectedResourceMetadataSchema.md) -- [defaultValues](/references/js/variables/defaultValues.md) -- [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) -- [serverMetadataPaths](/references/js/variables/serverMetadataPaths.md) -- [tokenVerificationErrorDescription](/references/js/variables/tokenVerificationErrorDescription.md) -- [validateServerConfig](/references/js/variables/validateServerConfig.md) - -## 函式 (Functions) {#functions} - -- [createVerifyJwt](/references/js/functions/createVerifyJwt.md) -- [fetchServerConfig](/references/js/functions/fetchServerConfig.md) -- [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [getIssuer](/references/js/functions/getIssuer.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md deleted file mode 100644 index d7772a5..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuth.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -sidebar_label: MCPAuth ---- - -# 類別:MCPAuth - -mcp-auth 函式庫的主要類別。它作為工廠與註冊中心,用於建立受保護資源的驗證 (Authentication) 原則。 - -初始化時需傳入伺服器設定,並提供 `bearerAuth` 方法,用於產生基於權杖的 Express 中介軟體(middleware)。 - -## 範例 {#example} - -### 在 `資源伺服器 (resource server)` 模式下的用法 {#usage-in-resource-server-mode} - -這是新應用程式推薦的方式。 - -#### 選項 1:Discovery 設定(建議用於 edge 執行環境) {#option-1-discovery-config-recommended-for-edge-runtimes} - -當你希望隨需擷取 metadata 時使用。這對於如 Cloudflare Workers 這類不允許頂層 async fetch 的 edge 執行環境特別有用。 - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - // 只需傳入 issuer 與 type,metadata 會在首次請求時自動擷取 - authorizationServers: [{ issuer: 'https://auth.logto.io/oidc', type: 'oidc' }], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### 選項 2:Resolved 設定(預先擷取 metadata) {#option-2-resolved-config-pre-fetched-metadata} - -當你希望在啟動時就擷取並驗證 metadata 時使用。 - -```ts -import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; - -const app = express(); -const resourceIdentifier = 'https://api.example.com/notes'; -const authServerConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); - -const mcpAuth = new MCPAuth({ - protectedResources: [ - { - metadata: { - resource: resourceIdentifier, - authorizationServers: [authServerConfig], - scopesSupported: ['read:notes', 'write:notes'], - }, - }, - ], -}); -``` - -#### 使用中介軟體 {#using-the-middleware} - -```ts -// 掛載路由以處理 Protected Resource Metadata -app.use(mcpAuth.protectedResourceMetadataRouter()); - -// 保護已設定資源的 API 端點 -app.get( - '/notes', - mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // 指定此端點所屬資源 - audience: resourceIdentifier, // 可選,驗證 'aud' 宣告 (claim) - requiredScopes: ['read:notes'], - }), - (req, res) => { - console.log('Auth info:', req.auth); - res.json({ notes: [] }); - }, -); -``` - -### 傳統 `授權伺服器 (authorization server)` 模式用法(已棄用) {#legacy-usage-in-authorization-server-mode-deprecated} - -此方式為相容舊版而保留。 - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth = new MCPAuth({ - // Discovery 設定 - metadata 隨需擷取 - server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, -}); - -// 掛載路由以處理舊版授權伺服器 Metadata -app.use(mcpAuth.delegatedRouter()); - -// 使用預設原則保護端點 -app.get( - '/mcp', - mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), - (req, res) => { - console.log('Auth info:', req.auth); - // 在此處理 MCP 請求 - }, -); -``` - -## 建構子 {#constructors} - -### 建構子 {#constructor} - -```ts -new MCPAuth(config: MCPAuthConfig): MCPAuth; -``` - -建立 MCPAuth 實例。 -會在初始化時即驗證整份設定,錯誤會立即拋出。 - -#### 參數 {#parameters} - -##### config {#config} - -[`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) - -驗證 (Authentication) 設定。 - -#### 回傳 {#returns} - -`MCPAuth` - -## 屬性 {#properties} - -### config {#config} - -```ts -readonly config: MCPAuthConfig; -``` - -驗證 (Authentication) 設定。 - -## 方法 {#methods} - -### bearerAuth() {#bearerauth} - -#### 呼叫簽章 {#call-signature} - -```ts -bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; -``` - -建立一個 Bearer 權杖驗證處理器(Express 中介軟體),用於驗證請求 `Authorization` 標頭中的存取權杖 (Access token)。 - -##### 參數 {#parameters} - -###### verifyAccessToken {#verifyaccesstoken} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -驗證存取權杖 (Access token) 的函式。應接受字串型態的權杖並回傳 promise(或值),解析為驗證結果。 - -**參見** - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以取得 `verifyAccessToken` 函式型別定義。 - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> - -Bearer 權杖驗證處理器的可選設定。 - -**參見** - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以取得可用設定選項(不含 `verifyAccessToken` 與 `issuer`)。 - -##### 回傳 {#returns} - -`RequestHandler` - -一個 Express 中介軟體函式,會驗證存取權杖 (Access token) 並將驗證結果加到請求物件 (`req.auth`) 上。 - -##### 參見 {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以瞭解實作細節與 `req.auth`(`AuthInfo`)物件的擴充型別。 - -#### 呼叫簽章 {#call-signature} - -```ts -bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; -``` - -建立一個 Bearer 權杖驗證處理器(Express 中介軟體),使用預設驗證模式驗證請求 `Authorization` 標頭中的存取權杖 (Access token)。 - -在 `'jwt'` 模式下,處理器會使用授權伺服器的 JWKS URI 建立 JWT 驗證函式。 - -##### 參數 {#parameters} - -###### mode {#mode} - -`"jwt"` - -存取權杖 (Access token) 的驗證模式。目前僅支援 'jwt'。 - -**參見** - -[VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) 以取得可用模式。 - -###### config? {#config} - -`Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` - -Bearer 權杖驗證處理器的可選設定,包含 JWT 驗證選項與遠端 JWK set 選項。 - -**參見** - - - VerifyJwtConfig 以取得 JWT 驗證可用設定選項。 - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以取得可用設定選項(不含 `verifyAccessToken` 與 `issuer`)。 - -##### 回傳 {#returns} - -`RequestHandler` - -一個 Express 中介軟體函式,會驗證存取權杖 (Access token) 並將驗證結果加到請求物件 (`req.auth`) 上。 - -##### 參見 {#see} - -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以瞭解實作細節與 `req.auth`(`AuthInfo`)物件的擴充型別。 - -##### 拋出 {#throws} - -若在 `'jwt'` 模式下伺服器 metadata 未提供 JWKS URI,則會拋出錯誤。 - -*** - -### ~~delegatedRouter()~~ {#delegatedrouter} - -```ts -delegatedRouter(): Router; -``` - -建立一個 delegated router,用於提供舊版 OAuth 2.0 授權伺服器 (Authorization Server) Metadata 端點 -(`/.well-known/oauth-authorization-server`),內容來自實例設定的 metadata。 - -#### 回傳 {#returns} - -`Router` - -一個提供 OAuth 2.0 授權伺服器 Metadata 端點的路由器,內容來自實例設定的 metadata。 - -#### 已棄用 {#deprecated} - -請改用 [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter)。 - -#### 範例 {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -const app = express(); -const mcpAuth: MCPAuth; // 假設已初始化 -app.use(mcpAuth.delegatedRouter()); -``` - -#### 拋出 {#throws} - -若於 `資源伺服器 (resource server)` 模式下呼叫會拋出錯誤。 - -*** - -### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} - -```ts -protectedResourceMetadataRouter(): Router; -``` - -建立一個路由器,為所有已設定資源提供 OAuth 2.0 Protected Resource Metadata 端點。 - -此路由器會根據你設定的資源識別符,自動建立正確的 `.well-known` 端點。 - -#### 回傳 {#returns} - -`Router` - -一個提供 OAuth 2.0 Protected Resource Metadata 端點的路由器。 - -#### 拋出 {#throws} - -若於 `授權伺服器 (authorization server)` 模式下呼叫會拋出錯誤。 - -#### 範例 {#example} - -```ts -import express from 'express'; -import { MCPAuth } from 'mcp-auth'; - -// 假設 mcpAuth 已以一個或多個 `protectedResources` 設定初始化 -const mcpAuth: MCPAuth; -const app = express(); - -// 這會根據你的資源識別符,在 `/.well-known/oauth-protected-resource/...` 提供 metadata -app.use(mcpAuth.protectedResourceMetadataRouter()); -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md deleted file mode 100644 index e7cd90a..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthAuthServerError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthAuthServerError ---- - -# 類別:MCPAuthAuthServerError - -當遠端授權伺服器發生問題時所拋出的錯誤。 - -## 繼承自 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 建構子 {#constructors} - -### 建構子 {#constructor} - -```ts -new MCPAuthAuthServerError(code: AuthServerErrorCode, cause?: unknown): MCPAuthAuthServerError; -``` - -#### 參數 {#parameters} - -##### code {#code} - -[`AuthServerErrorCode`](/references/js/type-aliases/AuthServerErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### 回傳 {#returns} - -`MCPAuthAuthServerError` - -#### 覆寫自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 屬性 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: AuthServerErrorCode; -``` - -錯誤代碼,採用 snake_case 格式。 - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthAuthServerError'; -``` - -#### 覆寫自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可選的堆疊追蹤格式化覆寫方法 - -#### 參數 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 回傳 {#returns} - -`any` - -#### 參考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -將錯誤轉換為適合 HTTP 回應的 JSON 格式。 - -#### 參數 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 回應中包含錯誤原因。 -預設為 `false`。 - -#### 回傳 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目標物件上建立 .stack 屬性 - -#### 參數 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 回傳 {#returns} - -`void` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md deleted file mode 100644 index 1763134..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthBearerAuthError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthError ---- - -# 類別:MCPAuthBearerAuthError - -當使用 Bearer 權杖進行驗證 (Authentication) 時發生問題時所拋出的錯誤。 - -## 繼承自 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 建構子 {#constructors} - -### 建構子 {#constructor} - -```ts -new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; -``` - -#### 參數 {#parameters} - -##### code {#code} - -[`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) - -##### cause? {#cause} - -[`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) - -#### 回傳 {#returns} - -`MCPAuthBearerAuthError` - -#### 覆寫自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 屬性 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: MCPAuthBearerAuthErrorDetails; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: BearerAuthErrorCode; -``` - -錯誤代碼,採用 snake_case 格式。 - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthBearerAuthError'; -``` - -#### 覆寫自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可選的堆疊追蹤格式化覆寫 - -#### 參數 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 回傳 {#returns} - -`any` - -#### 參考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -將錯誤轉換為適合 HTTP 回應的 JSON 格式。 - -#### 參數 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 回應中包含錯誤原因。 -預設為 `false`。 - -#### 回傳 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 覆寫自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目標物件上建立 .stack 屬性 - -#### 參數 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 回傳 {#returns} - -`void` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md deleted file mode 100644 index 755ad5a..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthConfigError.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebar_label: MCPAuthConfigError ---- - -# 類別:MCPAuthConfigError - -當 mcp-auth 配置出現問題時所拋出的錯誤。 - -## 繼承自 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 建構子 {#constructors} - -### 建構子 {#constructor} - -```ts -new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; -``` - -#### 參數 {#parameters} - -##### code {#code} - -`string` - -錯誤代碼,採用 snake_case 格式。 - -##### message {#message} - -`string` - -易於理解的錯誤描述。 - -#### 回傳 {#returns} - -`MCPAuthConfigError` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 屬性 {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -錯誤代碼,採用 snake_case 格式。 - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthConfigError'; -``` - -#### 覆寫自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可選的堆疊追蹤格式化覆寫 - -#### 參數 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 回傳 {#returns} - -`any` - -#### 參見 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -將錯誤轉換為適合 HTTP 回應的 JSON 格式。 - -#### 參數 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 回應中包含錯誤原因。 -預設為 `false`。 - -#### 回傳 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目標物件上建立 .stack 屬性 - -#### 參數 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 回傳 {#returns} - -`void` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md deleted file mode 100644 index 8516f21..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthError.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -sidebar_label: MCPAuthError ---- - -# 類別:MCPAuthError - -所有 mcp-auth 錯誤的基礎類別。 - -它提供一種標準化方式來處理與 MCP 驗證 (Authentication) 和授權 (Authorization) 相關的錯誤。 - -## 繼承自 {#extends} - -- `Error` - -## 被繼承於 {#extended-by} - -- [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) -- [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) -- [`MCPAuthBearerAuthError`](/references/js/classes/MCPAuthBearerAuthError.md) -- [`MCPAuthTokenVerificationError`](/references/js/classes/MCPAuthTokenVerificationError.md) - -## 建構子 {#constructors} - -### 建構子 {#constructor} - -```ts -new MCPAuthError(code: string, message: string): MCPAuthError; -``` - -#### 參數 {#parameters} - -##### code {#code} - -`string` - -錯誤代碼,採用 snake_case 格式。 - -##### message {#message} - -`string` - -易於理解的錯誤描述。 - -#### 回傳 {#returns} - -`MCPAuthError` - -#### 覆寫自 {#overrides} - -```ts -Error.constructor -``` - -## 屬性 {#properties} - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -#### 繼承自 {#inherited-from} - -```ts -Error.cause -``` - -*** - -### code {#code} - -```ts -readonly code: string; -``` - -錯誤代碼,採用 snake_case 格式。 - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 繼承自 {#inherited-from} - -```ts -Error.message -``` - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthError'; -``` - -#### 覆寫自 {#overrides} - -```ts -Error.name -``` - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 繼承自 {#inherited-from} - -```ts -Error.stack -``` - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可選的堆疊追蹤格式化覆寫方法 - -#### 參數 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 回傳 {#returns} - -`any` - -#### 參考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 繼承自 {#inherited-from} - -```ts -Error.prepareStackTrace -``` - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 繼承自 {#inherited-from} - -```ts -Error.stackTraceLimit -``` - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -將錯誤轉換為適合 HTTP 回應的 JSON 格式。 - -#### 參數 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 回應中包含錯誤原因。 -預設為 `false`。 - -#### 回傳 {#returns} - -`Record`\<`string`, `unknown`\> - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目標物件上建立 .stack 屬性 - -#### 參數 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 回傳 {#returns} - -`void` - -#### 繼承自 {#inherited-from} - -```ts -Error.captureStackTrace -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md deleted file mode 100644 index 5592dd9..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/classes/MCPAuthTokenVerificationError.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationError ---- - -# 類別:MCPAuthTokenVerificationError - -當驗證權杖時發生問題時所拋出的錯誤。 - -## 繼承自 {#extends} - -- [`MCPAuthError`](/references/js/classes/MCPAuthError.md) - -## 建構子 {#constructors} - -### 建構子 {#constructor} - -```ts -new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; -``` - -#### 參數 {#parameters} - -##### code {#code} - -[`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) - -##### cause? {#cause} - -`unknown` - -#### 回傳 {#returns} - -`MCPAuthTokenVerificationError` - -#### 覆寫自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) - -## 屬性 {#properties} - -### cause? {#cause} - -```ts -readonly optional cause: unknown; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`cause`](/references/js/classes/MCPAuthError.md#cause) - -*** - -### code {#code} - -```ts -readonly code: MCPAuthTokenVerificationErrorCode; -``` - -錯誤代碼,採用 snake_case 格式。 - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`code`](/references/js/classes/MCPAuthError.md#code) - -*** - -### message {#message} - -```ts -message: string; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`message`](/references/js/classes/MCPAuthError.md#message) - -*** - -### name {#name} - -```ts -name: string = 'MCPAuthTokenVerificationError'; -``` - -#### 覆寫自 {#overrides} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) - -*** - -### stack? {#stack} - -```ts -optional stack: string; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stack`](/references/js/classes/MCPAuthError.md#stack) - -*** - -### prepareStackTrace()? {#preparestacktrace} - -```ts -static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; -``` - -可選的堆疊追蹤格式化覆寫 - -#### 參數 {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### 回傳 {#returns} - -`any` - -#### 參考 {#see} - -https://v8.dev/docs/stack-trace-api#customizing-stack-traces - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) - -*** - -### stackTraceLimit {#stacktracelimit} - -```ts -static stackTraceLimit: number; -``` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`stackTraceLimit`](/references/js/classes/MCPAuthError.md#stacktracelimit) - -## 方法 {#methods} - -### toJson() {#tojson} - -```ts -toJson(showCause: boolean): Record; -``` - -將錯誤轉換為適合 HTTP 回應的 JSON 格式。 - -#### 參數 {#parameters} - -##### showCause {#showcause} - -`boolean` = `false` - -是否在 JSON 回應中包含錯誤原因。 -預設為 `false`。 - -#### 回傳 {#returns} - -`Record`\<`string`, `unknown`\> - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) - -*** - -### captureStackTrace() {#capturestacktrace} - -```ts -static captureStackTrace(targetObject: object, constructorOpt?: Function): void; -``` - -在目標物件上建立 .stack 屬性 - -#### 參數 {#parameters} - -##### targetObject {#targetobject} - -`object` - -##### constructorOpt? {#constructoropt} - -`Function` - -#### 回傳 {#returns} - -`void` - -#### 繼承自 {#inherited-from} - -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md deleted file mode 100644 index 40858f0..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/createVerifyJwt.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -sidebar_label: createVerifyJwt ---- - -# 函式:createVerifyJwt() - -```ts -function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; -``` - -建立一個函式,使用提供的金鑰擷取函式與選項來驗證 JWT 存取權杖 (Access token)。 - -## 參數 {#parameters} - -### getKey {#getkey} - -`JWTVerifyGetKey` - -用於擷取驗證 JWT 所需金鑰的函式。 - -**參見** - -JWTVerifyGetKey 以取得金鑰擷取函式的型別定義。 - -### options? {#options} - -`JWTVerifyOptions` - -可選的 JWT 驗證選項。 - -**參見** - -JWTVerifyOptions 以取得選項的型別定義。 - -## 回傳值 {#returns} - -[`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) - -一個用於驗證 JWT 存取權杖 (Access token) 的函式,若權杖有效則回傳 AuthInfo 物件。此函式要求 JWT 的 payload 中必須包含 `iss`、`client_id` 與 `sub` 欄位,且可選擇性包含 `scope` 或 `scopes` 欄位。該函式底層使用 `jose` 函式庫進行 JWT 驗證。 - -## 參見 {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以取得回傳函式的型別定義。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md deleted file mode 100644 index f9f6800..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -sidebar_label: fetchServerConfig ---- - -# 函式:fetchServerConfig() - -```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; -``` - -根據簽發者(Issuer)與授權伺服器類型,擷取伺服器設定。 - -此函式會根據伺服器類型自動判斷 well-known URL,因為 OAuth 及 OpenID Connect 伺服器的 metadata endpoint 慣例不同。 - -## 參數 {#parameters} - -### issuer {#issuer} - -`string` - -授權伺服器的簽發者(Issuer)URL。 - -### config {#config} - -`ServerMetadataConfig` - -包含伺服器類型與可選轉譯函式的設定物件。 - -## 回傳值 {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -一個 promise,解析後會取得包含 metadata 的靜態伺服器設定。 - -## 參見 {#see} - - - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) 以瞭解底層實作。 - - [https://www.rfc-editor.org/rfc/rfc8414](https://www.rfc-editor.org/rfc/rfc8414) 參考 OAuth 2.0 授權伺服器 metadata 規範。 - - [https://openid.net/specs/openid-connect-discovery-1\_0.html](https://openid.net/specs/openid-connect-discovery-1_0.html) 參考 OpenID Connect Discovery 規範。 - -## 範例 {#example} - -```ts -import { fetchServerConfig } from 'mcp-auth'; -// 取得 OAuth 伺服器設定 -// 這會從 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` 擷取 metadata -const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); - -// 取得 OpenID Connect 伺服器設定 -// 這會從 `https://auth.logto.io/oidc/.well-known/openid-configuration` 擷取 metadata -const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); -``` - -## 例外 {#throws} - -若擷取操作失敗則會拋出例外。 - -## 例外 {#throws} - -若伺服器 metadata 無效或不符合 MCP 規範則會拋出例外。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md deleted file mode 100644 index a9ca8a8..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfigByWellKnownUrl.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -sidebar_label: fetchServerConfigByWellKnownUrl ---- - -# 函式:fetchServerConfigByWellKnownUrl() - -```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; -``` - -從指定的 well-known URL 取得伺服器設定,並根據 MCP 規範進行驗證。 - -如果伺服器中繼資料不符合預期的結構,但你確定其相容,可以定義 `transpileData` 函式,將中繼資料轉換為預期格式。 - -## 參數 {#parameters} - -### wellKnownUrl {#wellknownurl} - -要從中取得伺服器設定的 well-known URL。可以是字串或 URL 物件。 - -`string` | `URL` - -### config {#config} - -`ServerMetadataConfig` - -包含伺服器類型與可選轉換函式的設定物件。 - -## 回傳值 {#returns} - -`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> - -一個 promise,解析後會取得包含中繼資料的靜態伺服器設定。 - -## 例外 {#throws} - -當取得操作失敗時會丟出例外。 - -## 例外 {#throws} - -當伺服器中繼資料無效或不符合 MCP 規範時會丟出例外。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md deleted file mode 100644 index b7a94ed..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -sidebar_label: getIssuer ---- - -# 函式:getIssuer() - -```ts -function getIssuer(config: AuthServerConfig): string; -``` - -從驗證伺服器設定中取得簽發者 (Issuer) URL。 - -- 已解析設定:從 `metadata.issuer` 擷取 -- 探索設定:直接回傳 `issuer` - -## 參數 {#parameters} - -### config {#config} - -[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) - -## 回傳值 {#returns} - -`string` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md deleted file mode 100644 index 707e4cb..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/handleBearerAuth.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: handleBearerAuth ---- - -# 函式:handleBearerAuth() - -```ts -function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; -``` - -建立一個用於在 Express 應用程式中處理 Bearer 驗證 (Authentication) 的中介軟體函式。 - -此中介軟體會從 `Authorization` 標頭中擷取 Bearer 存取權杖 (Access token),使用提供的 `verifyAccessToken` 函式進行驗證,並檢查簽發者 (Issuer)、受眾 (Audience) 以及所需權限範圍 (Scopes)。 - -- 如果權杖有效,會將驗證資訊加入 `request.auth` 屬性; - 若無效,則回應相應的錯誤訊息。 -- 若存取權杖 (Access token) 驗證失敗,會回應 401 未授權 (Unauthorized) 錯誤。 -- 若權杖未包含所需權限範圍 (Scopes),會回應 403 禁止存取 (Forbidden) 錯誤。 -- 若驗證 (Authentication) 流程中發生非預期錯誤,中介軟體會重新拋出錯誤。 - -**注意:** `request.auth` 物件會包含比 `@modelcontextprotocol/sdk` 模組中標準 AuthInfo 介面更多的擴充欄位。詳情請參閱本檔案中的擴充介面。 - -## 參數 {#parameters} - -### param0 {#param0} - -[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) - -Bearer 驗證 (Authentication) 處理器的設定。 - -## 回傳值 {#returns} - -`RequestHandler` - -一個處理 Bearer 驗證 (Authentication) 的 Express 中介軟體函式。 - -## 參見 {#see} - -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以瞭解設定選項。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md deleted file mode 100644 index 64c1e47..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfig.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerConfig ---- - -# 型別別名:AuthServerConfig - -```ts -type AuthServerConfig = - | ResolvedAuthServerConfig - | AuthServerDiscoveryConfig; -``` - -用於與 MCP 伺服器整合的遠端授權伺服器(Authorization server)設定。 - -可以是以下其中之一: -- **已解析(Resolved)**:包含 `metadata`,不需網路請求 -- **探索(Discovery)**:僅包含 `issuer` 和 `type`,metadata 會在需要時透過探索機制取得 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md deleted file mode 100644 index 87d6db5..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigError.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -sidebar_label: AuthServerConfigError ---- - -# 型別別名:AuthServerConfigError (Type Alias: AuthServerConfigError) - -```ts -type AuthServerConfigError = { - cause?: Error; - code: AuthServerConfigErrorCode; - description: string; -}; -``` - -表示在驗證授權伺服器中繼資料時發生的錯誤。 - -## 屬性 {#properties} - -### cause? {#cause} - -```ts -optional cause: Error; -``` - -錯誤的可選原因,通常為 `Error` 實例,用於提供更多背景資訊。 - -*** - -### code {#code} - -```ts -code: AuthServerConfigErrorCode; -``` - -代表特定驗證錯誤的代碼。 - -*** - -### description {#description} - -```ts -description: string; -``` - -錯誤的人類可讀描述。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md deleted file mode 100644 index 74bcbbd..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: AuthServerConfigErrorCode ---- - -# 型別別名:AuthServerConfigErrorCode (Type Alias: AuthServerConfigErrorCode) - -```ts -type AuthServerConfigErrorCode = - | "invalid_server_metadata" - | "code_response_type_not_supported" - | "authorization_code_grant_not_supported" - | "pkce_not_supported" - | "s256_code_challenge_method_not_supported"; -``` - -驗證授權伺服器中繼資料時可能發生的錯誤代碼 (The codes for errors that can occur when validating the authorization server metadata)。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md deleted file mode 100644 index 37c2826..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarning ---- - -# 型別別名:AuthServerConfigWarning (Type Alias: AuthServerConfigWarning) - -```ts -type AuthServerConfigWarning = { - code: AuthServerConfigWarningCode; - description: string; -}; -``` - -表示在驗證授權伺服器中繼資料時發生的警告。 - -## 屬性 (Properties) {#properties} - -### code {#code} - -```ts -code: AuthServerConfigWarningCode; -``` - -代表特定驗證警告的代碼。 - -*** - -### description {#description} - -```ts -description: string; -``` - -對警告的人類可讀描述。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md deleted file mode 100644 index e141dc2..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarningCode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerConfigWarningCode ---- - -# 型別別名:AuthServerConfigWarningCode (Type Alias: AuthServerConfigWarningCode) - -```ts -type AuthServerConfigWarningCode = "dynamic_registration_not_supported"; -``` - -驗證授權伺服器中繼資料時可能出現的警告代碼。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md deleted file mode 100644 index 30a531c..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -sidebar_label: AuthServerDiscoveryConfig ---- - -# 型別別名:AuthServerDiscoveryConfig (Type Alias: AuthServerDiscoveryConfig) - -```ts -type AuthServerDiscoveryConfig = { - issuer: string; - type: AuthServerType; -}; -``` - -遠端授權伺服器的探索(Discovery)設定。 - -當你希望在首次需要時,透過探索機制(discovery)即時取得 metadata 時,請使用此設定。 -這對於像 Cloudflare Workers 這類不允許頂層 async fetch 的 edge 執行環境特別有用。 - -## 範例 (Example) {#example} - -```typescript -const mcpAuth = new MCPAuth({ - protectedResources: { - metadata: { - resource: 'https://api.example.com', - authorizationServers: [ - { issuer: 'https://auth.logto.io/oidc', type: 'oidc' } - ], - scopesSupported: ['read', 'write'], - }, - }, -}); -``` - -## 屬性 (Properties) {#properties} - -### issuer {#issuer} - -```ts -issuer: string; -``` - -授權伺服器(authorization server)的簽發者 (Issuer) URL。metadata 將會從此 issuer 派生的 well-known endpoint 取得。 - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -授權伺服器的型別。 - -#### 參見 (See) {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) 以瞭解所有可能的值。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md deleted file mode 100644 index f90473a..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerErrorCode.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: AuthServerErrorCode ---- - -# 型別別名:AuthServerErrorCode (Type Alias: AuthServerErrorCode) - -```ts -type AuthServerErrorCode = - | "invalid_server_metadata" - | "invalid_server_config" - | "missing_jwks_uri"; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md deleted file mode 100644 index 84ec125..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: AuthServerModeConfig ---- - -# 型別別名:~~AuthServerModeConfig~~ - -```ts -type AuthServerModeConfig = { - server: AuthServerConfig; -}; -``` - -舊版 MCP 伺服器作為授權伺服器模式的設定。 - -## 已淘汰 {#deprecated} - -請改用 `ResourceServerModeConfig` 設定。 - -## 屬性 {#properties} - -### ~~server~~ {#server} - -```ts -server: AuthServerConfig; -``` - -單一授權伺服器設定。 - -#### 已淘汰 {#deprecated} - -請改用 `protectedResources` 設定。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md deleted file mode 100644 index 3c23d46..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerSuccessCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: AuthServerSuccessCode ---- - -# 型別別名:AuthServerSuccessCode - -```ts -type AuthServerSuccessCode = - | "server_metadata_valid" - | "dynamic_registration_supported" - | "pkce_supported" - | "s256_code_challenge_method_supported" - | "authorization_code_grant_supported" - | "code_response_type_supported"; -``` - -授權伺服器中繼資料驗證成功時所使用的代碼 (The codes for successful validation of the authorization server metadata)。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md deleted file mode 100644 index c372f2b..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerType.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: AuthServerType ---- - -# 型別別名:AuthServerType - -```ts -type AuthServerType = "oauth" | "oidc"; -``` - -授權伺服器 (Authorization server) 的型別。此資訊應由伺服器設定提供,用以指示該伺服器是 OAuth 2.0 還是 OpenID Connect (OIDC) 授權伺服器 (Authorization server)。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md deleted file mode 100644 index 5ee40ed..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: 授權伺服器中繼資料 (AuthorizationServerMetadata) ---- - -# 型別別名:授權伺服器中繼資料 (AuthorizationServerMetadata) - -```ts -type AuthorizationServerMetadata = z.infer; -``` - -根據 RFC 8414 所定義的 OAuth 2.0 授權伺服器中繼資料 (Authorization Server Metadata) 架構。 - -## 參考 {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md deleted file mode 100644 index f56862a..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthConfig.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -sidebar_label: BearerAuthConfig ---- - -# 型別別名:BearerAuthConfig - -```ts -type BearerAuthConfig = { - audience?: string; - issuer: | string - | ValidateIssuerFunction; - requiredScopes?: string[]; - resource?: string; - showErrorDetails?: boolean; - verifyAccessToken: VerifyAccessTokenFunction; -}; -``` - -## 屬性說明 {#properties} - -### audience? {#audience} - -```ts -optional audience: string; -``` - -存取權杖 (Access token) 預期的受眾 (Audience)(`aud` 宣告 (claim))。這通常是該權杖預期要存取的資源伺服器(API)。如果未提供,將略過受眾檢查。 - -**注意:** 如果你的授權伺服器 (Authorization server) 不支援資源標示符 (Resource Indicators, RFC 8707),可以省略此欄位,因為受眾可能不適用。 - -#### 參考 {#see} - -https://datatracker.ietf.org/doc/html/rfc8707 - -*** - -### issuer {#issuer} - -```ts -issuer: - | string - | ValidateIssuerFunction; -``` - -代表有效簽發者 (Issuer) 的字串,或用於驗證存取權杖簽發者的函式。 - -如果提供字串,將直接作為預期的簽發者值進行比對。 - -如果提供函式,則應依據 [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 的規則驗證簽發者。 - -#### 參考 {#see} - -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 以取得更多驗證函式細節。 - -*** - -### requiredScopes? {#requiredscopes} - -```ts -optional requiredScopes: string[]; -``` - -存取權杖必須具備的權限範圍 (Scopes) 陣列。如果權杖未包含所有這些權限範圍,將拋出錯誤。 - -**注意:** 處理器會檢查權杖中的 `scope` 宣告 (claim),其值可能是以空格分隔的字串或字串陣列,取決於授權伺服器的實作。如果 `scope` 宣告不存在,則會檢查 `scopes` 宣告(若有)。 - -*** - -### resource? {#resource} - -```ts -optional resource: string; -``` - -受保護資源的識別符。若提供此欄位,處理器將使用為該資源設定的授權伺服器來驗證收到的權杖。當搭配 `protectedResources` 設定使用時,此欄位為必填。 - -*** - -### showErrorDetails? {#showerrordetails} - -```ts -optional showErrorDetails: boolean; -``` - -是否在回應中顯示詳細錯誤資訊。這對於開發期間除錯很有幫助,但在生產環境中應關閉,以避免洩漏敏感資訊。 - -#### 預設值 {#default} - -```ts -false -``` - -*** - -### verifyAccessToken {#verifyaccesstoken} - -```ts -verifyAccessToken: VerifyAccessTokenFunction; -``` - -用於驗證存取權杖的函式型別。 - -此函式若權杖無效應拋出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md),若權杖有效則回傳 AuthInfo 物件。 - -#### 參考 {#see} - -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以取得更多細節。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md deleted file mode 100644 index 2fc8402..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/BearerAuthErrorCode.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_label: BearerAuthErrorCode ---- - -# 型別別名:BearerAuthErrorCode (Type Alias: BearerAuthErrorCode) - -```ts -type BearerAuthErrorCode = - | "missing_auth_header" - | "invalid_auth_header_format" - | "missing_bearer_token" - | "invalid_issuer" - | "invalid_audience" - | "missing_required_scopes" - | "invalid_token"; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md deleted file mode 100644 index 8c48216..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseAuthorizationServerMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseAuthorizationServerMetadata ---- - -# 型別別名:CamelCaseAuthorizationServerMetadata - -```ts -type CamelCaseAuthorizationServerMetadata = z.infer; -``` - -OAuth 2.0 授權伺服器中繼資料 (Authorization Server Metadata) 型別的 camelCase 版本。 - -## 參見 {#see} - -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 以取得原始型別與欄位資訊 (field information)。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md deleted file mode 100644 index d127b63..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/CamelCaseProtectedResourceMetadata.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_label: CamelCaseProtectedResourceMetadata ---- - -# 型別別名:CamelCaseProtectedResourceMetadata - -```ts -type CamelCaseProtectedResourceMetadata = z.infer; -``` - -OAuth 2.0 不透明權杖 (Opaque token) 保護資源中,欄位名稱為 camelCase 版本的型別。 - -## 參見 {#see} - -[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) 以取得原始型別與欄位資訊 (field information)。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md deleted file mode 100644 index 9ac67d2..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_label: MCPAuthBearerAuthErrorDetails ---- - -# 型別別名:MCPAuthBearerAuthErrorDetails (Type Alias: MCPAuthBearerAuthErrorDetails) - -```ts -type MCPAuthBearerAuthErrorDetails = { - actual?: unknown; - cause?: unknown; - expected?: unknown; - missingScopes?: string[]; - uri?: URL; -}; -``` - -## 屬性 (Properties) {#properties} - -### actual? {#actual} - -```ts -optional actual: unknown; -``` - -*** - -### cause? {#cause} - -```ts -optional cause: unknown; -``` - -*** - -### expected? {#expected} - -```ts -optional expected: unknown; -``` - -*** - -### missingScopes? {#missingscopes} - -```ts -optional missingScopes: string[]; -``` - -*** - -### uri? {#uri} - -```ts -optional uri: URL; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md deleted file mode 100644 index 77ab46b..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthConfig.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -sidebar_label: MCPAuthConfig ---- - -# 型別別名:MCPAuthConfig (Type Alias: MCPAuthConfig) - -```ts -type MCPAuthConfig = - | AuthServerModeConfig - | ResourceServerModeConfig; -``` - -[MCPAuth](/references/js/classes/MCPAuth.md) 類別的設定,支援單一舊版 `authorization server` 或 `resource server` 設定。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md deleted file mode 100644 index 6038b98..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: MCPAuthTokenVerificationErrorCode ---- - -# 型別別名:MCPAuthTokenVerificationErrorCode (Type Alias: MCPAuthTokenVerificationErrorCode) - -```ts -type MCPAuthTokenVerificationErrorCode = "invalid_token" | "token_verification_failed"; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md deleted file mode 100644 index a493929..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: ProtectedResourceMetadata ---- - -# 型別別名:ProtectedResourceMetadata - -```ts -type ProtectedResourceMetadata = z.infer; -``` - -OAuth 2.0 受保護資源中繼資料(Protected Resource Metadata)的結構定義。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md deleted file mode 100644 index 2c9b817..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -sidebar_label: ResolvedAuthServerConfig ---- - -# 型別別名:ResolvedAuthServerConfig - -```ts -type ResolvedAuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; -``` - -包含中繼資料的遠端授權伺服器(Authorization Server)已解析設定。 - -當中繼資料已可用(例如硬編碼或事先透過 `fetchServerConfig()` 取得)時,請使用此型別。 - -## 屬性 {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -授權伺服器(Authorization Server)的中繼資料,應符合 MCP 規範(基於 OAuth 2.0 授權伺服器中繼資料)。 - -這些中繼資料通常從伺服器的 well-known endpoint(OAuth 2.0 授權伺服器中繼資料或 OpenID Connect Discovery)取得;若伺服器不支援這類 endpoint,也可直接在設定中提供。 - -**注意:** 中繼資料應採用 camelCase 格式,符合 mcp-auth 函式庫的偏好。 - -#### 參考 {#see} - - - [OAuth 2.0 授權伺服器中繼資料 (OAuth 2.0 Authorization Server Metadata)](https://datatracker.ietf.org/doc/html/rfc8414) - - [OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) - -*** - -### type {#type} - -```ts -type: AuthServerType; -``` - -授權伺服器(Authorization Server)的型別。 - -#### 參考 {#see} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) 以瞭解所有可能值。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md deleted file mode 100644 index 3c4671a..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResourceServerModeConfig.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_label: ResourceServerModeConfig ---- - -# 型別別名:ResourceServerModeConfig - -```ts -type ResourceServerModeConfig = { - protectedResources: ResourceServerConfig | ResourceServerConfig[]; -}; -``` - -MCP 伺服器作為資源伺服器模式的設定。 - -## 屬性 {#properties} - -### protectedResources {#protectedresources} - -```ts -protectedResources: ResourceServerConfig | ResourceServerConfig[]; -``` - -單一資源伺服器設定或其陣列。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md deleted file mode 100644 index d5bb3c0..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -sidebar_label: ValidateIssuerFunction ---- - -# 型別別名:ValidateIssuerFunction() - -```ts -type ValidateIssuerFunction = (tokenIssuer: string) => void; -``` - -用於驗證存取權杖 (Access token) 簽發者 (Issuer) 的函式型別。 - -當簽發者無效時,此函式應拋出帶有 'invalid_issuer' 代碼的 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)。簽發者應根據以下條件進行驗證: - -1. MCP-Auth 的授權伺服器 (Authorization server) 中設定的授權伺服器元資料 -2. 受保護資源 (Protected resource) 元資料中列出的授權伺服器 - -## 參數 {#parameters} - -### tokenIssuer {#tokenissuer} - -`string` - -## 回傳 {#returns} - -`void` - -## 拋出 {#throws} - -當簽發者 (Issuer) 未被識別或無效時。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md deleted file mode 100644 index a314b85..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenFunction ---- - -# 型別別名:VerifyAccessTokenFunction() - -```ts -type VerifyAccessTokenFunction = (token: string) => MaybePromise; -``` - -用於驗證存取權杖 (Access token) 的函式型別。 - -當權杖無效時,此函式應拋出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md); -若權杖有效,則回傳一個 AuthInfo 物件。 - -例如,若你有一個 JWT 驗證函式,至少應檢查權杖的簽章、驗證其過期時間,並擷取必要的宣告 (Claims) 以回傳 `AuthInfo` 物件。 - -**注意:** 權杖中的下列欄位無需自行驗證,因為這些會由處理器自動檢查: - -- `iss`(簽發者 (Issuer)) -- `aud`(受眾 (Audience)) -- `scope`(權限範圍 (Scopes)) - -## 參數 {#parameters} - -### token {#token} - -`string` - -要驗證的存取權杖 (Access token) 字串。 - -## 回傳值 {#returns} - -`MaybePromise`\<`AuthInfo`\> - -一個 Promise,若權杖有效則解析為 AuthInfo 物件,或同步回傳該物件。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md deleted file mode 100644 index bd53bec..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenMode.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_label: VerifyAccessTokenMode ---- - -# 型別別名:VerifyAccessTokenMode - -```ts -type VerifyAccessTokenMode = "jwt"; -``` - -`bearerAuth` 支援的內建驗證模式。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md deleted file mode 100644 index 91f5bfc..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authServerErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: authServerErrorDescription ---- - -# 變數:authServerErrorDescription (authServerErrorDescription) - -```ts -const authServerErrorDescription: Readonly>; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md deleted file mode 100644 index 7bf29d6..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: authorizationServerMetadataSchema ---- - -# 變數:authorizationServerMetadataSchema - -```ts -const authorizationServerMetadataSchema: ZodObject<{ - authorization_endpoint: ZodString; - code_challenge_methods_supported: ZodOptional>; - grant_types_supported: ZodOptional>; - introspection_endpoint: ZodOptional; - introspection_endpoint_auth_methods_supported: ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: ZodOptional>; - issuer: ZodString; - jwks_uri: ZodOptional; - op_policy_uri: ZodOptional; - op_tos_uri: ZodOptional; - registration_endpoint: ZodOptional; - response_modes_supported: ZodOptional>; - response_types_supported: ZodArray; - revocation_endpoint: ZodOptional; - revocation_endpoint_auth_methods_supported: ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: ZodOptional>; - scopes_supported: ZodOptional>; - service_documentation: ZodOptional; - token_endpoint: ZodString; - token_endpoint_auth_methods_supported: ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: ZodOptional>; - ui_locales_supported: ZodOptional>; - userinfo_endpoint: ZodOptional; -}, $strip>; -``` - -用於 OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)的 Zod schema,依據 RFC 8414 定義。 - -## 參考 {#see} - -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md deleted file mode 100644 index ef9c398..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/bearerAuthErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: bearerAuthErrorDescription ---- - -# 變數:bearerAuthErrorDescription (bearerAuthErrorDescription) - -```ts -const bearerAuthErrorDescription: Readonly>; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md deleted file mode 100644 index 9ef2b7c..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_label: camelCaseAuthorizationServerMetadataSchema ---- - -# 變數:camelCaseAuthorizationServerMetadataSchema - -```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ - authorizationEndpoint: ZodString; - codeChallengeMethodsSupported: ZodOptional>; - grantTypesSupported: ZodOptional>; - introspectionEndpoint: ZodOptional; - introspectionEndpointAuthMethodsSupported: ZodOptional>; - introspectionEndpointAuthSigningAlgValuesSupported: ZodOptional>; - issuer: ZodString; - jwksUri: ZodOptional; - opPolicyUri: ZodOptional; - opTosUri: ZodOptional; - registrationEndpoint: ZodOptional; - responseModesSupported: ZodOptional>; - responseTypesSupported: ZodArray; - revocationEndpoint: ZodOptional; - revocationEndpointAuthMethodsSupported: ZodOptional>; - revocationEndpointAuthSigningAlgValuesSupported: ZodOptional>; - scopesSupported: ZodOptional>; - serviceDocumentation: ZodOptional; - tokenEndpoint: ZodString; - tokenEndpointAuthMethodsSupported: ZodOptional>; - tokenEndpointAuthSigningAlgValuesSupported: ZodOptional>; - uiLocalesSupported: ZodOptional>; - userinfoEndpoint: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)Zod schema 的 camelCase 版本。 - -## 參見 {#see} - -[authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) 以取得原始 schema 與欄位資訊。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md deleted file mode 100644 index 929f49d..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -sidebar_label: camelCaseProtectedResourceMetadataSchema ---- - -# 變數:camelCaseProtectedResourceMetadataSchema - -```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject<{ - authorizationDetailsTypesSupported: ZodOptional>; - authorizationServers: ZodOptional>; - bearerMethodsSupported: ZodOptional>; - dpopBoundAccessTokensRequired: ZodOptional; - dpopSigningAlgValuesSupported: ZodOptional>; - jwksUri: ZodOptional; - resource: ZodString; - resourceDocumentation: ZodOptional; - resourceName: ZodOptional; - resourcePolicyUri: ZodOptional; - resourceSigningAlgValuesSupported: ZodOptional>; - resourceTosUri: ZodOptional; - scopesSupported: ZodOptional>; - signedMetadata: ZodOptional; - tlsClientCertificateBoundAccessTokens: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 不透明權杖 (Opaque token) 受保護資源中繼資料 Zod schema 的 camelCase 版本。 - -## 參見 {#see} - -[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 以取得原始 schema 與欄位資訊。 \ No newline at end of file diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md deleted file mode 100644 index 822b791..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/defaultValues.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: defaultValues ---- - -# 變數:defaultValues (defaultValues) - -```ts -const defaultValues: Readonly>; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md deleted file mode 100644 index d5ee951..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -sidebar_label: protectedResourceMetadataSchema ---- - -# 變數:protectedResourceMetadataSchema - -```ts -const protectedResourceMetadataSchema: ZodObject<{ - authorization_details_types_supported: ZodOptional>; - authorization_servers: ZodOptional>; - bearer_methods_supported: ZodOptional>; - dpop_bound_access_tokens_required: ZodOptional; - dpop_signing_alg_values_supported: ZodOptional>; - jwks_uri: ZodOptional; - resource: ZodString; - resource_documentation: ZodOptional; - resource_name: ZodOptional; - resource_policy_uri: ZodOptional; - resource_signing_alg_values_supported: ZodOptional>; - resource_tos_uri: ZodOptional; - scopes_supported: ZodOptional>; - signed_metadata: ZodOptional; - tls_client_certificate_bound_access_tokens: ZodOptional; -}, $strip>; -``` - -OAuth 2.0 受保護資源中繼資料的 Zod schema(Zod schema for OAuth 2.0 Protected Resource Metadata)。 diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md deleted file mode 100644 index ff1fe69..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/serverMetadataPaths.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -sidebar_label: serverMetadataPaths ---- - -# 變數:serverMetadataPaths (serverMetadataPaths) - -```ts -const serverMetadataPaths: Readonly<{ - oauth: "/.well-known/oauth-authorization-server"; - oidc: "/.well-known/openid-configuration"; -}>; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md deleted file mode 100644 index 0c0db40..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/tokenVerificationErrorDescription.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: 權杖驗證錯誤描述 (tokenVerificationErrorDescription) ---- - -# 變數:權杖驗證錯誤描述 (tokenVerificationErrorDescription) - -```ts -const tokenVerificationErrorDescription: Readonly>; -``` diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md deleted file mode 100644 index 5c85420..0000000 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/validateServerConfig.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -sidebar_label: validateServerConfig ---- - -# 變數:validateServerConfig (validateServerConfig) - -```ts -const validateServerConfig: ValidateServerConfig; -``` diff --git a/sidebars.ts b/sidebars.ts index 05f64ca..fe89c22 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -24,7 +24,7 @@ const sidebars: SidebarsConfig = { { type: 'category', label: 'Tutorials', - items: ['tutorials/todo-manager/README', 'tutorials/whoami/README'], + items: ['tutorials/whoami/README', 'tutorials/todo-manager/README'], }, { type: 'category', @@ -36,6 +36,7 @@ const sidebars: SidebarsConfig = { 'provider-guides/generic', ], }, + 'migrate-to-v1', { type: 'category', label: 'References', diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 3618438..754dce4 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -29,8 +29,8 @@ const LandingPage: FC = () => {

- - Python and Node.js SDKs are now available! + + MCP Auth 1.0 for Node.js is here, built for the MCP TypeScript SDK v2!

@@ -90,7 +90,7 @@ const LandingPage: FC = () => { values={{ specLink: ( { How about the MCP SDKs?

- - The official MCP SDKs (Python, Node.js, etc.) are a great starting point. MCP Auth - uses them in all tutorials and it can serve a strong supplement to your existing - setup. + + The official MCP SDKs now ship the HTTP layer of MCP authorization themselves: + bearer auth middleware, metadata endpoints, and framework adapters. What they ask + you to bring is provider integration: a token verifier and your auth metadata.

- - MCP Auth bridges the gap between "it runs" and "it's secure, scalable, and - maintainable" for authentication and authorization. + + MCP Auth gives you both, for any OAuth 2.0 / OpenID Connect provider.

- - It's designed to work alongside the SDKs by offering: + + You could write the verifier yourself; a correct one is about a hundred lines with a + JWT library. These are the parts that tend to go wrong silently:

  • - First-class JWT support + aud }} + > + { + 'Audience binding (RFC 8707): required by the MCP spec, left to the verifier by the SDK. MCP Auth always validates the {aud} claim against your resource identifier, with no opt-out.' + } +
  • - Provider-agnostic tools + exp, expiresAt: expiresAt }} + > + { + 'Expiration mapping: miss the {exp} → {expiresAt} mapping and the SDK rejects every token. MCP Auth maps it automatically.' + } +
  • - - Step-by-step guides for various identity providers + + Error mapping: raw JWT-library errors surface as 500s with no challenge, so + clients never re-authorize. MCP Auth turns verification failures into proper 401 + challenges. + +
  • +
  • + scope, + scopes: scopes, + clientId: client_id, + azp: azp, + }} + > + { + 'Claim quirks across providers: {scope} strings vs. {scopes} arrays, {clientId} vs. {azp}: all handled.' + } + +
  • +
  • + + Discovery hygiene: issuer validation, cached metadata and JWKS fetches, and cache + reset on transient failures, all built in.

- - Plus, we keep up with changes to the MCP spec and SDKs, so you don't have to. + MCPAuth }} + > + { + 'Or: all of the above is one {mcpAuth} instance, tested and kept up to date as the MCP spec and SDKs evolve.' + } + +

+

+ + What stays in your hands: provider-side configuration (audience, scopes, client + registration), permission design, and your app-level authorization. That is exactly + what the tutorials and provider guides walk you through.

diff --git a/src/pages/provider-list.mdx b/src/pages/provider-list.mdx index 248e1a0..b012dd3 100644 --- a/src/pages/provider-list.mdx +++ b/src/pages/provider-list.mdx @@ -10,7 +10,7 @@ This list contains providers that have been tested with MCP Auth. | Provider | Type | OAuth 2.1 | Metadata URL | Dynamic Client Registration | Resource Indicator[^1] | | --------------------------------------------------------- | -------------- | --------- | ------------ | --------------------------- | ---------------------- | -| [Logto](https://logto.io) | OpenID Connect | ✅ | ✅ | ❌[^2] | ✅ | +| [Logto](https://logto.io) | OpenID Connect | ✅ | ✅ | ⚠️[^2] | ✅ | | [Keycloak](https://www.keycloak.org) | OpenID Connect | ✅ | ✅ | ⚠️[^3] | ❌ | | [Asgardeo](https://wso2.com/asgardeo) | OpenID Connect | ✅ | ✅ | ✅ | ❌ | | [WSO2 Identity Server](https://wso2.com/identity-server/) | OpenID Connect | ✅ | ✅ | ✅ | ❌ | @@ -21,7 +21,7 @@ If you have tested MCP Auth with another provider, please feel free to submit a [^1]: Resource Indicator stands for [RFC 8707: Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707), which is a standard for indicating the resource a client wants to access. -[^2]: Logto is working on adding support for dynamic client registration. +[^2]: Logto does not implement RFC 7591, but supports onboarding MCP clients without pre-registration through [dynamic apps](https://docs.logto.io/integrate-logto/third-party-applications/dynamic-apps), which implement the [OAuth Client ID Metadata Document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/) draft adopted by the latest MCP specification. [^3]: While Keycloak supports dynamic client registration, its client registration endpoint does not support CORS, preventing most MCP clients from registering directly. @@ -34,7 +34,8 @@ If you have tested MCP Auth with another provider, please feel free to submit a 1. **If you are developing an MCP server for internal use or a specific application you control**: it's fine to manually register your MCP client with the provider and configure the client ID (and optionally, the client secret) in your MCP client. 2. **If you are developing an MCP server that will be used by public applications (MCP clients)**: 1. You can leverage Dynamic Client Registration to allow your MCP clients to register themselves with the provider dynamically. Make sure to implement proper security measures to prevent unauthorized or malicious registrations. - 2. Alternatively, you can develop a custom registration flow that allows your MCP clients to register with the provider using a secure and controlled process, such as a web interface or an API endpoint that you control, without relying on Dynamic Client Registration. + 2. The [latest MCP specification](https://modelcontextprotocol.io/specification/latest/basic/authorization) also embraces [Client ID Metadata Documents](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/) (CIMD), where the client identifies itself with an HTTPS URL that serves its own metadata, so no registration step is needed at all. Some providers offer this instead of RFC 7591 (for example, Logto's [dynamic apps](https://docs.logto.io/integrate-logto/third-party-applications/dynamic-apps)). + 3. Alternatively, you can develop a custom registration flow that allows your MCP clients to register with the provider using a secure and controlled process, such as a web interface or an API endpoint that you control, without relying on Dynamic Client Registration. As long as your provider supports Management API or similar functionality, you can use it in your custom endpoints to register the MCP clients. ## Test your provider {#test-your-provider}